import { RouteObject } from 'react-router-dom';
import { RouteObjectType, routerList, whiteRouterList } from '~/router/router';
import { InterDataType } from '~/api/interface';
import { listMenuInfoType } from '~/api/interface/systemManageType';
//菜单类型
type menuType = InterDataType<listMenuInfoType>;

// 获取用户权限路由列表
export const authRouterList = (data?: menuType) => {
  const roleObj: menuType = data || JSON.parse(localStorage.getItem('roleObj') as string);
  if (roleObj) {
    const ids: number[] = getAllKeys([roleObj]);
    const getRouteList = (data: RouteObjectType[]) => {
      return data.reduce((pre: RouteObjectType[], cur) => {
        if (ids.includes(cur.meta.id) || cur.meta.hidden) {
          if (cur.children) {
            cur.children = getRouteList(cur.children);
          }
          pre.push(cur);
        }
        return pre;
      }, []);
    };
    return [...getRouteList(routerList)];
  }
  return [];
};
//获取全部节点
const getAllKeys = (data: menuType[]) => {
  return data.reduce((pre: number[], cur) => {
    pre.push(cur.id);
    if (cur.children) {
      pre.push(...getAllKeys(cur.children));
    }
    return pre;
  }, []);
};
// 整合路由数据
export const routes = [...authRouterList(), ...whiteRouterList];
// 路由表类型
export type routerItem = RouteObject & RouteObjectType;
