// 权限管理工具函数

import { mapMaterialRoutePathToSubKey } from '../components/material/materialSubMenu';

const PERMISSION_KEY = 'permissionInfo';
const USER_KEY = 'user';
const ROLES_KEY = 'roles';
const PERMISSIONS_KEY = 'permissions';
const MENUS_KEY = 'menus';

// 权限信息接口
export interface PermissionInfo {
  user: {
    id: number;
    nickname: string;
    avatar?: string;
    deptId?: number;
    username: string;
    email?: string;
  };
  roles: string[];
  permissions: string[];
  menus: MenuItem[];
  uiComponentList?: any[];
}

// 菜单项接口
export interface MenuItem {
  id: number;
  parentId: number;
  name: string;
  path: string;
  component?: string | null;
  componentName?: string | null;
  icon?: string;
  visible: boolean;
  keepAlive?: boolean;
  alwaysShow?: boolean;
  children?: MenuItem[] | null;
}

// 设置权限信息
export const setPermissionInfo = (info: PermissionInfo) => {
  localStorage.setItem(PERMISSION_KEY, JSON.stringify(info));
  if (info.user) {
    localStorage.setItem(USER_KEY, JSON.stringify(info.user));
  }
  if (info.roles) {
    localStorage.setItem(ROLES_KEY, JSON.stringify(info.roles));
  }
  if (info.permissions) {
    localStorage.setItem(PERMISSIONS_KEY, JSON.stringify(info.permissions));
  }
  if (info.menus) {
    localStorage.setItem(MENUS_KEY, JSON.stringify(info.menus));
  }
};

// 获取权限信息
export const getPermissionInfo = (): PermissionInfo | null => {
  const info = localStorage.getItem(PERMISSION_KEY);
  return info ? JSON.parse(info) : null;
};

// 获取用户信息
export const getPermissionUser = () => {
  const info = getPermissionInfo();
  return info?.user || null;
};

// 获取角色列表
export const getRoles = (): string[] => {
  const info = getPermissionInfo();
  return info?.roles || [];
};

// 获取权限列表
export const getPermissions = (): string[] => {
  const info = getPermissionInfo();
  return info?.permissions || [];
};

// 获取菜单列表
// 返回值说明：
// - 如果权限信息存在且menus字段为数组（包括空数组），返回该数组
// - 如果权限信息不存在或menus字段不存在，返回null（用于区分空数组和不存在的情况）
export const getMenus = (): MenuItem[] | null => {
  const info = getPermissionInfo();
  if (!info) {
    return null; // 权限信息不存在
  }
  if (info.menus !== undefined && info.menus !== null) {
    return Array.isArray(info.menus) ? info.menus : [];
  }
  return null; // menus字段不存在
};

// 检查是否有某个权限
export const hasPermission = (permission: string): boolean => {
  const permissions = getPermissions();
  // 如果权限列表为空或包含空字符串，表示有所有权限（超级管理员）
  if (permissions.length === 0 || permissions.includes('')) {
    return true;
  }
  return permissions.includes(permission);
};

// 检查是否有某个角色
export const hasRole = (role: string): boolean => {
  const roles = getRoles();
  return roles.includes(role);
};

// 检查是否有任一权限
export const hasAnyPermission = (permissions: string[]): boolean => {
  if (permissions.length === 0) return true;
  return permissions.some(permission => hasPermission(permission));
};

// 检查是否有所有权限
export const hasAllPermissions = (permissions: string[]): boolean => {
  if (permissions.length === 0) return true;
  return permissions.every(permission => hasPermission(permission));
};

// 根据菜单ID检查是否有菜单权限
export const hasMenuPermission = (menuId: number): boolean => {
  const menus = getMenus();
  // 如果menus为null或空数组，返回false
  if (!menus || menus.length === 0) {
    return false;
  }
  // 递归查找菜单
  const findMenu = (menuList: MenuItem[], id: number): boolean => {
    for (const menu of menuList) {
      if (menu.id === id) {
        return menu.visible !== false;
      }
      if (menu.children && menu.children.length > 0) {
        if (findMenu(menu.children, id)) {
          return true;
        }
      }
    }
    return false;
  };
  return findMenu(menus, menuId);
};

