<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>
    <Modal v-if="showFaceId" v-model="showFaceId" :mask-closable="false" :closable="false">
      <FaceId />
      <p slot="footer">
      </p>
    </Modal>
  </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 FaceId from "./FaceId.vue";
import FaceRecognition from "../../../components/FaceRecognition/FaceRecognition";
import { createNamespacedHelpers } from "vuex";
const { mapState, mapMutations } = createNamespacedHelpers("examingHomeModule");

export default {
  name: "ExamingHome",
  data() {
    return { showFaceId: false };
  },
  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);
      });

    this.submitInterval = setInterval(
      () => this.answerAllQuestions(),
      1 * 60 * 1000
    );

    // this.$Modal.info({
    //   // title: "活体检测",
    //   header: "",
    //   footerHide: true,
    //   render: h => {
    //     return <FaceId />;
    //   }
    // });
  },
  destroyed() {
    clearInterval(this.submitInterval);
  },
  // beforeRouteUpdate(to, from, next) {
  //   this.updateQuestion(next);
  // },
  methods: {
    ...mapMutations(["updateExamState", "toggleSnapNow", "updateExamResult"]),
    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
      );

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

      // 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;
      });

      this.updateExamState({
        exam: exam.data,
        paperStruct: paperStruct.data,
        examQuestionList: examQuestionList
      });
    },
    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 answerAllQuestions() {
      // TODO: reset dirty
      const answers = this.examQuestionList.filter(eq => eq.dirty).map(eq => {
        return { order: eq.order, studentAnswer: eq.studentAnswer };
      });
      await this.$http.post(
        "/api/ecs_oe_student/examQuestion/submitQuestionAnswer",
        answers
      );
      // this.updateExamQuestion({
      //   order: this.$route.params.order,
      //   studentAnswer
      // });
    },
    async submitPaper() {
      //FIXME: submit precondition
      await this.answerAllQuestions();

      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();
      try {
        const res = await this.$http.get(
          "/api/ecs_oe_student/examControl/endExam"
        );
        if (res.status === 200) {
          this.updateExamResult({
            examRecordDataId: res.data.examRecordDataId,
            isWarn: res.data.isWarn,
            objectiveScore: res.data.objectiveScore
          });
          this.$router.push({
            path: `/online-exam/exam/${
              this.$route.params.examId
            }/examRecordData/${this.$route.params.examRecordDataId}/end`
          });
        }
      } catch (e) {
        console.log(e);
      }
    },
    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,
    FaceId
  }
};
</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>
