import router from "@/router";
import { useTimers } from "@/setups/useTimers";
import { store } from "@/store/store";
import { useAnswerQuestions } from "./useAnswerQuestions";

export function useRealSubmitPaper(
  examId: number,
  examRecordDataId: number,
  doSnap: () => void
) {
  const { addTimeout } = useTimers();
  const answerAllQuestions = useAnswerQuestions()
  async function userSubmitPaper(usedExamTimes: {
    usedExamSeconds: number;
    startTimestamp: number;
  }) {
    // if (
    //   store.exam.freezeTime &&
    //   store.exam.remainTime >
    //     (store.exam.duration - store.exam.freezeTime) * 60 * 1000
    // ) {
    //   $message.info(`考试开始${store.exam.freezeTime}分钟后才允许交卷。`);
    //   return;
    // }
    if (
      store.exam.freezeTime &&
      usedExamTimes.usedExamSeconds * 1000 +
        Date.now() -
        usedExamTimes.startTimestamp <
        store.exam.freezeTime * 60 * 1000
    ) {
      $message.info(`考试开始${store.exam.freezeTime}分钟后才允许交卷。`);
      return;
    }
    logger({ cnl: ["server", "local", "console"], act: "学生点击交卷" });
    try {
      // 交卷前强制提交所有答案
      const ret = await answerAllQuestions(true);
      if (!ret) {
        // 提交答案失败，停止交卷逻辑。
        return;
      }
    } catch (error) {
      return;
    }

    const answered = store.exam.examQuestionList.filter(
      (q) => q.studentAnswer !== null
    ).length;
    const unanswered = store.exam.examQuestionList.filter(
      (q) => q.studentAnswer === null
    ).length;
    const signed = store.exam.examQuestionList.filter(
      (q) => q.isStarred
    ).length;
    $dialog.info({
      title: "确认交卷",
      content: () => (
        <div>
          <p>已答题目：{answered}</p>
          <p>未答题目：{unanswered}</p>
          <p>标记题目：{signed}</p>
        </div>
      ),
      positiveText: "确定",
      onPositiveClick: () => {
        void realSubmitPaper();
      },
    });
  }

  // 多种条件都可能触发交卷，所以要有一个锁来避免重复进入
  let sumbitLock = false;
  async function realSubmitPaper() {
    if (sumbitLock) {
      logger({ cnl: ["server"], act: "交卷", stk: "竟然有锁！" });
      return;
    } else {
      sumbitLock = true;
      store.exam.isSubmittingPaper = true;
    }
    store.increaseGlobalMaskCount("realSubmitPaper");
    store.spinMessage = "正在交卷，请耐心等待...";
    logger({ cnl: ["server"], act: "正在交卷，请耐心等待..." });
    let delay = 0;
    const oldSnapCount = store.exam.compareResultMap?.size;
    if (store.exam.faceCheckEnabled) {
      logger({ cnl: ["server"], act: "交卷前抓拍" });
      doSnap();
      await new Promise((resolve) => setTimeout(resolve, 3 * 1000));
      // 根据线上错误排查：可能已经退出页面了，没有数据了
      const newSnapCount = store.exam.compareResultMap?.size;
      if (store.exam.compareResultMap && newSnapCount - oldSnapCount === 0) {
        // 给抓拍照片多2秒处理时间
        delay = 8;
        logger({ cnl: ["server"], act: "交卷前抓拍", dtl: "3秒内未上传完毕" });
      }
    }
    // 和下行注释的sleep语句不是一样的。sleep之后还可以执行。加上clearTimeout则可拒绝。
    // await new Promise(resolve => setTimeout(() => resolve(), delay * 1000));
    addTimeout(() => {
      store.decreaseGlobalMaskCount("realSubmitPaper");
      store.spinMessage = "";
      void router
        .push({
          name: "SubmitPaper",
          params: { examId, examRecordDataId },
        })
        .finally(() => (sumbitLock = false));
    }, delay * 1000);
  }

  return { userSubmitPaper, realSubmitPaper };
}
