<template>
  <el-dialog
    v-model="visible"
    :title="title"
    :width="width"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <slot />
    <template #footer>
      <div class="flex justify-end gap-2">
        <button class="mos-btn mos-btn-secondary" @click="handleClose">
          取消
        </button>
        <button
          class="mos-btn mos-btn-accent"
          :disabled="!hasAllPermissions(requiredPermissions)"
          @click="handleConfirm"
        >
          {{ confirmText }}
        </button>
      </div>
    </template>
  </el-dialog>
</template>

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

const props = withDefaults(defineProps<{
  /** 弹窗标题 */
  title: string
  /** 确认按钮文字 */
  confirmText?: string
  /** 弹窗宽度 */
  width?: string | number
  /** 是否显示 */
  modelValue: boolean
  /** 所需权限列表 */
  requiredPermissions: Permission[]
}>(), {
  confirmText: '确定',
  width: '500px'
})

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  confirm: []
}>()

const { hasAllPermissions } = usePermission()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const handleClose = () => {
  visible.value = false
}

const handleConfirm = () => {
  emit('confirm')
  handleClose()
}
</script>
