import type { App } from 'vue'
import { useAsyncRouteStore } from '@/store/modules/asyncRoute'
import { judementSameArr } from '@/utils/arrayOperation'

const asyncRouteStore = useAsyncRouteStore()

/**
 * 用户权限指令
 * @directive 单个权限验证（v-auth="xxx"）
 * @directive 多个权限验证，满足一个则显示（v-auths="{auth: [xxx,xxx]}"）
 * @directive 多个权限验证，全部满足则显示（v-auth-all="{auth: [xxx,xxx]}"）
 */
export function authDirective(app: App) {
  // 单个权限验证（v-auth="xxx"）
  app.directive('auth', {
    mounted(el, binding) {
      if (!asyncRouteStore.getAuths.some((v: string) => v === binding.value))
        el.parentNode.removeChild(el)
    }
  })
  // 多个权限验证，满足一个则显示（v-auths="{auth: [xxx,xxx]}"）
  app.directive('auths', {
    mounted(el, binding) {
      let flag = false
      asyncRouteStore.getAuths.map((val: string) => {
        binding.value.auth.map((v: string) => {
          if (val === v) flag = true
        })
      })
      if (!flag) el.parentNode.removeChild(el)
    }
  })
  // 多个权限验证，全部满足则显示（v-auth-all="{auth: [xxx,xxx]}"）
  app.directive('auth-all', {
    mounted(el, binding) {
      const flag = judementSameArr(binding.value.auth, asyncRouteStore.getAuths)
      if (!flag) el.parentNode.removeChild(el)
    }
  })
}

/**
 * 用户权限-状态 主要运用在tabs组件上面
 * @directive authStr 单个权限验证
 * @directive type  auth 单个权限， auths 多个权限满足一个就行， auth-all 多个权限都满足
 * @return true 有权限
 */
export const disAuthCheckStatus = (authStr: any, type = 'auth') => {
  if (type === 'auth') {
    return asyncRouteStore.getAuths.some((v: string) => v === authStr)
  }

  if (type === 'auths') {
    let flag = false
    asyncRouteStore.getAuths.map((val: string) => {
      authStr.map((v: string) => {
        if (val === v) flag = true
      })
    })
    return flag
  }

  if (type === 'auth-all') {
    const flag = judementSameArr(authStr, asyncRouteStore.getAuths)
    return flag
  }
}
