<template>
  <div class="question-container">
    <div class="question-header">
      <Icon
        :type="examQuestion.isSign ? 'ios-star' : 'ios-star-outline'"
        :style="{ color: '#ffcc00' }"
        class="star"
        @click="toggleSign"
      />
      <question-index
        v-if="examQuestion.getQuestionContent"
        :exam-question="examQuestion"
      />
    </div>
    <split-pane
      v-if="parentQuestionBody"
      :min-percent="10"
      :default-percent="parentPaneHeight"
      split="horizontal"
    >
      <template slot="paneL">
        <div v-if="parentQuestionBody" class="question-view parent-question">
          <question-body
            :key="examQuestion.questionId"
            :question-body="parentQuestionBody"
            :exam-question="examQuestion"
            style="margin-bottom: 20px"
          ></question-body>
          <!-- <div class="hr" /> -->
        </div>
      </template>
      <template slot="paneR">
        <QuestionViewSingle
          :question="question"
          :exam-question="examQuestion"
        />
      </template>
    </split-pane>

    <QuestionViewSingle
      v-if="!parentQuestionBody"
      :question="question"
      :exam-question="examQuestion"
    />

    <div v-if="!examQuestion.getQuestionContent">试题获取中...</div>
  </div>
</template>

<script>
import QuestionIndex from "./QuestionIndex";
import QuestionBody from "./QuestionBody";
import QuestionViewSingle from "./QuestionViewSingle";
import { createNamespacedHelpers } from "vuex";
const { mapState, mapMutations } = createNamespacedHelpers("examingHomeModule");
import splitPane from "vue-splitpane";

