<template>
  <div class="mark-param-structure">
    <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="primary"
        :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>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";

import MarkPaperGroup from "./MarkPaperGroup.vue";
import MarkPaperStructure from "./MarkPaperStructure.vue";
import { examStructureSubmit } from "../../api";
import { calcSum, deepCopy } from "@/plugins/utils";

const STEPS_LIST = [
  {
    name: "structure",
    title: "试卷结构",
    desc: "请按试卷填写相应试卷结构信息",
  },
  {
    name: "group",
    title: "评卷分组",
    desc: "请设置评卷分组",
  },
];

export default {
  name: "mark-param-structure",
  components: { MarkPaperGroup, MarkPaperStructure },
  data() {
    return {
      infos: {
        basicPaperInfo: {},
        paperStructureInfo: [],
        groupInfo: [],
        paperStat: {},
        structureCanEdit: true,
      },
      // step
      steps: STEPS_LIST,
      current: 0,
      loading: false,
      dataReady: false,
    };
  },
  computed: {
    ...mapState("markParam", ["markParamInfos", "objectiveStructure"]),
    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;
    },
  },
  mounted() {
    this.initData();
  },
  methods: {
    ...mapMutations("markParam", [
      "setMarkParamInfos",
      "setObjectiveStructure",
    ]),
    async initData() {
      this.current = 0;
      this.loading = false;
      const {
        structureCanEdit,
        paperStructureInfo,
        groupInfo,
        classInfo,
        basicPaperInfo,
      } = this.markParamInfos;

      this.infos = {
        structureCanEdit,
        paperStructureInfo: deepCopy(paperStructureInfo),
        groupInfo: deepCopy(groupInfo),
        classInfo: deepCopy(classInfo),
        basicPaperInfo: this.getBaseInfo(basicPaperInfo),
        paperStat: this.statPaperStructure(paperStructureInfo),
      };
      this.dataReady = true;
    },
    getBaseInfo(baseInfo) {
      return this.$objAssign(
        {
          id: null,
          examPaperStructureId: baseInfo.id,
          examId: null,
          cardId: null,
          thirdRelateId: null,
          thirdRelateName: "",
          courseName: "",
          courseId: "",
          paperNumber: null,
          paperType: "",
          sequence: null,
          openClassReading: null,
          status: "",
        },
        baseInfo
      );
    },
    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,
      };
    },
    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.classInfo = [];
          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;
    },
    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 = {
        structureCanEdit: this.infos.structureCanEdit,
        basicPaperInfo: 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,
        classInfo: this.infos.classInfo,
      };
      const res = await examStructureSubmit(datas).catch(() => false);
      this.loading = false;

      if (!res) return;
      // 判断客观题数据结构是否变化
      const cacheStruct = this.getPaperStructData(this.objectiveStructure);
      const curStruct = this.getPaperStructData(
        datas.paperStructureInfo.objectiveQuestionList
      );
      if (curStruct.join("") !== cacheStruct.join("")) {
        this.setObjectiveStructure([]);
      }

      this.infos.basicPaperInfo.id = res;
      const infos = {
        ...this.infos,
        basicPaperInfo: Object.assign(
          this.markParamInfos.basicPaperInfo,
          this.infos.basicPaperInfo
        ),
      };
      this.setMarkParamInfos(infos);
      this.$message.success("提交成功！");
      this.$emit("confirm");
    },
    cancel() {
      this.$emit("cancel");
    },
  },
};
</script>
