
// src/components/AuthWrapper.tsx
import React, { useEffect, useState } from 'react';
import { history, useModel } from 'umi';
import type { IRoute } from 'umi';
import { Outlet } from '@umijs/max';

// 权限检查函数
function checkAccess(menu: IRoute[], pathname: string): boolean {
  for (const item of menu) {
    if (item.path === pathname) {
      return true;
    }
    if (item.children) {
      const hasAccess = checkAccess(item.children, pathname);
      if (hasAccess) {
        return true;
      }
    }
  }
  return false;
}

function removePrefix(input: string, prefix: string): string {
  if (input.startsWith(prefix)) {
    return input.slice(prefix.length);
  }
  return input;
}

// 权限包装组件
const AuthWrapper: React.FC = (props) => {
  const { initialState } = useModel('@@initialState');
  const [loading, setLoading] = useState(true);
  const [dataLoaded, setDataLoaded] = useState(false);

  useEffect(() => {
    if (!dataLoaded) {
      const menu = initialState?.memuData ?? [];
      if (menu.length > 0) {
        setDataLoaded(true);
        const { pathname } = history.location;
        const hasAccess = checkAccess(menu, removePrefix(pathname, '/CostAccountingSys'));
        // console.log({ hasAccess, menu, pathname });
        if (!hasAccess) {
          history.push('/noAccess');
        }
        setLoading(false);
      }
    }
  }, [initialState, dataLoaded]);

  return loading ? <>loading...</> : <Outlet />;
};

export default AuthWrapper;
export { checkAccess };
