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 { store } from '~/store';
import { SET_MENU } from '~/store/module/menu';
//菜单类型
type menuType = InterDataType<listMenuInfoType>;

// 获取用户权限路由列表
export const authRouterList = async () => {
  // 如果缓存中没有数据
  if (store.getState().Menu.menuList.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 ||
          ['/customManage/customVerification', '/flyerCenter', '/flyerCenter/flyerList'].includes(
            Obj.path as string,
          )
        ) {
          if (Obj.children) {
            Obj.children = [...getRouteList(Obj.children)];
          }
          pre.push(Obj);
        }
        return pre;
      }, []);
    };
    const arr = [...getRouteList(routerList)];
    // 将路由数据存到store中
    store.dispatch(SET_MENU(arr));
    // 完成后返回路由数据
    return Promise.resolve(arr);
  } else {
    return Promise.resolve(store.getState().Menu.menuList);
  }
};
//获取全部节点
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;
