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

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

// 当前用户权限
const currentPermissions = ref<Permission[]>([])
const currentRoles = ref<AdminRole[]>([])
const currentDataScope = ref<DataScope>('OWN')
const isLoading = ref(false)
const isInitialized = ref(false)

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

  /**
   * 从后端加载权限信息
   */
  async function loadPermissions() {
    if (isLoading.value) return
    isLoading.value = true
    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)
      // 使用本地角色权限作为后备
      loadLocalPermissions()
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 使用本地角色权限（后备方案）
   */
  function loadLocalPermissions() {
    // 从 localStorage 获取用户角色
    const 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
  }

  /**
   * 检查是否拥有指定权限
   */
  function hasPermission(permission: Permission): boolean {
    return currentPermissions.value.includes(permission)
  }

  /**
   * 检查是否拥有指定角色
   */
  function hasRole(role: AdminRole): boolean {
    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
    localStorage.removeItem('userRole')
  }

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

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

    // 方法
    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
  }
}
