package cn.iocoder.yudao.module.inspection.utils;

import com.alibaba.fastjson.JSONObject;

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



public class GetLocation {
    public static String[] getAdd(String log, String lat ){
        String apiKey = "Z2MBZ-YDXKQ-7O25N-B3ACC-ABVV5-SAFVZ"; // 替换为你自己的API密钥

        try {
            // 发送HTTP请求获取地理位置信息
            URL url = new URL("https://apis.map.qq.com/ws/geocoder/v1/?location=" + lat + "," + log + "&key=" + apiKey);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();

            if (responseCode == 200) { // 请求成功
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                // 解析JSON数据获取省市区信息
                JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                JSONObject result = jsonResponse.getJSONObject("result");
                JSONObject addressComponent = result.getJSONObject("address_component");
                String province = addressComponent.getString("province");
                String city = addressComponent.getString("city");
                String district = addressComponent.getString("district");
                return new String[]{province,city,district};
            } else {
                System.out.println("请求失败，响应码: " + responseCode);
            }

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

}
