import { timerTask } from '@/utils/timer'
import { useLoginStore } from '@/stores'
import { tokenCheck } from '@/services/api/account'
import eventBus from '@/services/bus'

/**
 * 令牌校验
 */
export async function checkToken() {
    try {
        const { loginId, token } = useLoginStore()
        return await tokenCheck({
            LoginID: loginId,
            Token: token,
        })
    } catch (err) {
        eventBus.$emit('LogoutNotify')
        return Promise.reject(err)
    }
}

/**
 * 轮询校验令牌
 */
export function checkTokenLoop() {
    const delay = 1 * 60 * 1000 // 每1分钟校验一次令牌
    timerTask.setTimeout(() => {
        checkToken().then(() => checkTokenLoop())
    }, delay, 'checkToken')
}

/**
 * 停止令牌校验
 */
export function stopCheckToken() {
    timerTask.clearTimeout('checkToken')
}