import { reactive, toRefs, onUnmounted } from 'vue'

export function useCountDown(defaultTime: number) {
    let intervalId = 0

    const state = reactive({
        time: defaultTime, // 倒计时秒数
        status: 0 // 倒计时状态
    })

    const start = (callback: () => void) => {
        state.status = 1
        intervalId = window.setInterval(() => {
            state.time--
            if (state.time < 0) {
                stop()
                callback()
            }
        }, 1000)
    }

    const stop = () => {
        clearInterval(intervalId)
        state.time = defaultTime
        state.status = 0
    }

    onUnmounted(() => {
        stop()
    })

    return {
        ...toRefs(state),
        start,
        stop
    }
}