yyy
2026-04-22 e032ce14c50d1d7ff769485d83b945754e356674
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
package com.xiaopeng.map.service.serviceimpl;
 
 
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaopeng.api.dto.operation.PointAddDto;
import com.xiaopeng.api.dto.operation.PointMapQuery;
import com.xiaopeng.api.dto.order.HistoryEndPointsDto;
import com.xiaopeng.api.dto.order.HistoryStartPointsDto;
import com.xiaopeng.api.feignClient.account.XpAppUserCollectAddrClient;
import com.xiaopeng.api.model.operation.XpElectronicFenceArea;
import com.xiaopeng.api.model.operation.XpElectronicFence;
import com.xiaopeng.api.model.operation.XpPoint;
import com.xiaopeng.api.model.operation.XpRegion;
import com.xiaopeng.api.model.operation.XpStation;
import com.xiaopeng.api.model.operation.XpSystemSetting;
import com.xiaopeng.api.query.operation.PointListQuery;
import com.xiaopeng.api.query.operation.PointPageListListQuery;
import com.xiaopeng.api.vo.order.XpHistoryEndPointsVo;
import com.xiaopeng.api.vo.order.XpHistoryStartPointsVo;
import com.xiaopeng.api.vo.order.XpPointsListVo;
import com.xiaopeng.api.vo.order.XpPointsSearchVo;
import com.xiaopeng.common.core.constant.CacheConstants;
import com.xiaopeng.common.core.domain.R;
import com.xiaopeng.common.core.exception.ServiceException;
import com.xiaopeng.common.core.utils.StringUtils;
import com.xiaopeng.common.core.web.page.PageInfo;
import com.xiaopeng.common.redis.service.RedisService;
import com.xiaopeng.evi.oss.service.AliOssService;
import com.xiaopeng.map.constant.I18nKeyConstant;
import com.xiaopeng.map.dto.NearestDto;
import com.xiaopeng.map.dto.StationDetailQueryDto;
import com.xiaopeng.map.mapper.XpPointMapper;
import com.xiaopeng.map.mapper.XpElectronicFenceMapper;
import com.xiaopeng.map.mapper.XpRegionMapper;
import com.xiaopeng.map.mapper.XpSystemSettingMapper;
import com.xiaopeng.map.query.PointByNameQuery;
import com.xiaopeng.map.service.XpElectronicFenceAreaService;
import com.xiaopeng.map.service.XpPointService;
import com.xiaopeng.map.service.XpStationService;
import com.xiaopeng.map.utils.TimeRangeChecker;
import com.xiaopeng.map.utils.holiday.HolidayUtil;
import com.xiaopeng.map.utils.map.map.FastDistanceCalculator;
import com.xiaopeng.map.vo.NearestNextVo;
import com.xiaopeng.map.vo.NearestVo;
import com.xiaopeng.map.vo.OrderDistanceVo;
import com.xiaopeng.map.vo.StationDetailVo;
import com.xiaopeng.map.vo.StationPointItemVo;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.apache.shardingsphere.transaction.annotation.ShardingSphereTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 点位管理 服务实现类
 * </p>
 *
 * @author liu
 * @author WuGuanFengYue
 * @since 2026-02-03
 */
@Service
@Slf4j
public class XpPointServiceImpl extends ServiceImpl<XpPointMapper, XpPoint> implements XpPointService {
 
    private static final String POINT_BIZ_TYPE = "PUD";
    private static final int SERIAL_WIDTH = 6;
    private static final int LOCK_WAIT_SECONDS = 5;
    private static final int LOCK_LEASE_SECONDS = 30;
 
    @Resource
    private XpSystemSettingMapper xpSystemSettingMapper;
 
    @Resource
    private RedisService redisService;
 
    @Resource
    private HolidayUtil holidayUtil;
 
    @Resource
    private XpElectronicFenceAreaService xpElectronicFenceAreaService;
 
    @Resource
    private XpElectronicFenceMapper xpElectronicFenceMapper;
 
    @Resource
    @Lazy
    private XpStationService xpStationService;
 
    @Resource
    private XpAppUserCollectAddrClient xpAppUserCollectAddrClient;
 
    @Resource
    private XpRegionMapper xpRegionMapper;
 
    @Autowired
    private RedissonClient redissonClient;
 
    @Autowired
    private AliOssService aliOssService;
 
