//package com.fleet.common.utils.hereMap;
//
//import com.fasterxml.jackson.databind.JsonNode;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.fleet.common.config.HereMapsProperties;
//import com.fleet.common.entity.hereMap.TruckRoute;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.http.client.utils.URIBuilder;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Service;
//
//import javax.annotation.Resource;
//import java.net.URI;
//import java.net.URLEncoder;
//import java.net.http.HttpClient;
//import java.net.http.HttpRequest;
//import java.net.http.HttpResponse;
//import java.nio.charset.StandardCharsets;
//import java.time.Duration;
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * @author ID
// * @date 2025/9/2 20:44
// */
//@Service
//@Slf4j
//public class HereMapRoutingService {
//
//    @Resource
//    private HereMapsProperties hereMapsProperties;
//
//    @Resource
//    private HttpClient httpClient;
//
//    @Resource
//    private ObjectMapper objectMapper;
//
//    @Value("${http.client.connect-timeout-seconds:10}")
//    private Integer connectTimeoutSeconds;
//
//
//    /**
//     * 计算卡车路线，支持所有参数
//     *
//     * @param truckRoute 包含所有卡车参数的请求对象
//     * @return 路线规划结果（JSON节点）
//     * @throws Exception 处理过程中发生的异常
//     */
//    public JsonNode calculateTruckRoute(TruckRoute truckRoute) throws Exception {
//        log.info("开始计算卡车路线，起点: {}, 终点: {}, 是否运输危化品: {}",
//                truckRoute.getStart(), truckRoute.getEnd(), truckRoute.isHazardous());
//
//        // 构建查询参数
//        List<String> queryParams = new ArrayList<>();
//
//        // 基本路线参数
//        queryParams.add("apiKey=" + URLEncoder.encode(hereMapsProperties.getApiKey(), StandardCharsets.UTF_8.name()));
//        queryParams.add("origin=" + URLEncoder.encode(truckRoute.getStart(), StandardCharsets.UTF_8.name()));
//        queryParams.add("destination=" + URLEncoder.encode(truckRoute.getEnd(), StandardCharsets.UTF_8.name()));
//        queryParams.add("transportMode=truck");
//
//        // 路线偏好
//        if (truckRoute.getRoutePreference() != null && !truckRoute.getRoutePreference().isEmpty()) {
//            queryParams.add("routingMode=" + truckRoute.getRoutePreference());
//        } else {
//            queryParams.add("routingMode=balanced"); // 默认值
//        }
//
//        // 车辆参数
//        if (truckRoute.getHeight() != null) {
//            queryParams.add("truck[height]=" + truckRoute.getHeight() + "m");
//        }
//        if (truckRoute.getWidth() != null) {
//            queryParams.add("truck[width]=" + truckRoute.getWidth() + "m");
//        }
//        if (truckRoute.getLength() != null) {
//            queryParams.add("truck[length]=" + truckRoute.getLength() + "m");
//        }
//        if (truckRoute.getWeightTotal() != null) {
//            queryParams.add("truck[totalWeight]=" + truckRoute.getWeightTotal() + "t");
//        }
//        if (truckRoute.getWeightPerAxle() != null) {
//            queryParams.add("truck[axleWeight]=" + truckRoute.getWeightPerAxle() + "t");
//        }
//        if (truckRoute.getAxes() != null) {
//            queryParams.add("truck[axes]=" + truckRoute.getAxes());
//        }
//        if (truckRoute.getTrailers() != null) {
//            queryParams.add("truck[trailers]=" + truckRoute.getTrailers());
//        }
//        if (truckRoute.getMaxGradient() != null) {
//            queryParams.add("truck[maxGradient]=" + truckRoute.getMaxGradient());
//        }
//        if (truckRoute.getMaxSpeed() != null) {
//            queryParams.add("truck[maxSpeed]=" + truckRoute.getMaxSpeed() + "km/h");
//        }
//
//        // 避开选项
//        List<String> avoidFeatures = new ArrayList<>();
//        if (truckRoute.isAvoidHighways()) avoidFeatures.add("highway");
//        if (truckRoute.isAvoidTolls()) avoidFeatures.add("tollroad");
//        if (truckRoute.isAvoidFerries()) avoidFeatures.add("ferry");
//        if (truckRoute.isAvoidTunnels()) avoidFeatures.add("tunnel");
//        if (truckRoute.isAvoidBorders()) avoidFeatures.add("borderCrossing");
//        if (truckRoute.isAvoidDirtRoads()) avoidFeatures.add("dirtRoad");
//
//        if (!avoidFeatures.isEmpty()) {
//            queryParams.add("avoid[features]=" + String.join(",", avoidFeatures));
//        }
//
//        // 危化品参数
//        if (truckRoute.isHazardous()) {
//            queryParams.add("truck[hazmat]=true");
//
//            // 危化品类别
//            if (truckRoute.getHazmatTypes() != null && !truckRoute.getHazmatTypes().isEmpty()) {
//                queryParams.add("truck[hazmatTypes]=" + String.join(",", truckRoute.getHazmatTypes()));
//            }
//
//            // 隧道限制代码
//            if (truckRoute.getHazmatTunnelRestrictionCode() != null &&
//                    !truckRoute.getHazmatTunnelRestrictionCode().isEmpty()) {
//                queryParams.add("truck[hazmatTunnelRestrictionCode]=" +
//                        truckRoute.getHazmatTunnelRestrictionCode());
//            }
//
//            // 爆炸物和放射性物质
//            if (truckRoute.isHazmatIsExplosive()) {
//                queryParams.add("truck[hazmatIsExplosive]=true");
//            }
//            if (truckRoute.isHazmatIsRadioactive()) {
//                queryParams.add("truck[hazmatIsRadioactive]=true");
//            }
//        }
//
//        // 构建完整URL
//        String queryString = String.join("&", queryParams);
//        String requestUri = hereMapsProperties.getRoutingApiUrl() + "?" + queryString;
//        log.info("HERE Maps API请求URL: {}", requestUri);
//
//        // 创建HTTP请求
////        HttptruckRoute httptruckRoute = HttptruckRoute.newBuilder()
////                .uri(URI.create(fullUrl))
////                .timeout(Duration.ofSeconds(15))
////                .header("Accept", "application/json")
////                .GET()
////                .build();
//
//        // 发送请求并获取响应
////        HttpResponse<String> response = httpClient.send(
////                httptruckRoute,
////                HttpResponse.BodyHandlers.ofString()
////        );
//
//        HttpRequest request = buildHttpRequest(new URIBuilder(requestUri).build());
//        HttpResponse<String> response = sendHttpRequest(request);
//
//        // 处理响应状态
//        if (response.statusCode() != 200) {
//            log.error("HERE Maps API请求失败，状态码: {}, 响应内容: {}",
//                    response.statusCode(), response.body());
//            throw new RuntimeException("路线规划失败，状态码: " + response.statusCode());
//        }
//
//        // 解析JSON响应
//        JsonNode responseNode = objectMapper.readTree(response.body());
//        log.info("卡车路线规划成功，找到 {} 条路线",
//                responseNode.get("routes").size());
//
//        return responseNode;
//    }
//
//    private HttpRequest buildHttpRequest(URI uri) {
//        return HttpRequest.newBuilder()
//                .uri(uri)
//                .timeout(Duration.ofSeconds(connectTimeoutSeconds))
//                .header("Accept", "application/json")
//                .GET()
//                .build();
//    }
//
//    private HttpResponse<String> sendHttpRequest(HttpRequest request) throws Exception {
//        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
//
//        int statusCode = response.statusCode();
//        if (statusCode != 200) {
//            String errorMsg = String.format(
//                    "HERE Maps API请求失败：状态码=%d, 响应体=%s",
//                    statusCode, response.body()
//            );
//            log.error(errorMsg);
//            throw new Exception(errorMsg);
//        }
//
//        return response;
//    }
//
//}
