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

    <div class="apply-body" v-if="dataReady">
      <div class="apply-part">
        <h3 class="apply-part-title">命题信息</h3>
        <info-exam-task ref="InfoExamTask"></info-exam-task>
      </div>
      <div class="apply-part">
        <h3 class="apply-part-title">考务信息</h3>
        <info-print-task ref="InfoPrintTask"></info-print-task>
      </div>
      <div class="apply-part">
        <h3 class="apply-part-title">流程</h3>
        <el-timeline>
          <el-timeline-item
            v-for="flow in flowList"
            :key="flow.taskKey"
            :type="flow.type"
          >
            <div class="flow-item">
              <h4 class="flow-item-title">{{ flow.taskName }}</h4>
              <p class="flow-item-desc">{{ flow.approveUserNames }}</p>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>

    <div class="text-center">
      <el-button type="success" :disabled="loading" @click="submit"
        >确认提交</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
    <div slot="footer"></div>
  </el-dialog>
</template>

<script>
import { mapMutations, mapState } from "vuex";
import { examRuleDetail, flowDetailByType } from "../../../base/api";
import { teacherSubmitTaskApply } from "../../api";
import InfoExamTask from "./InfoExamTask";
import InfoPrintTask from "./InfoPrintTask";

const initExamTask = {
  semesterId: "",
  examId: "",
  examModel: "",
  courseCode: "",
  courseName: "",
  paperNumber: "",
  cardRuleId: "",
  teachingRoomId: "",
  teacherName: "",
  paperName: ""
};

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

const initPrintPlan = {
  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 = {
  examStartTime: "",
  examEndTime: "",
  paperNumber: "",
  courseName: "",
  courseCode: "",
  printCount: 1, // MODEL2专用
  printHouseId: "", // MODEL2专用
  list: []
};

export default {
  name: "create-exam-and-print-task",
  components: { InfoExamTask, InfoPrintTask },
  data() {
    return {
      modalIsShow: false,
      needReview: false,
      examRule: {},
      // infos: {},
      flowList: [],
      flowInfo: {},
      loading: false,
      dataReady: false
    };
  },
  computed: {
    ...mapState("exam", [
      "infoExamTask",
      "infoExamTaskDetail",
      "infoExamPrintPlan",
      "infoPrintTask"
    ])
  },
  mounted() {
    this.getExamRule();
  },
  methods: {
    ...mapMutations("exam", ["updateTaskInfo"]),
    async getExamRule() {
      const examRule = await examRuleDetail();
      this.examRule = examRule || {};
      this.needReview = examRule && examRule.review;
    },
    async getFlowList() {
      const data = await flowDetailByType();
      if (!data) return;
      this.flowInfo = {
        customFlowId: data.id,
        version: data.version
      };
      this.flowList = data.flowTaskResultList || [];
      if (this.flowList.length) {
        this.flowList[0].type = "success";
      }
    },
    initData() {
      const infoExamTaskDetail = Object.assign({}, initExamTaskDetail, {
        includePaper: this.examRule.includePaper,
        review: this.examRule.review,
        customCard: this.examRule.customCard
      });

      const infos = {
        infoExamTask: { ...initExamTask },
        infoExamTaskDetail,
        infoPrintTask: { ...initPrintTask },
        infoExamPrintPlan: { ...initPrintPlan }
      };
      this.updateTaskInfo(infos);

      this.dataReady = true;
    },
    visibleChange() {
      if (!this.flowList.length) this.getFlowList();
      this.initData();
    },
    disalogClosed() {
      this.dataReady = false;
      this.loading = false;
    },
    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() {
      if (this.loading) return;
      const result = await this.$confirm("确定提交该任务？", "提示", {
        type: "warning"
      }).catch(() => {});
      if (result !== "confirm") return;
      this.loading = true;
      // 数据校验
      const validAll = [
        this.$refs.InfoExamTask.checkData(),
        this.$refs.InfoPrintTask.checkData()
      ];
      const validResult = await Promise.all(validAll).catch(() => {});
      if (!validResult) {
        this.loading = false;
        return;
      }
      // 更新infos
      this.$refs.InfoExamTask.updeteData();
      this.$refs.InfoPrintTask.updeteData();

      const examTaskContent = {
        examTask: this.infoExamTask,
        examTaskDetail: this.infoExamTaskDetail,
        examDetail: this.infoPrintTask
      };
      let datas = {
        examTaskContent: JSON.stringify(examTaskContent),
        ...this.flowInfo
      };

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