// 校验功能权限方法
import { useCoreStore } from '@/stores'
import type { DirectiveBinding, Directive } from 'vue'

function check(el: HTMLElement, binding: DirectiveBinding<string>) {
  const { value } = binding
  const coreStore = useCoreStore()
  const currentUser = coreStore.currentUser
  const authorities = coreStore.userAuthority?.permissions

  let flag: boolean = false

  if (!value) {
    flag = true
  } else {
    const permissions = value.split(',')
    if (currentUser && authorities) {
      flag = authorities.some((a) => permissions.includes(a.code))
    }
  }

  if (!flag) {
    el.parentNode?.removeChild(el)
  }
}

const permission: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding<string>) {
    check(el, binding)
  },
  updated(el: HTMLElement, binding: DirectiveBinding<string>) {
    check(el, binding)
  }
}

export default permission