export default {
  name: "QuestionView",
  components: {
    QuestionIndex,
    QuestionBody,
    "split-pane": splitPane,
    QuestionViewSingle,
  },
  props: {
    examQuestion: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      parentQuestionBody: null,
      question: null,
      parentPaneHeight: 50,
    };
  },
  computed: {
    ...mapState(["examQuestionList"]),
  },
  watch: {
    $route: function(to, from) {
      this.updateQuestion(to, from);
    },
  },
  created() {
    this.updateQuestion();
  },
  mounted() {},
  methods: {
    ...mapMutations(["updateExamQuestion"]),
    async updateQuestion(to, from) {
      const currentExamQuestion = this.examQuestion; // 避免以后执行时，this.examQuestion换掉了
      const examRecordDataId = this.$route.params.examRecordDataId;
      // if(this.examQuestion.questionId) {
      //   this.parentQuestionBody = null;
      //         this.question = null;
      // }
      // console.log(from, to);
      if (from && to) {
        const orderFrom = from.params.order - 1;
        const toFrom = to.params.order - 1;
        if (
          this.examQuestionList[orderFrom].questionId !==
          this.examQuestionList[toFrom].questionId
        ) {
          this.parentQuestionBody = null;
          this.question = null;
        }
      }
      let qContentRes = null;
      try {
        qContentRes = await this.$http.get(
          "/api/ecs_oe_student/examQuestion/getQuestionContent?questionId=" +
            currentExamQuestion.questionId +
            "&exam_record_id=" +
            examRecordDataId
        );
      } catch (e) {
        if (currentExamQuestion.order != this.$route.params.order) {
          // 如果网络异常，又离开本页面后，不再后续处理此请求
          console.log(
            "QuestionView: 如果网络异常，又离开本页面后，不再后续处理此请求 "
          );
          return;
        }
        this.parentQuestionBody = null;
        this.question = null;
        return;
      }

      if (currentExamQuestion.order != this.$route.params.order) {
        console.log(
          "试题获取内容后，发现页面已经切到别的题目上去了，放弃后续渲染. 获取的eq.order/$route.order" +
            currentExamQuestion.order +
            "/" +
            this.$route.params.order
        );
        return;
      }
      const question = qContentRes.data;

      this.updateExamQuestion({
        order: currentExamQuestion.order,
        getQuestionContent: true,
      });

      const transferWellNumberAndTrustInBody = function(repQuestion) {
        //将题干中的三个#替换为下划线
        if (repQuestion.body) {
          repQuestion.body = repQuestion.body
            .toString()
            .replace(new RegExp("###", "g"), "_______");
          //将题干中的两个##数字##替换为下划线
          // var baseIndex = examQuestion.orders - 1;
          repQuestion.body = repQuestion.body
            .toString()
            .replace(/##(\d+)##/g, function(a, b) {
              return "__" + parseInt(b) + "__";
            });
        }
        // console.log(repQuestion);
      };
      const initQuestion = function(repQuestion) {
        if (
          repQuestion.questionType === "SINGLE_CHOICE" ||
          repQuestion.questionType === "MULTIPLE_CHOICE"
        ) {
          for (
            var i = 0, imax = repQuestion.questionOptionList.length;
            i < imax;
            i++
          ) {
            // repQuestion.options[i].content = $sce.trustAsHtml(
            //   repQuestion.options[i].content
            // );
          }
        }
        if (repQuestion.questionType === "FILL_UP") {
          if (repQuestion.answer && repQuestion.answer.indexOf("##") > -1) {
            //优先使用##
            repQuestion.answerList = repQuestion.answer.split("##");
          } else {
            repQuestion.answerList = [repQuestion.answer];
          }
        }

        transferWellNumberAndTrustInBody(repQuestion);
      };

      //判断是否为套题
      if (question.body) {
        transferWellNumberAndTrustInBody(question);
        for (
          var j = 0, jmax = question.questionUnitList.length;
          j < jmax;
          j++
        ) {
          initQuestion(question.questionUnitList[j]);
        }
        this.parentQuestionBody = question.body;
      } else {
        this.parentQuestionBody = null;
        initQuestion(
          question.questionUnitList[currentExamQuestion.subNumber - 1]
        );
      }

      this.question =
        question.questionUnitList[currentExamQuestion.subNumber - 1];

      // 对于某些图片套题，会导致高度计算错误，需多次nextTick
      this.$nextTick(() => {
        this.$nextTick(() => {
          // 从非套题进入套题时，会根据套题的内容动态调整套题的默认高度
          const parentQuestion = document.getElementsByClassName(
            "parent-question"
          )[0];
          if (parentQuestion) {
            this.parentPaneHeight =
              5 +
              (100 * parentQuestion.clientHeight) /
                (document.body.clientHeight - 160);
            if (this.parentPaneHeight > 60) {
              this.parentPaneHeight = 60;
            }
          }
        });
      });
      {
        // cache next question content
        const currentOrder = currentExamQuestion.order;
        if (currentOrder < this.examQuestionList.length) {
          this.$http.get(
            "/api/ecs_oe_student/examQuestion/getQuestionContent?questionId=" +
              this.examQuestionList[currentOrder].questionId +
              "&exam_record_id=" +
              examRecordDataId
          );
        }
      }
    },
    async toggleSign() {
      this.updateExamQuestion({
        order: this.$route.params.order,
        isSign: !this.examQuestion.isSign,
      });
    },
  },
};
</script>

<style scoped>
.question-container {
  overflow: auto;
}
.question-container >>> .splitter-pane {
  overflow: auto;
}
.question-container >>> .vue-splitter-container {
  height: calc(100% - 42px);
}
.question-container >>> .splitter-pane-resizer.horizontal {
  height: 15px;
}
.question-view {
  padding: 20px 30px;
  font-size: 16px;
  text-align: left;
  overflow: auto;
}

.question-header {
  display: flex;
  align-items: center;
}

.star {
  font-size: 36px;
  align-self: flex-start;
}
.star:hover {
  cursor: pointer;
}

div.hr {
  border-bottom: 1px dashed gray;
}
</style>
