import type { Directive, DirectiveBinding } from 'vue'
import { usePermissionStore } from '@/stores/permission'

export const permissionDirective: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const permissionStore = usePermissionStore()
    
    const { arg, value } = binding
    const checkType = arg || 'permission'
    
    if (!value) {
      console.warn('v-permission 指令需要提供权限值')
      el.style.display = 'none'
      return
    }
    
    let hasAccess = false
    
    if (checkType === 'role') {
      hasAccess = permissionStore.hasRole(value)
    } else if (checkType === 'permission') {
      hasAccess = permissionStore.hasPermission(value)
    } else {
      console.warn(`未知的权限检查类型: ${checkType}`)
      el.style.display = 'none'
      return
    }
    
    if (!hasAccess) {
      el.style.display = 'none'
    }
  }
}
