<template>
  <div class="exam-modify part-box part-box-border part-box-pad">
    <el-form
      ref="ModalForm"
      :model="modalForm"
      :rules="rules"
      label-width="180px"
      style="min-width:800px;"
    >
      <el-form-item prop="examName" label="考试名称：">
        <el-input
          style="width: 439px;"
          v-model.trim="modalForm.examName"
          placeholder="请输入考试名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="examCodeTemp" label="考务文件：">
        <upload-file-view
          :upload-url="uploadUrl"
          @upload-error="uplaodError"
          @upload-success="uploadSuccess"
          ref="UploadFileView"
        ></upload-file-view>
        <el-button @click="toPreview" style="margin-left:16px;">预览</el-button>
      </el-form-item>
      <el-form-item label="考试开始时间：">
        <p class="form-item-content">{{ modalForm.beginTime }}</p>
      </el-form-item>
      <el-form-item prop="printTime" label="打印时间：">
        <el-date-picker
          v-model="modalForm.printTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="backup" label="备用方式：">
        <el-radio-group v-model="modalForm.backup">
          <el-radio
            v-for="(val, key) in RESERVE_TYPE"
            :key="key"
            :label="key"
            >{{ val }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="backupCard" label="备用各科试卷题卡份数：">
        <el-input-number
          style="width:220px;"
          v-model="modalForm.backupCard"
          :min="1"
          :max="1000"
          :step="1"
          step-strictly
          :controls="false"
        ></el-input-number>
      </el-form-item>
      <el-form-item prop="teacher" label="指派命题老师：">
        <el-table :data="courses" style="width: 420px;" border stripe>
          <el-table-column
            width="154"
            prop="courseName"
            label="科目"
          ></el-table-column>
          <el-table-column label="命题老师">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.teacherId"
                size="small"
                style="width: 156px;"
                placeholder="请选择"
              >
                <el-option
                  v-for="user in scope.row.users"
                  :key="user.id"
                  :value="user.id"
                  :label="user.name"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :disabled="isSubmit" @click="save"
          >保存</el-button
        >
        <el-button @click="goback">返回</el-button>
      </el-form-item>
    </el-form>

    <!-- business-data -->
    <business-data
      :exam-code="modalForm.examCodeTemp"
      ref="BusinessData"
    ></business-data>
  </div>
</template>

<script>
import { RESERVE_TYPE } from "@/constants/enumerate";
import { uploadExam, examDetail } from "../api";
import BusinessData from "../components/BusinessData";
import UploadFileView from "../components/UploadFileView";

export default {
  name: "exam-modify",
  components: { BusinessData, UploadFileView },
  data() {
    const printTimeValidator = (rule, value, callback) => {
      if (!this.checkDateRangeValid(value, this.modalForm.beginTime)) {
        callback(new Error("打印时间不能为空，且不得晚于考试开始时间"));
      } else {
        callback();
      }
    };
    const teacherValidator = (rule, value, callback) => {
      if (!this.checkTeacherSelected()) {
        callback(new Error("请选择各科目的命题老师"));
      } else {
        callback();
      }
    };

    return {
      examId: this.$route.params.examId,
      modalForm: {
        examName: "",
        beginTime: "",
        printTime: "",
        backup: "0",
        backupCard: "",
        examCodeTemp: "",
        attachmentId: ""
      },
      rules: {
        examName: [
          {
            required: true,
            message: "请输入考试名称",
            trigger: "change"
          }
        ],
        examCode: [
          {
            required: true,
            message: "请上传考务文件",
            trigger: "change"
          }
        ],
        printTime: [
          {
            required: true,
            validator: printTimeValidator,
            trigger: "change"
          }
        ],
        backup: [
          {
            required: true,
            message: "请选择备用方式",
            trigger: "change"
          }
        ],
        backupCard: [
          {
            required: true,
            message: "请输入备用各科试卷题卡份数",
            trigger: "change"
          }
        ],
        teacher: [
          {
            required: true,
            validator: teacherValidator
          }
        ]
      },
      RESERVE_TYPE,
      courses: [],
      isSubmit: false,
      // import
      uploadUrl: "/api/print/exam/exam/impExamData"
    };
  },
  computed: {
    isEdit() {
      return !!this.examId;
    }
  },
  mounted() {
    if (this.isEdit) {
      this.getExamDetail();
    }
  },
  methods: {
    async getExamDetail() {
      const data = await examDetail(this.examId);
      this.modalForm = Object.assign({}, this.modalForm, data.tcPExam);
      this.modalForm.backup += "";
      this.courses = data.userCourses;
      this.$refs.UploadFileView.setAttachmentName(
        `${data.tcPAttachment.name}${data.tcPAttachment.type}`
      );
    },
    checkDateRangeValid(startTime, endTime) {
      if (startTime && endTime) {
        var st = new Date(startTime.replace(/-/g, "/")).getTime();
        var et = new Date(endTime.replace(/-/g, "/")).getTime();

        return st < et;
      }
      return;
    },
    checkTeacherSelected() {
      return !this.courses.some(course => !course.teacherId);
    },
    async save() {
      const valid = await this.$refs["ModalForm"].validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      const datas = {
        tcPExam: this.modalForm,
        tcPExamCourseUsers: this.courses.map(course => {
          return {
            courseName: course.courseName,
            courseCode: course.courseCode,
            userId: course.teacherId
          };
        })
      };
      const data = await uploadExam(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;
      this.$message.success("保存成功！");
      this.goback();
    },
    toPreview() {
      if (!this.modalForm.examCodeTemp) {
        this.$message.error("请先上传考务文件！");
        return;
      }
      this.$refs.BusinessData.open();
    },
    // upload-handler
    uplaodError(msg) {
      this.$message.error(msg);
    },
    uploadSuccess(res) {
      this.$message.success("上传成功！");
      const data = res.data;

      this.modalForm.beginTime = data.startTime;
      this.modalForm.examCodeTemp = data.examCode;
      this.modalForm.attachmentId = data.attachmentId;
      this.$refs["ModalForm"].validateField("examCodeTemp");

      this.courses = data.userCourses.map(item => {
        item.teacherId = "";
        return item;
      });
    }
  }
};
</script>
