<template>
  <div class="text-answer-question">
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item prop="quesBody" label="题干">
        <v-editor
          v-model="modalForm.quesBody"
          @change="quesBodyChange"
        ></v-editor>
      </el-form-item>
      <el-form-item prop="quesAnswer" label="答案">
        <v-editor v-model="quesAnswer" @change="answerChange"></v-editor>
      </el-form-item>
      <el-form-item label="答案解析">
        <v-editor v-model="modalForm.comment"></v-editor>
      </el-form-item>
    </el-form>
    <question-info-edit
      ref="QuestionInfoEdit"
      :question="modalForm"
      @change="questionInfoChange"
    ></question-info-edit>
  </div>
</template>

<script>
import { isAnEmptyRichText } from "@/utils/utils";
import { getInitQuestionModel } from "../model/questionModel";
import QuestionInfoEdit from "../QuestionInfoEdit.vue";

export default {
  name: "TextAnswerQuestion",
  components: { QuestionInfoEdit },
  props: {
    question: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalForm: {},
      rules: {
        quesBody: [
          {
            validator: (rule, value, callback) => {
              if (!value || isAnEmptyRichText(value)) {
                return callback(new Error(`请输入题干`));
              }
              callback();
            },
            trigger: "change",
          },
        ],
        quesAnswer: [
          {
            validator: (rule, value, callback) => {
              if (!this.quesAnswer || isAnEmptyRichText(this.quesAnswer)) {
                return callback(new Error(`请输入答案`));
              }
              callback();
            },
            trigger: "change",
          },
        ],
      },
      quesAnswer: null,
    };
  },
  created() {
    this.initData();
  },
  methods: {
    initData() {
      this.modalForm = this.$objAssign(
        getInitQuestionModel("TEXT_ANSWER_QUESTION"),
        this.question
      );
      this.modalForm.quesAnswer = this.question.quesAnswer
        ? JSON.parse(this.question.quesAnswer)
        : [];
      this.quesAnswer = this.modalForm.quesAnswer[0] || null;
    },
    quesBodyChange() {
      this.$refs.modalFormComp.validateField(`quesBody`, () => {});
    },
    answerChange() {
      this.modalForm.quesAnswer = [
        {
          index: 1,
          ...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 = { ...this.modalForm };
      data.quesAnswer = JSON.stringify(data.quesAnswer);
      return data;
    },
  },
};
</script>
