package com.njcn.gateway.utils;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.JWSObject;
import com.njcn.common.pojo.constant.LogInfo;
import com.njcn.common.pojo.constant.SecurityConstants;
import lombok.extern.slf4j.Slf4j;

import org.apache.logging.log4j.util.Strings;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;


@Slf4j
public class WebFluxRequestUtil {

    /**
     * HttpServletRequest获取头中存储的IP地址
     */
    public static String getRealIp(ServerHttpRequest request) {
        String ip = request.getURI().getHost();
        return StrUtil.isBlank(ip) ? LogInfo.UNKNOWN_IP : ip;
    }




    /**
     * ServerHttpRequest获取在网关中存储的用户token元信息
     */
    public static JSONObject getJwtPayload(ServerHttpRequest request) {
        JSONObject jsonObject = null;
        HttpHeaders headers = request.getHeaders();
        try {
            if (CollectionUtil.isNotEmpty(headers.get("authorization"))) {
                String token = headers.get("authorization").get(0);
                token = token.replace(SecurityConstants.AUTHORIZATION_PREFIX, Strings.EMPTY);
                JWSObject jwsObject = JWSObject.parse(token);
                String payload = jwsObject.getPayload().toString();
                jsonObject = JSONUtil.parseObj(payload);
            }
        } catch (Exception e) {
            log.error("解码网关中心传递的请求头中内容异常，异常为：{}", e.getMessage());
            e.printStackTrace();
        }
        return jsonObject;
    }
}
