/**
 * 权限管理工具类
 * 提供用户权限验证、角色管理等功能
 */

import { PERMISSION_CONFIG } from '@/common/config/app.config.js'
import { useUserStore } from '@/common/store/modules/user.js'
import { createLogger } from './logger.js'

const logger = createLogger('Permission')

/**
 * 权限管理器类
 */
class PermissionManager {
  constructor() {
    this.userStore = null
    this.permissionCache = new Map()
    this.roleCache = new Map()
  }

  /**
   * 初始化权限管理器
   */
  init() {
    try {
      this.userStore = useUserStore()
      this.clearCache()
      logger.info('Permission manager initialized')
    } catch (error) {
      logger.error('Failed to initialize permission manager', null, error)
    }
  }

  /**
   * 检查用户是否有指定权限
   * @param {string|Array} permissions - 权限或权限数组
   * @param {string} operator - 操作符：'and'（所有权限）或 'or'（任一权限）
   * @returns {boolean} 是否有权限
   */
  hasPermission(permissions, operator = 'and') {
    try {
      if (!this.userStore) {
        this.init()
      }

      const user = this.userStore.userInfo
      if (!user || !user.id) {
        logger.debug('User not logged in, permission denied')
        return false
      }

      // 超级管理员拥有所有权限
      if (this.isSuperAdmin(user)) {
        return true
      }

      const userPermissions = this.getUserPermissions(user)
      const requiredPermissions = Array.isArray(permissions) ? permissions : [permissions]

      if (operator === 'and') {
        return requiredPermissions.every(permission => this.checkSinglePermission(permission, userPermissions))
      } else {
        return requiredPermissions.some(permission => this.checkSinglePermission(permission, userPermissions))
      }
    } catch (error) {
      logger.error('Error checking permission', { permissions, operator }, error)
      return false
    }
  }

  /**
   * 检查用户是否有指定角色
   * @param {string|Array} roles - 角色或角色数组
   * @param {string} operator - 操作符：'and'（所有角色）或 'or'（任一角色）
   * @returns {boolean} 是否有角色
   */
  hasRole(roles, operator = 'or') {
    try {
      if (!this.userStore) {
        this.init()
      }

      const user = this.userStore.userInfo
      if (!user || !user.id) {
        return false
      }

      const userRoles = this.getUserRoles(user)
      const requiredRoles = Array.isArray(roles) ? roles : [roles]

      if (operator === 'and') {
        return requiredRoles.every(role => userRoles.includes(role))
      } else {
        return requiredRoles.some(role => userRoles.includes(role))
      }
    } catch (error) {
      logger.error('Error checking role', { roles, operator }, error)
      return false
    }
  }

  /**
   * 检查是否为超级管理员
   * @param {Object} user - 用户信息
   * @returns {boolean} 是否为超级管理员
   */
  isSuperAdmin(user = null) {
    try {
      const targetUser = user || (this.userStore && this.userStore.userInfo)
      if (!targetUser) {
        return false
      }

      const userRoles = this.getUserRoles(targetUser)
      return userRoles.includes(PERMISSION_CONFIG.ROLES.SUPER_ADMIN)
    } catch (error) {
      logger.error('Error checking super admin', { user }, error)
      return false
    }
  }

  /**
   * 获取用户权限列表
   * @param {Object} user - 用户信息
   * @returns {Array} 权限列表
   */
  getUserPermissions(user) {
    try {
      const cacheKey = `permissions_${user.id}`
      
      if (this.permissionCache.has(cacheKey)) {
        return this.permissionCache.get(cacheKey)
      }

      const userRoles = this.getUserRoles(user)
      const permissions = new Set()

      // 根据角色获取权限
      userRoles.forEach(role => {
        const rolePermissions = PERMISSION_CONFIG.ROLE_PERMISSIONS[role] || []
        rolePermissions.forEach(permission => {
          if (permission === '*') {
            // 添加所有权限
            Object.values(PERMISSION_CONFIG.PERMISSIONS).forEach(p => permissions.add(p))
          } else if (permission.endsWith(':*')) {
            // 添加模块所有权限
            const module = permission.replace(':*', '')
            Object.values(PERMISSION_CONFIG.PERMISSIONS)
              .filter(p => p.startsWith(module + ':'))
              .forEach(p => permissions.add(p))
          } else {
            permissions.add(permission)
          }
        })
      })

      // 添加用户特定权限
      if (user.permissions && Array.isArray(user.permissions)) {
        user.permissions.forEach(permission => permissions.add(permission))
      }

      const result = Array.from(permissions)
      this.permissionCache.set(cacheKey, result)
      
      return result
    } catch (error) {
      logger.error('Error getting user permissions', { user }, error)
      return []
    }
  }

