package cn.novalon.manage.sys.util;

import org.springframework.stereotype.Component;

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

/**
 * IP地址解析工具类
 * 
 * 用于解析IP地址，获取地理位置信息
 * 
 * @author 张翔
 * @date 2026-03-26
 */
@Component
public class IpLocationParser {

    private static final Map<String, String> IP_LOCATION_CACHE = new HashMap<>();

    static {
        IP_LOCATION_CACHE.put("127.0.0.1", "本地");
        IP_LOCATION_CACHE.put("0:0:0:0:0:0:0:1", "本地");
        IP_LOCATION_CACHE.put("localhost", "本地");
    }

    public String parseLocation(String ip) {
        if (ip == null || ip.isEmpty()) {
            return "未知位置";
        }

        if (IP_LOCATION_CACHE.containsKey(ip)) {
            return IP_LOCATION_CACHE.get(ip);
        }

        if (isInternalIp(ip)) {
            return "内网";
        }

        return "未知位置";
    }

    private boolean isInternalIp(String ip) {
        if (ip == null || ip.isEmpty()) {
            return false;
        }

        String[] parts = ip.split("\\.");
        if (parts.length != 4) {
            return false;
        }

        try {
            int first = Integer.parseInt(parts[0]);
            int second = Integer.parseInt(parts[1]);

            if (first == 10) {
                return true;
            }
            if (first == 172 && second >= 16 && second <= 31) {
                return true;
            }
            if (first == 192 && second == 168) {
                return true;
            }
        } catch (NumberFormatException e) {
            return false;
        }

        return false;
    }
}
