<template>
  <div class="question-view">
    <question-body :questionBody="question.body" :examQuestionId="examQuestion.id"></question-body>
    <div class="ops">
      <div class="stu-answer">{{stuAnswer}}</div>
      <div class="score">({{question.questionScore}}分)</div>
    </div>
    <div v-for="(option, index) in question.options" :key="option.id" class="option" @click="answerQuestion(examQuestion.id, optionName[index])">
      <input type="radio" name="question" value="optionName[index]" :checked="stuAnswer === optionName[index]" />
      <span style="padding: 0 10px;">{{optionName[index]}}: </span>
      <span class="question-options" v-html="option.content"></span>
    </div>
    <div class="reset">
      <i-button type="warning" size="large" @click="resetQuestion(examQuestion.id)">重置答案</i-button>
    </div>
  </div>
</template>

<script>
import QuestionBody from "./QuestionBody";

const optionName = ["A", "B", "C", "D", "E", "F"];
export default {
  name: "SingleQuestionView",
  data() {
    return {
      optionName,
      stuAnswer: this.examQuestion.stuAnswer
    };
  },
  props: {
    question: Object,
    examQuestion: Object
  },
  created: function() {
    window.addEventListener("keyup", this.keyup);
  },
  destroyed() {
    window.removeEventListener("keyup", this.keyup);
  },
  methods: {
    keyup(e) {
      // console.log(e);
      // console.log(document.activeElement.type);
      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.options.length)
            .includes(e.code)
        ) {
          this.stuAnswer = e.code[3];
          this.answerQuestion(this.examQuestion.id, this.stuAnswer);
        }
      }
    },
    answerQuestion: function(examQuestionId, stuAnswer) {
      this.stuAnswer = stuAnswer;
      this.$http.put("/api/exam_question/" + examQuestionId, { stuAnswer });
    },
    resetQuestion: function(examQuestionId) {
      this.stuAnswer = null;
      this.$http.put("/api/exam_question/" + examQuestionId, {
        stuAnswer: null
      });
    }
  },
  watch: {
    examQuestion: function() {
      this.stuAnswer = this.examQuestion.stuAnswer;
    }
  },
  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>
