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>;

// 缓存路由列表
let routerListStore: any[] = [];
// 获取用户权限路由列表
export const authRouterList = async () => {
  if (localStorage.getItem('roleId') && Cookies.get('SHAREFLY-TOKEN')) {
    // 如果缓存中没有数据
    if (routerListStore.length === 0) {
      // 加载路由数据
      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;
        }, []);
      };
      const arr = [...getRouteList(routerList)];
      // 将路由数据存到store中
      routerListStore = arr;
      // 完成后返回路由数据
      return Promise.resolve(arr);
    } else {
      return Promise.resolve(routerListStore);
    }
  }
  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;
