import type { Directive, DirectiveBinding } from 'vue'
import { getStorage } from '@/utils/storage'

/**
 * v-auth 指令 - 包含任一权限则显示
 * 用法：v-auth="'admin'" 或 v-auth="'user:read,user:write'"
 */
export const authDirective: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding.value, 'some')
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding.value, 'some')
  },
}

/**
 * v-auth-all 指令 - 包含全部权限才显示
 * 用法：v-auth-all="'user:read,user:write'"（必须同时拥有两个权限）
 */
export const authAllDirective: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding.value, 'every')
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding.value, 'every')
  },
}

/**
 * v-auth-not 指令 - 不包含权限则显示
 * 用法：v-auth-not="'admin'" 或 v-auth-not="'user:read'"
 */
export const authNotDirective: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding.value, 'none')
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding.value, 'none')
  },
}

/**
 * 权限检查核心逻辑
 * @param el DOM 元素
 * @param value 指令绑定的权限字符串（单个或逗号分隔的多个）
 * @param mode 'some'=任一满足, 'every'=全部满足, 'none'=不包含时显示
 */
function checkPermission(
  el: HTMLElement,
  value: string | string[],
  mode: 'some' | 'every' | 'none',
) {
  // 空字符串/空数组时：some/every 模式展示，none 模式隐藏
  if (!value || (Array.isArray(value) && value.length === 0)) {
    if (mode === 'none') {
      el.remove()
    } else {
      el.style.display = ''
    }
    return
  }

  // 统一处理为字符串数组
  const permissions = Array.isArray(value)
    ? value.map((p) => String(p).trim()).filter(Boolean)
    : String(value)
        .split(',')
        .map((p) => p.trim())
        .filter(Boolean)

  // 如果过滤后为空（比如传入 ",," 这种情况），同空值处理
  if (permissions.length === 0) {
    if (mode === 'none') {
      el.remove()
    } else {
      el.style.display = ''
    }
    return
  }

  // 白名单权限配置（可从后端获取或配置文件读取）
  const WHITE_LIST: string[] = getStorage('btnAuth') || []

  let hasPermission: boolean

  switch (mode) {
    case 'some':
      // 任一权限满足即显示
      hasPermission = permissions.some((p) => WHITE_LIST.includes(p))
      hasPermission ? (el.style.display = '') : el.remove()
      break

    case 'every':
      // 全部权限满足才显示
      hasPermission = permissions.every((p) => WHITE_LIST.includes(p))
      hasPermission ? (el.style.display = '') : el.remove()
      break

    case 'none':
      // 不包含任一权限时显示
      hasPermission = permissions.some((p) => WHITE_LIST.includes(p))
      hasPermission ? el.remove() : (el.style.display = '')
      break
  }
}

/**
 * 注册所有权限指令
 */
export function setupAuthDirective(app: any) {
  app.directive('auth', authDirective)
  app.directive('auth-all', authAllDirective)
  app.directive('auth-not', authNotDirective)
}
