import React, { useEffect, useState } from 'react';
import { Menu } from 'antd';
import { useIntl, Link, useHistory } from 'umi';
import IconFont from '@/components/IconFont/IconFont';
import routerConfig from '../../config/router.config';

// 路由接口定义
interface IRouteItem {
  path: string;
  component?: string;
  name?: string;
  meta?: {
    title?: string;
    hide?: boolean;
    icon?: string;
  };
  routes?: IRouteItem[];
  children?: IRouteItem[];
  redirect?: string;
}

interface IMenuItem {
  label: string;
  key: string;
  path: string;
  icon: string;
  children?: IMenuItem[];
}

// 获取路由配置转换为菜单项
const generateMenuItems = (): IMenuItem[] => {
  // 找到主布局下的路由
  const mainLayoutRoute = routerConfig.find((route: IRouteItem) => route.path === '/');
  if (!mainLayoutRoute || !mainLayoutRoute.routes) return [];

  // 递归处理路由，生成菜单项
  const processRoutes = (routes: IRouteItem[], parentPath: string = ''): IMenuItem[] => {
    return routes
      .filter((route) => !route.redirect && route.name && !route.meta?.hide)
      .map((route) => {
        // 构建完整路径
        const routePath = route.path.startsWith('/')
          ? route.path
          : `${parentPath}/${route.path}`.replace(/\/+/g, '/');

        // 创建菜单项
        const menuItem: IMenuItem = {
          label: route.meta?.title ? `menu.${route.meta.title}` : `menu.${route.name || ''}`,
          key: route.name || '',
          path: routePath,
          icon: route.meta?.icon || 'icon-liebiaomoshi',
        };

        // 如果有子路由，递归处理
        if (route.routes && route.routes.length > 0) {
          const children = processRoutes(route.routes, routePath);
          if (children.length > 0) {
            menuItem.children = children;
          }
        }

        // 如果有children，递归处理
        if (route.children && route.children.length > 0) {
          const children = processRoutes(route.children, routePath);
          if (children.length > 0) {
            menuItem.children = children;
          }
        }

        return menuItem;
      });
  };

  return processRoutes(mainLayoutRoute.routes);
};

const items: IMenuItem[] = generateMenuItems();

const SiderMenu: React.FC = (props: any) => {
  //当前激活菜单
  const [current, setCurrent] = useState('index');
  const intl = useIntl();
  const history = useHistory();
  useEffect(() => {
    // 获取当前激活菜单
    const path = history.location.pathname;
    if (path.split('/').length > 1) {
      setCurrent(path.split('/')[path.split('/').length - 1]);
      return;
    }
  }, [history.location.pathname]);

  // 递归渲染菜单项
  const renderMenuItems = (menuItems: IMenuItem[]) => {
    return menuItems.map((item: IMenuItem) =>
      item.children && item.children.length > 0 ? (
        <Menu.SubMenu
          key={item.key}
          title={intl.formatMessage({ id: item.label })}
          icon={<IconFont type={item.icon} />}
        >
          {renderMenuItems(item.children)}
        </Menu.SubMenu>
      ) : (
        <Menu.Item key={item.key} icon={<IconFont type={item.icon} />}>
          <Link to={item.path}>{intl.formatMessage({ id: item.label })}</Link>
        </Menu.Item>
      ),
    );
  };

  return (
    <div className="header-menu">
      <Menu selectedKeys={[current]} mode="inline">
        {renderMenuItems(items)}
      </Menu>
    </div>
  );
};
export default SiderMenu;
