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

function check(el, binding) {
  const { value } = binding
  const userInfo = $store.getters && $store.getters.userInfo
  if (value && value instanceof Array) {
    if (value.length > 0) {
      let roles = []
      const permissionRoles = value
      if (userInfo.type === 1) {
        roles = ['admin'] // 供应商
      } else if (userInfo.type === 2) {
        roles = ['salesman'] // 业务员
      }
      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)
  }
})
