<template>
  <el-dialog
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :key="modalForm.id"
      :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="orgId" label="所属学院：">
        <org-select
          v-model="modalForm.orgId"
          placeholder="所属学院"
          :filter-param="{ orgId: instance.orgId, withoutPrintingRoom: true }"
        ></org-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 { updateProfessional } from "../api";

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

export default {
  name: "ModifyProfessional",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      rules: {
        name: [
          { required: true, message: "请输入专业名称", trigger: "change" },
          {
            message: "专业名称不能超过30个字",
            max: 30,
            trigger: "change",
          },
        ],
        orgId: [
          { required: true, message: "请选择所属学院", trigger: "change" },
        ],
      },
    };
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
    title() {
      return (this.isEdit ? "编辑" : "新增") + "专业";
    },
  },
  methods: {
    visibleChange() {
      this.modalForm = this.$objAssign(initModalForm, 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 updateProfessional(this.modalForm).catch(() => {});
      this.isSubmit = false;

      if (!data) return;

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