puzhibing
2026-05-18 d8440cc93f48e5a4b932d8daf740023e16d65008
xp-robotaxi-itinerary-boot/src/main/java/com/xiaopeng/itinerary/service/impl/XpPricingServiceImpl.java
@@ -1,18 +1,23 @@
package com.xiaopeng.itinerary.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Snowflake;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaopeng.api.dto.account.GetUserCouponDto;
import com.xiaopeng.api.dto.account.UcUserInfo;
import com.xiaopeng.api.dto.map.RouteAndFareDto;
import com.xiaopeng.api.dto.map.RouteStaleCheckDto;
import com.xiaopeng.api.dto.map.SelectNavigationRouteDto;
import com.xiaopeng.api.dto.operation.LonLatDto;
import com.xiaopeng.api.enums.RouteStrategyKind;
import com.xiaopeng.api.feignClient.account.UserResourcesClient;
import com.xiaopeng.api.feignClient.account.UserRoutePlanRuleClient;
import com.xiaopeng.api.feignClient.account.XpAppUserClient;
import com.xiaopeng.api.feignClient.account.XpAppUserCouponClient;
@@ -60,6 +65,7 @@
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
@@ -110,6 +116,9 @@
    private XpTradingStrategyMapper xpTradingStrategyMapper;
    @Resource
    private XpTradingStrategyPushMapper xpTradingStrategyPushMapper;
    @Resource
    private XpElectronicFenceAreaMapper xpElectronicFenceAreaMapper;
    @Resource
@@ -142,6 +151,10 @@
    private UserRoutePlanRuleClient userRoutePlanRuleClient;
    @Resource
    private XpTargetedServiceClient xpTargetedServiceClient;
    @Resource
    private XpTradingStrategyClient xpTradingStrategyClient;
    @Resource
    private UserResourcesClient userResourcesClient;
    @Resource(name = "hutoolSnowflake")
    private Snowflake snowflake;
@@ -226,16 +239,6 @@
    @Override
    public List<RouteAndFareVo> getRouteAndFare(RouteAndFareDto routeAndFareDto, String userId) {
//        // 判断是否5分钟内进行了查询 相同站点的起始点  并且是同时段
//        String key = "xp-map-query-" + routeAndFareDto.getOpenCityId()
//                + "-" + routeAndFareDto.getOrigin().getLongitude() + "-" + routeAndFareDto.getOrigin().getLatitude()
//                + "-" + routeAndFareDto.getDestination().getLongitude() + "-" + routeAndFareDto.getDestination().getLatitude() + "-" + getCurrentTimeSlot() + "-" + userId+routeAndFareDto.getUserCouponId();
//
//        if (redisService.hasKey(key)) {
//            String jsonStr = Objects.requireNonNull(redisService.getCacheObject(key)).toString();
//            RouteAndFareVo RouteAndFareVo = JSONObject.parseObject(jsonStr, RouteAndFareVo.class);
//            return (RouteAndFareVo);
//        }
        ArrayList<RouteAndFareVo> routeAndFareVos = new ArrayList<>(3);
        // 1. 基础数据查询
@@ -289,7 +292,8 @@
                xpPricingCardVo = xpPricingUtil.calculationPrice(userId,
                        JSON.parseObject(xpPricing.getBasicPricingJson()),
                        JSON.parseArray(xpPricing.getStartingFareJson()),
                        routeVo.getDistance(), routeVo.getDuration(), 0, 0.0, xpPricing.getIsDynamicPrice(), routeAndFareDto.getOpenCityId(), xpPricing.getDynamicPricingJson()
                        routeVo.getDistance(), routeVo.getDuration(), 0, 0.0, xpPricing.getIsDynamicPrice(),
                        routeAndFareDto.getOpenCityId(), xpPricing.getDynamicPricingJson()
                );
            } else {
                xpPricingCardVo = xpPricingUtil.calculationFixedPrice(userId,
@@ -372,11 +376,9 @@
                Double money = userCouponVo.getMoney();
                money = new BigDecimal(money).setScale(2, RoundingMode.HALF_UP).doubleValue();
                xpPricingCardVo.setCoupon(String.valueOf(money));
                if (xpPricingCardVo.getTotalPrice() > money) {
                    xpPricingCardVo.setSystemDiscount(xpPricingCardVo.getTotalPrice() - money);
                }
//                if (xpPricingCardVo.getTotalPrice() > money) {
//                    xpPricingCardVo.setSystemDiscount(xpPricingCardVo.getTotalPrice() - money);
//                }
            }
            // 8. 构建响应对象
@@ -387,7 +389,7 @@
            xpPricingCardVo.setStartPriceStr(new BigDecimal(xpPricingCardVo.getStartPrice()).setScale(2, RoundingMode.HALF_UP).toString());
            xpPricingCardVo.setDistancePriceStr(new BigDecimal(xpPricingCardVo.getDistancePrice()).setScale(2, RoundingMode.HALF_UP).toString());
            xpPricingCardVo.setDurationPriceStr(new BigDecimal(xpPricingCardVo.getDurationPrice()).setScale(2, RoundingMode.HALF_UP).toString());
            xpPricingCardVo.setSystemDiscountStr(new BigDecimal(xpPricingCardVo.getSystemDiscount()).setScale(2, RoundingMode.HALF_UP).toString());
//            xpPricingCardVo.setSystemDiscountStr(new BigDecimal(xpPricingCardVo.getSystemDiscount()).setScale(2, RoundingMode.HALF_UP).toString());
            routeAndFareVo.setXpPricingCard(xpPricingCardVo);
@@ -407,16 +409,16 @@
                    fareVo.setDiscountAmount(userCouponVo.getMoney());
                    fareVo.setFinalFare(fareVo.getOriginalFare() - fareVo.getDiscountAmount());
                }
                if(fareVo.getFinalFare()>0){
                    fareVo.setSystemDiscount(fareVo.getFinalFare());
                    fareVo.setFinalFare(0.00);
                }
