<template>
  <div class="question-import-paper-edit">
    <div
      v-for="(detail, dIndex) in paperData"
      :key="dIndex"
      class="ep-detail"
      :id="`detail-${dIndex}`"
    >
      <div class="ep-detail-head">
        <h3 class="ep-detail-title">
          {{ detail.number | numberToChaineseFilter }}、{{ detail.name }}
        </h3>
        <!-- <p class="ep-detail-desc"></p> -->
      </div>
      <div class="ep-detail-body">
        <div
          v-for="(question, qindex) in detail.questions"
          :key="qindex"
          class="ep-question"
        >
          <div class="ep-question-type">
            [题型：{{ question.sourceDetailName }}]
          </div>
          <div :id="`question-${question.id}`">
            <component
              :is="structTypeComp(question.questionType)"
              :ref="`QuestionEditDetail-${dIndex}-${qindex}-${question.id}`"
              :question="question"
            >
            </component>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { deepCopy, randomCode } from "@/plugins/utils";
import BooleanQuestion from "./import-edit/BooleanQuestion.vue";
import FillBlankQuestion from "./import-edit/FillBlankQuestion.vue";
import SelectQuestion from "./import-edit/SelectQuestion.vue";
import TextAnswerQuestion from "./import-edit/TextAnswerQuestion.vue";
import NestedQuestion from "./import-edit/NestedQuestion.vue";
import BankedClozeQuestion from "./import-edit/BankedClozeQuestion.vue";
import { STRUCT_TYPE_COMP_DICT } from "./edit/questionModel";
import { mapState } from "vuex";

export default {
  name: "QuestionImportPaperEdit",
  components: {
    FillBlankQuestion,
    SelectQuestion,
    TextAnswerQuestion,
    BooleanQuestion,
    NestedQuestion,
    BankedClozeQuestion,
  },
  props: {
    paper: {
      type: Array,
      default() {
        return [];
      },
    },
    courseId: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      paperData: [],
      questionContIndexList: [],
    };
  },
  computed: {
    ...mapState("import-edit", ["curQuestion"]),
  },
  watch: {
    curQuestion(val, oldval) {
      if (val && oldval && val.id !== oldval.id)
        this.updateQuestionContIndexTop();
    },
    paper() {
      this.transformPaperData();
      this.$nextTick(() => {
        this.updateQuestionContIndexTop();
      });
    },
  },
  mounted() {
    this.transformPaperData();
    this.$nextTick(() => {
      this.updateQuestionContIndexTop();
    });
  },
  methods: {
    structTypeComp(questionType) {
      return STRUCT_TYPE_COMP_DICT[questionType];
    },
    getQuestionInfo(question) {
      const exceptionField = ["bodyIndex", "optionIndex"];
      let exceptionIndexs = [];
      exceptionField.forEach((item) => {
        if (question.questionIndex[item])
          exceptionIndexs.push(...question.questionIndex[item]);
      });
      let exceptions = [];
      if (question.questionExceptions) {
        question.questionExceptions.forEach((item) => {
          if (
            item.exceptionIndex.some((key) => exceptionIndexs.includes(key))
          ) {
            exceptions.push(item.cause);
          }
        });
      }

      return {
        sourceDetailId: question.customizeQuestionType?.id,
        sourceDetailName: question.customizeQuestionType?.name,
        questionType: question.questionType,
        courseId: this.courseId,
        exceptions,
        score: question.score || 0,
        id: randomCode(),
      };
    },
    getQuestionContIndex(question) {
      const { id, questionIndex } = question;
      const questionId = `question-${id}`;
      const indexItems = ["bodyIndex", "optionIndex", "answerIndex"];
      let itemList = [];
      indexItems.forEach((item) => {
        let indexs = questionIndex[item];

        if (item === "answerIndex") {
          indexs = [];
          ["answerIndex", "difficultIndex", "propertyIndex"].forEach(
            (field) => {
              if (questionIndex[field] && questionIndex[field].length) {
                indexs.push(...questionIndex[field]);
              }
            }
          );
        }

        if (indexs && indexs.length) {
          itemList.push([questionId, item.replace("Index", ""), indexs, null]);
        }
      });

      return itemList;
    },
    transformPaperData() {
      let paperData = deepCopy(this.paper);
      let questionContIndexList = [];
      paperData.forEach((detail, dIndex) => {
        questionContIndexList.push([
          `detail-${dIndex}`,
          "detail",
          detail.detailIndex,
          null,
        ]);
        detail.questions.forEach((question) => {
          Object.assign(question, this.getQuestionInfo(question));
          questionContIndexList.push(...this.getQuestionContIndex(question));

          if (question.subQuestions && question.subQuestions.length) {
            question.subQuestions.forEach((subq) => {
              Object.assign(subq, this.getQuestionInfo(subq));
              questionContIndexList.push(...this.getQuestionContIndex(subq));
            });
          }
        });
      });
      this.paperData = paperData;
      this.questionContIndexList = questionContIndexList;
    },
    updateQuestionContIndexTop() {
      const elPos = this.$el.getBoundingClientRect();
      this.questionContIndexList.forEach((item) => {
        // item:[id,type,index,offsetTop];
        const [id, type] = item;
        let itemDom = document.getElementById(id);
        if (type === "body") {
          itemDom = itemDom.querySelector(".ep-question-title");
        } else if (type === "option") {
          itemDom = itemDom.querySelector(".ep-question-body");
        } else if (type === "answer") {
          itemDom =
            itemDom.querySelector(".question-info-view") ||
            itemDom.querySelector(".ep-question-props");
        }

        const itemPos = itemDom.getBoundingClientRect();
        item[3] = itemPos.y - elPos.y;
      });
    },
    getData() {
      this.paperData.forEach((detail, dIndex) => {
        detail.questions.forEach((question, qIndex) => {
          const refName = `QuestionEditDetail-${dIndex}-${qIndex}-${question.id}`;
          const questionData = this.$refs[refName][0].getData();
          Object.assign(question, questionData);
        });
      });
      return this.paperData;
    },
    // question
    questionActive(question) {
      this.activeQuestionId = question.id;
    },
    scrollToContentByIndex(indexs) {
      const questionCont = this.questionContIndexList.find((item) =>
        indexs.some((ind) => item[2].includes(ind))
      );
      if (!questionCont) return;
      const questionContDom = document.getElementById(questionCont[0]);
      const elPos = this.$el.getBoundingClientRect();
      const itemPos = questionContDom.getBoundingClientRect();
      const questionContOffsetTop = itemPos.y - elPos.y;
      this.$el.parentNode.scrollTop = questionContOffsetTop - 50;
    },
  },
};
</script>
