liujie
2026-02-28 0c738efb5ecca9727ed4b0cf01250c4c07e83b3c
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
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
package com.xiaopeng.order.service.impl;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.ImmutableMap;
import com.xiaopeng.api.dto.account.GetUserCouponDto;
import com.xiaopeng.api.dto.account.UseUserCouponDto;
import com.xiaopeng.api.dto.account.UserResourcesDto;
import com.xiaopeng.api.dto.automaticPilot.PushOrderDto;
import com.xiaopeng.api.dto.operation.LonLatDto;
import com.xiaopeng.api.dto.order.GetOrderNumDto;
import com.xiaopeng.api.dto.order.HistoryEndPointsDto;
import com.xiaopeng.api.dto.order.HistoryStartPointsDto;
import com.xiaopeng.api.dto.order.PopOrderDto;
import com.xiaopeng.api.dto.pushMessage.SendMessageDTO;
import com.xiaopeng.api.dto.statistics.DailyCountDTO;
import com.xiaopeng.api.dto.statistics.OrderStatisticsDTO;
import com.xiaopeng.api.dto.statistics.StatisticsQueryDTO;
import com.xiaopeng.api.dto.vehicleConvoy.BaseVehicleUserDto;
import com.xiaopeng.api.feignClient.account.UserResourcesClient;
import com.xiaopeng.api.feignClient.account.XpAppUserClient;
import com.xiaopeng.api.feignClient.account.XpAppUserCouponClient;
import com.xiaopeng.api.feignClient.automaticPilot.OrderMissionClient;
import com.xiaopeng.api.feignClient.maintenance.XpTaskRuleClient;
import com.xiaopeng.api.feignClient.operation.XpCruisePlanClient;
import com.xiaopeng.api.feignClient.operation.XpPointClient;
import com.xiaopeng.api.feignClient.operation.XpPricingClient;
import com.xiaopeng.api.feignClient.operation.XpSystemSettingClient;
import com.xiaopeng.api.feignClient.order.XpCruiseOrderClient;
import com.xiaopeng.api.feignClient.pushMessage.XpPushMessageClient;
import com.xiaopeng.api.feignClient.vehicleConvoy.UserVehicleClient;
import com.xiaopeng.api.feignClient.vehicleConvoy.XpFleetClient;
import com.xiaopeng.api.feignClient.vehicleConvoy.XpFleetVehicleClient;
import com.xiaopeng.api.feignClient.vehicleConvoy.XpVehicleClient;
import com.xiaopeng.api.model.account.XpAppUser;
import com.xiaopeng.api.model.maintenance.XpTaskRule;
import com.xiaopeng.api.model.operation.XpFeedbackType;
import com.xiaopeng.api.model.operation.XpGeoQueryEntity;
import com.xiaopeng.api.model.operation.XpPoint;
import com.xiaopeng.api.model.operation.XpPricing;
import com.xiaopeng.api.model.order.*;
import com.xiaopeng.api.model.vehicleConvoy.XpFleet;
import com.xiaopeng.api.model.vehicleConvoy.XpVehicle;
import com.xiaopeng.api.vo.OrderType;
import com.xiaopeng.api.vo.account.GetUserListByUidsVo;
import com.xiaopeng.api.vo.account.UserCouponVo;
import com.xiaopeng.api.vo.automaticPilot.proto.down.cloudOrderOperation.OrderOperationType;
import com.xiaopeng.api.vo.operation.RouteVo;
import com.xiaopeng.api.vo.order.*;
import com.xiaopeng.api.vo.vehicleConvoy.AddTaxiPassengerVo;
import com.xiaopeng.api.vo.vehicleConvoy.CancelTaxiPassengerVo;
import com.xiaopeng.common.core.constant.CacheConstants;
import com.xiaopeng.common.core.constant.HttpStatus;
import com.xiaopeng.common.core.domain.R;
import com.xiaopeng.common.core.enums.OrderStatusEnum;
import com.xiaopeng.common.core.enums.PushMessageTypeEnum;
import com.xiaopeng.common.core.exception.ServiceException;
import com.xiaopeng.common.core.utils.DateUtils;
import com.xiaopeng.common.core.utils.GeodesyUtil;
import com.xiaopeng.common.core.utils.StringUtils;
import com.xiaopeng.common.core.web.domain.BaseModel;
import com.xiaopeng.common.core.web.page.PageInfo;
import com.xiaopeng.common.redis.service.RedisService;
import com.xiaopeng.common.security.utils.SecurityUtils;
import com.xiaopeng.order.constant.I18nKeyConstant;
import com.xiaopeng.order.dto.MileageDto;
import com.xiaopeng.order.job.base.QuartzManager;
import com.xiaopeng.order.job.base.TimeJobType;
import com.xiaopeng.order.job.jobs.AddCruiseMissionJob;
import com.xiaopeng.order.job.jobs.EndTripJob;
import com.xiaopeng.order.job.jobs.OrderCancelJob;
import com.xiaopeng.order.mangodb.model.OrderTrajectory;
import com.xiaopeng.order.mangodb.service.OrderTrajectoryService;
import com.xiaopeng.order.mapper.XpCruiseOrderMapper;
import com.xiaopeng.order.mapper.XpOrderDetailMapper;
import com.xiaopeng.order.mapper.XpOrderMapper;
import com.xiaopeng.order.model.dto.XpOrderCommentDto;
import com.xiaopeng.order.model.dto.XpOrderPayDto;
import com.xiaopeng.order.model.query.XpHistoryOrderListQuery;
import com.xiaopeng.order.model.query.XpOrderPageQuery;
import com.xiaopeng.order.model.vo.*;
import com.xiaopeng.order.service.IXpOrderCancelService;
import com.xiaopeng.order.service.IXpOrderEvaluateService;
import com.xiaopeng.order.service.IXpOrderReassignService;
import com.xiaopeng.order.service.IXpOrderService;
import com.xiaopeng.order.utils.TaxiPricingDemoService;
import com.xiaopeng.order.utils.TrajectoryGenerator;
import com.xiaopeng.order.utils.holiday.HolidayUtil;
import com.xiaopeng.order.vo.OrderDetailVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.transaction.annotation.ShardingSphereTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author mitao
 * @since 2026-02-03
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Lazy)
public class XpOrderServiceImpl extends ServiceImpl<XpOrderMapper, XpOrder> implements IXpOrderService {
 
    private final UserResourcesClient userResourcesClient;
    private final XpPointClient xpPointClient;
    private final XpVehicleClient xpVehicleClient;
    private final XpAppUserCouponClient xpAppUserCouponClient;
    private final XpFleetClient xpFleetClient;
    private final XpFleetVehicleClient xpFleetVehicleClient;
    private final UserVehicleClient userVehicleClient;
    private final IXpOrderEvaluateService xpOrderEvaluateService;
    private final IXpOrderCancelService xpOrderCancelService;
    private final IXpOrderReassignService xpOrderReassignService;
    private final RedisService redisService;
    private final XpPricingClient xpPricingClient;
    private final XpSystemSettingClient xpSystemSettingClient;
    private final OrderTrajectoryService orderTrajectoryService;
    private final XpPushMessageClient xpPushMessageClient;
    private final OrderMissionClient orderMissionClient;
    private final XpOrderDetailMapper xpOrderDetailMapper;
    private final XpCruiseOrderMapper xpCruiseOrderMapper;
    private final XpTaskRuleClient xpTaskRuleClient;
    private final XpCruisePlanClient xpCruisePlanClient;
 
 
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private HolidayUtil holidayUtil;
//    @Autowired
//    private XpPricingUtil xpPricingUtil;
 
    @Override
    public OrderStatisticsDTO getOrderStatistics(StatisticsQueryDTO query) {
        OrderStatisticsDTO dto = new OrderStatisticsDTO();
 
        // 1. 查询订单总数(状态为9=待评价或10=已完成)
        dto.setTotalCount(baseMapper.countCompletedOrders());
 
        // 2. 查询时间范围内新增订单数
        if (Objects.nonNull(query.getStartDate()) && Objects.nonNull(query.getEndDate())) {
            dto.setNewCount(baseMapper.countNewOrders(query.getStartDate(), query.getEndDate()));
        } else {
            dto.setNewCount(0L);
        }
 
        // 3. 查询总交易金额和总收入(pay_money累加)
        BigDecimal totalMoney = baseMapper.sumTotalMoney();
        dto.setTotalMoney(Objects.nonNull(totalMoney) ? totalMoney : BigDecimal.ZERO);
        dto.setTotalIncome(Objects.nonNull(totalMoney) ? totalMoney : BigDecimal.ZERO);
 
        // 4. 查询近N天每日新增订单数(默认30天)
        Integer trendDays = Objects.nonNull(query.getTrendDays()) ? query.getTrendDays() : 30;
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(trendDays - 1);
        List<DailyCountDTO> dailyCountList = baseMapper.getDailyOrderCount(startDate, endDate);
        dto.setDailyCountList(Objects.nonNull(dailyCountList) ? dailyCountList : new ArrayList<>());
 
        return dto;
    }
 
    @Override
    public PageInfo<XpOrderPageVO> pageList(XpOrderPageQuery query) {
        // 1. 构建查询条件
        LambdaQueryWrapper<XpOrder> wrapper = buildQueryWrapper(query);
        wrapper.orderByDesc(XpOrder::getCreateTime);
 
        // 2. 分页查询
        Page<XpOrder> page = new Page<>(query.getPageNum(), query.getPageSize());
        Page<XpOrder> pageResult = this.page(page, wrapper);
 
        if (CollectionUtils.isEmpty(pageResult.getRecords())) {
            PageInfo<XpOrderPageVO> resultPage = new PageInfo<>(query.getPageNum(), query.getPageSize());
            resultPage.setTotal(0L);
            resultPage.setRecords(new ArrayList<>());
            return resultPage;
        }
 
        // 3. 收集关联ID
        Set<Long> userIds = new HashSet<>();
        Set<Long> vehicleIds = new HashSet<>();
        Set<Long> fleetIds = new HashSet<>();
        for (XpOrder order : pageResult.getRecords()) {
            if (Objects.nonNull(order.getAppUserId())) {
                userIds.add(order.getAppUserId());
            }
            if (Objects.nonNull(order.getVehicleId())) {
                vehicleIds.add(order.getVehicleId());
            }
            if (Objects.nonNull(order.getFleetId())) {
                fleetIds.add(order.getFleetId());
            }
        }
 
        // 4. 批量查询关联数据
        JSONObject jsonObject = batchGetUsers(userIds);
        Map<Long, XpVehicle> vehicleMap = batchGetVehicles(vehicleIds);
        Map<Long, XpFleet> fleetMap = batchGetFleets(fleetIds);
 
        // 5. 组装 VO
        List<XpOrderPageVO> voList = pageResult.getRecords().stream()
                .map(order -> convertToPageVO(order, jsonObject, vehicleMap, fleetMap))
                .collect(Collectors.toList());
 
        // 6. 返回分页结果
        PageInfo<XpOrderPageVO> resultPage = new PageInfo<>(query.getPageNum(), query.getPageSize());
        resultPage.setTotal(pageResult.getTotal());
        resultPage.setRecords(voList);
        return resultPage;
    }
 
    @Override
    public XpOrderDetailVO getOrderDetail(Long id) {
        // 1. 查询订单基础信息
        XpOrder order = this.getById(id);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
 
        // 2. 转换为详情 VO
        XpOrderDetailVO vo = BeanUtil.toBean(order, XpOrderDetailVO.class);
 
        // 3. 获取用户信息
        if (Objects.nonNull(order.getAppUserId())) {
            JSONObject jsonObject = batchGetUsers(Collections.singleton(order.getAppUserId()));
            JSONObject userInfo = jsonObject.getJSONObject(order.getAppUserId().toString());
            if (Objects.nonNull(userInfo)) {
                vo.setNickName(userInfo.getString("nickName"));
                vo.setPhoneNumber(userInfo.getString("mobile"));
            }
        }
 
        // 4. 获取车辆信息
        if (Objects.nonNull(order.getVehicleId())) {
            Map<Long, XpVehicle> vehicleMap = batchGetVehicles(Collections.singleton(order.getVehicleId()));
            XpVehicle vehicle = vehicleMap.get(order.getVehicleId());
            if (Objects.nonNull(vehicle)) {
                vo.setPlateNumber(vehicle.getPlateNumber());
                vo.setVehicleModel(vehicle.getVehicleModel());
            }
        }
 
        // 5. 获取车队信息
        if (Objects.nonNull(order.getFleetId())) {
            Map<Long, XpFleet> fleetMap = batchGetFleets(Collections.singleton(order.getFleetId()));
            XpFleet fleet = fleetMap.get(order.getFleetId());
            if (Objects.nonNull(fleet)) {
                vo.setFleetName(fleet.getFleetName());
            }
        }
 
        // 6. 获取评价信息
        LambdaQueryWrapper<XpOrderEvaluate> evaluateWrapper = new LambdaQueryWrapper<>();
        evaluateWrapper.eq(XpOrderEvaluate::getOrderId, id);
        XpOrderEvaluate evaluate = xpOrderEvaluateService.getOne(evaluateWrapper);
        if (Objects.nonNull(evaluate)) {
            vo.setOrderRating(evaluate.getOrderRating());
        }
        //TODO 7.查询mongodb 该订单上传的经纬度轨迹信息
        vo.setOrderPositionList(new ArrayList<>());
        return vo;
    }
 