  /**
   * 获取用户角色列表
   * @param {Object} user - 用户信息
   * @returns {Array} 角色列表
   */
  getUserRoles(user) {
    try {
      const cacheKey = `roles_${user.id}`
      
      if (this.roleCache.has(cacheKey)) {
        return this.roleCache.get(cacheKey)
      }

      let roles = []

      // 从用户信息中获取角色
      if (user.roles && Array.isArray(user.roles)) {
        roles = [...user.roles]
      } else if (user.role) {
        roles = [user.role]
      }

      // 默认用户角色
      if (roles.length === 0) {
        roles = [PERMISSION_CONFIG.ROLES.USER]
      }

      this.roleCache.set(cacheKey, roles)
      return roles
    } catch (error) {
      logger.error('Error getting user roles', { user }, error)
      return [PERMISSION_CONFIG.ROLES.USER]
    }
  }

  /**
   * 检查单个权限
   * @private
   */
  checkSinglePermission(permission, userPermissions) {
    // 直接匹配
    if (userPermissions.includes(permission)) {
      return true
    }

    // 通配符匹配
    const parts = permission.split(':')
    if (parts.length === 2) {
      const [module, action] = parts
      const wildcardPermission = `${module}:*`
      if (userPermissions.includes(wildcardPermission)) {
        return true
      }
    }

    return false
  }

  /**
   * 清除权限缓存
   */
  clearCache() {
    this.permissionCache.clear()
    this.roleCache.clear()
    logger.debug('Permission cache cleared')
  }

  /**
   * 刷新用户权限
   * @param {string} userId - 用户ID
   */
  refreshUserPermissions(userId) {
    const permissionKey = `permissions_${userId}`
    const roleKey = `roles_${userId}`
    
    this.permissionCache.delete(permissionKey)
    this.roleCache.delete(roleKey)
    
    logger.debug('User permissions refreshed', { userId })
  }

  /**
   * 获取权限描述
   * @param {string} permission - 权限标识
   * @returns {string} 权限描述
   */
  getPermissionDescription(permission) {
    const descriptions = {
      // 用户管理
      'user:create': '创建用户',
      'user:read': '查看用户',
      'user:update': '更新用户',
      'user:delete': '删除用户',
      
      // 牲畜管理
      'livestock:create': '添加牲畜',
      'livestock:read': '查看牲畜',
      'livestock:update': '更新牲畜',
      'livestock:delete': '删除牲畜',
      
      // 健康管理
      'health:create': '添加健康记录',
      'health:read': '查看健康记录',
      'health:update': '更新健康记录',
      'health:delete': '删除健康记录',
      
      // 交易管理
      'trade:create': '创建交易',
      'trade:read': '查看交易',
      'trade:update': '更新交易',
      'trade:delete': '删除交易',
      
      // 财务管理
      'finance:create': '创建财务记录',
      'finance:read': '查看财务记录',
      'finance:update': '更新财务记录',
      'finance:delete': '删除财务记录',
      
      // 报表管理
      'report:create': '创建报表',
      'report:read': '查看报表',
      'report:export': '导出报表',
      
      // 系统管理
      'system:config': '系统配置',
      'system:log': '系统日志',
      'system:backup': '系统备份'
    }

    return descriptions[permission] || permission
  }

