package com.ruoyi.web.modules.diagnosis.support;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.Ip2RegionUtils;
import com.ruoyi.common.utils.ip.IpUtils;

/**
 * 根据提问人 IP 解析所在区县展示名（如「巴青区」）。
 */
@Component
public class ConsultAskerIpRegionResolver
{
    private static final Logger log = LoggerFactory.getLogger(ConsultAskerIpRegionResolver.class);

    public String resolveDistrictLabel(String ip)
    {
        String normalized = StringUtils.trim(ip);
        if (StringUtils.isEmpty(normalized))
        {
            return null;
        }
        if (IpUtils.internalIp(normalized))
        {
            return "内网区";
        }
        try
        {
            String rspStr = HttpUtils.sendGet(AddressUtils.IP_URL, "ip=" + normalized + "&json=true", Constants.GBK);
            if (StringUtils.isEmpty(rspStr))
            {
                log.warn("IP 区县在线解析失败，尝试 ip2region: {}", normalized);
                return resolveDistrictLabelByIp2Region(normalized);
            }
            JSONObject obj = JSON.parseObject(rspStr);
            String district = firstNonEmpty(obj.getString("region"), obj.getString("city"), obj.getString("pro"));
            if (StringUtils.isEmpty(district))
            {
                log.warn("IP 区县在线解析无结果，尝试 ip2region: {}", normalized);
                return resolveDistrictLabelByIp2Region(normalized);
            }
            return formatDistrictLabel(district);
        }
        catch (Exception ex)
        {
            log.warn("IP 区县在线解析异常 ip={}，尝试 ip2region: {}", normalized, ex.getMessage());
            return resolveDistrictLabelByIp2Region(normalized);
        }
    }

    private String resolveDistrictLabelByIp2Region(String ip)
    {
        String region = Ip2RegionUtils.searchRegion(ip);
        String district = Ip2RegionUtils.extractDistrictName(region);
        if (StringUtils.isEmpty(district))
        {
            log.warn("IP 区县 ip2region 解析失败: {}", ip);
            return "未知区";
        }
        return formatDistrictLabel(district);
    }

    static String formatDistrictLabel(String raw)
    {
        if (StringUtils.isEmpty(raw))
        {
            return "未知区";
        }
        String name = raw.trim();
        if (name.endsWith("区") || name.endsWith("县"))
        {
            return name;
        }
        if (name.endsWith("市") || name.endsWith("州") || name.endsWith("盟"))
        {
            return name;
        }
        return name + "区";
    }

    private static String firstNonEmpty(String... values)
    {
        if (values == null)
        {
            return null;
        }
        for (String value : values)
        {
            if (StringUtils.isNotEmpty(value))
            {
                return value;
            }
        }
        return null;
    }
}
