<template>
  <div class="query-container">
    <!-- 查询条件折叠面板 -->
    <el-collapse v-model="activeCollapse" class="collapse-panel">
      <el-collapse-item title="指定参数" name="queryConditions">
        <div class="condition-section">
          <el-form :model="queryForm" class="condition-form" size="small">
            <div class="condition-row">
              <!-- 机型下拉框  -->
              <el-form-item label="机型" class="condition-item">
                <el-select v-model="queryForm.model"
                           placeholder="选择机型"
                           style="width:180px;"
                           clearable
                           filterable
                           @change="handleModelChange">
                  <el-option v-for="item in machineModels"
                             :key="item.ID"
                             :label="item.ProjectName"
                             :value="item.ID" />
                </el-select>
              </el-form-item>

              <!-- 站位下拉框  -->
              <el-form-item label="站位" class="condition-item">
                <el-select v-model="queryForm.station"
                           placeholder="选择站位"
                           style="width:180px;"
                           :disabled="!queryForm.model"
                           filterable
                           clearable
                           remote
                           :remote-method="filterStations"
                           :loading="stationLoading">
                  <el-option v-for="item in filteredStationsList"
                             :key="item.ID"
                             :label="item.StationName"
                             :value="item.ID" />
                </el-select>
              </el-form-item>

              <!-- 设备下拉框  -->
              <el-form-item label="设备" class="condition-item">
                <el-select v-model="queryForm.equipment"
                           placeholder="全部设备"
                           style="width: 180px;"
                           :disabled="!queryForm.model || !queryForm.station"
                           clearable
                           filterable
                           remote
                           :remote-method="filterEquipments"
                           :loading="equipmentLoading">
                  <el-option v-for="item in filteredEquipmentsList"
                             :key="item.ID"
                             :label="`${item.ID} - ${item.TerminalName}`"
                             :value="item.ID" />
                </el-select>
              </el-form-item>

              <!-- 结果下拉框 -->
              <el-form-item label="结果" class="condition-item">
                <el-select v-model="queryForm.result"
                           placeholder="全部结果"
                           :disabled="!queryForm.model"
                           style="width:180px;"
                           clearable>
                  <el-option label="ALL" value="" @click="queryForm.result = ''" />
                  <el-option label="PASS" value="1" />
                  <el-option label="FAIL" value="0" />
                </el-select>
              </el-form-item>

              <!-- 步骤下拉框  -->
              <el-form-item label="步骤" class="condition-item">
                <el-select v-model="queryForm.failSteps"
                           placeholder="全部步骤"
                           style="width:180px;"
                           :disabled="!queryForm.model || !queryForm.station"
                           clearable
                           filterable
                           remote
                           multiple
                           collapse-tags
                           :remote-method="filterFailSteps"
                           :loading="failStepsLoading">
                  <template #header>
                    <el-checkbox v-model="checkAllFailSteps"
                                 @change="selectAllFailSteps">
                      全选
                    </el-checkbox>
                  </template>
                  <el-option v-for="item in filteredFailStepsList"
                             :key="item.FailSteps"
                             :label="item.FailSteps"
                             :value="item.FailSteps" />
                </el-select>
              </el-form-item>

              <!-- 去重方式单选组 -->
              <el-form-item label="去重方式" class="condition-item" style="width:266px">
                <el-radio-group v-model="queryForm.distinct" size="small">
                  <el-tooltip content="全部测试记录" placement="bottom" show-after="233">
                    <el-radio-button label="None">全部</el-radio-button>
                  </el-tooltip>
                  <el-tooltip content="如有多次测试，只取最后一次结果" placement="bottom" show-after="233">
                    <el-radio-button label="Latest">去除重复</el-radio-button>
                  </el-tooltip>
                  <el-tooltip content="如有多次测试，只取第一次结果" placement="bottom" show-after="233">
                    <el-radio-button label="Earliest">一次直通</el-radio-button>
                  </el-tooltip>
                </el-radio-group>
              </el-form-item>

              <!-- 日期范围选择 -->
              <el-form-item label="日期" class="condition-item" v-show="timeShow">
                <div class="date-range">
                  <el-date-picker v-model="queryForm.startDate"
                                  type="date"
                                  style="width:115px;"
                                  placeholder="开始日期"
                                  value-format="YYYY-MM-DD" />
                  <span>&nbsp;-&nbsp;</span>
                  <el-date-picker v-model="queryForm.endDate"
                                  type="date"
                                  style="width:115px;"
                                  placeholder="结束日期"
                                  value-format="YYYY-MM-DD" />
                </div>
              </el-form-item>
            </div>
          </el-form>

          <div style="text-align:right">
            <el-button type="text" v-on:click="dateMobile(1)">1天内</el-button>
            <el-button type="text" v-on:click="dateMobile(3)">3天内</el-button>
            <el-button type="text" v-on:click="dateMobile(7)">7天内</el-button>
            <el-button type="text" v-on:click="dateMobile(30)">30天内</el-button>
            <el-button type="text" v-on:click="moreDate">更多</el-button>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>

    <!-- 勾选参数折叠面板 -->
    <el-collapse v-model="activeCollapse" class="collapse-panel">
      <el-collapse-item title="选择字段" name="selectParams">
        <div class="param-section">
          <div class="param-header">
            <el-checkbox v-model="allParamsSelected" size="small">
              全选
            </el-checkbox>
          </div>

          <div class="param-list">
            <el-checkbox-group v-model="selectedParams" size="small">
              <div class="param-grid">
                <el-checkbox v-for="param in availableParams"
                             :key="param.Field"
                             :label="param.Field"
                             class="param-item">
                  {{ param.Field }}
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>
    <!-- 操作按钮、统计信息和分页器区域 -->
    <div class="controls-container">
      <!-- 统计信息 -->
      <div class="stats-info" v-if="tableData.length > 0">
        <span>PASS: {{ firstPassCount }} / </span>
        <span>ALL: {{ total }} / </span>
        <span>{{ passRate }}%</span>
      </div>

      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination v-model:current-page="currentPage"
                       v-model:page-size="pageSize"
                       size="small"
                       pager-count="3"
                       :page-sizes="[50, 100, 200, 300]"
                       layout="sizes, prev, pager, next"
                       :total="total"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange" />
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-buttons">
        <el-input v-model="queryForm.dutSnLike"
                  size="small"
                  clearable
                  placeholder="筛选DUT_SN"
                  class="action-input" />
        <el-input v-model="queryForm.failstepsLike"
                  size="small"
                  clearable
                  placeholder="筛选Failsteps"
                  class="action-input" />
        <el-button icon="Download"
                   size="small"
                   :disabled="!tableData.length > 0"
                   @click="handleExportExcel"
                   class="action-btn">
          导出Excel
        </el-button>
        <el-button icon="Refresh"
                   size="small"
                   @click="handleReset"
                   type="info"
                   class="action-btn">
          重置
        </el-button>
        <el-button type="primary"
                   icon="Search"
                   size="small"
                   :disabled="!queryForm.model || !queryForm.station"
                   @click="handleSearch"
                   class="action-btn">
          查询
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="data-section">
      <el-table :data="tableData"
                stripe
                size="small"
                border
                :max-height="'calc(100vh - 198px)'"
                style="width: 100%"
                :row-style="{ height: '30px' }">
        <el-table-column v-for="col in tableColumns"
                         :key="col.prop"
                         :prop="col.prop"
                         :label="col.label"
                         :min-width="getMinWidth(col.prop)">
          <template v-if="col.prop === 'DUT_SN'" #default="scope">
            <!-- SN号查整个生命周期 -->
            <el-button @click="snGetLog(scope.row)"
                       :style="scope.row.TestResult === 'True' ? 'color: #336600' : 'color: #990000'" size="small" text>
              {{ scope.row.DUT_SN }}
            </el-button>
          </template>
          <template v-else-if="col.prop === 'TestResult'" #default="scope">
            <el-tag v-if="scope.row.TestResult === 'True'"
                    type="success" size="small" effect="light">
              PASS
            </el-tag>
            <el-tag v-else type="danger" size="small" effect="dark">
              FAIL
            </el-tag>
          </template>
          <template v-else #default="scope">
            <el-text v-if="scope.row.TestResult === 'True'"
                     style="color: #336600" size="small">
              {{ scope.row[col.prop] }}
            </el-text>
            <el-text v-else style="color: #990000" size="small">
              {{ scope.row[col.prop] }}
            </el-text>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <!-- 外层弹窗：SN生命周期记录 -->
  <el-dialog v-model="snDialogVisible"
             :title="`${modelName}-SN: ${selectedSn}`"
             width="666"
             :fullscreen="isMobile">

    <div class="stats-container">
      <el-tag type="success">PASS: {{ passCount }}</el-tag>
      <el-tag type="danger">FAIL: {{ failCount }}</el-tag>
    </div>

    <el-table :data="snLogs"
              size="small"
              border
              @row-click="showDetailDialog">
      <el-table-column prop="step" label="站" width="50">
        <template #default="scope">
          <el-text :style="scope.row.testResult === 'True' ? 'color: #336600' : 'color: #990000'" size="small">
            {{ getStationName(scope.row.step) }}
          </el-text>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="ID" width="60">
        <template #default="scope">
          <el-text :style="scope.row.testResult === 'True' ? 'color: #336600' : 'color: #990000'" size="small">
            {{ scope.row.id }}
          </el-text>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="开始时间" width="80">
        <template #default="scope">
          <el-text :style="scope.row.testResult === 'True' ? 'color: #336600' : 'color: #990000'" size="small">
            {{ scope.row.startTime }}
          </el-text>
        </template>
      </el-table-column>
      <el-table-column prop="usedTime" label="用时(秒)" width="70">
        <template #default="scope">
          <el-text :style="scope.row.testResult === 'True' ? 'color: #336600' : 'color: #990000'" size="small">
            {{ scope.row.usedTime }}
          </el-text>
        </template>
      </el-table-column>
      <el-table-column prop="failSteps" label="失败步骤" width="75">
        <template #default="scope">
          <el-text :style="scope.row.testResult === 'True' ? 'color: #336600' : 'color: #990000'" size="small">
            {{ scope.row.failSteps }}
          </el-text>
        </template>
      </el-table-column>
      <el-table-column prop="failMsg" label="失败信息" min-width="80">
        <template #default="scope">
          <el-text :style="scope.row.testResult === 'True' ? 'color: #336600' : 'color: #990000'" size="small">
            {{ scope.row.failMsg }}
          </el-text>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>

  <!-- 内层弹窗：详细测试数据 -->
  <el-dialog v-model="detailDialogVisible"
             :title="`测试详情 - ${modelName} - ${currentStationName}`"
             :width="isMobile ? '100%' : '500px'"
             :fullscreen="isMobile">

    <div class="detail-container">
      <el-descriptions :column="1" border size="small">
        <el-descriptions-item v-for="(value, key) in currentDetail.rObj[0]"
                              :key="key"
                              :label="key">
          <el-text :style="currentDetail.testResult === 'True'  ? 'color: #336600' : 'color: #990000'">{{ value }}</el-text>
        </el-descriptions-item>
      </el-descriptions>
    </div>
  </el-dialog>
