package cn.iocoder.yudao.framework.common.util.address;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class AddressUtil {

    // 替换成您在天地图官网申请的密钥
    private static final String API_KEY = "e11694af0e347f991a0b18f10f2491d3";

    public static void main(String[] args) {
        // 示例经纬度（深圳腾讯大厦）
        double longitude = 115.43835;
        double latitude = 28.200279;
        // 35.88052,114.8731
        try {
            String result = reverseGeocode(longitude, latitude);
            System.out.println("逆地理编码结果：");
            System.out.println(result);
        } catch (Exception e) {
            System.err.println("逆地理编码失败：");
            e.printStackTrace();
        }
    }


    public static String reverseGeocode(double longitude, double latitude) throws Exception {
        // 1. 构建请求参数（注意使用双引号）
        String postStr = String.format("{\"lon\":%f,\"lat\":%f,\"ver\":2}", longitude, latitude);

        // 2. URL编码参数
        String encodedPostStr = URLEncoder.encode(postStr, StandardCharsets.UTF_8.name());

        // 3. 构建完整URL
        String urlStr = "http://api.tianditu.gov.cn/geocoder?postStr=" + encodedPostStr
                + "&type=geocode&tk=" + API_KEY;

        // 4. 创建HTTP连接
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        // 5. 设置请求头（模拟浏览器访问）
        conn.setRequestProperty("User-Agent", "Mozilla/5.0");
        conn.setRequestProperty("Accept", "application/json");

        // 6. 获取响应
        int responseCode = conn.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取成功响应
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {

                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            }
        } else {
            // 读取错误信息
            try (BufferedReader errorReader = new BufferedReader(
                    new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8))) {

                StringBuilder errorResponse = new StringBuilder();
                String line;
                while ((line = errorReader.readLine()) != null) {
                    errorResponse.append(line);
                }

                throw new RuntimeException("API请求失败: HTTP " + responseCode
                        + "\n错误详情: " + errorResponse.toString());
            }
        }
    }
}
