/**
 * 权限路由守卫
 * 根据用户权限控制页面访问
 */

import type { Router } from 'vue-router'
import type { Permission } from '../auth/roles'
import { usePermission } from '../composables/usePermission'

export interface RoutePermission {
  /** 路由名称 */
  name: string
  /** 所需权限 */
  requiredPermissions?: Permission[]
  /** 所需角色 */
  requiredRoles?: string[]
  /** 是否需要登录 */
  requiresAuth?: boolean
}

/**
 * 默认路由权限配置
 */
export const routePermissions: RoutePermission[] = [
  // 仪表盘
  { name: 'Dashboard', requiredPermissions: ['dashboard:view'] },

  // 用户管理
  { name: 'Users', requiredPermissions: ['user:view'] },
  { name: 'UserDetail', requiredPermissions: ['user:view'] },

  // 活动管理
  { name: 'Activities', requiredPermissions: ['activity:view'] },
  { name: 'ActivityDetail', requiredPermissions: ['activity:view'] },
  { name: 'ActivityCreate', requiredPermissions: ['activity:create'] },
  { name: 'ActivityConfigWizard', requiredPermissions: ['activity:create'] },

  // 奖励管理
  { name: 'Rewards', requiredPermissions: ['reward:view'] },

  // 风险管理
  { name: 'Risk', requiredPermissions: ['risk:view'] },

  // 审批中心
  { name: 'Approvals', requiredPermissions: ['approval:view'] },

  // 审计日志
  { name: 'AuditLogs', requiredPermissions: ['audit:view'] },

  // 系统配置
  { name: 'System', requiredPermissions: ['system:view'] },

  // 权限管理
  { name: 'Permissions', requiredPermissions: ['permission:view'] },

  // 邀请用户
  { name: 'InviteUser', requiredPermissions: ['user:create'] },

  // 通知
  { name: 'Notifications', requiredPermissions: ['dashboard:view'] }
]

/**
 * 创建权限路由守卫
 */
export function createPermissionGuard(router: Router) {
  const { hasPermission, hasRole, initialized } = usePermission()

  router.beforeEach(async (to, from, next) => {
    // 等待权限初始化
    if (!initialized.value) {
      await new Promise(resolve => {
        const checkInit = setInterval(() => {
          if (initialized.value) {
            clearInterval(checkInit)
            resolve(true)
          }
        }, 100)
        // 超时5秒后继续
        setTimeout(() => {
          clearInterval(checkInit)
          resolve(true)
        }, 5000)
      })
    }

    // 检查路由权限
    const routePermission = routePermissions.find(rp => rp.name === to.name)

    if (routePermission) {
      // 检查所需权限
      if (routePermission.requiredPermissions?.length) {
        const hasRequired = routePermission.requiredPermissions.some(permission =>
          hasPermission(permission as Permission)
        )
        if (!hasRequired) {
          // 没有权限，跳转到403页面
          return next({ name: 'Forbidden' })
        }
      }

      // 检查所需角色
      if (routePermission.requiredRoles?.length) {
        const hasRequiredRole = routePermission.requiredRoles.some(role =>
          hasRole(role as any)
        )
        if (!hasRequiredRole) {
          return next({ name: 'Forbidden' })
        }
      }
    }

    next()
  })
}

/**
 * 检查路由是否有权限访问
 */
export function canAccessRoute(routeName: string): boolean {
  const { hasPermission } = usePermission()
  const routePermission = routePermissions.find(rp => rp.name === routeName)

  if (!routePermission) {
    return true // 没有配置权限的路由默认允许访问
  }

  if (routePermission.requiredPermissions?.length) {
    return routePermission.requiredPermissions.some(permission =>
      hasPermission(permission as Permission)
    )
  }

  if (routePermission.requiredRoles?.length) {
    const { hasRole } = usePermission()
    return routePermission.requiredRoles.some(role => hasRole(role as any))
  }

  return true
}
