<template>
  <el-dialog
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="800px"
    :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="detail" label="目标分解详情：">
        <el-input
          v-model="modalForm.detail"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 10 }"
          resize="none"
          placeholder="请输入目标分解详情"
          clearable
          maxlength="999"
          show-word-limit
        ></el-input>
      </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 { updateTrainingPlanTarget } from "../../api";

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

export default {
  name: "modify-training-plan-target",
  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",
          },
        ],
        detail: [
          { 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 updateTrainingPlanTarget(this.modalForm).catch(
        () => {}
      );
      this.isSubmit = false;

      if (!data) return;

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