

/**
 * 根据用户菜单数据生成对应的路由
 * @param {array} menus
 * @param {function} pageCompontent
 */
export default function calcRoutes(menus = [], pageCompontent) {
  let _routes = [];
  if (menus && menus.length > 0) {
    const convertMenus = (routes, resRoutes, level) => {
      routes.map(e => {
        if (e.path) {
          let urlList = e.path.split('/');
          let path = urlList[level + 1];
          if (urlList.length > 2) {
            let itemRoutes = { path, component: pageCompontent(path), childRoutes: [] };
            //特殊处理 地址（url）分割后个数大于当前循环层级时
            if (urlList.length > level + 2) {
              let _itemRoutes = itemRoutes.childRoutes;
              for (let i = level + 2; i < urlList.length; i++) {
                let newItemRoutes = { path: urlList[i], component: pageCompontent(urlList[i]), childRoutes: [] };
                _itemRoutes.push(newItemRoutes);
                _itemRoutes = newItemRoutes.childRoutes;
              }
            }
            if (e.children && e.children.length > 0){
              convertMenus(e.children, itemRoutes.childRoutes, level + 1);
            }
            resRoutes.push(itemRoutes);
          } else {
            if (e.children && e.children.length > 0){
              convertMenus(e.children, resRoutes, level);
            }
          }
        }
      });
    };
    convertMenus(menus, _routes, 1);
  }
  return _routes;
}
