import { Spin } from 'antd';
import React from 'react';
import type { MenuVO } from '@/services/system/menu';

export const loopMenuItem = (
  menus: MenuVO[],
  pId: number | string = '/',
): any[] => {
  return menus.map((item) => {
    let Component: React.ComponentType<any> | null = null;
    if (item.component && item.component.trim().length > 0) {
      // 防止配置了路由，但本地暂未添加对应的页面，产生的错误
      Component = React.lazy(() => {
        const importComponent = () => import(`@/pages/${item.component}`);
        const import404 = () => import('@/pages/404');
        return importComponent().catch(import404);
      });
    }

    const routeItem: any = {
      path: item.path,
      name: item.name,
      icon: '',
      id: item.id,
      parentId: pId,
      hideInMenu: !item.visible,
      children: [],
    };

    // 只有当 Component 存在时才添加 element 属性
    if (Component) {
      routeItem.element = (
        <React.Suspense
          fallback={<Spin style={{ width: '100%', height: '100%' }} />}
        >
          <Component />
        </React.Suspense>
      );
    } else if (item.children && item.children.length > 0) {
    }
    // 处理子菜单
    if (item.children && item.children.length > 0) {
      routeItem.children = loopMenuItem(item.children, item.id);
    }
    return routeItem;
  });
};
