import { DOMAIN, STRICT_CHECK_HOSTS } from "@/constants/constants";
import { checkMainExe, fileExists, isElectron } from "@/utils/nativeMethods";
import ua from "@/utils/ua";
import { onMounted, Ref, watch } from "vue";

export function useAppVersion(newVersionAvailable: Ref<boolean>) {
  // @ts-expect-error
  // eslint-disable-next-line no-undef
  const portableFile = window.proceess?.env?.PORTABLE_EXECUTABLE_FILE;

  function checkApp() {
    if (isElectron() && !portableFile && !import.meta.env.DEV) {
      // FIXME: 在苹果电脑跳过检测
      if (navigator.userAgent.includes("Macintosh")) {
        return;
      }

      disableLoginBtnBecauseAppVersionChecker = true;
      if (ua.getBrowser().version !== "1.9.3") {
        $message.error("请与学校申请最新的客户端，进行考试！", {
          duration: 24 * 60 * 60 * 1000,
        });
      } else {
        $message.error(
          "电脑环境达不到考试要求，请清理与考试无关软件或更换电脑",
          {
            duration: 24 * 60 * 60 * 1000,
          }
        );
      }
    }

    if (
      [
        "xjtu.ecs.qmth.com.cn",
        "ccnu.ecs.qmth.com.cn",
        "snnu.ecs.qmth.com.cn",
        "swjtu.ecs.qmth.com.cn",
      ].includes(DOMAIN)
    ) {
      if (!isElectron() || !fileExists("multiCamera.exe")) {
        disableLoginBtnBecauseAppVersionChecker = true;
        $message.error("请与学校申请最新的客户端，进行考试！", {
          duration: 24 * 60 * 60 * 1000,
        });
      }
    }

    if (STRICT_CHECK_HOSTS.includes(window.location.hostname)) {
      if (!checkMainExe()) {
        disableLoginBtnBecauseAppVersionChecker = true;
        if (ua.getBrowser().version !== "1.9.3") {
          $message.error("请与学校申请最新的客户端，进行考试！", {
            duration: 24 * 60 * 60 * 1000,
          });
        } else {
          $message.error(
            "电脑环境达不到考试要求，请清理与考试无关软件或更换电脑",
            { duration: 24 * 60 * 60 * 1000 }
          );
        }
      }
    }
  }

  onMounted(() => checkApp());

  watch(newVersionAvailable, () => {
    if (newVersionAvailable) {
      $message.error("程序有更新，请重新打开客户端！", {
        duration: 24 * 60 * 60 * 1000,
      });
    }
  });

  let disableLoginBtnBecauseAppVersionChecker = $ref(false);

  return {
    disableLoginBtnBecauseAppVersionChecker: $$(
      disableLoginBtnBecauseAppVersionChecker
    ),
  };
}
