package com.trade.client.security.utils;

import com.trade.client.enterprise.customer.domain.model.LoginUserInfo;
import com.trade.common.constant.HttpStatus;
import com.trade.common.exception.ServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @description: 用户信息工具类
 * @Author: wanglang
 * @Date: 2024/5/13
 * @Version: 1.0
 */
public class UserUtils {

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     **/
    public static LoginUserInfo getLoginUser() {
        LoginUserInfo loginUserInfo = null;
        try {
             loginUserInfo = (LoginUserInfo)getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
        }
        if (loginUserInfo == null) {
            throw new ServiceException("请您重新登录", HttpStatus.BAD_REQUEST);
        }
        return loginUserInfo;
    }

    /**
     * 获取用户ID
     */
    public static Long getCustomerUserId() {
        return getLoginUser().getCustomerUserId();
    }
}
