import { usePermissionStore } from '@/stores/permission'

export interface PermissionMapping {
  [key: string]: string | string[]
}

const permissionMapping: PermissionMapping = {
  'GET /users': 'system:user:list',
  'POST /users': 'system:user:add',
  'PUT /users': 'system:user:edit',
  'DELETE /users': 'system:user:remove',
  'GET /roles': 'system:role:list',
  'POST /roles': 'system:role:add',
  'PUT /roles': 'system:role:edit',
  'DELETE /roles': 'system:role:remove',
  'GET /menus': 'system:menu:list',
  'POST /menus': 'system:menu:add',
  'PUT /menus': 'system:menu:edit',
  'DELETE /menus': 'system:menu:remove',
  'GET /dict': 'system:dict:list',
  'POST /dict': 'system:dict:add',
  'PUT /dict': 'system:dict:edit',
  'DELETE /dict': 'system:dict:remove',
  'GET /config': 'system:config:list',
  'POST /config': 'system:config:list',
  'PUT /config': 'system:config:list',
  'DELETE /config': 'system:config:list',
  'GET /sys/config': 'system:config:list',
  'POST /sys/config': 'system:config:list',
  'PUT /sys/config': 'system:config:list',
  'DELETE /sys/config': 'system:config:list',
  'GET /files': 'system:file:list',
  'POST /files': 'system:file:upload',
  'DELETE /files': 'system:file:delete',
}

export function checkApiPermission(method: string, url: string): boolean {
  const key = `${method.toUpperCase()} ${url.split('?')[0]}`
  let requiredPermission = permissionMapping[key]
  
  if (!requiredPermission) {
    const baseUrl = url.split('?')[0].replace(/\/\d+$/, '')
    const baseKey = `${method.toUpperCase()} ${baseUrl}`
    requiredPermission = permissionMapping[baseKey]
  }
  
  if (!requiredPermission) {
    return true
  }
  
  if (key === 'GET /menus') {
    return true
  }
  
  const stored = localStorage.getItem('permission')
  if (!stored) {
    return true
  }
  
  try {
    const data = JSON.parse(stored)
    const permissions = data.permissions || []
    
    if (Array.isArray(requiredPermission)) {
      return requiredPermission.some(p => permissions.includes(p))
    }
    
    return permissions.includes(requiredPermission)
  } catch (error) {
    console.error('解析权限数据失败:', error)
    return true
  }
}

export function getRequiredPermission(method: string, url: string): string | string[] | null {
  const key = `${method.toUpperCase()} ${url.split('?')[0]}`
  return permissionMapping[key] || null
}
