<template>
  <Modal
    class="modify-data"
    v-model="modalIsShow"
    :title="title"
    :mask-closable="false"
    @on-visible-change="visibleChange"
  >
    <Form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      :key="modalForm.id"
      :label-width="100"
    >
      <FormItem prop="name" label="年级名称">
        <Input
          v-model.trim="modalForm.name"
          placeholder="请输入年级名称"
          clearable
        ></Input>
      </FormItem>
    </Form>
    <div slot="footer">
      <Button type="text" @click="cancel">取消</Button>
      <Button type="primary" :disabled="isSubmit" @click="submit">确认</Button>
    </div>
  </Modal>
</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(visible) {
      if (visible) {
        this.initData(this.instance);
      }
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate();
      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>