    @Override
    @Transactional
    @ShardingSphereTransactionType(TransactionType.BASE)
    public XpPoint addPointWithGeneratedNumber(PointAddDto pointAddDto) {
        if (pointAddDto == null) {
            throw new ServiceException("参数不能为空", I18nKeyConstant.SYSTEM_EXCEPTION);
        }
        if (pointAddDto.getElectronicAreaId() == null) {
            throw new ServiceException("运营区域ID不能为空", I18nKeyConstant.POINT_ELECTRONIC_AREA_ID_EMPTY);
        }
        validatePointNameUnique(pointAddDto.getPointName(), null);
 
        String pointNumber = getPointNumber(pointAddDto.getElectronicAreaId());
 
        XpPoint xpPoint = new XpPoint();
        BeanUtils.copyProperties(pointAddDto, xpPoint);
        xpPoint.setFpElectronicAreaId(pointAddDto.getElectronicAreaId());
        xpPoint.setPointNumber(pointNumber);
        xpPoint.setStationSortNo(0);
        this.save(xpPoint);
 
        //场站点位排序 后添加的点位 排第一个。
        this.setStationSortNo(xpPoint.getStationId(),0);
 
        return xpPoint;
    }
 
    /**
     * 场站 点位排序
     * @param stationId
     * @param stationSortNo
     */
    @Transactional
    @Override
    public void setStationSortNo(Long stationId, Integer stationSortNo){
        if(null != stationId  && stationSortNo != null && stationSortNo ==0){
            // 查询该场站下的所有点位,按 stationSortNo 排序
            List<XpPoint> points = this.lambdaQuery()
                    .eq(XpPoint::getStationId, stationId)
                    .orderByAsc(XpPoint::getStationSortNo)
                    .list();
 
            if (CollUtil.isNotEmpty(points)) {
                int newSortNo = 1;
                for (XpPoint point : points) {
                    point.setStationSortNo(newSortNo++);
                }
                this.updateBatchById(points);
            }
        }
    }
 
