/**
 * 认证和权限控制工具
 */

import { UserInfo } from '@/api/auth'

// 用户角色枚举
export enum UserRole {
  ADMIN = 'admin',
  MANAGER = 'manager',
  TRAINEE = 'trainee'
}

// 权限枚举
export enum Permission {
  // 用户管理
  USER_VIEW = 'user:view',
  USER_CREATE = 'user:create',
  USER_UPDATE = 'user:update',
  USER_DELETE = 'user:delete',
  USER_MANAGE = 'user:manage',

  // 课程管理
  COURSE_VIEW = 'course:view',
  COURSE_CREATE = 'course:create',
  COURSE_UPDATE = 'course:update',
  COURSE_DELETE = 'course:delete',
  COURSE_ASSIGN = 'course:assign',
  COURSE_MANAGE = 'course:manage',

  // 考试管理
  EXAM_VIEW = 'exam:view',
  EXAM_CREATE = 'exam:create',
  EXAM_MANAGE = 'exam:manage',
  EXAM_ANALYSIS = 'exam:analysis',

  // 陪练管理
  TRAINING_VIEW = 'training:view',
  TRAINING_CREATE = 'training:create',
  TRAINING_MANAGE = 'training:manage',
  TRAINING_ANALYSIS = 'training:analysis',

  // 团队管理
  TEAM_VIEW = 'team:view',
  TEAM_CREATE = 'team:create',
  TEAM_UPDATE = 'team:update',
  TEAM_DELETE = 'team:delete',
  TEAM_ASSIGN = 'team:assign',
  TEAM_MANAGE = 'team:manage',

  // 数据分析
  ANALYTICS_VIEW = 'analytics:view',
  ANALYTICS_EXPORT = 'analytics:export',

  // 系统管理
  SYSTEM_CONFIG = 'system:config',
  SYSTEM_LOG = 'system:log',
  SYSTEM_MONITOR = 'system:monitor',

  // 岗位管理
  POSITION_VIEW = 'position:view',
  POSITION_CREATE = 'position:create',
  POSITION_UPDATE = 'position:update',
  POSITION_DELETE = 'position:delete'
}

// 角色权限映射
const ROLE_PERMISSIONS: Record<UserRole, Permission[]> = {
  [UserRole.ADMIN]: [
    // 管理员拥有所有权限
    ...Object.values(Permission)
  ],
  [UserRole.MANAGER]: [
    // 管理者权限
    Permission.USER_VIEW,
    Permission.COURSE_VIEW,
    Permission.COURSE_CREATE,
    Permission.COURSE_UPDATE,
    Permission.COURSE_ASSIGN,
    Permission.EXAM_VIEW,
    Permission.EXAM_CREATE,
    Permission.EXAM_ANALYSIS,
    Permission.TRAINING_VIEW,
    Permission.TRAINING_CREATE,
    Permission.TRAINING_MANAGE,
    Permission.TRAINING_ANALYSIS,
    Permission.TEAM_VIEW,
    Permission.TEAM_CREATE,
    Permission.TEAM_UPDATE,
    Permission.TEAM_ASSIGN,
    Permission.ANALYTICS_VIEW,
    Permission.ANALYTICS_EXPORT,
    Permission.POSITION_VIEW
  ],
  [UserRole.TRAINEE]: [
    // 学员权限
    Permission.COURSE_VIEW,
    Permission.EXAM_VIEW,
    Permission.TRAINING_VIEW,
    Permission.ANALYTICS_VIEW
  ]
}

// 认证管理类
class AuthManager {
  private userKey = 'current_user'
  private tokenKey = 'access_token'
  private refreshTokenKey = 'refresh_token'

  /**
   * 获取当前用户信息
   */
  getCurrentUser(): UserInfo | null {
    try {
      const userStr = localStorage.getItem(this.userKey)
      return userStr ? JSON.parse(userStr) : null
    } catch {
      return null
    }
  }

