<template>
	<button
		:class="[
			'es-button',
			[btnType, btnSize],
			{
				'is-plain': plain,
				'is-round': round,
				'is-circle': circle,
				'is-disabled': disabled || loading,
			},
		]"
		:autofocus="autofocus"
		:type="nativeType"
		@click="handleClick"
	>
		<i v-if="icon && !loading" :class="['es-icon', icon]"></i>
		<i v-if="loading" :class="['es-icon', 'el-icon-loading']"></i>
		<slot></slot>
	</button>
</template>

<script lang="ts">
import { computed, defineComponent } from 'vue'
import type { PropType } from 'vue'

type IButtonType = PropType<
	'primary' | 'success' | 'warning' | 'danger' | 'info' | 'text' | 'default'
>
type IButtonNativeType = PropType<'button' | 'submit' | 'reset'>

interface IButtonProps {
	type: string
	size: string
	icon: string
	loading: boolean
	disabled: boolean
	plain: boolean
	autofocus: boolean
	round: boolean
	circle: boolean
	nativeType: string
}

type EmitFn = (evt: Event) => void

export default defineComponent({
	name: 'EsButton',
	props: {
		type: {
			type: String as IButtonType,
			default: 'default',
			validator: (val: string) => {
				return [
					'default',
					'primary',
					'success',
					'warning',
					'info',
					'danger',
					'text',
				].includes(val)
			},
		},
		size: {
			type: String as PropType<ComponentSize>,
			default: 'medium',
		},
		icon: {
			type: String,
			default: '',
		},
		loading: Boolean,
		disabled: Boolean,
		plain: Boolean,
		autofocus: Boolean,
		round: Boolean,
		circle: Boolean,
		nativeType: String as IButtonNativeType,
	},
	emits: ['click'],
	setup(props, { emit }) {
		const btnType = computed(
			() =>
				(props.type && `es-button--${props.type}`) ||
				'es-button--default',
		)
		const btnSize = computed(
			() =>
				(props.size && `es-button--size--${props.size}`) ||
				'es-button--size--medium',
		)
		const handleClick = () => {
			emit('click', ...arguments)
		}
		return {
			btnType,
			btnSize,
			handleClick,
		}
	},
})
</script>
