package com.sonic.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取地区工具类
 * Created by code on 2020/2/29
 */
@Slf4j
public class IpAddressUtils {

    public static String getIpAddress(HttpServletRequest request) {
        //优先从cloudFlare中获取用户的真实IP地址，获取不到再从代理中获取IP地址
        String cfIp = request.getHeader("Cf-Connecting-IP");
        if(StringUtils.isNotEmpty(cfIp)) {
            return cfIp;
        }
        //从亚马逊获取真实IP地址
        String awsIp = request.getHeader("x-original-forwarded-for");
        if(StringUtils.isNotEmpty(awsIp)) {
            return awsIp;
        }

        String Xip = request.getHeader("X-Real-IP");
        String ip = request.getHeader("X-Forwarded-For");

        if (StringUtils.isNotBlank(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = Xip;
        if (StringUtils.isNotBlank(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 获取UserAgent
     * @param request
     * @return
     */
    public static String getUserAgent(HttpServletRequest request) {
        return request.getHeader("user-agent");
    }
}