    @Override
    public String getPointNumber(Long electronicAreaId) {
        String cityPrefix = buildCityPrefix(electronicAreaId);
        String lockKey = buildPointNumberLockKey(cityPrefix, POINT_BIZ_TYPE);
        RLock lock = redissonClient.getLock(lockKey);
        boolean locked = false;
        String pointNumber;
        try {
            locked = lock.tryLock(LOCK_WAIT_SECONDS, LOCK_LEASE_SECONDS, TimeUnit.SECONDS);
            if (!locked) {
                throw new ServiceException("点位编号生成繁忙,请稍后重试", I18nKeyConstant.POINT_NUMBER_LOCK_FAIL);
            }
            String maxPointNumber = this.baseMapper.selectMaxPointNumber(cityPrefix, POINT_BIZ_TYPE);
            int nextSerial = 1;
            if (StringUtils.hasText(maxPointNumber)) {
                nextSerial = parseSerialOrThrow(maxPointNumber) + 1;
            }
            pointNumber = cityPrefix + "-" + POINT_BIZ_TYPE + "-" + String.format("%0" + SERIAL_WIDTH + "d", nextSerial);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new ServiceException("点位编号生成繁忙,请稍后重试", I18nKeyConstant.POINT_NUMBER_LOCK_FAIL);
        } finally {
            try {
                if (locked && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            } catch (Exception e) {
                log.warn("释放点位编号生成锁失败 lockKey={}", lockKey, e);
            }
        }
        return pointNumber;
    }
 
    @Override
    public void validatePointNameUnique(String pointName, Long excludeId) {
        if (!StringUtils.hasText(pointName)) {
            return;
        }
        long count = this.lambdaQuery()
                .eq(XpPoint::getPointName, pointName)
                .ne(excludeId != null, XpPoint::getId, excludeId)
                .count();
        if (count > 0) {
            throw new ServiceException("点位名称已存在", I18nKeyConstant.POINT_NAME_EXISTS);
        }
    }
 
    @Override
    public NearestVo nearest(NearestDto dto) {
        // 走缓存
        Object orderDistanceObj = redisService.getCacheObject(CacheConstants.NEAR_POINT_DISTANCE);
        Integer orderDistance;
        if (orderDistanceObj != null) {
            orderDistance = Integer.valueOf(orderDistanceObj.toString());
        } else {
            XpSystemSetting xpSystemSetting = xpSystemSettingMapper.selectOne(null);
            orderDistance = xpSystemSetting.getNearPointDistance();
        }
        // 获取所有的站点信息
        List<XpPoint> list = list(new LambdaQueryWrapper<XpPoint>().eq(XpPoint::getOperationStatus, 2).eq(XpPoint::getPointType,1).isNotNull(XpPoint::getElectronicAreaId)
                // 添加距离计算字段
                .apply("ST_Distance_Sphere(point({0}, {1}), point(point_lon, point_lat)) <= {2}",
                        dto.getLongitude(), dto.getLatitude(), orderDistance));
        NearestVo nearestVo = new NearestVo();
        List<NearestNextVo> nearestNextVos = new ArrayList<>();
        LocalTime now = LocalTime.now();
 
 
        for (XpPoint xpPoint : list) {
            // 判断是否在时间段内
            boolean intime = getInTime(now, xpPoint.getEffectivePeriod(), xpPoint.getEffectiveTimePeriod());
            if (!intime) {
                continue;
            }
            // 计算距离 小于的站点
            double v = FastDistanceCalculator.distanceFast(dto.getLatitude(), dto.getLongitude(), xpPoint.getPointLat(), xpPoint.getPointLon());
            if (v < orderDistance) {
                NearestNextVo nearestNextVo = new NearestNextVo();
                nearestNextVo.setId(xpPoint.getId());
                nearestNextVo.setName(xpPoint.getPointName());
                nearestNextVo.setLatitude(xpPoint.getPointLat());
                nearestNextVo.setLongitude(xpPoint.getPointLon());
                nearestNextVo.setDistance(v);
                nearestNextVo.setAddress(xpPoint.getPointAddress());
                nearestNextVo.setTime(xpPoint.getParkingTimeLimit());
                nearestNextVo.setElectronicAreaId(xpPoint.getElectronicAreaId());
 
 
                nearestNextVos.add(nearestNextVo);
            }
        }
        if (!nearestNextVos.isEmpty()) {
            nearestNextVos = nearestNextVos.stream().sorted(Comparator.comparing(NearestNextVo::getDistance)).collect(Collectors.toList());
        }
        nearestVo.setPoints(nearestNextVos);
        nearestVo.setTotal(nearestNextVos.size());
        return nearestVo;
 
    }
 
    private String buildCityPrefix(Long electronicAreaId) {
        //所有围栏范围之外,测试点位
        if(0 == electronicAreaId){
            return "TEST";
        }
        XpElectronicFenceArea area = xpElectronicFenceAreaService.getById(electronicAreaId);
        if (area == null) {
            throw new ServiceException("运营区域不存在", I18nKeyConstant.POINT_ELECTRONIC_AREA_NOT_EXIST);
        }
        if (!StringUtils.hasText(area.getCityCode())) {
            throw new ServiceException("城市信息不存在", I18nKeyConstant.POINT_CITY_NOT_EXIST);
        }
 
        XpRegion region = xpRegionMapper.selectOne(new LambdaQueryWrapper<XpRegion>()
                .eq(XpRegion::getCode, area.getCityCode()));
        if (region == null || !StringUtils.hasText(region.getName())) {
            throw new ServiceException("城市信息不存在", I18nKeyConstant.POINT_CITY_NOT_EXIST);
        }
 
        String name = region.getName();
        String prefix = name.length() <= 2 ? name : name.substring(0, 2);
        return getPinyinInitials(prefix).toUpperCase();
    }
 
    private static String buildPointNumberLockKey(String cityPrefix, String bizType) {
        return "xp:point:number:" + cityPrefix + ":" + bizType;
    }
 
    private static String getPinyinInitials(String chinese) {
        StringBuilder pinyinInitials = new StringBuilder();
        for (char c : chinese.toCharArray()) {
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c);
            if (pinyinArray != null && pinyinArray.length > 0) {
                pinyinInitials.append(pinyinArray[0].charAt(0));
            }
        }
        return pinyinInitials.toString();
    }
 