    @Override
    public void deleteOrder(Long id) {
        // 1. 校验订单是否存在
        XpOrder order = this.getById(id);
        if (Objects.isNull(order)) {
            throw new ServiceException("订单不存在", I18nKeyConstant.ORDER_NOT_EXISTS);
        }
 
        this.removeById(id);
    }
 
    @Override
    public List<XpOrderPageVO> exportList(XpOrderPageQuery query) {
        // 1. 构建查询条件
        LambdaQueryWrapper<XpOrder> wrapper = buildQueryWrapper(query);
 
        // 2. 查询订单列表
        List<XpOrder> orderList = this.list(wrapper);
 
        if (CollectionUtils.isEmpty(orderList)) {
            return new ArrayList<>();
        }
 
        // 3. 收集关联ID
        Set<Long> userIds = new HashSet<>();
        Set<Long> vehicleIds = new HashSet<>();
        Set<Long> fleetIds = new HashSet<>();
        for (XpOrder order : orderList) {
            if (Objects.nonNull(order.getAppUserId())) {
                userIds.add(order.getAppUserId());
            }
            if (Objects.nonNull(order.getVehicleId())) {
                vehicleIds.add(order.getVehicleId());
            }
            if (Objects.nonNull(order.getFleetId())) {
                fleetIds.add(order.getFleetId());
            }
        }
 
        // 4. 批量查询关联数据
        JSONObject jsonObject = batchGetUsers(userIds);
        Map<Long, XpVehicle> vehicleMap = batchGetVehicles(vehicleIds);
        Map<Long, XpFleet> fleetMap = batchGetFleets(fleetIds);
 
        // 5. 组装 VO
        return orderList.stream()
                .map(order -> convertToPageVO(order, jsonObject, vehicleMap, fleetMap))
                .collect(Collectors.toList());
    }
 
    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<XpOrder> buildQueryWrapper(XpOrderPageQuery query) {
        LambdaQueryWrapper<XpOrder> wrapper = new LambdaQueryWrapper<>();
 
        wrapper.like(StringUtils.isNotBlank(query.getOrderNumber()), XpOrder::getOrderNumber, query.getOrderNumber())
                .eq(Objects.nonNull(query.getFleetId()), XpOrder::getFleetId, query.getFleetId())
                .eq(Objects.nonNull(query.getOrderSource()), XpOrder::getOrderSource, query.getOrderSource())
                .like(StringUtils.isNotBlank(query.getCityCode()), XpOrder::getCityCode, query.getCityCode())
                .eq(Objects.nonNull(query.getStatus()), XpOrder::getStatus, query.getStatus());
 
        if (Objects.nonNull(query.getStartTime())) {
            wrapper.ge(XpOrder::getCreateTime, LocalDateTime.of(query.getStartTime(), LocalTime.MIN));
        }
        if (Objects.nonNull(query.getEndTime())) {
            wrapper.ge(XpOrder::getCreateTime, LocalDateTime.of(query.getEndTime(), LocalTime.MAX));
        }
        wrapper.orderByDesc(XpOrder::getCreateTime);
        return wrapper;
    }
 
