package com.jy.framework.utils;

import cn.hutool.core.net.Ipv4Util;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * 获取地址类
 */
@Slf4j
public class AddressUtils {

    private static final String INTERNAL_IP = "本机地址";
    private static final String UNKNOWN_ADDRESS = "未知地址";

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

    /**
     * 获取ip所在的省市
     *
     * @param ip ip
     * @return ip所在的省市
     */
    public static String getRealAddressByIP(String ip) {
        if (StrUtil.isBlank(ip)) {
            return UNKNOWN_ADDRESS;
        }
        try {
            String cleanHtmlTagIp = HtmlUtil.cleanHtmlTag(ip);
            if ("0:0:0:0:0:0:0:1".equals(cleanHtmlTagIp) || Ipv4Util.isInnerIP(cleanHtmlTagIp)) {
                return INTERNAL_IP;
            }
            return doGet(cleanHtmlTagIp);
        } catch (Exception e) {
            log.error("获取地理位置异常：{}", ip, e);
        }
        return UNKNOWN_ADDRESS;
    }

    /**
     * 获取ip所在的省市
     */
    private static String doGet(String ip) {
        HttpRequest httpRequest = HttpUtil.createGet(IP_URL).form("ip", ip).form("json", true);
        try (HttpResponse execute = httpRequest.execute()) {
            if (HttpServletResponse.SC_OK == execute.getStatus()) {
                return JSONObject.parseObject(execute.body()).getString("addr");
            } else {
                return UNKNOWN_ADDRESS;
            }
        }
    }

}
