<template>
  <div v-if="exam && examQuestion()" class="container">
    <div class="header">
      <RemainTime></RemainTime>
      <OverallProgress :exam-question-list="examQuestionList"></OverallProgress>
      <QuestionFilters :exam-question-list="examQuestionList"></QuestionFilters>
      <Button class="qm-primary-button" @click="submitPaper">交卷</Button>
    </div>
    <div class="main">
      <QuestionView :exam-question="examQuestion()"></QuestionView>
      <ArrowNavView :previousQuestionOrder="previousQuestionOrder" :nextQuestionOrder="nextQuestionOrder"></ArrowNavView>
    </div>
    <div class="side">
      <div class="question-nav">
        <QuestionNavView :paperStruct="paperStruct" />
      </div>
      <div class="camera">
        <!-- <FaceRecognition width="100%" height="100%" :showRecognizeButton="false" /> -->
      </div>
    </div>
  </div>
</template>

<script>
import RemainTime from "./RemainTime.vue";
import OverallProgress from "./OverallProgress.vue";
import QuestionFilters from "./QuestionFilters.vue";
import QuestionView from "./QuestionView.vue";
import ArrowNavView from "./ArrowNavView.vue";
import QuestionNavView from "./QuestionNavView.vue";
import FaceRecognition from "../../../components/FaceRecognition/FaceRecognition";
import { createNamespacedHelpers } from "vuex";
const { mapState, mapMutations } = createNamespacedHelpers("examingHomeModule");

export default {
  name: "ExamingHome",
  created() {
    this.initData();
    if (!this.$route.params.order) {
      // created can access this.$route?
      this.$router.push(this.$route.fullPath + "/order/1");
      return;
    }

    setTimeout(() => {
      this.toggleSnapNow();
    }, 60 * 1000); // 一分钟后抓拍

    this.$http
      .get(
        "/api/ecs_exam_work/exam/examOrgProperty/" +
          this.$route.params.examId +
          `/SNAPSHOT_INTERVAL`
      )
      .then(res => {
        // console.log(res);
        if (res.data) {
          // 考务设置抓拍间隔
          setInterval(() => {
            this.toggleSnapNow();
          }, res.data * 60 * 1000);
        }
      })
      .catch(reason => {
        this.$Message.error(reason);
      });
  },
  // beforeRouteUpdate(to, from, next) {
  //   this.updateQuestion(next);
  // },
  methods: {
    ...mapMutations(["updateExamState", "toggleSnapNow"]),
    async initData() {
      const exam = await this.$http.get(
        "/api/ecs_exam_work/exam/" + this.$route.params.examId
      );
      const paperStruct = await this.$http.get(
        "/api/ecs_oe_student/examRecordPaperStruct/getExamRecordPaperStruct?examRecordDataId=" +
          this.$route.params.examRecordDataId
      );

      const examQuestionList = await this.$http.get(
        "/api/ecs_oe_student/examQuestion/findExamQuestionList"
      );

      this.updateExamState({
        exam: exam.data,
        paperStruct: paperStruct.data,
        examQuestionList: examQuestionList.data
      });
    },
    updateQuestion: async function(next) {
      // 初始化套题的答案，为回填部分选项做准备
      // for (let q of this.examQuestionList) {
      //   if (q.subQuestionList.length > 0) {
      //     q.studentAnswer = [];
      //     for (let sq of q.subQuestionList) {
      //       q.studentAnswer.push(sq.studentAnswer);
      //     }
      //   }
      // }

      next && next();
      if (!this.exam) return;
    },
    async submitPaper() {
      //FIXME: submit precondition

      const answered = this.examQuestionList.filter(
        q => q.studentAnswer !== null
      ).length;
      const unanswered = this.examQuestionList.filter(
        q => q.studentAnswer === null
      ).length;
      this.$Modal.confirm({
        title: "确认交卷",
        content: `<p>已答题目：${answered}</p><p>未答题目：${unanswered}</p>`,
        onOk: this.realSubmitPaper
      });
    },
    async realSubmitPaper() {
      this.toggleSnapNow();
      await this.$http.get("/api/ecs_oe_student/examControl/endExam");
      this.$router.push({
        path: `/online-exam/exam/${this.$route.params.examId}/examRecordData/${
          this.$route.params.examRecordDataId
        }/end`
      });
    },
    examQuestion() {
      return (
        this.examQuestionList &&
        this.examQuestionList.find(
          eq => eq.order == this.$route.params.order // number == string
        )
      );
    }
  },
  computed: {
    ...mapState([
      "exam",
      "paperStruct",
      "examQuestionList",
      "snapNow",
      "shouldSubmitPaper"
    ]),
    previousQuestionOrder: vm => {
      if (vm.examQuestion().order > 1) {
        return vm.examQuestion().order - 1;
      } else {
        return null;
      }
    },
    nextQuestionOrder: vm => {
      if (vm.examQuestion().order < vm.examQuestionList.length) {
        return vm.examQuestion().order + 1;
      } else {
        return null;
      }
    }
  },
  watch: {
    $route: function() {
      this.examQuestion();
    },
    shouldSubmitPaper() {
      this.realSubmitPaper();
    }
    // examQuestionList(val, oldVal) {
    //   // console.log(val, oldVal);
    // }
  },
  components: {
    RemainTime,
    OverallProgress,
    QuestionFilters,
    QuestionView,
    ArrowNavView,
    QuestionNavView,
    FaceRecognition
  }
};
</script>

<style scoped>
.container {
  display: grid;
  grid-template-areas:
    "header header"
    "main side";
  grid-template-rows: 80px 1fr;
  grid-template-columns: 1fr 400px;

  height: 100vh;
  width: 100vw;
}

.header {
  display: grid;
  place-items: center;
  grid-template-columns: 200px 1fr 300px 100px;
  grid-area: header;
  height: 80px;
  background-color: #f5f5f5;
}

.main {
  display: grid;
  grid-area: main;
  grid-template-rows: 1fr 50px;
}

.side {
  display: grid;
  grid-area: side;
  grid-template-rows: 1fr 300px;
  background-color: #f5f5f5;
}

.camera {
  align-self: flex-end;
  justify-self: flex-end;
}

@media screen and (max-height: 768px) {
  .container {
    grid-template-rows: 50px 1fr;
  }
  .header {
    height: 50px;
  }
  .side {
    grid-template-rows: 1fr 200px;
  }
}
</style>
