<template>
  <el-dialog
    class="modify-mark-params"
    :visible.sync="modalIsShow"
    title="评卷参数设置"
    top="0"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    fullscreen
    :before-close="beforeClose"
    @open="visibleChange"
  >
    <el-steps
      class="mark-step"
      :active="current"
      align-center
      finish-status="success"
    >
      <el-step
        v-for="step in steps"
        :key="step.name"
        :title="step.title"
        :description="step.desc"
      >
      </el-step>
    </el-steps>

    <div class="mark-body" v-if="dataReady">
      <component
        :is="currentComponent"
        :ref="currentComponent"
        :datas="infos"
        @next-step="toNext"
        @on-ready="compReady"
        @data-change="dataChange"
      ></component>
    </div>

    <div class="text-center">
      <el-button
        v-if="!isFirstStep"
        type="primary"
        :disabled="loading"
        @click="prevStep"
        >上一步</el-button
      >
      <el-button
        v-if="isLastStep"
        type="success"
        :disabled="loading"
        @click="nextStep"
        >提交</el-button
      >
      <el-button v-else type="primary" @click="nextStep" :disabled="loading"
        >下一步</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>

    <div slot="footer"></div>
  </el-dialog>
</template>

<script>
import MarkPaperMarker from "./MarkPaperMarker.vue";
import MarkPaperStructure from "./MarkPaperStructure.vue";
// import paramData from "./paramData";
import { examStructureSubmit } from "../../api";
import { cardDetail } from "../../../card/api";
import { calcSum } from "@/plugins/utils";

const STEPS_LIST = [
  {
    name: "structure",
    title: "试卷结构",
    desc: "请按试卷填写相应试卷结构信息",
  },
  {
    name: "marker",
    title: "评卷员",
    desc: "请选择评卷老师及设置对应评卷题目",
  },
];

