<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import type { VbenFormSchema } from '#/adapter/form';
import type { SysMenuApi } from '#/api/auth/menu';

import { computed, ref } from 'vue';

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

import { Skeleton } from 'ant-design-vue';

import { useVbenForm, z } from '#/adapter/form';
import { apiAdd, apiMenuTree, apiUpdate } from '#/api/auth/menu';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { getMenuTypeOptions } from './data';

const emit = defineEmits<{
  success: [];
}>();
const formData = ref<SysMenuApi.menu>({});
const loading = ref(false);

function filterMenuTree(menuList: SysMenuApi.menu[]): SysMenuApi.menu[] {
  return menuList.filter((item) => {
    // 先递归处理子节点
    if (item.children && item.children.length > 0) {
      item.children = filterMenuTree(item.children);
      if (item.children.length === 0) {
        // item.isLeaf = true;
        delete item.children;
      }
    }
    // 返回 type === 2 的节点
    return item.type !== 2;
  });
}

const formSchema: VbenFormSchema[] = [
  {
    component: 'ApiTreeSelect',
    componentProps: {
      api: async () => {
        const menuArray = await apiMenuTree();
        const filterMenuArray = filterMenuTree(menuArray);
        const fullMenuTree = [
          {
            id: 0,
            name: '根目录',
            children: filterMenuArray,
          },
        ];
        addFullName(fullMenuTree, 'name', ' / ');
        return fullMenuTree;
      },
      class: 'w-full',
      treeLine: { showLeafIcon: false },
      treeIcon: false,
      filterTreeNode(input: string, node: Recordable<any>) {
        if (!input || input.length === 0) {
          return true;
        }
        const title: string = node.label;
        if (!title) return false;
        return title.includes(input);
      },
      getVxePopupContainer,
      labelField: 'name',
      showSearch: true,
      treeDefaultExpandAll: true,
      valueField: 'id',
      childrenField: 'children',
      // 筛选的字段
      treeNodeFilterProp: 'name',
      treeNodeLabelProp: 'fullName',
    },
    fieldName: 'parentId',
    label: '上级菜单',
    // renderComponentContent() {
    //   return {
    //     title({ label, meta }: { label: string; meta: Recordable<any> }) {
    //       const coms = [];
    //       if (!label) return '';
    //       if (meta?.icon) {
    //         coms.push(h(IconifyIcon, { class: 'size-4', icon: meta.icon }));
    //       }
    //       coms.push(h('span', { class: '' }, $t(label || '')));
    //       return h('div', { class: 'flex items-center gap-1' }, coms);
    //     },
    //   };
    // },
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      options: getMenuTypeOptions(),
      optionType: 'button',
    },
    defaultValue: 0,
    fieldName: 'type',
    formItemClass: 'col-span-2 md:col-span-2',
    label: '菜单类型',
  },
  {
    component: 'Input',
    fieldName: 'name',
    label: '标题',
    rules: 'required',
  },
  {
    component: 'Input',
    dependencies: {
      show: (values) => values.type !== 2,
      triggerFields: ['type'],
    },
    fieldName: 'pageName',
    label: '菜单名称',
    help: '菜单页面名称，如WorkSpace,Menu,Dept',
    rules: z
      .string()
      .min(2, '菜单名称至少2个字符')
      .max(30, '菜单名称最多30个字符'),
  },
  {
    component: 'Input',
    dependencies: {
      rules: (values) => {
        return values.type === 2 ? 'required' : null;
      },
      show: (values) => {
        return values.type !== 0;
      },
      triggerFields: ['type'],
    },
    fieldName: 'perms',
    label: '权限标识',
  },
  {
    component: 'InputNumber',
    fieldName: 'orderNum',
    help: '排序, 数字越小越靠前',
    label: '显示排序',
    rules: 'required',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      options: [
        { label: '显示', value: 1 },
        { label: '隐藏', value: 0 },
      ],
      optionType: 'button',
    },
    defaultValue: 1,
    dependencies: {
      // 类型不为按钮时显示
      show: (values) => values.type !== 2,
      triggerFields: ['type'],
    },
    fieldName: 'visible',
    help: '隐藏后不会出现在菜单栏, 但仍然可以访问',
    label: '是否显示',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      options: [
        { label: '是', value: 1 },
        { label: '否', value: 0 },
      ],
      optionType: 'button',
    },
    defaultValue: 1,
    dependencies: {
      // 类型为菜单时显示
      show: (values) => values.type === 1,
      triggerFields: ['type'],
    },
    fieldName: 'isCache',
    help: '路由的keepAlive属性',
    label: '是否缓存',
  },
  {
    component: 'Input',
    fieldName: 'remark',
    label: '拓展字段',
    formItemClass: 'items-baseline',
  },
];

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;
    }
    drawerApi.drawerLoading(true);
    loading.value = true;

    const data = drawerApi.getData<SysMenuApi.menu>();
    if (data) {
      formData.value = data;
      await formApi.setValues(formData.value);
    } else {
      formApi.resetForm();
    }
    await markInitialized();
    drawerApi.drawerLoading(false);
    loading.value = false;
  },
});

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    drawerApi.lock();
    const data =
      await formApi.getValues<Omit<SysMenuApi.menu, 'children' | 'id'>>();
    try {
      // await saveOne({ id: formData.value.id || 0, ...data });
      await (formData.value?.id
        ? apiUpdate({ id: formData.value.id, ...data })
        : apiAdd(data));
      resetInitialized();
      emit('success');
      drawerApi.close();
    } finally {
      drawerApi.unlock();
    }
  }
}

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

const getDrawerTitle = computed(() =>
  formData.value?.id ? '修改菜单' : '新增菜单',
);
</script>
<template>
  <Drawer class="w-[600px]" :title="getDrawerTitle">
    <Skeleton active v-if="loading" />
    <BasicForm v-show="!loading" class="mx-4" />
  </Drawer>
</template>