//                if(fareVo.getFinalFare()>0){
//                    fareVo.setSystemDiscount(fareVo.getFinalFare());
//                    fareVo.setFinalFare(0.00);
//                }
                fareVo.setCouponId(userCouponVo.getId());
            } else {
                fareVo.setDiscountAmount(0.00);
                fareVo.setFinalFare(fareVo.getOriginalFare());
                fareVo.setSystemDiscount(fareVo.getFinalFare());
                fareVo.setFinalFare(0.00);
//                fareVo.setSystemDiscount(fareVo.getFinalFare());
//                fareVo.setFinalFare(0.00);
            }
            // 10. 检查等待时间
@@ -435,7 +437,7 @@
            // 12. 设置费用信息
            fareVo.setFinalFareStr(new BigDecimal(fareVo.getFinalFare()).setScale(2, RoundingMode.HALF_UP).toString());
            fareVo.setOriginalFare(new BigDecimal(fareVo.getOriginalFare()).setScale(2,RoundingMode.HALF_UP).doubleValue());
            fareVo.setSystemDiscount(new BigDecimal(fareVo.getSystemDiscount() == null ? 0 : fareVo.getSystemDiscount()).setScale(2,RoundingMode.HALF_UP).doubleValue());
//            fareVo.setSystemDiscount(new BigDecimal(fareVo.getSystemDiscount() == null ? 0 : fareVo.getSystemDiscount()).setScale(2,RoundingMode.HALF_UP).doubleValue());
            routeAndFareVo.setFareEstimate(fareVo);
            routeAndFareVo.getXpPricingCard().setFinalFareStr(fareVo.getFinalFareStr());
