<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="company-home">
    <!-- 顶部标题样式块 -->
    <div class="top-bg">
      <div class="main-title">{{ mainTitle }}</div>
    </div>
    <!-- 中间样式块 -->
    <div class="center-info-bar">
      <div class="left-info-content">
        <div class="left-block block1">
          <div class="info-value">{{ fireSgWarnInfo.sgCoTbAlarmAddress }}</div>
          <div class="info-label">突变预警</div>
        </div>
        <div class="left-block block2">
          <div class="info-value">{{ fireSgWarnInfo.nyAlarmLevelStr }}</div>
          <div class="info-label">煤自燃氧化阶段</div>
        </div>
        <div class="left-block block3">
          <div class="info-value">{{ fireSgWarnInfo.sgMaxTemp }}</div>
          <div class="info-label">最高温度</div>
        </div>
      </div>
      <div class="center-info-content">
        <div class="info-value">{{ fireSgWarnInfo.aqfxLevelStr }}</div>
        <div class="info-label">火灾安全等级</div>
      </div>
      <div class="right-info-content">
        <div class="right-block block1">
          <div class="info-value">{{ fireSgWarnInfo.sgZbAlarmNum }}</div>
          <div class="info-label">指标预警</div>
        </div>
        <div class="right-block block2">
          <div class="info-value">{{ fireSgWarnInfo.yjjbLevelStr }}</div>
          <div class="info-label">预警等级</div>
        </div>
        <div class="right-block block3">
          <div class="info-value">{{ fireSgWarnInfo.sgSwAlarmAddress }}</div>
          <div class="info-label">升温预警</div>
        </div>
      </div>
    </div>
    <!-- 渲染所有模块 -->
    <ModuleCommon
      v-for="cfg in cfgs"
      :key="cfg.deviceType + cfg.moduleName"
      :show-style="cfg.showStyle"
      :module-data="cfg.moduleData"
      :module-name="cfg.moduleName"
      :device-type="cfg.deviceType"
      :data="data"
      :visible="true"
    />
    <ModuleCommonDual
      v-if="cfgA && cfgB"
      :show-style="cfgA.showStyle"
      :module-data-a="cfgA.moduleData"
      :module-name-a="cfgA.moduleName"
      :device-type-a="cfgA.deviceType"
      :module-data-b="cfgB.moduleData"
      :module-name-b="cfgB.moduleName"
      :device-type-b="cfgB.deviceType"
      :module-data-c="cfgC.moduleData"
      :module-name-c="cfgC.moduleName"
      :device-type-c="cfgC.deviceType"
      :data="data"
      :visible="true"
      :common-title="commonTitle"
    />
    <!-- 运维反应首页卡顿先行注释掉，后续再调整 -->
    <!-- <Three3D :modal-name="modalName" /> -->
  </div>
