package com.qmth.sop.common.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @Description: ip util
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2022/9/2
 */
public class IpUtil {
    private final static Logger log = LoggerFactory.getLogger(IpUtil.class);

    /**
     * 获取过程ip（默认不包含代理ip）
     *
     * @return
     */
    public static String getRemoteIp() {
        HttpServletRequest request = ServletUtil.getRequest();
        if (Objects.nonNull(request)) {
            return getRemoteIp(true);
        } else {
            return null;
        }
    }

    /**
     * excludeProxyIp
     *
     * @param excludeProxyIp 是否排除代理ip
     * @return
     */
    public static String getRemoteIp(boolean excludeProxyIp) {
        HttpServletRequest request = ServletUtil.getRequest();
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-real-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();
        }

        if (excludeProxyIp) {
            //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ip != null && ip.length() > 15) { //"***.***.***.***".length() = 15
                if (ip.indexOf(",") > 0) {
                    ip = ip.substring(0, ip.indexOf(","));
                }
            }
        }
        return ip;
    }
}
