<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <!-- 新增Tabs组件区分实时/历史数据 -->
  <Tabs v-model:activeKey="activeTab" type="line" class="common-page-tabs">
    <TabPane tab="实时分析" key="realtime">
      <div class="board-info">
        <MiniBoard
          v-for="(item, index) in boardData"
          :key="index"
          type="A"
          :label="item.label"
          :value="item.value"
          layout="label-top"
          class="board-item"
        />
      </div>
      <!-- 实时数据表格 -->
      <BasicTable @register="registerRealtimeTable" :scroll="{ x: 'max-content' }" :style="{ padding: 0 }">
        <!-- 核心：判断record是否有有效数据，无则显示- -->
        <template #action="{ record }">
          <div class="action-buttons">
            <button @click="openModal(record)" class="action-btn resolved-btn" title="解决">
              <SvgIcon name="details" />
            </button>
            <button @click="handleGoToPageQuery(record, '/warningAnalysis/connectAnalysis')" 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>
        <template #empty>
          <!-- 无数据时显示-，样式居中对齐 -->
          <span class="empty-placeholder">-</span>
        </template>
      </BasicTable>
    </TabPane>

    <TabPane tab="历史数据" key="history">
      <!-- 历史数据表格 -->
      <BasicTable @register="registerHistoryTable" :scroll="{ x: 'max-content' }" :style="{ padding: 0 }">
        <template #action="{ record }">
          <div class="action-buttons">
            <button @click="handleGoToPageQuery(record, '/warningAnalysis/connectAnalysis')" class="action-btn" title="智能分析数据">
              <SvgIcon name="chart" />
            </button>
          </div>
        </template>
        <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="historyTable.reload" />
        </template>
      </BasicTable>
    </TabPane>
  </Tabs>
  <!-- 弹窗组件 -->
  <RealtimeDetailsModal title="密闭爆炸危险性判定详情" :width="1000" :modal-details-data="modalDetailsData" @register="registerRealtimeModal" />
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { BasicTable } from '/@/components/Table';
  import { Tabs, TabPane } from 'ant-design-vue';
  import MiniBoard from '/@/components/Configurable/detail/MiniBoard.vue';
  import { SvgIcon } from '/@/components/Icon';
  // 引入模拟数据
  import { columns, modalDetailsData } from './sealRiskJudgeAnalysis.data';
  import { getProvinceAlarm, getProvinceAlarmHistory, getProvinceAlarmNum } from './sealRiskJudge.api';
  import RealtimeDetailsModal from '/@/views/monitor/sealedMonitor/components/RealtimeDetailsModal.vue';
  import { useModal } from '/@/components/Modal';
  import { useInitForm } from '../../common/analysis';
  import { historicalFormSchema } from '/@/views/monitor/sealedMonitor/monitor.data';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { advancedRoutePush } from '/@/utils';

  // 激活的Tab页签
  const activeTab = ref('realtime');

  const { goafOptions, goafId, hiscode, initGoafOptions } = useInitForm();

  const boardData = ref([
    {
      label: '存在风险情况数量',
      value: '-',
    },
    {
      label: '低风险',
      value: '-',
    },
    {
      label: '一般风险',
      value: '-',
    },
    {
      label: '较高风险',
      value: '-',
    },
    {
      label: '高风险',
      value: '-',
    },
  ]);

  const wrappedGetMineData = (params) => {
    // 调用原接口
    return Promise.all([getAlarmTotalData(params), getProvinceAlarm(params)]).then(([__, res]) => res);
  };

  // 注册实时数据表格
  const { tableContext: ctxRealtime, onExportXls: onExportXlsTime } = useListPage({
    tableProps: {
      immediate: false,
      columns,
      api: wrappedGetMineData,
      formConfig: {
        autoSearch: true,
        labelWidth: 120,
        schemas: [
          {
            label: '煤矿名称',
            field: 'deptId',
            component: 'MineCascader', // 自定义组件名
            colProps: { span: 6 },
            rules: [],
          },
        ],
        showAdvancedButton: false,
        schemaGroupNames: ['常规查询'],
      },
      pagination: true,
      striped: true,
      useSearchForm: true,
      bordered: true,
      showIndexColumn: false,
      actionColumn: {
        width: 80,
        title: '详情',
        dataIndex: 'action',
        slots: { customRender: 'action' },
        fixed: undefined,
      },
    },
    exportConfig: {
      url: '/ventanaly-province/province/alarm/exportProvinceAlarmReal',
      name: '密闭爆炸危险性判定',
      params: {
        alarmType: 'explosionAlarm',
      },
    },
  });
  const [registerRealtimeTable] = ctxRealtime;

  // 注册历史数据表格
  const { tableContext, onExportXls } = useListPage({
    tableProps: {
      immediate: false,
      columns,
      // columns: historyColumns,
      api: async (params) => {
        await initGoafOptions(params.deptId);
        if (!goafId.value) {
          return Promise.resolve([]);
        }
        params.goafId = goafId.value;
        return getProvinceAlarmHistory(params);
      },
      formConfig: {
        autoSearch: true,
        model: { deptId: hiscode },
        labelWidth: 120,
        schemas: [
          // {
          //   label: '开始时间',
          //   field: 'startTime',
          //   component: 'DatePicker',
          //   defaultValue: dayjs().add(-30, 'day').format('YYYY-MM-DD HH:mm:ss'),
          //   componentProps: {
          //     showTime: true,
          //     placeholder: '请选择开始时间',
          //     valueFormat: 'YYYY-MM-DD HH:mm:ss',
          //   },
          //   colProps: { span: 6 },
          //   rules: [{ required: true, message: '请选择开始时间' }],
          // },
          // {
          //   label: '结束时间',
          //   field: 'endTime',
          //   component: 'DatePicker',
          //   defaultValue: dayjs(),
          //   componentProps: {
          //     showTime: true,
          //     placeholder: '请选择结束时间',
          //     valueFormat: 'YYYY-MM-DD HH:mm:ss',
          //   },
          //   colProps: { span: 6 },
          //   rules: [{ required: true, message: '请选择结束时间' }],
          // },
          {
            label: '煤矿名称',
            field: 'deptId',
            component: 'MineCascader', // 自定义组件名
            componentProps: {
              initFromStore: false,
              syncToStore: false,
              changeOnSelect: false,
              // onChange: (e) => {
              //   historyTable.setLoading(true);
              //   initGoafOptions(e).finally(() => {
              //     historyTable.setLoading(false);
              //   });
              // },
            },
            colProps: { span: 6 },
            rules: [],
          },
          ...historicalFormSchema,
        ],
        showAdvancedButton: false,
        schemaGroupNames: ['常规查询'],
      },
      pagination: true,
      striped: true,
      useSearchForm: true,
      bordered: true,
      showIndexColumn: true,
      // showActionColumn: false,
    },
    exportConfig: {
      url: '/province/alarm/exportProvinceAlarmHistory',
      name: '历史数据',
      params: {
        alarmType: 'explosionAlarm',
        goafId,
      },
    },
  });

  const [registerHistoryTable, historyTable] = tableContext;

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

  // 打开弹窗方法（区分实时/历史）
  const openModal = (record) => {
    openRealtimeModal(true, record);
    // pause();
  };

  async function getAlarmTotalData(p) {
    const params = {
      ...p,
      alarmType: 'explosionAlarm',
    };
    const result = await getProvinceAlarmNum(params);
    boardData.value[1].value = result.alarmLevel1;
    boardData.value[2].value = result.alarmLevel2;
    boardData.value[3].value = result.alarmLevel3;
    boardData.value[4].value = result.alarmLevel4;
    boardData.value[0].value = result.alarmLevel1 + result.alarmLevel2 + result.alarmLevel3 + result.alarmLevel4;
  }

  /**
   * 通用页面跳转方法
   * @param record 当前行数据
   * @param path 目标路径
   */
  function handleGoToPageQuery(record: any, path: string) {
    advancedRoutePush({
      path,
      query: { deptId: record.deptId, goafId: record.goafId, filter: 'coVal,ch4Val,c2h2Val,c2h4Val,o2Val' },
    });
  }

  // const { pause, resume } = useIntervalFn(() => reload({ silence: true }), 60000);
</script>

<style lang="less" scoped>
  @import url(../../common/board.less);
</style>
