package com.qmth.themis.common.util;

import com.qmth.themis.common.exception.BusinessException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.lionsoul.ip2region.xdb.Searcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.Optional;

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

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

    /**
     * excludeProxyIp
     *
     * @param request
     * @param excludeProxyIp 是否排除代理ip
     * @return
     */
    public static String getRemoteIp(HttpServletRequest request, boolean excludeProxyIp) {
        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;
    }

    /**
     * 获取全局searcher
     *
     * @param path
     * @return
     */
    public static Searcher getSearcher(String path) throws IOException {
        InputStream inputStream = IpUtil.class.getClassLoader().getResourceAsStream(IP_REGION_FILE);
        Optional.ofNullable(inputStream).orElseThrow(() -> new BusinessException(IP_REGION_FILE + "未找到"));
        File file = new File(path + File.separator + IP_REGION_FILE);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        FileUtils.copyInputStreamToFile(inputStream, file);
        // 1、从 dbPath 加载整个 xdb 到内存。
        byte[] cBuff;
        try {
            cBuff = Searcher.loadContentFromFile(file.getPath());
        } catch (Exception e) {
            log.error("加载ip离线数据失败", e);
            if (e instanceof BusinessException) {
                throw new BusinessException(e.getMessage());
            } else {
                throw new RuntimeException(e);
            }
        } finally {
            if (Objects.nonNull(inputStream)) {
                inputStream.close();
            }
            if (Objects.nonNull(file)) {
                file.delete();
            }
        }

        // 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
        Searcher searcher;
        try {
            searcher = Searcher.newWithBuffer(cBuff);
        } catch (Exception e) {
            log.error("failed to create content cached searcher", e);
            if (e instanceof BusinessException) {
                throw new BusinessException(e.getMessage());
            } else {
                throw new RuntimeException(e);
            }
        }
        return searcher;
    }

    /**
     * 获取ip信息
     *
     * @param searcher
     * @param ip
     * @return
     */
    public static String getIpInfo(Searcher searcher, String ip) {
        if (Objects.isNull(searcher)) {
            return null;
        }
        String region = null;
        // 3、查询
        try {
            long start = System.currentTimeMillis();
            region = searcher.search(ip);
            long end = System.currentTimeMillis();
            log.info("region: {}, ioCount: {}, 耗时: {} 秒", region, searcher.getIOCount(), (end - start) / 1000);
        } catch (Exception e) {
            log.error("failed to search", e);
            if (e instanceof BusinessException) {
                throw new BusinessException(e.getMessage());
            } else {
                throw new RuntimeException(e);
            }
        }
        // 4、关闭资源 - 该 searcher 对象可以安全用于并发，等整个服务关闭的时候再关闭 searcher
        // searcher.close();
        // 备注：并发使用，用整个 xdb 数据缓存创建的查询对象可以安全的用于并发，也就是你可以把这个 searcher 对象做成全局对象去跨线程访问。
        return region;
    }
}
