/**
 * 权限组合式函数
 * 用于在组件中方便地使用权限功能
 */

import { ref, computed, onMounted } from 'vue'
import { RolePermissions, type Permission, type AdminRole, type DataScope } from '../auth/roles'
import { permissionService, type UserPermissions } from '../services/permission'
import { useAuthStore } from '../stores/auth'

// 当前用户权限
const currentPermissions = ref<Permission[]>([])
const currentRoles = ref<AdminRole[]>([])
const currentDataScope = ref<DataScope>('OWN')
const isLoading = ref(false)
const isInitialized = ref(false)
const permissionError = ref(false) // 权限加载错误状态，用于real模式下判定

/**
 * 权限码归一化工具
 * 支持三段式与四段式权限码的互相兼容匹配
 */

/**
 * 检查两个权限码是否语义相同（兼容三段式与四段式）
 * 例如: 'system.api-key.view' 与 'system.api-key.view.ALL' 视为相同
 */
function isPermissionCodeMatch(requested: string, granted: string): boolean {
  // 完全匹配
  if (requested === granted) return true

  // 提取权限前缀（去掉可能的 .ALL 后缀）
  const normalizeCode = (code: string): string => {
    // 移除末尾的 .ALL
    return code.replace(/\.ALL$/, '')
  }

  // 比较归一化后的权限码
  return normalizeCode(requested) === normalizeCode(granted)
}

/**
 * 检查权限码是否存在于用户权限列表中
 * 支持三段式与四段式权限码的互相兼容匹配
 */
function hasPermissionCode(permissions: Permission[], permission: Permission): boolean {
  // 直接匹配（优先精确匹配）
  if (permissions.includes(permission)) return true

  // 尝试兼容匹配
  return permissions.some(p => isPermissionCodeMatch(permission, p))
}

/**
 * 初始化权限信息
 */
export function usePermission() {
  const initialized = computed(() => isInitialized.value)

  /**
   * 从后端加载权限信息
   */
  async function loadPermissions() {
    if (isLoading.value) return
    // 演示模式下直接使用本地权限，不调用后端API
    const authStore = useAuthStore()
    if (authStore.isDemoMode) {
      loadLocalPermissions()
      return
    }
    isLoading.value = true
    permissionError.value = false
    try {
      const perms = await permissionService.getUserPermissions()
      currentPermissions.value = perms.permissions as Permission[]
      currentRoles.value = perms.roles as AdminRole[]
      currentDataScope.value = perms.dataScope
      isInitialized.value = true
    } catch (error) {
      console.error('加载权限失败:', error)
      // real模式下权限接口失败不回退到本地权限，保持错误状态
      permissionError.value = true
      currentPermissions.value = []
      currentRoles.value = []
      isInitialized.value = true
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 使用本地角色权限（后备方案）
   */
  function loadLocalPermissions() {
    // 优先从 mosquito_user 获取角色信息（新的存储键）
    let storedRole: AdminRole | null = null
    const storedUserStr = localStorage.getItem('mosquito_user')
    if (storedUserStr) {
      try {
        const storedUser = JSON.parse(storedUserStr)
        if (storedUser?.role) {
          storedRole = storedUser.role as AdminRole
        }
      } catch (e) {
        console.error('解析存储用户信息失败:', e)
      }
    }
    // 向后兼容：fallback 到旧的 userRole 键
    if (!storedRole) {
      storedRole = localStorage.getItem('userRole') as AdminRole
    }

    if (storedRole && RolePermissions[storedRole]) {
      currentRoles.value = [storedRole]
      currentPermissions.value = RolePermissions[storedRole]
      // 模拟数据权限
      if (storedRole === 'super_admin' || storedRole === 'system_admin' || storedRole === 'auditor') {
        currentDataScope.value = 'ALL'
      } else if (storedRole.includes('manager')) {
        currentDataScope.value = 'DEPARTMENT'
      } else {
        currentDataScope.value = 'OWN'
      }
    }
    isInitialized.value = true
  }

  /**
   * 检查是否拥有指定权限
   * 支持三段式与四段式权限码的互相兼容匹配
   * real模式下权限加载失败时返回false（不会获得本地权限）
   */
  function hasPermission(permission: Permission): boolean {
    // real模式下权限加载失败时，不授予任何权限
    if (permissionError.value) {
      return false
    }
    return hasPermissionCode(currentPermissions.value, permission)
  }

  /**
   * 检查是否拥有指定角色
   * real模式下权限加载失败时返回false
   */
  function hasRole(role: AdminRole): boolean {
    if (permissionError.value) {
      return false
    }
    return currentRoles.value.includes(role)
  }

  /**
   * 检查是否拥有任意一个权限
   */
  function hasAnyPermission(permissions: Permission[]): boolean {
    return permissions.some(p => hasPermission(p))
  }

  /**
   * 检查是否拥有所有权限
   */
  function hasAllPermissions(permissions: Permission[]): boolean {
    return permissions.every(p => hasPermission(p))
  }

  /**
   * 获取当前数据权限范围
   */
  function getDataScope(): DataScope {
    return currentDataScope.value
  }

  /**
   * 检查是否拥有所有数据权限
   */
  function hasAllDataScope(): boolean {
    return currentDataScope.value === 'ALL'
  }

  /**
   * 检查是否拥有部门数据权限
   */
  function hasDepartmentDataScope(): boolean {
    return currentDataScope.value === 'DEPARTMENT' || currentDataScope.value === 'ALL'
  }

  /**
   * 获取当前用户角色列表
   */
  function getRoles(): AdminRole[] {
    return currentRoles.value
  }

  /**
   * 获取当前用户权限列表
   */
  function getPermissions(): Permission[] {
    return currentPermissions.value
  }

  /**
   * 设置用户角色（用于本地开发/测试）
   */
  function setUserRole(role: AdminRole) {
    localStorage.setItem('userRole', role)
    currentRoles.value = [role]
    currentPermissions.value = RolePermissions[role] || []
    if (role === 'super_admin' || role === 'system_admin' || role === 'auditor') {
      currentDataScope.value = 'ALL'
    } else if (role.includes('manager')) {
      currentDataScope.value = 'DEPARTMENT'
    } else {
      currentDataScope.value = 'OWN'
    }
    isInitialized.value = true
  }

  /**
   * 清除权限信息
   */
  function clearPermissions() {
    currentPermissions.value = []
    currentRoles.value = []
    currentDataScope.value = 'OWN'
    isInitialized.value = false
    permissionError.value = false
    localStorage.removeItem('userRole')
  }

  // 初始化时自动加载
  onMounted(() => {
    if (!isInitialized.value) {
      loadPermissions()
    }
  })

  return {
    // 状态
    initialized,
    isLoading,
    currentPermissions,
    currentRoles,
    currentDataScope,
    permissionError,

    // 方法
    loadPermissions,
    hasPermission,
    hasRole,
    hasAnyPermission,
    hasAllPermissions,
    getDataScope,
    hasAllDataScope,
    hasDepartmentDataScope,
    getRoles,
    getPermissions,
    setUserRole,
    clearPermissions
  }
}

/**
 * 权限指令 composable
 * 用于模板中快速检查权限
 */
export function usePermissionCheck() {
  const { hasPermission, hasRole, hasAnyPermission } = usePermission()

  return {
    can: hasPermission,
    is: hasRole,
    canAny: hasAnyPermission
  }
}
