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

/**
 * 退出登录
 */
export function logout(callback?: () => void) {
    const { loginStore, accountStore } = useStore()
    socket.closeAll()
    timerTask.clearAll()
    loginStore.reset()
    accountStore.reset()
    callback && callback()
}

/**
 * 初始化业务数据
 */
export async function initBaseData() {
    const { enumStore, errorInfoStore, loginStore, userStore, futuresStore, menuStore, accountStore } = useStore()
    await enumStore.getAllEnumList()
    await errorInfoStore.getErrorInfoList()

    if (loginStore.getToken()) {
        await checkToken().then(() => checkTokenLoop())
        await Promise.all([
            userStore.getUserData(),
            menuStore.getUserMenuList(),
            futuresStore.getGoodsList(),
        ])

        accountStore.getAccountList()
    }
}

/**
 * 令牌效验
 */
export function checkToken() {
    const { loginStore } = useStore()
    const { LoginID, Token } = loginStore.loginInfo.value
    return tokenCheck({
        data: {
            LoginID,
            Token,
        },
        fail: () => eventBus.$emit('LogoutNotify')
    })
}

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

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