<template>
  <div>
    <el-dialog
      class="modify-task-apply"
      :visible.sync="modalIsShow"
      :title="title"
      top="10px"
      width="900px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      @open="visibleChange"
      @close="closeHandle"
    >
      <div v-if="dataReady" class="apply-content task-detail">
        <task-info></task-info>
        <task-paper
          ref="TaskPaper"
          @view-attachment="toViewAttachment"
        ></task-paper>
        <task-print v-if="showTaskPrint" ref="TaskPrint"></task-print>
        <task-flow
          ref="TaskFlow"
          @view-attachment="toViewAttachment"
        ></task-flow>
      </div>

      <div slot="footer">
        <el-button
          v-if="taskStatus.IS_APPLY"
          type="primary"
          :disabled="loading"
          @click="submit"
          >确认提交</el-button
        >
        <el-button
          v-if="taskStatus.IS_AUDIT"
          type="primary"
          :disabled="loading"
          @click="toAuditSubmit"
          >确定</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>

    <!-- PreviewFile -->
    <preview-file ref="PreviewFile" :data="curFile"></preview-file>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import {
  taskFlowApproverExchange,
  taskFlowApprover,
  examRuleDetail,
} from "../../../base/api";
import { taskApplyDetail, updateTaskApply } from "../../api";
import { COMMON_CARD_RULE_ID } from "@/constants/enumerate";

import TaskInfo from "./TaskInfo.vue";
import TaskPaper from "./TaskPaper.vue";
import TaskPrint from "./TaskPrint.vue";
import TaskFlow from "./TaskFlow.vue";
import PreviewFile from "@/components/PreviewFile.vue";

const initExamTask = {
  id: null,
  examId: "",
  examName: "",
  className: "",
  examModel: "",
  category: "",
  semesterId: "",
  semesterName: "",
  courseId: "",
  courseCode: "",
  courseName: "",
  specialty: "",
  paperNumber: "",
  startTime: "",
  endTime: "",
  cardRuleId: "",
  cardRuleName: "",
  flowId: "",
  setup: null,
  userId: "",
  userName: "",
  propositionName: "",
  auditStatus: "",
  reviewStatus: "",
  source: "",
  teachingRoomName: "",
  teacherName: "",
  lecturerName: "",
  openAb: false,
};

const initTaskApply = {
  examId: "",
  examTaskId: "",
  category: "",
  paperNumber: "",
  paperType: "A",
  paperAttachmentIds: "",
  paperConfirmAttachmentIds: "",
  cardId: "",
  cardRuleId: "",
  makeMethod: "",
  remark: "",
  courseId: "",
  courseCode: "",
  courseName: "",
  drawCount: 1,
  exposedPaperType: "",
  auditContent: [],
  examTaskDetailList: [],
  openAb: false,
  // 入库申请中新建的命题任务提交信息
  examTaskContent: "",

  // 流程
  flowId: "",
  flowStatus: "",
  setup: null,
  // 工作台任务id
  flowTaskId: "",
  // 题卡状态
  status: "",
  // 考务规则
  review: false,
  includePaper: false,
  customCard: false,
  // 一个命题任务至少交AB两套试卷
  twoPaperEnable: false,
  // 作废
  taskStatus: "",
  cancelRemark: "",
};

