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');
    const roleId = localStorage.getItem('roleId');
    if (!token && path !== '/login') {
      navigate('/login', { replace: true });
      return;
    }
    if (roleId && token) {
      // 整合路由数据
      authRouterList().then((value) => {
        if (value.length) {
          const routes = [...value, ...whiteRouterList];
          setRouter(routes);
          if (path === '/') {
            navigate({ pathname: value[0].children?.find((v: any) => !v.meta.hidden)?.path });
          }
        } else {
          message.warning('该账号暂无权限');
          navigate('/login', { replace: true });
        }
      });
    }
  };
  useEffect(() => {
    beforeEach();
  }, [location.pathname]);

  return useRoutes(router);
}

export default PrivateRouter;