// 根据菜单路径检查是否有菜单权限（会校验 visible）
export const hasMenuPathPermission = (path: string): boolean => {
  const menus = getMenus();
  if (!menus || menus.length === 0) return false;
  const findMenuByPath = (menuList: MenuItem[], menuPath: string): boolean => {
    for (const menu of menuList) {
      if (menu.path === menuPath || menu.path?.endsWith(menuPath)) {
        return menu.visible !== false;
      }
      if (menu.children && menu.children.length > 0) {
        if (findMenuByPath(menu.children, menuPath)) return true;
      }
    }
    return false;
  };
  return findMenuByPath(menus, path);
};

/** 只判断菜单树中是否包含该 path，不校验 visible */
export const hasMenuPath = (path: string): boolean => {
  const menus = getMenus();
  if (!menus || menus.length === 0) return false;
  const find = (list: MenuItem[], p: string): boolean => {
    for (const m of list) {
      if (m.path === p || m.path?.endsWith(p)) return true;
      if (m.children && m.children.length > 0 && find(m.children, p)) return true;
    }
    return false;
  };
  return find(menus, path);
};

// 过滤菜单（根据权限）
export const filterMenusByPermission = (menus: MenuItem[]): MenuItem[] => {
  return menus
    .filter(menu => menu.visible !== false)
    .map(menu => {
      const filteredMenu = { ...menu };
      if (menu.children && menu.children.length > 0) {
        filteredMenu.children = filterMenusByPermission(menu.children);
        // 如果子菜单都被过滤掉了，但菜单本身有component，则保留
        if (filteredMenu.children.length === 0 && !menu.component) {
          return null;
        }
      }
      return filteredMenu;
    })
    .filter((menu): menu is MenuItem => menu !== null);
};

// 清除权限信息
export const clearPermissionInfo = () => {
  localStorage.removeItem(PERMISSION_KEY);
  localStorage.removeItem(USER_KEY);
  localStorage.removeItem(ROLES_KEY);
  localStorage.removeItem(PERMISSIONS_KEY);
  localStorage.removeItem(MENUS_KEY);
};

// 根据菜单路径映射到前端菜单key
export const mapMenuPathToKey = (path: string): string | null => {
  // 系统管理相关
  if (path === '/system' || path.startsWith('/system/')) {
    if (path.includes('/system/menu') || path === '/system/menu') return 'menuManagement';
    if (path.includes('/system/dept') || path === '/system/dept') return 'departmentManagement';
    if (path.includes('/system/post') || path === '/system/post' || path.includes('/system/marsdept')) return 'positionManagement';
    if (path.includes('/system/role') || path === '/system/role') return 'roleManagement';
    if (path.includes('/system/dict') || path === '/system/dict') return 'dictionaryManagement';
    if (path.includes('/system/role') || path === '/system/role') return 'roleManagement';
    return 'systemConfig';
  }
  
  // 用户管理相关
  if (path === '/users' || path.startsWith('/users/')) {
    if (path.includes('/users/list')) return 'userList';
    if (path.includes('/users/notification')) return 'notificationManagement';
    return 'userManagement';
  }
  
  // 硬件管理相关
  if (path === '/hardware' || path.startsWith('/hardware/')) {
    if (path.includes('/hardware/cabinet')) return 'cabinet';
    if (path.includes('/hardware/key')) return 'key';
    if (path.includes('/hardware/lock')) return 'padlock';
    if (path.includes('/hardware/portable')) return 'portable';
    return 'hardwareManagement';
  }
  
  // 隔离作业相关 - clientSystem 路径（优先处理）
  if (path.startsWith('/clientSystem/IsolationWork/')) {
    if (path.includes('/processDesign') || path.endsWith('/processDesign')) return 'processDesign';
    if (path.includes('/sop') || path.endsWith('/sop')) return 'sopManagement';
    if (path.includes('/job') || path.endsWith('/job')) return 'workManagement';
    if (path.includes('/form') || path.endsWith('/form')) return 'formManagement';
    return 'isolationWork';
  }
  
  // 隔离作业相关 - jobTicket 路径
  if (path === '/jobTicket' || path.startsWith('/jobTicket/')) {
    if (path.includes('/form') || path.endsWith('/form')) return 'formManagement';
    if (path.includes('/processDesign') || path.endsWith('/design')) return 'processDesign';
    if (path.includes('/sop') || path.endsWith('/sop')) return 'sopManagement';
    if (path.includes('/job') || path.endsWith('/job')) return 'workManagement';
    if (path.includes('/step') || path.includes('/template')) return 'processTemplate';
    return 'isolationWork';
  }
  
  // 物资管理
  if (path === '/material') return 'materialManagement';
  if (path.startsWith('/material/')) {
    const k = mapMaterialRoutePathToSubKey(path);
    if (k) return k;
  }

  // 点位管理
  if (path === '/points' || path.startsWith('/points/')) {
    return 'locationManagement';
  }
  
  // 驾驶舱
  if (path === '/cockpit' || path === '/dashboard') {
    return 'dashboard';
  }
  
  // 任务管理相关
  if (path.includes('/task-management') || path.includes('/taskManagement') || path.includes('/admin-work') || path.includes('/adminWork')) {
    return 'taskManagement';
  }
  
  // 我的任务相关
  if (path.includes('/my-task') || path.includes('/myTask') || path.includes('/my-work')) {
    return 'myTask';
  }
  
  return null;
};