  /**
   * 设置当前用户信息
   */
  setCurrentUser(user: UserInfo): void {
    localStorage.setItem(this.userKey, JSON.stringify(user))
  }

  /**
   * 获取访问令牌
   */
  getAccessToken(): string | null {
    return localStorage.getItem(this.tokenKey)
  }

  /**
   * 设置访问令牌
   */
  setAccessToken(token: string): void {
    localStorage.setItem(this.tokenKey, token)
  }

  /**
   * 获取刷新令牌
   */
  getRefreshToken(): string | null {
    return localStorage.getItem(this.refreshTokenKey)
  }

  /**
   * 设置刷新令牌
   */
  setRefreshToken(token: string): void {
    localStorage.setItem(this.refreshTokenKey, token)
  }

  /**
   * 清除认证信息
   */
  clearAuth(): void {
    localStorage.removeItem(this.userKey)
    localStorage.removeItem(this.tokenKey)
    localStorage.removeItem(this.refreshTokenKey)
  }

  /**
   * 检查是否已登录
   */
  isAuthenticated(): boolean {
    const token = this.getAccessToken()
    const user = this.getCurrentUser()
    return !!(token && user)
  }

  /**
   * 检查token是否过期
   */
  isTokenExpired(): boolean {
    const token = this.getAccessToken()
    if (!token) return true

    try {
      // 解析JWT token
      const payload = JSON.parse(atob(token.split('.')[1]))
      const currentTime = Math.floor(Date.now() / 1000)
      return payload.exp < currentTime
    } catch {
      return true
    }
  }

  /**
   * 获取用户角色
   */
  getUserRole(): UserRole | null {
    const user = this.getCurrentUser()
    return user?.role as UserRole || null
  }

  /**
   * 检查用户是否有指定角色
   */
  hasRole(role: UserRole): boolean {
    const userRole = this.getUserRole()
    return userRole === role
  }

  /**
   * 检查用户是否有指定权限
   */
  hasPermission(permission: Permission): boolean {
    const userRole = this.getUserRole()
    if (!userRole) return false

    const rolePermissions = ROLE_PERMISSIONS[userRole] || []
    return rolePermissions.includes(permission)
  }

  /**
   * 检查用户是否有任一权限
   */
  hasAnyPermission(permissions: Permission[]): boolean {
    return permissions.some(permission => this.hasPermission(permission))
  }

  /**
   * 检查用户是否有所有权限
   */
  hasAllPermissions(permissions: Permission[]): boolean {
    return permissions.every(permission => this.hasPermission(permission))
  }

  /**
   * 检查是否为管理员
   */
  isAdmin(): boolean {
    return this.hasRole(UserRole.ADMIN)
  }

  /**
   * 检查是否为管理者
   */
  isManager(): boolean {
    return this.hasRole(UserRole.MANAGER)
  }

  /**
   * 检查是否为学员
   */
  isTrainee(): boolean {
    return this.hasRole(UserRole.TRAINEE)
  }

  /**
   * 检查是否可以访问指定路由
   */
  canAccessRoute(routePath: string): boolean {
    // 公共路由
    const publicRoutes = ['/login', '/register', '/404']
    if (publicRoutes.includes(routePath)) {
      return true
    }

    // 需要登录的路由
    if (!this.isAuthenticated()) {
      return false
    }

    // 根据路由路径检查权限
    if (routePath.startsWith('/admin')) {
      return this.isAdmin()
    }

    if (routePath.startsWith('/manager')) {
      return this.isManager() || this.isAdmin()
    }

    if (routePath.startsWith('/trainee')) {
      return true // 所有已登录用户都可以访问学员功能
    }

    if (routePath.startsWith('/analysis')) {
      return this.hasPermission(Permission.ANALYTICS_VIEW)
    }

    // 个人中心和首页所有已登录用户都可以访问
    if (routePath.startsWith('/user') || routePath === '/dashboard') {
      return true
    }

    return true
  }

