<template>
  <el-dialog
    class="modify-major"
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="448px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      :key="modalForm.id"
      label-position="top"
    >
      <el-form-item prop="majorName" label="专业名称：">
        <el-input
          v-model.trim="modalForm.majorName"
          placeholder="请输入专业名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="collegeId" label="所属机构：">
        <college-select
          v-model="modalForm.collegeId"
          style="width:100%;"
          placeholder="所属机构"
        ></college-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 { updateMajor } from "../api";

const initModalForm = {
  id: null,
  majorName: "",
  collegeId: ""
};

export default {
  name: "modify-major",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "专业";
    }
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      classList: [],
      modalForm: { ...initModalForm },
      rules: {
        majorName: [
          {
            required: true,
            message: "请输入专业名称",
            trigger: "change"
          },
          {
            message: "专业名称不能超过50个字",
            max: 50,
            trigger: "change"
          }
        ],
        collegeId: [
          {
            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;
      const data = await updateMajor(this.modalForm).catch(() => {
        this.isSubmit = false;
      });

      if (!data) return;

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