<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="company-home">
    <SystemSelect
      :class="{
        'custom-system-select': true,
        'custom-system-select-mine': appStore.getSimpleMapParams.isLeaf,
      }"
    />

    <template v-if="appStore.getSimpleMapParams.isLeaf">
      <div class="company-title">
        <div class="company-title-content">
          <span class="title-text">
            {{ departName }}
          </span>
        </div>
      </div>
    </template>
    <template v-else>
      <div class="button-border"></div>
    </template>
    <!-- 渲染所有模块 -->
    <ModulePrimary
      v-for="cfg in cfgs"
      :key="cfg.deviceType"
      :show-style="cfg.showStyle"
      :module-data="cfg.moduleData"
      :module-name="cfg.moduleName"
      :device-type="cfg.deviceType"
      :data="data"
      :visible="true"
    />
  </div>
</template>
<script lang="ts" setup>
  import { computed, onUnmounted, ref, watch, shallowRef } from 'vue';
  import { useInitConfigs, useInitPage } from '@/components/Configurable/hooks/useInit';
  import { testConfigSealedGoaf, testConfigSealedMine } from './configurable.data.sealedGoaf';
  import {
    getCoalSeamFireNum,
    getMineProductionStatusNum,
    getOverLimitNum,
    getGoafAlarmNum,
    getGoafAccessCount,
    getGoafData,
    getGoafStatusNum,
    getProvinceAlarm,
  } from './sealedGoaf.api';
  import ModulePrimary from '/@/components/Configurable/ModulePrimary.vue';
  import { useGlobSetting } from '/@/hooks/setting';
  import { useAppStore } from '/@/store/modules/app';
  import { useMineDepartmentStore } from '/@/store/modules/mine';
  import SystemSelect from '/@/layouts/default/feature/SystemSelect.vue';
  import { DEFAULT_DISPLAY_MAP, DEFAULT_OPERAND_SET, evaluateExpressionLite } from '../../system/algorithm/utils';
  import { map } from 'lodash-es';

  const { title = '老空区永久密闭监测与分析系统' } = useGlobSetting();
  const { data, updateData } = useInitPage(title);
  const appStore = useAppStore();
  const mineStore = useMineDepartmentStore();
  const departName = ref('');

  const cfgs = computed(() => configs.value);
  const { configs } = useInitConfigs();
  const mineData = shallowRef({
    coalSeamFireData: null,
    productionStatusData: null,
    overLimitData: null,
    goafAlarmData: null,
    // goafAlarmLevel: null,
    totalNum: {
      productionNum: 0, // 原有生产状态总计
      alarmNum: {
        alarm1Total: 0, // alarm1 总计
        alarm2Total: 0, // alarm2 总计
        alarm3Total: 0, // alarm3 总计
        alarm4Total: 0, // alarm4 总计
        alarmTotal: 0, // 所有alarm总计
      },
    },
    goafAccessCount: {
      accessDetails: null,
      totalNum: {
        yjTotal: 0, // 应接入总计
        zxTotal: 0, // 在线总计
        lxTotal: 0, // 离线总计
        wjTotal: 0, // 未接入总计
      },
    },
  }); // 所有数据汇总

  const goafData = ref({
    monitorData: null,
    transCoalSeamFireData: null as any[] | null,
    coalSeamFireData: null,
    goafStatusNum: null,
    goafAlarmNum: null,
    provinceAlarm: null,
  });

  async function fetchHomeData() {
    try {
      // 2. 异步获取所有接口数据（并行请求提升性能）
      const [coalSeamFireData, productionStatusData, overLimitData, goafAlarmData, accessDetails] = await Promise.all([
        getCoalSeamFireNum(appStore.simpleMapParams).then((r) => {
          return map(r, (val, key) => {
            return {
              coalSeamLevel: `${key}：${val}`,
              num: val,
            };
          }) as any;
        }), // 煤层自燃倾向数据
        getMineProductionStatusNum(appStore.simpleMapParams), // 当日生产状态数据
        getOverLimitNum(appStore.simpleMapParams), // 超限数据（可按需处理）
        getGoafAlarmNum(appStore.simpleMapParams), // 执法处风险统计
        getGoafAccessCount(appStore.simpleMapParams),

        // getGoafAlarmLevel(appStore.simpleMapParams),
        // getGoafAlarmLevel({ mineCode: '100008' }),
      ]);

      const totalProductionNum = Array.isArray(productionStatusData) ? productionStatusData.reduce((sum, item) => sum + (item.num || 0), 0) : 0;
      productionStatusData.push({
        num: [1, 7, 2, 0, 6, 8, 9].reduce((total, index) => total + productionStatusData[index].num, 0),
        name: '停产停建',
      });
      productionStatusData.push({
        num: [10, 11, 12].reduce((total, index) => total + productionStatusData[index].num, 0),
        name: '长期停产停建',
      });

      let alarm1Total = 0;
      let alarm2Total = 0;
      let alarm3Total = 0;
      let alarm4Total = 0;

      // 遍历数组累加（边界处理：确保是数组，字段非数字则取0）
      if (Array.isArray(goafAlarmData)) {
        goafAlarmData.forEach((item) => {
          alarm1Total += Number(item.alarm1) || 0;
          alarm2Total += Number(item.alarm2) || 0;
          alarm3Total += Number(item.alarm3) || 0;
          alarm4Total += Number(item.alarm4) || 0;
        });
      }

      // 计算所有alarm的总合计
      const alarmTotal = alarm1Total + alarm2Total + alarm3Total + alarm4Total;
      // console.log('所有alarm的总合计：', alarmTotal);
      const totalNum = { productionNum: totalProductionNum, alarmNum: { alarm1Total, alarm2Total, alarm3Total, alarm4Total, alarmTotal } };

      // 联网状态模块数据处理：遍历 accessDetails 数组，累加所有项的 yjNum、zxNum、lxNum、wjNum
      let yjTotal = 0;
      let zxTotal = 0;
      let lxTotal = 0;
      let wjTotal = 0;
      let zdTotal = 0;

      if (Array.isArray(accessDetails)) {
        accessDetails.forEach((item) => {
          yjTotal += Number(item.yjNum) || 0;
          zxTotal += Number(item.zxNum) || 0;
          lxTotal += Number(item.lxNum) || 0;
          wjTotal += Number(item.wjNum) || 0;
          zdTotal += Number(item.zdNum) || 0;
        });
      }
      const goafAccessCount = {
        accessDetails,
        totalNum: { yjTotal, zxTotal, lxTotal, wjTotal, zdTotal },
      };

      // const coalSeamFireChartData = ['Ⅰ类容易自燃', 'Ⅱ类自燃', 'Ⅲ类不易自燃'].reduce(
      //   (val: any, key) => {
      //     const arr = coalSeamFireData[key];
      //     val.coalSeamLevel.push(key);
      //     val.num.push(arr.length);
      //     val.desc.push(arr.map((e) => `${e.mineName}-${e.coalSeamName}`).join('、'));
      //     // return { coalSeamLevel: key, num: arr?.length, desc:  };
      //     return val;
      //   },
      //   { coalSeamLevel: [], num: [], desc: [] }
      // );
      // console.log('debug coal', coalSeamFireChartData);

      // 3. 把接口数据赋值给响应式变量（备用）
      mineData.value = {
        coalSeamFireData,
        productionStatusData,
        overLimitData,
        goafAlarmData,
        totalNum,
        goafAccessCount,
      };
      // 5. 更新页面数据
      updateData(mineData.value);
    } catch (error) {
      console.error('数据获取/配置更新失败：', error);
    }
  }

  async function fetchLeafData() {
    try {
      // 异步获取所有接口数据（并行请求提升性能）
      const [monitorData, coalSeamFireData, goafStatusNum, goafAlarmNum, provinceAlarm] = await Promise.all([
        getGoafData(appStore.simpleMapParams), // 密闭监测详情
        getCoalSeamFireNum(appStore.simpleMapParams), // 煤层自燃倾向数据
        getGoafStatusNum(appStore.simpleMapParams), // 密闭统计
        getGoafAlarmNum(appStore.simpleMapParams), // 预警统计
        getProvinceAlarm(appStore.simpleMapParams), // 预警信息列表
      ]);

      if (monitorData?.records) {
        monitorData.records.forEach((record) => {
          const { coalSeamAlarmRule, sourcePressureAlarm, fireAlarm, fireAlarmReson, fireAlarmOut, fireAlarmOutReson } = record;
          record.sourcePressureReason = evaluateExpressionLite(
            coalSeamAlarmRule[`ycWarn${sourcePressureAlarm.alarmLevel}`],
            ['sourcePressureChange'],
            DEFAULT_OPERAND_SET,
            DEFAULT_DISPLAY_MAP
          ).join('；');

          record.fireAlarmReason = evaluateExpressionLite(
            coalSeamAlarmRule[`fireWarn${fireAlarm.alarmLevel}`],
            fireAlarmReson,
            DEFAULT_OPERAND_SET,
            DEFAULT_DISPLAY_MAP
          ).join('；');

          record.fireAlarmOutReason = evaluateExpressionLite(
            coalSeamAlarmRule[`fireOutWarn${fireAlarmOut.alarmLevel}`],
            fireAlarmOutReson,
            DEFAULT_OPERAND_SET,
            DEFAULT_DISPLAY_MAP
          ).join('；');
        });
      }

      if (provinceAlarm?.records) {
        const alarmTypeMap = {
          leakageAlarm: '老空区永久密闭漏风状态报警',
          sourcePressureAlarm: '内外压差风险报警',
          fireAlarm: '自燃发火隐患报警',
          fireAlarmOut: '老空区永久密闭墙外自燃发火报警',
          unsealAlarm: '火区老空区永久密闭启封报警',
          explosionAlarm: '老空区永久密闭爆炸危险性报警',
          overLimitAlarm: '超限报警',
          lateReport: '数据延迟上报预警',
        };

        // 遍历列表，把 alarmType 替换成中文
        provinceAlarm.records = provinceAlarm.records.map((item) => {
          item.alarmTypeCont = alarmTypeMap[item.alarmType] || item.alarmType;
          return item;
        });
      }
      // 遍历煤层自燃倾向性，数据重组
      let transCoalSeamFireData: any[] = [];
      if (coalSeamFireData) {
        transCoalSeamFireData = Object.values(coalSeamFireData).flat();
      }

      // 把接口数据赋值给响应式变量（备用）
      goafData.value = { monitorData, coalSeamFireData, transCoalSeamFireData, goafStatusNum, goafAlarmNum, provinceAlarm };
      // 更新页面数据
      updateData(goafData.value);
    } catch (error) {
      console.error('数据获取/配置更新失败：', error);
    }
  }

  watch(
    () => appStore.getSimpleMapParams,
    (params) => {
      if (params.isLeaf) {
        fetchLeafData();
        configs.value = testConfigSealedMine; // 解构触发响应式更新

        const depart = mineStore.findDepartById(params.deptId, mineStore.getDepartTree);
        if (depart) {
          departName.value = depart.departName;
          // console.log('自动填充矿区名称:', depart.departName);
        }
      } else {
        fetchHomeData();
        configs.value = testConfigSealedGoaf; // 解构触发响应式更新
      }
    },
    {
      immediate: true,
    }
  );

  // 数据处理函数
  onUnmounted(() => {});
