import { httpApp } from "@/plugins/axiosApp";
import router from "@/router";
import { store } from "@/store/store";

/**
 * 检查当前用户是否存在断点，如果存在则
 * 1. 进入考试页面
 * 2. 如果超过断点次数或最大切屏次数，则交卷
 *
 * @returns true 代表有断点 false代表没有断点
 * @throws 接口调用不成功，则抛出异常
 */
export async function checkExamInProgress(): Promise<boolean> {
  try {
    store.increaseGlobalMaskCount("checkExamInProgress");
    // 断点续考
    let tried = 0;
    let examingRes: any;
    while (tried < 5) {
      examingRes = await httpApp.get(
        "/api/ecs_oe_student/examControl/checkExamInProgress",
        {
          noErrorMessage: true,
          "axios-retry": {
            retries: 4,
            retryCondition(error) {
              // console.log(error);
              if (error.response?.status === 503) {
                tried++;
                return true;
              } else {
                return false;
              }
            },
            shouldResetTimeout: true,
          },
        }
      );
      if (examingRes.data.code === "000000") {
        // 正常退出
        break;
      } else if (examingRes.data.code === "S-101000") {
        // 后台指示重试
        tried++;
        logger({
          cnl: ["local", "server"],
          key: "断点续考",
          pgu: "AUTO",
          dtl: "断点续考接口S-101000",
        });
      } else {
        logger({
          cnl: ["local", "server"],
          key: "断点续考",
          pgu: "AUTO",
          dtl: "断点续考接口返回异常",
          ejn: JSON.stringify(examingRes.data),
        });
        break;
      }
    }
    if (examingRes.status !== 200 || examingRes.data.code !== "000000") {
      logger({
        cnl: ["local", "server"],
        key: "断点续考",
        pgu: "AUTO",
        act: "断点续考处理异常",
        aus: examingRes.status,
        ejn: JSON.stringify(examingRes.data),
      });
      throw new Error("调用断点续考接口超过次数");
    }

    const content: {
      isExceed: boolean;
      exceedMaxSwitchScreenCount: boolean;
      maxInterruptNum: number;
      maxSwitchScreenCount: number;
      examId: number;
      examRecordDataId: number;
    } | null = examingRes.data.data;

    if (content?.isExceed || content?.exceedMaxSwitchScreenCount) {
      const hintStr = content.isExceed
        ? `超出最大断点续考次数(${content.maxInterruptNum})，正在自动交卷...`
        : `超出最大切屏次数(${content.maxSwitchScreenCount})，正在自动交卷...`;
      // 超出断点续考次数的逻辑，仅此block
      $message.info(hintStr);
      // 断点续考消息一闪而过，此处可以加延迟
      const res = await httpApp.get("/api/ecs_oe_student/examControl/endExam");
      if (res.status === 200) {
        void router.replace({
          path: `/online-exam/exam/${content.examId}/examRecordData/${content.examRecordDataId}/end`,
        });
        logger({
          cnl: ["local", "server"],
          key: "断点续考",
          pgu: "AUTO",
          act: "交卷成功",
        });
        return true;
      } else {
        logger({
          cnl: ["local", "server"],
          key: "断点续考",
          pgu: "AUTO",
          act: "交卷失败",
          dtl: "断点续考处理异常",
        });
        $message.error("交卷失败");
        throw new Error("交卷失败");
      }
    } else if (content) {
      const msg = $message.info("正在进入断点续考...");
      store.increaseGlobalMaskCount("checkExamInProgress");
      store.spinMessage = "正在进入断点续考...";
      await new Promise((res) => setTimeout(res, 1.5 * 1000));
      await router
        .push(
          `/online-exam/exam/${content.examId}/examRecordData/${content.examRecordDataId}/order/1`
        )
        .then(() => msg.destroy())
        .finally(() => {
          setTimeout(
            () => store.decreaseGlobalMaskCount("checkExamInProgress"),
            3 * 1000
          );
        });
      logger({
        cnl: ["local", "server"],
        key: "断点续考",
        pgu: "AUTO",
        act: "正在进入断点续考...",
      });
      return true;
    }
  } catch (error) {
    $message.warning("服务繁忙，请稍后重试！");
    throw error;
  } finally {
    store.decreaseGlobalMaskCount("checkExamInProgress");
  }
  return false;
}
