import { PermissionsType, useMyState } from '@/common';
import { useLocation } from 'react-router-dom';

const loopMenu = (permissions: PermissionsType[] | undefined) => {
  let tree: PermissionsType[] = [];
  let map: Record<number, PermissionsType> = {};
  permissions?.forEach((permission) => {
    map[permission.id] = {
      path: permission.type === 'Button' ? 'null' : permission.path,
      name: permission.name,
      label: permission.name,
      key: permission.path || permission.id.toString(),
      hideInMenu: permission.type === 'Button',
    };
  });

  permissions?.forEach((permission) => {
    let node = map[permission.id];
    const parentId = permission?.parent_id;

    if (parentId !== null && parentId !== undefined) {
      const parentNode = map[parentId];

      if (parentNode) {
        // 初始化 children 如果不存在
        if (!Array.isArray(parentNode.children)) {
          parentNode.children = [];
        }
        parentNode.children.push(node);
      } else {
        // 父节点不存在，作为根节点处理
        console.warn(
          `Parent node with id ${parentId} not found for permission ${permission.id}`,
        );
        tree.push(node);
      }
    } else {
      tree.push(node);
    }
  });
  return tree?.[0]?.children;
};

// 递归查找当前路由对应的菜单项
const findMenuByPath = (menus: any[], currentPath: string): any => {
  if (!menus || !Array.isArray(menus)) return null;

  for (const menu of menus) {
    // 跳过path为null或无效值的菜单
    if (!menu.path || menu.path === 'null' || menu.path === 'undefined') {
      // 继续检查子菜单
      if (menu.children && menu.children.length > 0) {
        const found = findMenuByPath(menu.children, currentPath);
        if (found) return found;
      }
      continue;
    }

    // 精确匹配当前路由
    if (menu.path === currentPath) {
      return menu;
    }

    // 如果有子菜单，递归查找
    if (menu.children && menu.children.length > 0) {
      const found = findMenuByPath(menu.children, currentPath);
      if (found) return found;
    }
  }
  return null;
};

// 根据当前路由获取子菜单
const getSubMenusByCurrentPath = (menus: any[], currentPath: string) => {
  if (!menus || !Array.isArray(menus) || !currentPath) {
    return [];
  }

  const currentMenu = findMenuByPath(menus, currentPath);

  // 如果找到当前菜单且有子菜单，返回子菜单
  if (currentMenu && currentMenu.children && currentMenu.children.length > 0) {
    return currentMenu.children;
  }

  return [];
};

// 自定义 Hook
export const useCurrentPermissions = () => {
  const { snap } = useMyState();
  const location = useLocation();

  const getCurrentPermissions = (res: any, path?: string) => {
    let objjs: any = [];
    snap.session.permissions?.forEach((permission: any) => {
      objjs.push(permission);
    });

    let data = objjs.sort((a: any, b: any) => {
      return a._lft - b._lft;
    });

    const menus = loopMenu(data);
    const currentSubMenus = getSubMenusByCurrentPath(
      menus,
      path || location.pathname,
    );

    // 直接过滤匹配的组件
    const matchedValues = currentSubMenus
      .filter((menu: any) => menu.key && res && res[menu.key])
      .map((menu: any) => res[menu.key]);

    return matchedValues;
  };
  return getCurrentPermissions;
};
