import { ref, onMounted, onUnmounted } from 'vue';
import dayjs from 'dayjs';
import { getAllDevice } from "@/apis/building";

export default function useAlarmData() {
  let timer = null;
  const alarmData = ref([]);
  const allDeviceList = ref([]);

  const getFormateDate = (datetime, formatRule = 'YYYY-MM-DD HH:mm') => {
    return dayjs(datetime).format(formatRule);
  };

  const getAlarmByBaja = (
    startDate,
    endDate,
    isRecover,
    isAck,
    alarmClass,
    callback
  ) => {
    window.require &&
      window.requirejs(["baja!"], (baja) => {
        let alarms = [];
        // console.log("進入 bajaSubscriber 準備執行BQL訂閱");
        const alarmClassQuery = alarmClass.map(ac => `alarmClass = '${ac}'`).join(' or ');
        const ord = `local:|foxs:|alarm:|bql:select * where (${alarmClassQuery}) and timestamp.millis > ${startDate} and timestamp.millis < ${endDate} and sourceState = '${isRecover}' and ackState = '${isAck}' order by timestamp desc`;
        baja.Ord.make(ord).get({
          cursor: {
            before: () => {
              timer = null;
            },
            each: (record) => {
              let alarmDisplayName = record.get("alarmData").get("sourceName");
              alarmDisplayName = alarmDisplayName.replace(/\$2d/g, "_");  // 檢查並替換 $2d 為 _
              const sourceTmp = alarmDisplayName.split("_");
              const bfName = sourceTmp[1] + "-" + sourceTmp[4];
              const sourceName = sourceTmp.slice(0, 8).join("_");
              const sourceTmpFinal = sourceTmp[7] + "-" + sourceTmp[8];
              const origSourceName = record.get("alarmData").get("sourceName");
              if (!sourceTmpFinal.includes("undefined")) {
                alarms.push({
                  building_tag: bfName,
                  uuid: record.get("uuid").$val,
                  timestamp_date: getFormateDate(record.get("timestamp").getJsDate(), "YYYY/MM/DD "),
                  timestamp_time: getFormateDate(record.get("timestamp").getJsDate(), "HH:mm:ss"),
                  alarmClass: record.get("alarmClass"),
                  device_number: sourceName,
                  origSourceName: origSourceName,
                  full_name: allDeviceList.value.find((d) => origSourceName.includes(d.device_number))?.full_name,
                  msg: record.get("alarmData").get("msgText"),
                  sourceState: record.get("sourceState").getDisplayTag(),
                  normalTime: getFormateDate(record.get("normalTime").getJsDate()),
                  ackState: record.get("ackState").getDisplayTag(),
                  ackedTime: getFormateDate(record.get("ackTime").getJsDate()),
                });
              }
            },
            after: () => {
              if (typeof callback === 'function') {
                callback({ count: alarms.length, data: alarms });
              }
            },
            limit: -1,
            offset: 0,
          },
        });
      });
  };

  const getDevice = async () => {
    const res = await getAllDevice();
    allDeviceList.value = res.data;
  };

  const stopFetching = () => {
    if (timer) {
      clearTimeout(timer);
    }
  };

  onMounted(() => {
    getDevice();
  });

  onUnmounted(() => {
    stopFetching();
  });

  return { getAlarmByBaja, alarmData, stopFetching };
}
