<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="grade" label="所属年级：">
        <grade-select
          v-model="modalForm.grade"
          placeholder="所属年级"
          clearable
        ></grade-select>
      </el-form-item>
      <el-form-item prop="professionalId" label="所属专业：">
        <professional-select
          v-model="modalForm.professionalId"
          placeholder="所属专业"
          class="width-full"
        ></professional-select>
      </el-form-item>
    </el-form>
    <p class="tips-info" style="padding-left: 50px">
      说明：系统会自动按专业名称+年级+人才培养方案命名
    </p>
    <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";
import GradeSelect from "@/components/base/GradeSelect.vue";

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

export default {
  name: "modify-training-plan",
  components: { GradeSelect },
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      rules: {
        grade: [
          { required: true, message: "请选择所属年级", 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>
