import Vue from 'vue'
import $store from '@/store'

function check(el, binding) {
  const { value } = binding
  const roles = $store.getters && $store.getters.roles
  if (value && value instanceof Array) {
    if (value.length > 0) {
      const permissionRoles = value
      const hasPermission = roles.some(role => permissionRoles.includes(role))
      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    }
  } else {
    console.warn('need config Like v-permission="[\'admin\']" or v-permission="\'admin\'"')
  }
}

Vue.directive('permission', {
  inserted(el, binding) {
    check(el, binding)
  },
  update(el, binding) {
    check(el, binding)
  }
})
