<template>
  <div class="l4-data-container">
    <div class="page-header">
      <h1 class="page-title">L4数据列表</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-if="column.key === 'createTime'">
            {{ formatDateTime(record.createTime) }}
          </template>
          <!-- <template v-else-if="column.key === 'processF1'">
            <a-tag :color="record.processF1 === 1 ? 'green' : 'red'">
              {{ record.processF1 === 1 ? '已加工' : '未加工' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'processF2'">
            <a-tag :color="record.processF2 === 1 ? 'green' : 'red'">
              {{ record.processF2 === 1 ? '已加工' : '未加工' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'goodProductF1'">
            <a-tag :color="record.goodProductF1 === 1 ? 'green' : 'red'">
              {{ record.goodProductF1 === 1 ? '良品' : '不良品' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'goodProductF2'">
            <a-tag :color="record.goodProductF2 === 1 ? 'green' : 'red'">
              {{ record.goodProductF2 === 1 ? '良品' : '不良品' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'electricalResult'">
            <a-tag :color="getElectricalResultColor(record.electricalResult)">
              {{ getElectricalResultText(record.electricalResult) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'engraveResult'">
            <a-tag :color="record.engraveResult === 0 ? 'green' : 'red'">
              {{ record.engraveResult === 0 ? '良品' : '不良品' }}
            </a-tag>
          </template> -->
          <template v-else-if="column.key === 'action'">
            <a-button type="link" size="small" @click="handleView(record as L4Data)">
              查看详情
            </a-button>
          </template>
          <template v-else>
            {{ record[column.key as string] }}
          </template>
        </template>
      </a-table>
    </div>

    <!-- 详情弹窗 -->
    <a-modal v-model:open="detailModalVisible" title="L4数据详情" width="800px" :footer="null">
      <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 === 'processF1'">
              <a-tag :color="value === 1 ? 'green' : 'red'">
                {{ value === 1 ? '已加工' : '未加工' }}
              </a-tag>
            </template>
            <template v-else-if="key === 'processF2'">
              <a-tag :color="value === 1 ? 'green' : 'red'">
                {{ value === 1 ? '已加工' : '未加工' }}
              </a-tag>
            </template>
            <template v-else-if="key === 'goodProductF1'">
              <a-tag :color="value === 1 ? 'green' : 'red'">
                {{ value === 1 ? '良品' : '不良品' }}
              </a-tag>
            </template>
            <template v-else-if="key === 'goodProductF2'">
              <a-tag :color="value === 1 ? 'green' : 'red'">
                {{ value === 1 ? '良品' : '不良品' }}
              </a-tag>
            </template>
            <template v-else-if="key === 'electricalResult'">
              <a-tag :color="getElectricalResultColor(value)">
                {{ getElectricalResultText(value) }}
              </a-tag>
            </template>
            <template v-else-if="key === 'engraveResult'">
              <a-tag :color="value === 0 ? 'green' : 'red'">
                {{ value === 0 ? '良品' : '不良品' }}
              </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 { getL4Data } from '@/api/data';
import { columns } from './data';
import type { QueryParams } from '@/api/data/model';
import type { L4Data } from './types';
import type { Dayjs } from 'dayjs';
import { idText } from 'typescript';

type DateRangeType = [Dayjs, Dayjs] | undefined;

// 响应式数据
const loading = ref(false);
const tableData = ref<L4Data[]>([]);
const detailModalVisible = ref(false);
const selectedRecord = ref<L4Data | null>(null);

// 筛选参数
const formData = reactive<{ dateRange: DateRangeType }>({
  dateRange: undefined,
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `共 ${total} 条记录，当前显示第 ${range[0]}-${range[1]} 条`,
});

// 电气检测结果颜色
const getElectricalResultColor = (result: number) => {
  switch (result) {
    case 7: return 'green';
    case 0: return 'red';
    case 1: return 'orange';
    case 3: return 'purple';
    default: return 'default';
  }
};

// 电气检测结果文本
const getElectricalResultText = (result: number) => {
  switch (result) {
    case 0: return 'DCR不良';
    case 1: return 'LCR不良';
    case 3: return 'IR不良';
    case 7: return '良品';
    default: return '未知';
  }
};

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

    // 添加日期范围筛选
    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 response = await getL4Data(params);

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

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

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

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

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

// 日期时间格式化
const formatDateTime = (dateTime: string | number) => {
  if (!dateTime) return '-';
  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">
.l4-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>