import type { LineDevices, NdmDeviceResultVO, Station, StationDevices } from '@/apis';
import { NDM_DEVICE_STORE_ID } from '@/constants';
import { tryGetDeviceType } from '@/enums';
import { defineStore } from 'pinia';
import { shallowRef, triggerRef } from 'vue';

export const useDeviceStore = defineStore(
  NDM_DEVICE_STORE_ID,
  () => {
    // 全线所有车站的设备
    const lineDevices = shallowRef<LineDevices>({}); // 数据量很大所以用shallowRef配合triggerRef优化性能

    const setLineDevices = (devices: LineDevices) => {
      lineDevices.value = devices;
    };

    const setStationDevices = (stationCode: Station['code'], devices: StationDevices) => {
      lineDevices.value[stationCode] = devices;
      triggerRef(lineDevices);
    };

    const patchDevice = (stationCode: Station['code'], device: NdmDeviceResultVO) => {
      const deviceType = tryGetDeviceType(device.deviceType);
      if (!!deviceType) {
        if (lineDevices.value[stationCode]) {
          const index = lineDevices.value[stationCode][deviceType].findIndex((d) => d.id === device.id);
          if (index > -1) {
            lineDevices.value[stationCode][deviceType][index] = device;
            triggerRef(lineDevices);
          }
        }
      }
    };

    return {
      lineDevices,

      setLineDevices,
      setStationDevices,
      patchDevice,
    };
  },
  {
    persistToIndexedDB: true,
  },
);