export default {
  name: "modify-mark-params",
  components: { MarkPaperMarker, MarkPaperStructure },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      infos: {
        basicPaperInfo: {},
        paperStructureInfo: [],
        groupInfo: [],
        paperStat: {},
      },
      // step
      steps: STEPS_LIST,
      current: 0,
      loading: false,
      dataReady: false,
    };
  },
  computed: {
    currentComponent() {
      return `mark-paper-${this.steps[this.current].name}`;
    },
    isFirstStep() {
      return this.current === 0;
    },
    isLastStep() {
      return this.current === this.lastStep;
    },
    lastStep() {
      return this.steps.length - 1;
    },
  },
  methods: {
    async visibleChange() {
      this.current = 0;
      this.loading = false;

      if (this.instance.paperInfoJson) {
        const { paperStructureInfo, groupInfo } = JSON.parse(
          this.instance.paperInfoJson
        );
        this.infos = {
          paperStructureInfo: [
            ...paperStructureInfo.objectiveQuestionList,
            ...paperStructureInfo.subjectiveQuestionList,
          ],
          groupInfo,
          basicPaperInfo: { ...this.instance },
        };
        this.infos.paperStat = this.statPaperStructure(
          this.infos.paperStructureInfo
        );
        this.dataReady = true;
        return;
      }

      const detData = await cardDetail(this.instance.cardId);
      const cardContent = JSON.parse(detData.content);
      this.infos = {
        paperStructureInfo: this.parsePaperStructureFromCard(cardContent.pages),
        groupInfo: [],
        basicPaperInfo: { ...this.instance },
        paperStat: this.statPaperStructure([]),
      };
      this.dataReady = true;
    },
    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);
          });
        });
      });
      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;
    },
    statPaperStructure(paperStructureInfo) {
      const questionCount = paperStructureInfo.length;

      const subjectiveQuestionCount = paperStructureInfo.filter(
        (item) => item.qType === "subjective"
      ).length;

      return {
        questionCount,
        paperTotalScore: calcSum(
          paperStructureInfo.map((item) => item.totalScore || 0)
        ),
        subjectiveQuestionCount,
        objectiveQuestionCount: questionCount - subjectiveQuestionCount,
        structChanged: false,
      };
    },
    async cancel() {
      const res = await this.$confirm("确定要退出阅卷参数编辑吗?", "提示", {
        type: "warning",
      }).catch(() => {});
      if (res !== "confirm") return;

      this.modalIsShow = false;
      this.dataReady = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async beforeClose(done) {
      const res = await this.$confirm("确定要退出阅卷参数编辑吗?", "提示", {
        type: "warning",
      }).catch(() => {});
      if (res !== "confirm") return;

      this.dataReady = false;
      done();
    },
    prevStep() {
      if (this.isFirstStep) return;
      this.$refs[this.currentComponent].updateData();
      this.current -= 1;
      if (this.steps[this.current].name === "structure") {
        this.$notify({
          title: "警告",
          message: "修改试卷结构会清空已经设置的评卷员，需要重新设置！",
          type: "warning",
          duration: 5000,
        });
      }
    },
    nextStep() {
      this.$refs[this.currentComponent].checkData();
    },
    toNext() {
      if (this.isLastStep) {
        this.submit();
      } else {
        const paperStat = this.infos.paperStat;

        let tipsContent = `本试卷共${paperStat.questionCount}道小题，客观题${paperStat.objectiveQuestionCount}道，主观题${paperStat.subjectiveQuestionCount}道，总分为${paperStat.paperTotalScore}分。`;
        if (paperStat.structChanged) {
          tipsContent += "试卷结构有变动，评卷员将被清空。";
        }
        if (paperStat.subjectiveQuestionCount) {
          this.$confirm(`${tipsContent}确定要下一步吗?`, "提示", {
            type: "warning",
          })
            .then(() => {
              this.current += 1;
            })
            .catch(() => {});
        } else {
          // 没有主观题，可以直接提交，不需要设置评卷员分组
          this.$confirm(`${tipsContent}, 是否立即提交?`, "提示", {
            type: "warning",
          })
            .then(() => {
              this.submit();
            })
            .catch(() => {});
        }
      }
    },
    getPaperStructData(paperStructureInfo) {
      let originStruct = [];
      let group = [];
      let curMainId = null;
      let curQType = null;
      paperStructureInfo.forEach((item) => {
        if (curMainId !== item.mainId) {
          curMainId = item.mainId;
          curQType = item.qType[0];
          if (group.length) originStruct.push(`${curQType}${group.length}`);
          group = [];
        }
        group.push(item);
      });
      if (group.length) originStruct.push(`${curQType}${group.length}`);
      return originStruct;
    },
    dataChange(data) {
      if (data.paperStructureInfo) {
        data.paperStat = this.statPaperStructure(data.paperStructureInfo);
      }
      if (data.paperStructureInfo && this.infos.paperStructureInfo.length) {
        // 检验试卷结构是否有变化
        const originStruct = this.getPaperStructData(
          this.infos.paperStructureInfo
        );
        const curStruct = this.getPaperStructData(data.paperStructureInfo);
        if (curStruct.join("") !== originStruct.join("")) {
          data.groupInfo = [];
          data.paperStat.structChanged = true;
        } else {
          // 更新分组中的试题信息
          const paperMap = {};
          data.paperStructureInfo.forEach((item) => {
            paperMap[`${item.mainNumber}-${item.subNumber}`] = item;
          });
          const groupInfo = this.infos.groupInfo.map((group) => {
            let ngroup = { ...group };
            ngroup.questions = ngroup.questions.map((q) => {
              return { ...paperMap[`${q.mainNumber}-${q.subNumber}`] };
            });
            return ngroup;
          });
          data.groupInfo = groupInfo;
        }
      }

      Object.entries(data).forEach(([key, val]) => {
        this.infos[key] = val;
      });
    },
    compReady(type = false) {
      this.loading = type;
    },
    getBaseInfo(baseInfo) {
      const data = this.$objAssign(
        {
          examPaperStructureId: null,
          examId: null,
          thirdRelateId: null,
          thirdRelateName: "",
          courseName: "",
          courseCode: "",
          paperNumber: null,
          paperType: "",
          sequence: null,
          status: "",
        },
        baseInfo
      );
      data.examPaperStructureId = baseInfo.id;
      return data;
    },
    async submit() {
      if (this.loading) return;
      const hasGroupNoPic = this.infos.groupInfo.some(
        (item) => !item.pictureConfigList.length
      );
      if (hasGroupNoPic) {
        const confirm = await this.$confirm(
          `当前评卷员分组中存在没有设置评卷区的分组, 确定要提交吗?`,
          "提示",
          {
            type: "warning",
          }
        ).catch(() => {});
        if (confirm !== "confirm") return;
      }

      this.loading = true;
      const datas = {
        basicPaperInfo: this.getBaseInfo(this.infos.basicPaperInfo),
        paperStructureInfo: {
          objectiveQuestionList: this.infos.paperStructureInfo.filter(
            (item) => item.qType === "objective"
          ),
          subjectiveQuestionList: this.infos.paperStructureInfo.filter(
            (item) => item.qType === "subjective"
          ),
        },
        groupInfo: this.infos.groupInfo,
      };
      const res = await examStructureSubmit(datas).catch(() => false);
      this.loading = false;

      if (!res) return;

      this.$message.success("提交成功！");
      this.$emit("modified");
      this.modalIsShow = false;
      this.dataReady = false;
    },
  },
};
</script>
