import {HOME_PATH, LOGIN_PATH, NOT_FOUND_PATH, NO_PERMISSION_PATH} from '@routes';
import {menuStore} from '@stores';
import {ChildrenFC, shallowEqual} from '@utils';
import {useMemo} from 'react';
import {Navigate, useLocation} from 'react-router-dom';
import {useStore} from 'zustand';

const Jurisdiction: ChildrenFC = function({children}) {
  const {pathname} = useLocation();
  const menus = useStore(menuStore, state => state.menus, shallowEqual);

  const pass = useMemo(function() {
    const passRoutes = [LOGIN_PATH, NOT_FOUND_PATH, NO_PERMISSION_PATH, HOME_PATH];

    /**
     * 如果是直接通过的路由返回ture
     * 如果是需要校验的路由判断是否在返回的路由列表中
     */
    if (passRoutes.includes(pathname)) return true;

    return menus.findIndex(val => val.url === pathname) >= 0;
  }, [pathname, menus]);

  return (
    <>
      {pass ? children : <Navigate to={NO_PERMISSION_PATH} replace />}
    </>
  );
};

export default Jurisdiction;
