<template>
  <div v-if="!!!loading" id="exam-end" class="container">
    <div class="instructions">
      <h1 class="">考试已结束</h1>
      <div><img class="user-avatar" :src="user.photoPath" alt="无底照" /></div>
      <div v-if="showObjectScore">
        <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="examResult">
          <div v-if="!examResult.isWarn" class="qm-big-text score-text">
            客观题得分:
            <span style="color: red">{{ examResult.objectiveScore }}</span>
          </div>
          <div v-if="examResult.isWarn" class="qm-big-text score-text">
            客观题得分: 成绩待审核
          </div>
          <h1
            v-if="showCheatingRemark && examResult.isWarn"
            style="text-align: left;"
          >
            违纪提示:
          </h1>
          <div
            v-if="showCheatingRemark && examResult.isWarn"
            class=""
            style="text-align: left;  padding-bottom: 20px"
          >
            <p v-html="cheatingRemark"></p>
          </div>
        </div>
      </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="backTo"
        style="display: inline-block; width: 100%;"
        ondragstart="return false;"
      >
        返回主页
      </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 {
      loading: true,
      exam: null,
      afterExamRemark: null,
      cheatingRemark: null,
      showObjectScore: null,
      showCheatingRemark: null,
      examResult: null,
      getResultTimes: 0,
    };
  },
  computed: {
    ...globalMapState(["user"]),
    // ...mapState(["exam"])
    backTo() {
      const examType = this.exam && this.exam.examType;
      if (examType === "PRACTICE") {
        return "/online-practice";
      } else if (examType === "ONLINE_HOMEWORK") {
        return "/online-homework";
      }

      return "/online-exam";
    },
  },
  created() {
    this.$Message.destroy(); // 避免极端情况下，心跳过期的错误消息
  },
  async mounted() {
    window._hmt.push(["_trackEvent", "考试结束页面", "进入页面"]);
    const examRecordDataId = this.$route.params.examRecordDataId;
    const examId = this.$route.params.examId;

    try {
      this.loading = true;
      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 resp = await this.$http.get(
        "/api/ecs_exam_work/exam/getExamPropertyFromCacheByStudentSession/" +
          examId +
          `/AFTER_EXAM_REMARK,IS_OBJ_SCORE_VIEW,SHOW_CHEATING_REMARK,CHEATING_REMARK`
      );
      this.afterExamRemark = resp.data.AFTER_EXAM_REMARK || "";
      this.cheatingRemark = resp.data.CHEATING_REMARK || "";
      this.showObjectScore = resp.data.IS_OBJ_SCORE_VIEW === "true";
      this.showCheatingRemark = resp.data.SHOW_CHEATING_REMARK === "true";

      this.loading = false;
    } catch (error) {
      window._hmt.push([
        "_trackEvent",
        "考试结束页面",
        "获取考试设置错误，请在待考列表查看成绩！",
      ]);
      this.$Message.error({
        content: "获取考试设置错误，请在待考列表查看成绩！",
        duration: 15,
        closable: true,
      });
      this.$router.push("/");
    }

    document.body.style = "";

    await this.getExamResult();
  },
  beforeDestroy() {
    clearTimeout(this.timeout);

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

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

  methods: {
    ...mapMutations(["updateExamState"]),
    async getExamResult() {
      const examRecordDataId = this.$route.params.examRecordDataId;
      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;
        } catch (error) {
          this.waitingNumber++;
          this.timeout = setTimeout(() => f(), 3000);
        }
      };
      await f();
    },
  },
};
</script>

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

.instructions {
  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;
}
</style>

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