<template>
  <el-dialog
    class="modify-data"
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    :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-width="100px"
    >
      <el-form-item prop="name" label="年级名称">
        <el-input
          v-model.trim="modalForm.name"
          placeholder="请输入年级名称"
          clearable
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="danger" @click="cancel" plain>取消</el-button>
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { updateCourse } from "../api";

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

export default {
  name: "modify-data",
  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"
          }
        ]
      }
    };
  },
  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 updateCourse(this.modalForm).catch(() => {
        this.isSubmit = false;
      });

      if (!data) return;

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