<template>
    <button
        ref="_ref"
        :class="[
            ns.b(),    // el-button
            ns.m(_type),  // 传入 type 生成 el-button--primary/success/info 等
            ns.m(_size),   // 传入 size 得到 el-button--large/small
            ns.is('disabled', disabled), // is-disabled
            ns.is('loading', loading),
            ns.is('plain', plain),
            ns.is('round', round),
            ns.is('circle', circle),
            ns.is('text', text),
            ns.is('link', link),
            ns.is('has-bg', bg),
        ]"
        :aria-disabled="disabled || loading"
        :disabled="disabled || loading"
        :autofocus="autofocus"
        :type="nativeType"
        :style="buttonStyle"
        @click="handleClick"
    >
        <!--加载图标-->
        <template v-if="loading">
            <slot v-if="$slots.loading" name="loading"/>
            <mo-icon v-else :class="ns.is('loading')" class="el-icon-loading">
                <component :is="loadingIcon"/>
            </mo-icon>
        </template>
        <!--自定义图标-->
        <mo-icon v-else-if="icon || $slots.icon">
            <component :is="icon" v-if="icon"/>
            <slot v-else name="icon"/>
        </mo-icon>
        <!--shouldAddSpace为true时class才生效-->
        <span
            v-if="$slots.default"
            :class="ns.em('text', 'expand')"
        >
            <slot/>
        </span>
    </button>
</template>

<script lang="ts">
export default {
    name: "MoButton",
};
</script>
<script lang="ts" setup>
import {Text, computed, inject, ref, useSlots} from 'vue'
import {useNamespace} from '@moui/hooks'
import {buttonGroupContextKey} from '@moui/tokens'
import {buttonEmits, buttonProps} from './button.ts'
import {useButtonCustomStyle} from './button-custom'
import MoIcon from "@moui/components/icon"

const props = defineProps(buttonProps)
const emit = defineEmits(buttonEmits)
// 获取$slots
const slots = useSlots()

const buttonGroupContext = inject(buttonGroupContextKey, undefined)
const ns = useNamespace('button')
const _size = computed(() => buttonGroupContext?.size)
const _ref = ref<HTMLButtonElement>()
const _type = computed(() => props.type || buttonGroupContext?.type || '')

const buttonStyle = useButtonCustomStyle(props)

const handleClick = (evt: MouseEvent) => {
    emit('click', evt)
}

defineExpose({
    /** @description button html element */
    ref: _ref,
    /* /!** @description button size *!/
     size: _size,
     /!** @description button type *!/
     type: _type,
     /!** @description button disabled *!/
     disabled: disabled,
     /!** @description whether adding space *!/
     shouldAddSpace,*/
})
</script>
