package com.zcloud.common.utils;

import com.alibaba.fastjson.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 百度地图工具类
 */
public class BaiduMapUtil {
    // 需替换为实际的百度地图AK（从配置中心获取更佳）
    private static final String BAIDU_AK = "OElqFYoKiAH8KFtph8ftLKF5NlNrbCUr";

    /**
     * 根据经纬度获取详细地址
     *
     * @param lng       经度
     * @param lat       纬度
     * @param coordtype 坐标系类型（wgs84ll/gcj02等）
     * @return 格式化地址
     */
    public static String getAddressByLocation(double lng, double lat, String coordtype) throws Exception {
        String url = String.format(
                "http://api.map.baidu.com/reverse_geocoding/v3/?ak=%s&output=json&coordtype=%s&location=%s,%s",
                BAIDU_AK, coordtype, lat, lng); // 注意百度坐标系是纬度在前

        String response = HttpRequestUtil.doGet(url);
        JSONObject result = JSONObject.parseObject(response);

        if (result.getInteger("status") == 0) {
            return result.getJSONObject("result")
                    .getString("formatted_address");
        }
        throw new RuntimeException("地址解析失败：" + result.getString("message"));
    }

    // 方法重载（默认使用wgs84坐标系）
    public static String getAddressByLocation(double lng, double lat) throws Exception {
        return getAddressByLocation(lng, lat, "wgs84ll");
    }

    /**
     * 将WGS84坐标转换为BD09坐标
     *
     * @param lng 经度（WGS84）
     * @param lat 纬度（WGS84）
     * @return 转换后的BD09坐标数组 [经度, 纬度]
     */
    public static double[] convertWGS84ToBD09(double lng, double lat) throws Exception {
        String url = String.format("%s?coords=%f,%f&from=1&to=5&ak=%s", "http://api.map.baidu.com/geoconv/v1/", lng, lat, BAIDU_AK);
        String response = HttpRequestUtil.doGet(url);

        if (response == null) {
            throw new RuntimeException("调用百度坐标转换API失败");
        }

        JSONObject result = JSONObject.parseObject(response);
        int status = result.getIntValue("status");

        if (status != 0) {
            throw new RuntimeException("坐标转换失败：" + result.getString("message"));
        }

        List<Map<String, Object>> list = result.getObject("result", List.class);
        Map<String, Object> point = list.get(0);

        double x = ((BigDecimal) point.get("x")).doubleValue();
        double y = ((BigDecimal) point.get("y")).doubleValue();

        return new double[]{x, y};
    }

    /**
     * 批量转换WGS84坐标为BD09坐标
     *
     * @param coordinates 多个坐标对，格式：List<double[]{lng, lat}>
     * @return 转换后的坐标列表，顺序与输入一致
     */
    public static List<double[]> batchConvertWGS84ToBD09(List<double[]> coordinates) throws Exception {
        if (coordinates == null || coordinates.isEmpty()) {
            return Collections.emptyList();
        }

        StringBuilder coordsBuilder = new StringBuilder();
        for (double[] coord : coordinates) {
            coordsBuilder.append(coord[0]).append(",").append(coord[1]).append(";");
        }
        String coords = coordsBuilder.substring(0, coordsBuilder.length() - 1); // 去掉最后一个分号

        String url = String.format("%s?coords=%s&from=1&to=5&ak=%s", "http://api.map.baidu.com/geoconv/v1/", coords, BAIDU_AK);
        String response = HttpRequestUtil.doGet(url);

        if (response == null) {
            throw new RuntimeException("调用百度坐标转换API失败");
        }

        JSONObject result = JSONObject.parseObject(response);
        int status = result.getIntValue("status");

        if (status != 0) {
            throw new RuntimeException("坐标转换失败：" + result.getString("message"));
        }

        List<Map<String, Object>> points = result.getObject("result", List.class);
        List<double[]> converted = new ArrayList<>();

        for (Map<String, Object> point : points) {
            converted.add(new double[]{
                    ((Double) point.get("x")),
                    ((Double) point.get("y"))
            });
        }

        return converted;
    }
}
