<template>
  <div class="l1-data-container">
    <div class="page-header">
      <h1 class="page-title">L1数据列表</h1>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <a-form layout="inline" :model="formData">
        <a-form-item label="日期范围">
          <a-range-picker v-model:value="formData.dateRange" :placeholder="['开始日期', '结束日期']"
            format="YYYY-MM-DD HH:mm:ss" show-time />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch" :loading="loading">
              <template #icon>
                <i-lucide-search />
              </template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon>
                <i-lucide-refresh-cw />
              </template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <a-table :columns="columns" :data-source="tableData" :loading="loading" :pagination="pagination"
        @change="handleTableChange" row-key="id" size="middle" :scroll="{ x: 1200 }">
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'index'">{{ index + 1 }}</template>
          <template v-else-if="column.key === 'createTime'">
            <span>{{ formatDateTime(record.createTime) }}</span>
          </template>
          <!-- <template v-else-if="column.key === 'productStatus'">
            <a-tag :color="record.productStatus === 1 ? 'success' : 'default'">
              {{ record.productStatus === 1 ? '有' : '无' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'goodFlag'">
            <a-tag :color="record.goodFlag === 1 ? 'success' : 'error'">
              {{ record.goodFlag === 1 ? '良品' : '不良品' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'processMemory'">
            <a-tag :color="record.processMemory === 1 ? 'success' : 'default'">
              {{ record.processMemory === 1 ? '已加工' : '未开工' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'functionSw'">
            <a-tag :color="record.functionSw === 1 ? 'success' : 'default'">
              {{ record.functionSw === 1 ? '有效' : '无效' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'visualResult'">
            <a-tag :color="record.visualResult === 1 ? 'success' : 'error'">
              {{ record.visualResult === 1 ? 'OK' : 'NG' }}
            </a-tag>
          </template> -->
          <template v-else-if="column.key === 'action'">
            <a-button type="link" size="small" @click="handleView(record as L1Data)">
              查看详情
            </a-button>
          </template>
          <template v-else>
            {{ record[column.key as string] }}
          </template>
        </template>
      </a-table>
    </div>

    <!-- 详情弹窗 -->
    <a-modal v-model:open="detailVisible" title="详情信息" :footer="null" width="800px">
      <div v-if="selectedRecord" class="detail-content">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item
            v-for="(value, key) in selectedRecord"
            :key="key"
            :label="columns.find((col) => col.key === key)?.title || key"
          >
            <template v-if="key === 'createTime'">
              {{ formatDateTime(value) }}
            </template>
            <!-- <template v-else-if="key === 'productStatus'">
                <a-tag :color="selectedRecord.productStatus === 1 ? 'success' : 'default'">
                  {{ selectedRecord.productStatus === 1 ? '有' : '无' }}
                </a-tag>
            </template>
            <template v-else-if="key === 'goodFlag'">
              <a-tag :color="selectedRecord.goodFlag === 1 ? 'success' : 'error'">
                {{ selectedRecord.goodFlag === 1 ? '良品' : '不良品' }}
              </a-tag>
            </template>
            <template v-else-if="key === 'processMemory'">
              <a-tag :color="selectedRecord.processMemory === 1 ? 'success' : 'default'">
                {{ selectedRecord.processMemory === 1 ? '已加工' : '未开工' }}
              </a-tag>
            </template>
            <template v-else-if="key === 'functionSw'">
              <a-tag :color="selectedRecord.functionSw === 1 ? 'success' : 'default'">
                {{ selectedRecord.functionSw === 1 ? '有效' : '无效' }}
              </a-tag>
            </template>
            <template v-else-if="key === 'visualResult'">
              <a-tag :color="selectedRecord.visualResult === 1 ? 'success' : 'error'">
                {{ selectedRecord.visualResult === 1 ? 'OK' : 'NG' }}
              </a-tag>
            </template> -->
            <template v-else>
              {{ value }}
            </template>
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { message } from "ant-design-vue";
import { getL1Data } from "@/api/line2/data";
import type { QueryParams } from "@/api/line2/data/model";
import type { L1Data } from "./types";
import type { Dayjs } from "dayjs";
import { columns } from "./data";

type DateRangeType = [Dayjs, Dayjs] | undefined;

// 响应式数据
const loading = ref(false);
const tableData = ref<L1Data[]>([]);
const formData = reactive<{ dateRange: DateRangeType }>({
  dateRange: undefined,
});
const detailVisible = ref(false);
const selectedRecord = ref<L1Data | null>(null);

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  pageSizeOptions: ["10", "20", "50", "100"],
});

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const params: QueryParams = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };

    // 添加日期范围筛选
    if (formData.dateRange && formData.dateRange.length === 2) {
      params.createTimeBegin = formData.dateRange[0].format("YYYY-MM-DD HH:mm:ss");
      params.createTimeEnd = formData.dateRange[1].format("YYYY-MM-DD HH:mm:ss");
    }

    const res = await getL1Data(params);

    if (res.code === 200) {
      tableData.value = res.rows || [];
      pagination.total = res.total || 0;
    } else {
      message.error(res.msg || "获取数据失败");
    }
  } catch (error) {
    console.error("获取L1数据失败:", error);
    message.error("获取数据失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  pagination.current = 1;
  fetchData();
};

// 重置处理
const handleReset = () => {
  formData.dateRange = undefined;
  pagination.current = 1;
  fetchData();
};

// 表格变化处理（分页、排序等）
const handleTableChange = (pag: any, filters: any, sorter: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;

  // 处理排序
  if (sorter.field) {
    // 这里可以根据需要添加排序逻辑
  }

  fetchData();
};

// 查看详情
const handleView = (record: L1Data) => {
  selectedRecord.value = record;
  detailVisible.value = true;
};

// 格式化日期时间
const formatDateTime = (dateTime: string | number) => {
  if (!dateTime) return null;
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
};

// 组件挂载时获取数据
onMounted(() => {
  fetchData();
});
</script>

<style scoped lang="scss">
.l1-data-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #1f2937;
    margin: 0;
  }
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.table-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.detail-content {
  max-height: 500px;
  overflow-y: auto;
}

:deep(.ant-table-thead > tr > th) {
  background: #f8fafc;
  font-weight: 600;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #f0f9ff;
}

:deep(.ant-descriptions-item-label) {
  font-weight: 600;
  background: #f8fafc;
}
</style>
