<template>
  <div class="select-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 class="ep-question-body">
        <div
          v-for="(option, optionIndex) in options"
          :key="optionIndex"
          class="ep-question-option"
        >
          <div v-if="isActive" class="ep-question-option-check">
            <el-radio
              v-if="IS_SIMPLE"
              v-model="quesAnswer"
              :label="option.number"
              @change="answerChange"
            >
              {{ (option.number - 1) | optionOrderWordFilter }}.
            </el-radio>
            <el-checkbox
              v-else
              v-model="option.isCorrect"
              :label="option.number"
              @change="answerChange"
            >
              {{ (option.number - 1) | optionOrderWordFilter }}.
            </el-checkbox>
          </div>
          <div v-else class="ep-question-option-check">
            {{ (option.number - 1) | optionOrderWordFilter }}.
          </div>
          <rich-text :text-json="option.body"></rich-text>
        </div>
      </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 }} -->
          {{
            question.ignoreOptionRepeat && cont.includes("选项内容相同")
              ? ""
              : cont
          }}
          <el-button
            size="mini"
            type="primary"
            v-if="!question.ignoreOptionRepeat && cont.includes('选项内容相同')"
            @click.stop="setIgnore(question, index, true)"
            >忽略</el-button
          >
        </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"
        :rules="rules"
        label-width="72px"
      >
        <el-form-item prop="quesAnswer" label="答案">
          <span>{{ answer }}</span>
        </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 QuestionInfoEdit from "../QuestionInfoEdit.vue";
import QuestionInfoView from "./QuestionInfoView.vue";
import { getInitQuestionModel } from "./model";
import { mapState, mapMutations } from "vuex";
import { objTypeOf } from "@/plugins/utils";
import { isAnEmptyRichText } from "@/utils/utils";

export default {
  name: "SelectQuestion",
  components: { QuestionInfoEdit, QuestionInfoView },
  props: {
    question: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalForm: {},
      quesAnswer: null,
      options: [],
      rules: {
        quesAnswer: [
          {
            validator: (rule, value, callback) => {
              if (!value || !value.length) {
                return callback(new Error(`请设置答案`));
              }
              callback();
            },
            trigger: "change",
          },
        ],
      },
      answerAnalysis: null,
    };
  },
  computed: {
    ...mapState("import-edit", ["curQuestion"]),
    isActive() {
      return this.curQuestion.id === this.question.id;
    },
    IS_SIMPLE() {
      return this.question.questionType === "SINGLE_ANSWER_QUESTION";
    },
    answer() {
      if (!this.quesAnswer) return "";
      const quesAnswer = this.IS_SIMPLE ? [this.quesAnswer] : this.quesAnswer;
      return quesAnswer
        .map((value) => String.fromCharCode(64 + value))
        .join("");
    },
  },
  created() {
    this.initData();
  },
  methods: {
    ...mapMutations("import-edit", ["setCurQuestion"]),
    setIgnore(question, index, bool) {
      let targetQuestionException = question.questionExceptions[index];
      let exceptionIndex = targetQuestionException.exceptionIndex.toString();
      this.$bus.emit("markIgnoreRepeatQuestion", exceptionIndex, bool);
    },
    initData() {
      this.modalForm = this.$objAssign(getInitQuestionModel(), this.question);
      // 因为会缓存答案，所以会导致答案的格式完全不确定。
      // 可能之前识别是判断题，后来识别成选择题。答案格式的不一样，会导致异常
      this.initAnswer(this.question.quesAnswer);
      this.initAnswerAnalysis(this.question.answerAnalysis);
      if (this.IS_SIMPLE) {
        this.quesAnswer = this.modalForm.quesAnswer.length
          ? this.modalForm.quesAnswer[0]
          : null;
      } else {
        this.quesAnswer = this.modalForm.quesAnswer || [];
      }
      this.answerAnalysis = this.modalForm.answerAnalysis[0] || {
        sections: [],
      };
      this.options = this.question.options.map((item) => {
        let nitem = { ...item };
        nitem.isCorrect = this.modalForm.quesAnswer.includes(item.number);
        return nitem;
      });
    },
    initAnswer(answer) {
      let quesAnswer = [];
      if (answer) {
        try {
          quesAnswer = JSON.parse(answer);
        } catch (err) {
          console.log(`answer error：${answer}`);
        }
      }
      if (this.checkAnswerFormatValid(quesAnswer)) {
        if (this.IS_SIMPLE) {
          this.modalForm.quesAnswer =
            quesAnswer.length === 1 ? [quesAnswer[0]] : [];
        } else {
          this.modalForm.quesAnswer = quesAnswer.length >= 1 ? quesAnswer : [];
        }
      } else {
        this.modalForm.quesAnswer = [];
      }
    },
    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
      );
    },
    checkAnswerFormatValid(answer) {
      if (objTypeOf(answer) !== "array") return;

      return !answer.some((item) => !/^[0-9]{1,2}$/.test(item));
    },
    answerChange() {
      if (this.IS_SIMPLE) {
        this.modalForm.quesAnswer =
          this.quesAnswer || this.quesAnswer === 0 ? [this.quesAnswer] : [];
      } else {
        this.quesAnswer = this.options
          .filter((item) => item.isCorrect)
          .map((item) => item.number);
        this.modalForm.quesAnswer = this.quesAnswer;
      }
      this.$refs.modalFormComp.validateField(`answer`, () => {});
    },
    answerAnalysisChange() {
      this.modalForm.answerAnalysis = [
        {
          ...this.answerAnalysis,
        },
      ];
    },
    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);
      data.answerAnalysis =
        data.answerAnalysis && data.answerAnalysis?.length
          ? data.answerAnalysis[0]
          : { sections: [] };
      return data;
    },
    activeQuestion() {
      this.setCurQuestion(this.question);
    },
    unactiveQuestion() {
      this.setCurQuestion({});
    },
  },
};
</script>
