<template>
  <my-dialog
    :visible="visible"
    :header="title"
    :width="600"
    :closeOnOverlayClick="false"
    @close="emit('update:visible', false)"
    @opened="dialogOpened"
  >
    <t-form ref="formRef" :data="formData" labelWidth="120px" :rules="rules">
      <t-form-item label="节点名称" name="name">
        <t-input v-model="formData.name" clearable></t-input>
      </t-form-item>
      <t-form-item label="父节点">
        <t-input v-model="formData.parentName" disabled></t-input>
      </t-form-item>
    </t-form>
    <template #foot>
      <t-button theme="default" @click="emit('update:visible', false)"
        >取消</t-button
      >
      <t-button theme="primary" @click="save">保存</t-button>
    </template>
  </my-dialog>
</template>
<script setup name="AddNodeDialog">
import { ref, reactive, computed } from 'vue';
import { addOrgNode } from '@/api/user';
import { MessagePlugin } from 'tdesign-vue-next';

const props = defineProps({
  visible: Boolean,
  curRow: Object,
});

const emit = defineEmits(['update:visible', 'success']);
const formRef = ref(null);

const formData = reactive({
  id: '',
  name: '',
  parentId: '',
  parentName: '',
});

const isEdit = computed(() => {
  return !!props.curRow?.id;
});
const title = computed(() => {
  return `${isEdit.value ? '修改' : '新增'}管理节点`;
});

const rules = {
  name: [
    {
      required: true,
      message: '请填写节点名称',
    },
  ],
};

const dialogOpened = () => {
  formData.id = props.curRow.id || null;
  formData.name = props.curRow.name || '';
  formData.parentId = props.curRow.parentId || '';
  formData.parentName = props.curRow.parentName || '';
};

const save = async () => {
  const valid = await formRef.value.validate();
  if (valid !== true) return;

  const res = await addOrgNode(formData).catch(() => {});
  if (!res) return;

  MessagePlugin.success('保存成功');
  emit('update:visible', false);
  emit('success');
};
</script>
