<template>
  <el-dialog
    class="modify-exam-task"
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="700px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      label-width="130px"
      :class="{ 'form-info': !editable }"
      :rules="rules"
      :model="modalForm"
    >
      <el-form-item prop="courseCode" label="课程（代码）：">
        <course-select
          v-if="editable"
          ref="CourseSelect"
          v-model.trim="modalForm.courseCode"
          placeholder="请选择"
          clearable
          @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>
          {{ modalForm.startTime | timestampFilter }} 至
          {{ modalForm.endTime | timestampFilter }}</span
        >
      </el-form-item>
      <el-form-item prop="cardRuleId" label="题卡规则：">
        <card-rule-select
          v-if="editable"
          ref="CardRuleSelect"
          v-model.trim="modalForm.cardRuleId"
          placeholder="请选择"
          clearable
        ></card-rule-select>
        <span v-else>{{ modalForm.cardRuleName }}</span>
        <p class="tips-info">
          说明：若选择全部通卡，则命题老师只能选择通卡，若选择题卡规则，则专卡和通卡均可选择
        </p>
      </el-form-item>
      <el-form-item label="命题老师：">
        <question-teacher-user-select
          v-if="editType !== 'PREVIEW' && modalIsShow"
          ref="QuestionTeacherSelect"
          v-model="modalForm.userId"
          :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,
  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: {
        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"
          }
        ],
        cardRuleId: [
          {
            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>
