import Router from '@/router';
import APP from '@/services';
import { getLoginData } from '@/services/bus/login';
import { tokenCheck } from '@/services/socket/login/index';
import timerUtil from '@/utils/timer/timerUtil';

/**
 * token 分为 游客和登录token
 * 未登录取游客token
 */
export function getToken(): string {
    let result: string;
    const loginData = getLoginData();
    if (loginData) {
        result = loginData.Token;
    } else {
        result = APP.get('touristToken');
    }
    return result;
}

/**
 * 处理token校验
 */
export function handleTokenCheck() {
    return tokenCheck().catch((err) => {
        Router.push({ path: '/login' }); // 回到登录页面
        console.error(`token校验失败：${err}`);
        return Promise.reject(`token校验失败：${err}`);
    });
}

/**
 * 轮询校验token
 */
export function checkTokenLoop(): void {
    const timeDiff = APP.get('checkTokenTimeDiff');
    timerUtil.setInterval(() => {
        handleTokenCheck()
    }, timeDiff, 'tokenCheck');
}
