<template>
  <component
    :is="tag"
    v-bind="bindProps"
    :class="buttonClass"
    :disabled="disabled || !hasPermission"
    @click="handleClick"
  >
    <slot />
  </component>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { usePermission } from '../composables/usePermission'
import type { Permission } from '../auth/roles'

const props = withDefaults(defineProps<{
  /** 所需权限 */
  permission: Permission
  /** 标签类型 */
  tag?: string
  /** 按钮类型 */
  type?: 'button' | 'submit' | 'reset'
  /** 禁用状态 */
  disabled?: boolean
  /** 是否显示为按钮 */
  asButton?: boolean
  /** 按钮变体 */
  variant?: 'primary' | 'secondary' | 'danger'
  /** 权限不足时隐藏 */
  hideWhenNoPermission?: boolean
}>(), {
  tag: 'button',
  type: 'button',
  disabled: false,
  asButton: true,
  variant: 'primary',
  hideWhenNoPermission: false
})

const emit = defineEmits<{
  click: [event: MouseEvent]
}>()

const { hasPermission } = usePermission()

const buttonClass = computed(() => {
  if (!props.asButton || !hasPermission(props.permission)) {
    return ''
  }

  const baseClass = 'mos-btn'
  const variantClass = props.variant === 'primary' ? 'mos-btn-accent' :
                      props.variant === 'danger' ? 'mos-btn-danger' : 'mos-btn-secondary'

  return `${baseClass} ${variantClass}`
})

const bindProps = computed(() => {
  const result: Record<string, unknown> = {}

  if (props.tag === 'button') {
    result.type = props.type
  }

  if (!props.asButton) {
    return result
  }

  if (!hasPermission(props.permission)) {
    if (props.hideWhenNoPermission) {
      return { style: 'display: none' }
    }
    result.style = 'opacity: 0.5; pointer-events: none'
  }

  return result
})

const handleClick = (event: MouseEvent) => {
  if (!hasPermission(props.permission)) {
    event.preventDefault()
    event.stopPropagation()
    return
  }
  emit('click', event)
}
</script>