@@ -485,7 +487,14 @@
                getCurrentTimeSlot()
        );
        log.info("等待时间查询参数:{}", lon + ":" + lat);
        log.info("等待时间查询结果:{}", entities.toString());
        for (XpGeoQueryEntity entity : entities) {
            log.info("等待时间查询结果:{}", entity.toString());
            log.info("等待时间查询结果 秒数:{}", entity.getSeconds());
            log.info("等待时间查询结果 状态:{}", entity.getStatus());
        }
        if (entities.isEmpty()) {
            return 1;
@@ -554,6 +563,21 @@
    @Override
    public String saveOrder(XpOrderDto dto, String uid) {
        //校验白名单用户
        List<XpWhitelist> xpWhitelists = xpWhitelistMapper.selectList(new QueryWrapper<XpWhitelist>().eq("app_user_id", uid)
                .eq("status", 1).eq("is_deleted", 0).last(" and (expire_time >= DATE(NOW()) or expire_time is null)"));
        if(xpWhitelists.isEmpty()){
            throw new ServiceException("未授权用户,不能使用该功能", I18nKeyConstant.NO_PERMISSION);
        }
        XpWhitelist xpWhitelist = xpWhitelists.get(0);
        //判断最大下单数
        if(null != xpWhitelist.getMaxOrderNum() && xpWhitelist.getMaxOrderNum()>0){
            Long count = xpOrderClient.getUserOrderNum(Long.valueOf(uid)).getData();
            if(xpWhitelist.getMaxOrderNum() <= count){
                throw new ServiceException("已达到最大下单数量,不能使用该功能", I18nKeyConstant.MAX_ORDER_NUM);
            }
        }
        // 是否在运营区域时间内
        XpElectronicFenceArea xpElectronicFenceArea = xpElectronicFenceAreaMapper.selectById(dto.getXpElectronicFenceAreaId());
        XpElectronicFence xpElectronicFence = xpElectronicFenceMapper.selectById(xpElectronicFenceArea.getElectronicId());
@@ -569,7 +593,7 @@
        // 判断是否有进行的订单
        R<Long> r = xpOrderClient.hasUnPaodOrder(uid);
        if (r.getData() > 0) {
            throw new RuntimeException("有正在进行的订单");
            throw new ServiceException("有正在进行的订单");
        }
        // 获取起点经纬度
@@ -594,7 +618,6 @@
        if (!inTime) {
            throw new ServiceException("当前点位未开通服务", I18nKeyConstant.NO_CURRENT_REGION);
        }
        // todo 需要判断用户是否白名单,且白名单当天最大订单量
        // 判断当天取消的次数 后台配置 redis 查询
        // 静默处理
@@ -613,15 +636,15 @@
//        }
        // 根据id获取手机号
        Boolean isPriorityDispatch = true;
//        R<XpAppUser> xpAppUserR = xpAppUserClient.queryOperationsUserById(Long.valueOf(uid));
//        if (xpAppUserR.getCode() == R.SUCCESS) {
//            Long count = xpWhitelistMapper.selectCount(new LambdaQueryWrapper<XpWhitelist>().eq(XpWhitelist::getAccount, xpAppUserR.getData().getPhoneNumber()).eq(XpWhitelist::getIsPriorityDispatch, 1));
//            if (count > 0) {
//                isPriorityDispatch = true;
//            }
//        }
        //判断是否在白名单且优先派单
        boolean isPriorityDispatch = false;
        UcUserInfo ucUserInfo = userResourcesClient.getBaseUserByUid(uid);
        if (null != ucUserInfo) {
            Long count = xpWhitelistMapper.selectCount(new LambdaQueryWrapper<XpWhitelist>().eq(XpWhitelist::getAccount, ucUserInfo.getMobile()).eq(XpWhitelist::getIsPriorityDispatch, 1));
            if (count > 0) {
                isPriorityDispatch = true;
            }
        }
        // 生成订单数据
        XpOrder xpOrder = new XpOrder();
@@ -729,77 +752,169 @@
        if (maxPushDistanceObj != null) {
            maxPushDistance = Double.valueOf(maxPushDistanceObj.toString());
        } else {
            maxPushDistance = xpTradingStrategyMapper.selectOne(null).getThreePushDistance();
            XpTradingStrategy xpTradingStrategy = xpTradingStrategyMapper.selectOne(null);
            List<XpTradingStrategyPush> xpTradingStrategyPushes = xpTradingStrategyPushMapper.selectList(new QueryWrapper<XpTradingStrategyPush>().eq("trading_strategy_id", xpTradingStrategy.getId()));
            long now = Long.parseLong(LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmm")));
            XpTradingStrategyPush xpTradingStrategyPush = xpTradingStrategyPushes.stream().filter(item -> {
                long start = Long.parseLong(item.getStartTime().replace(":", ""));
                long end = Long.parseLong(item.getEndTime().replace(":", ""));
                return now >= start && now < end;
            }).findFirst().orElse(null);
            maxPushDistance = null != xpTradingStrategyPush ? xpTradingStrategyPush.getFivePushDistance() : xpTradingStrategy.getFivePushDistance();
        }
        //获取定向服务配置
        R<Integer> targetedServiceWeight = xpTargetedServiceClient.getTargetedServiceWeight(xpOrder.getAppUserId(), xpOrder.getCityCode());
        if(targetedServiceWeight.getCode() == R.SUCCESS && null != targetedServiceWeight.getData()){
            log.info("添加定向服务订单:{}", xpOrder.getOrderNumber());
            return addSpOrderPush(xpOrder, xpPoint, xpRoutePlan, maxPushDistance, targetedServiceWeight.getData(), orderId, currentTimeSlot, distance, duration, uid);
        }else{
            log.info("添加普通订单:{}", xpOrder.getOrderNumber());
            return addOrderPush(xpOrder, xpPoint, xpRoutePlan, maxPushDistance, isPriorityDispatch, orderId, currentTimeSlot, distance, duration, uid);
        }
    }
    /**
     * 构建普通订单推送数据
     * @param xpOrder
     * @param xpPoint
     * @param xpRoutePlan
     * @param maxPushDistance
     * @param isPriorityDispatch
     * @param orderId
     * @param currentTimeSlot
     * @param distance
     * @param duration
     * @param uid
     * @return
     */
    private String addOrderPush(XpOrder xpOrder, XpPoint xpPoint, XpRoutePlan xpRoutePlan, double maxPushDistance,
                                Boolean isPriorityDispatch, Long orderId, String currentTimeSlot, Integer distance, Integer duration, String uid){
        // 找出现在所有的队列 通过计算距离 算出目前应该放在那个队列  如果没有符合的新增一个队列  符合后看是否白名单账号 是则直接放在队列前端
        Set<String> quoteMatchName = redisService.getQuoteMatchName(CacheConstants.QUEUE_POINT_ID);
        int targetedVal = 0;
        R<List<XpTargetedServiceVehicleVo>> targetedServiceUserR = xpTargetedServiceClient.findListByUserIdAndCityCode(xpOrder.getAppUserId(), xpOrder.getCityCode());
        if(targetedServiceUserR.getCode() == R.SUCCESS && !targetedServiceUserR.getData().isEmpty()){
            targetedVal = targetedServiceUserR.getData().get(0).getWeight();
        }
        //String key = CacheConstants.QUEUE_POINT_ID + "-" + xpPoint.getId() + "-" + xpPoint.getPointLon() + "," + xpPoint.getPointLat();
        String redis_key = redisService.redisKey_QUEUE_POINT_ID(xpPoint.getId(), xpPoint.getPointLon(), xpPoint.getPointLat());
        //orderId + "_" + xpPoint.getPointLon() + "," + xpPoint.getPointLat() + "_0" + "_" + uid + "_" + xpOrder.getOrderNumber() + "_" + distance + "_" + duration + "_" + planRuleForQueue+"_" + targetedVal;
        String redis_value = redisService.redisValue_QUEUE_POINT_ID(orderId.toString(), xpPoint.getPointLon().toString(), xpPoint.getPointLat().toString(), uid,
                xpOrder.getOrderNumber(), distance.toString(), duration.toString(), planRuleForQueue == null ? null : planRuleForQueue.toString(),targetedVal);
        log.info("当前队列:{}", quoteMatchName);
        RedisQueuePointIdVo redisQueuePointIdVo = null;
        for (String s : quoteMatchName) {
//            QUEUE_POINT_ID-1-30.233,120.233
            String lonLat = s.split("-")[2];
            // 和上车点进行判断是否<maxPushDistance
            double v = FastDistanceCalculator.distanceFast(Double.parseDouble(lonLat.split(",")[1]), Double.parseDouble(lonLat.split(",")[0]), xpPoint.getPointLat(), xpPoint.getPointLon());
            if (v < maxPushDistance) {
//                String value = orderId + "_" + xpPoint.getPointLon() + "," + xpPoint.getPointLat() + "_0" + "_" + uid + "_" + xpOrder.getOrderNumber() + "_" + distance + "_" + duration + "_" + planRuleForQueue;
                if(targetedVal>0){ //todo yyy 这里添加数据需要优化 需要redis 加锁
                    List<String> cacheList = redisService.getCacheList(s);
                    cacheList.add(redis_value);
                    List<RedisQueuePointIdVo> ll = new ArrayList<>();
                    for (String string : cacheList) {
                        String[] split = string.split("_");
                        redisQueuePointIdVo = new RedisQueuePointIdVo();
                        redisQueuePointIdVo.setOrderId(split[0]);
                        redisQueuePointIdVo.setPointLon(split[1]);
                        redisQueuePointIdVo.setPointLat(split[2]);
                        redisQueuePointIdVo.setUid(split[3]);
                        redisQueuePointIdVo.setOrderNumber(split[4]);
                        redisQueuePointIdVo.setDistance(split[5]);
                        redisQueuePointIdVo.setDuration(split[6]);
                        redisQueuePointIdVo.setPlanRuleForQueue(split[7]);
                        if(split.length>8){
                            redisQueuePointIdVo.setTargetedVal(Integer.valueOf(split[8]));
                        }else{
                            redisQueuePointIdVo.setTargetedVal(0);
                        }
                        ll.add(redisQueuePointIdVo);
                    }
                    ll.sort((o1, o2) -> o2.getTargetedVal() - o1.getTargetedVal());
                    List<String> redis_values = new ArrayList<>();
                    for (RedisQueuePointIdVo vo : ll) {
                        String redis_value2 = redisService.redisValue_QUEUE_POINT_ID(vo.getOrderId(), vo.getPointLon(), vo.getPointLat(), vo.getUid(),
                                vo.getOrderNumber(), vo.getDistance(), vo.getDuration(), vo.getPlanRuleForQueue(),vo.getTargetedVal());
                        redis_values.add(redis_value2);
                    }
                    redisService.setCacheList(s, redis_values);
                }else{
                    if (isPriorityDispatch) {
                        // 头部  value 订单_经纬度_状态_用户id_订单编号_距离_时间
                        redisService.addToHead(s, redis_value);
                        log.info("添加到队列头部:{} {}", s, redis_value);
                    } else {
                        // 尾部
                        redisService.addToTail(s, redis_value);
                        log.info("添加到队列尾部:{} {}", s, redis_value);
                    }
                String value = orderId + "_" + xpPoint.getPointLon() + "," + xpPoint.getPointLat() + "_0" + "_" + uid + "_" + xpOrder.getOrderNumber() + "_" + distance + "_" + duration + "_" + xpRoutePlan.getRoutePlanRule();
                if (isPriorityDispatch) {
                    // 头部  value 订单_经纬度_状态_用户id_订单编号_距离_时间
                    redisService.addToHead(s, value);
                    log.info("添加到队列头部:{} {}", s, value);
                } else {
                    // 尾部
                    redisService.addToTail(s, value);
                    log.info("添加到队列尾部:{} {}", s, value);
                }
                xpOrder.setQueueName(s);
                xpOrderClient.updateOrder(xpOrder);
                // 存储mongodb 数据
                XpGeoQueryEntity xpGeoQueryEntity = new XpGeoQueryEntity();
                xpGeoQueryEntity.setOrderId(orderId.toString());
                xpGeoQueryEntity.setLocation(new GeoJsonPoint(xpPoint.getPointLon(), xpPoint.getPointLat()));
                // 计算2个时间的秒数
                xpGeoQueryEntity.setTime(currentTimeSlot);
                xpGeoQueryEntity.setStatus(0);
                xpGeoQueryEntity.setTimestamp(System.currentTimeMillis());
                geoQueryEntityService.save(xpGeoQueryEntity);
                return orderId.toString();
            }
        }
        String key = CacheConstants.QUEUE_POINT_ID + "-" + xpPoint.getId() + "-" + xpPoint.getPointLon() + "," + xpPoint.getPointLat();
        if(xpRoutePlan==null){
            redisService.setCacheList(key, Arrays.asList(orderId + "_" + xpPoint.getPointLon() + "," + xpPoint.getPointLat() + "_0" + "_" + uid + "_" + xpOrder.getOrderNumber() + "_" + distance + "_" + duration + "_" + null));
        }else {
            redisService.setCacheList(key, Arrays.asList(orderId + "_" + xpPoint.getPointLon() + "," + xpPoint.getPointLat() + "_0" + "_" + uid + "_" + xpOrder.getOrderNumber() + "_" + distance + "_" + duration + "_" + xpRoutePlan.getRoutePlanRule()));
        }
        log.info("订单推单:{}   {}", key, redisService.getCacheList(key));
        xpOrder.setQueueName(key);
        xpOrderClient.updateOrder(xpOrder);
        // 存储mongodb 数据
        XpGeoQueryEntity xpGeoQueryEntity = new XpGeoQueryEntity();
        xpGeoQueryEntity.setOrderId(orderId.toString());
        xpGeoQueryEntity.setLocation(new GeoJsonPoint(xpPoint.getPointLon(), xpPoint.getPointLat()));
        // 计算2个时间的秒数
        xpGeoQueryEntity.setTime(currentTimeSlot);
        xpGeoQueryEntity.setStatus(0);
        xpGeoQueryEntity.setTimestamp(System.currentTimeMillis());
        geoQueryEntityService.save(xpGeoQueryEntity);
        return orderId.toString();
    }
    /**
     * 构建定向服务订单推送数据
     * @param xpOrder
     * @param xpPoint
     * @param xpRoutePlan
     * @param maxPushDistance
     * @param weight
     * @param orderId
     * @param currentTimeSlot
     * @param distance
     * @param duration
     * @param uid
     * @return
     */
    private String addSpOrderPush(XpOrder xpOrder, XpPoint xpPoint, XpRoutePlan xpRoutePlan, double maxPushDistance,
                                  Integer weight, Long orderId, String currentTimeSlot, Integer distance, Integer duration, String uid){
        // 找出现在所有的队列 通过计算距离 算出目前应该放在那个队列  如果没有符合的新增一个队列  符合后看是否白名单账号 是则直接放在队列前端
        Set<String> quoteMatchName = redisService.getQuoteMatchName(CacheConstants.SP_QUEUE_POINT_ID);
        log.info("当前队列(定向服务):{}", quoteMatchName);
        for (String s : quoteMatchName) {
//            QUEUE_POINT_ID-1-30.233,120.233
            String lonLat = s.split("-")[2];
            // 和上车点进行判断是否<maxPushDistance
            double v = FastDistanceCalculator.distanceFast(Double.parseDouble(lonLat.split(",")[1]), Double.parseDouble(lonLat.split(",")[0]), xpPoint.getPointLat(), xpPoint.getPointLon());
            if (v < maxPushDistance) {
                //在范围内,将队列中的数据转换成对象进行排序
                List<String> cacheList = redisService.getCacheList(s);
                List<RedisQueuePointIdVo> ll = new ArrayList<>();
                for (String string : cacheList) {
                    String[] split = string.split("_");
                    RedisQueuePointIdVo redisQueuePointIdVo = new RedisQueuePointIdVo();
                    redisQueuePointIdVo.setOrderId(split[0]);
                    redisQueuePointIdVo.setPointLonLat(split[1]);
                    redisQueuePointIdVo.setPushStatus(split[2]);
                    redisQueuePointIdVo.setUid(split[3]);
                    redisQueuePointIdVo.setOrderNumber(split[4]);
                    redisQueuePointIdVo.setDistance(split[5]);
                    redisQueuePointIdVo.setDuration(split[6]);
                    redisQueuePointIdVo.setPlanRuleForQueue(split[7]);
                    redisQueuePointIdVo.setTargetedVal(Integer.valueOf(split[8]));
                    ll.add(redisQueuePointIdVo);
                }
                RedisQueuePointIdVo redisQueuePointIdVo = new RedisQueuePointIdVo();
                redisQueuePointIdVo.setOrderId(orderId.toString());
                redisQueuePointIdVo.setPointLonLat(xpPoint.getPointLon() + "," + xpPoint.getPointLat());
                redisQueuePointIdVo.setPushStatus("0");
                redisQueuePointIdVo.setUid(uid);
                redisQueuePointIdVo.setOrderNumber(xpOrder.getOrderNumber());
                redisQueuePointIdVo.setDistance(distance.toString());
                redisQueuePointIdVo.setDuration(duration.toString());
                redisQueuePointIdVo.setPlanRuleForQueue(xpRoutePlan.getRoutePlanRule().toString());
                redisQueuePointIdVo.setTargetedVal(weight);
                ll.add(redisQueuePointIdVo);
                //排序
                ll.sort((o1, o2) -> o2.getTargetedVal() - o1.getTargetedVal());
                List<String> collect = ll.stream().map(item -> {
                    String value = item.getOrderId() + "_" + item.getPointLonLat() + "_" + item.getPushStatus() + "_" + item.getUid() + "_" + item.getOrderNumber()
                            + "_" + item.getDistance() + "_" + item.getDuration() + "_" + item.getPlanRuleForQueue() + "_" + item.getTargetedVal();
                    return value;
                }).collect(Collectors.toList());
                redisService.setCacheList(s, cacheList);
                xpOrder.setQueueName(s);
                xpOrderClient.updateOrder(xpOrder);
@@ -813,12 +928,19 @@
                xpGeoQueryEntity.setStatus(0);
                xpGeoQueryEntity.setTimestamp(System.currentTimeMillis());
                geoQueryEntityService.save(xpGeoQueryEntity);
                return orderId.toString();
            }
        }
        redisService.setCacheList(redis_key, ListUtil.toList(redis_value) );
        log.info("订单推单:{}   {}", redis_key, redisService.getCacheList(redis_key));
        xpOrder.setQueueName(redis_key);
        String key = CacheConstants.SP_QUEUE_POINT_ID + "-" + xpPoint.getId() + "-" + xpPoint.getPointLon() + "," + xpPoint.getPointLat();
        if(xpRoutePlan==null){
            redisService.setCacheList(key, Arrays.asList(orderId + "_" + xpPoint.getPointLon() + "," + xpPoint.getPointLat() + "_0" + "_" + uid + "_" + xpOrder.getOrderNumber() + "_" + distance + "_" + duration + "_" + null + "_" + weight));
        }else {
            redisService.setCacheList(key, Arrays.asList(orderId + "_" + xpPoint.getPointLon() + "," + xpPoint.getPointLat() + "_0" + "_" + uid + "_" + xpOrder.getOrderNumber() + "_" + distance + "_" + duration + "_" + xpRoutePlan.getRoutePlanRule() + "_" + weight));
        }
        log.info("订单推单:{}   {}", key, redisService.getCacheList(key));
        xpOrder.setQueueName(key);
        xpOrderClient.updateOrder(xpOrder);
@@ -831,8 +953,12 @@
        xpGeoQueryEntity.setStatus(0);
        xpGeoQueryEntity.setTimestamp(System.currentTimeMillis());
        geoQueryEntityService.save(xpGeoQueryEntity);
        return orderId.toString();
    }
    @Override
    public Boolean isInOperationTime(String operationStrategy) {
@@ -938,9 +1064,9 @@
            Double money = userCouponVo.getMoney();
            money = new BigDecimal(money).setScale(2, RoundingMode.HALF_UP).doubleValue();
            xpPricingCardVo.setCoupon(String.valueOf(money));
            if (xpPricingCardVo.getTotalPrice() > money) {
                xpPricingCardVo.setSystemDiscount(xpPricingCardVo.getTotalPrice() - money);
            }
//            if (xpPricingCardVo.getTotalPrice() > money) {
//                xpPricingCardVo.setSystemDiscount(xpPricingCardVo.getTotalPrice() - money);
//            }
        }
        RouteAndFareVo routeAndFareVo = new RouteAndFareVo();
        routeAndFareVo.setRoute(routeVo);
@@ -948,7 +1074,7 @@
        xpPricingCardVo.setStartPriceStr(new BigDecimal(xpPricingCardVo.getStartPrice()).setScale(2, RoundingMode.HALF_UP).toString());
        xpPricingCardVo.setDistancePriceStr(new BigDecimal(xpPricingCardVo.getDistancePrice()).setScale(2, RoundingMode.HALF_UP).toString());
        xpPricingCardVo.setDurationPriceStr(new BigDecimal(xpPricingCardVo.getDurationPrice()).setScale(2, RoundingMode.HALF_UP).toString());
        xpPricingCardVo.setSystemDiscountStr(new BigDecimal(xpPricingCardVo.getSystemDiscount()).setScale(2, RoundingMode.HALF_UP).toString());
//        xpPricingCardVo.setSystemDiscountStr(new BigDecimal(xpPricingCardVo.getSystemDiscount()).setScale(2, RoundingMode.HALF_UP).toString());
        routeAndFareVo.setXpPricingCard(xpPricingCardVo);
        FareVo fareVo = new FareVo();
        fareVo.setEstimatedDistanceKm(routeVo.getDistance().doubleValue() / 1000);
@@ -963,24 +1089,20 @@
                fareVo.setDiscountAmount(userCouponVo.getMoney());
                fareVo.setFinalFare(fareVo.getOriginalFare() - fareVo.getDiscountAmount());
            }
            if (fareVo.getFinalFare() > 0) {
                fareVo.setSystemDiscount(fareVo.getFinalFare());
                fareVo.setFinalFare(0.00);
            }
            fareVo.setCouponId(userCouponVo.getId());
        } else {
            fareVo.setDiscountAmount(0.00);
            fareVo.setFinalFare(fareVo.getOriginalFare());
            fareVo.setSystemDiscount(fareVo.getFinalFare());
            fareVo.setFinalFare(0.00);
//            fareVo.setSystemDiscount(fareVo.getFinalFare());
        }
        Integer waitTime = getWaitTime(routeAndFareDto.getOrigin().getLongitude(), routeAndFareDto.getOrigin().getLatitude());
        fareVo.setWaitingTime(waitTime);
        fareVo.setFinalFareStr(new BigDecimal(fareVo.getFinalFare()).setScale(2, RoundingMode.HALF_UP).toString());
        fareVo.setOriginalFare(new BigDecimal(fareVo.getOriginalFare()).setScale(2, RoundingMode.HALF_UP).doubleValue());
        fareVo.setSystemDiscount(new BigDecimal(fareVo.getSystemDiscount() == null ? 0 : fareVo.getSystemDiscount()).setScale(2, RoundingMode.HALF_UP).doubleValue());
//        fareVo.setSystemDiscount(new BigDecimal(fareVo.getSystemDiscount() == null ? 0 : fareVo.getSystemDiscount()).setScale(2, RoundingMode.HALF_UP).doubleValue());
        routeAndFareVo.setFareEstimate(fareVo);
        routeAndFareVo.getXpPricingCard().setFinalFareStr(fareVo.getFinalFareStr());
//        routeAndFareVo.setTrafficLights();//交通信号灯 todo 20260508 红绿灯功能还没有
        fareVo.setId(null);
        return routeAndFareVo;
    }
