import { useQuery } from '@tanstack/vue-query';
import { computed } from 'vue';
import { catalogChannelApi, catalogAllDeviceApi } from '../request';
import type { AxiosRequestConfig } from 'axios';
import axios from 'axios';
import type { CodeArea, CodeLines, CodeSites } from '../../types';
import { useCameraStore, useAlarmStore } from '../../stores';
import type { VimpChannel } from '../model';

export const useDeviceCenterQuery = () => {
  const cameraStore = useCameraStore();
  const alarmStore = useAlarmStore();

  return useQuery({
    queryKey: computed(() => ['vimp-device']),
    refetchInterval: 10 * 1000,
    refetchOnWindowFocus: false,
    queryFn: async ({ signal }) => {
      const config: AxiosRequestConfig = {
        headers: {
          'Cache-Control': 'no-store',
        },
      };

      const buildTrainAreas = () => {
        const codeTrainAreas: CodeArea[] = [];
        for (let i = 0; i < 999; i++) {
          const codeTrain = i.toString().padStart(3, '0');
          // 市域线name为车组，改造线name为车次
          const area: CodeArea = { code: codeTrain, name: '车次' + codeTrain, subs: [] };
          for (let j = 0; j <= 99; j++) {
            const codeCarriage = j.toString().padStart(2, '0');
            const subArea: CodeArea['subs'][number] = { code: codeTrain + codeCarriage, name: '车厢' + codeCarriage };
            area.subs.push(subArea);
          }
          // const areaPreserve: CodeArea['subs'][number] = { code: codeTrain + '51', name: '预留' };
          // area.subs.push(areaPreserve);
          codeTrainAreas.push(area);
        }
        return codeTrainAreas;
      };

      const codeLines = (await axios.get<CodeLines>('/cdn/vimp/codes/codeLines.json', config)).data;
      const codeSites = (await axios.get<CodeSites>('/cdn/vimp/codes/codeStations.json', config)).data;
      const codeStationAreas = (await axios.get<CodeArea[]>('/cdn/vimp/codes/codeStationAreas.json', config)).data;
      const codeParkingAreas = (await axios.get<CodeArea[]>('/cdn/vimp/codes/codeParkingAreas.json', config)).data;
      const codeOccAreas = (await axios.get<CodeArea[]>('/cdn/vimp/codes/codeOccAreas.json', config)).data;
      const codeTrainAreas = buildTrainAreas();

      const siteCamerasMap: Record<string, VimpChannel[]> = {};
      const siteAlarmsMap: Record<string, VimpChannel[]> = {};
      const sites = await catalogAllDeviceApi({ signal });

      if (!!sites) {
        for (const site of sites) {
          const channels = await catalogChannelApi(site.code, { signal });
          if (!channels || channels.length === 0) continue;

          const cameras: VimpChannel[] = [];
          const alarms: VimpChannel[] = [];

          channels.forEach((channel) => {
            const typeCode = Number(channel.code.substring(11, 14));
            if (typeCode >= 4 && typeCode <= 6) {
              cameras.push(channel);
            } else if ((typeCode >= 101 && typeCode <= 108) || (typeCode >= 810 && typeCode <= 815)) {
              alarms.push(channel);
            }
          });

          if (cameras.length > 0) {
            siteCamerasMap[site.code] = cameras;
          }
          if (alarms.length > 0) {
            siteAlarmsMap[site.code] = alarms;
          }
        }
      }

      cameraStore.buildLineTabPanes({
        sites,
        siteCamerasMap,
        codeLines,
        codeSites,
        codeStationAreas,
        codeParkingAreas,
        codeOccAreas,
        codeTrainAreas,
      });

      alarmStore.buildLineTabPanes({
        sites,
        siteAlarmsMap,
        codeLines,
        codeSites,
        codeStationAreas,
        codeParkingAreas,
        codeOccAreas,
        codeTrainAreas,
      });

      return null;
    },
  });
};
