package org.springblade.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;

import java.net.InetAddress;
import java.net.UnknownHostException;
/**
 * @className:IpWhitelistUtils
 * @author:cwchen
 * @date:2025-09-09-14:45
 * @version:1.0
 * @description: IP 工具类
 */
@Slf4j
public class IpWhitelistUtils {

    /**
     * 检查IP是否在范围内
     */
    public static boolean isIpInRange(String ip, String startIp, String endIp) {
        try {
            long ipLong = ipToLong(ip);
            long startLong = ipToLong(startIp);
            long endLong = ipToLong(endIp);
            return ipLong >= startLong && ipLong <= endLong;
        } catch (Exception e) {
            log.error("IP范围检查失败: ip={}, start={}, end={}", ip, startIp, endIp, e);
            return false;
        }
    }

    /**
     * IP地址转long
     */
    private static long ipToLong(String ip) {
        String[] ipParts = ip.split("\\.");
        long result = 0;
        for (int i = 0; i < 4; i++) {
            result = result << 8 | Integer.parseInt(ipParts[i]);
        }
        return result;
    }

    /**
     * 获取客户端真实IP
     */
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP
            int index = ip.indexOf(",");
            if (index != -1) {
                ip = ip.substring(0, index);
            }
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "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();
            if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
                // 根据本机网卡取本机配置的IP
                try {
                    InetAddress inet = InetAddress.getLocalHost();
                    ip = inet.getHostAddress();
                } catch (UnknownHostException e) {
                    log.error("获取本地IP失败", e);
                }
            }
        }
        return ip;
    }
}
