yyy
2026-04-22 43e9944347e51d5628166f8c1b78d98cfd2013ea
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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
package com.xiaopeng.map.service.serviceimpl;
 
 
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.ImmutableMap;
import com.xiaopeng.api.dto.operation.ElectronicFenceAddDto;
import com.xiaopeng.api.dto.operation.ElectronicFenceUpdateDto;
import com.xiaopeng.api.model.map.XpGeoFencingPolygon;
import com.xiaopeng.api.model.map.XpGeoFencingProhibitedPolygon;
import com.xiaopeng.api.model.operation.*;
import com.xiaopeng.api.query.operation.ElectronicPageListQuery;
import com.xiaopeng.common.core.domain.R;
import com.xiaopeng.common.core.exception.ServiceException;
import com.xiaopeng.common.core.utils.DateUtils;
import com.xiaopeng.common.core.utils.StringUtils;
import com.xiaopeng.common.core.utils.bean.BeanUtils;
import com.xiaopeng.common.core.web.page.PageInfo;
import com.xiaopeng.map.constant.I18nKeyConstant;
import com.xiaopeng.map.job.base.QuartzManager;
import com.xiaopeng.map.job.base.TimeJobType;
import com.xiaopeng.map.job.jobs.ElectronicEffectJob;
import com.xiaopeng.map.mangodb.service.XpGeoFencingPolygonService;
import com.xiaopeng.map.mapper.XpElectronicFenceAreaMapper;
import com.xiaopeng.map.mapper.XpElectronicFenceMapper;
import com.xiaopeng.map.mapper.XpPointMapper;
import com.xiaopeng.map.mapper.XpRegionMapper;
import com.xiaopeng.map.event.FenceChangedEvent;
import com.xiaopeng.map.service.XpElectronicFenceAreaService;
import com.xiaopeng.map.service.XpElectronicFenceService;
import com.xiaopeng.map.service.XpPointService;
import com.xiaopeng.map.utils.OperationStrategyIndex;
import com.xiaopeng.map.utils.GDMapGeocodingUtil;
import com.xiaopeng.map.utils.PolygonOverlapService;
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.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.Polygon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPolygon;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 电子围栏 服务实现类
 * </p>
 *
 * @author liu
 * @since 2026-02-03
 */
@Service
@Slf4j
public class XpElectronicFenceServiceImpl extends ServiceImpl<XpElectronicFenceMapper, XpElectronicFence> implements XpElectronicFenceService {
 
    @Resource
    private PolygonOverlapService polygonOverlapService;
    @Resource
    private XpElectronicFenceAreaMapper xpElectronicFenceAreaMapper;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private XpPointMapper xpPointMapper;
 
    @Autowired
    private XpPointService xpPointService;
 
    @Resource
    private XpGeoFencingPolygonService xpGeoFencingPolygonService;
 
    @Autowired
    private XpRegionMapper xpRegionMapper;
    @Autowired
    private GDMapGeocodingUtil gdMapGeocodingUtil;
    @Resource
    private XpElectronicFenceAreaService xpElectronicFenceAreaService;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
 
    @Override
    public PageInfo<XpElectronicFence> pageList(ElectronicPageListQuery query) {
        if (query == null) {
            return new PageInfo<>();
        }
        normalizeProhibitedAreaCountFilter(query);
        PageInfo<XpElectronicFence> pageInfo = new PageInfo<>(query.getPageNum(), query.getPageSize());
        List<XpElectronicFence> list = this.baseMapper.pageList(pageInfo, query);
        if (list.isEmpty()) {
            return new PageInfo<>();
        }
        List<Long> electronicIds = list.stream().map(XpElectronicFence::getId).collect(Collectors.toList());
        Map<Long, List<XpElectronicFenceArea>> electronicFenceAreaMap = xpElectronicFenceAreaMapper.selectList(new LambdaQueryWrapper<XpElectronicFenceArea>()
                        .in(XpElectronicFenceArea::getElectronicId, electronicIds)).stream()
                .collect(Collectors.groupingBy(XpElectronicFenceArea::getElectronicId));
        for (XpElectronicFence xpElectronicFence : list) {
            List<XpElectronicFenceArea> xpElectronicFenceAreas = electronicFenceAreaMap.get(xpElectronicFence.getId());
            if (xpElectronicFenceAreas != null) {
                xpElectronicFence.setOperatingAreaCount(xpElectronicFenceAreas.stream().filter(xpElectronicFenceArea -> xpElectronicFenceArea.getAreaType() == 1).count());
                xpElectronicFence.setProhibitedAreaCount(xpElectronicFenceAreas.stream().filter(xpElectronicFenceArea -> xpElectronicFenceArea.getAreaType() == 2).count());
            } else {
                xpElectronicFence.setOperatingAreaCount(0L);
                xpElectronicFence.setProhibitedAreaCount(0L);
            }
        }
        pageInfo.setRecords(list);
        return pageInfo;
    }
 
    private void normalizeProhibitedAreaCountFilter(ElectronicPageListQuery query) {
        Integer prohibitedAreaCountMin = query.getProhibitedAreaCountMin();
        Integer prohibitedAreaCountMax = query.getProhibitedAreaCountMax();
        if (prohibitedAreaCountMin != null || prohibitedAreaCountMax != null) {
            if (prohibitedAreaCountMin != null && prohibitedAreaCountMax != null) {
                int min = Math.min(prohibitedAreaCountMin, prohibitedAreaCountMax);
                int max = Math.max(prohibitedAreaCountMin, prohibitedAreaCountMax);
                if (min < 0) {
                    clearAreaFilter(query);
                    return;
                }
                query.setProhibitedAreaCountMin(min);
                query.setProhibitedAreaCountMax(max);
                query.setElectronicAreaId(null);
                return;
            }
            if (prohibitedAreaCountMin != null) {
                if (prohibitedAreaCountMin < 0) {
                    clearAreaFilter(query);
                    return;
                }
                query.setElectronicAreaId(null);
                return;
            }
            if (prohibitedAreaCountMax < 0) {
                clearAreaFilter(query);
                return;
            }
            query.setElectronicAreaId(null);
            return;
        }
 
        String electronicAreaId = query.getElectronicAreaId();
        if (StringUtils.isEmpty(electronicAreaId)) {
            return;
        }
        try {
            if (electronicAreaId.contains(",")) {
                String[] parts = electronicAreaId.split(",");
                if (parts.length != 2) {
                    clearAreaFilter(query);
                    return;
                }
                int left = Integer.parseInt(parts[0].trim());
                int right = Integer.parseInt(parts[1].trim());
                int min = Math.min(left, right);
                int max = Math.max(left, right);
                if (min < 0) {
                    clearAreaFilter(query);
                    return;
                }
                query.setProhibitedAreaCountMin(min);
                query.setProhibitedAreaCountMax(max);
                query.setElectronicAreaId(null);
                return;
            }
            int threshold = Integer.parseInt(electronicAreaId.trim());
            if (threshold < 0 || threshold == Integer.MAX_VALUE) {
                clearAreaFilter(query);
                return;
            }
            query.setProhibitedAreaCountMin(threshold + 1);
            query.setProhibitedAreaCountMax(null);
            query.setElectronicAreaId(null);
        } catch (Exception e) {
            clearAreaFilter(query);
        }
    }
 
