<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:211px;"
                           clearable>
                  <el-option v-for="item in machineModels"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value" />
                </el-select>
              </el-form-item>

              <!-- 当机型不为空时显示其他条件 -->
              <template v-if="queryForm.model">
                <!-- 条形码输入 -->
                <el-form-item label="条码" class="condition-item">
                  <el-input v-model="queryForm.barcode"
                            placeholder="请输入条形码"
                            style="width:211px;"
                            clearable />
                </el-form-item>
                <!-- 日期范围选择 -->
                <el-form-item label="日期" class="condition-item">
                  <div class="date-range">
                    <el-date-picker v-model="queryForm.startDate"
                                    type="date"
                                    style="width:120px;"
                                    placeholder="开始日期"
                                    value-format="YYYY-MM-DD" />
                    <span>&nbsp;-&nbsp;</span>
                    <el-date-picker v-model="queryForm.endDate"
                                    type="date"
                                    style="width:120px;"
                                    placeholder="结束日期"
                                    value-format="YYYY-MM-DD" />
                  </div>
                </el-form-item>
                <!-- 查询条件选择 -->
                <el-form-item label="条件" class="condition-item">
                  <el-select v-model="queryForm.queryType"
                             style="width:211px;"
                             placeholder="请选择">
                    <el-option label="BARCODE" value="BARCODE" />
                    <!-- 其他选项根据实际接口返回添加 -->
                  </el-select>
                </el-form-item>

                <!-- 当条件选择不为空时显示模糊匹配和数值范围 -->
                <template v-if="queryForm.queryType">
                  <!-- 模糊匹配 - 仅在数值范围没有值时显示 -->
                  <el-form-item v-if="!hasNumberRangeValue"
                                label="模糊"
                                class="condition-item">
                    <el-input v-model="queryForm.keyword"
                              style="width:211px;"
                              placeholder="输入关键词" />
                  </el-form-item>

                  <!-- 数值范围 - 仅在模糊匹配没有值时显示 -->
                  <el-form-item v-if="!hasKeywordValue"
                                label="数值"
                                class="condition-item">
                    <div class="number-range">
                      <el-input v-model="queryForm.minValue"
                                style="width:100px;"
                                placeholder="最小值" />
                      <span>&nbsp;-&nbsp;</span>
                      <el-input v-model="queryForm.maxValue"
                                style="width:100px;"
                                placeholder="最大值" />
                    </div>
                  </el-form-item>
                </template>
              </template>
            </div>
          </el-form>
        </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"
                         @change="handleSelectAll">
              全选
            </el-checkbox>
            <el-checkbox v-model="resParamsSelected" size="small"
                         @change="handleSelectAll">
              选择Results
            </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.value"
                             :label="param.value"
                             class="param-item">
                  {{ param.label }}
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>
    <!-- 操作按钮 - 主要修改点：优化移动端按钮布局 -->
    <div class="action-buttons">
      <el-button type="primary"
                 icon="Search" size="small"
                 @click="handleSearch"
                 class="action-btn">
        查询
      </el-button>
      <el-button icon="Refresh" size="small"
                 @click="handleReset"
                 class="action-btn">重置</el-button>
      <!-- 导出按钮 -->
      <el-button type="success"
                 icon="Download"
                 size="small"
                 @click="handleExportExcel"
                 class="action-btn">
        导出Excel
      </el-button>
    </div>

    <!-- 分页器 -->
    <div class="pagination">
      <el-pagination v-model:current-page="currentPage"
                     v-model:page-size="pageSize"
                     size="small"
                     :page-sizes="[50, 100, 200, 300]"
                     layout="total, sizes, prev, pager, next"
                     :total="total"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" />
    </div>
    <!-- 数据表格 -->
    <div class="data-section">
      <el-table :data="tableData"
                stripe
                size="small"
                border
                style="width: 100%">
        <el-table-column v-for="col in tableColumns"
                         :key="col.prop"
                         :prop="col.prop"
                         :label="col.label"
                         min-width="120" />
      </el-table>
    </div>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, watch, inject, computed } from 'vue';
  import { Toast } from 'tdesign-mobile-vue';
  import { AddIcon, SaveIcon } from 'tdesign-icons-vue-next';
  import { ElMessage, ElMessageBox, ElCollapse, ElCollapseItem } from 'element-plus'
  import { RefreshRight, Refresh, Search } from '@element-plus/icons-vue'
  import dayjs from 'dayjs'

  const $http = inject('$http')
  
  // ---------- 数据定义 ----------
  const queryForm = reactive({
    model: null,         // 机型
    barcode: null,       // 条形码
    startDate: '',     // 开始日期
    endDate: '',       // 结束日期
    queryType: null,     // 查询条件
    keyword: null,       // 字符模糊匹配
    minValue: null,      // 最小值
    maxValue: null       // 最大值
  });

  // 机型选项
  const machineModels = ref([]);
  const activeCollapse = ref(['queryConditions', 'selectParams']); // 默认展开
  // 可用参数列表
  const availableParams = ref([
    { label: 'COLORBOX_BARCODE', value: 'COLORBOX_BARCODE' },
    { label: 'OUTBOXCODE', value: 'OUTBOXCODE' },
    { label: 'MACCODE', value: 'MACCODE' },
    { label: 'UNITWEIGTH', value: 'UNITWEIGTH' },
    { label: 'LABEL_PRINT_CNT', value: 'LABEL_PRINT_CNT' },
    { label: 'S1', value: 'S1' },
    { label: 'S4', value: 'S4' },
    { label: 'S5', value: 'S5' },
    { label: 'S6', value: 'S6' },
    { label: 'S7', value: 'S7' },
    { label: 'S10', value: 'S10' },
    { label: 'RESULT1', value: 'RESULT1' },
    { label: 'RESULT4', value: 'RESULT4' },
    { label: 'RESULT7', value: 'RESULT7' },
    { label: 'RESULT10', value: 'RESULT10' },
    { label: 'MO', value: 'MO' },
    { label: 'SHIPPINGLOADER', value: 'SHIPPINGLOADER' },
    { label: 'SHIPPINGDATETIME', value: 'SHIPPINGDATETIME' },
    { label: '589_LCM_SN', value: '589_LCM_SN' },
    { label: '589_KEYBOARD_SN', value: '589_KEYBOARD_SN' },
    { label: 'RESULT2', value: 'RESULT2' },
    { label: 'RESULT3', value: 'RESULT3' },
    { label: 'RESULT6', value: 'RESULT6' },
    { label: 'RESULT12', value: 'RESULT12' },
    { label: 'SHIPPINGCODE', value: 'SHIPPINGCODE' },
    { label: '589_LCM_SN', value: '589_LCM_SN' },
    { label: '589_MODULEBOARD_SN', value: '589_MODULEBOARD_SN' },
    { label: '189_MAINBOARD_SN', value: '189_MAINBOARD_SN' }
  ]);

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

  // 表格数据
  const tableData = ref([]);
  const tableColumns = ref([
    { prop: 'id', label: 'ID' },
    { prop: 'barcode', label: '条形码' },
    { prop: 'result', label: '结果' }
  ]);

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

  // ---------- 计算属性 ----------
  // 检查是否有数值范围值
  const hasNumberRangeValue = computed(() => {
    return queryForm.minValue || queryForm.maxValue;
  });

  // 检查是否有模糊匹配值
  const hasKeywordValue = computed(() => {
    return queryForm.keyword;
  });
  // 全选参数控制
  const allParamsSelected = computed({
    get: () => availableParams.value.length > 0 &&
      selectedParams.value.length === availableParams.value.length,
    set: (value) => {
      selectedParams.value = value
        ? availableParams.value.map(p => p.value)
        : [];
    }
  });
  const resParamsSelected = computed({
    get: () => availableParams.value.length > 0 &&
      selectedParams.value.length === availableParams.value.length,
    set: (value) => {
      selectedParams.value = value
        ? availableParams.value.map(p => p.value)
        : [];
    }
  });
  // ---------- 生命周期 ----------
  onMounted(() => {
    fetchMachineModels();
    fetchAvailableParams();
  });

  // ---------- 方法定义 ----------
  // 获取机型列表
  const fetchMachineModels = async () => {
    try {
      // 实际接口调用:
      // const response = await $http.get('/api/models');
      // machineModels.value = response.data.map(item => ({
      //   value: item.id,
      //   label: item.name
      // }));

      // 模拟数据
      machineModels.value = [
        { value: 'model1', label: '机型1' },
        { value: 'model2', label: '机型2' },
        { value: 'model3', label: '机型3' }
      ];
    } catch (error) {
      console.error('获取机型失败:', error);
    }
  };

  // 获取可用参数列表
  const fetchAvailableParams = async () => {
    try {
      // 实际接口调用:
      // const response = await $http.get('/api/parameters');
      // availableParams.value = response.data.map(item => ({
      //   value: item.id,
      //   label: item.name
      // }));

      // 模拟数据 - 默认使用上面定义的初始数据
    } catch (error) {
      console.error('获取参数列表失败:', error);
    }
  };

  // 全选/取消全选
  const handleSelectAll = (val) => {
    selectedParams.value = val
      ? availableParams.value.map(p => p.value)
      : [];
  };

  // 查询数据
  const handleSearch = async () => {
    try {
      currentPage.value = 1;
      await fetchTableData();
    } catch (error) {
      console.error('查询失败:', error);
    }
  };

  // 重置查询
  const handleReset = () => {
    Object.keys(queryForm).forEach(key => {
      // 日期字段需要空字符串而非null
      if (key.includes('Date')) {
        queryForm[key] = '';
      } else {
        queryForm[key] = null;
      }
    });
    selectedParams.value = [];
    tableData.value = [];
    currentPage.value = 1;
    pageSize.value = 50;
  };
  // 获取表格数据
  const fetchTableData = async () => {
    try {
      // 实际查询接口调用:
      // const params = {
      //   ...queryForm,
      //   selectedParams: selectedParams.value.join(','),
      //   page: currentPage.value,
      //   size: pageSize.value
      // };
      // const response = await $http.get('/api/query', { params });
      // tableData.value = response.data.list;
      // total.value = response.data.total;

      // 模拟数据
      console.log('调用查询接口:', {
        ...queryForm,
        selectedParams: selectedParams.value,
        page: currentPage.value,
        size: pageSize.value
      });

      // 模拟响应
      tableData.value = [
        { id: 1, barcode: 'SN123456', result: '通过' },
        { id: 2, barcode: 'SN789012', result: '失败' },
        { id: 3, barcode: 'SN345678', result: '通过' },
        { id: 4, barcode: 'SN901234', result: '通过' },
        { id: 5, barcode: 'SN567890', result: '失败' }
      ];
      total.value = 5;

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

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

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

  // 导出Excel
  const handleExportExcel = async () => {
    try {
      console.log('导出Excel参数:', {
        ...queryForm,
        selectedParams: selectedParams.value
      });

      // 实际导出接口调用:
      // const params = {
      //   ...queryForm,
      //   selectedParams: selectedParams.value.join(',')
      // };
      // window.location.href = `/api/export?${new URLSearchParams(params)}`;

    } catch (error) {
      console.error('导出失败:', error);
    }
  };
</script>

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

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

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

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

  .condition-item {
    flex: 1;
    min-width: 250px;
    margin-bottom: 5px;
  }

  .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-buttons {
    margin: 5px 0;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }

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

  /* 表格区域 */
  .data-section {
    position: relative;
  }

  .pagination {
    margin: 2px 0;
    display: flex;
    justify-content: center;
  }
  .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;
  }

  /* 移动端适配 */
  @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(.param-grid) {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(123px, 1fr)) !important;
      gap: 2px;
    }

    /* 移动端按钮优化 - 保持一行显示 */
    .action-buttons {
      flex-wrap: nowrap; /* 防止按钮换行 */
      overflow-x: auto; /* 如果按钮过多允许水平滚动 */
      justify-content: flex-start; /* 从左对齐 */
      gap: 1px; /* 减小按钮间距 */
    }

    .action-btn {
      flex-shrink: 0; /* 不收缩按钮 */
      padding: 4px 6px; /* 减小按钮内边距 */
      font-size: 12px; /* 缩小字体 */
      white-space: nowrap; /* 确保文本不换行 */
    }
  }
</style>