</script>
<style lang="less" scoped>
  @import '/@/design/theme.less';

  @font-face {
    font-family: 'douyuFont';
    src: url('/@/assets/font/douyuFont.otf');
  }

  .company-home {
    position: fixed;
    width: 100%;
    height: 100%;
    color: @white;
    background-image: linear-gradient(90deg, @map-bg 0%, @map-bg 20%, transparent 30%, transparent 70%, @map-bg 80%, @map-bg 100%);
    background-repeat: no-repeat;
    background-size: 100% 100%;
    z-index: @layout-basic-z-index;
    // 允许点击穿透以支持下面的地图进行交互
    pointer-events: none;

    .custom-system-select {
      z-index: @layout-header-fixed-z-index;
      position: absolute;
      top: 25px;
      left: 25px;
      pointer-events: all;
    }
  }
  .custom-system-select-mine {
    top: 70px !important;
  }
  .button-border {
    position: absolute;
    width: 405px;
    height: 60px;
    left: 22px;
    top: 15px;
    border: 2px dashed #0070ff;
    border-radius: 5px;
  }
  .company-title {
    position: absolute;
    width: 405px;
    height: 110px;
    left: 22px;
    top: 15px;
    border: 2px dashed #0070ff;
    border-radius: 5px;
    // padding: 14px 20px;

    .company-title-content {
      width: 100%;
      height: 52px;
      background-image: url(/src/assets/images/sealedGoaf/title-bg.png);
      background-repeat: no-repeat;
      background-size: 100% 100%;
    }

    .title-text {
      display: block;
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      text-align: center;
      line-height: 52px;
    }
  }

  :deep(.ant-select-selection-item) {
    display: flex;
    align-items: center;
  }
</style>
