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';
import Cookies from 'js-cookie';
//菜单类型
type menuType = InterDataType<listMenuInfoType>;

// 获取用户权限路由列表
export const authRouterList = async () => {
  if (localStorage.getItem('roleId') && Cookies.get('SHAREFLY-TOKEN')) {
    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) => {
        const Obj: RouteObjectType = { ...cur };
        if (ids.includes(Obj.meta.id) || Obj.meta.hidden || Obj.path?.includes('pilotTraining')) {
          if (Obj.children) {
            Obj.children = [...getRouteList(Obj.children)];
          }
          pre.push(Obj);
        }
        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;
