<template>
  <div>
    <div class="el-table-content">
      <div>
        <base-search :isShowDate="true" :dateValue="date.arr" 
        :isShowMecSect="true" :sectMecName="'机构'" :sectMecValue="sectMecValue" :sectMecOption="sectMecOption"
        :isShowVarDictSect="true" :sectVarDictName="'点位'" :sectVarDictValue="sectVarDictValue" :sectVarDictOption="sectVarDictOption"
        @on-search="search" @reset="reset" @sectMecChange="sectMecChange" @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 BizMecAPI,{ BizMecPageQuery } from '@/api/module_business/mec';
import dayjs from 'dayjs';
import { useDictStore } from "@/store";
import * as XLSX from 'xlsx';
import { formatToDateTime } from "@/utils/dateUtil";

const receiveData = inject<(data: { craneName: string; isShowHomeButton: boolean }) => void>('receiveData');
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 sectMecValue = ref('0')
const sectVarDictValue = ref('0')
const sectMecOption = ref<OptionItem[]>([])
const sectVarDictOption = ref<OptionItem[]>([])
interface OptionItem {
  value: number | string;
  label: string;
}
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 queryMecVarDictData = reactive<BizVarDictPageQuery>({
  page_no: 1,
  page_size: 200,
  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:undefined
});

const queryFormMecData = reactive<BizMecPageQuery>({
  page_no: 1,
  page_size: 20,
  crane_no: craneInfo.crane_no,
  mec_no: undefined,
  mec_category: undefined,
  mec_type: undefined,
  status: undefined,
  created_time: undefined,
  updated_time: undefined,
  order_by: 'sort,asc;'
})



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

const dictStore = useDictStore()
const dictTypes: any = [
  'mec_type',
]

const getCraneMecData = async () => {
  const res = await BizMecAPI.listBizMec(queryFormMecData);
  sectMecOption.value.push({
    value: '0',
    label: '全部机构'
  })
  res.data.data.items.forEach(item => {
    if(item.mec_type){
      sectMecOption.value.push({
        value: item.mec_type.toString(),
        label: (item.mec_type 
                  ? (dictStore.getDictLabel("mec_type", item.mec_type) as any)
                  : undefined
                )?.dict_label || item.mec_type
      })
    }
  });
}

const getCraneVarDictData = async () => {
  sectVarDictOption.value = []
  queryMecVarDictData.mec_type = sectMecValue.value === '0' ? undefined : sectMecValue.value;
  const res = await BizVarDictAPI.listBizVarDictAnalog(queryMecVarDictData);
  sectVarDictOption.value.push({
    value: '0',
    label: '全部点位'
  })
  res.data.data.forEach(item => {
    if(item.var_code){
      sectVarDictOption.value.push({
        value: item.var_code,
        label: item.var_name || item.var_code,
      })
    }
  });
}

const getData = async () => {
  tab_loading.value = true
  queryFormVarDictData.created_time = [formatToDateTime(date.arr[0]), formatToDateTime(date.arr[1])]
  queryFormVarDictData.mec_type = sectMecValue.value === '0' ? undefined : sectMecValue.value;
  queryFormVarDictData.var_code = sectVarDictValue.value === '0' ? undefined : sectVarDictValue.value;
  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) => {
  queryFormVarDictData.page_no = newPage;
  getData(); // 页码变化后重新请求数据
};

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

const search = (v:any) => {
  date.arr = v.dateValue
  sectMecValue.value = v.sectMecValue
  sectVarDictValue.value = v.sectVarDictValue
  getData();
}
const reset = () => {
  date.arr = [dayjs(dayjs().subtract(1, 'day')).format('YYYY-MM-DD HH:mm:ss'), dayjs().format('YYYY-MM-DD HH:mm:ss')]
  sectMecValue.value = '0'
  sectVarDictValue.value = '0'
  getCraneVarDictData();
  getData();
}

const sectMecChange = (v:any) => {
  sectMecValue.value = v.sectMecValue
  getCraneVarDictData();
}
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 : Record<string, any> = {};
      exportFields.forEach(field => {
        const typedItem = item as Record<string, any>;
        row[field] = typedItem[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:any) {
    ElMessage.error(`导出失败：${error.message}`);
  }
};

onMounted(async () => {
  if (receiveData) {
    receiveData({ craneName: craneInfo.crane_name ?? '', isShowHomeButton: true });
  }
  if (dictTypes.length > 0) {
    await dictStore.getDict(dictTypes)
  }
  await getCraneMecData();
  await getCraneVarDictData();
  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>