package com.yeejoin.equipmanage.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.equipmanage.common.entity.Car;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

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

public class CarUtils {
    private static final String GUIDE_KEY = "813684495d9a3981dd2c7694916fe404";

    private  static final String GUIDE_URL = "https://restapi.amap.com/v3/geocode/regeo?";
    public static String getAddress(double longitude, double lantitude) {
        StringBuilder api = new StringBuilder(GUIDE_URL);
        api.append("key=").append(GUIDE_KEY).append("&location=").append(longitude).append(",").append(lantitude)
                .append("&radius=1000").append("&batch=false").append("&extensions=base").append("&roadlevel=0")
                .append("&batch=false");
        StringBuilder res = new StringBuilder();
        BufferedReader in = null;
        try {
            System.out.println(api.toString());
            URL url = new URL(api.toString());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res.append(line).append("\n");
            }
            JSONObject object = JSONObject.parseObject(res.toString());
            System.out.println(object);
            JSONObject regeocode = object.getJSONObject("regeocode");
            String address = regeocode.getString("formatted_address");
            if ("[]".equals(address)) {
                System.out.println("===============无效坐标:" + longitude + "," + lantitude);
                address = "无效坐标";
            }
            res = new StringBuilder(address);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return res.toString();
    }
}