</template>
<script lang="ts" setup>
  import { computed, onMounted, onUnmounted, ref } from 'vue';
  import { useInitConfigs, useInitPage } from './hooks/useInit';
  import { getAlarmRecord, getDeviceSys } from './configurable.api';
  import { testConfigTSFire } from './configurable.data.tashan';
  import ModuleCommon from './components/ModuleCommon.vue';
  import ModuleCommonDual from './components/ModuleCommonDual.vue';
  // import Three3D from './components/three3D.vue';

  // const modalName = ref('workFace11');
  const cfgs = computed(() => configs.value.filter((_, index) => index !== 6 && index !== 7 && index !== 8));
  const cfgA = computed<any>(() => configs.value[6]);
  const cfgB = computed<any>(() => configs.value[7]);
  const cfgC = computed<any>(() => configs.value[8]);
  const { configs, fetchConfigs } = useInitConfigs();
  const { mainTitle, data, updateData } = useInitPage('回采工作面智能管控');
  let interval: ReturnType<typeof setInterval> | undefined;
  const commonTitle = '实时监测与预警';
  const fireSgWarnInfo = ref({
    aqfxLevelStr: '-',
    nyAlarmLevel: 0,
    nyAlarmLevelStr: '-',
    sgCoTbAlarmAddress: '-',
    sgMaxTemp: '-',
    sgSwAlarmAddress: '-',
    sgZbAlarmNum: 0,
    yjjbLevelStr: '-',
  });
  onMounted(() => {
    let alarmLogData = [];
    fetchConfigs('ts_fire').then(() => {
      configs.value = testConfigTSFire;
      getDeviceSys({
        devicetype: 'sys',
        type: 'all',
      }).then((res) => {
        const processedRes = handleData(res);
        getAlarmRecord({
          sysId: '1955807282207465474',
          devicekind: 'bundletube',
          pageNo: '1',
          pageSize: '10',
        }).then((res) => {
          alarmLogData = res.records || [];
          processedRes.alarmLog = alarmLogData;
          updateData(processedRes);
        });
      });
    });
    interval = setInterval(() => {
      getDeviceSys({
        devicetype: 'sys',
        type: 'all',
      }).then((res) => {
        const processedRes = handleData(res);
        processedRes.alarmLog = alarmLogData;
        updateData(processedRes);
      });
    }, 2000);
  });

  const handleData = (res: any) => {
    const processedData = { ...res };
    fireSgWarnInfo.value = res?.fireSgWarnInfo || {};
    // 处理束管数据，分类进风、回风
    if (processedData.deviceInfo?.bundletube) {
      const { datalist = [] } = processedData.deviceInfo.bundletube;
      processedData.deviceInfo.bundletube = {
        ...processedData.deviceInfo.bundletube,
        enterWind: datalist.filter((item) => item.strRemark === 'enterWind'),
        returnWind: datalist.filter((item) => item.strRemark === 'returnWind'),
      };
    }
    // 处理光纤测温数据
    if (processedData.deviceInfo?.fiber?.datalist) {
      processedData.deviceInfo.fiber.datalist.forEach((item) => {
        const tempData = item.readData.fibreTemperature;
        if (typeof tempData === 'string') {
          try {
            item.readData.fibreTemperature = JSON.parse(tempData || '[]');
          } catch (e) {
            // 解析失败时的容错处理
            console.error('解析JSON失败:', e);
            item.readData.fibreTemperature = []; // 给个默认值
          }
        }
      });
    }
    // 处理束管数据
    if (processedData.deviceInfo?.bundletube?.datalist) {
      // 每次处理前先清空chartData，避免数据累积
      chartData.value = [];
      const bundletubeDataList = processedData.deviceInfo.bundletube.datalist;
      // 处理selectorConfig1：遍历datalist，提取deviceID和strinstallpos
      selectorConfig1 = {
        options: bundletubeDataList.map((device) => ({
          value: device.deviceID, // 选项值：设备唯一ID
          label: device.strinstallpos, // 选项标签：设备
        })),
      };
      const targetIndicators: Array<keyof Pick<BundletubeHistoryItem, 'ch2val' | 'chval' | 'co2val' | 'coval' | 'gasval' | 'o2val'>> = [
        'ch2val',
        'chval',
        'co2val',
        'coval',
        'gasval',
        'o2val',
      ];

      // 遍历datalist（每个item对应一个设备安装位置）
      bundletubeDataList.forEach((deviceItem) => {
        const deviceID = deviceItem.deviceID; // 设备ID
        const deviceHistory = deviceItem.history; // 当前设备的history数组

        // 跳过history为空的情况
        if (!deviceHistory || !Array.isArray(deviceHistory)) return;

        //  遍历每个指标，生成对应的chartData项
        targetIndicators.forEach((indicator) => {
          // 收集当前指标的seriesData（时间+数值）
          const seriesData: SeriesDataItem[] = deviceHistory
            .map((historyItem: BundletubeHistoryItem) => ({
              time: historyItem.time,
              value: historyItem[indicator], // 匹配当前指标的数值
            }))
            .filter((item) => item.time); // 过滤掉无时间的无效数据

          // 推送到最终chartData
          chartData.value.push({
            deviceID,
            sensorId: indicator,
            seriesData,
          });
        });
      });
      processedData.deviceInfo.bundletube.chartConfig = {
        selectorConfig1: selectorConfig1,
        selectorConfig2: selectorConfig2,
        chartData: chartData,
      };
    }
    return processedData;
  };
  interface BundletubeHistoryItem {
    time: string; // 时间戳（如"2025-08-23 07:56:35"）
    ch2val: string | number; // 甲烷2值
    chval: string | number; // 甲烷值
    co2val: string | number; // 二氧化碳值
    coval: string | number; // 一氧化碳值
    gasval: string | number; // 瓦斯值
    o2val: string | number; // 氧气值
  }
  // 定义chartData中seriesData的单个元素类型
  interface SeriesDataItem {
    time: string;
    value: string | number; // 对应指标的数值
  }
  interface ChartDataItem {
    deviceID: string; // 设备id
    sensorId: 'ch2val' | 'chval' | 'co2val' | 'coval' | 'gasval' | 'o2val'; // 指标ID（固定6个）
    seriesData: SeriesDataItem[]; // 时间+数值数组
  }
  // 处理selectorConfig1：遍历datalist，提取deviceID和strinstallpos
  let selectorConfig1 = {
    options: [
      {
        value: '', // 选项值：设备唯一Id
        label: '', // 设备名
      },
    ],
  };
  // 处理selectorConfig2：固定6个指标ID及对应中文标签
  const selectorConfig2 = {
    options: [
      { value: 'o2val', label: '氧气' },
      { value: 'coval', label: '一氧化碳' },
      { value: 'co2val', label: '二氧化碳' },
      { value: 'chval', label: '甲烷' },
      { value: 'ch2val', label: '乙烷' },
      { value: 'gasval', label: '瓦斯' },
    ],
  };
  // 最终生成的图表数据
  const chartData = ref<ChartDataItem[]>([]);
  // 数据处理函数
  onUnmounted(() => {
    clearInterval(interval);
  });