    private static int parseSerialOrThrow(String pointNumber) {
        String[] parts = pointNumber.split("-");
        if (parts.length < 3) {
            throw new ServiceException("点位编号生成失败(历史编号格式异常)", I18nKeyConstant.POINT_NUMBER_PARSE_FAIL);
        }
        String serialPart = parts[parts.length - 1];
        if (serialPart.length() != SERIAL_WIDTH) {
            throw new ServiceException("点位编号生成失败(历史编号格式异常)", I18nKeyConstant.POINT_NUMBER_PARSE_FAIL);
        }
        try {
            return Integer.parseInt(serialPart);
        } catch (NumberFormatException e) {
            throw new ServiceException("点位编号生成失败(历史编号格式异常)", I18nKeyConstant.POINT_NUMBER_PARSE_FAIL);
        }
    }
 
 
 
    public boolean getInTime(LocalTime now,  Integer effectivePeriod, String effectiveTimePeriod){
        //  2非工作日  0工作日  1节假日 3调休日
        Integer holidayToday = holidayUtil.isHolidayToday();
        if(effectivePeriod==1){
            boolean inTime = TimeRangeChecker.isCurrentTimeInRanges(now,effectiveTimePeriod);
            if (!inTime) {
                return false;
            }
        }else if(effectivePeriod==2){
            if(holidayToday!=0){
                return false;
            }
            boolean inTime = TimeRangeChecker.isCurrentTimeInRanges(now,effectiveTimePeriod);
            if (!inTime) {
                return false;
            }
        }else if(effectivePeriod==3){
            if(holidayToday!=2){
                return false;
            }
            boolean inTime = TimeRangeChecker.isCurrentTimeInRanges(now,effectiveTimePeriod);
            if (!inTime) {
                return false;
            }
        }else if(effectivePeriod==4){
            if(holidayToday!=1){
                return false;
            }
            boolean inTime = TimeRangeChecker.isCurrentTimeInRanges(now,effectiveTimePeriod);
            if (!inTime) {
                return false;
            }
        }
        return true;
    }
 
    @Override
    public List<XpPoint> pointMap(PointMapQuery query) {
        List<XpPoint> list = this.baseMapper.pointMap(query);
        return list;
    }
 
    @Override
    public List<XpPoint> listAll(PointListQuery query) {
        List<XpPoint> list = this.baseMapper.listAll(query);
        for (XpPoint xpPoint : list) {
            String pointPictures = xpPoint.getPointPictures();
            log.info("pointPictures:{}", pointPictures);
            if (StringUtils.isNotBlank(pointPictures)) {
                log.info("pointPictures进入处理:{}", pointPictures);
 
                JSONArray jsonArray = JSONArray.parseArray(pointPictures);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    if (Objects.isNull(jsonObject)) {
                        continue;
                    }
                    String downloadUrl ="";
//                    try { todo 20260422 yyy暂时注释
//                        downloadUrl = aliOssService.getDownloadUrl(jsonObject.getString("id"), jsonObject.getString("name"), true);
//                        log.info("downloadUrl:{}", downloadUrl);
//                    } catch (UnsupportedEncodingException e) {
//                        log.error("获取图片下载地址失败", e);
//                    }
                    jsonObject.put("url", downloadUrl);
                }
                log.info("jsonArray:{}", jsonArray);
                xpPoint.setPointPictures(JSONArray.toJSONString(jsonArray));
                log.info("xpPoint:{}", xpPoint.getPointPictures());
            }
 
        }
 
