package com.nailart.utils;

import cn.hutool.core.io.resource.ResourceUtil;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Description IP 解析工具类,使用 ip2region 实现 IP 地址解析城市功能
 * @Classname IpAddressUtil
 * @Date 2025/7/11 0:04
 * @Created by 21616
 */

@Component
public class IpAddressUtil {
    private static Searcher searcher;

    // 初始化IP数据库
    static {
        try {
            // 从资源文件中读取ip2region.xdb
            InputStream inputStream = ResourceUtil.getStream("ip2region.xdb");
            byte[] dbContent = new byte[inputStream.available()];
            inputStream.read(dbContent);
            searcher = Searcher.newWithBuffer(dbContent);
        } catch (Exception e) {
            throw new RuntimeException("初始化IP地址解析器失败", e);
        }
    }

    /**
     * 根据IP获取城市信息
     *
     * @param ip IP地址
     * @return 城市信息（格式：国家|区域|省份|城市|ISP）
     */
    public String getCityInfo(String ip) {
        if (ip == null || ip.isEmpty()) {
            return "未知IP";
        }

        // 本地IP处理
        if ("127.0.0.1".equals(ip) || "localhost".equals(ip)) {
            return "本地主机";
        }

        try {
            String result = searcher.search(ip);
            return result != null ? result : "未知地址";
        } catch (IOException e) {
            return "解析失败";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
