import { userBrowser, getLocationParams } from "@/utils";
import storage, { actions } from "@/utils/storage";
import { useBaseStoreWithOut } from "@/stores/modules/base";

export default function () {
  // 当前环境判断
  const browser = userBrowser();
  storage.setSessionStorage(actions.BROWSER, JSON.stringify(browser));
  const addToHome = !!Number(storage.getSessionStorage(actions.ADD_TO_HOME));
  if (getLocationParams(window.location.href).appType == 1) {
    return;
  }
  // 是否注册service-worker
  if (!window.Android && !browser.isIos) {
    window.addEventListener("load", () => {
      navigator.serviceWorker
        .register("./service-worker.js")
        .then((registration) => {
          // console.log('Service Worker 注册成功:', registration);
          window.addEventListener("beforeinstallprompt", (e) => {
            e.preventDefault();
            useBaseStoreWithOut().setDeferredPrompt(e);
            useBaseStoreWithOut().setShowAddToHomeVisible(!addToHome);
          });
        })
        .catch((error) => {
          // console.log('Service Worker 注册失败:', error);
        });
    });
  } else {
    useBaseStoreWithOut().setShowAddToHomeVisible(!addToHome);
  }
}
