package com.jeequan.jeepay.core.utils.ip;

import cn.hutool.http.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.model.ip.IpAddressResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 获取地址类
 * 
 * @author ruoyi
 */
public class AddressUtils
{
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    // IP地址查询
    public static final String IP_URL = "https://whois.pconline.com.cn/ipJson.jsp";

    // 未知地址
    public static final String UNKNOWN = "未知";

    public static final String LOCATION_TEXT = "内网IP";

    public static IpAddressResult getRealAddressByIP(String ip)
    {
        // 内网不查询
        if (IpUtils.internalIp(ip))
        {
            return IpAddressResult.internal(ip);
        }
        try{
            HttpResponse response = HttpUtil.createGet(IP_URL)
                    .form("ip", ip)
                    .form("json", "true")
                    .contentType(ContentType.FORM_URLENCODED.getValue())
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.9999.999 Safari/537.36")
                    .execute();
            log.info("ip：{}，解析地域接口返回参数：{}", ip,response.body());
            if(!response.isOk()){
                return IpAddressResult.fail(ip,"获取地理信息异常");
            }
            return JSON.parseObject(response.body(), IpAddressResult.class);
        }catch (Exception e){
            log.error("获取地理位置异常 {}", ip);
        }
        return IpAddressResult.fail(ip,"获取地理位置异常");
    }

    public static void main(String[] args) {
        String ip = "111.175.29.61";
        IpAddressResult realAddressByIP = getRealAddressByIP(ip);
        System.out.println(JSON.toJSONString(realAddressByIP));
    }
}
