<template>
  <el-dialog
    class="modify-exam"
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="460px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item prop="name" label="考试名称：">
        <el-input
          v-model.trim="modalForm.name"
          placeholder="请输入考试名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="semesterId" label="所属学期：">
        <semester-select
          v-model="modalForm.semesterId"
          placeholder="请选择所属学期"
          :clearable="false"
        ></semester-select>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateExam } from "../api";
import { slashesLimitValidator } from "@/plugins/formRules";

const initModalForm = {
  id: null,
  semesterId: "",
  name: "",
};

export default {
  name: "modify-exam",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "考试";
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      rules: {
        name: [
          {
            required: true,
            message: "请输入考试名称",
            trigger: "change",
          },
          {
            message: "考试名称不能超过100字符",
            max: 100,
            trigger: "change",
          },
          ...slashesLimitValidator,
        ],
        semesterId: [
          {
            required: true,
            message: "请选择所属学期",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    initData(val) {
      if (val.id) {
        this.modalForm = this.$objAssign(initModalForm, val);
      } else {
        this.modalForm = { ...initModalForm };
      }
    },
    visibleChange() {
      this.initData(this.instance);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      let datas = { ...this.modalForm };
      const data = await updateExam(datas).catch(() => {});
      this.isSubmit = false;

      if (!data) return;

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