  /**
   * 获取角色描述
   * @param {string} role - 角色标识
   * @returns {string} 角色描述
   */
  getRoleDescription(role) {
    const descriptions = {
      [PERMISSION_CONFIG.ROLES.SUPER_ADMIN]: '超级管理员',
      [PERMISSION_CONFIG.ROLES.ADMIN]: '管理员',
      [PERMISSION_CONFIG.ROLES.MANAGER]: '经理',
      [PERMISSION_CONFIG.ROLES.OPERATOR]: '操作员',
      [PERMISSION_CONFIG.ROLES.VIEWER]: '查看者',
      [PERMISSION_CONFIG.ROLES.USER]: '普通用户'
    }

    return descriptions[role] || role
  }
}

// 创建权限管理器实例
const permissionManager = new PermissionManager()

// 权限检查装饰器
export const requirePermission = (permissions, operator = 'and') => {
  return (target, propertyKey, descriptor) => {
    const originalMethod = descriptor.value

    descriptor.value = function (...args) {
      if (!permissionManager.hasPermission(permissions, operator)) {
        logger.warn('Permission denied', { 
          method: propertyKey, 
          permissions, 
          operator 
        })
        
        uni.showToast({
          title: '权限不足',
          icon: 'none',
          duration: 2000
        })
        
        return Promise.reject(new Error('Permission denied'))
      }

      return originalMethod.apply(this, args)
    }

    return descriptor
  }
}

// 角色检查装饰器
export const requireRole = (roles, operator = 'or') => {
  return (target, propertyKey, descriptor) => {
    const originalMethod = descriptor.value

    descriptor.value = function (...args) {
      if (!permissionManager.hasRole(roles, operator)) {
        logger.warn('Role check failed', { 
          method: propertyKey, 
          roles, 
          operator 
        })
        
        uni.showToast({
          title: '角色权限不足',
          icon: 'none',
          duration: 2000
        })
        
        return Promise.reject(new Error('Role check failed'))
      }

      return originalMethod.apply(this, args)
    }

    return descriptor
  }
}

// 页面权限检查混入
export const permissionMixin = {
  onLoad() {
    // 检查页面权限
    if (this.$options.permissions) {
      const { permissions, operator = 'and', redirect = '/pages/login/login' } = this.$options.permissions
      
      if (!permissionManager.hasPermission(permissions, operator)) {
        logger.warn('Page permission denied', { 
          page: this.$mp.page.route, 
          permissions, 
          operator 
        })
        
        uni.showToast({
          title: '页面权限不足',
          icon: 'none',
          duration: 2000
        })
        
        setTimeout(() => {
          uni.redirectTo({ url: redirect })
        }, 2000)
        
        return
      }
    }
  }
}

// 导出便捷方法
export const permission = {
  /**
   * 检查权限
   */
  check: (permissions, operator) => permissionManager.hasPermission(permissions, operator),
  
  /**
   * 检查角色
   */
  checkRole: (roles, operator) => permissionManager.hasRole(roles, operator),
  
  /**
   * 是否为超级管理员
   */
  isSuperAdmin: () => permissionManager.isSuperAdmin(),
  
  /**
   * 获取用户权限
   */
  getUserPermissions: () => {
    const user = permissionManager.userStore?.userInfo
    return user ? permissionManager.getUserPermissions(user) : []
  },
  
  /**
   * 获取用户角色
   */
  getUserRoles: () => {
    const user = permissionManager.userStore?.userInfo
    return user ? permissionManager.getUserRoles(user) : []
  },
  
  /**
   * 清除缓存
   */
  clearCache: () => permissionManager.clearCache(),
  
  /**
   * 刷新权限
   */
  refresh: (userId) => permissionManager.refreshUserPermissions(userId),
  
  /**
   * 获取权限描述
   */
  getPermissionDesc: (permission) => permissionManager.getPermissionDescription(permission),
  
  /**
   * 获取角色描述
   */
  getRoleDesc: (role) => permissionManager.getRoleDescription(role)
}

// 导出权限管理器
export default permissionManager