package com.ruoyi.database.util;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class AmapGeocoding {


    public static String apiKey = "4cc27f0dbf3ebb77a3cf219866b405ad";



    /**
     * 根据地址名称获取地址经纬度
     * @param address （详细地址） 如：常熟市海虞北路27号
     * @return
     */
    public static String getLocation(String address) {
        // 对地址进行URL编码，处理特殊字符
        String encodedAddress = java.net.URLEncoder.encode(address);
        // 构建请求URL
        String urlStr = "https://restapi.amap.com/v3/geocode/geo?key=" + apiKey +
                "&address=" + encodedAddress + "&output=json";
        try {
            // 创建URL对象并建立连接
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 读取API返回的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 将响应转换为JSON对象便于解析
            JSONObject jsonResponse = new JSONObject(response.toString());

            // 检查API请求状态
            if ("1".equals(jsonResponse.getStr("status"))) {
                // 获取地理编码数组
                JSONArray geocodes = jsonResponse.getJSONArray("geocodes");
                if (geocodes.size() > 0) {
                    // 从第一个结果中获取经纬度
                    String location = geocodes.getJSONObject(0).getStr("location");
                    System.out.println("该地址的经纬度为: " + location); // 输出示例: "116.480881,39.989410"
                    // 如果需要单独使用经度和纬度
                    String[] lngLat = location.split(",");
                    String longitude = lngLat[0]; // 经度
                    String latitude = lngLat[1];  // 纬度
                    System.out.println("经度: " + longitude + ", 纬度: " + latitude);

                    return location;
                } else {
                    System.out.println("未找到该地址对应的经纬度。");
                }
            } else {
                // 处理请求失败的情况
                String errorInfo = jsonResponse.getStr("info");
                System.err.println("地理编码请求失败: " + errorInfo);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取周边地址信息，根据地址经纬度，距离，关键词查询
     * @param centerLocation （中心地址经纬度）如 ： 120.754471,31.666573
     * @param searchRadius （距离 单位：米）如 ：1000
     * @param searchKeyword （关键词） 如：停车场
     * @return
     */
    public static JSONArray getPois(String centerLocation,int searchRadius,String searchKeyword) {
        try {
            // 构建请求URL（注意：实际应用中需对keyword进行URL编码）
            String urlStr = String.format("https://restapi.amap.com/v3/place/around?key=%s&location=%s&radius=%d&keywords=%s&sortrule=distance",
                    apiKey, centerLocation, searchRadius, java.net.URLEncoder.encode(searchKeyword, "UTF-8"));
            // 创建URL对象并建立连接
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }

                // 解析JSON响应
                JSONObject jsonResponse = new JSONObject(response.toString());

                // 检查请求状态
                if ("1".equals(jsonResponse.getStr("status"))) {
                    JSONArray pois = jsonResponse.getJSONArray("pois");
                    System.out.println("找到 " + pois.size() + " 个结果:");

                    // 遍历并输出结果
                    for (int i = 0; i < pois.size(); i++) {
                        JSONObject poi = pois.getJSONObject(i);
                        String name = poi.getStr("name");
                        String address = poi.getStr("address");
                        String location = poi.getStr("location"); // 格式: "经度,纬度"
                        String distance = poi.getStr("distance", "未知"); // 距离中心点的距离

                        System.out.printf("名称: %s | 地址: %s | 经纬度: %s | 距离: %s米%n",
                                name, address, location, distance);
                    }
                    return pois;
                } else {
                    String errorInfo = jsonResponse.getStr("info");
                    System.err.println("请求失败: " + errorInfo);
                }
            } finally {
                conn.disconnect();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }


    public static void main(String[] args) {
//        String location = getLocation("海虞北路27号");
//        System.out.println(location);
//        120.754471,31.666573

//        getPois("120.754471,31.666573",1000,"常客隆超市");
    }
}
