<template>
  <div v-if="afterExamRemark !== null" id="exam-end" class="container">
    <div class="instructions">
      <h1 class="">考试已结束</h1>
      <div><img class="user-avatar" :src="user.photoPath" alt="无底照" /></div>
      <div
        v-if="!examResult && getResultTimes <= 10"
        class="qm-big-text score-text"
      >
        考试结果计算中...
      </div>
      <div
        v-if="!examResult && getResultTimes > 10"
        class="qm-big-text score-text"
        style="font-size: 20px;"
      >
        请稍后在待考列表中查看客观题得分。
      </div>
      <div
        v-if="showObjectScore && (examResult && !examResult.isWarn)"
        class="qm-big-text score-text"
      >
        客观题得分:
        <span style="color: red">{{ examResult.objectiveScore }}</span>
      </div>
      <div
        v-if="
          exam &&
            exam.examType !== 'ONLINE' &&
            showObjectScore &&
            !examResult.isWarn
        "
        class="qm-big-text score-text"
      >
        客观题正确率:
        <span style="color: red">{{ examResult.objectiveAccuracy }}%</span>
      </div>
      <div
        v-if="examResult && examResult.isWarn"
        class="qm-big-text score-text"
      >
        客观题得分: 成绩待审核
      </div>
      <h1 v-if="examResult && examResult.isWarn" style="text-align: left;">
        违纪提示:
      </h1>
      <div
        v-if="examResult && examResult.isWarn"
        class=""
        style="text-align: left;  padding-bottom: 20px"
      >
        <p v-html="cheatingRemark"></p>
      </div>
      <h1 style="text-align: left;">考后说明:</h1>
      <div style="text-align: left;  padding-bottom: 20px">
        <p v-html="afterExamRemark"></p>
      </div>

      <router-link
        class="qm-primary-button"
        to="/online-exam"
        style="display: inline-block; width: 100%;"
      >
        返回主页
      </router-link>
    </div>
  </div>

  <div v-else>正在等待数据返回...</div>
</template>

<script>
import { mapState as globalMapState } from "vuex";
import { createNamespacedHelpers } from "vuex";
const { mapMutations } = createNamespacedHelpers("examingHomeModule");

export default {
  name: "ExamingEnd",
  data() {
    return {
      exam: null,
      afterExamRemark: null,
      showObjectScore: null,
      cheatingRemark: null,
      examResult: null,
      getResultTimes: 0,
    };
  },
  computed: {
    ...globalMapState(["user"]),
    // ...mapState(["exam"])
  },
  created() {
    this.$Message.destroy(); // 避免极端情况下，心跳过期的错误消息
  },
  async mounted() {
    window._hmt.push(["_trackEvent", "考试结束页面", "进入页面"]);
    const examRecordDataId = this.$route.params.examRecordDataId;
    const examId = this.$route.params.examId;
    this.waitingNumber = 0;
    const f = async () => {
      if (this.$route.name !== "ExamingEnd" || this.waitingNumber > 30) {
        // 非成绩页，不在查询成绩
        return;
      }
      try {
        this.getResultTimes = this.getResultTimes + 1;
        const examResult = (await this.$http.get(
          "/api/ecs_oe_student/examControl/getEndExamInfo?examRecordDataId=" +
            examRecordDataId
        )).data;

        if (
          examResult === undefined ||
          examResult === null ||
          examResult === ""
        ) {
          this.waitingNumber++;
          this.timeout = setTimeout(() => f(), 3000);
          return;
        }
        window._hmt.push([
          "_trackEvent",
          "考试结束页面",
          "等待分数",
          "等待次数=" + this.waitingNumber,
        ]);
        this.examResult = examResult;

        if (this.examResult.isWarn) {
          const cheatingRemark = await this.$http.get(
            "/api/ecs_exam_work/exam/examOrgPropertyFromCache4StudentSession/" +
              examId +
              `/CHEATING_REMARK`
          );
          this.cheatingRemark = cheatingRemark.data.CHEATING_REMARK || "";
        }
      } catch (error) {
        this.waitingNumber++;
        this.timeout = setTimeout(() => f(), 3000);
      }
    };
    await f();

    try {
      // if (!this.exam) {
      this.exam = (await this.$http.get(
        "/api/ecs_exam_work/exam/" + examId
      )).data;
      // }

      if (this.exam.examType === "PRACTICE") {
        this.$router.replace(
          `/online-practice/exam/${examId}/detail?examRecordDataId=${examRecordDataId}&disableGoBack=true`
        );
        return;
      }
      const afterExamRemark = await this.$http.get(
        "/api/ecs_exam_work/exam/examOrgPropertyFromCache4StudentSession/" +
          examId +
          `/AFTER_EXAM_REMARK`
      );
      this.afterExamRemark = afterExamRemark.data.AFTER_EXAM_REMARK || "";
      const showObjectScore = await this.$http.get(
        "/api/ecs_exam_work/exam/examOrgPropertyFromCache4StudentSession/" +
          examId +
          `/IS_OBJ_SCORE_VIEW`
      );
      this.showObjectScore =
        (showObjectScore.data.IS_OBJ_SCORE_VIEW &&
          JSON.parse(showObjectScore.data.IS_OBJ_SCORE_VIEW)) ||
        false;
    } catch (error) {
      this.$Message.error({
        content: "获取考试设置错误，请在待考列表查看成绩！",
        duration: 15,
        closable: true,
      });
      this.$router.push("/");
    }

    document.body.style = "";
  },
  beforeDestroy() {
    clearTimeout(this.timeout);

    this.updateExamState({
      exam: null,
      paperStruct: null,
      examQuestionList: null,
      questionAnswerFileUrl: [],
      pictureAnswer: {},
    });

    // 清除考试过程中存储的音频
    caches.open("audios").then(function(cache) {
      cache.keys().then(function(keys) {
        keys.forEach(function(request) {
          cache.delete(request);
        });
      });
    });
  },

  methods: {
    ...mapMutations(["updateExamState"]),
  },
};
</script>

<style scoped>
.container {
  margin: 0 auto;
  width: 80vw;
  overflow: auto;
}

.instructions {
  /* display: grid; */
  /* grid-template-rows: 40px 300px min(100px) 30px minmax(200px, auto) min(100px) min(
      100px
    ) min(100px); */
  padding: 40px 20px;
}

.instructions > h1,
.instructions > div {
  padding-bottom: 30px;
}

.user-avatar {
  display: inline-block;
  width: 140px;
  height: 140px;
  object-fit: contain;
}

.score-text {
  font-size: 40px;
}

/* .exam-detail {
  padding: 40px 20px;
  background-color: #f5f5f5;

  text-align: left;
} */
</style>

<style>
#exam-end img {
  max-width: 100%;
  height: auto !important;
}
</style>