  /**
   * 获取用户权限列表
   */
  getUserPermissions(): Permission[] {
    const userRole = this.getUserRole()
    if (!userRole) return []

    return ROLE_PERMISSIONS[userRole] || []
  }

  /**
   * 获取默认首页路由
   */
  getDefaultRoute(): string {
    const userRole = this.getUserRole()
    
    switch (userRole) {
      case UserRole.ADMIN:
        return '/admin/dashboard'
      case UserRole.MANAGER:
        return '/manager/team-dashboard'
      case UserRole.TRAINEE:
        return '/trainee/course-center'
      default:
        return '/dashboard'
    }
  }

  /**
   * 登录
   */
  async login(credentials: { username: string; password: string }): Promise<UserInfo> {
    // 这里调用登录API
    const { login } = await import('@/api/auth')
    const response = await login(credentials)
    
    // 保存认证信息
    this.setAccessToken(response.data.token.access_token)
    this.setRefreshToken(response.data.token.refresh_token)
    
    // 添加缺少的字段
    const userInfo: UserInfo = {
      ...response.data.user,
      created_at: response.data.user.created_at || new Date().toISOString(),
      updated_at: response.data.user.updated_at || new Date().toISOString()
    }
    this.setCurrentUser(userInfo)
    
    return userInfo
  }

  /**
   * 登出
   */
  async logout(): Promise<void> {
    try {
      // 调用登出API
      const { logout } = await import('@/api/auth')
      await logout()
    } catch (error) {
      console.warn('Logout API call failed:', error)
    } finally {
      // 清除本地认证信息
      this.clearAuth()
    }
  }

  /**
   * 刷新token
   */
  async refreshToken(): Promise<string> {
    const refreshTokenValue = this.getRefreshToken()
    if (!refreshTokenValue) {
      throw new Error('No refresh token available')
    }

    try {
      const { refreshToken: refreshTokenApi } = await import('@/api/auth')
      const response = await refreshTokenApi(refreshTokenValue)
      
      this.setAccessToken(response.data.token.access_token)
      return response.data.token.access_token
    } catch (error) {
      // 刷新失败，清除认证信息
      this.clearAuth()
      throw error
    }
  }
}

// 创建认证管理器实例
export const authManager = new AuthManager()

// 导出便捷方法（绑定this上下文）
export const getCurrentUser = () => authManager.getCurrentUser()
export const setCurrentUser = (user: UserInfo) => authManager.setCurrentUser(user)
export const getAccessToken = () => authManager.getAccessToken()
export const setAccessToken = (token: string) => authManager.setAccessToken(token)
export const getRefreshToken = () => authManager.getRefreshToken()
export const setRefreshToken = (token: string) => authManager.setRefreshToken(token)
export const clearAuth = () => authManager.clearAuth()
export const isAuthenticated = () => authManager.isAuthenticated()
export const isTokenExpired = () => authManager.isTokenExpired()
export const getUserRole = () => authManager.getUserRole()
export const hasRole = (role: UserRole) => authManager.hasRole(role)
export const hasPermission = (permission: Permission) => authManager.hasPermission(permission)
export const hasAnyPermission = (permissions: Permission[]) => authManager.hasAnyPermission(permissions)
export const hasAllPermissions = (permissions: Permission[]) => authManager.hasAllPermissions(permissions)
export const isAdmin = () => authManager.isAdmin()
export const isManager = () => authManager.isManager()
export const isTrainee = () => authManager.isTrainee()
export const canAccessRoute = (routePath: string) => authManager.canAccessRoute(routePath)
export const getUserPermissions = () => authManager.getUserPermissions()
export const getDefaultRoute = () => authManager.getDefaultRoute()
export const login = (credentials: { username: string; password: string }) => authManager.login(credentials)
export const logout = () => authManager.logout()
export const refreshToken = () => authManager.refreshToken()

export default authManager
