<template>
  <el-dialog
    :visible.sync="modalIsShow"
    :title="title"
    top="10vh"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :key="modalForm.id"
      label-width="100px"
    >
      <template v-if="isNode">
        <el-form-item label="毕业要求：">
          {{ instance.parentName }}
        </el-form-item>
        <el-form-item label="指标点：">
          {{ instance.name }}
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item label="毕业要求：">
          {{ instance.name }}
        </el-form-item>
      </template>

      <el-form-item label="内容：">
        <el-input
          v-model="modalForm.content"
          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 { updateTrainingPlanRequirement } from "../../api";

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

export default {
  name: "modify-training-plan-requirement",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
    };
  },
  computed: {
    isNode() {
      return !!this.instance.parentId;
    },
    title() {
      const typeName = this.isNode ? "指标点" : "毕业要求";
      return `编辑${typeName}`;
    },
  },
  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 updateTrainingPlanRequirement(this.modalForm).catch(
        () => {}
      );
      this.isSubmit = false;

      if (!data) return;

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