package com.younike.common.utils.gaode;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.younike.common.utils.string.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * 高德地图 工具类
 * 2021-8-13 Another
 */
public class GaodeUtil {

    private final static Logger logger = LoggerFactory.getLogger(GaodeUtil.class);

    /**
     * web服务 key（测试）
     */
    public static final String key = "b42f9a88b850e944de8d231658d0de0a";


    /**
     * 获取 高德骑行路线规划
     * @param startLonLat 起始地经纬度（逗号分割）
     * @param endLonLat 目的地经纬度（逗号分割）
     * @return 路线规划距离（单位：米）
     */
    public static Long getDistanceByElectricVehicle(String startLonLat, String endLonLat){
        Long distance = 0L;

        if (StringUtils.isBlank(startLonLat) || StringUtils.isBlank(endLonLat)) {
            return distance;
        }

        // 高德 骑行路线规划路径请求url
        String url = "https://restapi.amap.com/v5/direction/bicycling?key=" + key + "&origin=" + startLonLat + "&destination=" + endLonLat;

        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(50000)    // 设置 读取超时时间
                .setConnectTimeout(50000)    // 设置 连接超时时间
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpGet get = new HttpGet(url);

        try {
            CloseableHttpResponse execute = httpClient.execute(get);
            int stateCode = execute.getStatusLine().getStatusCode();
            if(stateCode == 200){
                HttpEntity httpentity = execute.getEntity();
                if (httpentity != null){
                    // 请求高德返回结果（解析出返回的路线规划中第一条规划的米数）
                    String result = EntityUtils.toString(httpentity);
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    String status = jsonObject.getString("status");
                    String info = jsonObject.getString("info");
                    String infocode = jsonObject.getString("infocode");
                    if ("1".equals(status) && "OK".equals(info) && "10000".equals(infocode)) {
                        // 返回成功
                        String route = jsonObject.getString("route");
                        JSONObject pathsJson = JSONObject.parseObject(route);
                        JSONArray jsonArray = pathsJson.getJSONArray("paths");
                        if (jsonArray.isEmpty() || jsonArray.size() < 1) {
                            logger.info("请求高德骑行路径规划成功，但返回路径规划为空。返回结果：" + result);
                            return distance;
                        }
                        distance = Long.valueOf(jsonArray.getJSONObject(0).getString("distance"));
                    } else {
                        logger.info("请求高德骑行路径规划失败，失败结果：" + result);
                    }
                }
            }
        } catch (IOException e) {
            logger.error("请求高德骑行路径规划失败，失败信息：" + e);
            e.printStackTrace();
        }

        return distance;
    }

    /**
     * 根据 米数 转化成 骑手端页面显示（km/m）
     * @param distance
     * @return 骑手端页面显示距离（**km/**m）
     */
    public static String conversionDistance(Long distance) {
        // 若 高德骑行路线规划 返回为0，则默认显示 **
        String distanceCompany = "**";
        if (distance >= 1000) {
            // 计算 公里数
            BigDecimal kilometre = new BigDecimal(distance).divide(new BigDecimal(1000));
            distanceCompany = kilometre.setScale(1, BigDecimal.ROUND_HALF_UP) + "km";
        } else if (distance > 0) {
            distanceCompany = distance + "m";
        }
        return distanceCompany;
    }

    /**
     * 获取 高德骑行路线规划 返回结果 转化 骑手端页面显示（km/m）
     * @param startLonLat 起始地经纬度（逗号分割）
     * @param endLonLat 目的地经纬度（逗号分割）
     * @return 骑手端页面显示距离（**km/**m）
     */
    public static String conversionDistanceByElectricVehicle(String startLonLat, String endLonLat) {
        Long distance = getDistanceByElectricVehicle(startLonLat, endLonLat);
        return conversionDistance(distance);
    }

}
