<template>
  <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"
  >
    <div class="part-box part-box-pad part-box-border part-box-gray">
      <el-form class="form-info mb-4" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程（代码）：">
              <span
                >{{ modalForm.courseName }}（{{ modalForm.courseCode }}）</span
              >
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教研室：">
              <span>{{ modalForm.teachingRoomName | defaultFieldFilter }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="使用学期：">
              <span>{{ modalForm.paperName || "--" }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考试时间：">
              <span v-if="modalForm.examDate && modalForm.examTime">
                {{ modalForm.examDate }} <i class="mr-1"></i>
                {{ modalForm.examTime }}
              </span>
              <span v-else>--</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="拟卷教师：">
              <span>{{ modalForm.teacherName | defaultFieldFilter }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="命题老师：">
              <span>{{ modalForm.propositionName || modalForm.userName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="审核状态：">
              <span>{{ modalForm.auditStatus | auditStatusFilter }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <table class="table task-exam-room" v-if="examRoomInfoList.length">
        <colgroup>
          <col width="400" />
          <col width="100" />
          <col width="100" />
        </colgroup>
        <tr>
          <th>使用班级</th>
          <th>人数</th>
          <th>总印份数</th>
        </tr>
        <tr v-for="(item, index) in examRoomInfoList" :key="index">
          <td>{{ item.clazzNames }}</td>
          <td>{{ item.studentCount }}</td>
          <td>{{ item.printCount }}</td>
        </tr>
      </table>
    </div>
    <div class="task-apply-steps" v-if="flows.length">
      <el-steps align-center>
        <el-step
          v-for="flow in flows"
          :key="flow.taskKey"
          :title="flow.taskName"
          :status="flow.status"
        >
          <div slot="description">
            <div class="step-info" v-if="flow.firstUser">
              <span>{{ flow.firstUser }}</span>
              <el-popover
                v-if="flow.moreUser"
                placement="top-start"
                width="300"
                trigger="hover"
                :content="flow.moreUser"
              >
                <span class="color-primary ml-1" slot="reference">更多</span>
              </el-popover>
            </div>
          </div>
        </el-step>
      </el-steps>
    </div>

    <div class="mb-4 tab-btns" v-if="needReview">
      <el-button
        v-for="item in menus"
        :key="item.id"
        size="medium"
        :type="item.id == curMenu.id ? 'primary' : 'default'"
        @click="selectMenu(item)"
        >{{ item.name }}</el-button
      >
    </div>
    <div v-if="modalIsShow">
      <apply-content
        v-show="curMenu.id === '1'"
        ref="ApplyContent"
        :exam-task="modalForm"
        :edit-type="editType"
        @step-change="stepChange"
        @cancel="cancel"
        @modified="modified"
      ></apply-content>
      <apply-audit-history
        v-if="needReview"
        v-show="curMenu.id === '2'"
        ref="ApplyAuditHistory"
        :flow-id="modalForm.flowId"
      ></apply-audit-history>
      <apply-submit-history
        v-if="needReview"
        v-show="curMenu.id === '3'"
        ref="ApplySubmitHistory"
        :exam-task-id="modalForm.id"
      ></apply-submit-history>
    </div>

    <div slot="footer"></div>
  </el-dialog>
</template>

<script>
import ApplyContent from "./ApplyContent";
import ApplyAuditHistory from "./ApplyAuditHistory";
import ApplySubmitHistory from "./ApplySubmitHistory";
import { examRuleDetail } from "../../base/api";
import { cancelOrRestartTaskApply, taskApplyExamObject } from "../api";
import { parseTimeRangeDateAndTime } from "@/plugins/utils";

const initModalForm = {
  id: null,
  courseCode: "",
  courseName: "",
  specialty: "",
  paperNumber: "",
  startTime: "",
  endTime: "",
  cardRuleId: "",
  cardRuleName: "",
  flowId: "",
  setup: 0,
  userId: "",
  userName: "",
  propositionName: "",
  auditStatus: "",
  reviewStatus: "",
  source: "",
  teachingRoomName: "",
  teacherName: "",
  lecturerName: "",
  paperName: "",
  examDate: "",
  examTime: ""
};

export default {
  name: "modify-task-apply",
  components: { ApplyContent, ApplyAuditHistory, ApplySubmitHistory },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    },
    editType: {
      type: String,
      default: ""
    }
  },
  computed: {
    title() {
      // editType为主
      if (this.editType) {
        const names = {
          APPLY: "提交入库申请",
          PREVIEW: "入库申请详情",
          AUDIT: "审核入库申请"
        };
        return names[this.editType];
      }

      if (this.modalForm.setup === 1 || this.modalForm.setup === null) {
        return "提交入库申请";
      } else if (this.modalForm.setup <= 0) {
        return "入库申请详情";
      } else {
        return "审核入库申请";
      }
    }
  },
  data() {
    return {
      modalIsShow: false,
      modalForm: {},
      needReview: false,
      examRule: {},
      menus: [
        { id: "1", name: "命题处理", component: "apply-content" },
        { id: "2", name: "审核意见", component: "apply-audit-history" },
        { id: "3", name: "提交记录", component: "apply-submit-history" }
      ],
      curMenu: {},
      flows: [],
      examRoomInfoList: [],
      printTotalCount: 0
    };
  },
  created() {
    this.getExamRule();
  },
  methods: {
    async getExamRule() {
      const examRule = await examRuleDetail();
      this.examRule = examRule || {};
      this.needReview = examRule && examRule.review;
    },
    initData(val) {
      this.modalForm = this.$objAssign(initModalForm, val);
      this.modalForm.includePaper = this.examRule.includePaper;
      this.modalForm.review = this.examRule.review;
      this.modalForm.customCard = this.examRule.customCard;
    },
    visibleChange() {
      this.initData(this.instance);
      this.curMenu = this.menus[0];

      this.getExamRoomInfo();
    },
    async getExamRoomInfo() {
      const data = await taskApplyExamObject(this.instance.paperNumber);

      this.examRoomInfoList = data.examRoomInfoList || [];
      this.printTotalCount = data.printTotalCount;
      this.modalForm.paperName = data.paperName || "";
      const { date, time } = parseTimeRangeDateAndTime(
        data.examStartTime,
        data.examEndTime
      );

      this.modalForm.examDate = date;
      this.modalForm.examTime = time;
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    toCancel() {
      this.$confirm("确定要撤销当前申请吗？", "提示", {
        type: "warning"
      })
        .then(async () => {
          const data = await cancelOrRestartTaskApply({
            id: this.instance.id
          }).catch(() => {});
          if (!data) return;
          this.$message.success("操作成功！");
          this.modified();
        })
        .catch(() => {});
    },
    selectMenu(item) {
      this.curMenu = item;
    },
    stepChange(flows) {
      this.flows = flows;
    },
    modified() {
      this.cancel();
      this.$emit("modified");
    }
  }
};
</script>
