<template>
  <el-dialog
    class="modify-mark-params"
    :visible.sync="modalIsShow"
    top="0"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    append-to-body
    fullscreen
    @open="initData"
  >
    <div slot="title">
      <h2 class="el-dialog__title">评卷参数设置</h2>
      <span
        >课程名称：{{ instance.courseName }}（{{ instance.courseCode }}）</span
      >
      <button class="el-dialog__headerbtn" @click="cancel"></button>
    </div>

    <div class="mb-4 tab-btns">
      <el-button
        v-for="tab in tabs"
        :key="tab.val"
        size="medium"
        :type="curTab == tab.val ? 'primary' : 'default'"
        :disabled="!basicInfoIsSave && tab.val !== 'structure'"
        @click="selectMenu(tab.val)"
        >{{ tab.name }}
      </el-button>
    </div>

    <div v-if="dataReady">
      <component
        :is="currentComponent"
        def="MarkParamRef"
        @cancel="cancel"
        @confirm="confirm"
      ></component>
    </div>
    <div slot="footer"></div>
  </el-dialog>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import MarkParamStructure from "./MarkParamStructure.vue";
import MarkParamMarker from "./MarkParamMarker.vue";
import MarkParamMarkerLeader from "./MarkParamMarkerLeader.vue";
import MarkParamObjectiveAnswer from "./MarkParamObjectiveAnswer.vue";
import MarkParamUploadAnswer from "./MarkParamUploadAnswer.vue";
import { cardDetail } from "../../../card/api";
import { examStructureStatus } from "../../api";