</template>

<script setup>
  import { ref, reactive, onMounted, watch, inject, computed, onBeforeUnmount, nextTick } from 'vue';
  import { Toast } from 'tdesign-mobile-vue';
  import { ElCollapse, ElCollapseItem, ElLoading } from 'element-plus'
  import dayjs from 'dayjs'
  import * as XLSX from 'xlsx';

  const $http = inject('$http')
  const isMobile = ref(window.innerWidth < 768)
  window.addEventListener('resize', () => {
    isMobile.value = window.innerWidth < 768
  })
  // 全局加载遮罩实例
  let loadingInstance = null;

  // ---------- 遮罩方法 ----------
  const showLoading = (text = '加载中...') => {
    // 如果已有加载实例，先关闭
    if (loadingInstance) {
      loadingInstance.close();
    }
    // 创建新的全局加载遮罩
    loadingInstance = ElLoading.service({
      lock: true,
      text: text,
      background: 'rgba(0, 0, 0, 0.7)',
      fullscreen: true
    });
  };

  const hideLoading = () => {
    if (loadingInstance) {
      loadingInstance.close();
      loadingInstance = null;
    }
  };

  // ---------- 数据定义 ----------
  const queryForm = reactive({
    model: null,         // 机型
    station: null,       // 站位
    equipment: null,     // 设备
    result: '',        // 结果
    failSteps: [],     // 失败步骤
    dutSnLike: '',      // DUT_SN模糊筛选（支持逗号分隔）
    failstepsLike: '',  // Failsteps模糊筛选（支持逗号分隔）
    distinct: 'None',     // 去重方式，默认None（全部）
    startDate: dayjs().format('YYYY-MM-DD'), // 开始日期
    endDate: dayjs().format('YYYY-MM-DD')    // 结束日期
  });
  const timeShow = ref(true); // 时间选择器是否显示
  // 状态保存恢复标志
  const isRestoring = ref(false);
  const autoRefreshTimer = ref(null);
  // 选项列表
  const machineModels = ref([]);       // 机型列表
  const stationsList = ref([]);        // 站位列表
  const equipmentsList = ref([]);      // 设备列表
  const failStepsList = ref([]);       // 失败步骤列表

  // 可用参数列表
  const availableParams = ref([]);

  // 选中的参数
  const selectedParams = ref([]);

  // 折叠面板状态
  const activeCollapse = ref(['queryConditions', 'selectParams']); // 默认展开

  // 表格数据
  const tableData = ref([]);
  const tableColumns = ref([
    { prop: 'ID', label: 'ID' },
    { prop: 'SID', label: 'SID' },
    { prop: 'StartTime', label: 'StartTime' },
    { prop: 'DUT_SN', label: 'DUT_SN' },
    { prop: 'TestResult', label: 'TestResult' },
    { prop: 'Failsteps', label: 'Failsteps' },
  ]);

  // 新增状态变量
  const selectedSn = ref('')
  const snDialogVisible = ref(false)
  const detailDialogVisible = ref(false)
  const snLogs = ref([])
  const currentDetail = ref({})
  const passCount = computed(() => snLogs.value.filter(log => log.testResult === 'True').length)
  const failCount = computed(() => snLogs.value.filter(log => log.testResult === 'False').length)
  // 定义默认字段（始终显示）
  const defaultColumns = [
    'ID',
    'SID',
    'StartTime',
    'DUT_SN',
    'TestResult',
    'Failsteps'
  ];

  // 分页数据
  const currentPage = ref(1);
  const pageSize = ref(50);
  const total = ref(0);
  const firstPassCount = ref(0);
  const passRate = ref(0);

  // 状态变量
  const stationLoading = ref(false);
  const equipmentLoading = ref(false);
  const failStepsLoading = ref(false);

  // 筛选列表
  const filteredStationsList = ref([]);
  const filteredEquipmentsList = ref([]);
  const filteredFailStepsList = ref([]);
  const indeterminate = ref(false)
  const checkAllFailSteps = ref(false)

  // ---------- 计算属性 ----------
  const getMinWidth = (prop) => {
    if (prop === 'DUT_SN') return 130;
    if (prop === 'TestPlan') return 150;
    if (prop === 'FailMsg') return 160;
    if (prop === 'AppName') return 80;
    if (prop === 'StartTime') return 75;
    if (prop === 'RCU_FW_Ver') return 100;
    if (prop === 'Launcher_Ver') return 100;
    if (prop === 'ModelNo') return 100;
    return 62;
  };
  // 全选参数控制
  const allParamsSelected = computed({
    get: () => availableParams.value.length > 0 &&
      selectedParams.value.length === availableParams.value.length,
    set: (value) => {
      // 修正字段映射：使用Field而不是value
      selectedParams.value = value
        ? availableParams.value.map(p => p.Field)  // 关键修改这里
        : [];
    }
  });

  const TBLName = computed(() => {
    if (queryForm.model && queryForm.station) {
      return 'tbl_' + queryForm.model + '_' + queryForm.station + '_testlog'
    } else {
      return ""
    }
  });
  const modelName = computed(() => {
    if (queryForm.model) {
      const model = machineModels.value.find(item => item.ID === queryForm.model)
      return model ? model.ProjectName : ''
    }
    return ''
  })


  // ---------- 生命周期 ----------
  onMounted(async () => {
    //await fetchMachineModels();
    // 设置默认日期范围
    queryForm.startDate = dayjs().format('YYYY-MM-DD');
    queryForm.endDate = dayjs().format('YYYY-MM-DD');

    await fetchMachineModels();
    await restoreQuerySettings();
  });
  onBeforeUnmount(() => {
    clearInterval(autoRefreshTimer.value);
    autoRefreshTimer.value = null;
  });
  // ---------- 方法定义 ----------
  // 获取机型列表
  const fetchMachineModels = async () => {
    try {
      showLoading('加载机型列表中...');

      const rqs = {
        key: "getModelList",
        CmdType: "sys",
        DBQueryData: [{
          key: "@dbName",
          value: localStorage.getItem('selectdb'),
          valueType: "string",
        }]
      }

      const rs = await $http.post('DataHandle/R_InfoCommon', rqs);
      console.log(rs);

      if (rs.data.isok) {
        machineModels.value = rs.data.response;
      } else {
        Toast(rs.data.message);
      }
    } catch (error) {
      console.error('获取机型失败:', error);
      Toast.error('获取机型失败');
    } finally {
      hideLoading();
    }
  };

  // 修改后的handleModelChange
  const handleModelChange = async () => {
    // 重置相关值
    queryForm.station = null;
    queryForm.equipment = null;
    queryForm.failSteps = null;
    selectedParams.value = [];

    if (queryForm.model) {
      try {
        showLoading('加载相关选项...');
        await fetchStations();
      } catch (error) {
        console.error('加载选项失败:', error);
      } finally {
        hideLoading();
      }
    } else {
      stationsList.value = [];
      equipmentsList.value = [];
      failStepsList.value = [];
    }
  };
  /*const handleStationChange = async () => {
    await fetchAvailableParams()
  }*/
  // 获取站位列表
  const fetchStations = async () => {
    try {
      const rqs = {
        key: "getStationList",
        CmdType: "sys",
        DBQueryData: [{
          key: "@dbName",
          value: localStorage.getItem('selectdb'),
          valueType: "string",
        }, {
          key: "@ProjectID",
          value: queryForm.model.toString(),
          valueType: "string",
        },]
      }
      const rs = await $http.post('DataHandle/R_InfoCommon', rqs);
      //console.log(rs.data);
      if (rs.data.isok) {
        stationsList.value = rs.data.response;
        filteredStationsList.value = [...stationsList.value];
      } else {
        Toast.error(rs.data.message);
      }
    } catch (error) {
      console.error('获取站位列表失败:', error);
      Toast.error('获取站位列表失败');
    }
  };

  // 获取设备列表
  const fetchEquipments = async () => {
    try {
      const rqs = {
        key: "getTestDeviceList",
        CmdType: "sys",
        DBQueryData: [{
          key: "@dbName",
          value: localStorage.getItem('selectdb'),
          valueType: "string",
        }, {
          key: "@tbName",
          value: TBLName.value,
          valueType: "string",
        },]
      }
      const rs = await $http.post('DataHandle/R_InfoCommon', rqs);

      if (rs.data.isok) {
        equipmentsList.value = rs.data.response;
        filteredEquipmentsList.value = [...equipmentsList.value]; // 初始化为完整列表
      } else {
        Toast.error(rs.data.message);
      }

    } catch (error) {
      console.error('获取设备列表失败:', error);
      Toast.error('获取设备列表失败');
    }
  };

  // 获取失败步骤列表
  const fetchFailSteps = async () => {
    try {
      const rqs = {
        key: "getFailStepsList",
        CmdType: "sys",
        DBQueryData: [{
          key: "@dbName",
          value: localStorage.getItem('selectdb'),
          valueType: "string",
        }, {
          key: "@tbName",
          value: TBLName.value,
          valueType: "string",
        },]
      }
      const rs = await $http.post('DataHandle/R_InfoCommon', rqs);

      if (rs.data.isok) {
        failStepsList.value = rs.data.response;
        filteredFailStepsList.value = [...failStepsList.value]; // 初始化为完整列表
        //console.log(failStepsList.value)
      } else {
        Toast.error(rs.data.message);
      }

    } catch (error) {
      console.error('获取失败步骤列表失败:', error);
      Toast.error('获取失败步骤列表失败');
    }
  };
  // 获取参数列表
  const fetchAvailableParams = async () => {
    try {
      const rqs = {
        key: "getColumnNameList",
        CmdType: "sys",
        DBQueryData: [{
          key: "@dbName",
          value: localStorage.getItem('selectdb'),
          valueType: "string",
        }, {
          key: "@tbName",
          value: TBLName.value,
          valueType: "string",
        },]
      }
      const rs = await $http.post('DataHandle/R_InfoCommon', rqs);

      if (rs.data.isok) {
        availableParams.value = rs.data.response;
        await nextTick();
        //console.log(availableParams.value)
      } else {
        Toast.error(rs.data.message);
      }

    } catch (error) {
      console.error('获取失败步骤列表失败:', error);
      Toast.error('获取失败步骤列表失败');
    }
  };
  // 获取SN查询
  const snGetLog = async (row) => {
    try {
      showLoading('加载SN记录中...')
      selectedSn.value = row.DUT_SN

      const rqs = {
        DBName: localStorage.getItem('selectdb'),
        SnCode: row.DUT_SN,
        DbList: stationsList.value.map(item => ({
          ProId: item.ProjectID.toString(),
          Step: item.ID.toString()
        }))
      }

      const rs = await $http.post('TestLogs/GetLogListBySN', JSON.stringify(rqs))
      //console.log(rs.data)
      if (rs.data.isok) {
        // 先按原始 startTime 降序，然后格式化时间并设置到 snLogs
        const rawLogs = Array.isArray(rs.data.response) ? rs.data.response : [];
        rawLogs.sort((a, b) => {
          const aTime = a.startTime ? dayjs(a.startTime).valueOf() : 0;
          const bTime = b.startTime ? dayjs(b.startTime).valueOf() : 0;
          return bTime - aTime;
        });
        snLogs.value = rawLogs.map(log => ({
          ...log,
          startTime: log.startTime ? formatDateTime(log.startTime) : '',
        }));
        snDialogVisible.value = true
      } else {
        Toast.error(rs.data.message)
      }
    } catch (error) {
      console.error('获取SN记录失败:', error)
      Toast.error('获取记录失败')
    } finally {
      hideLoading()
    }
  }
  // 站位搜索方法
  const filterStations = (query = '') => {
    stationLoading.value = true;
    if (query) {
      const lowerCaseQuery = query.toLowerCase();
      filteredStationsList.value = stationsList.value.filter(item =>
        item.StationName.toLowerCase().includes(lowerCaseQuery) ||
        item.ID.toString().includes(query)
      );
    } else {
      filteredStationsList.value = [...stationsList.value];
    }
    stationLoading.value = false;
  };

  // 设备搜索方法
  const filterEquipments = (query = '') => {
    equipmentLoading.value = true;
    if (query) {
      const lowerCaseQuery = query.toLowerCase();
      filteredEquipmentsList.value = equipmentsList.value.filter(item =>
        item.TerminalName.toLowerCase().includes(lowerCaseQuery) ||
        item.ID.toString().includes(query)
      );
    } else {
      filteredEquipmentsList.value = [...equipmentsList.value];
    }
    equipmentLoading.value = false;
  };

  // 失败步骤搜索方法
  const filterFailSteps = (query = '') => {
    failStepsLoading.value = true;
    if (query) {
      filteredFailStepsList.value = failStepsList.value.filter(item =>
        item.FailSteps.toLowerCase().includes(query.toLowerCase())
      );
    } else {
      filteredFailStepsList.value = [...failStepsList.value];
    }
    failStepsLoading.value = false;
  };
  // 显示详细数据弹窗
  const showDetailDialog = (log) => {
    currentDetail.value = log
    //console.log(currentDetail.value)
    detailDialogVisible.value = true
  }
  // 查询数据
  const handleSearch = async () => {
    try {
      currentPage.value = 1;
      await fetchTableData();

      // 设置自动刷新
      if (currentPage.value === 1 && isToday(queryForm.endDate)) {
        if (autoRefreshTimer.value) {
          clearInterval(autoRefreshTimer.value);
        }

        autoRefreshTimer.value = setInterval(() => {
          fetchTableData();
          console.log('自动刷新数据...');
        }, 60000);
      }
    } catch (error) {
      console.error('查询失败:', error);
    }
  };

  // 重置查询
  const handleReset = () => {
    queryForm.model = null;
    queryForm.station = null;
    queryForm.equipment = null;
    queryForm.result = null;
    queryForm.failSteps = null;
    queryForm.dutSnLike = '';
    queryForm.failstepsLike = '';
    queryForm.startDate = '';
    queryForm.endDate = '';

    stationsList.value = [];
    equipmentsList.value = [];
    failStepsList.value = [];

    selectedParams.value = [];
    tableData.value = [];
    currentPage.value = 1;
    pageSize.value = 50;
  };

  // 获取表格数据
  const fetchTableData = async () => {
    try {
      showLoading('加载数据中...');
      saveQuerySettings()
      const rqs = {
        dbName: localStorage.getItem('selectdb'),
        tbName: TBLName.value,
        StartTime: queryForm.startDate,
        EndTime: queryForm.endDate,
        TestResult: queryForm.result || '',
        FailSteps: queryForm.failSteps || [],
        DutSnLike: queryForm.dutSnLike || '',
        FailstepsLike: queryForm.failstepsLike || '',
        ColumnList: selectedParams.value.length > 0
          ? ',' + selectedParams.value.join(',')
          : '',
        Page: currentPage.value,   // 新增分页参数
        PageSize: pageSize.value,    // 新增分页参数
        DistinctType: queryForm.distinct   // 新增去重类型
      }

      const rs = await $http.post('TestLogs/GetTestSummaryTable', JSON.stringify(rqs));
      //console.log(rs.data)
      if (rs.data.isok) {
        if (rs.data.response.length === 0) {
          Toast("所选条件记录为空")
        }
        firstPassCount.value = rs.data.passCount;
        passRate.value = rs.data.passRate;
        tableData.value = rs.data.response.map(item => ({
          ...item,
          CreationTime: formatDateTime(item.CreationTime)
        }));

        // 保证前端按 StartTime 做降序排序（最新时间在前）
        tableData.value.sort((a, b) => {
          const aTime = a.StartTime ? dayjs(a.StartTime).valueOf() : 0;
          const bTime = b.StartTime ? dayjs(b.StartTime).valueOf() : 0;
          return bTime - aTime;
        });
        //console.log(tableData.value)
        total.value = rs.data.total;  // 设置总记录数
        // 1. 首先添加默认字段
        const columns = defaultColumns.map(prop => ({
          prop,
          label: prop
        }));

        // 2. 添加用户选择的其他字段（排除重复）
        selectedParams.value.forEach(param => {
          if (!defaultColumns.includes(param)) {
            columns.push({
              prop: param,
              label: param
            });
          }
        });
        tableColumns.value = columns;
      } else {
        Toast(rs.data.message);
      }

      const columnsForRequest = Array.from(new Set([
        ...defaultColumns,
        ...selectedParams.value
      ]));

    } catch (error) {
      console.error('获取表格数据失败:', error);
      Toast.error('获取数据失败');
    } finally {
      hideLoading();
    }
  };

  // 日期格式化辅助函数
  const formatDateTime = (dateString) => {
    return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
  };

  // 分页大小变化
  const handleSizeChange = (newSize) => {
    pageSize.value = newSize;
    fetchTableData();
  };

  // 当前页变化
  const handleCurrentChange = (newPage) => {
    currentPage.value = newPage;
    fetchTableData();
  };

  const getStationName = (stepId) => {
    if (stepId && stationsList.value.length > 0) {
      const station = stationsList.value.find(item => item.ID == stepId)
      return station ? station.StationName : stepId
    }
    return stepId
  }

  // 导出Excel方法
  const handleExportExcel = async () => {
    try {
      showLoading('正在导出Excel...');

      // 检查必要参数
      if (!queryForm.model || !queryForm.station) {
        Toast.warning('请先选择机型和站位');
        return;
      }

      // 构建请求参数
      const exportParams = {
        dbName: localStorage.getItem('selectdb'),
        tbName: TBLName.value,
        StartTime: queryForm.startDate,
        EndTime: queryForm.endDate,
        TestResult: queryForm.result || '',
        FailSteps: queryForm.failSteps || '',
        ColumnList: selectedParams.value.length > 0
          ? ',' + selectedParams.value.join(',')
          : '',
        DistinctType: queryForm.distinct   // 新增去重类型
      };

      // 调用导出接口
      const response = await $http.post(
        'TestLogs/GetTestSummaryTableExcel',
        exportParams,
        { responseType: 'blob' } // 重要：指定响应类型为blob
      );

      // 创建下载链接
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;

      // 生成文件名：机型_站位_导出时间
      const fileName = `${modelName.value}_${getStationName(queryForm.station)}_${dayjs().format('YYYYMMDD_HHmmss')}.xlsx`;
      link.setAttribute('download', fileName);

      document.body.appendChild(link);
      link.click();

      // 清理
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      Toast.success('导出成功');
    } catch (error) {
      console.error('导出失败:', error);

      // 尝试解析错误信息
      let errorMessage = '导出失败';
      if (error.response) {
        if (error.response.data instanceof Blob) {
          const reader = new FileReader();
          reader.onload = () => {
            try {
              const errorText = JSON.parse(reader.result);
              Toast.error(`导出失败: ${errorText.message || errorText}`);
            } catch (e) {
              Toast.error('导出失败: 未知错误');
            }
          };
          reader.readAsText(error.response.data);
        } else {
          Toast.error(`导出失败: ${error.response.data.message || error.response.data}`);
        }
      } else {
        Toast.error(`导出失败: ${error.message}`);
      }
    } finally {
      hideLoading();
    }
  };
  // 新增辅助函数
  const isToday = (dateString) => {
    return dayjs().format('YYYY-MM-DD') === dateString;
  };
  // 状态恢复方法
  const restoreQuerySettings = async () => {
    const savedData = localStorage.getItem('querySettings');
    if (savedData) {
      try {
        const settings = JSON.parse(savedData);

        // 检查保存的机型是否在当前机型列表中
        const modelExists = machineModels.value.some(
          model => model.ID === settings.queryForm.model
        );

        if (modelExists) {
          isRestoring.value = true;

          // 设置主模型
          queryForm.model = settings.queryForm.model;

          // 等待相关数据加载
          await fetchStations();

          // 设置其他查询参数
          queryForm.station = settings.queryForm.station;
          queryForm.equipment = settings.queryForm.equipment;
          queryForm.result = settings.queryForm.result;
          queryForm.failSteps = settings.queryForm.failSteps;
          queryForm.dutSnLike = settings.queryForm.dutSnLike || '';
          queryForm.failstepsLike = settings.queryForm.failstepsLike || '';
          queryForm.distinct = settings.queryForm.distinct || 'None'; // 恢复去重方式，默认None

          // 加载辅助数据
          await fetchEquipments();
          await fetchFailSteps();
          await fetchAvailableParams();

          // 设置UI状态
          selectedParams.value = settings.selectedParams || [];
          activeCollapse.value = settings.activeCollapse || ['queryConditions', 'selectParams'];
          timeShow.value = settings.timeShow !== false;

          // 短时禁用状态保存
          setTimeout(() => {
            isRestoring.value = false;
          }, 1000);
        }
      } catch (error) {
        console.error('恢复设置失败:', error);
      }
    }
  };
  // 状态保存方法
  const saveQuerySettings = () => {
    const settings = {
      queryForm: {
        model: queryForm.model,
        station: queryForm.station,
        equipment: queryForm.equipment,
        result: queryForm.result,
        failSteps: queryForm.failSteps,
        dutSnLike: queryForm.dutSnLike,
        failstepsLike: queryForm.failstepsLike,
        distinct: queryForm.distinct
      },
      selectedParams: selectedParams.value,
      activeCollapse: activeCollapse.value,
      timeShow: timeShow.value
    };
    localStorage.setItem('querySettings', JSON.stringify(settings));
  };
  const dateMobile = (date) => {
    queryForm.startDate = dayjs().subtract(date, 'day').format('YYYY-MM-DD');
    queryForm.endDate = dayjs().format('YYYY-MM-DD');
  };

  const moreDate = () => {
    timeShow.value = !timeShow.value;
  };
  // 全选失败步骤
  const selectAllFailSteps = () => {
    if (checkAllFailSteps.value == true) {
      queryForm.failSteps = filteredFailStepsList.value.map(item => item.FailSteps);
    } else {
      queryForm.failSteps = [];
    }
  };

  /* watch方法 */
  // 添加一个watcher监听机型和站位变化
  watch(
    () => [queryForm.model, queryForm.station],
    ([newModel, newStation]) => {
      // 如果机型和站位都有值，获取设备列表和失败步骤列表
      if (newModel && newStation) {
        fetchEquipments();
        fetchFailSteps();
        fetchAvailableParams(); // 如果有可用参数列表也可以在这里获取
      } else {
        // 如果机型和站位任何一个为空，清空列表
        availableParams.value = [];
        equipmentsList.value = [];
        failStepsList.value = [];
        queryForm.equipment = null;
        queryForm.failSteps = null;
        tableData.value = [];
      }
    }
  );
