import { httpApp } from "@/plugins/axiosApp";
import { store } from "@/store/store";
import { onBeforeUnmount, onMounted } from "vue";

export function useScreenTop(examRecordDataId: string | number) {
  let lastBlurTimeStamp = 0;
  function blurHandler() {
    if (Date.now() - lastBlurTimeStamp < 1000) {
      // 小于1秒的切屏不计算在内，快捷键alt+tab容易连续触发两次
      return;
    }
    lastBlurTimeStamp = Date.now();

    logger({
      cnl: ["server"],
      act: "切屏处理预备",
      dtl: "学生端不是置顶状态",
      pgu: "AUTO",
    });
    $message.warning("考试过程请勿尝试切屏，可能影响考试成绩");
    void httpApp
      .post(
        "/api/ecs_oe_student/examControl/switchScreen?examRecordDataId=" +
          examRecordDataId
      )
      .then((res) => {
        if (
          store.QECSConfig.PREVENT_CHEATING_CONFIG.includes(
            "RECORD_SWITCH_SCREEN"
          )
        ) {
          logger({
            cnl: ["server"],
            act: "切屏处理结果",
            dtl: "学生端不是置顶状态",
            pgu: "AUTO",
            ext: { res: JSON.stringify(res.data) },
          });
          if (res.data) {
            // console.log(res.data);
            const { switchScreenCount, maxSwitchScreenCount } = res.data;
            if (
              typeof switchScreenCount === "number" &&
              typeof maxSwitchScreenCount === "number"
            ) {
              if (switchScreenCount > maxSwitchScreenCount) {
                store.exam.isExceededSwitchCount = true;
              }
            }
          }
        }
      })
      .catch((e) =>
        logger({ cnl: ["server"], act: "切屏处理请求失败", possibleError: e })
      );
  }

  function toggleSwitchCount(switchState: "on" | "off") {
    if (!store.QECSConfig.PREVENT_CHEATING_CONFIG.includes("FULL_SCREEN_TOP")) {
      return;
    }
    if (typeof window.nodeRequire == "undefined") {
      logger({
        cnl: ["server"],
        act: "非考生端，不检测置顶状态",
        ext: { switchState },
      });
      return;
    }

    logger({
      cnl: ["server"],
      act: "考生端，设置检测置顶状态",
      ext: { switchState },
    });
    const remote: typeof import("electron").remote =
      window.nodeRequire("electron").remote;
    const mainWindow = remote.getCurrentWindow();

    if (switchState === "on") {
      mainWindow.on("blur", blurHandler);
    } else {
      mainWindow.removeListener("blur", blurHandler);
    }
  }

  onMounted(() => toggleSwitchCount("on"));
  onBeforeUnmount(() => toggleSwitchCount("off"));
}
