<script setup lang="ts">
import type { MenuItem } from 'primevue/menuitem';

import { createGetRoutes } from '@/plugins/router';

const router = useRouter();

type MenuItemWithRoute = MenuItem & { routeName?: string };
const menuItems = computed(() => {
  let flatArray: MenuItemWithRoute[] = createGetRoutes(router)()
    .filter((route) => !route.path.includes('/:'))
    .filter((route) => !route.meta.hidden)
    .map((route) => ({
      id: route.path,
      label: route.meta.title || `${(route.name as string) || route.path}`,
      routeName: route.name as string,
    }));

  flatArray = flatArray.map((item /* index */) => {
    let id = item.id;
    if (flatArray.some((item) => item.id.startsWith(`${id}/`))) {
      id = `${id}/index`;
    }
    // 去掉最前面的 /
    id = id.replace(/^\//, '');

    let parentId = id.replace(/\/[^/]+$/, '');
    if (parentId === id) {
      parentId = '_ROOT_';
    }
    return {
      ...item,
      parentId,
    };
  });
  const groupItems: Record<string, string>[] = [];
  for (const flatArrayItem of flatArray) {
    if (
      !groupItems.some((item) => item.id === flatArrayItem.parentId) && //
      flatArrayItem.parentId !== '_ROOT_'
    ) {
      let groupItemParentId = flatArrayItem.parentId.replace(/\/[^/]+$/, '');
      if (groupItemParentId === flatArrayItem.parentId) groupItemParentId = '_ROOT_';
      groupItems.push({
        id: flatArrayItem.parentId,
        label: `Group ${flatArrayItem.parentId}`,
        parentId: groupItemParentId,
      });
    }
  }
  console.debug(`groupItems :>>`, groupItems);
  const tree = arrayToTree([...flatArray, ...groupItems], { id: 'id', parentId: 'parentId', rootId: '_ROOT_' });

  // 递归把 children 改为 items
  function _convertChildrenToItems(tree: MenuItemWithRoute[]) {
    return tree.map((item) => {
      if (item.children.length > 0) {
        item.items = _convertChildrenToItems(item.children);
      } else {
        item.command = (/* event */) => {
          router.push({ name: item.routeName as never });
        };
      }
      delete item.children;
      return item;
    });
  }
  return _convertChildrenToItems(tree);
});
</script>

<template>
  <PanelMenu :model="menuItems" />
</template>

<style lang="scss" scoped></style>
