<template>
  <div v-if="exam" class="container" :key="exam.id">
    <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, index) in questionWrapper.questionUnitList"
            :key="index"
          >
            <div class="flex">
              <div>{{ questionWrapper.eqs[index].order }}、</div>
              <div v-html="restoreAudio(questionUnit.body)"></div>
            </div>
            <div
              v-for="(optionOrder, index) in questionWrapper.eqs[index]
                .optionPermutation"
              :key="index"
            >
              <div class="flex">
                <div>{{ indexToABCD(index) }}、</div>
                <div
                  v-html="
                    restoreAudio(
                      questionUnit.questionOptionList[optionOrder - 0].body
                    )
                  "
                ></div>
              </div>
            </div>

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

<script>
const optionName = "ABCDEFGHIJ".split("");

export default {
  name: "ExamPaper",
  data() {
    return {
      exam: null,
      questionGroupList: null,
      examQuestionList: null,
      practiceType: null
    };
  },
  props: {
    examId: Number,
    examRecordDataId: Number
  },
  async created() {
    await this.initData();
  },
  methods: {
    async initData() {
      const practiceType = (await this.$http.get(
        "/api/ecs_exam_work/exam/examOrgProperty/" +
          this.examId +
          `/PRACTICE_TYPE`
      )).data;
      this.practiceType = practiceType; // 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_student/examRecordPaperStruct/getExamRecordPaperStruct?examRecordDataId=" +
            this.examRecordDataId
        ),
        this.$http.get(
          "/api/ecs_oe_admin/examRecordQuestions/getExamRecordQuestions?examRecordDataId=" +
            this.examRecordDataId
        ),
        this.$http.get(
          "/api/ecs_oe_admin/exam/record/data/findExamRecordDataEntity?examRecordDataId=" +
            this.examRecordDataId
        ),
        this.$http.get(
          "/api/ecs_oe_student/practice/getPracticeDetailInfo?examRecordDataId=" +
            this.examRecordDataId
        )
      ]);
      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 num.toLocaleString("zh-u-nu-hanidec");
    },
    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>
