import routes from './routes';

let routeArr = [];

// 菜单是否显示
// 没有 meta 或者 meta.title 为空, 或者 meta.hideInMenu = true 的 都不显示
const isShow = item => item.meta && item.meta.title && !item.meta.hideInMenu;

const hasChildren = (list) => {
  if (!list || list.length < 1) return false;

  // 如果子元素全部都是不显示的, 说明子菜单不需要显示
  return list.filter(it => !isShow(it)).length !== list.length;
}

const getPath = (parent, current = '') => {
  if (current.indexOf('/') === 0 || current.indexOf('http') === 0) return current;
  return `${parent}/${current}`.replace(/\/\//g, '/');
}

const getMenuItems = (dts = [], fullPath = '/') => {
  return dts.map(item => {
    const path = getPath(fullPath, item.path);

    routeArr.push({
      ...item,
      path,
    });

    //
    if (!isShow(item)) return false;
    
    const children = hasChildren(item.children) ? getMenuItems(item.children, path) : false;

    return Object.assign(
      {
        key: path,
        label: item.meta.title,
        title: item.meta.title,
        icon: item.meta.icon,
      },
      children && { children },
    )
  }).filter(Boolean);
}

const getItems = () => getMenuItems(routes[0]?.children);
const getRouteArr = () => {
  if (routeArr.length < 1) {
    getItems();
  }
  return routeArr;
}
// 
export {
  getItems,
  getRouteArr,
};
