<template>
  <div>
    <div class="el-table-content">
      <div>
        <base-search :isShowDate="true" :dateValue="date.arr"
        @on-search="search" @reset="reset" @exportToExcel="exportToExcel"></base-search>
      </div>
      <div>
        <pro-table :height="tabHeight" :loading="tab_loading" :data="allData" :config="tableConfig"></pro-table>
      </div>
      <div style="height: 50px;display: flex;align-items: flex-end;justify-content: flex-end;">
        <el-pagination
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          :current-page="queryFormVarDictData.page_no"
          :page-size="queryFormVarDictData.page_size"
          :page-sizes="[20, 50, 100, 200]" 
          :total="total"
          layout="sizes,->,prev, next"
          :disabled="total === 0"
          background
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import BizVarDictAPI, { BizVarDictTable,BizVarDictPageQuery } from '@/api/module_business/vardict'
import dayjs from 'dayjs';
import * as XLSX from 'xlsx';
import { formatToDateTime } from "@/utils/dateUtil";

const tabHeight = ref('calc(100vh - 70px - 5px - 50px - 10px - 44px - 50px - 50px)')
const tab_loading = ref(true)
const allData = ref<BizVarDictTable[]>([]);
const total = ref(0);
const craneInfo = JSON.parse(localStorage.getItem('craneInfo') || '{}');
const date = reactive({
  arr: [dayjs(dayjs().subtract(1, 'day')).format('YYYY/MM/DD HH:mm:ss'), dayjs().format('YYYY/MM/DD HH:mm:ss')]
})
const queryFormVarDictData = reactive<BizVarDictPageQuery>({
  page_no: 1,
  page_size: 20,
  crane_no: craneInfo.crane_no,
  var_code: undefined,
  var_name: undefined,
  mec_type: undefined,
  switch_type: undefined,
  gateway_id: undefined,
  var_group: undefined,
  var_category: undefined,
  is_top_show: undefined,
  is_save: undefined,
  is_overview_top_show: undefined,
  is_home_page_show: undefined,
  status: undefined,
  created_time: undefined,
  updated_time: undefined,
  created_id: undefined,
  updated_id: undefined,
  data_type:'1'
});

const tableConfig = [
  {
    label: '点位名称',
    prop: 'var_name'
  },
  {
    label: '点位数据',
    prop: 'val'
  },
  {
    label: '时间',
    prop: 'ts'
  }
]

const getData = async () => {
  // 时间查询条件
  queryFormVarDictData.created_time = [formatToDateTime(date.arr[0]), formatToDateTime(date.arr[1])]
  let response = await BizVarDictAPI.historyData(queryFormVarDictData);
  allData.value = response.data.data.items
  total.value = response.data.data.total
  tab_loading.value = false
};

const handlePageChange = (newPage: number) => {
  tab_loading.value = true
  queryFormVarDictData.page_no = newPage;
  getData(); // 页码变化后重新请求数据
};

const handleSizeChange = (newSize: number) => {
  tab_loading.value = true
  queryFormVarDictData.page_size = newSize; // 更新每页条数
  queryFormVarDictData.page_no = 1; // 条数变化时重置为第1页（通用逻辑）
  getData(); // 重新请求数据
};

const search = (v:any) => {
  tab_loading.value = true
  date.arr = v.dateValue
  getData();
}
const reset = () => {
  tab_loading.value = true
  date.arr = [dayjs(dayjs().subtract(1, 'day')).format('YYYY-MM-DD HH:mm:ss'), dayjs().format('YYYY-MM-DD HH:mm:ss')]
  getData();
}
const exportToExcel = () => {
  // 1. 空数据校验
  if (!allData.value || allData.value.length === 0) {
    ElMessage.warning('暂无可导出的数据');
    return;
  }

  try {
    // 2. 从tableConfig中提取【导出字段】和【中文表头】（核心复用逻辑）
    const exportFields = tableConfig.map(item => item.prop); // 提取字段名：['var_name', 'val', 'ts']
    const chineseHeaders = tableConfig.map(item => item.label); // 提取中文表头：['点位名称', '点位状态', '时间']

    // 3. 处理原始数据：只保留tableConfig中配置的字段，空值兜底
    const processedData = allData.value.map(item => {
      const row = {};
      exportFields.forEach(field => {
        row[field] = item[field] ?? ''; // 空值替换为''，避免undefined
      });
      return row;
    });

    // 4. 生成Excel工作表（复用tableConfig的表头）
    const worksheet = XLSX.utils.json_to_sheet(processedData, {
      header: exportFields, // 匹配tableConfig的字段名
      skipHeader: true, // 跳过默认的英文字段表头
    });

    // 5. 手动设置中文表头（从tableConfig取label）
    chineseHeaders.forEach((header, index) => {
      const cellRef = XLSX.utils.encode_cell({ r: 0, c: index }); // 0行=表头行，index=列索引
      worksheet[cellRef] = { v: header, t: 's' }; // 设置表头内容为tableConfig的label
    });

    // 6. 生成工作簿并导出
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, '历史数据'); // 自定义sheet名
    // 文件名加时间戳，避免覆盖
    const fileName = craneInfo.crane_name+`历史数据.xlsx`;
    XLSX.writeFile(workbook, fileName);

    ElMessage.success('Excel导出成功！');
  } catch (error) {
    ElMessage.error(`导出失败：${error.message}`);
  }
};

onMounted(async () => {
  await getData();
});
</script>

<style lang="less" scoped>
.el-table-content {
  padding: 20px;
  background: linear-gradient(to bottom, rgba(20, 66, 140, 0.8) 0%, rgba(18, 31, 52, 1) 15%);
  border: 2px solid rgba(40, 73, 136, 1);
  height: 100%;
}
</style>