<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import type { SysDeptApi } from '#/api/auth/dept';

import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { addFullName, getVxePopupContainer } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { apiAdd, apiUpdate, treeList } from '#/api/auth/dept';
import { getDictOptions } from '#/utils/dict';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

const emit = defineEmits<{
  success: [];
}>();
const formData = ref<SysDeptApi.Dept>({});

function genDeptTree(deptList: SysDeptApi.Dept[]): SysDeptApi.Dept[] {
  const top: SysDeptApi.Dept = {
    children: [],
    id: 0,
    name: '顶级部门',
    parentId: -1,
    nodePath: '/',
    orderNum: 0,
    status: 1,
  };
  deptList.forEach((item) => {
    if (item.parentId === 0) {
      top.children?.push(item);
    }
  });
  return [top];
}

const formSchema: VbenFormSchema[] = [
  {
    component: 'ApiTreeSelect',
    componentProps: {
      api: async () => {
        const deptArray = await treeList();
        const filterDeptArray = genDeptTree(deptArray);
        addFullName(filterDeptArray, 'name', ' / ');
        return filterDeptArray;
      },
      class: 'w-full',
      treeLine: { showLeafIcon: false },
      treeIcon: false,
      getVxePopupContainer,
      // 筛选的字段
      treeNodeFilterProp: 'name',
      treeNodeLabelProp: 'fullName',
      labelField: 'name',
      showSearch: true,
      treeDefaultExpandAll: true,
      valueField: 'id',
      childrenField: 'children',
    },
    fieldName: 'parentId',
    label: '父级部门',
    // rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'name',
    label: '部门名称',
    rules: 'required',
  },
  // {
  //   component: 'Input',
  //   fieldName: 'nodePath',
  //   label: '祖级关系',
  //   rules: 'required',
  // },
  // {
  //   component: 'Input',
  //   fieldName: 'isLeaf',
  //   label: '叶子节点',
  //   rules: 'required',
  // },
  {
    component: 'Input',
    fieldName: 'orderNum',
    label: '显示顺序',
    rules: 'required',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(DictEnum.SYS_COMMON_STATUS, true),
    },
    fieldName: 'status',
    defaultValue: 1,
    formItemClass: 'col-span-2 md:col-span-2',
    label: '状态',
    rules: 'required',
  },
];

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 90,
  },
  schema: formSchema,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [Drawer, drawerApi] = useVbenDrawer({
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: onSubmit,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return null;
    }
    const data = drawerApi.getData<SysDeptApi.Dept>();
    if (data) {
      formData.value = data;
      await formApi.setValues(formData.value);
    } else {
      await formApi.resetForm();
    }
    await markInitialized();
  },
});

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    drawerApi.lock();
    const data = await formApi.getValues<SysDeptApi.Dept>();
    try {
      await (formData.value?.id
        ? apiUpdate({ id: formData.value.id, ...data })
        : apiAdd(data));
      resetInitialized();
      emit('success');
      drawerApi.close();
    } finally {
      drawerApi.unlock();
    }
  }
}

async function handleClosed() {
  formApi.resetForm();
  resetInitialized();
}

const getDrawerTitle = computed(() =>
  formData.value?.id ? '修改部门' : '新增部门',
);
</script>
<template>
  <Drawer class="w-[600px]" :title="getDrawerTitle">
    <BasicForm class="mx-4" />
  </Drawer>
</template>
