<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="120px"
    >
      <el-form-item prop="name" label="培养方案名称：">
        <el-input
          v-model.trim="modalForm.name"
          placeholder="培养方案名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="professionalId" label="所属专业：">
        <professional-select
          v-model="modalForm.professionalId"
          placeholder="所属专业"
          :org-id="userOrgId"
        ></professional-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 { updateTrainingPlan } from "../../api";

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

export default {
  name: "modify-training-plan",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      userOrgId: this.$ls.get("orgId", ""),
      modalForm: { ...initModalForm },
      rules: {
        name: [
          { required: true, message: "请输入培养方案名称", trigger: "change" },
          {
            message: "培养方案名称不能超过30个字",
            max: 30,
            trigger: "change",
          },
        ],
        professionalId: [
          { 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 updateTrainingPlan(this.modalForm).catch(() => {});
      this.isSubmit = false;

      if (!data) return;

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