import { useEffect } from 'react';
import { useRoutes, Navigate } from 'react-router-dom';
import { filterAsyncRouter } from './lazyLoadAndDelay'; 
import { useSelector } from 'react-redux';
import baseRouter from './baseRouter';

const addDefaultNavigation = (menuRoutes) => {
  menuRoutes.forEach(item => {
    const children = item.children;

    if (children && children.length > 0) {
      // 如果有子项，递归调用 addDefaultNavigation
      addDefaultNavigation(children);

      // 在 children 数组的开头添加默认导航项
      children.unshift({
        index: true,
        element: <Navigate to={children[0].path} />
      });
    }
  });
  return menuRoutes;
};

const GetroutesDyamic = () => {
  // 合并路由
  const { menuRouter } = useSelector(state => state.user);
  // console.log(menuRouter);
  useEffect(() => {
    if (menuRouter?.length) {
      const menuRoutes = filterAsyncRouter(menuRouter);
      const hasRoute = baseRouter[0].children;
      const newMenus = addDefaultNavigation(menuRoutes);
      const firstObj = {
        index: true,
        element: <Navigate to={newMenus[0].path} />
      }
      baseRouter[0].children = [firstObj, ...newMenus, ...hasRoute];
    }
    
  }, [menuRouter]);
  const element = useRoutes(baseRouter);

  return (
    <>
      {element}
    </>
  )
}

export {
  GetroutesDyamic
}
