<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.semesterName || "--" }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考试：">
              <span>{{ modalForm.examName || "--" }}</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 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-col :span="12">
            <el-form-item label="审核状态：">
              <span>{{ modalForm.auditStatus | auditStatusFilter }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div v-if="examRoomInfoList.length && !IS_MODEL2" class="task-exam-room">
        <el-table
          :data="examRoomInfoList"
          border
          style="width: 100%"
          max-height="300"
        >
          <el-table-column
            v-if="hasClassInfo"
            prop="clazzNames"
            label="使用班级"
            min-width="400"
          ></el-table-column>
          <el-table-column
            prop="studentCount"
            label="人数"
            min-width="100"
          ></el-table-column>
          <el-table-column
            prop="printCount"
            label="总印份数"
            min-width="100"
          ></el-table-column>
        </el-table>
      </div>

      <div
        class="part-box part-box-pad task-exam-room"
        v-if="examRoomInfoList.length && IS_MODEL2"
      >
        <p>
          正式考生{{ examRoomInfoList[0].studentCount }}个，总印份数{{
            examRoomInfoList[0].printCount
          }}份（正式考生{{ examRoomInfoList[0].studentCount }}份，备用卷{{
            examRoomInfoList[0].backupCount
          }}份）
        </p>
      </div>
    </div>

    <apply-content
      v-if="modalIsShow"
      ref="ApplyContent"
      :exam-task="modalForm"
      :edit-type="editType"
      @info-update="modalInfoUpdate"
      @cancel="cancel"
      @modified="modified"
    ></apply-content>

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

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

const initModalForm = {
  id: null,
  examId: "",
  examName: "",
  examModel: "",
  semesterId: "",
  semesterName: "",
  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 },
  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 "审核入库申请";
      }
    },
    IS_MODEL2() {
      return this.modalForm.examModel === "MODEL2";
    }
  },
  data() {
    return {
      modalIsShow: false,
      modalForm: {},
      examRule: {},
      hasClassInfo: false,
      examRoomInfoList: [],
      printTotalCount: 0
    };
  },
  created() {
    this.getExamRule();
  },
  methods: {
    async getExamRule() {
      const examRule = await examRuleDetail();
      this.examRule = examRule || {};
    },
    modalInfoUpdate(data) {
      this.modalForm = this.$objAssign(this.modalForm, data);
      this.getExamRoomInfo();
    },
    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);
    },
    async getExamRoomInfo() {
      const data = await taskApplyExamObject(this.instance.paperNumber);

      if (this.IS_MODEL2) {
        const { printCount } = data.examRoomInfoList[0];
        const nums = printCount.split("+").map(item => item * 1);
        console.log(nums);
        this.examRoomInfoList = [
          {
            backupCount: nums[1],
            studentCount: nums[0],
            printCount: nums[0] + nums[1]
          }
        ];
      } else {
        this.examRoomInfoList = data.examRoomInfoList || [];
        this.hasClassInfo = this.examRoomInfoList.some(item => item.clazzNames);
      }
      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(() => {});
    },
    modified() {
      this.cancel();
      this.$emit("modified");
    }
  }
};
</script>
