<script setup>
import { ref, watch, computed } from "vue";
import { useRouter } from "vue-router";
import useNiagaraDataStore from "@/stores/useNiagaraDataStore";
import useAlarmDataStore from "@/stores/useAlarmDataStore";

const niagaraStore = useNiagaraDataStore();
const alarmDataStore = useAlarmDataStore();

// 計算 alarmCount 的總和
const totalAlarmCount = computed(() => {
  return alarmDataStore.alarmData.reduce((total, child) => total + (child.alarmCount || 0), 0);
});

const initializeAlarmData = () => {
  // 使用 useAlarmDataStore 建立 alarmData
  if (!alarmDataStore.alarmData.length) {
    alarmDataStore.createAlarmData(niagaraStore.alarmList);
  }

  // 對每個 alarm 項目建立訂閱
  alarmDataStore.alarmData.forEach((alarm, index) => {
    if (!alarm.alarmOrd) return;

    window.require &&
      window.requirejs(["baja!"], (baja) => {
        //  建立訂閱器
        const subscriber = new baja.Subscriber();
        // 定義 changed 事件的處理函數
        subscriber.attach("changed", (prop) => {
          // console.log("prop", prop.$getDisplayName(), prop.$getValue());
          try {
            let alarmCount = alarmDataStore.alarmData[index].alarmCount;
            let unackedCount = alarmDataStore.alarmData[index].unackedCount;

            if (prop.$getDisplayName() === "In Alarm Count") {
              // 取得 In Alarm Count
              alarmCount = prop.$getValue();
            }
            if (prop.$getDisplayName() === "Unacked Alarm Count") {
              // 取得 Unacked Alarm Count
              unackedCount = prop.$getValue();
            }

            // 更新 useAlarmDataStore 中的資料
            alarmDataStore.updateAlarmItem(index, alarmCount, unackedCount);
          } catch (error) {
            console.error(
              `處理 ${alarm.name || index} 告警變化失敗: ${error.message}`,
              error
            );
          }
        });

        // 訂閱 alarm 資訊
        baja.Ord.make(alarm.alarmOrd)
          .get({ subscriber })
          .then((result) => {
            console.log(`Successfuly subscribed to alarm ${alarm.name}`);
          })
          .catch((err) => {
            console.error(
              `訂閱 Alarm ${alarm.name || index} 失敗: ${err.message}`
            );
            subscriber.detach("changed");
          });
      });
  });
};

watch(
  () => niagaraStore.alarmList.children,
  (newValue, oldValue) => {
    if (newValue) {
      console.log("niagaraStore.alarmList changed:", newValue);
      initializeAlarmData();
    }
  },
  { immediate: true } // 立即執行一次
);
</script>

<template>
  <a-dropdown>
    <template #overlay>
      <a-menu>
        <a-menu-item v-for="child in alarmDataStore.alarmData" :key="child.key">
          <router-link
            :to="{
              name: 'baja',
              query: { ord: encodeURIComponent(child.Ord) },
            }"
            class="flex items-center justify-between gap-8"
          >
            <span>{{ child.name }}</span>
            <span>{{ child.alarmCount }}/{{ child.unackedCount }}</span>
          </router-link>
        </a-menu-item>
      </a-menu>
    </template>
    <a-badge :count="totalAlarmCount" :overflow-count="999"
      >
      <a class="flex flex-col items-center">
        <font-awesome-icon :icon="['fas', 'bell']" size="2x" />
        <span class="text-sm">告警</span>
      </a>
    </a-badge>
  </a-dropdown>
</template>

<style lang="css" scoped></style>