</script>
<style lang="less" scoped>
  @import '/@/design/theme.less';

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

  .company-home {
    --image-fire-title: url(/@/assets/images/vent/vent-header1.png);
    --image-common-border1: url('/@/assets/images/home-container/configurable/minehome/common-border1.png');
    --image-common-border3: url('/@/assets/images/home-container/configurable/minehome/common-border3.png');
    width: 100%;
    height: 100%;
    color: @white;
    position: relative;
    background: #09172c;

    .top-bg {
      width: 100%;
      height: 73px;
      background: var(--image-fire-title) no-repeat top;
      position: absolute;
      z-index: 1;
      .main-title {
        height: 80px;
        font-family: 'douyuFont';
        font-size: 26px;
        letter-spacing: 2px;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 0 0 10px 0;
      }
    }
    // 顶部中间样式块
    .center-info-bar {
      position: relative;
      top: 75px;
      left: 50%;
      transform: translateX(-50%);
      width: 900px;
      height: 160px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: url('@/assets/images/home-container/configurable/tashanhome/center-bar-bg.png') no-repeat center;
      z-index: 1;
      .center-info-content {
        position: relative;
        top: 15px;
        background: url('@/assets/images/home-container/configurable/tashanhome/center-bar-circle.png') no-repeat center;
        width: 160px;
        height: 160px;
        text-align: center;
        .info-value {
          position: absolute;
          top: 34%;
          left: 50%;
          transform: translateX(-50%);
          font-family: 'douyuFont';
          font-size: 25px;
          color: #2cffdd;
        }
        .info-label {
          width: 100%;
          position: absolute;
          bottom: 25px;
          font-size: 17px;
          left: 50%;
          transform: translateX(-50%);
        }
      }
      .left-info-content {
        position: relative;
        text-align: right;
        .left-block {
          position: absolute;
          width: 190px;
          height: 55px;
          background: url('@/assets/images/home-container/configurable/tashanhome/leftbar-bg1.png') no-repeat right;
          padding-right: 52px;
          .info-value {
            height: 28px;
            line-height: 28px;
            font-family: 'douyuFont';
            font-size: 12px;
            color: var(--vent-gas-primary-text);
          }
          .info-label {
            height: 28px;
            line-height: 28px;
          }
        }
        .block1 {
          top: -70px;
          right: -5px;
        }
        .block2 {
          top: -15px;
          left: -280px;
          background: url('@/assets/images/home-container/configurable/tashanhome/leftbar-bg2.png') no-repeat right;
          .info-value {
            color: #2cffdd;
          }
        }
        .block3 {
          top: 40px;
          right: -5px;
        }
      }
      .right-info-content {
        position: relative;
        .right-block {
          position: absolute;
          width: 190px;
          height: 55px;
          background: url('@/assets/images/home-container/configurable/tashanhome/rightbar-bg1.png') no-repeat left;
          padding-left: 52px;
          .info-value {
            height: 28px;
            line-height: 28px;
            font-family: 'douyuFont';
            font-size: 12px;
            color: var(--vent-gas-primary-text);
          }
          .info-label {
            height: 28px;
            line-height: 28px;
          }
        }
        .block1 {
          top: -70px;
          left: -5px;
        }
        .block2 {
          top: -15px;
          right: -280px;
          background: url('@/assets/images/home-container/configurable/tashanhome/rightbar-bg2.png') no-repeat left;
          .info-value {
            color: #2cffdd;
          }
        }
        .block3 {
          top: 40px;
          left: -5px;
        }
      }
    }

    ::v-deep .dane-bd {
      background-repeat: no-repeat;
      background-position: center;
      background-size: 100% 100%;
      &.dane-w {
        background-image: var(--image-common-border3);
      }
      .dane-title {
        justify-content: space-around;
        padding: 0 50px 0 0;

        .common-navL {
          font-size: 14px;
          font-weight: bold;
          font-family: 'douyuFont';
        }
      }
      .dane-content {
        border: none;
        background: none;
        padding: 10px 35px;
      }
    }
    ::v-deep .table__content .table__content_list {
      width: 95%;
    }
    ::v-deep .table__content .table__content_label {
      width: 95%;
    }
  }
</style>
