import { httpApp } from "@/plugins/axiosApp";
import { store } from "@/store/store";
import { ExamQuestion, PaperStruct, Store } from "@/types/student-client";
import { dimensionLog } from "@/utils/logger";

type PRACTICE_TYPE = "IN_PRACTICE" | "NO_ANSWER";

export async function initExamData(examId: number, examRecordDataId: number) {
  logger({ cnl: ["server", "local"], pgn: "答题页面", act: "before initData" });
  const { courseName, courseCode } = (
    await httpApp.post<{ courseName: string; courseCode: string }>(
      "/api/ecs_oe_student/examControl/getCourseInfo/" + examRecordDataId,
      { "axios-retry": { retries: 4 }, noErrorMessage: true }
    )
  ).data;
  const [
    { data: weixinAnswerEnabled },
    { data: faceCheckEnabled },
    { data: faceLivenessEnabled },
    { data: examProp },
    { data: exam },
    { data: paperStruct },
    { data: examQuestionListOrig },
  ] = await Promise.all([
    // 是否开放微信小程序作答
    httpApp.get<boolean>(
      `/api/ecs_exam_work/exam/weixinAnswerEnabled/${examId}?courseCode=${courseCode}`,
      {
        "axios-retry": { retries: 4 },
        noErrorMessage: true,
      }
    ),
    // 是否支持人脸识别
    httpApp.get<boolean>("/api/ecs_exam_work/exam/faceCheckEnabled/" + examId, {
      "axios-retry": { retries: 4 },
      noErrorMessage: true,
    }),
    // 是否支持活体检测
    httpApp.get<boolean>(
      "/api/ecs_exam_work/exam/identificationOfLivingEnabled/" + examId,
      { "axios-retry": { retries: 4 }, noErrorMessage: true }
    ),
    // 查询考生的考试批次属性集; 实际上后台都是字符串 {PRACTICE_TYPE: string | null; FREEZE_TIME: string; SNAPSHOT_INTERVAL: string;  }
    httpApp.get<{
      PRACTICE_TYPE: string | null;
      FREEZE_TIME: number | null;
      SNAPSHOT_INTERVAL: number;
    }>(
      "/api/ecs_exam_work/exam/getExamPropertyFromCacheByStudentSession/" +
        examId +
        `/SNAPSHOT_INTERVAL,PRACTICE_TYPE,FREEZE_TIME`,
      { "axios-retry": { retries: 4 }, noErrorMessage: true }
    ),
    // 按ID查询考试批次信息
    httpApp.get<Store["exam"]>("/api/ecs_exam_work/exam/" + examId, {
      "axios-retry": { retries: 4 },
      noErrorMessage: true,
    }),
    // 获取考试记录试卷结构
    httpApp.get<PaperStruct>(
      "/api/ecs_oe_student/examRecordPaperStruct/getExamRecordPaperStruct?examRecordDataId=" +
        examRecordDataId,
      { "axios-retry": { retries: 4 }, noErrorMessage: true }
    ),
    // 获取试题列表
    httpApp.get<ExamQuestion[]>(
      "/api/ecs_oe_student/examQuestion/findExamQuestionList",
      { "axios-retry": { retries: 4 }, noErrorMessage: true }
    ),
  ]);
  store.exam.courseName = courseName;

  let examQuestionList = examQuestionListOrig;

  logger({
    cnl: ["server", "local"],
    pgn: "答题页面",
    dtl: `end${typeof Object.fromEntries === "function" ? " " : "　"}initData`,
  });

  dimensionLog("答题页面");

  if (exam.examType === "PRACTICE") {
    exam.practiceType = examProp.PRACTICE_TYPE as PRACTICE_TYPE;
  }

  exam.freezeTime = JSON.parse("" + examProp.FREEZE_TIME);
  exam.SNAPSHOT_INTERVAL = JSON.parse("" + examProp.SNAPSHOT_INTERVAL);

  exam.WEIXIN_ANSWER_ENABLED = weixinAnswerEnabled;

  store.exam.faceCheckEnabled = faceCheckEnabled;
  store.exam.faceLivenessEnabled = faceLivenessEnabled;

  logger({
    cnl: ["server", "local"],
    pgn: "答题页面",
    ext: {
      examRecordDataId: examRecordDataId,
      faceCheckEnabled: faceCheckEnabled,
      faceLivenessEnabled: faceLivenessEnabled,
      WEIXIN_ANSWER_ENABLED: exam.WEIXIN_ANSWER_ENABLED,
      SNAPSHOT_INTERVAL: examProp.SNAPSHOT_INTERVAL,
      PRACTICE_TYPE: examProp.PRACTICE_TYPE,
      FREEZE_TIME: examProp.FREEZE_TIME,
    },
  });

  // parentQuestionBody
  //     questionUnitWrapperList
  //         questionBody  => from examQuestionList
  //         questionUnitList =>
  //         studentAnswer
  //         rightAnswer

  // init subNumber
  let questionId: string | null = null;
  let i = 1;

  examQuestionList = examQuestionList.map((eq) => {
    if (questionId == eq.questionId) {
      eq.subNumber = i++;
    } else {
      i = 1;
      questionId = eq.questionId;
      eq.subNumber = i++;
    }
    return eq;
  });

  let groupOrder = 1;
  let mainNumber = 0;
  examQuestionList = examQuestionList.map((eq) => {
    if (mainNumber == eq.mainNumber) {
      eq.inGroupOrder = groupOrder++;
    } else {
      mainNumber = eq.mainNumber;
      groupOrder = 1;
      eq.inGroupOrder = groupOrder++;
    }

    const questionWrapperList =
      paperStruct.defaultPaper.questionGroupList[eq.mainNumber - 1]
        .questionWrapperList;
    const groupName =
      paperStruct.defaultPaper.questionGroupList[eq.mainNumber - 1].groupName;
    const groupTotal = questionWrapperList.reduce(
      (accumulator, questionWrapper) =>
        accumulator + questionWrapper.questionUnitWrapperList.length,
      0
    );

    eq.groupName = groupName;
    eq.groupTotal = groupTotal;
    return eq;
  });

  store.exam.examQuestionList = examQuestionList.map((eq) => {
    const paperStructQuestion = paperStruct.defaultPaper.questionGroupList[
      eq.mainNumber - 1
    ].questionWrapperList.find((q) => q.questionId === eq.questionId);
    return Object.assign(eq, {
      limitedPlayTimes: paperStructQuestion!.limitedPlayTimes,
    });
  });

  Object.assign(store.exam, exam);
  store.exam.paperStruct = paperStruct;
  // TODO: 此处类型待优化
  store.exam.allAudioPlayTimes =
    JSON.parse(
      store.exam.examQuestionList[0].audioPlayTimes as unknown as string
    ) || [];
}
