
import Cookies from "js-cookie";
import router from '@/router';
const TokenKey = "token";  

export function getToken() {
//   return Cookies.get(TokenKey);
    return sessionStorage.getItem(TokenKey);
}

export function setToken(token) {
//   return Cookies.set(TokenKey, token);
    return sessionStorage.setItem(TokenKey, token);
}

export function removeToken() {
//   return Cookies.remove(TokenKey);
    return sessionStorage.removeItem(TokenKey);
}

//获取用户信息
export function getUserInfo() {
    try {
        const userData = sessionStorage.getItem("userData");
       
        // 如果userData不存在，执行未授权处理
        if (!userData) { 
            handleUnauthorized();
            return null;
        }
        
        // 尝试解析JSON数据
        try {
            const parsedData = JSON.parse(userData);
            return parsedData;
        } catch (parseError) {
            console.error('用户数据格式错误，无法解析JSON:', parseError);
            // 数据格式错误也视为未登录
            sessionStorage.removeItem("userData");
            handleUnauthorized();
            return null;
        }
        
    } catch (error) {
        console.error('获取用户信息时发生错误:', error);
        handleUnauthorized();
        return null;
    }
}


function handleUnauthorized() { 
    removeToken();
    
    // 使用 nextTick 确保路由状态已更新
    import('vue').then(({ nextTick }) => {
        nextTick(() => {
            const currentPath = router.currentRoute.value.fullPath;  
            if (router.currentRoute.value.path !== '/login') {
                router.push({
                    path: '/login',
                    query: { 
                        redirect: currentPath !== '/login' ? currentPath : undefined
                    }
                });
            } else {
                window.location.reload();
            }
        });
    });
}