import { Navigate, Outlet, useModel, useLocation } from '@umijs/max';
import { useEffect, useMemo } from 'react';

function treeToArr(data) {
  const result = [];
  data?.forEach?.((item) => {
    const loop = (data) => {
      result.push(data?.path);
      let child = data.routes;
      if (child) {
        for (let i = 0; i < child.length; i++) {
          loop(child[i]);
        }
      }
    };
    loop(item);
  });
  return result;
}

export default (props) => {
  const { initialState } = useModel('@@initialState');
  const { pathname } = useLocation();

  const autharr = useMemo(() => {
    return treeToArr(initialState?.newMenu?.userHavePermList);
  }, [initialState?.newMenu?.userHavePermList]);

  if (autharr.includes(pathname) || pathname == '/' || pathname == '/welcome') {
    return <Outlet />;
  } else {
    return <Navigate to="/403" />;
  }
};
