<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
      >
      <span class="ml-4">卷型：{{ instance.paperType }}卷</span>
      <span class="ml-4">试卷编号：{{ instance.paperNumber }}</span>
      <button class="el-dialog__headerbtn" @click="cancel"></button>
    </div>

    <div v-if="dataReady" class="part-box part-box-pad mark-param-head">
      <el-steps :active="curStepIndex" align-center finish-status="success">
        <el-step
          v-for="(item, ind) in steps"
          :key="item.val"
          :status="item.status"
        >
          <el-button
            slot="title"
            :class="[
              'step-title',
              {
                'is-active': curStepIndex === ind,
              },
            ]"
            type="text"
            :disabled="item.disabled"
            @click="changeStep(ind)"
          >
            {{ item.name }}
          </el-button>
        </el-step>
      </el-steps>
    </div>

    <component
      v-if="dataReady"
      ref="paramComponentRef"
      class="mark-param-body"
      :is="currentComponent"
      @next="nextHandler"
      @prev="prevHandler"
    ></component>
    <div slot="footer"></div>
  </el-dialog>
</template>

<script>
import { mapMutations } from "vuex";
import MarkParamStructure from "./MarkParamStructure.vue";
import MarkParamGroup from "./MarkParamGroup.vue";
import MarkParamClass from "./MarkParamClass.vue";
import MarkParamObjectiveAnswer from "./MarkParamObjectiveAnswer.vue";
import {
  markStructureList,
  markSubjectiveList,
  markParamStepStatus,
} from "../../api";

const steps = [
  {
    name: "第一步：设置试卷结构",
    val: "structure",
    disabled: false,
    status: "process",
  },
  {
    name: "第二步：主观题评卷设置",
    val: "group",
    disabled: false,
    status: "wait",
  },
  {
    name: "第三步：分班阅卷设置",
    val: "class",
    disabled: false,
    status: "wait",
  },
  {
    name: "第四步：客观题标答设置",
    val: "objective-answer",
    disabled: false,
    status: "wait",
  },
];

export default {
  name: "modify-mark-params",
  components: {
    MarkParamStructure,
    MarkParamGroup,
    MarkParamClass,
    MarkParamObjectiveAnswer,
  },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      dataReady: false,
      // step
      steps,
      curStepIndex: 0,
      finishedSteps: [],
      questionSubmit: false,
    };
  },
  computed: {
    currentComponent() {
      return `mark-param-${this.curStep.val}`;
    },
    curStep() {
      return this.steps[this.curStepIndex];
    },
    isFirstStep() {
      return this.curStepIndex === 0;
    },
    isLastStep() {
      return this.curStepIndex === this.lastStep;
    },
    lastStep() {
      return this.steps.length - 1;
    },
  },
  methods: {
    ...mapMutations("markParam", [
      "setBasicInfo",
      "setPaperStructureInfo",
      "setSubjectiveTaskList",
      "setOpenMergeMarker",
      "setOpenDoubleMark",
      "setOpenClassMark",
      "setAiMark",
      "initStore",
    ]),
    async initData() {
      this.setBasicInfo({ ...this.instance });

      // check step status
      await this.initSteps();

      const params = {
        examId: this.instance.examId,
        paperNumber: this.instance.paperNumber,
      };
      // structure
      const structRes = await markStructureList(params);
      let curMainNumber = null;
      const questions = (structRes.questions || []).map((item) => {
        let nitem = {
          ...item,
          mainFirstSub: false,
        };
        if (curMainNumber !== item.mainNumber) {
          curMainNumber = item.mainNumber;
          nitem.mainFirstSub = true;
        }
        return nitem;
      });
      this.setPaperStructureInfo(questions || []);
      this.questionSubmit = structRes.questionSubmit;

      // group
      const subjectRes = await markSubjectiveList(params);
      this.setSubjectiveTaskList(subjectRes.questions || []);
      this.setOpenMergeMarker(!!subjectRes.mergeMarker);
      this.setOpenDoubleMark(!!subjectRes.doubleMark);
      this.setOpenClassMark(!!subjectRes.classMark);
      this.setAiMark({
        enableAIMark: subjectRes.aiMarkSet,
        aiMarkType: subjectRes.aiMarkType,
      });

      this.dataReady = true;
    },
    async initSteps() {
      const stepRes = await markParamStepStatus({
        examId: this.instance.examId,
        paperNumber: this.instance.paperNumber,
      });
      const stepMap = {
        subjectiveStruct: 0,
        subjectiveMarker: 1,
        subjectiveMarkerClass: 2,
        objectiveAnswer: 3,
      };
      this.finishedSteps = Object.keys(stepMap)
        .filter((key) => stepRes[key])
        .map((key) => stepMap[key]);
      if (this.finishedSteps.length > 0) {
        this.curStepIndex = Math.max(...this.finishedSteps);
        if (this.curStepIndex !== this.lastStep) {
          this.curStepIndex++;
        }
      } else {
        this.curStepIndex = 0;
      }

      this.steps = steps.map((step, index) => {
        step.status =
          index < this.curStepIndex
            ? "success"
            : index === this.curStepIndex
            ? "process"
            : "wait";
        step.disabled = step.status === "wait";
        return step;
      });
    },
    changeStep(ind) {
      if (ind === this.curStepIndex) return;
      if (this.curStep.disabled) return;

      const step = ind - this.curStepIndex;
      const absStep = Math.abs(step);
      if (step > 0) {
        this.$refs.paramComponentRef.toNext(absStep);
      } else {
        this.$refs.paramComponentRef.toPrev(absStep);
      }
    },
    nextHandler(step = 1) {
      // 最后一步如何继续下一步就关闭窗口
      if (this.isLastStep) {
        this.steps[this.curStepIndex].status = "success";
        if (!this.finishedSteps.includes(this.curStepIndex)) {
          this.finishedSteps.push(this.curStepIndex);
        }
        this.steps.forEach((item) => {
          item.disabled = item.status === "wait";
        });
        return;
      }

      const nextStepIndex = this.curStepIndex + step;
      if (nextStepIndex > this.lastStep) return;
      this.steps[this.curStepIndex].status = "success";
      if (!this.finishedSteps.includes(this.curStepIndex)) {
        this.finishedSteps.push(this.curStepIndex);
      }

      this.steps[nextStepIndex].status = "process";
      this.curStepIndex = nextStepIndex;
      this.steps.forEach((item) => {
        item.disabled = item.status === "wait";
      });
    },
    prevHandler(step = 1) {
      if (this.isFirstStep) return;
      const prevStepIndex = this.curStepIndex - step;
      if (prevStepIndex < 0) return;

      this.steps[this.curStepIndex].status = this.finishedSteps.includes(
        this.curStepIndex
      )
        ? "success"
        : "wait";

      this.curStepIndex = prevStepIndex;
      this.steps[prevStepIndex].status = "process";

      this.steps.forEach((item) => {
        item.disabled = item.status === "wait";
      });
    },
    async cancel() {
      const res = await this.$confirm("确定要退出阅卷参数编辑吗?", "提示", {
        type: "warning",
      }).catch(() => {});
      if (res !== "confirm") return;
      this.close();
    },
    close() {
      this.initStore();
      this.dataReady = false;
      this.$emit("modified");
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
  },
};
</script>
