/**
 * v-hasPermiRouter 操作权限处理
 * Copyright (c) 2023 ded
 * 注意:此方法会通过路由名称进行过滤,所以不可以出现重复的路由名称
 */

import store from '@/store'
import router from '@/router'

export default {
  inserted(el, binding, vnode) {
    let pageRoute = router.currentRoute.matched[router.currentRoute.matched.length-1].name
    const { value } = binding
    const all_permission = "*:*:*";
    const permissions = store.getters && store.getters.permissions
    if (permissions == all_permission) {
      return true
    }else if (value && value instanceof Array && value.length > 0) {
      const permissionFlag = value
      let maxNum = 0;
      for(let i=0;i<permissions.length;i++){
        if(permissions[i].path == pageRoute){
          maxNum++
          if(permissionFlag[1]){
            let num = 0;
            for(let o=0;o<permissionFlag.length;o++){
              if(permissions[i].permissions == all_permission){
                num++
              }else{
                if(permissions[i].permissions.includes(permissionFlag[o], 0)){
                  num++
                }
              }
            }
            if(num == permissionFlag.length){
              return true
            } else {
              el.parentNode && el.parentNode.removeChild(el)
              return false
            }
          }else{
            const hasPermissions = permissions[i].permissions.some(permission => {
              return all_permission === permission || permissionFlag.includes(permission)
            })
            if (!hasPermissions) {
              el.parentNode && el.parentNode.removeChild(el)
            }
          }
        }
      }
      if (maxNum == 0){
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error(`请设置操作权限标签值`)
    }
  }
}