@@ -1010,63 +1132,77 @@
            throw new ServiceException("当前区域未开通服务", I18nKeyConstant.NO_CURRENT_REGION);
        }
        StrategyPlanningConfig planningConfig = buildStrategyKindsForPlanning(userId, routeAndFareDto.getOpenCityId());
        StrategyPlanningConfig planningConfig = this.buildStrategyKindsForPlanning(userId, routeAndFareDto.getOpenCityId());
        List<RouteStrategyKind> kinds = planningConfig.getKinds();
        Map<String, RouteVo> routeById = new LinkedHashMap<>();
        Map<String, Set<RouteStrategyKind>> strategiesById = new LinkedHashMap<>();
        for (RouteStrategyKind kind : kinds) {
        Map<String, RouteStrategyKind> strategiesById = new HashMap<>();
        List<RouteVo> routePoints = new ArrayList<>();
        List<XpRoutePlan> xpRoutePlans = xpRoutePlanMapper.selectList(new LambdaQueryWrapper<XpRoutePlan>().eq(XpRoutePlan::getOpenCityId, routeAndFareDto.getOpenCityId())
                .eq(XpRoutePlan::getAuditStatus, 2));
        log.info("导航策略配置 {} {}", routeAndFareDto.getOpenCityId(), JSON.toJSONString(xpRoutePlans));
        for (XpRoutePlan xpRoutePlan : xpRoutePlans) {
            RouteAndFareDto copy = new RouteAndFareDto();
            copy.setOrigin(routeAndFareDto.getOrigin());
            copy.setDestination(routeAndFareDto.getDestination());
            copy.setOpenCityId(routeAndFareDto.getOpenCityId());
            copy.setUserCouponId(routeAndFareDto.getUserCouponId());
            copy.setVehicleId(routeAndFareDto.getVehicleId());
            copy.setRoutePlanRule(kind.getAmapStrategy());
            R<RouteVo> r = xpMapClient.getDistanceAndDuration(copy);
            if (r.getCode() != 200 || r.getData() == null || r.getData().getRouteID() == null) {
            copy.setRoutePlanRule(xpRoutePlan.getRoutePlanRule());
            R<List<RouteVo>> r = xpMapClient.getDistanceAndDurationList(copy);
            if (r.getCode() != 200 || r.getData() == null || r.getData().isEmpty()) {
                continue;
            }
            String fid = r.getData().getRouteID();
            routeById.putIfAbsent(fid, r.getData());
            strategiesById.computeIfAbsent(fid, k -> new LinkedHashSet<>()).add(kind);
            bb: for (RouteVo datum : r.getData()) {
                for (RouteVo routePoint : routePoints) {
                    if(CollUtil.isEqualList(routePoint.getPolyline(), datum.getPolyline())){
                        continue bb;
                    }
                }
                routePoints.add(datum);
                RouteStrategyKind routeStrategyKind = kinds.stream().filter(kind -> kind.getAmapStrategy() == xpRoutePlan.getRoutePlanRule()).findFirst().get();
                strategiesById.put(datum.getRouteID(), routeStrategyKind);
                break;
            }
        }
        if (routeById.isEmpty()) {
        if (routePoints.isEmpty()) {
            throw new ServiceException("获取导肮信息失败", I18nKeyConstant.PATH_NOT_FOUND);
        }
        XpSystemSetting xpSystemSetting = systemSettingMapper.selectOne(null);
        Integer operateFree = 0 ;
        if(null != xpSystemSetting) {
            operateFree = xpSystemSetting.getOperateFree();
        }
        List<RouteOptionVo> options = new ArrayList<>();
        for (Map.Entry<String, RouteVo> e : routeById.entrySet()) {
            String fid = e.getKey();
            RouteVo rv = e.getValue();
            Set<RouteStrategyKind> kindsOnRoute = strategiesById.get(fid);
            RouteStrategyKind primary = RouteStrategyKind.primaryOf(kindsOnRoute);
        for (RouteVo routePoint : routePoints) {
            RouteAndFareDto pricingDto = new RouteAndFareDto();
            pricingDto.setOrigin(routeAndFareDto.getOrigin());
            pricingDto.setDestination(routeAndFareDto.getDestination());
            pricingDto.setOpenCityId(routeAndFareDto.getOpenCityId());
            pricingDto.setUserCouponId(routeAndFareDto.getUserCouponId());
            pricingDto.setVehicleId(routeAndFareDto.getVehicleId());
            pricingDto.setRoutePlanRule(primary.getAmapStrategy());
            RouteAndFareVo part = pricingForRoute(pricingDto, rv, xpPricing, userId);
            //计算导航对应的费用
            RouteAndFareVo part = pricingForRoute(pricingDto, routePoint, xpPricing, userId);
            RouteOptionVo opt = new RouteOptionVo();
            opt.setPathFingerprint(fid);
            List<String> labels = RouteStrategyKind.orderedOf(kindsOnRoute).stream()
                    .map(kind -> resolveStrategyDisplayName(kind, planningConfig.getDisplayNames()))
                    .collect(Collectors.toList());
            opt.setStrategyLabels(labels);
            opt.setPathFingerprint(routePoint.getRouteID());
            RouteStrategyKind primary = strategiesById.get(routePoint.getRouteID());
            opt.setStrategyLabels(Arrays.asList(primary.getDisplayName()));
            opt.setPrimaryStrategyLabel(resolveStrategyDisplayName(primary, planningConfig.getDisplayNames()));
            opt.setPrimaryRoutePlanRule(primary.getAmapStrategy());
            opt.setPrimaryRoutePlanName(primary.getDisplayName());
            opt.setRoute(part.getRoute());
            opt.setFareEstimate(part.getFareEstimate());
            opt.setXpPricingCard(part.getXpPricingCard());
            if (part.getFareEstimate() != null && part.getFareEstimate().getCouponId() == null) {
                opt.setCouponMessage("当前路线不满足优惠券使用条件");
            }
            opt.setOperateFree(operateFree);
            options.add(opt);
        }
        RouteStrategyKind userPref = resolveUserPreferredKind(userId).orElse(RouteStrategyKind.SMART);
        options.sort((a, b) -> compareRouteOptionByUserPreference(a, b, userPref, strategiesById));
        options.sort((a, b) -> compareRouteOptionByUserPreference(a, b, userPref));
        String snapshotId = UUID.randomUUID().toString().replace("-", "");
        long now = System.currentTimeMillis();
@@ -1080,8 +1216,10 @@
        payload.setUserCouponId(routeAndFareDto.getUserCouponId());
        payload.setRoutes(options);
        XpTradingStrategyDetailVO strategyDetailVO = xpTradingStrategyClient.queryById().getData();
        R<XpTradingStrategyDetailVO>  strategyDetailVOR = xpTradingStrategyClient.queryById();
        XpTradingStrategyDetailVO strategyDetailVO = strategyDetailVOR.getData();
        redisService.setCacheObject(CacheConstants.ORDER_MULTI_ROUTE_SNAPSHOT + userId + ":" + snapshotId, JSON.toJSONString(payload), Long.valueOf(strategyDetailVO.getMaxStandingTiming()), TimeUnit.SECONDS);
        MultiRouteAndFareVo vo = new MultiRouteAndFareVo();
        vo.setSnapshotId(snapshotId);
@@ -1091,12 +1229,14 @@
        vo.setRoutePreferences(listRoutePreferences(routeAndFareDto.getOpenCityId(), userId));
        vo.setStaleCheckSeconds(navigationStaleSeconds);
        vo.setPriceWaveThresholdPercent(navigationPriceWavePercent);
        vo.setOperateFree(operateFree);
        //产品喊写死
        vo.setMaxPeopleNumber(5);
        RouteOptionVo first = options.get(0);
        redisService.setCacheObject("ORDER_NAVIGATION_END_DATA:" + userId, JSON.toJSONString(first.getRoute()), 24L, TimeUnit.HOURS);
        return vo;
    }
    XpTradingStrategyClient xpTradingStrategyClient;
    @Override
    public void selectNavigationRoute(SelectNavigationRouteDto dto, String userId) {
        String json = redisService.getCacheObject(CacheConstants.ORDER_MULTI_ROUTE_SNAPSHOT + userId + ":" + dto.getSnapshotId());
@@ -1165,22 +1305,25 @@
    @Override
    public List<RoutePreferenceItemVo> listRoutePreferences(Long openCityId, String userId) {
        Set<String> enabledCodes = parseEnabledPreferenceCodes();
        Optional<RouteStrategyKind> savedPref = resolveUserPreferredKind(userId);
        Map<RouteStrategyKind, String> displayNames = buildStrategyKindsForPlanning(userId, openCityId).getDisplayNames();
        Optional<RouteStrategyKind> savedPref = resolveUserPreferredKind(userId);//获取用户设置的路线偏好
        List<XpRoutePlan> routePlans = findRoutePlans(openCityId);
        List<RoutePreferenceItemVo> list = new ArrayList<>();
        int i = 0;
        for (RouteStrategyKind k : RouteStrategyKind.orderedValues()) {
            if (!enabledCodes.contains(k.name())) {
                continue;
        if(CollUtil.isNotEmpty(routePlans)){
            int i = 0;
            for (XpRoutePlan routePlan : routePlans) {
                RoutePreferenceItemVo v = new RoutePreferenceItemVo();
                RouteStrategyKind strategy = RouteStrategyKind.getStrategy(routePlan.getRoutePlanRule());
                if(strategy != null){
                    v.setCode(strategy.name());
                }
                v.setName(routePlan.getPlanName());
                v.setEnabled(true);
                v.setSortOrder(i++);
                v.setAmapStrategy(routePlan.getRoutePlanRule());
                v.setSelected(savedPref.isPresent() && strategy == savedPref.get());
                list.add(v);
            }
            RoutePreferenceItemVo v = new RoutePreferenceItemVo();
            v.setCode(k.name());
            v.setName(resolveStrategyDisplayName(k, displayNames));
            v.setEnabled(true);
            v.setSortOrder(i++);
            v.setAmapStrategy(k.getAmapStrategy());
            v.setSelected(savedPref.isPresent() && k == savedPref.get());
            list.add(v);
        }
        return list;
    }
@@ -1212,16 +1355,21 @@
        return set;
    }
    private List<XpRoutePlan> findRoutePlans (Long openCityId){
        return xpRoutePlanMapper.selectList(new LambdaQueryWrapper<XpRoutePlan>().eq(XpRoutePlan::getOpenCityId, openCityId)
                .eq(XpRoutePlan::getAuditStatus, 2));
    }
    /**
     * 用户偏好策略优先请求,其余策略仍请求以便合并去重。
     */
    private StrategyPlanningConfig buildStrategyKindsForPlanning(String userId, Long openCityId) {
        Set<String> enabled = parseEnabledPreferenceCodes();
        List<XpRoutePlan> xpRoutePlans = xpRoutePlanMapper.selectList(new LambdaQueryWrapper<XpRoutePlan>().eq(XpRoutePlan::getOpenCityId, openCityId));
        List<XpRoutePlan> xpRoutePlans = xpRoutePlanMapper.selectList(new LambdaQueryWrapper<XpRoutePlan>().eq(XpRoutePlan::getOpenCityId, openCityId)
                .eq(XpRoutePlan::getAuditStatus, 2));
        Map<RouteStrategyKind, String> displayNames = new LinkedHashMap<>();
        List<RouteStrategyKind> configuredKinds = new ArrayList<>();
        if (xpRoutePlans.isEmpty()) {
            configuredKinds.addAll(RouteStrategyKind.defaultPreferenceKinds());
            throw new ServiceException("未配置有效的导航策略", I18nKeyConstant.PATH_NOT_FOUND);
        } else {
            for (XpRoutePlan xpRoutePlan : xpRoutePlans) {
                Integer strategy = xpRoutePlan.getRoutePlanRule();
@@ -1236,31 +1384,7 @@
                });
            }
        }
        List<RouteStrategyKind> all = new ArrayList<>();
        for (RouteStrategyKind k : configuredKinds) {
            if (enabled.contains(k.name())) {
                addIfAbsent(all, k);
            }
        }
        if (all.isEmpty()) {
            all.add(resolveDefaultEnabledKind(enabled));
        }
        Optional<RouteStrategyKind> pref = resolveUserPreferredKind(userId);
        if (!pref.isPresent()) {
            return new StrategyPlanningConfig(all, displayNames);
        }
        RouteStrategyKind p = pref.get();
        if (!all.contains(p)) {
            return new StrategyPlanningConfig(all, displayNames);
        }
        List<RouteStrategyKind> ordered = new ArrayList<>();
        ordered.add(p);
        for (RouteStrategyKind k : all) {
            if (k != p) {
                ordered.add(k);
            }
        }
        return new StrategyPlanningConfig(ordered, displayNames);
        return new StrategyPlanningConfig(configuredKinds, displayNames);
    }
    private String resolveStrategyDisplayName(RouteStrategyKind kind, Map<RouteStrategyKind, String> displayNames) {
@@ -1322,23 +1446,12 @@
        }
    }
    private int compareRouteOptionByUserPreference(RouteOptionVo a, RouteOptionVo b, RouteStrategyKind pref,
                                                   Map<String, Set<RouteStrategyKind>> strategiesById) {
        Set<RouteStrategyKind> sa = strategiesById.getOrDefault(a.getPathFingerprint(), Collections.emptySet());
        Set<RouteStrategyKind> sb = strategiesById.getOrDefault(b.getPathFingerprint(), Collections.emptySet());
        boolean aHas = sa.contains(pref);
        boolean bHas = sb.contains(pref);
        if (aHas != bHas) {
            return bHas ? 1 : -1;
    private int compareRouteOptionByUserPreference(RouteOptionVo a, RouteOptionVo b, RouteStrategyKind pref) {
        Integer primaryRoutePlanRule = a.getPrimaryRoutePlanRule();
        if(primaryRoutePlanRule == pref.getAmapStrategy()){
            return 1;
        }
        boolean aPrimary = a.getPrimaryRoutePlanRule() != null && a.getPrimaryRoutePlanRule() == pref.getAmapStrategy();
        boolean bPrimary = b.getPrimaryRoutePlanRule() != null && b.getPrimaryRoutePlanRule() == pref.getAmapStrategy();
        if (aPrimary != bPrimary) {
            return bPrimary ? 1 : -1;
        }
        int da = a.getRoute() != null && a.getRoute().getDuration() != null ? a.getRoute().getDuration() : Integer.MAX_VALUE;
        int db = b.getRoute() != null && b.getRoute().getDuration() != null ? b.getRoute().getDuration() : Integer.MAX_VALUE;
        return Integer.compare(da, db);
        return -1;
    }
    @Override
@@ -1380,9 +1493,10 @@
            int totalCount = queueItems.size();
            for (int i = 0; i < queueItems.size(); i++) {
                currentPosition++;
                String item = queueItems.get(i);
                if (item.startsWith(orderId + "_")) {
                    currentPosition = i + 1; // 位置从1开始
                String[] split = item.split("_");
                if (split[0].equals(orderId + "")) {
                    break;
                }
            }