package com.tuoheng.common.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.model.dto.LoginUser;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUserUtils {
    /**
     * 获取认证信息
     *
     * @return
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户登录信息
     *
     * @return
     */
    public static LoginUser getLoginUser() {
        // header中获取用户token
        String token = ServletUtils.getRequest().getHeader("th-token");
        String oUserJson = ServletUtils.getRequest().getHeader("o-user-json");
        String json = EncryptUtil.decodeUTF8StringBase64(oUserJson);
        JSONObject jsonObject = JSON.parseObject(json);
        String username = jsonObject.getString("username");
        Long oidcUserId = jsonObject.getLong("oUserId");
        // 这里可以自定义封装自己的用户信息
        //UserPo userPo = clientUserMapper.getUserByUserName(username);
        LoginUser user = new LoginUser()
                .setUsername(username)
                .setUserId(oidcUserId)
                .setThToken(token);
        return user;
    }

    public static String token() {
        // header中获取用户token
        String token = ServletUtils.getRequest().getHeader("th-token");
        if (StringUtils.isEmpty(token)) {
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "token不能为空");
        }
        return token;
    }

    /**
     * 获取username
     *
     * @return
     */
    public static String username() {
        // header中获取用户token
        String oUserJson = ServletUtils.getRequest().getHeader("o-user-json");
        if (StringUtils.isEmpty(oUserJson)) {
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "oUserJson不能为空");
        }
        String json = EncryptUtil.decodeUTF8StringBase64(oUserJson);
        JSONObject jsonObject = JSON.parseObject(json);
        String username = jsonObject.getString("username");
        return username;
    }

}