    /**
     * 批量获取用户信息
     */
    private JSONObject batchGetUsers(Set<Long> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return new JSONObject();
        }
        try {
            GetUserListByUidsVo getUserListByUidsVo = new GetUserListByUidsVo();
            getUserListByUidsVo.setUids(new ArrayList<>(userIds));
            getUserListByUidsVo.setGetPreCarOwner(Boolean.TRUE);
            UserResourcesDto userListByUids = userResourcesClient.getUserListByUids(getUserListByUidsVo);
            if (userListByUids.getCode().equals(HttpStatus.SUCCESS)) {
                return JSONObject.parseObject(userListByUids.getData().toString());
            }
        } catch (Exception e) {
            log.error("批量获取用户信息失败: {}", e.getMessage());
        }
        return new JSONObject();
    }
 
    /**
     * 批量获取车辆信息
     */
    private Map<Long, XpVehicle> batchGetVehicles(Set<Long> vehicleIds) {
        if (CollectionUtils.isEmpty(vehicleIds)) {
            return new HashMap<>();
        }
        try {
            R<List<XpVehicle>> result = xpVehicleClient.listByIds(new ArrayList<>(vehicleIds));
            if (Objects.nonNull(result) && Objects.nonNull(result.getData())) {
                return result.getData().stream()
                        .collect(Collectors.toMap(XpVehicle::getId, Function.identity(), (a, b) -> a));
            }
        } catch (Exception e) {
            log.error("批量获取车辆信息失败: {}", e.getMessage());
        }
        return new HashMap<>();
    }
 
    /**
     * 批量获取车队信息
     */
    private Map<Long, XpFleet> batchGetFleets(Set<Long> fleetIds) {
        if (CollectionUtils.isEmpty(fleetIds)) {
            return new HashMap<>();
        }
        try {
            R<List<XpFleet>> result = xpFleetClient.listByIds(new ArrayList<>(fleetIds));
            if (Objects.nonNull(result) && Objects.nonNull(result.getData())) {
                return result.getData().stream()
                        .collect(Collectors.toMap(XpFleet::getId, Function.identity(), (a, b) -> a));
            }
        } catch (Exception e) {
            log.error("批量获取车队信息失败: {}", e.getMessage());
        }
        return new HashMap<>();
    }
 
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancelOrCloseOrder(Long orderId, Integer type) {
        // 1. 校验订单是否存在
        XpOrder order = this.getById(orderId);
        if (Objects.isNull(order)) {
            throw new ServiceException("订单不存在");
        }
 
        // 2. 校验操作类型
        if (type != 1 && type != 2) {
            throw new ServiceException("操作类型错误,type只能为1或2");
        }
 
        // 3. 校验订单状态是否允许操作
        Integer currentStatus = order.getStatus();
        //取消订单:在未接到乘客前都可以,关闭订单,在送达目的地可以操作关闭
        if (type == 1) {
            // 取消订单:只有待接单(1)、待出发(2)、接驾中(3)状态可以取消
            if (currentStatus != 1 && currentStatus != 2 && currentStatus != 3) {
                throw new ServiceException("当前订单状态不允许取消,只有待接单、待出发、接驾中状态的订单可以取消", I18nKeyConstant.ORDER_CANCEL_FAILED);
            }
        } else {
            // 关闭订单:只有待付款(8)、待评价(9)状态可以关闭
            if (currentStatus != 7 && currentStatus != 8 && currentStatus != 9) {
                throw new ServiceException("当前订单状态不允许关闭,只有待付款、待评价状态的订单可以关闭", I18nKeyConstant.ORDER_CLOSE_FAILED);
            }
        }
 
        // 4. 执行操作
        if (type == 1) {
            // 取消订单
            cancelOrder(order);
        } else {
            // 关闭订单
            closeOrder(order);
        }
    }
 
    /**
     * 转换为分页列表 VO
     */
    private XpOrderPageVO convertToPageVO(XpOrder order,
                                          JSONObject jsonObject,
                                          Map<Long, XpVehicle> vehicleMap,
                                          Map<Long, XpFleet> fleetMap) {
        XpOrderPageVO vo = new XpOrderPageVO();
        vo.setId(order.getId());
        vo.setOrderNumber(order.getOrderNumber());
        vo.setCreateTime(order.getCreateTime());
        vo.setOrderSource(order.getOrderSource());
        vo.setRideTime(order.getRideTime());
        vo.setStartAddress(order.getStartAddress());
        vo.setEndAddress(order.getEndAddress());
        vo.setOrderMoney(order.getOrderMoney());
        vo.setStatus(order.getStatus());
 
        // 用户信息
        if (Objects.nonNull(order.getAppUserId()) && jsonObject.containsKey(order.getAppUserId().toString())) {
            JSONObject userInfo = jsonObject.getJSONObject(order.getAppUserId().toString());
            vo.setNickName(userInfo.getString("nickName"));
            vo.setPhoneNumber(userInfo.getString("mobile"));
        }
 
        // 车辆信息
        if (Objects.nonNull(order.getVehicleId()) && vehicleMap.containsKey(order.getVehicleId())) {
            XpVehicle vehicle = vehicleMap.get(order.getVehicleId());
            vo.setPlateNumber(vehicle.getPlateNumber());
            vo.setVehicleModel(vehicle.getVehicleModel());
        }
 
        // 车队信息
        if (Objects.nonNull(order.getFleetId()) && fleetMap.containsKey(order.getFleetId())) {
            XpFleet fleet = fleetMap.get(order.getFleetId());
            vo.setFleetName(fleet.getFleetName());
        }
 
        return vo;
    }
 
    /**
     * 取消订单
     */
    private void cancelOrder(XpOrder order) {
        // 1. 更新订单状态为已取消(0)
        order.setStatus(0);
        this.updateById(order);
 
        // 2. 保存取消记录
        XpOrderCancel orderCancel = new XpOrderCancel();
        orderCancel.setOrderId(order.getId());
        orderCancel.setCancelSource(3); // 3=运营人员(后台管理接口固定为运营人员)
        orderCancel.setUserId(SecurityUtils.getUserId()); // 当前登录用户ID
        orderCancel.setCancelReason("运营人员取消订单");
        orderCancel.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        xpOrderCancelService.save(orderCancel);
        //查询车辆信息
        R<XpVehicle> xpVehicleR = xpVehicleClient.queryById(order.getId());
        if (xpVehicleR.getCode() == HttpStatus.SUCCESS && Objects.nonNull(xpVehicleR.getData())) {
            // 下发命令
            if (order.getStatus() > 1) {
                PushOrderDto pushOrderDto = new PushOrderDto();
                pushOrderDto.setOrderId(order.getId().toString());
                pushOrderDto.setVin(xpVehicleR.getData().getVehicleVin());
                pushOrderDto.setOperation_type(OrderOperationType.CLOUD_CANCEL_ORDER);
                orderMissionClient.cancelOrder(pushOrderDto);
            }
        } else {
            log.info("查询车辆信息失败,订单ID: {}, 下发取消订单命令失败", order.getId());
        }
        log.info("订单取消成功,订单ID: {}, 操作人: {}", order.getId(), SecurityUtils.getUsername());
    }
 
    /**
     * 关闭订单
     */
    private void closeOrder(XpOrder order) {
        // 更新订单状态为已完成(10)
        order.setStatus(10);
        this.updateById(order);
 
        log.info("订单关闭成功,订单ID: {}, 操作人: {}", order.getId(), SecurityUtils.getUsername());
    }
 
    /**
     * 改派订单
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void reassignOrder(Long orderId, Long newVehicleId, String reassignReason) {
        // 1. 校验订单是否存在
        XpOrder order = this.getById(orderId);
        if (Objects.isNull(order)) {
            throw new ServiceException("订单不存在");
        }
 
        // 2. 校验订单状态(只有待出发、接驾中、待乘客上车状态可以改派)
        Integer currentStatus = order.getStatus();
        if (currentStatus != 2 && currentStatus != 3 && currentStatus != 4) {
            throw new ServiceException("当前订单状态不允许改派,只有待出发、接驾中、待乘客上车状态的订单可以改派", I18nKeyConstant.ORDER_REASSIGN_FAILED);
        }
 
        // 3. 校验新旧车辆是否相同
        if (Objects.equals(order.getVehicleId(), newVehicleId)) {
            throw new ServiceException("新车辆与原车辆相同,无需改派", I18nKeyConstant.ORDER_REASSIGN_VEHICLE_FAILED);
        }
 
        // 4. 查询新车辆信息并校验
        R<List<XpVehicle>> vehicleResult = xpVehicleClient.listByIds(Collections.singletonList(newVehicleId));
        if (Objects.isNull(vehicleResult) || Objects.isNull(vehicleResult.getData()) || vehicleResult.getData().isEmpty()) {
            throw new ServiceException("新车辆不存在", I18nKeyConstant.ORDER_REASSIGN_NEW_VEHICLE_NOT_EXISTS);
        }
        XpVehicle newVehicle = vehicleResult.getData().get(0);
 
        // 5. 校验新车辆的运营状态
        // 车辆状态:1=待完善 2=待运营 3=保险/年检过期
        // 运营状态:1=运营中 2=维修中 3=已收车 4=车辆异常
        // 当前模式:1=接单 2=测试
        // 模式状态:1=开始接单/开始测试 2=停止接单/停止测试
        if (Objects.isNull(newVehicle.getStatus()) || newVehicle.getStatus() == 3) {
            throw new ServiceException("新车辆保险或年检已过期,无法接单", I18nKeyConstant.ORDER_REASSIGN_NEW_VEHICLE_STATUS_INVALID);
        }
        if (Objects.isNull(newVehicle.getOperatingStatus()) || newVehicle.getOperatingStatus() != 1) {
            throw new ServiceException("新车辆运营状态异常,无法接单", I18nKeyConstant.ORDER_REASSIGN_NEW_VEHICLE_OPERATING_STATUS_INVALID);
        }
        if (Objects.isNull(newVehicle.getAcceptOrTest()) || newVehicle.getAcceptOrTest() != 1) {
            throw new ServiceException("新车辆当前不在接单模式", I18nKeyConstant.ORDER_REASSIGN_NEW_VEHICLE_NOT_IN_ACCEPT_MODE);
        }
        if (Objects.isNull(newVehicle.getAcceptOrTestStatus()) || newVehicle.getAcceptOrTestStatus() != 1) {
            throw new ServiceException("新车辆未开始接单", I18nKeyConstant.ORDER_REASSIGN_NEW_VEHICLE_NOT_START_ACCEPT);
        }
        if (Objects.isNull(newVehicle.getState()) || newVehicle.getState() != 0) {
            throw new ServiceException("新车辆已接单,请重新选择", I18nKeyConstant.ORDER_REASSIGN_NEW_VEHICLE_NOT_FREE);
        }
 
        // 6. 保存原车辆和车队信息
        Long oldVehicleId = order.getVehicleId();
        Long oldFleetId = order.getFleetId();
 
        // 6.1 处理原车辆:取消订单指令、解绑乘客、更新状态、创建返程巡游订单
        if (Objects.nonNull(oldVehicleId)) {
            try {
                R<XpVehicle> oldVehicleResult = xpVehicleClient.queryById(oldVehicleId);
                if (oldVehicleResult != null && oldVehicleResult.getCode() == HttpStatus.SUCCESS && oldVehicleResult.getData() != null) {
                    XpVehicle oldVehicle = oldVehicleResult.getData();
 
                    // 6.1.1 取消原订单指令
                    PushOrderDto cancelDto = new PushOrderDto();
                    cancelDto.setOrderId(order.getId().toString());
                    cancelDto.setVin(oldVehicle.getVehicleVin());
                    cancelDto.setOperation_type(OrderOperationType.CLOUD_CANCEL_ORDER);
                    orderMissionClient.cancelOrder(cancelDto);
                    log.info("已取消原车辆订单指令,订单ID: {}, VIN: {}", orderId, oldVehicle.getVehicleVin());
 
                    // 6.1.2 解绑乘客与原车辆关系
                    if (Objects.nonNull(order.getAppUserId())) {
                        CancelTaxiPassengerVo cancelVo = new CancelTaxiPassengerVo();
                        cancelVo.setVin(oldVehicle.getVehicleVin());
                        cancelVo.setUid(order.getAppUserId().toString());
                        cancelVo.setOrderNo(order.getOrderNumber());
                        cancelVo.setAppId("");
                        userVehicleClient.cancelTaxiPassenger(cancelVo);
                        log.info("已解绑乘客与原车辆关系,用户ID: {}, VIN: {}", order.getAppUserId(), oldVehicle.getVehicleVin());
                    }
 
                    // 6.1.3 修改原车辆状态为空闲
                    oldVehicle.setState(0);
                    xpVehicleClient.updateVehicleById(oldVehicle);
                    log.info("已将原车辆状态设为空闲,车辆ID: {}", oldVehicleId);
 
                    // 6.1.4 为原车辆创建返程巡游订单
                    createReturnCruiseOrder(oldVehicle, order);
                } else {
                    log.warn("查询原车辆信息失败,车辆ID: {}", oldVehicleId);
                }
            } catch (Exception e) {
                log.error("处理原车辆失败,车辆ID: {},错误: {}", oldVehicleId, e.getMessage());
            }
        }
 
        // 7. 查询新车辆关联的车队ID
        Long newFleetId = null;
        try {
            R<Long> fleetIdResult = xpFleetVehicleClient.getFleetIdByVehicleId(newVehicleId);
            if (Objects.nonNull(fleetIdResult) && Objects.nonNull(fleetIdResult.getData())) {
                newFleetId = fleetIdResult.getData();
                log.info("查询到新车辆ID: {} 关联的车队ID: {}", newVehicleId, newFleetId);
            } else {
                log.warn("新车辆ID: {} 未关联任何车队,将使用原车队ID: {}", newVehicleId, oldFleetId);
                newFleetId = oldFleetId;
            }
        } catch (Exception e) {
            log.error("查询新车辆关联的车队ID失败,车辆ID: {},错误: {}", newVehicleId, e.getMessage());
            newFleetId = oldFleetId;
        }
 
        // 8. 如果旧订单的车队ID为空,尝试查询旧车辆的车队ID
        if (Objects.isNull(oldFleetId) && Objects.nonNull(oldVehicleId)) {
            try {
                R<Long> oldFleetIdResult = xpFleetVehicleClient.getFleetIdByVehicleId(oldVehicleId);
                if (Objects.nonNull(oldFleetIdResult) && Objects.nonNull(oldFleetIdResult.getData())) {
                    oldFleetId = oldFleetIdResult.getData();
                    log.info("补充查询到旧车辆ID: {} 关联的车队ID: {}", oldVehicleId, oldFleetId);
                }
            } catch (Exception e) {
                log.warn("查询旧车辆关联的车队ID失败,车辆ID: {},错误: {}", oldVehicleId, e.getMessage());
            }
        }
 
        // 9. 更新订单的车辆和车队信息
        order.setVehicleId(newVehicleId);
        if (Objects.nonNull(newFleetId)) {
            order.setFleetId(newFleetId);
        }
        this.updateById(order);
 
        // 10. 保存改派记录
        XpOrderReassign orderReassign = new XpOrderReassign();
        orderReassign.setOrderId(orderId);
        orderReassign.setUserId(SecurityUtils.getUserId());
        orderReassign.setOperationTime(LocalDateTime.now());
        orderReassign.setOldVehicleId(oldVehicleId);
        orderReassign.setNewVehicleId(newVehicleId);
        orderReassign.setOldFleetId(oldFleetId);
        orderReassign.setNewFleetId(newFleetId);
        orderReassign.setReassignReason(
                StringUtils.isNotBlank(reassignReason) ? reassignReason : "运营人员改派订单"
        );
        orderReassign.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        xpOrderReassignService.save(orderReassign);
 
        log.info("订单改派成功,订单ID: {}, 原车辆ID: {}, 新车辆ID: {}, 原车队ID: {}, 新车队ID: {}, 操作人: {}",
                orderId, oldVehicleId, newVehicleId, oldFleetId, newFleetId, SecurityUtils.getUsername());
 
        // 11. 处理新车辆:绑定乘客、下发订单、更新状态
        try {
            // 11.1 绑定乘客与新车辆关系
            if (Objects.nonNull(order.getAppUserId())) {
                AddTaxiPassengerVo addVo = new AddTaxiPassengerVo();
                addVo.setVin(newVehicle.getVehicleVin());
                addVo.setUid(order.getAppUserId().toString());
                addVo.setOrderNo(order.getOrderNumber());
                addVo.setAppId(""); // TODO 获取appId
                userVehicleClient.addTaxiPassenger(addVo);
                log.info("已绑定乘客与新车辆关系,用户ID: {}, VIN: {}", order.getAppUserId(), newVehicle.getVehicleVin());
            }
 
            // 11.2 下发订单到新车辆
            PushOrderDto pushDto = new PushOrderDto();
            pushDto.setOrderId(order.getId().toString());
            pushDto.setVin(newVehicle.getVehicleVin());
            orderMissionClient.pushOrder(pushDto);
            log.info("已下发订单到新车辆,订单ID: {}, VIN: {}", orderId, newVehicle.getVehicleVin());
 
            // 11.3 更新新车辆状态为已接单
            newVehicle.setState(1);
            xpVehicleClient.updateVehicleById(newVehicle);
            log.info("已将新车辆状态设为已接单,车辆ID: {}", newVehicleId);
 
        } catch (Exception e) {
            log.error("处理新车辆失败,车辆ID: {},错误: {}", newVehicleId, e.getMessage());
        }
 
    }
 
    /**
     * 为原车辆创建返程巡游订单
     * <p>
     * 改派时,原车辆需要返回巡游路线:
     * - 若最新巡游订单状态为已终止(status=2),返回原出发点
     * - 若最新巡游订单状态为已完成(status=3),返回原终点
     * - 其他状态,默认返回原出发点
     * </p>
     *
     * @param oldVehicle 原车辆信息
     * @param order      当前订单信息
     */
    private void createReturnCruiseOrder(XpVehicle oldVehicle, XpOrder order) {
        try {
            // 查询该车辆最新的一条巡游订单
            XpCruiseOrder lastCruise = xpCruiseOrderMapper.selectOne(
                    new LambdaQueryWrapper<XpCruiseOrder>()
                            .eq(XpCruiseOrder::getVehicleId, oldVehicle.getId())
                            .orderByDesc(BaseModel::getCreateTime)
                            .last("limit 1")
            );
 
            if (lastCruise == null) {
                log.warn("原车辆没有巡游订单记录,跳过创建返程订单,车辆ID: {}", oldVehicle.getId());
                return;
            }
 
            XpCruiseOrder returnOrder = new XpCruiseOrder();
            returnOrder.setId("XU" + IdUtil.fastUUID());
            returnOrder.setVehicleId(oldVehicle.getId());
            returnOrder.setVehicleVin(oldVehicle.getVehicleVin());
            returnOrder.setFleetId(oldVehicle.getFleetId());
            returnOrder.setOrderType(2); // 返程单
            returnOrder.setStatus(1);    // 进行中
            returnOrder.setLastOrderId(lastCruise.getId());
            returnOrder.setCreateTime(LocalDateTime.now());
 
            // 返程起点 = 当前订单的终点(车辆当前位置附近)
            returnOrder.setStartPointId(order.getEndPointId());
            returnOrder.setStartPointName(order.getEndPointName());
            returnOrder.setStartLon(order.getEndLon());
            returnOrder.setStartLat(order.getEndLat());
 
            // 根据最新巡游订单状态决定返程终点
            if (lastCruise.getStatus() != null && lastCruise.getStatus() == 2) {
                // 已终止(status=2) -> 返回原出发点
                returnOrder.setEndPointId(lastCruise.getStartPointId());
                returnOrder.setEndPointName(lastCruise.getStartPointName());
                returnOrder.setEndLon(lastCruise.getStartLon());
                returnOrder.setEndLat(lastCruise.getStartLat());
                log.info("巡游订单状态为已终止,返回原出发点");
            } else if (lastCruise.getStatus() != null && lastCruise.getStatus() == 3) {
                // 已完成(status=3) -> 返回原终点
                returnOrder.setEndPointId(lastCruise.getEndPointId());
                returnOrder.setEndPointName(lastCruise.getEndPointName());
                returnOrder.setEndLon(lastCruise.getEndLon());
                returnOrder.setEndLat(lastCruise.getEndLat());
                log.info("巡游订单状态为已完成,返回原终点");
            } else {
                // 其他状态(进行中等),默认返回原出发点
                returnOrder.setEndPointId(lastCruise.getStartPointId());
                returnOrder.setEndPointName(lastCruise.getStartPointName());
                returnOrder.setEndLon(lastCruise.getStartLon());
                returnOrder.setEndLat(lastCruise.getStartLat());
                log.info("巡游订单状态为{},默认返回原出发点", lastCruise.getStatus());
            }
 
            xpCruiseOrderMapper.insert(returnOrder);
 
            // 下发巡游订单到原车辆
            PushOrderDto pushDto = new PushOrderDto();
            pushDto.setVin(oldVehicle.getVehicleVin());
            pushDto.setOrderId(returnOrder.getId());
            orderMissionClient.pushOrder(pushDto);
 
            log.info("为原车辆创建返程巡游订单成功,订单ID: {}, 车辆ID: {}", returnOrder.getId(), oldVehicle.getId());
 
        } catch (Exception e) {
            log.error("创建返程巡游订单失败,车辆ID: {},错误: {}", oldVehicle.getId(), e.getMessage());
        }
    }
 
    @Override
    public XpPointInfoVo getUserQuickCapsule(String uid) {
        try {
            // 使用Redis的sorted set(排行榜)获取第一个元素
            // 获取分数最高的元素(默认按分数从高到低排序)
            Set<Object> result = redisService.redisTemplate.opsForZSet().reverseRange("history_order_" + uid, 0, 0);
            if (result != null && !result.isEmpty()) {
                // 排行榜中存储的是JSON字符串
                String jsonString = result.iterator().next().toString();
                // 使用Hutool的JSON工具解析为XpPointInfoVo对象
                return JSONUtil.toBean(jsonString, XpPointInfoVo.class);
            }
        } catch (Exception e) {
            log.error("获取用户快捷胶囊失败: {}", e.getMessage(), e);
        }
        return null;
    }
 
    @Override
    public List<XpHistoryStartPointsVo> getHistoryStartPoints(String uid, double lon, double lat) {
        //
        List<XpOrder> xpOrders = this.baseMapper.selectList(new LambdaQueryWrapper<XpOrder>().eq(XpOrder::getAppUserId, Long.parseLong(uid)).orderByDesc(BaseModel::getCreateTime).last("LIMIT 10"));
        if (xpOrders.isEmpty()) {
            return Collections.emptyList();
        }
        // 获取点位信息
        List<Long> startPointsIds = xpOrders.stream().map(XpOrder::getStartPointId).collect(Collectors.toList());
 
        R<List<XpHistoryStartPointsVo>> r = xpPointClient.getHistoryStartPoints(new HistoryStartPointsDto(startPointsIds, lon, lat));
        return r.getData();
 
    }
 
    @Override
    public List<XpHistoryEndPointsVo> getHistoryEndPoints(String uid, double lon, double lat) {
        //
        List<XpOrder> xpOrders = this.baseMapper.selectList(new LambdaQueryWrapper<XpOrder>().eq(XpOrder::getAppUserId, Long.parseLong(uid)).orderByDesc(BaseModel::getCreateTime).last("LIMIT 10"));
        if (xpOrders.isEmpty()) {
            return Collections.emptyList();
        }
        // 获取点位信息
        List<Long> endPointsIds = xpOrders.stream().map(XpOrder::getEndPointId).collect(Collectors.toList());
 
        R<List<XpHistoryEndPointsVo>> r = xpPointClient.getHistoryEndPoints(new HistoryEndPointsDto(endPointsIds, lon, lat));
        return r.getData();
 
    }
 
    /**
     * 获取历史订单列表
     *
     * @param query
     * @param uid
     * @return
     */
    @Override
    public XpOrderHistoryVO getHistoryOrderList(XpHistoryOrderListQuery query, String uid) {
        Page<XpOrderHistoryListVO> page = new Page<>(query.getPageNum(), query.getPageSize());
        List<XpOrderHistoryListVO> list = this.baseMapper.getHistoryOrderList(page, query, Long.parseLong(uid));
        XpOrderHistoryVO xpOrderHistoryVO = new XpOrderHistoryVO();
        if(list.isEmpty()){
            return xpOrderHistoryVO;
        }
 
 
        Set<Long> points = list.stream().map(XpOrderHistoryListVO::getStartPointId).collect(Collectors.toSet());
        points.addAll(list.stream().map(XpOrderHistoryListVO::getEndPointId).collect(Collectors.toSet()));
 
 
        // 查询 点位信息
        R<List<XpPoint>> pointInfoVos = xpPointClient.getPointsInfo(points);
        List<XpPoint> pointList = pointInfoVos.getData();
        xpOrderHistoryVO.setTotal((int) page.getTotal());
 
        // 根据time分组
        Map<String, List<XpOrderHistoryListVO>> map = list.stream().collect(Collectors.groupingBy(XpOrderHistoryListVO::getTimeStr));
        List<XpOrderHistoryDateVO> dateVOS = map.entrySet().stream().map(entry -> {
            XpOrderHistoryDateVO xpOrderHistoryDateVO = new XpOrderHistoryDateVO();
            xpOrderHistoryDateVO.setDateLabel(entry.getKey());
            List<XpOrderHistoryListVO> value = entry.getValue();
            value = value.stream().sorted(Comparator.comparing(XpOrderHistoryListVO::getTime).reversed()).collect(Collectors.toList());
 
            for (XpOrderHistoryListVO xpOrderHistoryListVO : value) {
                XpPoint xpPoint = pointList.stream().filter(e -> e.getId().equals(xpOrderHistoryListVO.getStartPointId())).findFirst().orElse(null);
                if(xpPoint!=null){
                    xpOrderHistoryListVO.setStartPointName(xpPoint.getPointName());
                    xpOrderHistoryListVO.setStartLat(xpPoint.getPointLat());
                    xpOrderHistoryListVO.setStartLon(xpPoint.getPointLon());
                    xpOrderHistoryListVO.setXpElectronicFenceAreaId(xpPoint.getElectronicAreaId());
                    xpOrderHistoryListVO.setStartParkingTimeLimit(xpPoint.getParkingTimeLimit());
                }
 
                xpPoint = pointList.stream().filter(e -> e.getId().equals(xpOrderHistoryListVO.getEndPointId())).findFirst().orElse(null);
                if(xpPoint!=null){
                    xpOrderHistoryListVO.setEndPointName(xpPoint.getPointName());
                    xpOrderHistoryListVO.setEndLat(xpPoint.getPointLat());
                    xpOrderHistoryListVO.setEndLon(xpPoint.getPointLon());
                    xpOrderHistoryListVO.setXpElectronicFenceAreaId(xpPoint.getElectronicAreaId());
                    xpOrderHistoryListVO.setEndParkingTimeLimit(xpPoint.getParkingTimeLimit());
                }
            }
 
 
            xpOrderHistoryDateVO.setOrders(value);
            return xpOrderHistoryDateVO;
        }).collect(Collectors.toList());
        xpOrderHistoryVO.setList(dateVOS);
 
        return xpOrderHistoryVO;
    }
 
 
    /**
     * 取消订单
     *
     * @param orderId
     * @param uid
     */
    @Override
    @Transactional
    public void cancelOrder(Long orderId, String uid) {
        XpOrder order = this.getById(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在",I18nKeyConstant.ORDER_NOT_EXISTS);
        }
        if (!order.getAppUserId().toString().equals(uid)) {
            throw new ServiceException("订单不存在",I18nKeyConstant.ORDER_NOT_EXISTS);
        }
        if (order.getStatus() > 5 || order.getStatus() < 1) {
            throw new ServiceException("订单状态错误",I18nKeyConstant.ORDER_STATUS_ERROR);
        }
        order.setStatus(0);
 
        // 组装调用车机参数
        CancelTaxiPassengerVo cancelTaxiPassengerVo = new CancelTaxiPassengerVo();
        Long vehicleId = order.getVehicleId();
        R<XpVehicle> xpVehicleR = xpVehicleClient.queryById(vehicleId);
        XpVehicle xpVehicle = xpVehicleR.getData();
        if (xpVehicle == null) {
            throw new ServiceException("车辆不存在",I18nKeyConstant.VEHICLE_NOT_EXISTS);
        }
        cancelTaxiPassengerVo.setVin(xpVehicle.getVehicleVin());
        cancelTaxiPassengerVo.setUid(order.getAppUserId().toString());
        cancelTaxiPassengerVo.setOrderNo(order.getOrderNumber());
        // TODO 加配置文件取
        cancelTaxiPassengerVo.setAppId("");
 
        BaseVehicleUserDto baseVehicleUserDto = userVehicleClient.cancelTaxiPassenger(cancelTaxiPassengerVo);
        if (baseVehicleUserDto==null) {
            // TODO 本地无法调通
//            throw new RuntimeException("取消订单失败");
        }
        order.setAppUserId(null);
        baseMapper.updateById(order);
        XpOrderCancel xpOrderCancel = new XpOrderCancel();
        xpOrderCancel.setOrderId(orderId);
        xpOrderCancel.setUserId(Long.valueOf(uid));
        xpOrderCancel.setCancelSource(1);
        xpOrderCancel.setCancelReason("用户取消订单");
        xpOrderCancelService.save(xpOrderCancel);
 
 
        // 设置当天的取消次数缓存
        Object cacheObject = redisService.getCacheObject("CANCEL_ORDER_" + uid);
        if (cacheObject == null) {
            redisService.setCacheCancelOrder("CANCEL_ORDER_" + uid, 1);
        } else {
            Integer i = Integer.valueOf(cacheObject.toString());
            redisService.setCacheCancelOrder("CANCEL_ORDER_" + uid, i + 1);
        }
 
        // 下发命令
        if(order.getStatus()>1){
            PushOrderDto pushOrderDto = new PushOrderDto();
            pushOrderDto.setOrderId(order.getId().toString());
            pushOrderDto.setVin(xpVehicle.getVehicleVin());
            pushOrderDto.setOperation_type(OrderOperationType.VEHICLE_CANCEL_ORDER);
            orderMissionClient.cancelOrder(pushOrderDto);
        }
 
    }
 
    @Override
    @Transactional
    public void cancelOrder(String orderId) {
        XpOrder order = this.getById(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在",I18nKeyConstant.ORDER_NOT_EXISTS);
        }
        order.setStatus(0);
        baseMapper.updateById(order);
        XpOrderCancel xpOrderCancel = new XpOrderCancel();
        xpOrderCancel.setOrderId(Long.valueOf(orderId));
        xpOrderCancel.setUserId(1l);
        xpOrderCancel.setCancelSource(4);
        xpOrderCancel.setCancelReason("系统取消订单");
        xpOrderCancel.setCreateTime(LocalDateTime.now());
        xpOrderCancelService.save(xpOrderCancel);
 
 
        R<XpVehicle> xpVehicleR = xpVehicleClient.queryById(order.getVehicleId());
        XpVehicle xpVehicle = xpVehicleR.getData();
 
 
        // 消息推送
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> content = new HashMap<>();
        content.put("orderId", order.getId());
        content.put("status", OrderStatusEnum.CANCELED.getCode());
        params.put("type", PushMessageTypeEnum.ORDER_STATUS.getDesc());
        params.put("content", com.alibaba.fastjson2.JSONObject.toJSONString(content));
        params.put("timestamp", new Date().getTime() + "");
        String message = JSONObject.toJSONString(params);
        SendMessageDTO sendMessageDTO = new SendMessageDTO();
        sendMessageDTO.setMessage(message);
        sendMessageDTO.setAppUserId(String.valueOf(order.getAppUserId()));
        xpPushMessageClient.sendStatus(sendMessageDTO);
        log.info("订单取消消息推送完毕");
 
        // 下发命令
        if(order.getStatus()>1){
            PushOrderDto pushOrderDto = new PushOrderDto();
            pushOrderDto.setOrderId(order.getId().toString());
            pushOrderDto.setVin(xpVehicle.getVehicleVin());
            pushOrderDto.setOperation_type(OrderOperationType.CLOUD_CANCEL_ORDER);
            orderMissionClient.cancelOrder(pushOrderDto);
        }
 
    }
 
    /**
     * 评价订单
     *
     * @param dto
     * @param uid
     */
    @Override
    @Transactional
    public void comment(XpOrderCommentDto dto, String uid) {
        XpOrder xpOrder = this.getById(dto.getOrderId());
        if (xpOrder == null) {
            throw new ServiceException("订单不存在",I18nKeyConstant.ORDER_NOT_EXISTS);
        }
        if (!xpOrder.getAppUserId().toString().equals(uid)) {
            throw new ServiceException("订单不存在",I18nKeyConstant.ORDER_NOT_EXISTS);
        }
        if (xpOrder.getStatus() != 9) {
            throw new ServiceException("订单状态错误",I18nKeyConstant.ORDER_STATUS_ERROR);
        }
        xpOrder.setAppUserId(null);
        xpOrder.setStatus(10);
        baseMapper.updateById(xpOrder);
 
        XpOrderEvaluate evaluate = new XpOrderEvaluate();
        evaluate.setOrderId(xpOrder.getId());
        evaluate.setVehicleId(xpOrder.getVehicleId());
        evaluate.setAppUserId(Long.valueOf(uid));
        evaluate.setOrderRating(dto.getOrderRating());
        evaluate.setEvaluateTime(LocalDateTime.now());
        evaluate.setFeedbackContent(dto.getFeedbackContent());
        evaluate.setFeedbackPictures(dto.getFeedbackPictures());
        evaluate.setFeedbackTypeId(dto.getFeedbackTypeId());
        evaluate.setCreateTime(LocalDateTime.now());
        xpOrderEvaluateService.save(evaluate);
    }
 
    @Override
    public R<String> updateOrderStatus(Long orderId, Integer status) {
        XpOrder xpOrder = this.getById(orderId);
        if (Objects.isNull(xpOrder)) {
            return R.fail("订单不存在");
        }
        if (xpOrder.getStatus() == 0) {
            return R.fail("订单已取消");
        }
        xpOrder.setStatus(status);
        switch (status) {
            case 4:
                // 查询起点点位
                Long startPointId = xpOrder.getStartPointId();
                XpPoint xpPoint = xpPointClient.queryById(startPointId).getData();
                // 添加取消订单定时任务job  时间为点位限停时长
                Map<String, ? extends Object> cancelJobMaps =
                        new ImmutableMap.Builder<String, Long>().
                                put("id", xpOrder.getId())
                                .build();
                QuartzManager.addJob(
                        OrderCancelJob.class,
                        (OrderCancelJob.name + xpOrder.getId()).toUpperCase(),
                        TimeJobType.ORDER_CANCEL,
                        DateUtils.localDateTimeToDate(LocalDateTime.now().plusMinutes(xpPoint.getParkingTimeLimit())),
                        cancelJobMaps
                );
                // 车辆到达上车点时间
                xpOrder.setArrivalTime(LocalDateTime.now());
                break;
            case 5:
                // 删除定时任务job
                QuartzManager.removeJob((OrderCancelJob.name + xpOrder.getId()).toUpperCase(), TimeJobType.ORDER_CANCEL);
                break;
            case 6:
                // 行程开始时间
                xpOrder.setTripBegin(LocalDateTime.now());
                break;
            case 7:
                // 查询自动结束行程时间
                Integer arriveTime = xpSystemSettingClient.getOrderFinishTime().getData();
                // 添加自动结束行程定时任务job
                Map<String, ? extends Object> endTripJobMaps =
                        new ImmutableMap.Builder<String, Long>().
                                put("id", xpOrder.getId())
                                .build();
                QuartzManager.addJob(
                        EndTripJob.class,
                        (EndTripJob.name + xpOrder.getId()).toUpperCase(),
                        TimeJobType.END_TRIP,
                        DateUtils.localDateTimeToDate(LocalDateTime.now().plusMinutes(arriveTime)),
                        endTripJobMaps
                );
                break;
        }
        this.updateById(xpOrder);
        return R.ok();
    }
 
    @Override
    public void endTrip(Long orderId, String uid) {
        List<XpOrderDetail> xpOrderDetails = new ArrayList<>();
        // 起步价格明细
        List<FareBreakdownDetailVo> start = new ArrayList<>();
        // 里程费价格明细
        List<FareBreakdownDetailVo> mileage = new ArrayList<>();
        // 时长费价格明细
        List<FareBreakdownDetailVo> duration = new ArrayList<>();
        // 远途费价格明细
        List<FareBreakdownDetailVo> longDistance = new ArrayList<>();
        XpOrder order = this.getById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
 
        if (order.getStatus() != 7) {
            throw new RuntimeException("订单状态错误");
        }
        order.setStatus(8);
        order.setAppUserId(null);
        order.setTripEnd(LocalDateTime.now());
        order.setMileageKilometers(80.0);
        baseMapper.updateById(order);
        // 解绑用户与车辆关系
        CancelTaxiPassengerVo cancelTaxiPassengerVo = new CancelTaxiPassengerVo();
        XpVehicle vehicle = xpVehicleClient.queryById(order.getVehicleId()).getData();
        if (vehicle != null) {
            cancelTaxiPassengerVo.setVin(vehicle.getVehicleVin());
            cancelTaxiPassengerVo.setUid(uid);
            cancelTaxiPassengerVo.setOrderNo(order.getOrderNumber());
            // TODO 加配置文件取
            cancelTaxiPassengerVo.setAppId("");
            userVehicleClient.cancelTaxiPassenger(cancelTaxiPassengerVo);
 
            // 修改车辆接单状态
            vehicle.setState(0);
            xpVehicleClient.updateVehicleById(vehicle);
        }
 
 
 
        // 根据订单所属开通城市id 查询定价
        R<XpPricing> pricingByCityId = xpPricingClient.getPricingByCid(order.getCityId());
        XpPricing pricing = pricingByCityId.getData();
        if (pricing == null) {
            throw new ServiceException("当前城市未配置定价规则", I18nKeyConstant.ORDER_PRICING_NOT_EXISTS);
        }
        // 费用
//        // 查询订单轨迹
//        List<OrderTrajectory> trajectories = mongoTemplate.find(
//                new Query(Criteria.where("orderId").is(orderId))
//                        .with(Sort.by(Sort.Direction.ASC, "locatetime")),
//                OrderTrajectory.class
//        );
//        List<TaxiPricingDemoService.GpsPoint> gpsPoints = new ArrayList<>();
//        for (OrderTrajectory trajectory : trajectories) {
//            TaxiPricingDemoService.GpsPoint point = new TaxiPricingDemoService.GpsPoint(trajectory.getDistance(), trajectory.getLocatetime());
//            gpsPoints.add(point);
//        }
    // 补充临时轨迹数据
        List<TaxiPricingDemoService.GpsPoint> gpsPoints = TaxiPricingDemoService.createMockGpsPoints(DateUtils.toDate(order.getCreateTime()));
 
 
        TaxiPricingDemoService.PricingConfig config = new TaxiPricingDemoService.PricingConfig();
        JSONArray startingFareJsonArray = JSONArray.parseArray(pricing.getStartingFareJson());
        if(pricing.getPricingType()==1){
            JSONObject basicPricingJson = JSONObject.parseObject(pricing.getBasicPricingJson());
            config.peaks.add(new TaxiPricingDemoService.PricingRule("高峰期", basicPricingJson.getString("num21").split(" - ")[0], basicPricingJson.getString("num21").split(" - ")[1], Double.parseDouble(basicPricingJson.getString("num24")), Double.parseDouble(basicPricingJson.getString("num25")), Double.parseDouble(basicPricingJson.getString("num26")), Double.parseDouble(basicPricingJson.getString("num27")), Double.parseDouble(basicPricingJson.getString("num28"))));
            config.peaks.add(new TaxiPricingDemoService.PricingRule("高峰期", basicPricingJson.getString("num22").split(" - ")[0], basicPricingJson.getString("num22").split(" - ")[1], Double.parseDouble(basicPricingJson.getString("num24")), Double.parseDouble(basicPricingJson.getString("num25")), Double.parseDouble(basicPricingJson.getString("num26")), Double.parseDouble(basicPricingJson.getString("num27")), Double.parseDouble(basicPricingJson.getString("num28"))));
            config.night = new TaxiPricingDemoService.PricingRule("夜间行驶", basicPricingJson.getString("num14").split(" - ")[0], basicPricingJson.getString("num14").split(" - ")[1], Double.parseDouble(basicPricingJson.getString("num16")), Double.parseDouble(basicPricingJson.getString("num17")), Double.parseDouble(basicPricingJson.getString("num18")), Double.parseDouble(basicPricingJson.getString("num19")), Double.parseDouble(basicPricingJson.getString("num20")));
            config.holiday = new TaxiPricingDemoService.PricingRule("节假日", "00:00", "23:59", Double.parseDouble(basicPricingJson.getString("num30")), Double.parseDouble(basicPricingJson.getString("num31")), Double.parseDouble(basicPricingJson.getString("num32")), Double.parseDouble(basicPricingJson.getString("num33")), Double.parseDouble(basicPricingJson.getString("num34")));
            // --- 远途加价区间配置 (关键修改) ---
            // 1. 超过 num1(12) 不足 num2(20), 加收 num3(1.2)
            config.longSteps.add(new TaxiPricingDemoService.LongRangeStep(Double.parseDouble(basicPricingJson.getString("num6")), Double.parseDouble(basicPricingJson.getString("num7")), Double.parseDouble(basicPricingJson.getString("num8"))));
            // 2. 超过 num4(20) 不足 num5(35), 加收 num6(2.0)
            config.longSteps.add(new TaxiPricingDemoService.LongRangeStep(Double.parseDouble(basicPricingJson.getString("num9")), Double.parseDouble(basicPricingJson.getString("num10")), Double.parseDouble(basicPricingJson.getString("num11"))));
            // 3. 超过 num7(35) 以后, 加收 num8(3.5) -> numEnd 传个极大值
            config.longSteps.add(new TaxiPricingDemoService.LongRangeStep(Double.parseDouble(basicPricingJson.getString("num12")), 999999, Double.parseDouble(basicPricingJson.getString("num13"))));
        }
        for (int i = 0; i < startingFareJsonArray.size(); i++) {
            com.alibaba.fastjson.JSONObject jsonObject = startingFareJsonArray.getJSONObject(i);
            String num1 = jsonObject.getString("num1");
            String num2 = jsonObject.getString("num2");
            String num3 = jsonObject.getString("num3");
            String num4 = jsonObject.getString("num4");
            String num5 = jsonObject.getString("num5");
            String num6 = jsonObject.getString("num6");
            String num7 = jsonObject.getString("num7");
            config.normals.add(new TaxiPricingDemoService.PricingRule("普通时段", num1, num2, Double.parseDouble(num3), Double.parseDouble(num4), Double.parseDouble(num5), Double.parseDouble(num6), Double.parseDouble(num7)));
        }
 
        TaxiPricingDemoService.TaxiPricingService service = new TaxiPricingDemoService.TaxiPricingService();
        Map<String, BigDecimal> bill = service.calculateOrderPrice(DateUtils.toDate(order.getCreateTime()), order.getMileageKilometers(), gpsPoints, config);
        System.err.println("======= 订单计费账单 =======");
        bill.forEach((detail, price) -> System.err.println(detail + ": " + price + " 元"));
 
        BigDecimal totalAmount = bill.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        System.err.println("--------------------------");
        System.err.println("应付总额: " + totalAmount + " 元");
        BigDecimal startMoney = BigDecimal.ZERO;
         // 默认费率1
        double priceRate = 1;
        if (pricing.getIsDynamicPrice() == 1) {
            // 先判断是否已经调价过了
            Object userDynamicPriceObj = redisService.getCacheObject("USER_DYNAMIC_PRICE_" + order.getCityId() + "_" + uid);
            if (userDynamicPriceObj != null) {
                // 是否调价过了
                priceRate = Double.parseDouble(userDynamicPriceObj.toString());
            } else {
                // 没有调过
                //是否触发动态调价 redis获取
                Object dynamicPriceObj = redisService.getCacheObject("DYNAMIC_PRICE_" + order.getCityId());
                if (dynamicPriceObj != null) {
                    JSONObject jsonObject = JSONObject.parseObject(pricing.getDynamicPricingJson());
                    // 触发动态调价
                    // value=时间
                    String timeStr = dynamicPriceObj.toString();
                    // 判断当前距离这个时间范围的新增订单数(排除取消) / 上浮数量 算出应该增加的价格率
                    Integer num = this.getOrderNum(new GetOrderNumDto(timeStr, order.getCityId()));
                    // X单上升一次调价
                    Integer orderNum = getOrderNum(jsonObject, 4);
                    // 需要调价的次数
                    int count = num / orderNum;
                    if (count > 0) {
                        // 计算每次上升的费率
                        Integer upRate = getOrderNum(jsonObject, 5);
                        BigDecimal divide = new BigDecimal(upRate).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
                        for (int i = count; i > 0; i--) {
                            // 当前费率+(费率*上升百分比)
                            priceRate = new BigDecimal(priceRate).multiply(divide).add(new BigDecimal(priceRate)).setScale(2, RoundingMode.HALF_UP).doubleValue();
                        }
                        // 冷却时间
                        Integer time = getOrderNum(jsonObject, 6);
                        // 触发调价了
                        redisService.setCacheObject("USER_DYNAMIC_PRICE_" + order.getCityId() + "_" + uid, priceRate, time.longValue(), TimeUnit.MINUTES);
                    }
 
                }
            }
 
        }
        // 封装费用明细数据
        for (Map.Entry<String, BigDecimal> stringBigDecimalEntry : bill.entrySet()) {
            // 封装起步价
            FareBreakdownDetailVo startDetail = new FareBreakdownDetailVo();
            String key = stringBigDecimalEntry.getKey();
            if (key.contains("起步价")) {
                startDetail.setTime(key.split("\\|")[1]);
                startDetail.setMoney(stringBigDecimalEntry.getValue());
                startMoney = startMoney.add(stringBigDecimalEntry.getValue());
                if (key.contains("普通时段")) {
                    startDetail.setType(1);
                } else if (key.contains("夜间")) {
                    startDetail.setType(2);
                } else if (key.contains("高峰")) {
                    startDetail.setType(3);
                } else if (key.contains("节假")) {
                    startDetail.setType(4);
                }
                String durationAndMileage = key.split("\\|")[2];
                startDetail.setDuration(Double.valueOf(durationAndMileage.split("&")[0]));
                startDetail.setMileage(new BigDecimal(durationAndMileage.split("&")[1]));
                start.add(startDetail);
            }
            // 封装里程费
            if (!key.contains("起步") && !key.contains("时长") && !key.contains("远途") && !key.contains("distance")) {
                FareBreakdownDetailVo mileageDetail = new FareBreakdownDetailVo();
                if (key.contains("普通时段")) {
                    mileageDetail.setType(1);
                    String key1 = "distance普通时段|" + key.split("\\|")[1];
                    String key2 = "普通时段|" + key.split("\\|")[1];
                    BigDecimal distance = bill.get(key1);
                    BigDecimal money = bill.get(key2);
                    mileageDetail.setMileage(distance);
                    order.setStartMoney(money.multiply(BigDecimal.valueOf(priceRate)));
                    mileageDetail.setMoney(money.multiply(BigDecimal.valueOf(priceRate)));
                } else if (key.contains("夜间行驶")) {
                    mileageDetail.setType(2);
                    String key1 = "distance夜间行驶|" + key.split("\\|")[1];
                    String key2 = "夜间行驶|" + key.split("\\|")[1];
                    BigDecimal distance = bill.get(key1);
                    BigDecimal money = bill.get(key2);
                    mileageDetail.setMileage(distance);
                    order.setStartMoney(money.multiply(BigDecimal.valueOf(priceRate)));
 
                    mileageDetail.setMoney(money.multiply(BigDecimal.valueOf(priceRate)));
                } else if (key.contains("高峰期")) {
                    mileageDetail.setType(3);
                    String key1 = "distance高峰期|" + key.split("\\|")[1];
                    String key2 = "高峰期|" + key.split("\\|")[1];
                    BigDecimal distance = bill.get(key1);
                    BigDecimal money = bill.get(key2);
                    mileageDetail.setMileage(distance);
                    order.setStartMoney(money.multiply(BigDecimal.valueOf(priceRate)));
 
                    mileageDetail.setMoney(money.multiply(BigDecimal.valueOf(priceRate)));
                } else if (key.contains("节假")) {
                    mileageDetail.setType(4);
                    String key1 = "distance节假日|" + key.split("\\|")[1];
                    String key2 = "节假日|" + key.split("\\|")[1];
                    BigDecimal distance = bill.get(key1);
                    BigDecimal money = bill.get(key2);
                    mileageDetail.setMileage(distance);
                    order.setStartMoney(money.multiply(BigDecimal.valueOf(priceRate)));
                    mileageDetail.setMoney(money.multiply(BigDecimal.valueOf(priceRate)));
                }
                mileage.add(mileageDetail);
            }
            // 封装时长费
            FareBreakdownDetailVo timeDetail = new FareBreakdownDetailVo();
            if (key.contains("时长费")) {
                timeDetail.setType(startDetail.getType());
                timeDetail.setMoney(stringBigDecimalEntry.getValue());
                timeDetail.setDuration(Double.valueOf(key.split("&")[1]));
                duration.add(timeDetail);
            }
            // 封装远途费
            FareBreakdownDetailVo longDetail = new FareBreakdownDetailVo();
            if (key.contains("远途费")) {
                longDetail.setType(startDetail.getType());
                longDetail.setMoney(stringBigDecimalEntry.getValue());
                longDetail.setMileage(new BigDecimal(key.split("&")[1]));
                longDistance.add(longDetail);
            }
        }
        for (FareBreakdownDetailVo fareBreakdownDetailVo : start) {
            XpOrderDetail xpOrderDetail = new XpOrderDetail();
            BeanUtils.copyProperties(fareBreakdownDetailVo, xpOrderDetail);
            xpOrderDetail.setOrderId(orderId);
            xpOrderDetail.setDetailType(1);
            xpOrderDetail.setCreateTime(LocalDateTime.now());
            xpOrderDetails.add(xpOrderDetail);
        }
        BigDecimal mileageMoney = BigDecimal.ZERO;
        for (FareBreakdownDetailVo fareBreakdownDetailVo : mileage) {
            XpOrderDetail xpOrderDetail = new XpOrderDetail();
            BeanUtils.copyProperties(fareBreakdownDetailVo, xpOrderDetail);
            xpOrderDetail.setOrderId(orderId);
            xpOrderDetail.setDetailType(2);
            xpOrderDetail.setCreateTime(LocalDateTime.now());
            mileageMoney = mileageMoney.add(fareBreakdownDetailVo.getMoney());
            xpOrderDetails.add(xpOrderDetail);
        }
        order.setMileageMoney(mileageMoney);
        for (XpOrderDetail xpOrderDetail : xpOrderDetails) {
            xpOrderDetailMapper.insert(xpOrderDetail);
        }
        for (XpOrderDetail xpOrderDetail : xpOrderDetails) {
            if (xpOrderDetail.getDetailType() == 1){
                order.setDurationType(xpOrderDetail.getType());
                order.setDurationMoney(xpOrderDetail.getMoney());
                order.setDuration(Double.parseDouble(xpOrderDetail.getDuration() + ""));
            }else{
                order.setLongDistanceType(order.getDurationType());
                order.setLongDistance(xpOrderDetail.getMileage().doubleValue());
                order.setLongDistancemoney(xpOrderDetail.getMoney());
            }
 
        }
 
        BigDecimal orderMoney = startMoney.add(mileageMoney).add(order.getDurationMoney() != null ? order.getDurationMoney() : BigDecimal.ZERO)
                .add(order.getLongDistancemoney() != null ? order.getLongDistancemoney() : BigDecimal.ZERO)
                .add(order.getWaitMoney()!=null?order.getWaitMoney():BigDecimal.ZERO);
        order.setOrderMoney(orderMoney);
        order.setAppUserId(null);
        baseMapper.updateById(order);
        if (order.getCouponId() != null) {
            UseUserCouponDto useUserCouponDto = new UseUserCouponDto();
            useUserCouponDto.setUserId(Long.valueOf(uid));
            useUserCouponDto.setTotalAmount(order.getOrderMoney().doubleValue());
            useUserCouponDto.setOpenCityId(order.getCityId());
            useUserCouponDto.setOrderId(orderId);
            useUserCouponDto.setUserCouponId(order.getCouponId());
            xpAppUserCouponClient.useUserCoupon(useUserCouponDto);
        }
       // 计算完价格后 挑选优惠券
        GetUserCouponDto getUserCouponDto = new GetUserCouponDto();
        getUserCouponDto.setUserId(Long.valueOf(uid));
        getUserCouponDto.setTotalAmount(order.getOrderMoney().doubleValue());
        R<UserCouponVo> userCouponVoR = xpAppUserCouponClient.getUserCoupon(getUserCouponDto);
        UserCouponVo userCouponVo = userCouponVoR.getData();
        if (userCouponVo != null) {
            order.setCouponId(userCouponVo.getId());
            order.setCouponMoney(BigDecimal.valueOf(userCouponVo.getMoney()));
        }
        order.setAppUserId(null);
        baseMapper.updateById(order);
 
 
 
 
 
        // 结束后的车辆操作
        if(vehicle!=null){
            // 修改车辆状态
            vehicle.setState(0);
 
            // 获取配置 根据配置判断是否该收车 如果是则找到收车点位进行收车操作
            R<XpTaskRule> xpTaskRuleR = xpTaskRuleClient.queryDetail();
            XpTaskRule xpTaskRule = xpTaskRuleR.getData();
 
            // 生成新的巡游单子 回到最新巡游的初始起点位置
            XpCruiseOrder xpCruiseOrders = xpCruiseOrderMapper.selectOne(new LambdaQueryWrapper<XpCruiseOrder>().eq(XpCruiseOrder::getVehicleId, vehicle.getId()).eq(XpCruiseOrder::getStatus, 2).orderByDesc(BaseModel::getCreateTime).last("limit 1"));
            int temp=0;
            if(xpCruiseOrders==null){
                temp=1;
                //特殊情况 可能没有产生终止的订单  (到站点就被正常接单了)所以找正常订单
                xpCruiseOrders=xpCruiseOrderMapper.selectOne(new LambdaQueryWrapper<XpCruiseOrder>().eq(XpCruiseOrder::getVehicleId, vehicle.getId()).eq(XpCruiseOrder::getStatus, 3).orderByDesc(BaseModel::getCreateTime).last("limit 1"));
            }
            XpCruiseOrder xpCruiseOrder = new XpCruiseOrder();
            xpCruiseOrder.setVehicleId(vehicle.getId());
            xpCruiseOrder.setFleetId(vehicle.getFleetId());
            xpCruiseOrder.setVehicleVin(vehicle.getVehicleVin());
            xpCruiseOrder.setOrderType(2);
            // 返程起点是当前正常订单的终点
            xpCruiseOrder.setStartPointId(order.getEndPointId());
            xpCruiseOrder.setStartPointName(order.getEndPointName());
            xpCruiseOrder.setStartLon(order.getEndLon());
            xpCruiseOrder.setStartLat(order.getEndLat());
 
            // 完成的直接走终点   终止的走起点
            if(temp==0){
                xpCruiseOrder.setEndPointId(xpCruiseOrders.getStartPointId());
                xpCruiseOrder.setEndPointName(xpCruiseOrders.getStartPointName());
                xpCruiseOrder.setEndLon(xpCruiseOrders.getStartLon());
                xpCruiseOrder.setEndLat(xpCruiseOrders.getStartLat());
            }else {
                xpCruiseOrder.setEndPointId(xpCruiseOrders.getEndPointId());
                xpCruiseOrder.setEndPointName(xpCruiseOrders.getEndPointName());
                xpCruiseOrder.setEndLon(xpCruiseOrders.getEndLon());
                xpCruiseOrder.setEndLat(xpCruiseOrders.getEndLat());
            }
 
 
            xpCruiseOrder.setStatus(1);
            xpCruiseOrder.setLastOrderId(xpCruiseOrders.getId());
            xpCruiseOrder.setCreateTime(LocalDateTime.now());
            xpCruiseOrder.setId("XU"+ IdUtil.fastUUID());
 
            // 判断当前时分秒是否大于收车时间
            LocalTime vehicleCollectionTime = xpTaskRule.getVehicleCollectionTime();
            if (vehicleCollectionTime.isBefore(LocalTime.now())) {
                vehicle.setOperatingStatus(3);
                //找到车辆的收车点位 更新终点点位
                R<XpCruiseOrder> returnCruisePoint = xpCruisePlanClient.findReturnCruisePoint(xpCruiseOrder);
                xpCruiseOrder = returnCruisePoint.getData();
            }
            xpVehicleClient.updateVehicleById(vehicle);
 
            xpCruiseOrderMapper.insert(xpCruiseOrder);
 
 
            R<XpPoint> xpPointR = xpPointClient.queryById(order.getEndPointId());
            XpPoint data = xpPointR.getData();
            //下发命令
            // 添加自动结束行程定时任务job
            Map<String, ? extends Object> jobMaps =
                    new ImmutableMap.Builder<String, String>().
                            put("id", xpCruiseOrder.getId())
                            .build();
            QuartzManager.addJob(
                    AddCruiseMissionJob.class,
                    (AddCruiseMissionJob.name + xpCruiseOrder.getId()).toUpperCase(),
                    TimeJobType.ADD_CRUISE_MISSION,
                    DateUtils.localDateTimeToDate(LocalDateTime.now().plusMinutes(data.getParkingTimeLimit())),
                    jobMaps
            );
 
 
        }
 
 
 
 
 
 
 
 
 
 
 
    }
 
 
    private MileageDto mileageType(MileageDto param, JSONArray startingFareJsonArray, Date mileageDate, LocalDateTime begin, String num14, String num16, String num17, String num21, String num22, String num24, String num25, String num30, String num31) {
        // 计算出是在哪个普通时间段内
        for (Object o : startingFareJsonArray) {
            JSONObject startingFare = (JSONObject) o;
            Calendar calendarStart = Calendar.getInstance();
            calendarStart.setTime(mileageDate);
            calendarStart.set(Calendar.HOUR_OF_DAY, Integer.valueOf(startingFare.getString("num1").split(":")[0]));
            calendarStart.set(Calendar.MINUTE, Integer.valueOf(startingFare.getString("num1").split(":")[1]));
 
            Calendar calendarEnd = Calendar.getInstance();
            calendarEnd.setTime(mileageDate);
            calendarEnd.set(Calendar.HOUR_OF_DAY, Integer.valueOf(startingFare.getString("num2").split(":")[0]));
            calendarEnd.set(Calendar.MINUTE, Integer.valueOf(startingFare.getString("num2").split(":")[1]));
            // 找到符合条件的直接跳出循环
            if (mileageDate.getTime() > calendarStart.getTimeInMillis() && mileageDate.getTime() < calendarEnd.getTimeInMillis()) {
                param.setMileage(startingFare.getString("num6"));
                param.setTime(startingFare.getString("num7"));
                param.setMileageTypeTemp(1);
                break;
            }
        }
        // 根据时间确定是否使用基础信息配置
        LocalDateTime createTime = begin;
        Date date = DateUtils.toDate(createTime);
        LocalDate localDate = DateUtils.toLocalDate(date);
        // 判断是否为夜间行驶 获取里程费用
        Calendar calendarStart = Calendar.getInstance();
        calendarStart.setTime(date);
        calendarStart.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num14.split("-")[0].split(":")[0]));
        calendarStart.set(Calendar.MINUTE, Integer.valueOf(num14.split("-")[0].split(":")[1]));
        Calendar calendarEnd = Calendar.getInstance();
        calendarEnd.setTime(date);
        calendarEnd.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num14.split("-")[1].split(":")[0]));
        calendarEnd.set(Calendar.MINUTE, Integer.valueOf(num14.split("-")[1].split(":")[1]));
        if (date.getTime() > calendarStart.getTimeInMillis() && date.getTime() < calendarEnd.getTimeInMillis()
        ) {
 
            param.setMileage(num16);
            param.setTime(num17);
            param.setMileageTypeTemp(2);
        }
        // 判断是否为高峰期 获取里程费用
        Calendar calendar1Start = Calendar.getInstance();
        calendar1Start.setTime(date);
        calendar1Start.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num21.split("-")[0].split(":")[0]));
        calendar1Start.set(Calendar.MINUTE, Integer.valueOf(num21.split("-")[0].split(":")[1]));
 
        Calendar calendar1End = Calendar.getInstance();
        calendar1End.setTime(date);
        calendar1End.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num21.split("-")[1].split(":")[0]));
        calendar1End.set(Calendar.MINUTE, Integer.valueOf(num21.split("-")[1].split(":")[1]));
 
        Calendar calendar2Start = Calendar.getInstance();
        calendar2Start.setTime(date);
        calendar2Start.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num22.split("-")[0].split("-")[0].split(":")[0]));
        calendar2Start.set(Calendar.MINUTE, Integer.valueOf(num22.split("-")[0].split("-")[0].split(":")[1]));
 
        Calendar calendar2End = Calendar.getInstance();
        calendar2End.setTime(date);
        calendar2End.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num22.split("-")[1].split(":")[0]));
        calendar2End.set(Calendar.MINUTE, Integer.valueOf(num22.split("-")[1].split(":")[1]));
        if ((date.getTime() > calendar1Start.getTimeInMillis() && date.getTime() < calendar1End.getTimeInMillis())
                || (date.getTime() > calendar2Start.getTimeInMillis() && date.getTime() < calendar2End.getTimeInMillis())) {
 
            param.setMileage(num24);
            param.setTime(num25);
            param.setMileageTypeTemp(3);
        }
        // 判断当前是否属于节假日 获取里程费用
        boolean holiday = holidayUtil.isHoliday(localDate);
        if (holiday) {
            // 判断是否为节假日 起步价修改
            param.setMileage(num30);
            param.setTime(num31);
            param.setMileageTypeTemp(4);
        }
        return param;
    }
 
    private void calculateStartingFare(List<OrderTrajectory> trajectories, LocalDateTime tripBegin, boolean startFlag, Double startDistance, JSONArray startingFareJsonArray, String num3, String num4, String num5, Date endDate, XpOrder order, String num14, String num15, String num16, String num17, Integer startType, String num21, String num22, String num23, String num24, String num25, String num29, String num30, String num31, SimpleDateFormat timeFormat, Date startDate, List<FareBreakdownDetailVo> start) {
        String startTime;
        String num6;
        String num7;
        String endTime;
        // 根据订单创建时间确定是否使用基础信息配置
        LocalDateTime createTime = order.getCreateTime();
        Date date = DateUtils.toDate(createTime);
        LocalDate localDate = DateUtils.toLocalDate(date);
        for (Object o : startingFareJsonArray) {
            JSONObject startingFare = (JSONObject) o;
            Calendar calendarStart = Calendar.getInstance();
            calendarStart.setTime(date);
            calendarStart.set(Calendar.HOUR_OF_DAY, Integer.valueOf(startingFare.getString("num1").split(":")[0]));
            calendarStart.set(Calendar.MINUTE, Integer.valueOf(startingFare.getString("num1").split(":")[1]));
 
            Calendar calendarEnd = Calendar.getInstance();
            calendarEnd.setTime(date);
            calendarEnd.set(Calendar.HOUR_OF_DAY, Integer.valueOf(startingFare.getString("num2").split(":")[0]));
            calendarEnd.set(Calendar.MINUTE, Integer.valueOf(startingFare.getString("num2").split(":")[1]));
            // 找到符合条件的直接跳出循环
            if (date.getTime() > calendarStart.getTimeInMillis() && date.getTime() < calendarEnd.getTimeInMillis()) {
                num3 = startingFare.getString("num3");
                num4 = startingFare.getString("num4");
                num5 = startingFare.getString("num5");
                num6 = startingFare.getString("num6");
                num7 = startingFare.getString("num7");
                startTime = startingFare.getString("num1");
                endTime = startingFare.getString("num2");
                break;
            }
        }
        // 判断是否为夜间行驶 起步价修改
        Calendar calendarStart = Calendar.getInstance();
        calendarStart.setTime(date);
        calendarStart.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num14.split("-")[0].split(":")[0]));
        calendarStart.set(Calendar.MINUTE, Integer.valueOf(num14.split("-")[0].split(":")[1]));
        Calendar calendarEnd = Calendar.getInstance();
        calendarEnd.setTime(date);
        calendarEnd.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num14.split("-")[1].split(":")[0]));
        calendarEnd.set(Calendar.MINUTE, Integer.valueOf(num14.split("-")[1].split(":")[1]));
        if (date.getTime() > calendarStart.getTimeInMillis() && date.getTime() < calendarEnd.getTimeInMillis()
        ) {
            num3 = num15;
            num6 = num16;
            num7 = num17;
            startType = 2;
 
        }
        // 判断是否为高峰期
        Calendar calendar1Start = Calendar.getInstance();
        calendar1Start.setTime(date);
        calendar1Start.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num21.split("-")[0].split(":")[0]));
        calendar1Start.set(Calendar.MINUTE, Integer.valueOf(num21.split("-")[0].split(":")[1]));
 
        Calendar calendar1End = Calendar.getInstance();
        calendar1End.setTime(date);
        calendar1End.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num21.split("-")[1].split(":")[0]));
        calendar1End.set(Calendar.MINUTE, Integer.valueOf(num21.split("-")[1].split(":")[1]));
 
        Calendar calendar2Start = Calendar.getInstance();
        calendar2Start.setTime(date);
        calendar2Start.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num22.split("-")[0].split("-")[0].split(":")[0]));
        calendar2Start.set(Calendar.MINUTE, Integer.valueOf(num22.split("-")[0].split("-")[0].split(":")[1]));
 
        Calendar calendar2End = Calendar.getInstance();
        calendar2End.setTime(date);
        calendar2End.set(Calendar.HOUR_OF_DAY, Integer.valueOf(num22.split("-")[1].split(":")[0]));
        calendar2End.set(Calendar.MINUTE, Integer.valueOf(num22.split("-")[1].split(":")[1]));
        // 判断是否为高峰期 起步价,里程费,时长费修改
        if ((date.getTime() > calendar1Start.getTimeInMillis() && date.getTime() < calendar1End.getTimeInMillis())
                || (date.getTime() > calendar2Start.getTimeInMillis() && date.getTime() < calendar2End.getTimeInMillis())) {
            num3 = num23;
            num6 = num24;
            num7 = num25;
            startType = 3;
        }
        // 判断当前是否属于节假日
        boolean holiday = holidayUtil.isHoliday(localDate);
        if (holiday) {
            // 判断是否为节假日 起步价修改
            num3 = num29;
            num6 = num30;
            num7 = num31;
            startType = 4;
        }
        // 起步价价格明细封装
        FareBreakdownDetailVo fareBreakdownDetailVo = new FareBreakdownDetailVo();
        fareBreakdownDetailVo.setType(startType);
        fareBreakdownDetailVo.setTime(timeFormat.format(startDate) + "-" + timeFormat.format(endDate));
        fareBreakdownDetailVo.setMileage(new BigDecimal(startDistance / 1000).setScale(2, RoundingMode.HALF_UP));
 
        // 计算startDate和endDate相差多少分钟
        // 将 Date 转换为 LocalDateTime
        LocalDateTime startDateTime = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime endDateTime = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
 
        // 计算时间差(单位:分钟)
        long minutesDifference = Duration.between(startDateTime, endDateTime).toMinutes();
        fareBreakdownDetailVo.setDuration((double) minutesDifference);
        fareBreakdownDetailVo.setMoney(new BigDecimal(num3));
        start.add(fareBreakdownDetailVo);
    }
 
    /**
     * 获取配置  4每X单  5上升X%  6冷却
     *
     * @param rule
     * @param num
     * @return
     */
    private Integer getOrderNum(JSONObject rule, int num) {
        Integer param = rule.getInteger("num" + num);
        return param;
    }
 
    @Override
    public R<FareBreakdownVo> fareBreakdown(Long orderId, String uid) {
 
        XpOrder order = this.getById(orderId);
        order.setAppUserId(null);
        // 查询订单轨迹
        List<OrderTrajectory> trajectories = mongoTemplate.find(
                new Query(Criteria.where("orderId").is(orderId))
                        .with(Sort.by(Sort.Direction.ASC, "locatetime")),
                OrderTrajectory.class
        );
 
        FareBreakdownVo res = new FareBreakdownVo();
 
        List<FareBreakdownDetailVo> start = new ArrayList<>();
        List<FareBreakdownDetailVo> mileage = new ArrayList<>();
 
        List<XpOrderDetail> xpOrderDetails = xpOrderDetailMapper.selectList(new LambdaQueryWrapper<XpOrderDetail>().eq(XpOrderDetail::getOrderId, orderId));
        for (XpOrderDetail xpOrderDetail : xpOrderDetails) {
            FareBreakdownDetailVo detail = new FareBreakdownDetailVo();
            detail.setType(xpOrderDetail.getType());
            detail.setTime(xpOrderDetail.getTime());
            detail.setMileage(xpOrderDetail.getMileage());
            detail.setDuration(xpOrderDetail.getDuration());
            if (xpOrderDetail.getDetailType() == 1){
                start.add(detail);
            }else{
                mileage.add(detail);
            }
        }
        List<FareBreakdownDetailVo> duration = new ArrayList<>();
        if (order.getDuration()!=null&&order.getDuration()>0){
            FareBreakdownDetailVo durationDetail = new FareBreakdownDetailVo();
            durationDetail.setType(order.getDurationType());
            durationDetail.setDuration(order.getDuration());
            durationDetail.setMoney(order.getDurationMoney());
            duration.add(durationDetail);
        }
        List<FareBreakdownDetailVo> longDistance = new ArrayList<>();
 
        if (order.getLongDistance()!=null&&order.getLongDistance()>0){
            FareBreakdownDetailVo longDistanceDetail = new FareBreakdownDetailVo();
            longDistanceDetail.setType(order.getLongDistanceType());
            longDistanceDetail.setMileage(BigDecimal.valueOf(order.getLongDistance()));
            longDistanceDetail.setMoney(order.getLongDistancemoney());
            longDistance.add(longDistanceDetail);
        }
        res.setStart( start);
        res.setMileage( mileage);
        res.setDuration( duration);
        res.setLongDistance( longDistance);
        res.setRedPacketMoney(order.getRedPacketMoney());
        res.setCouponMoney(order.getCouponMoney());
        res.setOrderMoney(order.getOrderMoney());
        res.setKilometer(order.getMileageKilometers()==null?BigDecimal.ZERO:BigDecimal.valueOf(order.getMileageKilometers()));
        LocalDateTime createTime = order.getCreateTime();
        LocalDateTime tripEnd = order.getTripEnd();
        if (tripEnd==null){
            tripEnd = LocalDateTime.now();
            order.setTripEnd(tripEnd);
            this.updateById(order);
        }
        // 计算行程时间 单位分钟
        // 计算时间差
        Duration durationBetween = Duration.between(createTime, tripEnd);
 
        // 转换为分钟并保留一位小数
        BigDecimal minutes = BigDecimal.valueOf(durationBetween.getSeconds())
                .divide(BigDecimal.valueOf(60), 1, RoundingMode.HALF_UP);
        res.setTime(minutes);
        return R.ok(res);
    }
 
    @Override
    public R payment(XpOrderPayDto dto, String uid) {
        // mvp版本不做支付 使用优惠券抵扣为0元订单处理 处理订单状态即可
        XpOrder order = this.getById(dto.getOrderId());
        order.setStatus(9);
        order.setAppUserId(null);
        baseMapper.updateById(order);
        return R.ok();
    }
 
    /**
     * 添加订单
     *
     * @param xpOrder
     * @return
     */
    @Override
    public boolean addOrder(XpOrder xpOrder) {
        int insert = this.baseMapper.insert(xpOrder);
        if (insert <= 0) {
            return false;
        }
        return true;
    }
 
 
    @Override
    public XpVehicle queryVehicleByOrderId(Long orderId, String uid) {
        XpOrder xpOrder = this.getById(orderId);
        XpVehicle xpVehicle = xpVehicleClient.queryById(xpOrder.getVehicleId()).getData();
        return xpVehicle;
    }
 
    /**
     * 获取订单数量
     *
     * @param dto
     * @return
     */
    @Override
    public Integer getOrderNum(GetOrderNumDto dto) {
        Long num = this.baseMapper.selectCount(new LambdaQueryWrapper<XpOrder>().eq(XpOrder::getCityId, dto.getOpenCityId()).between(BaseModel::getCreateTime, dto.getTimeStr(), new Date()));
        return num.intValue();
    }
 
    @Override
    public void saveVehicleLocation(OrderTrajectory orderTrajectory) {
        // 查询订单信息
        XpOrder xpOrder = this.getById(orderTrajectory.getOrderId());
 
        // 计算距离
        // 获取上一次定位
        String oldLocation = redisService.getCacheObject(CacheConstants.ORDER_OLD_LOCATION + orderTrajectory.getOrderId());
        if (StringUtils.isEmpty(oldLocation)) {
            // 首次定位
            xpOrder.setMileageKilometers(0D);
            this.updateById(xpOrder);
            orderTrajectory.setDistance(0D);
            // 存储mongo数据
            orderTrajectoryService.create(orderTrajectory);
            // 存储首次定位
            redisService.setCacheObject(CacheConstants.ORDER_OLD_LOCATION + orderTrajectory.getOrderId(), orderTrajectory.getLocation());
        } else {
            Map<String, Double> distance = GeodesyUtil.getDistance(orderTrajectory.getLocation(), oldLocation);
            if (null != distance) {
                Double distance1 = distance.get("WGS84");
                if (distance1 > 50 && xpOrder.getStatus() == 6) {//大于50米表示在移动,且在服务中的时候记录里程
                    xpOrder.setMileageKilometers(BigDecimal.valueOf(xpOrder.getMileageKilometers()).add(new BigDecimal(distance1)).setScale(2, RoundingMode.HALF_EVEN).doubleValue());
                    this.updateById(xpOrder);
                    // 存储本次距离
                    orderTrajectory.setDistance(distance1);
                    // 存储mongo数据
                    orderTrajectoryService.create(orderTrajectory);
                }
            } else {
                log.error("调用高德计算距离出错");
            }
        }
    }
 
    @Override
    public OrderDetailVo orderDetail(Long orderId, String uid) {
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        XpOrder order = this.getById(orderId);
        BeanUtils.copyProperties(order, orderDetailVo);
        // 查询车辆信息
        XpVehicle vehicle = xpVehicleClient.queryById(order.getVehicleId()).getData();
        if (vehicle != null) {
            orderDetailVo.setVehicleCode(vehicle.getVehicleCode());
            orderDetailVo.setPlateNumber(vehicle.getPlateNumber());
            orderDetailVo.setVehicleColor(vehicle.getVehicleColor());
            orderDetailVo.setVehiclePictures(vehicle.getVehiclePictures());
        }
        // 查询评价信息
        XpOrderEvaluate evaluate = xpOrderEvaluateService.lambdaQuery().eq(XpOrderEvaluate::getOrderId, orderId)
                .last("limit 1").one();
        if (evaluate != null) {
            orderDetailVo.setFeedbackPictures(evaluate.getFeedbackPictures());
            orderDetailVo.setFeedbackContent(evaluate.getFeedbackContent());
            orderDetailVo.setOrderRating(evaluate.getOrderRating());
            if (evaluate.getFeedbackTypeId() != null) {
                XpFeedbackType feedbackType = xpSystemSettingClient.getFeedbackTypeById(evaluate.getFeedbackTypeId()).getData();
                orderDetailVo.setFeedbackTypeName(feedbackType.getFeedbackType());
            }
 
        }
//        List<OrderTrajectory> trajectories = mongoTemplate.find(
//                new Query(Criteria.where("orderId").is(orderId))
//                        .with(Sort.by(Sort.Direction.ASC, "locatetime")),
//                OrderTrajectory.class
//        );
        List<TaxiPricingDemoService.GpsPoint> mockGpsPoints = TaxiPricingDemoService.createMockGpsPoints(DateUtils.toDate(order.getCreateTime()));
 
        // 生成轨迹记录
        List<OrderTrajectory> trajectories = TrajectoryGenerator.generateTrajectory(mockGpsPoints);
        orderDetailVo.setTrajectories(trajectories);
        if (order.getTripBegin() != null && order.getTripEnd() != null) {
            // 计算两个时间相差多少分钟
            long minutesDifference = Duration.between(order.getTripBegin(), order.getTripEnd()).toMinutes();
            orderDetailVo.setOrderTime(minutesDifference);
        } else {
            orderDetailVo.setOrderTime(0l);
        }
        if (order.getStartMileage() != null) {
            orderDetailVo.setTotalMileage(order.getStartMileage() + (order.getMileageKilometers() != null ? order.getMileageKilometers() : 0D));
 
        }
        return orderDetailVo;
    }
 
    @Override
    public R<String> feeDescription(Long orderId, String uid) {
        XpOrder order = this.getById(orderId);
        R<XpPricing> pricingByCityId = xpPricingClient.getPricingByCid(order.getCityId());
        XpPricing pricing = pricingByCityId.getData();
        if (pricing == null) {
            throw new ServiceException("当前城市未配置定价规则", I18nKeyConstant.ORDER_PRICING_NOT_EXISTS);
        }else{
            return R.ok(pricing.getPriceRule());
        }
    }
 
 
    /**
     * 成功操作下发命令后调用 用于弹出redis队列的获取成功的数据
     *
     * @param dto
     */
    @Override
    @Transactional
    @ShardingSphereTransactionType(TransactionType.BASE)
    public void popOrder(PopOrderDto dto) {
        String orderType = dto.getOrderType();
        Long orderId = dto.getOrderId();
        //巡游单处理逻辑
        if(OrderType.CRUISE_ORDER.equals(orderType)){
            // todo 需要处理巡游的逻辑
 
 
 
        }
        //乘客单处理逻辑
        if(OrderType.USER_ORDER.equals(orderType)){
            XpOrder order = this.getById(orderId);
            //订单为待接单状态
            if(order.getStatus() == 1){
                AddTaxiPassengerVo addTaxiPassengerVo = new AddTaxiPassengerVo();
                order.setAcceptanceTime(LocalDateTime.now());
                R<XpVehicle> byVehicleVin = xpVehicleClient.findByVehicleVin(dto.getXpVehicleVin());
                XpVehicle vehicle = null;
                if (byVehicleVin.getCode() == 200) {
                    vehicle = byVehicleVin.getData();
                    order.setVehicleId(vehicle.getId());
                    order.setFleetId(vehicle.getFleetId());
                    addTaxiPassengerVo.setVin(vehicle.getVehicleVin());
                }
                order.setStatus(2);
 
                // Redis弹出这个队列元素
                // value 订单Id_经纬度_状态_用户id_订单编号_距离_时间
                String popFirstElement = redisService.popFirstElement(order.getQueueName());
                XpGeoQueryEntity xpGeoQueryEntity = new XpGeoQueryEntity();
                String[] split = popFirstElement.split("_");
                xpGeoQueryEntity.setOrderId(split[0]);
                // 存mongo数据
                xpPricingClient.updateXpGeoQueryEntity(split[0]);
                this.updateById(order);
 
                // 修改车辆信息
                vehicle.setState(1);
                xpVehicleClient.updateVehicleById(vehicle);
 
                //绑定用户和车辆关系
                addTaxiPassengerVo.setUid(order.getAppUserId().toString());
                addTaxiPassengerVo.setOrderNo(order.getOrderNumber());
                // TODO appid
                addTaxiPassengerVo.setAppId("");
                userVehicleClient.addTaxiPassenger(addTaxiPassengerVo);
                //推送乘客车辆到达预约点的导航数据
                sendRoute(order.getAppUserId().toString(), orderId, "ORDER_NAVIGATION_START_DATA");
            }else{
                //推送行起点到终点的驶轨迹给乘客端
                sendRoute(order.getAppUserId().toString(), orderId, "ORDER_NAVIGATION_END_DATA");
            }
        }
    }
 
 
    /**
     * 发送乘客导航路径数据
     * @param appUserId
     * @param keyStr
     */
    public void sendRoute(String appUserId, Long orderId, String keyStr){
        Object cacheObject = redisService.getCacheObject(keyStr + ":" + appUserId);
        if(null != cacheObject){
            RouteVo routeVo = JSON.parseObject(cacheObject.toString(), RouteVo.class);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "ORDER_ROUTE");
            jsonObject.put("timestamp", System.currentTimeMillis());
            JSONObject content = new JSONObject();
            content.put("orderId", orderId);
            content.put("routeType", "ORDER_NAVIGATION_START_DATA".equals(keyStr) ? 1 : 2);
            JSONObject route = new JSONObject();
            route.put("distance", routeVo.getDistance());
            route.put("duration", routeVo.getDuration());
            route.put("routeID", routeVo.getRouteID());
 
            List<JSONObject> collect = routeVo.getPolyline().stream().map(item->{
                JSONObject point = new JSONObject();
                point.put("latitude", item.getLatitude());
                point.put("longitude", item.getLongitude());
                return point;
            }).collect(Collectors.toList());
 
            route.put("polyline", collect);
            content.put("route", route.toJSONString());
            jsonObject.put("content", content.toJSONString());
            SendMessageDTO messageDTO = new SendMessageDTO();
            messageDTO.setAppUserId(appUserId);
            messageDTO.setMessage(jsonObject.toJSONString());
            xpPushMessageClient.sendRoute(messageDTO);
        }
    }
 
 
 
 
    /**
     * 获取当前用户正在执行的订单
     *
     * @param uid
     * @return
     */
    @Override
    public XpOrderDetailVO getActiveOrder(String uid) {
        XpOrderDetailVO xpOrderDetailVO = new XpOrderDetailVO();
        XpOrder xpOrder = this.baseMapper.selectOne(new LambdaQueryWrapper<XpOrder>().eq(XpOrder::getAppUserId, Long.parseLong(uid)).in(XpOrder::getStatus, Arrays.asList(1,2,3, 4, 5, 6, 7, 8)).orderByDesc(BaseModel::getCreateTime).last("LIMIT 1"));
        if (xpOrder == null) {
            return null;
        }
        BeanUtils.copyProperties(xpOrder, xpOrderDetailVO);
 
        R<XpPoint> xpPointR = xpPointClient.queryById(xpOrder.getStartPointId());
        if (xpPointR.getCode() == R.SUCCESS) {
            XpPoint startPoint = xpPointR.getData();
            xpOrderDetailVO.setStartParkingTimeLimit(startPoint.getParkingTimeLimit());
        }
 
        R<XpPoint> xpPointR1 = xpPointClient.queryById(xpOrder.getEndPointId());
        if (xpPointR1.getCode() == R.SUCCESS) {
            XpPoint endPoint = xpPointR1.getData();
            xpOrderDetailVO.setEndParkingTimeLimit(endPoint.getParkingTimeLimit());
        }
        // 算时间
        if (xpOrder.getStatus() == 1) {
            R<Integer> r = xpPricingClient.getWaitTime(new LonLatDto(xpOrder.getStartLon(), xpOrder.getStartLat()));
            if (r.getCode() == R.SUCCESS) {
                xpOrderDetailVO.setEstimatedTime(r.getData());
            } else {
                throw new RuntimeException(r.getMsg());
            }
 
        }
 
        return xpOrderDetailVO;
    }
}