import { initStationAlarms, type LineAlarms, type NdmDeviceAlarmLogResultVO } from '@/apis';
import { NDM_UNREAD_STORE_ID } from '@/constants';
import { tryGetDeviceType } from '@/enums';
import { defineStore } from 'pinia';
import { computed, shallowRef, triggerRef } from 'vue';

export const useUnreadStore = defineStore(NDM_UNREAD_STORE_ID, () => {
  // 全线所有车站的未读告警 (来自stomp订阅)
  const unreadLineAlarms = shallowRef<LineAlarms>({});
  const unreadAlarmCount = computed(() => {
    let count = 0;
    Object.values(unreadLineAlarms.value).forEach((stationAlarms) => {
      count += stationAlarms['unclassified'].length;
    });
    return count;
  });

  const pushUnreadAlarm = (alarm: NdmDeviceAlarmLogResultVO) => {
    const stationCode = alarm.stationCode;
    if (!stationCode) return;
    if (!unreadLineAlarms.value[stationCode]) {
      unreadLineAlarms.value[stationCode] = initStationAlarms();
    }
    const deviceType = tryGetDeviceType(alarm.deviceType);
    if (!deviceType) return;
    const stationAlarms = unreadLineAlarms.value[stationCode];
    stationAlarms[deviceType].push(alarm);
    stationAlarms['unclassified'].push(alarm);
    triggerRef(unreadLineAlarms);
  };

  const clearUnreadAlarms = () => {
    unreadLineAlarms.value = {};
    triggerRef(unreadLineAlarms);
  };

  return {
    unreadLineAlarms,
    unreadAlarmCount,

    pushUnreadAlarm,
    clearUnreadAlarms,
  };
});
