package com.ytpm.lemonios.config.ip2Regin;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.service.Ip2Region;
import org.lionsoul.ip2region.xdb.Util;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <a href="https://github.com/lionsoul2014/ip2region">离线IP地址定位</a>
 *
 * @author lih
 * @date 2025-12-25 15:09
 */
@Slf4j
@Component
public class IP2ReginService {

    @Resource
    private Ip2Region ip2Regin;


    public String parseIPAddress(String ip) {
        String result = null;
        if (StrUtil.isNotEmpty(ip)) {
            try {
                if (Util.parseIP(ip).length == 16) {
                    String urlString = "https://ip.zxinc.org/api.php?type=json&ip=" + ip;
                    try {
                        String json = HttpUtil.get(urlString, 200);
                        if (StrUtil.isNotEmpty(json)) {
                            JSONObject jsonObject = JSONObject.parseObject(json);
                            if (jsonObject.get("data") != null) {
                                result = jsonObject.getJSONObject("data").getString("location")
                                        .replace("\t", "|")
                                        .replace(" ", "|")
                                        .replace("||", "|");
                            }
                        }
                        return buildAddress(result);
                    } catch (Exception e) {
                        log.warn("ipv6地址解析接口调用失败:{}", urlString);
                    }
                }
                result = ip2Regin.search(ip);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return buildAddress(result);
    }


    private String buildAddress(String str) {
        if (StrUtil.isNotEmpty(str)) {
            List<String> addresses = new ArrayList<>();
            String[] arr = str.split("\\|");
            for (int i = 0; i < arr.length; i++) {
                if (i > 3) {
                    break;
                }
                if (i == 3) {
                    switch (arr[i]) {
                        case "移动":
                            arr[i] = "中国移动";
                            break;
                        case "电信":
                            arr[i] = "中国电信";
                            break;
                        case "联通":
                            arr[i] = "中国联通";
                            break;
                        case "广电":
                            arr[i] = "中国广电";
                            break;
                    }
                }
                addresses.add(arr[i]);
            }
            return String.join("|", addresses);
        }
        return str;
    }
}
