package com.ho.common.tools.util;

import com.ho.common.tools.entity.MyAddress;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author kerwin
 *
 * 海外地址反向解析
 *
 */
@Slf4j
public class AbroadAddressUtils {

    static String APIKEY = "AIzaSyAM4JOtE9yt48f60ATwByB7uWzTIrYSSUg";
    // 正则表达式-中文字符
    static String PATTERN1 = "[\u4e00-\u9fff]";
    // 正则表达式-数字
    static String PATTERN2 = "\\d";

    public static MyAddress getAddress(String lat, String lng){
        // 构建API请求URL
        String urlString = "https://maps.googleapis.com/maps/api/geocode/json?" +
                "latlng=" + lat + "," + lng +
                "&language=zh-CN&key=" + APIKEY;
        // 发送HTTP请求
        URL url = null;
        StringBuilder response = new StringBuilder();
        try {
            url = new URL(urlString);
            // 创建代理（如果不需要代理，可以移除这部分）
//            Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 4781));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10000); // 10秒连接超时
            conn.setReadTimeout(10000);    // 10秒读取超时
            // 检查响应状态
            int responseCode = conn.getResponseCode();
            if (responseCode != 200) {
                throw new RuntimeException("HTTP请求失败: " + responseCode);
            }
            // 读取响应内容
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (ProtocolException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 解析JSON响应
        return parseGeocodeResponse(response.toString());
    }

    private static MyAddress parseGeocodeResponse(String jsonResponse) {
        JSONObject json = new JSONObject(jsonResponse);
        String status = json.getString("status");

        if (!"OK".equals(status)) {
            throw new RuntimeException("地理编码API错误: " + status);
        }
        MyAddress address = new MyAddress();

        JSONArray results = json.getJSONArray("results");
        for (int j = 0; j < results.length(); j++){
            JSONObject result = json.getJSONArray("results").getJSONObject(j);
            // 解析地址组件
            JSONArray components = result.getJSONArray("address_components");
            for (int i = 0; i < components.length(); i++) {
                JSONObject component = components.getJSONObject(i);
                JSONArray types = component.getJSONArray("types");
                String longName = component.getString("long_name");
                Pattern p1 = Pattern.compile(PATTERN1);
                Pattern p2 = Pattern.compile(PATTERN2);
                Matcher m1 = p1.matcher(longName);
                Matcher m2 = p2.matcher(longName);
                if(m1.find() || m2.find()){
                    // 国家信息
                    if (types.toString().contains("country")) {
                        address.setNation(longName);
                    }
                    // 省份/州信息
                    if (types.toString().contains("administrative_area_level_1")) {
                        address.setProvince(longName);
                    }
                    // 城市信息
                    if (types.toString().contains("locality")) {
                        address.setCity(longName);
                    }
                    // 区县信息
                    if (types.toString().contains("sublocality")) {
                        address.setDistrict(longName);
                    }
                    // 邮政编码
                    if (types.toString().contains("postal_code")) {
                        address.setCityCode(longName);
                    }
                }
            }
        }
        return address;
    }

    public static void main(String[] args) {
        // 示例坐标 - 纽约
        String latitude = "49.102024";
        String longitude = "31.136961";

        try {
            // 获取地址信息
            MyAddress address = getAddress(latitude, longitude);

            // 打印结果
            System.out.println("============ 反向地理编码结果 ============");
            System.out.println("国家: " + address.getNation() );
            System.out.println("省份/州: " + address.getProvince());
            System.out.println("城市: " + address.getCity());
            System.out.println("地区/区县: " + address.getDistrict());
            System.out.println("邮政编码: " + address.getCityCode());
        } catch (Exception e) {
            System.err.println("发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
