<template>
  <div v-if="exam" :key="exam.id" class="container">
    <div class="main">
      <div v-for="(qG, index) in questionGroupList" :key="index">
        <div>
          {{ toChineseNumber(index + 1) }}、{{ qG.groupName }} ({{
            qG.groupScore
          }}分)
        </div>
        <div
          v-for="questionWrapper in qG.questionWrapperList"
          :key="questionWrapper.questionId"
          class="question-wrapper"
        >
          <div v-html="restoreAudio(questionWrapper.body)"></div>
          <div
            v-for="(questionUnit, index2) in questionWrapper.questionUnitList"
            :key="index2"
          >
            <div class="flex">
              <div>{{ questionWrapper.eqs[index2].order }}、</div>
              <div v-html="restoreAudio(questionUnit.body)"></div>
            </div>
            <div
              v-for="(optionOrder, index3) in questionWrapper.eqs[index2]
                .optionPermutation"
              :key="index3"
            >
              <div class="flex">
                <div>{{ indexToABCD(index3) }}、</div>
                <div
                  v-html="
                    restoreAudio(
                      questionUnit.questionOptionList[optionOrder - 0].body
                    )
                  "
                ></div>
              </div>
            </div>

            <div v-if="practiceType !== 'NO_ANSWER'" class="flex">
              正确答案：
              <div
                v-html="
                  rightAnswerToABCD(
                    questionUnit.questionType,
                    questionUnit.rightAnswer,
                    questionWrapper.eqs[index2].optionPermutation
                  )
                "
              ></div>
            </div>
            <div class="flex">
              学生答案：
              <div
                v-html="
                  rightAnswerToABCD(
                    questionUnit.questionType,
                    questionWrapper.eqs[index2].studentAnswer,
                    questionWrapper.eqs[index2].optionPermutation,
                    questionUnit.rightAnswer
                  )
                "
              ></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div v-else>正在等待数据返回...</div>
</template>

<script>
import { toChineseNumber } from "@/utils/util";

const optionName = "ABCDEFGHIJ".split("");

