import type { App, Directive, DirectiveBinding } from 'vue'
// import router from '@/router'

const hasPermission = (value: string, args: any): boolean => {
  if (!value) {
    throw new Error('请设置操作权限值')
  }
  if (args?.btns?.includes(value)) {
    return true
  }
  return false
}

function hasPermi(el: Element, binding: DirectiveBinding) {
  const value = binding.value
  const args = binding?.arg

  const flag = hasPermission(value, args)
  if (!flag) {
    el.parentNode?.removeChild(el)
  }

  // else {
  //   el.parentNode?.appendChild(el)
  // }
}

const mounted = (el: Element, binding: DirectiveBinding<any>) => {
  hasPermi(el, binding)
}

// const updated = (el: Element, binding: DirectiveBinding<any>) => {
//   hasPermi(el, binding)
// }

const permiDirective: Directive = {
  mounted
  // updated
}

export const setupPermissionDirective = (app: App<Element>) => {
  app.directive('hasPermi', permiDirective)
}

export default permiDirective
