<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"
  >
    <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"
          :datas="infos"
          @relate-info-change="printTaskRelateInfoChange"
        ></info-exam-task>
      </div>
      <div class="apply-part">
        <h3 class="apply-part-title">考务信息</h3>
        <info-print-task ref="InfoPrintTask" :datas="infos"></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 {
  examConfigByExamIdOrgId,
  examRuleDetail,
  flowDetailByType
} from "../../../base/api";
import { teacherSubmitTaskApply } from "../../api";
import InfoExamTask from "./InfoExamTask";
import InfoPrintTask from "./InfoPrintTask";

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

const initExamTaskDetail = {
  operateType: "STAGE",
  paperType: "A",
  cardId: "",
  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: "",
  list: []
};

export default {
  name: "create-exam-and-print-task",
  components: { InfoExamTask, InfoPrintTask },
  data() {
    return {
      modalIsShow: false,
      needReview: false,
      examRule: {},
      infos: {},
      flowList: [],
      loading: false,
      dataReady: false
    };
  },
  mounted() {
    this.getExamRule();
    this.getFlowList();
  },
  methods: {
    async getExamRule() {
      const examRule = await examRuleDetail();
      this.examRule = examRule || {};
      this.needReview = examRule && examRule.review;
    },
    async getFlowList() {
      const data = await flowDetailByType();
      this.flowList = data || [];
      if (this.flowList.length) {
        this.flowList[0].type = "success";
      }
    },
    async initData() {
      const examTaskDetail = Object.assign({}, initExamTaskDetail, {
        includePaper: this.examRule.includePaper,
        review: this.examRule.review,
        customCard: this.examRule.customCard
      });

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

      this.dataReady = true;
    },
    visibleChange() {
      this.dataReady = false;
      this.loading = false;
      this.initData();
    },
    dataChange(data) {
      // console.log(data);
      Object.entries(data).forEach(([key, val]) => {
        this.infos[key] = Object.assign(this.infos[key], val);
      });
    },
    async printTaskRelateInfoChange(data, type) {
      if (type === "exam") {
        const { examId, teachingRoomId } = data.examTask;
        const {
          examId: infoExamId,
          teachingRoomId: infoTeachingRoomId
        } = this.infos.examTask;
        if (
          examId &&
          teachingRoomId &&
          (examId !== infoExamId || teachingRoomId !== infoTeachingRoomId)
        ) {
          this.dataChange(data);
          await this.updatePrintPlan({ examId, orgId: teachingRoomId });
          this.$nextTick(() => {
            this.$refs.InfoPrintTask.buildTableData();
            this.$refs.InfoPrintTask.updatePackageInfos();
          });
        }
        return;
      }

      if (type === "course") {
        this.dataChange(data);

        this.$nextTick(() => {
          this.$refs.InfoPrintTask.initData();
        });
      }
    },
    async updatePrintPlan({ examId, orgId }) {
      const printPlan = await examConfigByExamIdOrgId({
        examId,
        orgId
      }).catch(() => {});
      if (!printPlan) {
        this.loading = false;
        return;
      }
      let examPrintPlan = Object.assign({}, initPrintPlan, printPlan);
      this.infos.examPrintPlan = examPrintPlan;
      this.infos.examTask.cardRuleId = examPrintPlan.cardRuleId;
    },
    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
      const examDatas = [
        this.$refs.InfoExamTask.getData(),
        this.$refs.InfoPrintTask.getData()
      ];
      examDatas.forEach(item => {
        this.dataChange(item);
      });

      const examTaskContent = {
        examTask: this.infos.examTask,
        examTaskDetail: this.infos.examTaskDetail,
        examDetail: this.infos.printTask
      };
      let datas = {
        examTaskContent: JSON.stringify(examTaskContent)
      };

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