/**
 * v-auth
 * 按钮权限指令
 */
import { useUserStore } from '@/stores'
import type { Directive, DirectiveBinding } from 'vue'

const auth: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding
    const all_permission = '*:*:*'
    const permissions = useUserStore().permissionCodes

    if (typeof value === 'string') {
      if (!permissions.includes(value)) {
        el.parentNode && el.parentNode.removeChild(el)
      }
      return
    }

    if (value && value instanceof Array && value.length > 0) {
      const hasPermissions = value.every(item => all_permission === item || permissions.includes(item))
      if (!hasPermissions) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      return false
    }
  }
}

export default auth
