import type { NavigationGuardNext, RouteLocationNormalized } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { StorageManager } from '@/utils/storage'
import { ElMessage } from 'element-plus'
import type { UserType } from '@/types/auth'

// 路由权限配置
const ROUTE_PERMISSIONS: Record<string, UserType[]> = {
  '/admin': ['admin'],
  '/merchant': ['manager'],
  '/user': ['customer'],
  '/login': [], // 公开路由
  '/register': [], // 公开路由
  '/change-password': ['admin', 'manager', 'customer'], // 需要登录
}

// 公开路由（不需要认证）
const PUBLIC_ROUTES = ['/login', '/register', '/', '/error','/chat']

/**
 * 全局前置守卫
 * 检查用户认证状态和权限
 */
export const createAuthGuard = () => {
  return async (
    to: RouteLocationNormalized,
    from: RouteLocationNormalized,
    next: NavigationGuardNext,
  ) => {
    const authStore = useAuthStore()

    // 初始化认证状态（从本地存储恢复）
    if (!authStore.isAuthenticated && StorageManager.isLoggedIn()) {
      authStore.initAuth()
    }

    const targetPath = to.path
    const isPublicRoute = PUBLIC_ROUTES.some(
      (route) => targetPath === route || targetPath.startsWith(route),
    )

    // 如果是公开路由，直接通过
    if (isPublicRoute) {
      // 如果已登录用户访问登录页，重定向到对应模块
      if (targetPath === '/login' && authStore.isAuthenticated) {
        const redirectPath = authStore.getRedirectPath()
        next(redirectPath)
        return
      }
      next()
      return
    }

    // 检查是否已登录
    if (!authStore.isAuthenticated) {
      ElMessage.warning('请先登录')
      next({
        path: '/error',
        query: {
          type: 'auth',
          message: '请先登录',
          redirect: to.fullPath,
        },
      })
      return
    }

    // 检查路由权限
    const requiredRoles = getRequiredRoles(targetPath)
    if (requiredRoles.length > 0 && !hasPermission(authStore.userType, requiredRoles)) {
      ElMessage.error('您没有权限访问此页面')
      next({
        path: '/error',
        query: {
          type: '403',
          message: '您没有权限访问此页面',
          path: targetPath,
        },
      })
      return
    }

    // 验证通过，允许访问
    next()
  }
}

/**
 * 获取路由所需的角色权限
 */
function getRequiredRoles(path: string): UserType[] {
  // 查找最匹配的路由权限配置
  for (const [routePath, roles] of Object.entries(ROUTE_PERMISSIONS)) {
    if (path.startsWith(routePath)) {
      return roles
    }
  }

  // 默认需要登录（任何角色都可以访问）
  return ['admin', 'manager', 'customer']
}

/**
 * 检查用户是否有访问权限
 */
function hasPermission(userType: UserType | null, requiredRoles: UserType[]): boolean {
  if (!userType) return false
  if (requiredRoles.length === 0) return true
  return requiredRoles.includes(userType)
}

/**
 * 全局后置守卫
 * 处理页面标题等
 */
export const createAfterGuard = () => {
  return (to: RouteLocationNormalized) => {
    // 设置页面标题
    const title = getPageTitle(to.path, to.meta?.title as string)
    document.title = title
  }
}

/**
 * 获取页面标题
 */
function getPageTitle(path: string, metaTitle?: string): string {
  const baseTitle = '餐厅管理系统'

  if (metaTitle) {
    return `${metaTitle} - ${baseTitle}`
  }

  // 根据路径生成标题
  const titleMap: Record<string, string> = {
    '/login': '用户登录',
    '/register': '用户注册',
    '/change-password': '修改密码',
    '/admin': '管理员后台',
    '/merchant': '商户后台',
    '/user': '用户中心',
  }

  for (const [routePath, title] of Object.entries(titleMap)) {
    if (path.startsWith(routePath)) {
      return `${title} - ${baseTitle}`
    }
  }

  return baseTitle
}

/**
 * 路由错误处理
 */
export const createErrorHandler = () => {
  return (error: any) => {
    console.error('路由错误:', error)
    ElMessage.error('页面加载失败，请重试')
  }
}

/**
 * Token过期处理
 */
export const handleTokenExpired = () => {
  const authStore = useAuthStore()
  authStore.logout()
  ElMessage.warning('登录已过期，请重新登录')
  // 如果当前不在登录页，则跳转到登录页
  if (window.location.pathname !== '/login') {
    window.location.href = '/login'
  }
}

/**
 * 权限验证中间件
 * 可在组件中使用
 */
export const usePermissionCheck = () => {
  const authStore = useAuthStore()

  return {
    /**
     * 检查是否有指定权限
     */
    hasRole: (role: UserType): boolean => {
      return authStore.userType === role
    },

    /**
     * 检查是否有任一权限
     */
    hasAnyRole: (roles: UserType[]): boolean => {
      return roles.some((role) => authStore.userType === role)
    },

    /**
     * 检查是否为管理员
     */
    isAdmin: (): boolean => {
      return authStore.userType === 'admin'
    },

    /**
     * 检查是否为商户
     */
    isMerchant: (): boolean => {
      return authStore.userType === 'manager'
    },

    /**
     * 检查是否为客户
     */
    isCustomer: (): boolean => {
      return authStore.userType === 'customer'
    },
  }
}