        return list;
    }
 
    @Override
    public List<XpHistoryStartPointsVo> getHistoryStartPoints(HistoryStartPointsDto historyStartPointsDto) {
        List<XpPoint> xpPoints = this.baseMapper.selectBatchIds(historyStartPointsDto.getPointIds());
        ArrayList<XpHistoryStartPointsVo> resultList = new ArrayList<>(10);
        for (XpPoint xpPoint : xpPoints) {
            XpHistoryStartPointsVo xpHistoryStartPointsVo = new XpHistoryStartPointsVo();
            xpHistoryStartPointsVo.setName(xpPoint.getPointName());
            xpHistoryStartPointsVo.setAddress(xpPoint.getPointAddress());
            xpHistoryStartPointsVo.setLatitude(xpPoint.getPointLat());
            xpHistoryStartPointsVo.setLongitude(xpPoint.getPointLon());
            xpHistoryStartPointsVo.setId(xpPoint.getId());
            double distanced = FastDistanceCalculator.distanceFastKm(historyStartPointsDto.getLat(), historyStartPointsDto.getLon(), xpPoint.getPointLat(), xpPoint.getPointLon());
            xpHistoryStartPointsVo.setDistance(distanced);
            xpHistoryStartPointsVo.setTime(xpPoint.getParkingTimeLimit());
            xpHistoryStartPointsVo.setElectronicAreaId(xpPoint.getElectronicAreaId());
            resultList.add(xpHistoryStartPointsVo);
 
        }
 
        return resultList;
    }
 
    @Override
    public List<XpHistoryEndPointsVo> getHistoryEndPoints(HistoryEndPointsDto historyEndPointsDto) {
        List<XpPoint> xpPoints = this.baseMapper.selectBatchIds(historyEndPointsDto.getPointIds());
        ArrayList<XpHistoryEndPointsVo> resultList = new ArrayList<>(10);
        for (XpPoint xpPoint : xpPoints) {
            XpHistoryEndPointsVo xpHistoryEndPointsVo = new XpHistoryEndPointsVo();
            xpHistoryEndPointsVo.setName(xpPoint.getPointName());
            xpHistoryEndPointsVo.setAddress(xpPoint.getPointAddress());
            xpHistoryEndPointsVo.setLatitude(xpPoint.getPointLat());
            xpHistoryEndPointsVo.setLongitude(xpPoint.getPointLon());
            xpHistoryEndPointsVo.setId(xpPoint.getId());
            double distanced = FastDistanceCalculator.distanceFastKm(historyEndPointsDto.getLat(), historyEndPointsDto.getLon(), xpPoint.getPointLat(), xpPoint.getPointLon());
            xpHistoryEndPointsVo.setDistance(distanced);
            xpHistoryEndPointsVo.setTime(xpPoint.getParkingTimeLimit());
            xpHistoryEndPointsVo.setElectronicAreaId(xpPoint.getElectronicAreaId());
            resultList.add(xpHistoryEndPointsVo);
        }
 
        return resultList;
    }
 
    @Override
    public StationDetailVo queryStationDetail(StationDetailQueryDto dto, String uid) {
        StationDetailVo stationDetailVo = new StationDetailVo();
        if (dto == null || dto.getStationId() == null) {
            return stationDetailVo;
        }
 
        XpStation station = xpStationService.getById(dto.getStationId());
        if (station == null || !isStationAvailable(station)) {
            return stationDetailVo;
        }
 
        // 仅查询场站下运营点位,最终结果还会叠加时段/围栏有效性过滤。
        List<XpPoint> stationPoints = this.lambdaQuery()
                .eq(XpPoint::getStationId, station.getId())
                .eq(XpPoint::getPointType, 1)
                .eq(XpPoint::getOperationStatus, 2)
                .list();
        if (CollUtil.isEmpty(stationPoints)) {
            return stationDetailVo;
        }
 
        Map<Long, XpElectronicFenceArea> areaMap = buildAreaMap(stationPoints.stream()
                .map(XpPoint::getElectronicAreaId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList()));
        Map<Long, XpElectronicFence> fenceMap = buildFenceMap(areaMap.values().stream()
                .map(XpElectronicFenceArea::getElectronicId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList()));
        Set<Long> collectStationIds = getCollectStationIds(uid);
        Set<Long> collectPointIds = getCollectPointIds(uid);
 
        // 默认点位优先置顶,其余点位再按场站内排序和距离排序。
        List<StationPointItemVo> points = stationPoints.stream()
                .filter(point -> isPointAvailable(point, areaMap, fenceMap))
                .map(point -> toStationPointItem(point, station.getDefaultPointId(), dto.getLatitude(), dto.getLongitude(), collectPointIds))
                .sorted(buildStationPointComparator())
                .collect(Collectors.toList());
        if (points.isEmpty()) {
            return new StationDetailVo();
        }
 
        stationDetailVo.setStationId(station.getId());
        stationDetailVo.setStationName(station.getStationName());
        stationDetailVo.setDefaultPointId(station.getDefaultPointId());
        stationDetailVo.setCenterLon(station.getCenterLon());
        stationDetailVo.setCenterLat(station.getCenterLat());
        if (collectStationIds.contains(station.getId())) {
            stationDetailVo.setIsCollect(1);
        }
        stationDetailVo.setPoints(points);
        return stationDetailVo;
    }
 
    @Override
    public XpPointsSearchVo queryPointByName(PointByNameQuery query) {
        XpPointsSearchVo searchVo = new XpPointsSearchVo();
        List<XpPointsListVo> list = this.baseMapper.queryPointByName(query);
        if (list.isEmpty()) {
            return searchVo;
        }
 
        LocalTime now = LocalTime.now();
        for (XpPointsListVo xpPointsListVo : list) {
            boolean inTime = getInTime(now, xpPointsListVo.getEffectivePeriod(), xpPointsListVo.getEffectiveTimePeriod());
            if (!inTime) {
                // 不在运营段
                xpPointsListVo.setState(0);
            }
 
        }
 
        // 组装数据 并排序 剔除不在运营段的 数据
        List<XpPointsListVo> resultList = list.stream().peek(vo -> vo.setDistance(FastDistanceCalculator.distanceFast(query.getLat(), query.getLon(), vo.getLatitude(), vo.getLongitude()))).filter(vo -> vo.getState() == 1).collect(Collectors.toList());
 
        // 可用点位
        List<XpPointsListVo> availablePoints = resultList.stream().filter(e -> query.getElectronicAreaId() != null && e.getElectronicAreaId().equals(query.getElectronicAreaId())).sorted(Comparator.comparing(XpPointsListVo::getDistance)).collect(Collectors.toList());//
 
        // 不可用点位
        List<XpPointsListVo> unavailablePoints = resultList.stream().filter(e -> query.getElectronicAreaId() == null || !e.getElectronicAreaId().equals(query.getElectronicAreaId())).sorted(Comparator.comparing(XpPointsListVo::getDistance)).collect(Collectors.toList());
        searchVo.setAvailablePoints(availablePoints);
        searchVo.setUnavailablePoints(unavailablePoints);
        return searchVo;
    }
 
    @Override
    public OrderDistanceVo getOrderDistance() {
        OrderDistanceVo orderDistanceVo = new OrderDistanceVo();
        XpSystemSetting xpSystemSetting = xpSystemSettingMapper.selectOne(null);
        if (xpSystemSetting != null) {
            orderDistanceVo.setMaxDistance(xpSystemSetting.getOrderDistance());
            orderDistanceVo.setMinDistance(xpSystemSetting.getMinOrderDistance());
            orderDistanceVo.setAdsorptionDistance(xpSystemSetting.getAdsorptionDistance());
            orderDistanceVo.setNearPointDistance(xpSystemSetting.getNearPointDistance());
            return orderDistanceVo;
        }
        return orderDistanceVo;
    }
 
    @Override
    public PageInfo<XpPoint> pageList(PointPageListListQuery query) {
        PageInfo<XpPoint> pageInfo = new PageInfo<>(query.getPageNum(),query.getPageSize());
        if (StringUtils.isNotBlank(query.getPointLonAndLat())) {
            List<String> lonAndLat = query.getPointLonAndLat().trim().contains(",") ? Arrays.asList(query.getPointLonAndLat().split(",")) :
                    query.getPointLonAndLat().trim().contains(" ") ? Arrays.asList(query.getPointLonAndLat().split(" ")) :
                            Collections.emptyList();
            if (CollUtil.isNotEmpty(lonAndLat)) {
                query.setPointLon(lonAndLat.get(0));
                query.setPointLat(lonAndLat.get(1));
                query.setPointLonAndLat(null);
            }
        }
        List<XpPoint> list = this.baseMapper.pageList(pageInfo,query);
        pageInfo.setRecords(list);
        return pageInfo;
    }
 
    private Map<Long, XpElectronicFenceArea> buildAreaMap(List<Long> areaIds) {
        if (CollUtil.isEmpty(areaIds)) {
            return Collections.emptyMap();
        }
        return xpElectronicFenceAreaService.listByIds(areaIds).stream()
                .collect(Collectors.toMap(XpElectronicFenceArea::getId, area -> area, (a, b) -> a));
    }
 
    /**
     * 提前拉取电子围栏,避免逐点位重复查库。
     */
    private Map<Long, XpElectronicFence> buildFenceMap(List<Long> fenceIds) {
        if (CollUtil.isEmpty(fenceIds)) {
            return Collections.emptyMap();
        }
        return xpElectronicFenceMapper.selectBatchIds(fenceIds).stream()
                .collect(Collectors.toMap(XpElectronicFence::getId, fence -> fence, (a, b) -> a));
    }
 
    /**
     * 场站可展示判断:
     * 1. 状态必须为启用中;
     * 2. 与运营区同步时,依赖运营区和围栏的当前有效性;
     * 3. 自定义时段时,依赖场站自身时段配置。
     */
    private boolean isStationAvailable(XpStation station) {
        if (station == null || !Integer.valueOf(6).equals(station.getStatus())) {
            return false;
        }
        if (Integer.valueOf(1).equals(station.getOperationType())) {
            if (station.getElectronicAreaId() == null) {
                return false;
            }
            XpElectronicFenceArea area = xpElectronicFenceAreaService.getById(station.getElectronicAreaId());
            if (area == null || !Integer.valueOf(1).equals(area.getAreaStatus()) || area.getElectronicId() == null) {
                return false;
            }
            XpElectronicFence fence = xpElectronicFenceMapper.selectById(area.getElectronicId());
            return isFenceAvailable(fence);
        }
        if (Integer.valueOf(2).equals(station.getOperationType())
                && station.getEffectivePeriod() != null
                && StringUtils.isNotBlank(station.getEffectiveTimePeriod())) {
            return getInTime(LocalTime.now(), station.getEffectivePeriod(), station.getEffectiveTimePeriod());
        }
        return false;
    }
 
    /**
     * 子点位是否可展示与场站卡片中。
     * 规则与现有点位有效性保持一致,避免地图页和其他点位查询出现口径偏差。
     */
    private boolean isPointAvailable(XpPoint point, Map<Long, XpElectronicFenceArea> areaMap, Map<Long, XpElectronicFence> fenceMap) {
        if (point == null || !Integer.valueOf(2).equals(point.getOperationStatus())) {
            return false;
        }
        if (Integer.valueOf(1).equals(point.getOperationType())) {
            if (point.getElectronicAreaId() == null) {
                return false;
            }
            XpElectronicFenceArea area = areaMap.get(point.getElectronicAreaId());
            if (area == null || !Integer.valueOf(1).equals(area.getAreaStatus()) || area.getElectronicId() == null) {
                return false;
            }
            return isFenceAvailable(fenceMap.get(area.getElectronicId()));
        }
        if (Integer.valueOf(2).equals(point.getOperationType())
                && point.getEffectivePeriod() != null
                && StringUtils.isNotBlank(point.getEffectiveTimePeriod())) {
            return getInTime(LocalTime.now(), point.getEffectivePeriod(), point.getEffectiveTimePeriod());
        }
        return false;
    }
 
    /**
     * 围栏生效判断:
     * 启用中,且当前时间需要落在生效时间与失效时间窗口内。
     */
    private boolean isFenceAvailable(XpElectronicFence fence) {
        if (fence == null || !Integer.valueOf(2).equals(fence.getStatus())) {
            return false;
        }
        LocalDateTime now = LocalDateTime.now();
        if (fence.getEffectTime() != null && now.isBefore(fence.getEffectTime())) {
            return false;
        }
        return !Integer.valueOf(2).equals(fence.getFailureType()) || fence.getFailureTime() == null || !now.isAfter(fence.getFailureTime());
    }
 
    /**
     * 组装单个场站子点位返回对象,并在有默认点位配置时打标。
     */
    private StationPointItemVo toStationPointItem(XpPoint point, Long defaultPointId, Double latitude, Double longitude, Set<Long> collectPointIds) {
        StationPointItemVo itemVo = new StationPointItemVo();
        itemVo.setPointId(point.getId());
        itemVo.setPointName(point.getPointName());
        itemVo.setPointAddress(point.getPointAddress());
        itemVo.setLatitude(point.getPointLat());
        itemVo.setLongitude(point.getPointLon());
        itemVo.setStationSortNo(point.getStationSortNo());
        if (collectPointIds.contains(point.getId())) {
            itemVo.setIsCollect(1);
        }
        if (defaultPointId != null && defaultPointId.equals(point.getId())) {
            itemVo.setIsDefault(1);
        }
        if (latitude != null && longitude != null && point.getPointLat() != null && point.getPointLon() != null) {
            double distance = FastDistanceCalculator.distanceFast(latitude, longitude, point.getPointLat(), point.getPointLon());
            itemVo.setDistance(BigDecimal.valueOf(distance).setScale(2, RoundingMode.HALF_UP).doubleValue());
        }
        return itemVo;
    }
 
    /**
     * 排序规则:
     * 默认点位优先,其次按场站内排序,再按与当前定位距离排序。
     */
    private Comparator<StationPointItemVo> buildStationPointComparator() {
        return Comparator
                .comparing((StationPointItemVo item) -> item.getIsDefault() == null ? 2 : item.getIsDefault())
                .thenComparing(item -> item.getStationSortNo() == null ? Integer.MAX_VALUE : item.getStationSortNo())
                .thenComparing(item -> item.getDistance() == null ? Double.MAX_VALUE : item.getDistance());
    }
 
    /**
     * 查询用户收藏的场站ID。
     * 收藏服务异常时降级为空集合,避免影响场站详情主流程。
     */
    private Set<Long> getCollectStationIds(String uid) {
        if (!StringUtils.hasText(uid)) {
            return Collections.emptySet();
        }
        try {
            R<List<Long>> result = xpAppUserCollectAddrClient.getStationIdsByUserId(Long.valueOf(uid));
            if (result == null || CollUtil.isEmpty(result.getData())) {
                return Collections.emptySet();
            }
            return new HashSet<>(result.getData());
        } catch (Exception e) {
            log.warn("查询用户收藏场站失败 uid={}", uid, e);
            return Collections.emptySet();
        }
    }
    
    @Override
    public List<XpPoint> listByStationId(Long stationId) {
        if (stationId == null) {
            return Collections.emptyList();
        }
        return this.lambdaQuery()
                .eq(XpPoint::getStationId, stationId)
                .list();
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void clearStationInfoByStationId(Long stationId) {
        if (stationId == null) {
            return;
        }
        this.lambdaUpdate()
                .eq(XpPoint::getStationId, stationId)
                .set(XpPoint::getStationId, null)
                .set(XpPoint::getStationSortNo, null)
                .update();
    }
 
    /**
     * 查询用户收藏的点位ID。
     * 子点位收藏态只用于回显,不影响场站筛选和排序主逻辑。
     */
    private Set<Long> getCollectPointIds(String uid) {
        if (!StringUtils.hasText(uid)) {
            return Collections.emptySet();
        }
        try {
            R<List<Long>> result = xpAppUserCollectAddrClient.getPointIdsByUserId(Long.valueOf(uid));
            if (result == null || CollUtil.isEmpty(result.getData())) {
                return Collections.emptySet();
            }
            return new HashSet<>(result.getData());
        } catch (Exception e) {
            log.warn("查询用户收藏点位失败 uid={}", uid, e);
            return Collections.emptySet();
        }
    }
 
 
 
    /**
     * 场站停用
     *     -  操作项展示为 [停用]。点击后弹出二次确认框,“当前场站包含12个点位,确认一起停用?
     *       - 是:确认后场站以及子点位状态流转至“已停用”。
     *       - 否:子点位维持当前状态,但自动退回为“独立点位”。
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void statusStopByStationId(Long stationId, Boolean pointStop) {
        if (stationId == null) {
            return;
        }
        if(pointStop){
            this.lambdaUpdate()
                    .eq(XpPoint::getStationId, stationId)
                    .set(XpPoint::getOperationStatus, 3)//运营状态 1=待启用 2=启用中 3=已停用 4=已失效
                    .update();
        }else{
            clearStationInfoByStationId(stationId);
        }
    }
 
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void statusEnableByStationId(Long stationId) {
        if (stationId == null) {
            return;
        }
        this.lambdaUpdate()
                .eq(XpPoint::getStationId, stationId)
                .set(XpPoint::getOperationStatus, 2)//运营状态 1=待启用 2=启用中 3=已停用 4=已失效
                .update();
    }
 
    /**
     * 场站删除
     *       - 删除拦截逻辑:
     *         - 测试阶段(待测试、测试中等):点击直接删除。
     *         - 历史运营阶段(已停用、失效):点击弹出二次确认框“当前场站包含12个点位,确认一起删除?”
     *           - 是:点位统一一起删除
     *           - 否:不自动删除点位,点位自动退回为[待测试]的“独立点位”,并自动继承父级运营区的运营时段
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void pointDeleteByStationId(Long stationId, Boolean pointDelete) {
        if (stationId == null) {
            return;
        }
        if(pointDelete){
            this.lambdaUpdate()
                    .eq(XpPoint::getStationId, stationId)
                    .set(XpPoint::getDeleted, 1)
                    .update();
        }else{
            clearStationInfoByStationId(stationId);
        }
    }
 
}