<template>
  <div class="fill-blank-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>
      <div v-if="question.exceptions.length" class="ep-question-exception">
        <p
          class="tips-info tips-error"
          v-for="(cont, index) in question.exceptions"
          :key="index"
        >
          {{ cont }}
        </p>
      </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" label-width="72px">
        <el-form-item label="答案"></el-form-item>
        <el-form-item
          v-for="(answer, oindex) in modalForm.quesAnswer"
          :key="oindex"
          label-width="12px"
        >
          <div class="question-edit-option">
            <div class="option-check">（{{ oindex + 1 }}）</div>
            <div class="option-body">
              <v-editor v-model="answer.body" :enable-audio="false"></v-editor>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="答案解析">
          <v-editor
            v-model="answerAnalysis"
            :enable-audio="false"
            @change="answerAnalysisChange"
          ></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 class="ep-question-props-close" @click="unactiveQuestion">
        <i class="el-icon-error"></i>
      </div>
    </div>
  </div>
</template>

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

export default {
  name: "FillBlankQuestion",
  components: { QuestionInfoEdit, QuestionInfoView },
  props: {
    question: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalForm: {},
      answerAnalysis: null,
    };
  },
  computed: {
    ...mapState("import-edit", ["curQuestion"]),
    isActive() {
      return this.curQuestion.id === this.question.id;
    },
  },
  created() {
    this.initData();
  },
  methods: {
    ...mapMutations("import-edit", ["setCurQuestion"]),
    initData() {
      this.modalForm = this.$objAssign(getInitQuestionModel(), this.question);
      this.initAnswerAnalysis(this.question.answerAnalysis);
      this.modalForm.quesAnswer = [];
      const quesAnswer = this.initAnswer(this.question.quesAnswer);

      if (!this.question.body || !this.question.body.sections) return;
      this.question.body.sections.forEach((section) => {
        section.blocks.forEach((block) => {
          if (block.type !== "cloze") return;
          const answerBody = quesAnswer[this.modalForm.quesAnswer.length] || {
            sections: [],
          };

          this.modalForm.quesAnswer.push({ body: answerBody });
        });
      });
      this.answerAnalysis = this.modalForm.answerAnalysis[0] || {
        sections: [],
      };
    },
    initAnswerAnalysis(answer) {
      let answerAnalysis = [];
      if (answer) {
        try {
          answerAnalysis = JSON.parse(answer);
        } catch (err) {
          console.log(`answer error：${answer}`);
        }
      }
      this.modalForm.answerAnalysis = answerAnalysis.map((item) =>
        isAnEmptyRichText(item)
          ? {
              sections: [],
            }
          : item
      );
    },
    answerAnalysisChange() {
      this.modalForm.answerAnalysis = [
        {
          ...this.answerAnalysis,
        },
      ];
    },
    initAnswer(answer) {
      let quesAnswer = [];
      if (answer) {
        try {
          quesAnswer = JSON.parse(answer);
        } catch (err) {
          console.log(`answer error：${answer}`);
        }
      }
      if (this.checkAnswerFormatValid(quesAnswer)) {
        return quesAnswer.map((item) =>
          isAnEmptyRichText(item) ? null : item
        );
      } else {
        return [];
      }
    },
    checkAnswerFormatValid(answer) {
      return objTypeOf(answer) === "array";
    },
    questionInfoChange(questionInfo) {
      this.modalForm = Object.assign({}, this.modalForm, questionInfo);
    },
    validate() {
      return Promise.resolve(true);
    },
    getData() {
      let data = Object.assign({}, this.question, this.modalForm);
      data.quesAnswer = data.quesAnswer.map((item, index) => {
        return {
          ...item.body,
          index,
        };
      });
      data.quesAnswer = JSON.stringify(data.quesAnswer);
      data.answerAnalysis =
        data.answerAnalysis && data.answerAnalysis?.length
          ? data.answerAnalysis[0]
          : { sections: [] };
      return data;
    },
    activeQuestion() {
      this.setCurQuestion(this.question);
    },
    unactiveQuestion() {
      this.setCurQuestion({});
    },
  },
};
</script>
