package com.czg.utils;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 获取地址类
 *
 * @author admin admin@cashier.com
 * @since 1.0.0
 */
@UtilityClass
@Slf4j
public class AddressUtil {
    /**
     * IP地址查询
     */
    public final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";
    /**
     * 未知地址
     */
    public final String UNKNOWN = "未知";

    public static String getRealAddressByIp(String ip) {
        // 内网不查询
        if (NetUtil.isInnerIP(ip)) {
            return "内网IP";
        }
        try {
            Map<String, Object> paramMap = new HashMap<>(16);
            paramMap.put("ip", ip);
            paramMap.put("json", "true");
            String rspStr = HttpUtil.createGet(IP_URL).header("User-Agent","Apifox/1.0.0 (https://apifox.com)").form(paramMap).timeout(1000*5).execute().body();
            if (StrUtil.isEmpty(rspStr)) {
                log.error("获取地理位置异常 {}", ip);
                return UNKNOWN;
            }
            JSONObject obj = JSONUtil.parseObj(rspStr);
            String region = obj.getStr("pro");
            String city = obj.getStr("city");
            return String.format("%s %s", region, city);
        } catch (Exception e) {
            log.error("获取地理位置异常 {}", ip);
        }
        return UNKNOWN;
    }
}
