<template>
  <div class="nested-question">
    <div class="ep-question-title">
      <rich-text :text-json="question.body"></rich-text>
    </div>
    <div
      v-for="subq in question.subQuestions"
      :key="subq.id"
      class="ep-question-subq"
    >
      <component
        :is="getStructTypeComp(subq.questionType)"
        ref="QuestionEditDetail"
        :question="subq"
      ></component>
    </div>
  </div>
</template>

<script>
import { STRUCT_TYPE_COMP_DICT } from "../edit/questionModel";
import BooleanQuestion from "./BooleanQuestion.vue";
import FillBlankQuestion from "./FillBlankQuestion.vue";
import SelectQuestion from "./SelectQuestion.vue";
import TextAnswerQuestion from "./TextAnswerQuestion.vue";
import { BASE_QUESTION_TYPES } from "@/constants/constants";

export default {
  name: "NestedQuestion",
  components: {
    FillBlankQuestion,
    SelectQuestion,
    TextAnswerQuestion,
    BooleanQuestion,
  },
  props: {
    question: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalForm: {},
      BASE_QUESTION_TYPES,
      activeNames: [],
    };
  },
  computed: {
    IS_CLOZE() {
      return this.question.questionType === "CLOZE";
    },
    IS_LISTENING_QUESTION() {
      return this.question.questionType === "LISTENING_QUESTION";
    },
  },
  methods: {
    getStructTypeComp(questionType) {
      return STRUCT_TYPE_COMP_DICT[questionType];
    },
    async validate() {
      let errorQuestionIndexs = [];
      for (let i = 0; i < this.$refs.QuestionEditDetail.length; i++) {
        const compInst = this.$refs.QuestionEditDetail[i];
        const res = await compInst.validate().catch(() => {});
        if (!res) {
          errorQuestionIndexs.push(i + 1);
        }
      }
      if (errorQuestionIndexs.length) {
        this.$message.error(
          `请完成第${errorQuestionIndexs.join()}小题的编辑！`
        );
        return Promise.reject();
      }

      return true;
    },
    getData() {
      let data = { ...this.question, subQuestions: [] };
      if (!this.$refs.QuestionEditDetail) return;
      data.subQuestions = this.$refs.QuestionEditDetail.map((compInst) =>
        compInst.getData()
      );
      return data;
    },
  },
};
</script>
