import { onMounted, onUnmounted } from "vue";

/**
 * newVersionAvailable: boolean 是否有新版本
 * checkNewVersion 有版本更新返回true，函数内部处理；没版本更新则返回false
 */
export function useNewVersion() {
  async function checkNewVersion(): Promise<boolean> {
    const myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/javascript");
    myHeaders.append("Cache-Control", "no-cache");
    const scripts = document.scripts;
    const response = await fetch(
      scripts[scripts.length - 1]?.getAttribute("data-src") + "?x" + Date.now(),
      {
        method: import.meta.env.DEV ? "GET" : "HEAD",
        headers: myHeaders,
      }
    );
    if (!response.ok || newVersionAvailable) {
      if (
        response.ok &&
        newVersionAvailable &&
        localStorage.getItem("__swReload")
      ) {
        logger({
          cnl: ["local", "server"],
          pgu: "AUTO",
          dtl: "service worker刷新失败",
        });
        $message.info("请重新打开程序。", { duration: 24 * 60 * 60 * 1000 });
        return true;
      }
      logger({
        cnl: ["local", "server"],
        pgu: "AUTO",
        dtl: "新版本发布后，客户端自动刷新",
      });
      $message.info("正在获取新版本...");
      localStorage.setItem("__swReload", "anything");
      // disableLoginBtnBecauseRefreshServiceWorker = true;
      await new Promise((resolve) => setTimeout(resolve, 1000));
      location.reload();

      return true;
    }

    return false;
  }

  let newVersionAvailable = $ref(false);
  const checkNewVersionListener = () => {
    newVersionAvailable = true;
  };

  onMounted(async () => {
    document.addEventListener("__newSWAvailable", checkNewVersionListener, {
      once: true,
    });
    if (localStorage.getItem("__swReload")) {
      localStorage.removeItem("__swReload");
      $message.info("正在更新版本...");
      // disableLoginBtnBecauseRefreshServiceWorker = true;
      await new Promise((resolve) => setTimeout(resolve, 2000));
      location.reload();
    }
  });

  onUnmounted(() =>
    document.removeEventListener("__newSWAvailable", checkNewVersionListener)
  );

  return { newVersionAvailable: $$(newVersionAvailable), checkNewVersion };
}