export default {
  name: "ExamPaper",
  props: {
    examId: { type: Number, default: 0 },
    examRecordDataId: { type: Number, default: 0 },
    fromCache: { type: Boolean, default: false },
  },
  data() {
    return {
      exam: null,
      questionGroupList: null,
      examQuestionList: null,
      practiceType: null,
    };
  },
  async created() {
    await this.initData();
  },
  methods: {
    async initData() {
      const practiceType = (await this.$http.get(
        "/api/ecs_exam_work/exam/getExamPropertyFromCacheByStudentSession/" +
          this.examId +
          `/PRACTICE_TYPE`
      )).data;
      this.practiceType = practiceType.PRACTICE_TYPE; // IN_PRACTICE NO_ANSWER

      const [
        examData,
        paperStructData,
        examQuestionListData,
        examRecordDataData,
        courseInfoData,
      ] = await Promise.all([
        this.$http.get("/api/ecs_exam_work/exam/" + this.examId),
        this.$http.get(
          "/api/ecs_oe_admin/examRecordPaperStruct/getExamRecordPaperStruct?examRecordDataId=" +
            this.examRecordDataId +
            (this.fromCache ? "&fromCache=1" : "")
        ),
        this.$http.get(
          "/api/ecs_oe_admin/examRecordQuestions/getExamRecordQuestions?examRecordDataId=" +
            this.examRecordDataId +
            (this.fromCache ? "&fromCache=1" : "")
        ),
        this.$http.get(
          "/api/ecs_oe_admin/exam/record/data/findExamRecordDataEntity?examRecordDataId=" +
            this.examRecordDataId +
            (this.fromCache ? "&fromCache=1" : "")
        ),
        this.$http.get(
          "/api/ecs_oe_admin/practice/getPracticeDetailInfo?examRecordDataId=" +
            this.examRecordDataId +
            (this.fromCache ? "&fromCache=1" : "")
        ),
      ]);
      const [exam, paperStruct, examRecordData, courseInfo] = [
        examData.data,
        paperStructData.data,
        examRecordDataData.data,
        courseInfoData.data,
      ];

      let examQuestionList = examQuestionListData.data.examQuestionEntities;

      if (
        exam === undefined ||
        paperStruct === undefined ||
        examQuestionListData === undefined
      ) {
        this.$Message.error({
          content: "获取试卷信息失败",
          duration: 15,
          closable: true,
        });
        return;
      }

      // init subNumber
      let questionId = 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.groupOrder = groupOrder++;
        } else {
          mainNumber = eq.mainNumber;
          groupOrder = 1;
          eq.groupOrder = 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;
      });

      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,
        });
      });

      this.exam = examData.data;
      this.examQuestionList = examQuestionList;

      // 子题乱序只在纯选择题中出现。选项乱序出现在任何选择题中。
      const questionGroupList =
        paperStructData.data.defaultPaper.questionGroupList;
      for (const qG of questionGroupList) {
        for (const question of qG.questionWrapperList) {
          const qs = this.examQuestionList.filter(
            eq => eq.questionId === question.questionId
          );
          // if (qs.length === 1) {
          //   const q = qs[0];
          //   Object.assign(question, {
          //     correctAnswer: q.correctAnswer,
          //     groupOrder: q.groupOrder,
          //     groupTotal: q.groupTotal,
          //     isAnswer: q.isAnswer,
          //     isSign: q.isSign,
          //     mainNumber: q.mainNumber,
          //     optionPermutation: q.optionPermutation,
          //     order: q.order,
          //     questionScore: q.questionScore,
          //     questionType: q.questionType,
          //     studentAnswer: q.studentAnswer,
          //     subNumber: q.subNumber
          //   });
          // } else {
          Object.assign(question, {
            eqs: qs,
          });
          // }
        }
      }
      for (const qG of questionGroupList) {
        for (const question of qG.questionWrapperList) {
          const q = await this.getQuestionContent(
            question.questionId,
            this.exam,
            courseInfo,
            examRecordData
          );
          question.body = q.body;
          question.hasAudios = q.hasAudios;
          question.questionUnitList = q.questionUnitList;
        }
      }

      this.questionGroupList = questionGroupList;
    },
    async getQuestionContent(questionId, exam, courseInfo, examRecordData) {
      const qContentRes = await this.$http.post(
        "/api/ecs_ques/default_question/question",
        {
          questionId: questionId,
          examId: this.exam.id,
          courseCode: courseInfo.courseCode,
          groupCode: examRecordData.examRecord.paperType,
        }
      );

      return qContentRes.data.masterVersion;
    },
    restoreAudio(str) {
      return (str || "")
        .replace(/<a/g, "<audio controls ")
        .replace(/url=/g, "src=")
        .replace(/a>/g, "audio>");
    },
    toChineseNumber(num) {
      return toChineseNumber(num);
    },
    indexToABCD(index) {
      return optionName[index];
    },
    rightAnswerToABCD(
      questionType,
      studentAnswer,
      optionPermutation,
      rightAnswer
    ) {
      if (studentAnswer === null) studentAnswer = [];
      if (["SINGLE_CHOICE", "MULTIPLE_CHOICE"].includes(questionType)) {
        // 学生的答案是字符串
        if (typeof studentAnswer === "string") {
          studentAnswer = studentAnswer.split("");
        }
        const t = studentAnswer
          .map(v => optionPermutation.indexOf(v - 0))
          .sort();
        let result = t.map(v => this.indexToABCD(v + "")).join("");

        if (rightAnswer && rightAnswer.join("") == studentAnswer.join(""))
          result +=
            '<i class="ivu-icon ivu-icon-md-checkmark" style="color: red"></i>';
        else if (rightAnswer && rightAnswer.join("") != studentAnswer.join(""))
          result +=
            '<i class="ivu-icon ivu-icon-md-close" style="color: red"></i>';

        return result;
      } else if (["TRUE_OR_FALSE"].includes(questionType)) {
        if (typeof studentAnswer === "string") {
          studentAnswer = [studentAnswer];
        }
        let result = { true: "正确", false: "错误" }[studentAnswer.join("")];
        result = result || "";
        if (rightAnswer && rightAnswer.join("") == studentAnswer.join(""))
          result +=
            '<i class="ivu-icon ivu-icon-md-checkmark" style="color: red"></i>';
        else if (rightAnswer && rightAnswer.join("") != studentAnswer.join(""))
          result +=
            '<i class="ivu-icon ivu-icon-md-close" style="color: red"></i>';

        return result;
      }
      let result =
        typeof studentAnswer === "string"
          ? studentAnswer
          : studentAnswer.join("");
      return result;
    },
  },
};
</script>

<style scoped>
.flex {
  display: flex;
}

.container {
  text-align: left;
  padding: 20px;
}

.question-wrapper {
  padding-bottom: 20px;
}
</style>
