<template>
    <uv-button v-bind="binding" :disabled="counting" @click="handleClick">
        <template v-if="counting" #default>
            <uv-count-down ref="timer" :time="time" :auto-start="false" :format="format" @finish="counting=false"/>
        </template>
    </uv-button>
</template>

<script>
import {nextTick, ref} from 'vue'
import {buttonProps} from "@/uni_modules/uv-button/components/uv-button/uv-button.vue";
import {blockRunner, createPropDefine} from "@/utils";

export default {
    name: "mx-count-down",
    props: {
        ...buttonProps,
        time: createPropDefine(60 * 1000, Number),
        format: createPropDefine('ss'),
        type: createPropDefine('text'),
        plain: createPropDefine(true, Boolean),
        customStyle: createPropDefine({
            width: '40px',
            height: '32px',
            color: 'var(--primary-deep-color)'
        }, [Object, String]),
        validateBlock: createPropDefine(null, Function)
    },
    emits: ['click'],
    setup(props, {attrs, emit}) {
        const binding = {
            ...props,
            ...attrs
        }
        const counting = ref(false)
        const timer = ref(null)

        const handleClick = async function () {
            await blockRunner(props.validateBlock)
            if (counting.value) return
            counting.value = true // NOTE：这里手工控制，让template#default渲染出来timer才能挂钩
            emit('click')
            await nextTick() // NOTE: 等待template#default渲染之后
            timer.value.start()
        }
        return {
            binding,
            timer,
            counting,
            handleClick
        }
    }
}
</script>

<style scoped lang="scss">
::v-deep .uv-count-down__text {
    color: var(--primary-color);
}
</style>