export default {
  name: "modify-task-apply",
  components: {
    TaskInfo,
    TaskPaper,
    TaskFlow,
    TaskPrint,
    PreviewFile,
  },
  props: {
    rowData: {
      type: Object,
      default() {
        return {};
      },
    },
    type: {
      type: String,
      validate(val) {
        return ["APPLY", "PREVIEW", "AUDIT"].includes(val);
      },
    },
  },
  computed: {
    ...mapState("exam", ["editType", "examTask", "curTaskApply", "taskStatus"]),
    title() {
      // editType为主
      if (this.editType) {
        const names = {
          APPLY: "提交入库申请",
          PREVIEW: "入库申请详情",
          AUDIT: "审核入库申请",
        };
        return names[this.editType];
      }

      if (this.examTask.setup === 1 || this.examTask.setup === null) {
        return "提交入库申请";
      } else if (this.examTask.setup <= 0) {
        return "入库申请详情";
      } else {
        return "审核入库申请";
      }
    },
    showTaskPrint() {
      return Boolean(
        this.examTask.examModel !== "MODEL3" &&
          this.curTaskApply.examTaskContent
      );
    },
  },
  data() {
    return {
      modalIsShow: false,
      loading: false,
      examRule: {},
      dataReady: false,
      // preview file
      curFile: {
        id: "",
        type: "",
      },
    };
  },
  created() {
    this.getExamRule();
  },
  methods: {
    ...mapMutations("exam", [
      "setEditType",
      "setExamTask",
      "setCurTaskApply",
      "setTaskStatus",
    ]),
    async getExamRule() {
      const examRule = await examRuleDetail();
      this.examRule = examRule || {};
    },
    async initData() {
      this.setEditType(this.type);

      const data = await taskApplyDetail(this.rowData.id, this.rowData.source);
      const examTask = this.$objAssign(initExamTask, {
        ...this.rowData,
        review: this.examRule.review,
        customCard: this.examRule.customCard,
        setup: data.setup,
        semesterName: data.semesterName,
        examId: data.examId,
        examName: data.examName,
        examModel: data.examModel,
      });

      // curTaskApply
      const curTaskApply = this.$objAssign(initTaskApply, {
        ...data,
        examTaskId: examTask.id,
        courseId: examTask.courseId,
        courseName: examTask.courseName,
        cardRuleId: examTask.cardRuleId,
        customCard: examTask.customCard,
        paperNumber: examTask.paperNumber,
        auditContent: JSON.parse(data.auditContent || "[]"),
        includePaper: data.printContent.indexOf("PAPER") !== -1,
      });

      examTask.openAb = data.openAb;
      this.setExamTask(examTask);

      this.setCurTaskApply(curTaskApply);
      this.updateStatus();
      this.dataReady = true;
    },
    updateStatus() {
      const IS_APPLY = this.editType
        ? this.editType === "APPLY"
        : this.curTaskApply.setup === 1 || this.curTaskApply.setup === null;

      const IS_PREVIEW = this.editType
        ? this.editType === "PREVIEW"
        : this.curTaskApply.setup !== null && this.curTaskApply.setup <= 0;

      const IS_AUDIT = this.editType
        ? this.editType === "AUDIT"
        : this.curTaskApply.setup > 1;

      const CAN_CREATE_CARD =
        this.curTaskApply.courseId &&
        this.curTaskApply.examId &&
        this.curTaskApply.cardRuleId !== COMMON_CARD_RULE_ID;

      const IS_EXPOSED_MODE = !!this.curTaskApply.exposedPaperType;

      const IS_REBUILD = this.curTaskApply.category === "REBUILD";

      this.setTaskStatus({
        IS_APPLY,
        IS_PREVIEW,
        IS_AUDIT,
        CAN_CREATE_CARD,
        IS_EXPOSED_MODE,
        IS_REBUILD,
      });
    },
    visibleChange() {
      this.initData();
    },
    closeHandle() {
      this.dataReady = false;
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    modified() {
      this.cancel();
      this.$emit("modified");
    },
    async toViewAttachment(attachment) {
      if (!attachment.attachmentId) {
        this.$message.error("附件丢失！");
        return;
      }
      this.curFile = {
        id: attachment.attachmentId,
        type: "application/pdf",
      };
      this.$refs.PreviewFile.open();
    },
    async submit() {
      if (!this.$refs.TaskPaper.checkData()) return;
      if (this.showTaskPrint && !this.$refs.TaskPrint.checkData()) return;
      if (!this.$refs.TaskFlow.checkData()) return;

      const result = await this.$confirm(
        "任务确定提交后，则不可更改试卷及答题卡内容，确定提交该任务？",
        "提示",
        {
          type: "warning",
        }
      ).catch(() => {});
      if (result !== "confirm") return;

      const paperData = this.$refs.TaskPaper.getData();
      const flowData = this.$refs.TaskFlow.getData();
      const datas = {
        ...this.curTaskApply,
        ...paperData,
        ...flowData,
        operateType: "SUBMIT",
      };

      if (this.showTaskPrint) {
        const examTaskContent = this.$refs.TaskPrint.getData(datas);
        datas.examTaskContent = JSON.stringify(examTaskContent);
      }

      const data = await updateTaskApply(datas).catch(() => {});
      if (!data) return;
      this.$message.success("提交成功！");
      this.modified();
    },
    async toAuditSubmit() {
      const valid = await this.$refs.TaskFlow.checkAuditData();
      if (!valid) return;

      const datas = this.$refs.TaskFlow.getAuditData();
      const result = await this.$confirm(
        `确定${datas.actionName}该申请吗？`,
        "提示",
        {
          type: "warning",
        }
      ).catch(() => {});
      if (result !== "confirm") return;

      const apiFunc =
        datas.approvePass === "EXCHANGE"
          ? taskFlowApproverExchange
          : taskFlowApprover;

      const data = await apiFunc(datas).catch(() => {});
      if (!data) return;

      this.$message.success("审批成功！");
      this.modified();
    },
  },
};
</script>
