<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 { 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: {
    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
        );
      } else {
        this.infos = {
          paperStructureInfo: [],
          groupInfo: [],
          basicPaperInfo: { ...this.instance },
          paperStat: this.statPaperStructure([])
        };
      }

      this.dataReady = true;
    },
    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;
      let subjectiveStartPos = this.infos.paperStructureInfo.findIndex(
        item => item.qType === "subjective"
      );
      if (subjectiveStartPos === -1) {
        subjectiveStartPos = this.infos.paperStructureInfo.length;
      }
      const datas = {
        basicPaperInfo: this.getBaseInfo(this.infos.basicPaperInfo),
        paperStructureInfo: {
          objectiveQuestionList: this.infos.paperStructureInfo.slice(
            0,
            subjectiveStartPos
          ),
          subjectiveQuestionList: this.infos.paperStructureInfo.slice(
            subjectiveStartPos
          )
        },
        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>
