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

// 获取用户权限路由列表
export const authRouterList = async () => {
  if (localStorage.getItem('roleId')) {
    const { result } = await SystemManageAPI.getListRoleMenuInfo({
      roleId: Number(localStorage.getItem('roleId')),
    });
    const ids: number[] = getAllKeys([result]);
    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 Promise.resolve([...getRouteList(routerList)]);
  }
  return Promise.resolve([]);
};
//获取全部节点
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 type routerItem = RouteObject & RouteObjectType;
