// 定义函数类型，支持任意参数
type PollingCallback = (...args: any[]) => void;

export const requestArray = new Map<string, { callback: PollingCallback; args?: any[] }>();
// 添加函数到 Map
export const addRequest = (key: string, callback: PollingCallback, args?: any[]) => {
  requestArray.set(key, { callback, args });
};

// 从 Map 中移除函数
export const removeRequest = (key: string) => {
  requestArray.delete(key);
};

export const runImmediatelyByKey = (key: string) => {
  const { callback, args } = requestArray.get(key) || {};
  if (callback) {
    callback(...(args || []));
  }
};

export const runImmediatelyAll = () => {
  updateTime.value = new Date().getTime();
  requestArray.forEach(({ callback, args }) => {
    if (args) {
      callback(...args);
    }else{
      callback()
    }
  });
};

export let updateTime = ref(0);

export const usePolling = () => {
  const pollingWorker = new Worker("/js/polling.worker.js");

  pollingWorker.onmessage = (_e: any) => {
    // 执行所有存储的函数
    updateTime.value = new Date().getTime();
    requestArray.forEach(({ callback, args }) => {
      if (args) {
        callback(...args);
      } else {
        callback();
      }
    });
  };

  onMounted(() => {
    pollingWorker.postMessage({ command: "start", interval: 1000 * 60 * 60 });
  });

  onBeforeUnmount(() => {
    pollingWorker.postMessage({ command: "stop" });
    // 清理所有存储的函数
    requestArray.clear();
  });
};
