<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
    @open="visibleChange"
  >
    <div slot="title">
      <span class="el-dialog__title">新增命题申请</span>
    </div>

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

    <div class="apply-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 { examRuleDetail } from "../../../base/api";
import { teacherSubmitTaskApply } from "../../api";
import { printPlanTemplateList } from "../../../print/api";
import InfoPrintPlan from "./InfoPrintPlan";
import InfoExamTask from "./InfoExamTask";
import InfoPrintTask from "./InfoPrintTask";
import { COMMON_CARD_RULE_ID } from "@/constants/enumerate";
import { deepCopy } from "@/plugins/utils";

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

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

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

const initPrintPlan = {
  name: "",
  examStartTime: "",
  examEndTime: "",
  printContent: [],
  backupMethod: "ROOM",
  backupCount: 1,
  drawRule: "ONE",
  templateSources: {},
  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 = {
  examStartTime: "",
  examEndTime: "",
  paperNumber: "",
  courseName: "",
  courseCode: "",
  list: []
};

export default {
  name: "create-task-apply",
  components: { InfoPrintPlan, InfoExamTask, InfoPrintTask },
  data() {
    return {
      modalIsShow: false,
      needReview: false,
      examRule: {},
      infos: {},
      templateSources: {},
      // step
      steps: STEPS_LIST,
      current: 0,
      loading: false,
      dataReady: false
    };
  },
  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;
    }
  },
  methods: {
    async getExamRule() {
      const examRule = await examRuleDetail();
      this.examRule = examRule || {};
      this.needReview = examRule && examRule.review;
    },
    async getTemplates() {
      const data = await printPlanTemplateList();
      const templateSources = {};
      const templates = [...data.variable, ...data.ordinary];
      templates.forEach(item => {
        templateSources[item.type] = item.template;
      });
      this.templateSources = templateSources;
    },
    async initData() {
      await this.getExamRule();
      await this.getTemplates();

      const examTaskDetail = Object.assign({}, initExamTaskDetail, {
        includePaper: this.examRule.includePaper,
        review: this.examRule.review,
        customCard: this.examRule.customCard
      });

      // printPlan
      let printPlan = deepCopy(initPrintPlan);
      printPlan.variableContent = printPlan.variableContent.filter(
        item => this.templateSources[item.type]
      );
      printPlan.ordinaryContent = printPlan.ordinaryContent.filter(
        item => this.templateSources[item.type]
      );
      printPlan.templateSources = this.templateSources;

      this.infos = {
        examTask: { ...initExamTask },
        examTaskDetail,
        printPlan,
        printTask: { ...initPrintTask }
      };

      this.dataReady = true;
    },
    visibleChange() {
      this.dataReady = false;
      this.current = 0;
      this.loading = false;
      this.initData();
    },
    prevStep() {
      if (this.isFirstStep) return;
      this.$refs[this.currentComponent].updateData();
      this.current -= 1;
    },
    nextStep() {
      this.loading = true;
      this.$refs[this.currentComponent].checkData();
    },
    toNext() {
      if (this.isLastStep) {
        this.submit();
      } else {
        this.current += 1;
      }
    },
    dataChange(data) {
      console.log(data);
      Object.entries(data).forEach(([key, val]) => {
        this.infos[key] = Object.assign(this.infos[key], val);
      });
    },
    compReady(type = false) {
      this.loading = type;
    },
    async cancel() {
      const result = await this.$confirm("确定取消该任务？", "提示", {
        type: "warning"
      }).catch(() => {});

      if (result !== "confirm") return;

      this.close();
    },
    close() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async submit() {
      const result = await this.$confirm("确定提交该任务？", "提示", {
        type: "warning"
      }).catch(() => {});

      if (result !== "confirm") {
        this.loading = false;
        return;
      }

      let examPrintPlan = deepCopy(this.infos.printPlan);
      delete examPrintPlan.templateSources;
      examPrintPlan.variableContent = JSON.stringify(
        examPrintPlan.variableContent
      );
      examPrintPlan.ordinaryContent = JSON.stringify(
        examPrintPlan.ordinaryContent
      );

      const examTaskContent = {
        examTask: this.infos.examTask,
        examTaskDetail: this.infos.examTaskDetail,
        examPrintPlan,
        examDetail: this.infos.printTask
      };

      const data = await teacherSubmitTaskApply({
        examTaskContent: JSON.stringify(examTaskContent)
      }).catch(() => {});
      this.loading = false;
      if (!data) return;
      this.$message.success("提交成功！");
      this.close();
      this.$emit("modified");
    }
  }
};
</script>
