package com.ai.da.common.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

@Slf4j
public class RequestInfoUtil {

    /**
     * description 获取客户端IP
     *
     * @param request
     * @return java.lang.String
     * @version 1.0
     * <p>
     * <p>
     * 使用了ng等代理服务器要在ng加以下配置
     * location / {
     * proxy_pass http://127.0.0.1:10678;
     * proxy_set_header Host $host;
     * proxy_set_header X-Real-IP $remote_addr;
     * proxy_set_header REMOTE-HOST $remote_addr;
     * proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     * }
     */
    public static String getIpAddress(HttpServletRequest request) {
        String 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.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 如果是多级代理，那么取第一个IP为客户端IP
        if (ip != null && ip.indexOf(",") != -1) {
            ip = ip.substring(0, ip.indexOf(",")).trim();
        }
        return ip;
    }

    /**
     * 免费 API 服务可能有请求频率限制，如果你需要处理大量 IP 地址，可能需要考虑使用付费服务或购买 IP 地理位置数据库。此外，始终要遵守 API 提供商的使用条款和隐私政策
     * @param ip https://ip-api.com/docs/api:json 使用的接口api
     * @return
     * {
     *   "query": "24.48.0.1",
     *   "status": "success",
     *   "country": "Canada",
     *   "countryCode": "CA",
     *   "region": "QC",
     *   "regionName": "Quebec",
     *   "city": "Montreal",
     *   "zip": "H1L",
     *   "lat": 45.6026,
     *   "lon": -73.5167,
     *   "timezone": "America/Toronto",
     *   "isp": "Le Groupe Videotron Ltee",
     *   "org": "Videotron Ltee",
     *   "as": "AS5769 Videotron Ltee"
     * }
     */
    public static Map getIPLocation(String ip) {
//        String ip = "117.143.125.1"; // 替换为你想查询的 IP 地址
//        String ip = "194.5.48.180"; // 替换为你想查询的 IP 地址
        String apiURL = "http://ip-api.com/json/" + ip;

        try {
            URL url = new URL(apiURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String output;
            StringBuilder outputBuilder = new StringBuilder();
//            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                outputBuilder.append(output);
                System.out.println(output);
            }
            conn.disconnect();
            Map map = JSONObject.parseObject(outputBuilder.toString(), Map.class);
            log.info("map: {}", map);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
