import type { Directive, DirectiveBinding } from 'vue'
import { useUserStore } from '@/store/modules/user'

/**
 * 权限指令
 * 用法: v-permission="'user:add'" 或 v-permission="['user:add', 'user:edit']"
 */
export const permission: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding
    const userStore = useUserStore()
    const permissions = userStore.userInfo?.permissions || []
    
    // 超级管理员拥有所有权限
    if (permissions.includes('*')) {
      return
    }
    
    if (value) {
      const hasPermission = Array.isArray(value)
        ? value.some(p => permissions.includes(p))
        : permissions.includes(value)
      
      if (!hasPermission) {
        el.parentNode?.removeChild(el)
      }
    }
  }
}

/**
 * 检查是否有权限
 */
export function hasPermission(permission: string | string[]): boolean {
  const userStore = useUserStore()
  const permissions = userStore.userInfo?.permissions || []
  
  // 超级管理员拥有所有权限
  if (permissions.includes('*')) {
    return true
  }
  
  if (Array.isArray(permission)) {
    return permission.some(p => permissions.includes(p))
  }
  
  return permissions.includes(permission)
}

export default permission