/**
 * 从菜单树中按顺序（深度优先）找到第一个 path 有效且 visible 的菜单路径
 */
export const getFirstMenuPath = (menus: MenuItem[] | null): string | null => {
  if (!menus || menus.length === 0) return null;
  const find = (list: MenuItem[]): string | null => {
    for (const m of list) {
      if (m.visible === false) continue;
      const p = (m.path || '').trim();
      if (p && p !== '/') return p;
      if (m.children && m.children.length > 0) {
        const c = find(m.children);
        if (c) return c;
      }
    }
    return null;
  };
  return find(menus);
};

/**
 * 根据 mapMenuPathToKey 的 key 映射为 { menu, subMenu }，供 navigateToMenu 使用
 */
export const getMenuAndSubMenuFromKey = (key: string): { menu: string; subMenu: string } => {
  const sys = ['menuManagement', 'departmentManagement', 'positionManagement', 'roleManagement', 'dictionaryManagement', 'cabinetManagement'];
  if (key === 'systemConfig' || sys.includes(key)) return { menu: 'systemConfig', subMenu: sys.includes(key) ? key : 'menuManagement' };
  if (key === 'userManagement' || key === 'userList' || key === 'notificationManagement') return { menu: 'userManagement', subMenu: key === 'userManagement' ? 'userList' : key };
  const hw = ['cabinet', 'key', 'padlock', 'portable'];
  if (key === 'hardwareManagement' || hw.includes(key)) return { menu: 'hardwareManagement', subMenu: hw.includes(key) ? key : 'cabinet' };
  if (key === 'locationManagement') return { menu: 'locationManagement', subMenu: 'locationManagement' };
  const iw = ['processDesign', 'sopManagement', 'workManagement', 'formManagement', 'processTemplate'];
  if (key === 'isolationWork' || iw.includes(key)) return { menu: 'isolationWork', subMenu: iw.includes(key) ? key : 'processDesign' };
  const mat = [
    'materialLockers',
    'materialInventory',
    'materialType',
    'materialStandard',
    'materialStandardPropertyValues',
    'materialInformation',
    'materialLoan',
    'materialInspectionPlan',
    'materialInspectionRecord',
    'materialReplacementRecord',
    'materialBlacklist',
    'materialInstructions',
  ];
  if (key === 'materialManagement' || mat.includes(key))
    return { menu: 'materialManagement', subMenu: mat.includes(key) ? key : 'materialLockers' };
  if (key === 'taskManagement') return { menu: 'taskManagement', subMenu: 'taskManagement' };
  if (key === 'myTask') return { menu: 'isolationWork', subMenu: 'myTask' };
  if (key === 'dashboard') return { menu: 'dashboard', subMenu: 'dashboard' };
  return { menu: key, subMenu: key };
};

/**
 * 根据菜单 path 得到 { menu, subMenu }，用于登录后跳转到非 /dashboard 的首个菜单时设置 navigateToMenu
 */
export const getMenuAndSubMenuFromPath = (path: string): { menu: string; subMenu: string } | null => {
  const k = mapMenuPathToKey(path);
  return k ? getMenuAndSubMenuFromKey(k) : null;
};

