package com.aiotagro.common.core.utils.uuid;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;

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

/**
 * @author xiefan
 */
@Slf4j
public class DistinctUtil {

    private static final String API_KEY = "f9c298affa8aedea29d604ffb26c7078";
    private static final String BASE_URL = "https://restapi.amap.com/v5/direction/driving";

    /**
     * 高德api计算两地之间的开车距离
     *
     * @param startLat
     * @param startLon
     * @param endLat
     * @param endLon
     * @return
     */
    public static double calculateDistance(double startLat, double startLon, double endLat, double endLon) throws IOException, JSONException {
        // 比较经纬度，如果相同则直接返回0
        if (Math.abs(startLat - endLat) < 1e-6 && Math.abs(startLon - endLon) < 1e-6) {
            log.info("起始地和目的地相同，距离设置为0公里");
            return 0;
        }
        // //进行格式拼接（当前位置/起点）
        String origin = startLon + "," + startLat;
        //进行格式拼接（目的地当前位置/终点）
        String destination = endLon + "," + endLat;
        log.info("起始地的经纬度" + origin + "目的地" + destination);
        String url = BASE_URL + "?key=" + API_KEY +
                "&origin=" + origin +
                "&destination=" + destination +
                "&output=json";

        log.info("请求高德api计算距离url：" + url);
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        connection.disconnect();

        log.info("请求高德api计算距离返回：" + response);

        // 使用Fastjson解析JSON字符串
        JSONObject jsonResponse = JSONObject.parseObject(response.toString());

        // 获取路径信息并提取距离
        JSONObject routes = jsonResponse.getJSONObject("route");
        JSONArray path = routes.getJSONArray("paths");
        JSONObject jsonObject = path.getJSONObject(0);
        String distance = jsonObject.get("distance").toString();
        double number = Double.parseDouble(distance) / 1000;
        log.info("距离：" + number + "公里");
        return number;
    }
}