</script>

<style scoped>
  .query-container {
    padding: 3px;
    border-radius: 3px;
    box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.1);
  }

  /* 查询条件区域样式 */
  .condition-section {
    margin-bottom: 2px;
  }

  .condition-form {
    display: flex;
    flex-direction: column;
  }

  .condition-row {
    display: flex;
    flex-wrap: wrap;
    gap: 3px;
  }

  .condition-item {
    min-width: 235px;
    margin-bottom: 1px;
  }

  .date-range,
  .number-range {
    display: flex;
    align-items: center;
  }

  .date-separator {
    padding: 0 5px;
  }

  /* 参数区域样式 */
  .param-section {
    margin-bottom: 5px;
    padding: 5px;
  }
  /* 参数列表网格布局 */
  .param-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 2px;
  }

  .param-item {
    margin-right: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .param-header {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 6px;
    font-weight: bold;
  }



  .action-btn {
    flex-shrink: 1; /* 允许按钮宽度缩小 */
    min-width: auto; /* 去除最小宽度限制 */
  }

  .controls-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 5px 0;
    flex-wrap: wrap;
  }

  .stats-info {
    flex: 1;
    min-width: 120px;
    font-weight: 800;
  }

  .pagination {
    flex: 2;
    display: flex;
    justify-content: center;
    min-width: 200px;
  }

  .action-buttons {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    min-width: 200px;
  }

  .action-input {
    width: 170px;
  }

  .collapse-panel {
    margin-bottom: 1px;
    border: none;
    border-radius: 1px;
    box-shadow: 0 1px 1px rgba(0,0,0,0.1);
  }

  :deep(.el-collapse-item__header) {
    font-weight: bold;
    padding: 0 2px;
    border-radius: 1px;
  }

  :deep(.el-collapse-item__content) {
    padding: 2px;
  }

  :deep(.el-collapse) {
    --el-collapse-header-height: 25px;
  }
  /* 表格布局 */
  :deep(.el-table) {
    --el-table-row-height: 30px;
    --el-table-header-background-color: #f5f7fa;
  }

  :deep(.el-table th.el-table__cell) {
    padding: 0 !important;
  }

  :deep(.el-table td.el-table__cell) {
    padding: 0 !important;
  }

  :deep(.el-table .cell) {
    line-height: 1.2 !important;
    padding: 0 2px !important;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .stats-container {
    margin-bottom: 2px;
    display: flex;
    gap: 5px;
  }

  .detail-container {
    max-height: 70vh;
    overflow-y: auto;
  }

  /* 移动端适配 */
  @media (max-width: 768px) {
    .condition-row {
      flex-direction: column;
    }

    .condition-item {
      min-width: 100%;
    }

    .param-list {
      flex-direction: column;
      gap: 3px;
    }

    .param-item {
      margin-right: 0;
    }
    /* 表格布局 */
    :deep(.el-table) {
      --el-table-row-height: 30px;
      --el-table-header-background-color: #f5f7fa;
    }

    :deep(.el-table th.el-table__cell) {
      padding: 0 !important;
    }

    :deep(.el-table td.el-table__cell) {
      padding: 0 !important;
    }

    :deep(.el-table .cell) {
      line-height: 1 !important;
      padding: 0 2px !important;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    /* 表格容器高度 */
    .data-section {
      position: relative;
      overflow: auto;
    }
    /* 参数列表网格布局 */
    :deep(.param-grid) {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(123px, 1fr)) !important;
      gap: 2px;
    }

    .controls-container {
      flex-direction: column;
      align-items: stretch;
      gap: 8px;
    }

    .stats-info {
      order: 1;
      text-align: center;
    }

    .action-buttons {
      order: 2;
      justify-content: center;
    }

    .pagination {
      order: 3;
    }

    .action-btn {
      flex-shrink: 0;
      padding: 4px 6px;
      font-size: 12px;
      white-space: nowrap;
    }
  }
</style>
