import { defineStore } from 'pinia';
import type { VimpChannel, VimpStation } from '../apis';
import { h, ref } from 'vue';
import type { AlarmAreaNodeOption, AlarmNodeOption, CodeArea, CodeLines, CodeSites, AlarmLineTabPane, AlarmSiteNodeOption, AlarmSubAreaNodeOption } from '../types';

interface BuildLineTabPanesParams {
  sites: VimpStation[] | null;
  siteAlarmsMap: Record<string, VimpChannel[]>;
  codeLines: CodeLines;
  codeSites: CodeSites;
  codeStationAreas: CodeArea[];
  codeParkingAreas: CodeArea[];
  codeOccAreas: CodeArea[];
  codeTrainAreas: CodeArea[];
}

export const useAlarmStore = defineStore('vimp-alarm', () => {
  const lineTabPanes = ref<AlarmLineTabPane[]>([]);

  const buildLineTabPanes = (params: BuildLineTabPanesParams) => {
    const { sites, siteAlarmsMap, codeLines, codeSites, codeStationAreas, codeParkingAreas, codeOccAreas, codeTrainAreas } = params;
    if (!sites) {
      lineTabPanes.value = [];
      return;
    }
    // 构造线路TabPane
    const _lineTabPanes: AlarmLineTabPane[] = [];
    const lineCode = sites.at(0)?.code.substring(0, 3) ?? '';
    const lineName = codeLines[lineCode]?.name ?? '';
    if (!_lineTabPanes.some((lineNode) => lineNode.lineCode === lineCode)) {
      _lineTabPanes.push({
        lineCode,
        lineName,
        alarmTree: [],
      });
    }

    // 遍历所有站点
    for (const site of sites) {
      const siteCode = site.code.substring(0, 6);
      const siteName = codeSites[siteCode]?.name;
      if (!siteName) continue;

      // 构造站点节点
      const siteNode: AlarmSiteNodeOption = {
        key: siteCode,
        label: siteName,
        children: [],
        stats: { online: 0, offline: 0, total: 0 },
        online: site.online,
      };
      _lineTabPanes.find((lineTabPane) => lineTabPane.lineCode === lineCode)?.alarmTree.push(siteNode);

      // 获取所有警报器
      const alarms = siteAlarmsMap[site.code];
      if (!alarms || alarms.length === 0) continue;

      // 遍历警报器
      for (const alarm of alarms) {
        // 计算相关编码
        const { code: alarmGbCode, name: alarmName } = alarm;
        const alarmSiteCode = alarmGbCode.substring(0, 6);
        const alarmSiteType = codeSites[alarmSiteCode]?.type;
        const alarmAreaCode = alarmGbCode.substring(6, 11);
        const alarmMainAreaCode = alarmAreaCode.slice(0, 2);

        // 构造车站/基地/OCC/车次区域
        let siteArea: CodeArea | undefined = undefined;
        if (alarmSiteType === 'station') {
          siteArea = codeStationAreas.find((area) => area.code === alarmMainAreaCode);
        } else if (alarmSiteType === 'parking') {
          siteArea = codeParkingAreas.find((area) => area.code === alarmMainAreaCode);
        } else if (alarmSiteType === 'occ') {
          siteArea = codeOccAreas.find((area) => area.code === alarmMainAreaCode);
        } else if (alarmSiteType === 'train') {
          siteArea = codeTrainAreas.find((area) => area.code === alarmMainAreaCode);
        } else {
          continue;
        }
        if (!siteArea) continue; // 如果还是未找到区域，则跳过该警报器

        // 构造区域节点
        if (!siteNode.children?.find((areaNode) => areaNode.key === `${alarmSiteCode}${alarmMainAreaCode}`)) {
          const areaNode: AlarmAreaNodeOption = {
            key: `${alarmSiteCode}${alarmMainAreaCode}`,
            label: siteArea.name,
            children: [],
            stats: { online: 0, offline: 0, total: 0 },
            site: site,
          };
          siteNode.children?.push(areaNode);
        }
        const areaNode = siteNode.children?.find((areaNode) => areaNode.key === `${alarmSiteCode}${alarmMainAreaCode}`);
        if (!areaNode) continue; // 如果区域节点不存在，则跳过该警报器

        // 构造子区域节点
        if (!areaNode.children?.find((subAreaNode) => subAreaNode.key === `${alarmSiteCode}${alarmAreaCode}`)) {
          let subArea: CodeArea['subs'][number] | undefined = undefined;
          if (alarmSiteType === 'station') {
            subArea = codeStationAreas.find((area) => area.code === alarmMainAreaCode)?.subs.find((subArea) => subArea.code === alarmAreaCode);
          } else if (alarmSiteType === 'parking') {
            subArea = codeParkingAreas.find((area) => area.code === alarmMainAreaCode)?.subs.find((subArea) => subArea.code === alarmAreaCode);
          } else if (alarmSiteType === 'occ') {
            subArea = codeOccAreas.find((area) => area.code === alarmMainAreaCode)?.subs.find((subArea) => subArea.code === alarmAreaCode);
          } else if (alarmSiteType === 'train') {
            subArea = codeTrainAreas.find((area) => area.code === alarmMainAreaCode)?.subs.find((subArea) => subArea.code === alarmAreaCode);
          } else {
            continue;
          }
          if (!subArea) continue; // 如果还是未找到子区域，则跳过该警报器

          const subAreaNode: AlarmSubAreaNodeOption = {
            key: `${alarmSiteCode}${alarmAreaCode}`,
            label: subArea.name,
            children: [],
            stats: { online: 0, offline: 0, total: 0 },
            site: site,
          };
          areaNode.children?.push(subAreaNode);
        }
        const subAreaNode = areaNode.children?.find((subAreaNode) => subAreaNode.key === `${alarmSiteCode}${alarmAreaCode}`);
        if (!subAreaNode) continue; // 如果子区域节点不存在，则跳过该警报器

        // 构造警报器节点
        const alarmType = alarm.code.substring(11, 14);
        const alarmNode: AlarmNodeOption = {
          key: alarmGbCode,
          label: alarmName,
          type: alarmType,
          alarm: alarm,
          site: site,
          prefix: () => {
            return `[警报器]`;
          },
        };

        // 添加警报器节点到子区域节点
        if (!subAreaNode.children?.find((alarmNode) => alarmNode.key === alarmGbCode)) {
          subAreaNode.children?.push(alarmNode);
        }

        // 统计站点、区域、子区域的在线/离线/总警报器数量
        siteNode.stats.total++;
        areaNode.stats.total++;
        subAreaNode.stats.total++;
        if (alarm.status === 1) {
          siteNode.stats.online++;
          areaNode.stats.online++;
          subAreaNode.stats.online++;
        }
        if (alarm.status === 0) {
          siteNode.stats.offline++;
          areaNode.stats.offline++;
          subAreaNode.stats.offline++;
        }
      }
      siteNode.suffix = () => {
        const { online, offline, total } = siteNode.stats;
        return `(${online}/${offline}/${total})`;
      };
      siteNode.children?.forEach((areaNode) => {
        areaNode.suffix = () => {
          const { online, offline, total } = areaNode.stats;
          return h('div', { style: { marginRight: '8px', opacity: 0.6 } }, `(${online}/${offline}/${total})`);
        };
        areaNode.children?.forEach((subAreaNode) => {
          subAreaNode.suffix = () => {
            const { online, offline, total } = subAreaNode.stats;
            return h('div', { style: { marginRight: '16px', opacity: 0.4 } }, `(${online}/${offline}/${total})`);
          };
        });
      });
    }
    lineTabPanes.value = _lineTabPanes;
  };

  return {
    lineTabPanes,
    buildLineTabPanes,
  };
});
