<template>
  <div class="remain-time">剩余时间 {{remainTimeFormatted}}</div>
</template>

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

export default {
  name: "RemainTime",
  data() {
    return {
      remainTime: null
    };
  },
  async mounted() {
    this.heartbeatErrorNum = 0;
    this.first = true;
    this.getRemainTimeFromServer();
    this.intervalA = setInterval(() => {
      // if (this.first) {
      //   // 跳过第一次
      //   this.first = false;
      //   return;
      // }
      this.getRemainTimeFromServer();
    }, 60 * 1000);
    this.intervalB = setInterval(
      () => (this.remainTime = this.remainTime - 1000),
      1000
    );
  },
  beforeDestroy() {
    clearInterval(this.intervalA);
    clearInterval(this.intervalB);
  },
  methods: {
    ...mapMutations(["setShouldSubmitPaper"]),
    async getRemainTimeFromServer() {
      try {
        const res = await this.$http.get(
          "/api/ecs_oe_student/examControl/examHeartbeat"
        );
        this.remainTime = res.data;
        // if (this.first) {
        //   this.remainTime += 60 * 1000; //补偿心跳
        // }
        this.heartbeatErrorNum = 0;
      } catch (e) {
        this.heartbeatErrorNum++;
        if (this.heartbeatErrorNum === 5) {
          // 心跳异常5次则退出考试
          this.$Modal.error({
            title: "网络连接异常",
            content: "退出考试",
            onOk: () => {
              this.$router.push("/login/" + localStorage.getItem("domain"));
            }
          });
          return;
        }
        this.getRemainTimeFromServer();
      }
    }
  },
  computed: {
    remainTimeFormatted: function() {
      return moment.utc(this.remainTime).format("HH:mm:ss");
    }
  },
  watch: {
    remainTime(val) {
      if (val < 0) {
        this.setShouldSubmitPaper();
      }
    }
  }
};
</script>
