<template>
  <div class="match-question">
    <div
      :class="['ep-question-content', { 'is-active': isActive }]"
      @click="activeQuestion"
    >
      <div class="ep-question-title">
        <span class="ep-question-title-number">{{ question.number }}.</span>
        <rich-text :text-json="question.body"></rich-text>
      </div>
      <question-info-view
        v-if="!isActive"
        :question="getData()"
      ></question-info-view>
    </div>
    <div v-if="isActive" class="ep-question-props">
      <el-form
        ref="modalFormComp"
        :model="modalForm"
        :rules="rules"
        label-width="72px"
      >
        <el-form-item prop="quesAnswer" label="答案">
          <el-radio-group v-model="quesAnswer" @change="answerChange">
            <el-radio-button
              v-for="option in parentQuestion.options"
              :key="option.number"
              :label="option.number"
            >
              {{ (option.number - 1) | optionOrderWordFilter }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="答案解析">
          <v-editor
            v-model="modalForm.answerAnalysis"
            :enable-audio="false"
          ></v-editor>
        </el-form-item>
      </el-form>
      <question-info-edit
        ref="QuestionInfoEdit"
        :question="modalForm"
        label-width="72px"
        use-course-property-cache
        @change="questionInfoChange"
      ></question-info-edit>
    </div>
  </div>
</template>

<script>
import QuestionInfoEdit from "../QuestionInfoEdit.vue";
import QuestionInfoView from "./QuestionInfoView.vue";
import { getInitQuestionModel } from "./model";
import { mapState, mapMutations } from "vuex";
import { objTypeOf } from "@/plugins/utils";

export default {
  name: "MatchQuestion",
  components: { QuestionInfoEdit, QuestionInfoView },
  props: {
    question: {
      type: Object,
      default() {
        return {};
      },
    },
    parentQuestion: {
      type: Object,
      default() {
        return {
          options: [],
          questionType: "",
        };
      },
    },
  },
  data() {
    return {
      modalForm: {},
      quesAnswer: null,
      rules: {
        quesAnswer: [
          {
            validator: (rule, value, callback) => {
              if (!value || !value.length) {
                return callback(new Error(`请设置答案`));
              }
              callback();
            },
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {
    ...mapState("import-edit", ["curQuestion"]),
    isActive() {
      return this.curQuestion.id === this.question.id;
    },
    IS_PARAGRAPH_MATCHING() {
      return this.parentQuestion.questionType === "PARAGRAPH_MATCHING";
    },
  },
  created() {
    this.initData();
  },
  methods: {
    ...mapMutations("import-edit", ["setCurQuestion"]),
    initData() {
      this.modalForm = this.$objAssign(getInitQuestionModel(), this.question);
      this.modalForm.courseId = this.parentQuestion.courseId;
      this.initAnswer(this.question.quesAnswer);
      this.quesAnswer = this.modalForm.quesAnswer[0] || null;
    },
    initAnswer(answer) {
      let quesAnswer = [];
      if (answer) {
        try {
          quesAnswer = JSON.parse(answer);
        } catch (err) {
          console.log(`answer error：${answer}`);
        }
      }
      if (this.checkAnswerFormatValid(quesAnswer)) {
        this.modalForm.quesAnswer = quesAnswer;
      } else {
        this.modalForm.quesAnswer = [];
      }
    },
    checkAnswerFormatValid(answer) {
      if (objTypeOf(answer) !== "array") return;

      return !answer.some((item) => !/^[0-9]{1,2}$/.test(item));
    },
    answerChange() {
      this.modalForm.quesAnswer =
        this.quesAnswer || this.quesAnswer === 0 ? [this.quesAnswer] : [];
      this.$refs.modalFormComp.validateField(`quesAnswer`, () => {});
    },
    questionInfoChange(questionInfo) {
      this.modalForm = Object.assign({}, this.modalForm, questionInfo);
    },
    validate() {
      return this.$refs.modalFormComp.validate();
    },
    getData() {
      let data = Object.assign({}, this.question, this.modalForm);
      data.quesAnswer = JSON.stringify(this.modalForm.quesAnswer);
      return data;
    },
    activeQuestion() {
      this.setCurQuestion(this.question);
    },
  },
};
</script>
