<!-- 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">
        <div :key="index" v-for="(item, index) in boardData" class="board-item">
          <MiniBoard type="A" :label="item.label" :value="item.value" layout="label-top" />
        </div>
      </div>
      <!-- 实时数据表格 -->
      <BasicTable @register="registerTable" :scroll="{ x: 'max-content' }" :style="{ padding: 0 }">
        <template #action="{ record }">
          <!-- 操作按钮 -->
          <!-- <button @click="openModal(record, 'detail')" class="action-btn detail-btn" title="操作">
            <span class="action-text">详情</span>
          </button> -->
          <!-- 已解决按钮 -->
          <button @click="openModal(record, 'resolved')" class="action-btn resolved-btn" title="已解决">
            <span class="action-text">解决</span>
          </button>
        </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="实时监测数据">
    <a-table></a-table>
  </a-modal>
  <!-- 弹窗组件 -->
  <a-modal
    style="height: 400px"
    v-model:visible="visibleresolveModal"
    :width="600"
    centered
    title="密闭漏风处理情况"
    @ok="handleOkEdit"
    @cancel="handleCancelEdit"
  >
    <a-textarea style="width: 90%; margin-left: 20px; margin-right: 20px" v-model:value="resolveValue" placeholder="请输入解决情况" :rows="4" />
  </a-modal>
</template>

<script setup lang="ts">
import { onMounted, ref } 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 {
  getMineData,
  getProvinceAlarm,
  getProvinceAlarmNum,
  getGoafData,
  getProvinceAlarmHistory,
  getEnfMineTreeData,
  resolveAlarm,
} from './airLeak.api';
import formConfig from '/@/components/Form/src/jeecg/components/formCard/formConfig.vue';
import JPopup from '/@/components/Form/src/jeecg/components/JPopup.vue';
// 引入模拟数据
import { columns, historyColumns, searchFormSchema } from './airLeakStatus.data';

// 激活的Tab页签
const activeTab = ref('realtime');
const visibleModal = ref(false);
const visibleresolveModal = ref(false);
const resolveValue = ref('');
const resolveId = ref('');
//煤矿列表数据
const deviceOptions = ref([]);
const goafOptions = ref([]);
const boardData = ref([
  { label: '存在风险情况数量', value: 0 },
  { label: '闭内气体涌出', value: 0 },
  { label: '闭外气体涌出', value: 0 },
]);
const minesData = ref([]);
const mineCode = ref('');
const goafId = ref('');
const alarmFiled = ref('');
const historyData = ref([]);
const lawDeptOptions = ref([]);
// 注册实时数据表格
const [registerTable] = useTable({
  dataSource: minesData,
  title: '密闭漏风状态判定',
  api: getProvinceAlarm,
  columns,
  formConfig: {
    labelWidth: 120,
    schemas: [
      {
        label: '煤矿名称',
        field: 'mineCode', // 对应组件的value.mineCode（最终传给Table的查询参数）
        component: 'MineCascader', // 自定义组件名
        colProps: { span: 6 },
      },
    ],
    showAdvancedButton: false,
    schemaGroupNames: ['常规查询'],
  },
  pagination: true,
  striped: true,
  useSearchForm: true,
  bordered: true,
  showIndexColumn: false,
  actionColumn: {
    width: 120,
    title: '操作',
    dataIndex: 'action',
    slots: { customRender: 'action' },
  },
});

// 注册历史数据表格
const [registerHistoryTable] = useTable({
  dataSource: historyData,
  columns: historyColumns,
  api: getProvinceAlarmHistory,
  formConfig: {
    labelWidth: 120,
    schemas: [
      {
        label: '开始时间',
        field: 'startTime',
        component: 'DatePicker',
        componentProps: {
          showTime: true,
          // valueFormat: 'YYYY-MM-DD HH:mm:ss',
          placeholder: '请选择开始时间',
        },
        colProps: { span: 6 }, // 占比可根据布局调整
        rules: [{ required: true, message: '请选择开始时间' }],
      },
      {
        label: '结束时间',
        field: 'endTime',
        component: 'DatePicker',
        componentProps: {
          showTime: true,
          // valueFormat: 'YYYY-MM-DD HH:mm:ss',
          placeholder: '请选择结束时间',
        },
        colProps: { span: 6 },
        rules: [{ required: true, message: '请选择结束时间' }],
      },
      {
        label: '煤矿名称',
        field: 'mineCode', // 对应组件的value.mineCode（最终传给Table的查询参数）
        component: 'MineCascader', // 自定义组件名
        componentProps: {
          onChange: async (e, option) => {
            mineCode.value = e;
            await getGoafDataList(e);
          },
        },
        colProps: { span: 6 },
        rules: [],
      },
      {
        label: '采空区查询',
        field: 'goafId',
        component: 'Select',
        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);

// 打开弹窗方法（区分实时/历史）
const openModal = (record, type) => {
  if (type === 'realtime') {
    // 可向实时弹窗传递当前记录数据
    realtimeModalRef.value?.showModal(record);
  } else if (type === 'resolved') {
    visibleresolveModal.value = true;
    resolveValue.value = '';
    // record.isResolved = resolveValue.value || '';
    resolveId.value = record.id;
  } else if (type === 'detail') {
    visibleModal.value = true;
  } else {
    // 可向历史弹窗传递当前记录数据
    historyModalRef.value?.showModal(record);
  }
};
async function fetchAlarmData(id) {
  const params = {
    // 填写所需参数
    alarmType: 'leakageAlarm',
    mineId: id,
    pageNo: 1,
    pageSize: 50,
  };
  const result = await getProvinceAlarm(params);
  minesData.value = result.records;
}
async function getAlarmTotalData() {
  const params = {
    alarmType: 'leakageAlarm',
  };
  const result = await getProvinceAlarmNum(params);
  boardData.value[1].value = result.alarmLevel1;
  boardData.value[2].value = result.alarmLevel2;
  boardData.value[0].value = result.alarmLevel1 + result.alarmLevel2;
}
// async function getAlarmHistory() {
//   const result = await getProvinceAlarmHistory();
//   historyData.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 getEnfMineData() {
  const res = await getEnfMineTreeData();
  lawDeptOptions.value = res.map((item) => ({
    label: item.departName,
    value: item.id,
    rawdata: item,
  }));
  // deviceOptions.value = res;
}
// 解决预警
async function handleOkEdit() {
  const params = {
    id: resolveId.value,
    content: resolveValue.value,
  };
  await resolveAlarm(params);
  visibleresolveModal.value = false;
}
const handleCancelEdit = () => {
  visibleresolveModal.value = false;
};
onMounted(() => {
  // 页面挂载时的逻辑
  getMineDataList();
  getEnfMineData();
  getAlarmTotalData();
});
</script>

<style lang="less" scoped>
.board-info {
  display: flex;
  padding: 10px;
  background-color: @white;
  // margin: 0 10px;
  margin-bottom: 5px;
  gap: 10px;
  box-sizing: border-box;
}
.board-item {
  flex: 1;
  box-sizing: border-box;
}
:deep(.jeecg-basic-table-form-container .ant-form) {
  border: none !important;
}
:where(.css-dev-only-do-not-override-x9w3vz).ant-form-item .ant-form-item-label {
  margin-top: 10px !important;
}
</style>
