package org.springblade.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springblade.common.constant.IPInterceptorConstant;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.sing.desk.entity.IpBlack;
import org.springblade.sing.desk.service.IIpBlackService;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * IP工具
 */
@Slf4j
public class IPUtils {
	private static final BladeRedis bladeRedis = SpringContextHolder.getBean(BladeRedis.class);

	private static final IIpBlackService ipBlackService = SpringContextHolder.getBean(IIpBlackService.class);

	/**
	 * 添加到redis
	 */
	public static void addToRedis(){
		log.info("正在查询IP黑名单，并添加到Redis...");
		List<IpBlack> list = ipBlackService.list();
		//先删除
		bladeRedis.del(IPInterceptorConstant.CACHE_KEY);
		//后添加
		bladeRedis.hMset(IPInterceptorConstant.CACHE_KEY,list.stream().collect(Collectors.toMap(IpBlack::getIp,IpBlack::getType)));
	}

    /**
     * 获取真实IP
     * @param request 请求体
     * @return 真实IP
     */
    public static String getRealIp(HttpServletRequest request) {
        // 这个一般是Nginx反向代理设置的参数
        String ip = request.getHeader("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 处理多IP的情况（只取第一个IP）
        if (ip != null && ip.contains(",")) {
            String[] ipArray = ip.split(",");
            ip = ipArray[0];
        }
        return ip;
    }
}
