import type { DirectiveBinding } from 'vue'
import { useUserStore } from '@/stores/modules/user'

/**
 * v-perms 权限控制指令
 * @example v-perms="['auth.menu/add']"
 */
export default {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const userStore = useUserStore()
    const { value } = binding
    if (!value || !Array.isArray(value) || value.length === 0) {
      throw new Error(`请设置操作权限标签值，格式：v-perms="['auth.menu/add']"`)
    }
    const all_permission = '*'
    const hasPermission = value.some((perm) => {
      if (userStore.permissions.includes(all_permission)) {
        return true
      }
      return userStore.permissions.includes(perm)
    })
    if (!hasPermission) {
      el.parentNode?.removeChild(el)
    }
  }
}
