import { isMatchRoute } from '.';
import { sessionStore } from './store';

// 获取完整的路由地址
export const pathHolder = (path?: string): string => {
  // @ts-ignore
  const basename = window.pathBase || '';
  if (basename) {
    return path ? `/${basename}${path}` : '';
  }
  return path || '';
};

const DEFAULT_AUTHORIZED_RELATIVE_ROUTE_LIST: {
  parent: string;
  pathList: string[];
}[] = [
  {
    parent: '/sysSetting/dict',
    pathList: ['/sysSetting/dict/data'],
  },
];
const UNAUTHORIZED_ROUTE_LIST: string[] = [];

// 判断路由是否是有效的
export function isEffectiveRoute(pathname: string) {
  // 判断路由权限
  // 1.判断是否是权限数据，即菜单列表中的路由地址
  // 2.判断是否是权限路由相关的路由，即不在菜单中的详情页面等
  // 3.判断是否是免登录页面
  // 4.判断是否是开发者本地设置的非权限路由

  // 不用处理路由地址了，接口获取之后已处理
  const authorizedRouteList = sessionStore.get('authorized-route-list') || [];

  const loginBlackRouteList = (
    sessionStore.get('login-black-route-list') || []
  ).map(pathHolder);

  const authorizedRelativeRouteList =
    DEFAULT_AUTHORIZED_RELATIVE_ROUTE_LIST.concat(
      sessionStore.get('authorized-relative-route-list') || [],
    ).map(({ parent, pathList }) => {
      return {
        parent: pathHolder(parent),
        pathList: (pathList || []).map(pathHolder),
      };
    });

  const unauthorizedRouteList = UNAUTHORIZED_ROUTE_LIST.concat(
    sessionStore.get('unauthorized-route-list') || [],
  ).map(pathHolder);

  const isAuthorizedRoute = authorizedRouteList.some(
    (item: any) => item.path === pathname,
  );
  const isUnauthorizedRoute = unauthorizedRouteList.some((path: string) =>
    isMatchRoute(path, pathname),
  );
  const isAuthorizedRelativeRoute = authorizedRelativeRouteList.some(
    (item: any) => {
      const { parent, pathList } = item || {};
      const isAuthorizedRoute = authorizedRouteList.some(
        (route: any) => route.path === parent,
      );
      if (isAuthorizedRoute) {
        return (pathList || []).some((path: string) =>
          isMatchRoute(path, pathname),
        );
      }
      return false;
    },
  );
  const isLoginBlackRoute = loginBlackRouteList.some((path: string) =>
    isMatchRoute(path, pathname),
  );
  return (
    isAuthorizedRoute ||
    isUnauthorizedRoute ||
    isAuthorizedRelativeRoute ||
    isLoginBlackRoute
  );
}
