
package com.tmerclub.cloud.common.util;

import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.common.constant.Constant;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * IP帮助工具
 *
 * @author tmerclub
 */
public class IpHelper {
    private static final String UNKNOWN = "unknown";


    /**
     * 得到用户的真实地址,如果有多个就取第一个
     *
     * @return
     */
    public static String getIpAddr() {
        if (RequestContextHolder.getRequestAttributes() == null) {
            return "";
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String[] ips = ip.split(Constant.COMMA);
        return ips[0].trim();
    }

    public static long getIpNumber() {
        String ipAddress = getIpAddr();
        return ipToLong(ipAddress);
    }
    public static long ipToLong(String ipAddress) {
        long result = 0;
        if (StrUtil.isBlank(ipAddress)) {
            return result;
        }
        String[] ipAddressInArray = ipAddress.split("\\.");
        for (int i = Constant.THREE; i >= 0; i--) {
            long ip = Long.parseLong(ipAddressInArray[3 - i]);
            result |= ip << (i * 8);

        }
        return result;
    }

    public static String longToIp(long ip) {
        if (ip == 0) {
            return "";
        }
        return ((ip >> 24) & 0xFF) + "."
                + ((ip >> 16) & 0xFF) + "."
                + ((ip >> 8) & 0xFF) + "."
                + (ip & 0xFF);
    }
}
