<template>
  <div v-if="isSyncState && examQuestion.questionType === 'MULTIPLE_CHOICE'" class="question-view">
    <question-body :questionBody="question.body" :examQuestion="examQuestion"></question-body>
    <div class="ops">
      <div class="stu-answer"> {{oldIndexToABCD}}</div>
      <div class="score">({{examQuestion.questionScore}}分)</div>
    </div>
    <div v-for="(option, index) in newQuestionOptions" :key="index" class="option" @click="toggleAnswer(option.oldIndex)">
      <input type="checkbox" name="question" value="option.oldIndex" :checked="studentAnswer && studentAnswer.includes(option.oldIndex)" />
      <span style="padding: 0 10px;">{{optionName[index]}}: </span>
      <span class="question-options" v-if="option.value" v-html="option.value.body"></span>
    </div>
    <div class="reset">
      <i-button type="warning" size="large" @click="() => answerQuestion(null)">重置答案</i-button>
      <span v-if="question.rightAnswer">
        &nbsp;&nbsp;&nbsp;<i-button type="info" size="large" @click="showAnswer">显示答案</i-button>
      </span>
      <div v-if="question.rightAnswer && isShowAnswer">
        正确答案：<div>{{rightAnswerTransform}}</div>
      </div>
    </div>
  </div>
</template>

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

const optionName = "ABCDEF".split("");
export default {
  name: "MultipleQuestionView",
  data() {
    return {
      questionBody: this.question.body,
      optionName,
      studentAnswer: this.examQuestion.studentAnswer || "",
      isShowAnswer: false
    };
  },
  props: {
    question: Object,
    examQuestion: Object
  },
  created: function() {
    window.addEventListener("keyup", this.keyup);
  },
  beforeDestroy() {
    window.removeEventListener("keyup", this.keyup);
  },
  beforeUpdate() {
    this.answerQuestion(this.studentAnswer);
  },
  methods: {
    ...mapMutations(["updateExamQuestion"]),
    keyup(e) {
      if (
        ["BODY", "A", "BUTTON", "DIV"].includes(
          document.activeElement.tagName
        ) ||
        (["INPUT"].includes(document.activeElement.tagName) &&
          ["checkbox", "radio"].includes(document.activeElement.type))
      ) {
        if (
          ["KeyA", "KeyB", "KeyC", "KeyD", "KeyE", "KeyF", "KeyG"]
            .slice(0, this.question.questionOptionList.length)
            .includes(e.code)
        ) {
          const selectedOldIndex =
            "" +
            this.newQuestionOptions.find(v => v.name == e.code[3]).oldIndex;
          if (this.studentAnswer.includes(selectedOldIndex)) {
            this.studentAnswer = this.studentAnswer.replace(
              selectedOldIndex,
              ""
            );
          } else {
            this.studentAnswer = this.studentAnswer
              .concat(selectedOldIndex)
              .split("")
              .sort()
              .join("");
          }
        }
      }
    },
    toggleAnswer: function(selectedOldIndex) {
      if (this.studentAnswer.includes(selectedOldIndex)) {
        this.studentAnswer = this.studentAnswer.replace(selectedOldIndex, "");
      } else {
        this.studentAnswer = this.studentAnswer
          .concat(selectedOldIndex)
          .split("")
          .sort()
          .join("");
      }
    },
    async answerQuestion(studentAnswer) {
      let realAnswer = studentAnswer;
      if (studentAnswer === "") {
        realAnswer = null;
      }
      if (realAnswer !== this.examQuestion.studentAnswer) {
        this.updateExamQuestion({
          order: this.examQuestion.order,
          studentAnswer: realAnswer
        });
      }
    },
    showAnswer() {
      this.isShowAnswer = !this.isShowAnswer;
    }
  },
  watch: {
    examQuestion: function() {
      this.studentAnswer = this.examQuestion.studentAnswer || "";
    }
  },
  computed: {
    isSyncState() {
      return this.examQuestion.order == this.$route.params.order;
    },
    newQuestionOptions() {
      return this.question.questionOptionList.map((v, i) => {
        return {
          value: this.question.questionOptionList[
            this.examQuestion.optionPermutation[i]
          ],
          oldIndex: "" + this.examQuestion.optionPermutation[i],
          name: optionName[i]
        };
      });
    },
    oldIndexToABCD() {
      return (
        this.examQuestion.studentAnswer &&
        this.newQuestionOptions
          .filter(v => this.examQuestion.studentAnswer.includes(v.oldIndex))
          .map(v => v.name)
          .join("")
      );
    },
    rightAnswerTransform() {
      return (
        this.question.rightAnswer &&
        this.newQuestionOptions
          .filter(v => this.question.rightAnswer.includes(v.oldIndex))
          .map(v => v.name)
          .join("")
      );
    }
  },
  components: {
    QuestionBody
  }
};
</script>

<style scoped>
.question-view {
  display: grid;
  grid-row-gap: 10px;
}

.question-body {
  font-size: 18px;
  margin-bottom: 10px;
}

.ops {
  display: flex;
  align-items: flex-end;
}

.stu-answer {
  width: 100px;
  border-bottom: 1px solid black;
  text-align: center;
  height: 20px;
}

.option {
  display: flex;
}
.question-options {
  text-align: left;
}
</style>
