<template>
  <div>
    <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 v-if="!IS_MODEL3" class="apply-part">
          <h3 class="apply-part-title">考务信息</h3>
          <info-print-task ref="InfoPrintTask"></info-print-task>
        </div>
        <div v-if="infoExamTask.review" class="apply-part flow-timeline">
          <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">
                <div class="flow-item-content">
                  <h4 class="flow-item-title">{{ flow.taskName }}</h4>
                  <p v-if="flow.approveUserNames" class="flow-item-desc">
                    {{ flow.approveUserNames }}
                  </p>
                  <div
                    v-if="flow.isApproveSetFlowNextNode && approveUsers.length"
                    class="flow-item-users"
                  >
                    <span>审批人：</span>
                    <el-tag
                      v-for="user in approveUsers"
                      :key="user.id"
                      size="small"
                      :disable-transitions="false"
                    >
                      {{ user.name }}
                    </el-tag>
                  </div>
                </div>
                <div
                  v-if="flow.isApproveSetFlowNextNode"
                  class="flow-item-action"
                >
                  <el-button
                    class="user-select"
                    icon="el-icon-plus"
                    @click="toSelectNextFlowUser"
                  ></el-button>
                  <p v-if="!approveUsers.length" class="tips-info tips-error">
                    请选择审核人
                  </p>
                </div>
              </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>

    <!-- SelectUserDialog -->
    <select-user-dialog
      v-if="IS_NEED_SELECT_APPROVE_USER"
      ref="SelectUserDialog"
      :users="approveUsers"
      :user-limit-count="userLimitCount"
      :filter-roles="userFilterRoles"
      @modified="userSelected"
    ></select-user-dialog>
  </div>
</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";
import SelectUserDialog from "../../../base/components/SelectUserDialog.vue";
import { randomCode } from "@/plugins/utils";

const initExamTask = {
  semesterId: "",
  examId: "",
  examModel: "",
  category: "",
  courseId: "",
  courseCode: "",
  courseName: "",
  paperNumber: "",
  cardRuleId: "",
  teachingRoomId: "",
  teacherName: "",
  paperName: "",
  uuid: "",
  openAb: false,
  paperConfirmAttachmentIds: "[]",
  remark: "",
  // 题卡状态
  status: "",
  // 考务规则
  review: false,
  includePaper: false,
  customCard: false,
};

// const examTaskDetailItem = {
//   serialNumber: 1,
//   paperType: "A",
//   paperAttachmentIds: "[]",
// };

// const initExamTaskDetail = []; // examTaskDetailItem[]

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: "",
  courseId: "",
  printCount: 1, // MODEL2专用
  printHouseId: "", // MODEL2专用
  classId: "", // MODEL2专用
  className: "", // MODEL2专用
  basicStudentIds: [], // MODEL2专用
  list: [],
};

export default {
  name: "create-exam-and-print-task",
  components: { InfoExamTask, InfoPrintTask, SelectUserDialog },
  data() {
    return {
      modalIsShow: false,
      needReview: false,
      examRule: {},
      flowList: [],
      flowInfo: {},
      loading: false,
      dataReady: false,
      // 选择下一节点审批人
      IS_NEED_SELECT_APPROVE_USER: false,
      nextFlowTaskResult: {}, //下一节点信息
      approveUsers: [],
      userLimitCount: 1,
      userFilterRoles: [],
    };
  },
  computed: {
    ...mapState("exam", [
      "infoExamTask",
      "infoExamTaskDetail",
      "infoExamPrintPlan",
      "infoPrintTask",
    ]),
    IS_MODEL3() {
      return this.infoExamTask.examModel === "MODEL3";
    },
  },
  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;

      const modelType =
        data.flowTaskResultList[0] && data.flowTaskResultList[0].modelType;
      this.flowInfo = {
        customFlowId: data.id,
        version: data.version,
      };
      const nextFlowNodeIndex = 1;
      this.IS_NEED_SELECT_APPROVE_USER = modelType === "APPROVE_SET";
      const flowList = data.flowTaskResultList || [];
      this.flowList = flowList.map((flow, index) => {
        flow.isApproveSetFlowNextNode =
          this.IS_NEED_SELECT_APPROVE_USER && index === nextFlowNodeIndex;
        return flow;
      });
      if (this.flowList.length) {
        this.flowList[0].type = "success";
      }

      this.nextFlowTaskResult = this.flowList[nextFlowNodeIndex];
    },
    initData() {
      this.approveUsers = [];
      this.userLimitCount = 1;
      this.userFilterRoles = [];

      const infos = {
        infoExamTask: {
          ...initExamTask,
          uuid: randomCode(32),
          review: this.examRule.review,
          customCard: this.examRule.customCard,
        },
        infoExamTaskDetail: [],
        infoPrintTask: { ...initPrintTask },
        infoExamPrintPlan: { ...initPrintPlan },
      };
      this.updateTaskInfo(infos);

      this.dataReady = true;
    },
    async visibleChange() {
      if (!this.flowList.length) await 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;
    },
    toSelectNextFlowUser() {
      if (!this.IS_NEED_SELECT_APPROVE_USER) return;

      this.userLimitCount =
        this.nextFlowTaskResult.approveUserCountType === "ONE" ? 1 : 0;
      this.userFilterRoles =
        this.nextFlowTaskResult.approveUserSelectRange === "ROLE"
          ? this.nextFlowTaskResult.approveUserSelectRoles.map(
              (item) => item.id
            )
          : [];
      this.$refs.SelectUserDialog.open();
    },
    userSelected(users) {
      this.approveUsers = users;
    },
    async submit() {
      if (this.loading) return;
      const result = await this.$confirm("确定提交该任务？", "提示", {
        type: "warning",
      }).catch(() => {});
      if (result !== "confirm") return;
      this.loading = true;
      // 数据校验
      let validAll = [this.$refs.InfoExamTask.checkData()];
      if (!this.IS_MODEL3) validAll.push(this.$refs.InfoPrintTask.checkData());
      const validResult = await Promise.all(validAll).catch(() => {});
      if (!validResult) {
        this.loading = false;
        return;
      }
      // 更新infos
      this.$refs.InfoExamTask.updateData();
      if (!this.IS_MODEL3) this.$refs.InfoPrintTask.updateData();

      let examTaskContent = {
        examTask: this.infoExamTask,
        examTaskDetailList: this.infoExamTaskDetail,
      };
      if (!this.IS_MODEL3) {
        examTaskContent.examDetail = this.infoPrintTask;
        examTaskContent.examTask.examStartTime =
          this.infoPrintTask.examStartTime;
        examTaskContent.examTask.examEndTime = this.infoPrintTask.examEndTime;
      }
      let datas = {
        examTaskContent: JSON.stringify(examTaskContent),
        ...this.flowInfo,
      };
      if (this.IS_NEED_SELECT_APPROVE_USER)
        datas.approveUserIds = this.approveUsers.map((item) => item.id);

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