<template>
  <div class="build-paper-manual">
    <div class="build-step-title">
      <h3><span>大题设置</span></h3>
      <el-button
        type="primary"
        size="small"
        icon="el-icon-circle-plus-outline"
        @click="addDetail"
        >新增大题</el-button
      >
    </div>

    <el-collapse v-model="activeNames">
      <el-collapse-item
        v-for="(detail, dindex) in details"
        :key="detail.id"
        :name="detail.id"
      >
        <div slot="title" class="detail-header">
          <h3>
            {{ dindex + 1 }}、{{ detail.detailName }}（题目数量
            <span class="color-primary">{{ detail.questions.length }}</span
            >）
          </h3>
          <div>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              title="编辑"
              @click.stop="editDetail(detail)"
            ></el-button>
            <el-button
              class="btn-danger"
              size="mini"
              type="text"
              icon="el-icon-delete"
              title="删除"
              @click.stop="removeDetail(dindex)"
            ></el-button>
          </div>
        </div>
        <div v-if="detail.description" class="detail-desc">
          <rich-text :text-json="detail.description"></rich-text>
        </div>
        <div class="detail-questions">
          <template v-for="(question, qindex) in detail.questions">
            <build-paper-question-base
              v-if="checkIsBaseQuestion(question.questionType)"
              :key="question.id"
              v-model="question.score"
              :question="question"
              :question-serialno="qindex + 1"
              @on-edit="toEditQuestion"
              @on-remove="toRemoveQuestion"
            >
            </build-paper-question-base>
            <build-paper-question-nested
              v-else
              :key="question.id"
              :question="question"
              :question-serialno="qindex + 1"
              @on-edit="toEditQuestion"
              @on-remove="toRemoveQuestion"
            ></build-paper-question-nested>
          </template>
        </div>
        <el-button
          size="mini"
          type="success"
          icon="el-icon-circle-plus-outline"
          @click="toAddQuestion(detail)"
          >新增小题</el-button
        >
      </el-collapse-item>
    </el-collapse>

    <!-- ModifyDetailStruct -->
    <modify-detail-struct
      ref="ModifyDetailStruct"
      :detail="curDetail"
      @modified="detailModified"
    ></modify-detail-struct>
    <!-- SelectQuestionDialog -->
    <select-question-dialog
      ref="SelectQuestionDialog"
      :course-id="courseId"
      :source-detail="curDetail"
      disabled-source-detail
      :disabled-question-ids="disabledQuestionIds"
      @confirm="questionSelected"
    ></select-question-dialog>
    <!-- QuestionEditDialog -->
    <question-edit-dialog
      ref="QuestionEditDialog"
      :question="curQuestion"
      @modified="questionModified"
    ></question-edit-dialog>
  </div>
</template>

<script>
import ModifyDetailStruct from "../components/ModifyDetailStruct.vue";
import BuildPaperQuestionBase from "./BuildPaperQuestionBase.vue";
import BuildPaperQuestionNested from "./BuildPaperQuestionNested.vue";
import SelectQuestionDialog from "./SelectQuestionDialog.vue";
import QuestionEditDialog from "../../question/components/QuestionEditDialog.vue";
import { BASE_QUESTION_TYPES } from "@/constants/constants";

// import details from "../datas/details.json";

export default {
  name: "BuildPaperManual",
  components: {
    ModifyDetailStruct,
    BuildPaperQuestionBase,
    BuildPaperQuestionNested,
    SelectQuestionDialog,
    QuestionEditDialog,
  },
  props: {
    courseId: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      details: [],
      // details,
      curDetail: {},
      curQuestion: {},
      activeNames: [],
      disabledQuestionIds: [],
    };
  },
  methods: {
    checkIsBaseQuestion(questionType) {
      const qtype = BASE_QUESTION_TYPES.find(
        (item) => item.code === questionType
      );
      return !!qtype;
    },
    addDetail() {
      this.curDetail = { courseId: this.courseId };
      this.$refs.ModifyDetailStruct.open();
    },
    editDetail(curDetail) {
      this.curDetail = curDetail;
      this.$refs.ModifyDetailStruct.open();
    },
    async removeDetail(index) {
      const confirm = await this.$confirm(`确定要删除当前大题吗?`, "提示", {
        type: "warning",
      }).catch(() => {});
      if (confirm !== "confirm") return;

      const delDetailId = this.details[index].id;
      this.activeNames = this.activeNames.filter(
        (item) => item !== delDetailId
      );
      this.details.splice(index, 1);
    },
    detailModified(data) {
      const index = this.details.findIndex((item) => item.id === data.id);
      if (index === -1) {
        this.details.push({ ...data, questions: [] });
        if (!this.activeNames.includes(data.id)) this.activeNames.push(data.id);
      } else {
        this.$set(
          this.details,
          index,
          Object.assign({}, this.details[index], data)
        );
      }
    },
    toAddQuestion(detail) {
      this.curDetail = detail;
      let disabledQuestionIds = [];
      this.details.forEach((detail) => {
        detail.questions.forEach((q) => {
          disabledQuestionIds.push(q.id);
        });
      });
      this.disabledQuestionIds = disabledQuestionIds;
      this.$refs.SelectQuestionDialog.open();
    },
    questionSelected(questions) {
      questions.forEach((q) => {
        q.score = this.curDetail.scorePerQuestion;
      });
      this.curDetail.questions.push(...questions);
    },
    toEditQuestion(question) {
      this.curQuestion = question;
      this.$refs.QuestionEditDialog.open();
    },
    questionModified(question) {
      this.details.forEach((detail) => {
        const qindex = detail.questions.findIndex((q) => q.id === question.id);
        if (qindex !== -1) detail.questions.splice(qindex, 1, question);
      });
    },
    toRemoveQuestion(question) {
      this.details.forEach((detail) => {
        const qindex = detail.questions.findIndex((q) => q.id === question.id);
        if (qindex !== -1) detail.questions.splice(qindex, 1);
      });
    },
    getData() {
      let detailInfo = this.details.map((item) => {
        return {
          description: item.description,
          detailName: item.detailName,
          unitInfo: item.questions.map((q) => {
            return {
              questionId: q.id,
              score: q.score,
            };
          }),
        };
      });

      return { detailInfo };
    },
    validate() {
      if (!this.details.length) {
        this.$message.error("请设置大题！");
        return Promise.reject();
      }

      let hasNoQuestionDetail = this.details.some(
        (detail) => !detail.questions.length
      );
      if (hasNoQuestionDetail) {
        this.$message.error("有大题未设置小题！");
        return Promise.reject();
      }

      let hasNoScoreQuestion = this.details.some((detail) => {
        return detail.questions.some((q) => !q.score);
      });
      if (hasNoScoreQuestion) {
        this.$message.error("有小题未设置分数！");
        return Promise.reject();
      }

      return Promise.resolve(true);
    },
  },
};
</script>
