import { authRouterList } from '~/router/index';
import { useNavigate, useLocation, useRoutes } from 'react-router-dom';
import { useEffect, useState } from 'react';
import Cookies from 'js-cookie';
import { whiteRouterList } from '~/router/router';
import { message } from 'antd';

function PrivateRouter() {
  const location = useLocation();
  const navigate = useNavigate();
  const [router, setRouter] = useState(whiteRouterList);
  // 在切换路由之前判断
  const beforeEach = () => {
    // TODO: 判断是否登录 (需要改为实时获取地址栏的路由)
    const path = location.pathname;
    const token = Cookies.get('SHAREFLY-TOKEN');
    if (!token && path !== '/login') {
      navigate('/login', { replace: true });
      return;
    }
  };
  useEffect(() => {
    beforeEach();
    // 整合路由数据
    authRouterList().then((value) => {
      if (value.length) {
        const routes = [...value, ...whiteRouterList];
        setRouter(routes); //不同账号登录时，重新更新路由（有瑕疵）
      } else if (localStorage.getItem('roleId')) {
        message.warning('该账号暂无权限');
        navigate('/login', { replace: true });
      }
    });
  }, [location.pathname]);

  return useRoutes(router);
}

export default PrivateRouter;