export default {
  name: "modify-mark-params",
  components: {
    MarkParamStructure,
    MarkParamMarker,
    MarkParamMarkerLeader,
    MarkParamObjectiveAnswer,
    MarkParamUploadAnswer,
  },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      dataReady: false,
      // step
      curTab: "structure",
      tabs: [
        {
          name: "评卷参数设置",
          val: "structure",
        },
        {
          name: "科组长设置",
          val: "marker-leader",
        },
        {
          name: "评卷员管理",
          val: "marker",
        },
        {
          name: "客观题标答设置",
          val: "objective-answer",
        },
        {
          name: "主观题标答设置",
          val: "upload-answer",
        },
      ],
      current: 0,
    };
  },
  computed: {
    ...mapState("markParam", ["markParamInfos"]),
    currentComponent() {
      return `mark-param-${this.curTab}`;
    },
    isFirstStep() {
      return this.current === 0;
    },
    isLastStep() {
      return this.current === this.lastStep;
    },
    lastStep() {
      return this.tabs.length - 1;
    },
    basicInfoIsSave() {
      return !!this.markParamInfos.basicPaperInfo.id;
    },
  },
  watch: {
    curTab() {
      this.updateMarkStatus();
    },
  },
  methods: {
    ...mapMutations("markParam", [
      "setMarkParamInfos",
      "setObjectiveStructure",
      "setMarkStatus",
      "setMarkLeader",
      "initStore",
    ]),
    async initData() {
      const basicPaperInfo = {
        ...this.instance,
        openClassReading: !!this.instance.openClassReading,
      };

      if (this.instance.paperInfoJson) {
        const { paperStructureInfo, groupInfo, classInfo, structureCanEdit } =
          JSON.parse(this.instance.paperInfoJson);
        const infos = {
          structureCanEdit,
          paperStructureInfo: [
            ...paperStructureInfo.objectiveQuestionList,
            ...paperStructureInfo.subjectiveQuestionList,
          ],
          groupInfo: groupInfo || [],
          classInfo: classInfo || [],
          basicPaperInfo,
        };
        this.setMarkParamInfos(infos);
      } else {
        const detData = await cardDetail(this.instance.cardId);
        const cardContent = JSON.parse(detData.content);
        let infos = { basicPaperInfo, structureCanEdit: true };
        if (
          (detData.type === "GENERIC" && detData.createMethod === "STANDARD") ||
          detData.type === "CUSTOM"
        ) {
          infos.structureCanEdit = false;
          infos.paperStructureInfo = this.parsePaperStructureFromCard(
            cardContent.pages
          );
        }
        // console.log(infos);
        this.setMarkParamInfos(infos);
      }

      if (this.instance.status) {
        const data = JSON.parse(this.instance.status);
        this.setMarkStatus(data);
      }

      if (this.instance.markLeader) {
        const data = JSON.parse(this.instance.markLeader);
        this.setMarkLeader(data);
      }

      const objectiveStructure = JSON.parse(
        this.instance.objectiveStructure || "[]"
      );
      this.setObjectiveStructure(objectiveStructure);

      this.selectMenu("structure");
      this.dataReady = true;
    },
    async updateMarkStatus() {
      if (!this.markParamInfos.basicPaperInfo.id) return;
      const res = await examStructureStatus(
        this.markParamInfos.basicPaperInfo.id
      ).catch(() => {});
      if (!res) return;

      const data = JSON.parse(res);
      this.setMarkStatus(data);
    },
    parsePaperStructureFromCard(pages) {
      let structData = [];
      let curTopicId = 0;
      pages.forEach((page) => {
        page.columns.forEach((column) => {
          column.elements.forEach((topic) => {
            if (!topic.parent) return;
            if (curTopicId === topic.parent.id) return;

            curTopicId = topic.parent.id;
            let questionsCount = 1,
              startNumber = 1;
            if (topic.type === "COMPOSITION") {
              // 相同大题号的作文题合并处理
              const compositionData = structData.find(
                (struct) =>
                  struct.cardTopicType === "COMPOSITION" &&
                  struct.mainNumber === topic.parent.topicNo * 1
              );
              if (compositionData) return;
            } else {
              questionsCount = topic.parent.questionsCount;
              startNumber = topic.parent.startNumber || 1;
            }
            const typeInfo = this.getQuestionType(topic);
            if (!typeInfo) return;

            let data = {
              mainNumber: topic.parent.topicNo * 1,
              mainTitle: topic.parent.topicName,
              questionsCount,
              startNumber,
              cardTopicType: topic.type,
              ...typeInfo,
            };
            if (topic.type === "FILL_QUESTION") {
              data.optionCount = topic.optionCount;
            }
            structData.push(data);
          });
        });
      });
      // console.log(structData);
      let structure = [];
      let mainIds = {};
      structData.forEach((struct) => {
        const { startNumber, questionsCount, qType, mainNumber, mainTitle } =
          struct;
        if (!mainIds[mainNumber]) {
          mainIds[mainNumber] = this.$randomCode();
        }
        for (let i = 0; i < questionsCount; i++) {
          structure.push({
            id: this.$randomCode(),
            qType,
            mainId: mainIds[mainNumber],
            mainTitle,
            mainNumber,
            subNumber: startNumber + i,
            type: struct.type,
            typeName: struct.typeName,
            optionCount: struct.optionCount || null,
            totalScore: undefined,
            mainFirstSub: false,
            expandSub: true,
          });
        }
      });
      structure.sort(
        (a, b) => a.mainNumber - b.mainNumber || a.subNumber - b.subNumber
      );
      let curMainId = null;
      structure.forEach((item) => {
        if (curMainId !== item.mainId) {
          curMainId = item.mainId;
          item.mainFirstSub = true;
        }
      });
      return structure;
    },
    getQuestionType(topic) {
      // const questionType = {
      //   1: "SINGLE_ANSWER_QUESTION",
      //   2: "MULTIPLE_ANSWER_QUESTION",
      //   3: "BOOL_ANSWER_QUESTION",
      //   4: "FILL_BLANK_QUESTION",
      //   5: "TEXT_ANSWER_QUESTION",
      // };
      if (topic.type === "COMPOSITION" || topic.type === "EXPLAIN") {
        return {
          type: 5,
          typeName: "解答题",
          qType: "subjective",
        };
      }
      if (topic.type === "FILL_LINE") {
        return {
          type: 4,
          typeName: "填空题",
          qType: "subjective",
        };
      }
      if (topic.type === "FILL_QUESTION") {
        if (topic.isBoolean)
          return {
            type: 3,
            typeName: "判断题",
            qType: "objective",
          };
        if (topic.isMultiply)
          return {
            type: 2,
            typeName: "多选题",
            qType: "objective",
          };
        return {
          type: 1,
          typeName: "单选题",
          qType: "objective",
        };
      }
      return;
    },
    selectMenu(val) {
      this.curTab = val;
      this.current = this.tabs.findIndex((item) => item.val === val);
    },
    async cancel() {
      const res = await this.$confirm("确定要退出阅卷参数编辑吗?", "提示", {
        type: "warning",
      }).catch(() => {});
      if (res !== "confirm") return;

      this.initStore();
      this.dataReady = false;
      this.$emit("modified");
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    confirm() {
      if (this.isLastStep) {
        this.selectMenu(this.tabs[0].val);
      } else {
        this.selectMenu(this.tabs[this.current + 1].val);
      }
    },
  },
};
</script>
