<!-- 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
          :key="index"
          v-for="(item, index) in boardData"
          type="A"
          :label="item.label"
          :value="item.value"
          layout="label-top"
          class="board-item"
        />
      </div>
      <!-- 实时数据表格 -->
      <BasicTable @register="registerTable" :scroll="{ x: 'max-content' }" :style="{ padding: 0 }">
        <!-- 核心：判断record是否有有效数据，无则显示- -->
        <template #action="{ record }">
          <button @click="openModal(record, 'resolved')" class="resolved-btn" title="已解决">
            <span class="action-text">已解决</span>
          </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="openModal(record, 'history')" class="action-btn">
              <SvgIcon name="details" />
            </button>
          </div>
        </template>
      </BasicTable>
    </TabPane>
  </Tabs>
  <!-- 弹窗组件 -->
  <a-modal
    style="top: 30%; left: 170px"
    v-model:visible="visibleModal"
    :width="450"
    title="实时监测数据"
    @ok="handleOkEdit"
    @cancel="handleCancelEdit"
  >
    <a-table></a-table>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { BasicTable, useTable } from '/@/components/Table';
import { Tabs, TabPane } from 'ant-design-vue';
import MiniBoard from '/@/components/Configurable/detail/MiniBoard.vue';
import { SvgIcon } from '/@/components/Icon';
// 引入模拟数据
import { boardData, columns, searchFormSchema, historicalMinesData } from './sealRiskJudgeAnalysis.data';
import { getMineData, getProvinceAlarm, getGoafData, getProvinceAlarmHistory, getProvinceAlarmNum } from './sealRiskJudge.api';
import dayjs from 'dayjs';
// 激活的Tab页签
const activeTab = ref('realtime');
const visibleModal = ref(false);
//煤矿列表数据
const deviceOptions = ref([]);
const goafOptions = ref([]);
const mineCode = ref('');
const goafId = ref('');
const visibleresolveModal = ref(false);
const resolveValue = ref('');
const boardData = ref([
  {
    label: '采空区数量',
    value: '',
  },
  {
    label: '增减风安全区',
    value: '',
  },
  {
    label: '减风危险区',
    value: '',
  },
  {
    label: '增风危险区',
    value: '',
  },
  {
    label: '爆炸危险区',
    value: '',
  },
]);
const minesData = ref([]);
// 注册实时数据表格
const [registerTable, { reload }] = useTable({
  dataSource: minesData,
  columns,
  api: getProvinceAlarm,
  formConfig: {
    labelWidth: 120,
    schemas: [
      {
        label: '煤矿名称',
        field: 'mineCodeList', // 对应组件的value.mineCode（最终传给Table的查询参数）
        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,
  },
});

// 注册历史数据表格
const [registerHistoryTable] = useTable({
  dataSource: historicalMinesData,
  columns,
  api: getProvinceAlarmHistory,
  formConfig: {
    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: 'mineCode', // 对应组件的value.mineCode（最终传给Table的查询参数）
        defaultValue: deviceOptions.value[0] ? deviceOptions.value[0]['value'] : '',
        component: 'MineCascader', // 自定义组件名
        componentProps: {
          onChange: async (e, option) => {
            mineCode.value = e;
            await getGoafDataList(e);
          },
        },
        colProps: { span: 6 },
        rules: [],
      },
      {
        label: '采空区查询',
        field: 'goafId',
        component: 'Select',
        defaultValue: goafOptions.value[0] ? goafOptions.value[0]['value'] : '',
        componentProps: {
          options: goafOptions,
          onChange: async (e, option) => {
            goafId.value = e;
          },
        },
        colProps: {
          span: 6,
        },
      },
      {
        field: 'alarmFiled',
        label: '预警字段',
        component: 'Select',
        componentProps: {
          options: [
            { label: '甲烷', value: 'ch4Val' },
            { label: '氧气', value: 'o2Val' },
            { label: '一氧化碳', value: 'coVal' },
            { label: '二氧化碳', value: 'co2Val' },
            { label: '乙烯', value: 'c2h4Val' },
            { label: '乙炔', value: 'c2h2Val' },
            { label: '压差', value: 'sourcePressure' },
            { label: '温度', value: 'temperature' },
          ],
        },
        colProps: { span: 6 },
      },
    ],
    showAdvancedButton: false,
    schemaGroupNames: ['常规查询'],
  },
  pagination: true,
  striped: true,
  useSearchForm: true,
  bordered: true,
  showIndexColumn: false,
  // actionColumn: {
  //   width: 60,
  //   title: '操作',
  //   dataIndex: 'action',
  //   slots: { customRender: 'action' },
  //   fixed: undefined,
  // },
});

// 弹窗引用
const realtimeModalRef = ref(null);
const historyModalRef = ref(null);
// 定时器
let timer: IntervalHandle;
const fetchTableData = async () => {
  await reload();
};
// 打开弹窗方法（区分实时/历史）
const openModal = (record, type) => {
  if (type === 'realtime') {
    // 可向实时弹窗传递当前记录数据
    realtimeModalRef.value?.showModal(record);
  } else if (type === 'resolved') {
    visibleresolveModal.value = true;
    record.isResolved = resolveValue.value || '';
  } else if (type === 'detail') {
    visibleModal.value = true;
  } else {
    // 可向历史弹窗传递当前记录数据
    historyModalRef.value?.showModal(record);
  }
};
const handleOkEdit = () => {
  visibleresolveModal.value = false;
};
const handleCancelEdit = () => {
  visibleresolveModal.value = false;
};
async function fetchAlarmData(id) {
  const params = {
    // 填写所需参数
    alarmType: 'leakageAlarm',
    mineId: id,
    pageNo: 1,
    pageSize: 50,
  };
  const result = await getProvinceAlarm(params);
  minesData.value = result.records;
}
const getMineDataList = async () => {
  const params = {
    pageNo: 1,
    pageSize: 50,
  };
  const response = await getMineData(params);
  deviceOptions.value = response.records.map((item, index) => {
    return {
      label: item['mineName'],
      value: item['mineCode'],
    };
  });
};
const getGoafDataList = async (mineId) => {
  const params = {
    mineCode: mineId,
  };
  const response = await getGoafData(params);
  goafOptions.value = response.map((item, index) => {
    return {
      label: item['devicePos'],
      value: item['deviceCode'],
    };
  });
};
async function getAlarmTotalData() {
  const params = {
    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;
}
onMounted(() => {
  // 页面挂载时的逻辑
  getMineDataList();
  getAlarmTotalData();
  timer = setInterval(() => {
    fetchTableData();
  }, 5000);
});
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});
</script>

<style lang="less" scoped>
.board-info {
  display: grid;
  grid-template-columns: repeat(5, auto); /* 3列：改5则为5列 */
  gap: auto;
  justify-content: start;
  flex-wrap: wrap;
  box-sizing: border-box;
  background-color: @white;
  padding: 10px;
  gap: 100px;
  // margin: 0 10px;
  margin-bottom: 5px;
}
.board-item {
  box-sizing: border-box;
}
</style>
