package com.yn.bftl.thirdparty.common.util;

import com.yn.bftl.thirdparty.common.exception.YnceErrorException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * IP工具类
 *
 */
@Slf4j
public class IPUtils {

    public static void checkWhileIp(String whiteIp) {
        if (StringUtils.isEmpty(whiteIp)) {
            throw new YnceErrorException("参数不能为空");
        }
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String ip = IPUtils.getClientIpAddress(requestAttributes.getRequest());
        log.info("==========================u8 IP地址：" + ip);
        if (StringUtils.isEmpty(ip)) {
            throw new YnceErrorException("非法IP");
        }
        if (!whiteIp.equals(ip)) {
            throw new YnceErrorException("非法访问");
        }
    }

	/**
	 * 获取IP地址
	 */
	public static String getClientIpAddress(HttpServletRequest request) {
    	String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
        	log.error("IPUtils ERROR ", e);
        }

        return ip;
    }

    public static String getServerIpAddress() {
        try {
            InetAddress localhost = InetAddress.getLocalHost();
            return localhost.getHostAddress();
        } catch (UnknownHostException e) {
            log.error(e.getMessage());
            return null;
        }
    }

    public static void main(String[] args) {
        try {
            InetAddress localhost = InetAddress.getLocalHost();
            String ip = localhost.getHostAddress();
            System.out.println("服务端IP地址：" + ip);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

}
