import { store } from "@/store/store";
import { execLocal, fileExists } from "@/utils/nativeMethods";
import { getBlackAppConfig } from "@/utils/common";
import { watch } from "vue";

export function useVCamChecker() {
  void getBlackAppConfig();
  /** 检测出错则提示；检测通过则将禁用登录按钮的flag置为false */
  async function checkVCamTxt() {
    let cameraInfo;
    try {
      const fs: typeof import("fs") = window.nodeRequire("fs");
      try {
        cameraInfo = fs.readFileSync("CameraInfo.txt", "utf-8");
      } catch (error) {
        logger({
          cnl: ["local", "server"],
          key: "checkVCamTxt",
          pgu: "AUTO",
          dtl: "CameraInfo.txt出错--0",
          ejn: JSON.stringify(error),
        });
        await new Promise((resolve2) => setTimeout(resolve2, 3000));
        cameraInfo = fs.readFileSync("CameraInfo.txt", "utf-8");
      }
    } catch (error) {
      logger({
        cnl: ["local", "server"],
        key: "checkVCamTxt",
        pgu: "AUTO",
        stk: error instanceof Error ? error.message : JSON.stringify(error),
        dtl: "读取CameraInfo.txt出错",
        ext: { errorType: "e-02", applicationNames: cameraInfo },
      });
      $message.error("请关闭虚拟摄像头软件或直接更换电脑", {
        duration: 24 * 60 * 60 * 1000,
      });
      return;
    }
    let found = false;
    const { vCamList: VCAM_LIST } = await getBlackAppConfig();
    if (cameraInfo && cameraInfo.trim()) {
      for (const vc of VCAM_LIST) {
        if (cameraInfo.toUpperCase().includes(vc.toUpperCase())) {
          found = true;
          $message.info(
            () => (
              <div class="enhanced-error-message">
                在考试期间，请关掉虚拟摄像头软件，诚信考试。
              </div>
            ),
            {
              duration: 24 * 60 * 60 * 1000,
            }
          );
          logger({
            cnl: ["local", "server"],
            key: "checkVCamTxt",
            pgu: "AUTO",
            dtl: "提示CameraInfo.txt成功",
            ext: { applicationNames: cameraInfo },
          });
        }
      }
    }
    disableLoginBtnBecauseVCam = found;
  }

  let disableLoginBtnBecauseVCam = $ref(true);

  const QECSConfig = $computed(() => store.QECSConfig);
  watch(
    () => QECSConfig.PREVENT_CHEATING_CONFIG,
    async () => {
      // 由于在刷新时，会重新从sessionStorage里面获取值并设置QECSConfig，
      // 同时，还通过网络获取，所以此时的监听会发生两次，两次可能导致 CameraInfo.txt 被删除后读取不到
      // 所以此时发现值一样就不要进行后续
      // new discover: 因为 useRemoteAppChecker 的 watch 是 immediate 所以行为不太一样
      // if (JSON.stringify(val) === JSON.stringify(oldVal)) return;

      if (
        !QECSConfig.PREVENT_CHEATING_CONFIG?.includes("DISABLE_VIRTUAL_CAMERA")
      ) {
        disableLoginBtnBecauseVCam = false;
        return;
      }

      if (import.meta.env.DEV) return;

      try {
        const fs: typeof import("fs") = window.nodeRequire("fs");
        fileExists("CameraInfo.txt") && fs.unlinkSync("CameraInfo.txt");
      } catch (error) {
        console.log(error);
        logger({
          cnl: ["local", "server"],
          key: "checkVCamTxt",
          dtl: "unlink CameraInfo.txt 失败",
          possibleError: error,
        });
        $message.error("请关闭虚拟摄像头软件或直接更换电脑", {
          duration: 24 * 60 * 60 * 1000,
        });
        throw error;
      }

      await execLocal("multiCamera.exe");

      await checkVCamTxt();
    }
  );

  return { disableLoginBtnBecauseVCam: $$(disableLoginBtnBecauseVCam) };
}
