<template>
  <el-dialog
    class="create-task-apply"
    :visible.sync="modalIsShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    append-to-body
    fullscreen
    destroy-on-close
    @open="visibleChange"
  >
    <div slot="title">
      <span class="el-dialog__title">新增命题申请</span>
      <button class="el-dialog__headerbtn" @click="close"></button>
    </div>

    <el-steps class="apply-step" :active="current" align-center>
      <el-step
        v-for="step in steps"
        :key="step.name"
        :title="step.name"
        :description="step.title"
      >
      </el-step>
    </el-steps>

    <component
      :is="currentComponent"
      :ref="currentComponent"
      @next-step="toNext"
      @on-ready="compReady"
    ></component>

    <div slot="footer">
      <el-button v-if="!isFirstStep" type="primary" @click="prevStep"
        >上一步</el-button
      >
      <el-button
        v-if="isLastStep"
        type="success"
        :disabled="isSubmit"
        @click="submit"
        >确认提交</el-button
      >
      <el-button v-else type="primary" @click="nextStep" :disabled="nextHolder"
        >下一步</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { examRuleDetail } from "../../base/api";
import { teacherCreateTaskApply, teacherCancelTaskApply } from "../api";

const STEPS_LIST = [
  {
    name: "exam-task",
    title: "命题信息"
  },
  {
    name: "print",
    title: "备卷印品信息"
  },
  {
    name: "exam-business",
    title: "考务信息"
  }
];

const initExamTask = {
  id: null,
  courseCode: "",
  courseName: "",
  paperNumber: "",
  cardRuleId: "",
  teachingRoomId: "",
  teacherName: "",
  lecturerName: ""
};

const initExamTaskDetail = {
  operateType: "STAGE",
  paperType: "A",
  cardId: "",
  paperAttachmentIds: [],
  paperConfirmAttachmentIds: [],
  drawCount: 2,
  remark: "",
  makeMethod: "",
  // 题卡状态
  status: "",
  // 考务规则
  review: false,
  includePaper: false,
  customCard: false
};

const initPrintPlan = {
  id: null,
  name: "",
  examStartTime: "",
  examEndTime: "",
  printContent: [],
  backupMethod: "ROOM",
  backupCount: 1,
  drawRule: "ONE",
  variableContent: [
    {
      type: "SIGN",
      templateId: [],
      oldTemplateId: [],
      backupMethod: "ROOM",
      backupCount: 1
    },
    {
      type: "PACKAGE",
      templateId: [],
      oldTemplateId: [],
      backupMethod: "ROOM",
      backupCount: 1
    }
  ],
  ordinaryContent: [
    {
      type: "CHECK_IN",
      templateId: [],
      oldTemplateId: [],
      backupMethod: "ROOM",
      backupCount: 1
    }
  ]
};

const initPrintTask = {
  printPlanName: "",
  printPlanId: "",
  examStartTime: "",
  examEndTime: "",
  paperNumber: "",
  courseName: "",
  courseCode: "",
  list: []
};

export default {
  name: "create-task-apply",
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      needReview: false,
      examRule: {},
      infos: {},
      // step
      steps: STEPS_LIST,
      current: 0,
      nextHolder: false,
      isPaying: false,
      dataReady: true
    };
  },
  computed: {
    currentComponent() {
      return `info-${this.steps[this.current].name}`;
    },
    isFirstStep() {
      return this.current === 0;
    },
    isLastStep() {
      return this.current === this.lastStep;
    },
    lastStep() {
      return this.steps.length - 1;
    },
    isFree() {
      return this.infos.free || !this.infos.fee;
    },
    payBtnName() {
      return this.isFree ? "确认并提交" : "确认并缴费";
    }
  },
  created() {
    this.getExamRule();
  },
  methods: {
    async getExamRule() {
      const examRule = await examRuleDetail();
      this.examRule = examRule || {};
      this.needReview = examRule && examRule.review;
    },
    initData() {
      const examTaskDetail = Object.assign({}, initExamTaskDetail, {
        includePaper: this.examRule.includePaper,
        review: this.examRule.review,
        customCard: this.examRule.customCard
      });

      this.infos = {
        examTask: { ...initExamTask },
        examTaskDetail,
        printPlan: { ...initPrintPlan },
        printTask: { ...initPrintTask }
      };
    },
    visibleChange() {
      this.initData();
    },
    prevStep() {
      if (this.isFirstStep) return;
      this.current -= 1;
    },
    nextStep() {
      if (this.isLastStep) return;
      this.$refs[this.currentComponent].checkForm();
    },
    toNext() {
      if (this.isLastStep) return;
      this.current += 1;
      this.nextHolder = true;
    },
    compReady(type = false) {
      this.nextHolder = type;
    },
    checkData() {
      return this.$refs.examTaskComp.validate().catch(() => {});
    },
    async cancel() {
      if (this.examTask.id) {
        await teacherCancelTaskApply(this.examTask.id);
        this.$message.success("取消命题申请成功！");
      }
      this.close();
    },
    close() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async toSave(silent) {
      const valid = await this.$refs.examTaskComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      this.getTaskDetailData();
      const datas = {
        examTaskDetail: this.examTaskDetail,
        examTask: this.examTask
      };
      const data = await teacherCreateTaskApply(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      this.examTask = this.$objAssign(this.examTask, data);

      if (!silent) this.$message.success("保存成功！");
      return true;
    },
    async submit() {
      const valid = await this.$refs.examTaskComp.validate().catch(() => {});
      if (!valid) return;

      if (!this.checkDataValid()) return;

      this.$confirm(
        "任务确定提交后，则不可更改试卷及答题卡内容，确定提交该任务？",
        "提示",
        {
          type: "warning"
        }
      )
        .then(async () => {
          this.getTaskDetailData();
          this.examTaskDetail.operateType = "SUBMIT";
          const datas = {
            examTaskDetail: this.examTaskDetail,
            examTask: this.examTask
          };
          const data = await teacherCreateTaskApply(datas).catch(() => {});

          if (!data) return;
          this.$message.success("提交成功！");
          this.close();
          this.$emit("modified");
        })
        .catch(() => {});
    }
  }
};
</script>
