<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <!-- 新增Tabs组件区分实时/历史数据 -->
  <Tabs v-model:activeKey="activeTab" class="common-page-tabs" type="line">
    <TabPane tab="实时数据监测" key="realtime">
      <!-- 实时数据表格 -->
      <BasicTable style="padding: 0" @register="registerRealtimeTable">
        <template #action="{ record }">
          <div class="action-buttons">
            <button @click="openModal(record)" class="action-btn" title="详情">
              <SvgIcon name="details" />
            </button>
            <!-- <button @click="openModal(record)" class="action-btn" title="详情">
            <SvgIcon name="chart" />
          </button> -->
          </div>
        </template>
        <template #resetBefore>
          <a-button type="default" class="ml-8px" preIcon="mdi:download" @click="onExportXlsTime"> 导出 </a-button>
        </template>
      </BasicTable>
    </TabPane>

    <TabPane tab="历史数据监测" key="history">
      <!-- 历史数据表格 -->
      <BasicTable style="padding: 0" @register="registerHistoryTable">
        <template #resetBefore>
          <a-button type="default" class="ml-8px" preIcon="mdi:download" @click="onExportXls"> 导出 </a-button>
        </template>
        <template #form-goaf-select>
          <a-select v-model:value="goafId" :options="goafOptions" placeholder="请选择" @change="reloadHistory" />
        </template>
        <template #action="{ record }">
          <div class="action-buttons">
            <button @click="handleGoToPageQuery(record, '/warningAnalysis/connectAnalysis')" class="action-btn" title="智能分析数据">
              <SvgIcon name="chart" />
            </button>
          </div>
        </template>
      </BasicTable>
    </TabPane>
  </Tabs>

  <!-- 实时数据详情弹框 -->
  <HistoricalDetailsModal :modal-details-data="modalDetailsData" @register="registerRealtimeModal" @close="resume" />
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { BasicTable } from '/@/components/Table';
  import { Tabs, TabPane } from 'ant-design-vue';
  // 引入模拟数据
  import { columns, historicalColumns, historicalFormSchema, searchFormSchema } from './monitor.data';
  import HistoricalDetailsModal from './components/HistoricalDetailsModal.vue';
  import { SvgIcon } from '/@/components/Icon';
  import { getGoafData, getGoafHistory } from './monitor.api';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { useModal } from '/@/components/Modal';
  import { useIntervalFn } from '@vueuse/core';
  import { useInitForm } from './hooks/form';
  import { modalDetailsData } from './monitor.data';
  import { advancedRoutePush } from '/@/utils';
  // import { getGoafList } from '../../system/algorithm/algorithm.api';

  // 激活的Tab页签

  // 处理矿名选择器相关的逻辑
  const { departId, goafOptions, goafId, rawcode, hiscode, route, initGoafOptions } = useInitForm();

  const activeTab = ref('realtime');
  const tableQueryParams = ref({}); // 存储表格查询参数的响应式变量

  const wrappedGetMineData = (params) => {
    // 缓存参数（这就是getMineData实际请求的参数）
    tableQueryParams.value = { ...params };
    // 调用原接口
    return getGoafData(params);
  };
  // 注册实时数据表格
  const { tableContext: ctxRealtime, onExportXls: onExportXlsTime } = useListPage({
    tableProps: {
      immediate: false,
      api: wrappedGetMineData,
      columns,
      formConfig: {
        autoSearch: true,
        model: { deptId: rawcode, alarmLevel: route.query.alarmLevel },
        schemas: [
          {
            field: 'deptId',
            label: '煤矿名称',
            component: 'MineCascader',
            colProps: { span: 6 },
            required: true,
            componentProps: {
              initFromStore: false,
              // syncFromStore: false,
              rootId: departId,
            },
          },
          ...searchFormSchema,
        ],
        schemaGroupNames: ['常规查询'],
      },
      showIndexColumn: false,
      scroll: { x: 'max-content' },
    },
    pagination: false,
    exportConfig: {
      url: '/ventanaly-province/province/device/exportGoafReal',
      name: '老空区永久密闭监测数据',
      // params: {
      //   goafId,
      // },
    },
  });
  const [registerRealtimeTable, realtimeTable] = ctxRealtime;

  const { pause, resume } = useIntervalFn(() => realtimeTable.reload({ silence: true }), 60000);

  // 注册历史数据表格
  const { tableContext: ctxHistory, onExportXls } = useListPage({
    tableProps: {
      immediate: false,
      api: async (params) => {
        await initGoafOptions(params.deptId);
        if (!goafId.value) {
          return Promise.resolve([]);
        }
        params.goafId = goafId.value;
        return getGoafHistory(params);
      },
      columns: historicalColumns,
      formConfig: {
        autoSearch: true,
        model: {
          deptId: hiscode,
        },
        schemas: [
          {
            field: 'deptId',
            label: '煤矿名称',
            component: 'MineCascader',
            colProps: { span: 6 },
            required: true,
            componentProps: {
              initFromStore: false,
              syncToStore: false,
              rootId: departId,
              // onChange(v) {
              //   historyTable.setLoading(true);
              //   initGoafOptions(v).finally(() => {
              //     historyTable.setLoading(false);
              //   });
              // },
            },
          },
          ...historicalFormSchema,
        ], // 使用历史数据的搜索配置
        schemaGroupNames: ['常规查询'],
      },
      useSearchForm: true,
      bordered: true,
      showIndexColumn: false,
      scroll: { x: 'max-content' },
      // showActionColumn: false,
    },
    exportConfig: {
      url: '/province/device/exportGoafHistory',
      name: '历史数据',
      params: {
        goafId,
      },
    },
    pagination: true,
  });
  const [registerHistoryTable, { reload: reloadHistory }] = ctxHistory;

  // 弹窗引用
  const [registerRealtimeModal, { openModal: openRealtimeModal }] = useModal();
  // const [registerHistoryModal, { openModal: openHistoryModal }] = useModal();

  // 打开弹窗方法（区分实时/历史）
  const openModal = (record) => {
    openRealtimeModal(true, record);
    // if (type === 'realtime') {
    //   // 可向实时弹窗传递当前记录数据
    // } else {
    //   // 可向历史弹窗传递当前记录数据
    //   openHistoryModal(true, record);
    // }
    pause();
  };

  /**
   * 通用页面跳转方法
   * @param record 当前行数据
   * @param path 目标路径
   */
  function handleGoToPageQuery(record: any, path: string) {
    advancedRoutePush({
      path,
      query: { deptId: record.deptId, goafId: record.goafId },
    });
  }
</script>

<style lang="less" scoped></style>
