<template>
    <ElDialogInner
        v-bind="dialogAttrs"
        :width="resolvedWidth"
        :class="dialogClass"
        :draggable="resolvedDraggable"
        :close-on-click-modal="closeOnClickModal"
    >
        <template v-for="(_, name) in $slots" #[name]="slotData">
            <slot :name="name" v-bind="slotData || {}" />
        </template>
    </ElDialogInner>
</template>

<script setup lang="ts">
import { ElDialog as ElDialogInner } from 'element-plus'
import { computed, useAttrs } from 'vue'
import {
    getDialogPreset,
    resolveDialogSize,
    resolveDialogSizeByClass,
    type DialogSize
} from '@/config/dialog'

defineOptions({ inheritAttrs: false })

const props = defineProps<{
    /** 显式指定弹框尺寸：small | middle | big */
    dialogSize?: DialogSize
}>()

const attrs = useAttrs()

const resolvedSize = computed<DialogSize>(() => {
    if (props.dialogSize) return props.dialogSize

    const width = attrs.width as string | number | undefined
    if (width !== undefined && width !== null && width !== '') {
        return resolveDialogSize(width)
    }

    return resolveDialogSizeByClass(attrs.class)
})

const dialogPreset = computed(() => getDialogPreset(resolvedSize.value))

const resolvedWidth = computed(() => dialogPreset.value.width)

const dialogClass = computed(() => [
    'cn-dialog',
    `cn-dialog--${resolvedSize.value}`,
    dialogPreset.value.class,
    attrs.class
])

const dialogAttrs = computed(() => {
    const {
        width: _width,
        class: _class,
        draggable: _draggable,
        closeOnClickModal: _closeOnClickModal,
        ...rest
    } = attrs
    const { 'close-on-click-modal': _closeOnClickModalKebab, ...restWithoutKebab } = rest as Record<
        string,
        unknown
    >
    return restWithoutKebab
})

const resolvedDraggable = computed(() => {
    if (attrs.draggable !== undefined) return attrs.draggable as boolean
    return dialogPreset.value.draggable
})

const closeOnClickModal = computed(() => {
    if (attrs.closeOnClickModal !== undefined) return attrs.closeOnClickModal as boolean
    if (attrs['close-on-click-modal'] !== undefined) return attrs['close-on-click-modal'] as boolean
    return dialogPreset.value.closeOnClickModal
})
</script>
