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

/**
 * 按钮权限校验
 */
export const perm: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding
    const { user } = useStore()
    if (value) {
      const requiredPerms = value // DOM绑定需要的按钮权限标识

      const hasPerm = user.perms?.some(perm => {
        return requiredPerms.includes(perm)
      })

      if (!hasPerm) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error(
        "need perms! Like v-has-perm=\"['sys:user:add','sys:user:edit']\""
      )
    }
  }
}