    private void clearAreaFilter(ElectronicPageListQuery query) {
        query.setElectronicAreaId(null);
        query.setProhibitedAreaCountMin(null);
        query.setProhibitedAreaCountMax(null);
    }
 
    public 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();
    }
 
    @Override
    @Transactional
    @ShardingSphereTransactionType(TransactionType.BASE)
    public R addElectronic(ElectronicFenceAddDto dto) {
        validateElectronicNameUnique(dto.getElectronicName(), null);
        // 获取现有的运营区域(areaType=1)
        LambdaQueryWrapper<XpElectronicFenceArea> xpElectronicFenceAreaLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xpElectronicFenceAreaLambdaQueryWrapper.eq(XpElectronicFenceArea::getAreaType, 1);
        xpElectronicFenceAreaLambdaQueryWrapper.eq(XpElectronicFenceArea::getAreaStatus, 1);
        List<XpElectronicFenceArea> existingOperationAreas = xpElectronicFenceAreaMapper.selectList(xpElectronicFenceAreaLambdaQueryWrapper);
 
        // 获取待添加的新区域
        List<XpElectronicFenceArea> newElectronicFenceAreas = dto.getElectronicFenceAreas();
 
 
        // 检查新区域与现有运营区域是否有重叠
        for (XpElectronicFenceArea newArea : newElectronicFenceAreas) {
            //处理围栏闭合
            String[] split = newArea.getFencePoints().split(",");
            if (!split[0].equals(split[split.length - 1])) {
                newArea.setFencePoints(newArea.getFencePoints() + "," + split[0]);
            }
            if (newArea.getAreaType() == 1) { // 只检查运营区域
                for (XpElectronicFenceArea existingArea : existingOperationAreas) {
                    if (polygonOverlapService.checkPolygonOverlap(
                            newArea.getFencePoints(),
                            existingArea.getFencePoints())) {
                        throw new ServiceException(
                                "运营区域{}与现有运营区域{}发生重叠",
                                I18nKeyConstant.AREA_OVERLAP_ERROR,
                                new Object[]{existingArea.getAreaName(), existingArea.getAreaName()}
                        );
                    }
                }
            }
        }
 
        // 保存主表数据
        XpElectronicFence xpElectronicFence = new XpElectronicFence();
        BeanUtils.copyProperties(dto, xpElectronicFence);
        LocalDateTime now = LocalDateTime.now();
        int targetStatus = resolveFenceStatus(dto.getStatus(), dto.getEffectType(), dto.getEffectTime(), now);
        xpElectronicFence.setStatus(targetStatus);
        if (targetStatus == 2 && dto.getEffectType() != null && dto.getEffectType() == 1) {
            xpElectronicFence.setEffectTime(now);
        }
 
        //根据经纬度获取当前城市code
        XpElectronicFenceArea xpElectronicFenceArea = dto.getElectronicFenceAreas().get(0);
        String[] split = xpElectronicFenceArea.getFencePoints().split(",");
        Coordinate[] coordinates = new Coordinate[split.length + 1];
        for (int i = 0; i < split.length; i++) {
            String[] split1 = split[i].split("_");
            coordinates[i] = new Coordinate(Double.parseDouble(split1[0]), Double.parseDouble(split1[1]));
        }
        org.locationtech.jts.geom.Point point = calculateCentroid(coordinates);
        Map<String, String> geocode = gdMapGeocodingUtil.geocode(point.getX() + "", point.getY() + "");
        if (null == geocode) {
            return R.fail("经纬度转换城市code失败");
        }
        String cityCode = geocode.get("cityCode");
        dto.setCityCode(cityCode);
        xpElectronicFence.setCityCode(dto.getCityCode());
        // 生成围栏id 规则:城市首字母-类型简写-4位自增流水号(如 SZ-OP-001),支持复制;数据停用或删除后,流水号不回收
        XpRegion xpRegion = xpRegionMapper.selectOne(new LambdaQueryWrapper<XpRegion>()
                .eq(XpRegion::getCode, dto.getCityCode()));
        String name = xpRegion.getName();
        this.save(xpElectronicFence);
        // 根据城市中文名,截取前两位的首字母并且大写
        // 截取前两个字符
        String prefix = name.substring(0, 2);
        // 获取拼音首字母并大写
        String result = getPinyinInitials(prefix).toUpperCase();
        xpElectronicFence.setElectronicNumber(result + "-OP-" + String.format("%04d", xpElectronicFence.getId()));
        if (dto.getStatus() == 1) {
            registerEffectJobIfNeeded(xpElectronicFence.getId(), targetStatus, dto.getEffectType(), dto.getEffectTime(), now);
            registerFailureJobIfNeeded(xpElectronicFence.getId(), dto.getFailureType(), dto.getFailureTime(), now);
        }
        this.updateById(xpElectronicFence);
        if (xpElectronicFence.getStatus() == 2) {
            // 设置电子围栏ID并保存区域数据
            for (XpElectronicFenceArea area : newElectronicFenceAreas) {
                area.setElectronicId(xpElectronicFence.getId());
                area.setAreaStatus(1);
                area.setArea(area.getArea());
                area.setCityCode(dto.getCityCode());
                xpElectronicFenceAreaMapper.insert(area);
            }
 
        } else {
            // 设置电子围栏ID并保存区域数据
            for (XpElectronicFenceArea area : newElectronicFenceAreas) {
                area.setElectronicId(xpElectronicFence.getId());
                area.setAreaStatus(2);
                area.setArea(area.getArea());
                area.setCityCode(dto.getCityCode());
                xpElectronicFenceAreaMapper.insert(area);
 
            }
        }
 
        if (xpElectronicFence.getStatus() == 1 || xpElectronicFence.getStatus() == 2) {
            for (XpElectronicFenceArea newElectronicFenceArea : newElectronicFenceAreas) {
                if (newElectronicFenceArea.getAreaType() == 1
                        && newElectronicFenceArea.getAreaStatus() == 1) {
                    XpGeoFencingPolygon xpGeoFencingPolygon = new XpGeoFencingPolygon();
                    xpGeoFencingPolygon.setFenceId(String.valueOf(xpElectronicFence.getId()));
                    xpGeoFencingPolygon.setName(xpElectronicFence.getElectronicName());
                    xpGeoFencingPolygon.setAreaId(String.valueOf(newElectronicFenceArea.getId()));
                    xpGeoFencingPolygon.setCityCode(xpElectronicFence.getCityCode());
                    xpGeoFencingPolygon.setOperationStrategy(xpElectronicFence.getOperationStrategy());
                    // 将围栏点转换为GeoJSON多边形
                    GeoJsonPolygon geoJsonPolygon = convertToGeoJsonPolygon(newElectronicFenceArea.getFencePoints());
                    xpGeoFencingPolygon.setPoints(geoJsonPolygon);
                    mongoTemplate.insert(xpGeoFencingPolygon);
                }
                if (newElectronicFenceArea.getAreaType() == 2
                        && newElectronicFenceArea.getAreaStatus() == 1) {
                    XpGeoFencingProhibitedPolygon xpGeoFencingProhibitedPolygon = new XpGeoFencingProhibitedPolygon();
                    xpGeoFencingProhibitedPolygon.setFenceId(String.valueOf(xpElectronicFence.getId()));
                    xpGeoFencingProhibitedPolygon.setName(xpElectronicFence.getElectronicName());
                    xpGeoFencingProhibitedPolygon.setAreaId(String.valueOf(newElectronicFenceArea.getId()));
                    // 将围栏点转换为GeoJSON多边形
                    GeoJsonPolygon geoJsonPolygon = convertToGeoJsonPolygon(newElectronicFenceArea.getFencePoints());
                    xpGeoFencingProhibitedPolygon.setPoints(geoJsonPolygon);
                    mongoTemplate.save(xpGeoFencingProhibitedPolygon);
                }
            }
        }
 
        return R.ok();
    }
 
    @Override
    @Transactional
    @ShardingSphereTransactionType(TransactionType.BASE)
    public R editElectronic(ElectronicFenceUpdateDto dto) {
        validateElectronicNameUnique(dto.getElectronicName(), dto.getId());
        // 获取现有的运营区域(areaType=1),排除当前正在编辑的电子围栏
        LambdaQueryWrapper<XpElectronicFenceArea> xpElectronicFenceAreaLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xpElectronicFenceAreaLambdaQueryWrapper.eq(XpElectronicFenceArea::getAreaType, 1);
        xpElectronicFenceAreaLambdaQueryWrapper.eq(XpElectronicFenceArea::getAreaStatus, 1);
        xpElectronicFenceAreaLambdaQueryWrapper.ne(XpElectronicFenceArea::getElectronicId, dto.getId());
        List<XpElectronicFenceArea> existingOperationAreas = xpElectronicFenceAreaMapper.selectList(xpElectronicFenceAreaLambdaQueryWrapper);
 
        // 获取待更新的区域
        List<XpElectronicFenceArea> updatedElectronicFenceAreas = dto.getElectronicFenceAreas();
 
        // 检查更新后的区域与现有运营区域是否有重叠
        for (XpElectronicFenceArea updatedArea : updatedElectronicFenceAreas) {
            //处理围栏闭合
            String[] split = updatedArea.getFencePoints().split(",");
            if (!split[0].equals(split[split.length - 1])) {
                updatedArea.setFencePoints(updatedArea.getFencePoints() + "," + split[0]);
            }
            if (updatedArea.getAreaType() == 1) { // 只检查运营区域
                for (XpElectronicFenceArea existingArea : existingOperationAreas) {
                    if (polygonOverlapService.checkPolygonOverlap(
                            updatedArea.getFencePoints(),
                            existingArea.getFencePoints())) {
                        List<String> res = new ArrayList<>();
                        res.add(updatedArea.getAreaName());
                        res.add(existingArea.getAreaName());
                        throw new ServiceException(
                                "运营区域{}与现有运营区域{}发生重叠,请编辑已有的运营区域",
                                I18nKeyConstant.AREA_OVERLAP_ERROR,
                                res.toArray()
                        );
                    }
                }
            }
        }
 
        XpElectronicFence electronicFence = this.getById(dto.getId());
        Integer status = electronicFence.getStatus();
        String oldOperationStrategy = electronicFence.getOperationStrategy();
        String newOperationStrategy = dto.getOperationStrategy();
 
 
        // 更新主表数据
        XpElectronicFence xpElectronicFence = new XpElectronicFence();
        BeanUtils.copyProperties(dto, xpElectronicFence);
        LocalDateTime now = LocalDateTime.now();
        int targetStatus = resolveFenceStatus(dto.getStatus(), dto.getEffectType(), dto.getEffectTime(), now);
        xpElectronicFence.setStatus(targetStatus);
        if (targetStatus == 2 && dto.getEffectType() != null && dto.getEffectType() == 1) {
            xpElectronicFence.setEffectTime(now);
        }
        if (dto.getStatus() == 1 || dto.getStatus() == 2) {
            registerEffectJobIfNeeded(xpElectronicFence.getId(), targetStatus, dto.getEffectType(), dto.getEffectTime(), now);
            registerFailureJobIfNeeded(xpElectronicFence.getId(), dto.getFailureType(), dto.getFailureTime(), now);
        } else {
            QuartzManager.removeJob((ElectronicEffectJob.effect + xpElectronicFence.getId()).toUpperCase(), TimeJobType.ELECTRONIC_EFFECT);
            QuartzManager.removeJob((ElectronicEffectJob.failure + xpElectronicFence.getId()).toUpperCase(), TimeJobType.ELECTRONIC_FAILURE);
        }
        //根据经纬度获取当前城市code
        XpElectronicFenceArea electronicFenceArea = dto.getElectronicFenceAreas().get(0);
        String[] split = electronicFenceArea.getFencePoints().split(",");
        Coordinate[] coordinates = new Coordinate[split.length];
        for (int i = 0; i < split.length; i++) {
            String[] split1 = split[i].split("_");
            coordinates[i] = new Coordinate(Double.parseDouble(split1[0]), Double.parseDouble(split1[1]));
        }
        org.locationtech.jts.geom.Point point = calculateCentroid(coordinates);
        Map<String, String> geocode = gdMapGeocodingUtil.geocode(point.getX() + "", point.getY() + "");
        if (null == geocode) {
            return R.fail("经纬度转换城市code失败");
        }
        String cityCode = geocode.get("cityCode");
        dto.setCityCode(cityCode);
        xpElectronicFence.setCityCode(dto.getCityCode());
 
        this.updateById(xpElectronicFence);
 
        // 禁行区(areaType=2)差异删除:对比原有禁行区与本次编辑入参禁行区(按id)
        List<XpElectronicFenceArea> existingProhibitedAreas = xpElectronicFenceAreaService.lambdaQuery()
                .eq(XpElectronicFenceArea::getElectronicId, dto.getId())
                .eq(XpElectronicFenceArea::getAreaType, 2)
                .list();
        Set<Long> incomingProhibitedIds = updatedElectronicFenceAreas.stream()
                .filter(a -> a != null && a.getAreaType() != null && a.getAreaType() == 2 && a.getId() != null)
                .map(XpElectronicFenceArea::getId)
                .collect(Collectors.toSet());
        List<Long> toDeleteProhibitedIds = existingProhibitedAreas.stream()
                .map(XpElectronicFenceArea::getId)
                .filter(id -> id != null && !incomingProhibitedIds.contains(id))
                .collect(Collectors.toList());
        if (!toDeleteProhibitedIds.isEmpty()) {
            // 逻辑删除MySQL禁行区
            xpElectronicFenceAreaService.removeByIds(toDeleteProhibitedIds);
            // 同步删除Mongo禁行区多边形
            List<String> toDeleteAreaIdStrings = toDeleteProhibitedIds.stream().map(String::valueOf).collect(Collectors.toList());
            Query delMongoQuery = new Query();
            delMongoQuery.addCriteria(Criteria.where("fenceId").is(String.valueOf(dto.getId())));
            delMongoQuery.addCriteria(Criteria.where("areaId").in(toDeleteAreaIdStrings));
            mongoTemplate.remove(delMongoQuery, XpGeoFencingProhibitedPolygon.class);
        }
        // 删除旧的区域数据,然后保存新的区域数据
        mongoTemplate.remove(new Query(Criteria.where("fenceId").is(String.valueOf(dto.getId()))), XpGeoFencingPolygon.class);
        if (xpElectronicFence.getStatus() == 2) {
            // 设置电子围栏ID并保存区域数据
            for (XpElectronicFenceArea area : updatedElectronicFenceAreas) {
                area.setElectronicId(xpElectronicFence.getId());
                if (area.getAreaType() == null || area.getAreaType() == 1) {
                    area.setAreaStatus(1);
                }
                area.setArea(area.getArea());
                area.setCityCode(dto.getCityCode());
                if (null != area.getId()) {
                    xpElectronicFenceAreaService.updateById(area);
                } else {
                    xpElectronicFenceAreaService.save(area);
                }
            }
        } else {
            // 设置电子围栏ID并保存区域数据
            for (XpElectronicFenceArea area : updatedElectronicFenceAreas) {
                area.setElectronicId(xpElectronicFence.getId());
                if (area.getAreaType() == null || area.getAreaType() == 1) {
                    area.setAreaStatus(2);
                }
                area.setArea(area.getArea());
                area.setCityCode(dto.getCityCode());
                if (null != area.getId()) {
                    xpElectronicFenceAreaService.updateById(area);
                } else {
                    xpElectronicFenceAreaService.save(area);
                }
            }
        }
        if (dto.getStatus() == 1 || dto.getStatus() == 2) {
            for (XpElectronicFenceArea newElectronicFenceArea : updatedElectronicFenceAreas) {
                if (newElectronicFenceArea.getAreaType() == 1
                        && newElectronicFenceArea.getAreaStatus() == 1) {
                    // 先查询出mongo里围栏相同的数据 如果有 那么更新数据
                    Query query = new Query();
                    query.addCriteria(Criteria.where("fenceId").is(String.valueOf(xpElectronicFence.getId())));
                    query.addCriteria(Criteria.where("areaId").is(String.valueOf(newElectronicFenceArea.getId())));
                    XpGeoFencingPolygon old = mongoTemplate.findOne(query, XpGeoFencingPolygon.class);
                    if (old == null) {
                        XpGeoFencingPolygon xpGeoFencingPolygon = new XpGeoFencingPolygon();
                        xpGeoFencingPolygon.setFenceId(String.valueOf(xpElectronicFence.getId()));
                        xpGeoFencingPolygon.setName(xpElectronicFence.getElectronicName());
                        xpGeoFencingPolygon.setCityCode(cityCode);
                        xpGeoFencingPolygon.setAreaId(String.valueOf(newElectronicFenceArea.getId()));
                        xpGeoFencingPolygon.setOperationStrategy(xpElectronicFence.getOperationStrategy());
                        // 将围栏点转换为GeoJSON多边形
                        GeoJsonPolygon geoJsonPolygon = convertToGeoJsonPolygon(newElectronicFenceArea.getFencePoints());
                        xpGeoFencingPolygon.setPoints(geoJsonPolygon);
                        mongoTemplate.save(xpGeoFencingPolygon);
                    } else {
                        // 如果存在,则更新已有文档
                        old.setFenceId(String.valueOf(xpElectronicFence.getId()));
                        old.setName(xpElectronicFence.getElectronicName());
                        old.setCityCode(cityCode);
                        old.setAreaId(String.valueOf(newElectronicFenceArea.getId()));
                        old.setOperationStrategy(xpElectronicFence.getOperationStrategy());
                        // 将围栏点转换为GeoJSON多边形
                        GeoJsonPolygon geoJsonPolygon = convertToGeoJsonPolygon(newElectronicFenceArea.getFencePoints());
                        old.setPoints(geoJsonPolygon);
                        // 执行更新操作
                        mongoTemplate.save(old); // save() 会根据 _id 自动判断是插入还是更新
                    }
 
                }
                if (newElectronicFenceArea.getAreaType() == 2
                        && newElectronicFenceArea.getAreaStatus() == 1) {
                    // 先查询出mongo里围栏相同的数据 如果有 那么更新数据
                    Query query = new Query();
                    query.addCriteria(Criteria.where("fenceId").is(String.valueOf(xpElectronicFence.getId())));
                    query.addCriteria(Criteria.where("areaId").is(String.valueOf(newElectronicFenceArea.getId())));
                    XpGeoFencingProhibitedPolygon old = mongoTemplate.findOne(query, XpGeoFencingProhibitedPolygon.class);
                    if (old == null) {
                        XpGeoFencingProhibitedPolygon xpGeoFencingProhibitedPolygon = new XpGeoFencingProhibitedPolygon();
                        xpGeoFencingProhibitedPolygon.setFenceId(String.valueOf(xpElectronicFence.getId()));
                        xpGeoFencingProhibitedPolygon.setName(xpElectronicFence.getElectronicName());
                        xpGeoFencingProhibitedPolygon.setAreaId(String.valueOf(newElectronicFenceArea.getId()));
                        // 将围栏点转换为GeoJSON多边形
                        GeoJsonPolygon geoJsonPolygon = convertToGeoJsonPolygon(newElectronicFenceArea.getFencePoints());
                        xpGeoFencingProhibitedPolygon.setPoints(geoJsonPolygon);
                        mongoTemplate.save(xpGeoFencingProhibitedPolygon);
                    } else {
                        old.setFenceId(String.valueOf(xpElectronicFence.getId()));
                        old.setName(xpElectronicFence.getElectronicName());
                        old.setAreaId(String.valueOf(newElectronicFenceArea.getId()));
                        // 将围栏点转换为GeoJSON多边形
                        GeoJsonPolygon geoJsonPolygon = convertToGeoJsonPolygon(newElectronicFenceArea.getFencePoints());
                        old.setPoints(geoJsonPolygon);
                        mongoTemplate.save(old);
                    }
                } else if (newElectronicFenceArea.getAreaType() == 2
                        && newElectronicFenceArea.getId() != null) {
                    Query query = new Query();
                    query.addCriteria(Criteria.where("fenceId").is(String.valueOf(xpElectronicFence.getId())));
                    query.addCriteria(Criteria.where("areaId").is(String.valueOf(newElectronicFenceArea.getId())));
                    mongoTemplate.remove(query, XpGeoFencingProhibitedPolygon.class);
                }
            }
        }
        // 判断区域下的所有运营点位是否处于运营区域内 如果不是则更新为测试点位
        List<Long> areaIds = updatedElectronicFenceAreas.stream().map(XpElectronicFenceArea::getId).collect(Collectors.toList());
        LambdaQueryWrapper<XpPoint> pointLambdaQueryWrapper = new LambdaQueryWrapper<>();
        pointLambdaQueryWrapper.in(XpPoint::getElectronicAreaId, areaIds).eq(XpPoint::getPointType, 1);
        List<XpPoint> xpPoints = xpPointMapper.selectList(pointLambdaQueryWrapper);
        if (!xpPoints.isEmpty()) {
            List<Long> electronicAreaId = xpPoints.stream().map(XpPoint::getElectronicAreaId).distinct().collect(Collectors.toList());
            if (!electronicAreaId.isEmpty()) {
                Map<Long, XpElectronicFenceArea> longXpElectronicFenceAreaMap = updatedElectronicFenceAreas
                        .stream().collect(Collectors.toMap(XpElectronicFenceArea::getId, e -> e));
                for (XpPoint xpPoint : xpPoints) {
                    XpElectronicFenceArea xpElectronicFenceArea = longXpElectronicFenceAreaMap.get(xpPoint.getElectronicAreaId());
 
                    if (xpElectronicFenceArea != null) {
                        String fencePoints = xpElectronicFenceArea.getFencePoints();
                        Double pointLat = xpPoint.getPointLat();
                        Double pointLon = xpPoint.getPointLon();
                        // 判断这个点位有没有处于当前区域 由多个经纬度点构成的面里
                        if (fencePoints != null && !fencePoints.trim().isEmpty() &&
                                pointLat != null && pointLon != null) {
                            boolean isInside = isPointInPolygon(fencePoints, pointLon, pointLat);
                            // 如果点不在区域内,更新为测试点位
                            if (!isInside) {
                                xpPoint.setPointType(2); //
                                log.info("点位ID: {} 经纬度: ({}, {}) 不在电子围栏区域内,已更新为测试点位",
                                        xpPoint.getId(), pointLon, pointLat);
                                UpdateWrapper<XpPoint> xpPointUpdateWrapper = new UpdateWrapper<>();
                                xpPointUpdateWrapper.eq("id", xpPoint.getId());
                                xpPointUpdateWrapper.set("point_type", 2);
                                xpPointMapper.update(xpPoint, xpPointUpdateWrapper);
                            }
                        }
                    }
                }
            }
        }
        // 围栏从已停用(3)改为启用中(2)时:同步启用点位需校验点位在运营区内且不在禁行区内
        Integer newFenceStatus = xpElectronicFence.getStatus();
        if (status != null && status == 3 && newFenceStatus != null && newFenceStatus == 2) {
            XpElectronicFenceArea operationAreaToEnable = xpElectronicFenceAreaService.lambdaQuery()
                    .eq(XpElectronicFenceArea::getElectronicId, dto.getId())
                    .eq(XpElectronicFenceArea::getAreaType, 1)
                    .orderByDesc(XpElectronicFenceArea::getId)
                    .last("limit 1")
                    .one();
            if (operationAreaToEnable == null || operationAreaToEnable.getId() == null) {
                log.warn("围栏启用同步启用点位跳过:未查询到运营区 fenceId={}", dto.getId());
            } else {
                Long operationAreaIdToEnable = operationAreaToEnable.getId();
                LambdaQueryWrapper<XpPoint> pendingEnableQuery = new LambdaQueryWrapper<>();
                pendingEnableQuery.eq(XpPoint::getElectronicAreaId, operationAreaIdToEnable)
                        .eq(XpPoint::getPointType, 1)
                        .eq(XpPoint::getOperationStatus, 3);
                List<XpPoint> pendingEnablePoints = xpPointMapper.selectList(pendingEnableQuery);
                int pendingCount = pendingEnablePoints == null ? 0 : pendingEnablePoints.size();
                if (pendingCount == 0) {
                    log.info("围栏启用同步启用点位:无待启用点位 fenceId={}, operationAreaId={}", dto.getId(), operationAreaIdToEnable);
                } else {
                    String fenceId = String.valueOf(dto.getId());
                    List<Long> enableIds = new ArrayList<>();
                    for (XpPoint pointItem : pendingEnablePoints) {
                        if (pointItem == null || pointItem.getId() == null) {
                            continue;
                        }
                        Double lon = pointItem.getPointLon();
                        Double lat = pointItem.getPointLat();
                        if (lon == null || lat == null) {
                            continue;
                        }
                        try {
                            boolean inOperatingArea = xpGeoFencingPolygonService.isInFence(lon, lat, fenceId, "operating_area");
                            if (!inOperatingArea) {
                                continue;
                            }
                            boolean inProhibitedArea = xpGeoFencingPolygonService.isInFence(lon, lat, fenceId, "prohibited_area");
                            if (inProhibitedArea) {
                                continue;
                            }
                        } catch (Exception e) {
                            log.error("围栏启用同步启用点位校验失败 fenceId={}, pointId={}", dto.getId(), pointItem.getId(), e);
                            throw new ServiceException("系统异常", I18nKeyConstant.SYSTEM_EXCEPTION);
                        }
                        enableIds.add(pointItem.getId());
                    }
                    if (CollUtil.isNotEmpty(enableIds)) {
                        xpPointService.lambdaUpdate()
                                .in(XpPoint::getId, enableIds)
                                .eq(XpPoint::getOperationStatus, 3)
                                .set(XpPoint::getOperationStatus, 2)
                                .update();
                    }
                    log.info("围栏启用同步启用点位完成 fenceId={}, pendingCount={}, enableCount={}, skipCount={}",
                            dto.getId(), pendingCount, enableIds.size(), Math.max(0, pendingCount - enableIds.size()));
                }
            }
        }
 
        // 围栏改为已停用(3)时:将围栏下启用中点位(operation_status=2)更新为已停用(operation_status=3)
        if (newFenceStatus != null && newFenceStatus == 3) {
            XpElectronicFenceArea operationAreaToDisable = xpElectronicFenceAreaService.lambdaQuery()
                    .eq(XpElectronicFenceArea::getElectronicId, dto.getId())
                    .eq(XpElectronicFenceArea::getAreaType, 1)
                    .orderByDesc(XpElectronicFenceArea::getId)
                    .last("limit 1")
                    .one();
            if (operationAreaToDisable == null || operationAreaToDisable.getId() == null) {
                log.warn("围栏停用同步停用点位跳过:未查询到运营区 fenceId={}", dto.getId());
            } else {
                Long operationAreaIdToDisable = operationAreaToDisable.getId();
                boolean updated = xpPointService.lambdaUpdate()
                        .eq(XpPoint::getElectronicAreaId, operationAreaIdToDisable)
                        .eq(XpPoint::getPointType, 1)
                        .eq(XpPoint::getOperationStatus, 2)
                        .set(XpPoint::getOperationStatus, 3)
                        .update();
                log.info("围栏停用同步停用点位完成 fenceId={}, operationAreaId={}, updated={}",
                        dto.getId(), operationAreaIdToDisable, updated);
            }
        }
 
        OperationStrategyIndex oldIndex = OperationStrategyIndex.parse(oldOperationStrategy);
        OperationStrategyIndex newIndex = OperationStrategyIndex.parse(newOperationStrategy);
        boolean needAutoDisableByUnion = !oldIndex.equalsNormalized(newIndex);
        List<Long> addPointIds = normalizePointIds(dto.getAddPointIdList());
        List<Long> delPointIds = normalizePointIds(dto.getDelPointIdList());
        List<Long> disablePointIds = normalizePointIds(dto.getDisablePointIdList());
        boolean needPointHandling = CollUtil.isNotEmpty(addPointIds)
                || CollUtil.isNotEmpty(delPointIds)
                || CollUtil.isNotEmpty(disablePointIds);
        boolean needFenceAreaIds = needPointHandling || needAutoDisableByUnion;
        XpElectronicFenceArea operationArea =  xpElectronicFenceAreaService.lambdaQuery()
                .eq(XpElectronicFenceArea::getElectronicId, dto.getId())
                .eq(XpElectronicFenceArea::getAreaType, 1)
                .orderByDesc(XpElectronicFenceArea::getId)
                .last("limit 1")
                .one();
        Long operationAreaId = operationArea == null ? null : operationArea.getId();
        if (needPointHandling && operationAreaId == null) {
            throw new ServiceException("运营区域不存在", I18nKeyConstant.POINT_ELECTRONIC_AREA_NOT_EXIST);
        }
 
        if (CollUtil.isNotEmpty(addPointIds)) {
            if (operationAreaId == null) {
                throw new ServiceException("运营区域不存在", I18nKeyConstant.POINT_ELECTRONIC_AREA_NOT_EXIST);
            }
            xpPointService.lambdaUpdate()
                    .in(XpPoint::getId, addPointIds)
                    .set(XpPoint::getElectronicAreaId, operationAreaId)
                    .set(XpPoint::getVerificationStatus, 1)
                    .update();
        }
 
        if (CollUtil.isNotEmpty(disablePointIds)) {
            // operation_status: 3=已停用
            xpPointService.lambdaUpdate()
                    .in(XpPoint::getId, disablePointIds)
                    .eq(XpPoint::getElectronicAreaId, operationAreaId)
                    .set(XpPoint::getOperationStatus, 3)
                    .update();
        }
 
        if (CollUtil.isNotEmpty(delPointIds)) {
            // operation_status: 4=已失效
            xpPointService.lambdaUpdate()
                    .in(XpPoint::getId, delPointIds)
                    .eq(XpPoint::getElectronicAreaId, operationAreaId)
                    .set(XpPoint::getOperationStatus, 4)
                    .update();
        }
 
        // 围栏运营时间缩短校验:若缩短后点位时间段不在新范围内,则更新为已停用(operation_status=3)
        if (true) {
            LambdaQueryWrapper<XpPoint> pointQuery = new LambdaQueryWrapper<>();
            pointQuery.eq(XpPoint::getElectronicAreaId, operationAreaId)
                    .eq(XpPoint::getPointType, 1)
                    .eq(XpPoint::getOperationType, 2);
            List<XpPoint> points = xpPointMapper.selectList(pointQuery);
            if (points != null && !points.isEmpty()) {
                List<Long> disablePointIdList = new ArrayList<>();
                for (XpPoint pointItem : points) {
                    if (pointItem == null) {
                        continue;
                    }
                    if (pointItem.getOperationStatus() != null && pointItem.getOperationStatus() == 4) {
                        continue;
                    }
                    String effectiveTimePeriod = pointItem.getEffectiveTimePeriod();
                    if (effectiveTimePeriod == null || effectiveTimePeriod.isEmpty()) {
                        continue;
                    }
                    List<OperationStrategyIndex.TimeInterval> pointIntervals = OperationStrategyIndex.parsePointEffectiveTimePeriod(effectiveTimePeriod);
                    if (pointIntervals.isEmpty()) {
                        continue;
                    }
                    boolean shouldDisable = !newIndex.isPointScheduleWithin(pointIntervals);
                    if (shouldDisable && pointItem.getId() != null) {
                        disablePointIdList.add(pointItem.getId());
                    }
                }
                if (!disablePointIdList.isEmpty()) {
                    for (Long l : disablePointIdList) {
                        XpPoint xpPoint = xpPointMapper.selectById(l);
                        if(xpPoint.getOperationStatus()!=4){
                            xpPoint.setOperationStatus(3);
                            xpPoint.setVerificationStatus(5);
                            xpPointMapper.updateById(xpPoint);
                        }
 
                    }
                }
            }
        }
        // 发布围栏变更事件,事务提交后异步触发 ADC 推送
        applicationEventPublisher.publishEvent(
                new FenceChangedEvent(this, xpElectronicFence.getId(), xpElectronicFence.getStatus()));
        return R.ok();
 
    }
 
    @Override
    public void validateElectronicNameUnique(String electronicName, Long excludeId) {
        if (!StringUtils.hasText(electronicName)) {
            return;
        }
        long count = this.lambdaQuery()
                .eq(XpElectronicFence::getElectronicName, electronicName)
                .ne(excludeId != null, XpElectronicFence::getId, excludeId)
                .count();
        if (count > 0) {
            throw new ServiceException("围栏名称已存在", I18nKeyConstant.FENCE_NAME_EXISTS);
        }
    }
 
    private static List<Long> normalizePointIds(List<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return ids.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
    }
 
    private int resolveFenceStatus(Integer requestedStatus, Integer effectType, LocalDateTime effectTime, LocalDateTime now) {
        if (requestedStatus == null) {
            return 0;
        }
        if (requestedStatus == 0) {
            return 0;
        }
        if (requestedStatus == 3) {
            return 3;
        }
        if (effectType != null && effectType == 1) {
            return 2;
        }
        if (effectTime != null && !effectTime.isAfter(now)) {
            return 2;
        }
        return 1;
    }
 
    private void registerEffectJobIfNeeded(Long electronicId, Integer targetStatus, Integer effectType,
                                           LocalDateTime effectTime, LocalDateTime now) {
        QuartzManager.removeJob((ElectronicEffectJob.effect + electronicId).toUpperCase(), TimeJobType.ELECTRONIC_EFFECT);
        if (targetStatus != 1 || effectType == null || effectType == 1 || effectTime == null || !effectTime.isAfter(now)) {
            return;
        }
        Map<String, ? extends Object> effectMaps =
                new ImmutableMap.Builder<String, Long>()
                        .put("type", 1L)
                        .put("id", electronicId)
                        .build();
        QuartzManager.addJob(
                ElectronicEffectJob.class,
                (ElectronicEffectJob.effect + electronicId).toUpperCase(),
                TimeJobType.ELECTRONIC_EFFECT,
                DateUtils.localDateTimeToDate(effectTime),
                effectMaps
        );
    }
 
    /**
     * 失效
     * @param electronicId
     * @param failureType
     * @param failureTime
     * @param now
     */
    private void registerFailureJobIfNeeded(Long electronicId, Integer failureType, LocalDateTime failureTime, LocalDateTime now) {
        QuartzManager.removeJob((ElectronicEffectJob.failure + electronicId).toUpperCase(), TimeJobType.ELECTRONIC_FAILURE);
        if (failureType == null || failureType != 2 || failureTime == null || failureTime.isBefore(now)) {
            return;
        }
        Map<String, ? extends Object> failureMaps =
                new ImmutableMap.Builder<String, Long>()
                        .put("type", 2L)
                        .put("id", electronicId)
                        .build();
        QuartzManager.addJob(
                ElectronicEffectJob.class,
                (ElectronicEffectJob.failure + electronicId).toUpperCase(),
                TimeJobType.ELECTRONIC_FAILURE,
                DateUtils.localDateTimeToDate(failureTime),
                failureMaps
        );
    }
 
    /**
     * 判断点是否在多边形内
     *
     * @param fencePointsStr 多边形顶点字符串,格式:经度_维度,经度_维度
     * @param pointLon       待检测点的经度
     * @param pointLat       待检测点的纬度
     * @return true表示在多边形内,false表示在多边形外
     */
    private boolean isPointInPolygon(String fencePointsStr, double pointLon, double pointLat) {
        if (fencePointsStr == null || fencePointsStr.trim().isEmpty()) {
            return false;
        }
 
        // 解析多边形顶点
        String[] pointPairs = fencePointsStr.split(",");
        List<double[]> polygonVertices = new ArrayList<>();
 
        for (String pointPair : pointPairs) {
            String[] lngLat = pointPair.trim().split("_");
            if (lngLat.length >= 2) {
                try {
                    double longitude = Double.parseDouble(lngLat[0]);
                    double latitude = Double.parseDouble(lngLat[1]);
                    polygonVertices.add(new double[]{longitude, latitude});
                } catch (NumberFormatException e) {
                    log.error("解析多边形顶点坐标失败: {}", pointPair, e);
                    return false;
                }
            }
        }
 
        if (polygonVertices.size() < 3) {
            return false; // 至少需要3个点才能构成多边形
        }
 
        return isPointInPolygon(polygonVertices, pointLon, pointLat);
    }
 
    /**
     * 使用射线法判断点是否在多边形内
     *
     * @param polygonVertices 多边形顶点列表
     * @param pointLon        待检测点的经度
     * @param pointLat        待检测点的纬度
     * @return true表示在多边形内,false表示在多边形外
     */
    private boolean isPointInPolygon(List<double[]> polygonVertices, double pointLon, double pointLat) {
        int n = polygonVertices.size();
        boolean inside = false;
 
        // 射线法判断点是否在多边形内
        double x = pointLon, y = pointLat;
 
        for (int i = 0, j = n - 1; i < n; j = i++) {
            double xi = polygonVertices.get(i)[0], yi = polygonVertices.get(i)[1];
            double xj = polygonVertices.get(j)[0], yj = polygonVertices.get(j)[1];
 
            // 判断当前边是否与水平射线相交
            boolean intersect = ((yi > y) != (yj > y)) &&
                    (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
 
            if (intersect) {
                inside = !inside;
            }
        }
 
        return inside;
    }
 
    /**
     * 将围栏点字符串转换为GeoJsonPolygon
     * 格式:经度_维度,经度_维度
     */
    @Override
    public GeoJsonPolygon convertToGeoJsonPolygon(String fencePointsStr) {
        if (fencePointsStr == null || fencePointsStr.trim().isEmpty()) {
            return null;
        }
 
        // 分割多个点对
        String[] pointPairs = fencePointsStr.split(",");
        List<Point> points = new ArrayList<>();
 
        for (String pointPair : pointPairs) {
            String[] lngLat = pointPair.trim().split("_");
            if (lngLat.length >= 2) {
                try {
                    double longitude = Double.parseDouble(lngLat[0]);
                    double latitude = Double.parseDouble(lngLat[1]);
                    points.add(new Point(longitude, latitude)); // Point 构造函数是 (x, y) -> (longitude, latitude)
                } catch (NumberFormatException e) {
                    log.error("解析经纬度坐标失败: {}", pointPair, e);
                    throw new IllegalArgumentException("经纬度格式错误: " + pointPair);
                }
            }
        }
 
        // 如果没有足够的点构成多边形,至少需要3个点
        if (points.size() < 3) {
            throw new IllegalArgumentException("围栏点数量不足,至少需要3个点构成多边形");
        }
 
        // 确保多边形是闭合的(如果最后一个点不等于第一个点,则添加第一个点)
        if (!points.get(0).equals(points.get(points.size() - 1))) {
            points.add(points.get(0)); // 添加第一个点作为最后一个点,闭合多边形
        }
 
        return new GeoJsonPolygon(points);
    }
 
    /**
     * 检查新添加的区域之间是否有重叠
     */
    private boolean hasOverlapWithinNewAreas(List<XpElectronicFenceArea> newAreas) {
        for (int i = 0; i < newAreas.size(); i++) {
            XpElectronicFenceArea area1 = newAreas.get(i);
            if (area1.getAreaType() != 1) continue; // 只检查运营区域
 
            for (int j = i + 1; j < newAreas.size(); j++) {
                XpElectronicFenceArea area2 = newAreas.get(j);
                if (area2.getAreaType() == 1) {
                    if (polygonOverlapService.checkPolygonOverlap(
                            area1.getFencePoints(),
                            area2.getFencePoints())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
 
    /**
     * @return
     */
    @Override
    public List<XpElectronicFence> getAvailableList() {
        return lambdaQuery().eq(XpElectronicFence::getStatus, 2).list(); //查询已启用的围栏
    }
 
    @Override
    public List<XpElectronicFence> getList(ElectronicPageListQuery query) {
        LambdaQueryWrapper<XpElectronicFence>   queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(query.getCityCode() != null, XpElectronicFence::getCityCode, query.getCityCode());
        return list(queryWrapper);
    }
 
    @Override
    @Transactional
    @ShardingSphereTransactionType(TransactionType.BASE)
    public void expireFence(Long electronicId) {
        if (electronicId == null) {
            return;
        }
        XpElectronicFence electronicFence = this.getById(electronicId);
        if (electronicFence == null || electronicFence.getStatus() == null) {
            return;
        }
        Integer status = electronicFence.getStatus();
        if (status != 1 && status != 2) {
            return;
        }
        electronicFence.setStatus(3);
        this.updateById(electronicFence);
 
        List<XpElectronicFenceArea> electronicFenceAreaList = xpElectronicFenceAreaService.lambdaQuery()
                .eq(XpElectronicFenceArea::getElectronicId, electronicId)
                .list();
        if (CollUtil.isEmpty(electronicFenceAreaList)) {
            return;
        }
        for (XpElectronicFenceArea electronicFenceArea : electronicFenceAreaList) {
            electronicFenceArea.setAreaStatus(2);
        }
        xpElectronicFenceAreaService.updateBatchById(electronicFenceAreaList);
    }
 
 
    /**
     * 计算围栏中心点
     *
     * @param coordinates
     * @return
     */
    private org.locationtech.jts.geom.Point calculateCentroid(Coordinate[] coordinates) {
        // 1. 判空校验
        if (coordinates == null || coordinates.length == 0) {
            throw new ServiceException("坐标数组不能为空");
        }
 
        // 2. 过滤掉 null 坐标点
        Coordinate[] validCoords = Arrays.stream(coordinates)
                .filter(Objects::nonNull)
                .toArray(Coordinate[]::new);
 
        // 3. LinearRing 至少需要 4 个点(首尾相同),且必须闭合
        if (validCoords.length < 4) {
            throw new ServiceException("有效坐标点不足,至少需要4个点");
        }
 
        // 4. 确保首尾坐标相同(闭合)
        Coordinate first = validCoords[0];
        Coordinate last = validCoords[validCoords.length - 1];
        if (!first.equals2D(last)) {
            // 自动补上闭合点
            validCoords = Arrays.copyOf(validCoords, validCoords.length + 1);
            validCoords[validCoords.length - 1] = new Coordinate(first.x, first.y);
        }
 
        GeometryFactory factory = new GeometryFactory();
        LinearRing ring = factory.createLinearRing(validCoords);
        Polygon polygon = factory.createPolygon(ring);
        org.locationtech.jts.geom.Point centroid = polygon.getCentroid();
        System.out.println("中心点经度: " + centroid.getX());
        System.out.println("中心点纬度: " + centroid.getY());
        return centroid;
    }
}