<template>
  <el-dialog
    custom-class="side-dialog"
    :visible.sync="modalIsShow"
    :title="title"
    width="500px"
    :modal="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item v-if="modalForm.name" prop="name" label="文件夹名称">
        <el-input
          v-model="modalForm.name"
          placeholder="请输入文件夹名称"
          clearable
        >
        </el-input>
      </el-form-item>
    </el-form>

    <div slot="footer">
      <el-button type="primary" :disabled="loading" @click="confirm"
        >确认</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

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

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

export default {
  name: "ModifyFolder",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      modalForm: {
        ...initModalForm,
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入文件夹名称",
            trigger: "change",
          },
          {
            max: 100,
            message: "文件夹名称不能超过100",
            trigger: "change",
          },
        ],
      },
      loading: false,
    };
  },
  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 confirm() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.loading) return;
      this.loading = true;

      const datas = { ...this.modalForm };
      const res = await updateClassifyApi(datas).catch(() => {});
      this.loading = false;
      if (!res) return;

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