<template>
  <el-dialog
    class="modify-exam-task"
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      v-if="modalIsShow"
      ref="modalFormComp"
      label-width="120px"
      :class="{ 'form-info': !editable }"
      :rules="rules"
      :model="modalForm"
    >
      <el-form-item prop="semesterId" label="学期：">
        <semester-select
          v-if="editable"
          ref="SemesterSelect"
          v-model="modalForm.semesterId"
          default-select-in-used
          class="width-full"
        ></semester-select>
        <span v-else>{{ modalForm.semesterName }}</span>
      </el-form-item>
      <el-form-item prop="examId" label="考试：">
        <exam-select
          v-if="editable"
          v-model="modalForm.examId"
          :semester-id="modalForm.semesterId"
          class="width-full"
        ></exam-select>
        <span v-else>{{ modalForm.examName }}</span>
      </el-form-item>
      <el-form-item prop="courseCode" label="课程（代码）：">
        <course-select
          v-if="editable"
          ref="CourseSelect"
          v-model.trim="modalForm.courseCode"
          placeholder="请选择"
          clearable
          class="width-full"
          @change="courseChange"
        ></course-select>
        <span v-else
          >{{ modalForm.courseName }}（{{ modalForm.courseCode }}）</span
        >
      </el-form-item>
      <el-form-item prop="paperNumber" label="试卷编号：">
        <el-input
          v-if="editable"
          v-model="modalForm.paperNumber"
          clearable
        ></el-input>
        <span v-else>{{ modalForm.paperNumber | defaultFieldFilter }}</span>
      </el-form-item>
      <el-form-item prop="startTime" label="命题时间：">
        <el-date-picker
          v-if="editable"
          v-model="createTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="timestamp"
          align="right"
          unlink-panels
          @change="dateChange"
        >
        </el-date-picker>
        <span v-else>
          <span v-if="modalForm.startTime && modalForm.endTime">
            {{ modalForm.startTime | timestampFilter }} 至
            {{ modalForm.endTime | timestampFilter }}
          </span>
          <span v-else>--</span>
        </span>
      </el-form-item>
      <el-form-item label="命题老师：">
        <question-teacher-user-select
          v-if="editType !== 'PREVIEW' && modalIsShow"
          ref="QuestionTeacherSelect"
          v-model="modalForm.userId"
          class="width-full"
          :course-code="modalForm.courseCode"
          placeholder="请选择"
        ></question-teacher-user-select>
        <span v-else>{{ modalForm.userName | defaultFieldFilter }}</span>
      </el-form-item>
    </el-form>

    <div slot="footer">
      <el-button
        v-if="editType !== 'PREVIEW'"
        type="primary"
        :disabled="isSubmit"
        @click="submit"
        >确认</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateExamTask, updatExamTaskTeacher } from "../api";

const initModalForm = {
  id: null,
  semesterId: "",
  semesterName: "",
  examId: "",
  examName: "",
  courseCode: "",
  courseName: "",
  specialty: "",
  paperNumber: "",
  startTime: "",
  endTime: "",
  cardRuleId: "",
  cardRuleName: "",
  userId: "",
  userName: ""
};

export default {
  name: "modify-exam-task",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    },
    editType: {
      type: String,
      default: "ADD",
      validator: val => ["ADD", "PREVIEW", "EDIT"].includes(val)
    }
  },
  computed: {
    title() {
      const names = {
        ADD: "新增命题任务",
        PREVIEW: "命题任务详情",
        EDIT: "指派命题任务"
      };
      return names[this.editType];
    },
    editable() {
      return this.editType === "ADD";
    }
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: {},
      createTime: [],
      rules: {
        semesterId: [
          {
            required: true,
            message: "请选择学期",
            trigger: "change"
          }
        ],
        examId: [
          {
            required: true,
            message: "请选择考试",
            trigger: "change"
          }
        ],
        courseCode: [
          {
            required: true,
            message: "请选择课程",
            trigger: "change"
          }
        ],
        paperNumber: [
          {
            required: false,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback();
              }

              if (value.length < 200) {
                callback();
              } else {
                callback(new Error("试卷编号长度不能超过200"));
              }
              // if (/^[0-9a-zA-Z]{3,30}$/.test(value)) {
              //   callback();
              // } else {
              //   callback(new Error("试卷编号只能包含字母数字，长度在3-30之间"));
              // }
            },
            trigger: "change"
          }
        ],
        startTime: [
          {
            required: true,
            message: "请设置命题时间",
            trigger: "change"
          }
        ]
      }
    };
  },
  methods: {
    initData(val) {
      this.modalForm = this.$objAssign(initModalForm, val);
      this.createTime = [];
    },
    visibleChange() {
      this.initData(this.instance);

      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    dateChange() {
      if (this.createTime) {
        this.modalForm.startTime = this.createTime[0];
        this.modalForm.endTime = this.createTime[1];
      } else {
        this.modalForm.startTime = "";
        this.modalForm.endTime = "";
      }
    },
    courseChange(course) {
      this.modalForm.courseName = course.name;
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      let modals = {
        ...this.modalForm
      };
      const func =
        this.editType === "ADD" ? updateExamTask : updatExamTaskTeacher;
      const data = await func(modals).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      this.$message.success("保存成功！");
      this.$emit("modified");
      this.cancel();
    }
  }
};
</script>
