hejianhao
2026-03-27 2c7f82b6b7aecfb25df9cdd76f5fd7ab4722e58a
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
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
import Taro, { useDidShow, useDidHide } from "@tarojs/taro"
import { useEffect, useState, useRef, useMemo } from 'react';
import { View, Map, Text, Image, CoverView, CoverImage } from '@tarojs/components';
import './index.less';
 
import CustomerServicePopup from '../../components/customer-service';
import ReleaseRoute from './components/release-route';
import ReleaseBeBeing from './components/release-be-being';
import CancelPopup from './components/cancel-popup';
import CallingCar from './components/calling-car';
import AnnouncementsPopup from './components/announcements-popup';
import OverRoute from './components/over-route';
import PassengerNotice from './components/passenger-notice';
import EvaluatePopup from './components/evaluate-popup';
import TipPopup from '../select-map-site/components/tip-popup';
 
import backIcon from '../../../robotaxi/assets/back-icon.png'
import contactService from '../../../robotaxi/assets/contact-service.png'
import coupon from '../../../robotaxi/assets/coupon.png'
import suggest from '../../../robotaxi/assets/suggest.png'
import originIcon from '../../../robotaxi/assets/origin-icon.png'
import wsManager from '../../../utils/websocket';
import {
  getWalkingRoute,
  formatDateTime,
  clearOrderTripStorage,
  preloadImageToTemp,
  debounce,
  computeAdaptiveBottomPadding,
  getAddressByLocation,
  convertAdcodeToCityCode,
  getCityInfoWithId,
  getDistance,
  mapOrderStatusToTripStatus,
  reportEvent
} from '../../../utils/Robotaxi-public-method';
import {
  saveOrder,
  queryRouteAndFare,
  queryVehicleByOrderId,
  getOrderPayment,
  cancelOrder,
  queryOrderRoute,
  queryOrderTrajectory,
  endOrder,
} from '../../../robotaxi/api/begin-route';
import { getOrderActive } from '../../../robotaxi/api/home';
import { getOrderDetail } from '../../../robotaxi/api/order';
import { getOrderDistance } from '../../api/select-map-site';
import { checkOtp } from '../../../utils/tools';
import { jumpTo } from '../../../utils/jump';
 
export default function SelectMapSite() {
  const WAITING_TIMER_START_KEY = 'waitingTimerStartAt'; // 等待计时开始时间
  const WAITING_TIMER_ELAPSED_KEY = 'waitingTimerElapsed'; // 等待计时已过秒数
  const REQUOTE_EXPIRE_SECONDS = 10 * 60; // 10分钟
 
  const [showCustomerService, setShowCustomerService] = useState(false); // 客服弹窗是否显示
  const [longitude, setLongitude] = useState<number | null>(null); // 经度
  const [latitude, setLatitude] = useState<number | null>(null); // 纬度
  const [markers, setMarkers] = useState<any[]>([]); // 标记点列表
  const [polyline, setPolyline] = useState<any[]>([]); // 路线
  const [startSite, setStartSite] = useState<any>(null); // 上车点
  const [endSite, setEndSite] = useState<any>({}); // 下车点
  const [tripStatus, setTripStatus] = useState<number>(Number(Taro.getStorageSync('tripStatus')) || 1); // 行程状态 1:发布行程 2:发布中 3:呼叫车中 4:车辆即将到达 5:车辆到达上车点 6:车辆行驶中 7:到达目的地 8:行程已结束 9:支付成功 10:取消订单时页面只展示一个上车点
  const [elapsedSeconds, setElapsedSeconds] = useState(0); // 等待计时秒数
  const requoteTriggeredRef = useRef(false); // 重新报价触发标记,防止重复触发
  const [showCancelPopup, setShowCancelPopup] = useState(false); // 取消弹窗是否显示
  const [showAnnouncementsPopup, setShowAnnouncementsPopup] = useState(false); // 安全注意事项动画弹窗是否显示
  const [showOverRoutePopup, setShowOverRoutePopup] = useState(false); // 结束行程弹窗是否显示
  const [showPassengerNotice, setShowPassengerNotice] = useState(false); // 乘车需知弹窗是否显示
  const [cancelType, setCancelType] = useState(1); // 取消类型
  const [showEvaluatePopup, setShowEvaluatePopup] = useState(false); // 评价弹窗是否显示
  const [showTipPopup, setShowTipPopup] = useState(false); // 提示弹窗是否显示
  const [tipType, setTipType] = useState(''); // 提示类型
  const [routePoints, setRoutePoints] = useState<any[]>([]); // 路线点集合
  const [walkingPoints, setWalkingPoints] = useState<any[]>([]); // 步行路径点
  const [walkingTime, setWalkingTime] = useState<number>(0); // 步行到上车点的预估时间(秒)
  const carMarkerInitialized = useRef(false); // 车辆标记是否已初始化
  const [fareEstimate, setFareEstimate] = useState<any>({}); // 预估费用信息
  const [routeAndFareError, setRouteAndFareError] = useState(false); // 路线费用查询是否出错
  const [callSubmitting, setCallSubmitting] = useState(false); // 呼叫车辆提交中状态
  const [vehicleLocation, setVehicleLocation] = useState<{ latitude: number, longitude: number } | null>(null); // 车辆当前位置坐标
  const [vehicleDirection, setVehicleDirection] = useState<number | null>(null); // 车辆航向角(0-360度)
  const [routeDistance, setRouteDistance] = useState<{ value: number; unit: 'km' | 'm' } | null>(null); // 路线距离
  const [routeDuration, setRouteDuration] = useState<number | null>(null); // 路线时间
  const [vehicleInfo, setVehicleInfo] = useState<any>({}); // 车辆信息
  const [orderId, setOrderId] = useState<string>(''); // 订单ID
  const [finishCountdownEnabled, setFinishCountdownEnabled] = useState(false); // 完成倒计时是否启用
  const customCalloutIconUrl = 'https://huishou-1323682843.cos.ap-nanjing.myqcloud.com/images/f9e285fc-4c09-404d-90f8-4bac178565d0.png'; // 自定义气泡图标URL
  const waitingCalloutBgUrl = 'https://huishou-1323682843.cos.ap-nanjing.myqcloud.com/images/f55ce277-68de-4615-9c7c-807f588afaac.png'; // 等待气泡背景图URL
  const waitingRadarUrl = 'https://huishou-1323682843.cos.ap-nanjing.myqcloud.com/images/63ff36fc-e84c-4078-a53b-467870645105.webp'; // 等待雷达动画图URL
  const [customCalloutIconSrc, setCustomCalloutIconSrc] = useState(customCalloutIconUrl); // 自定义气泡图标源(本地缓存路径)
  const [waitingCalloutBgSrc, setWaitingCalloutBgSrc] = useState(waitingCalloutBgUrl); // 等待气泡背景图源
  const [waitingRadarSrc, setWaitingRadarSrc] = useState(waitingRadarUrl); // 等待雷达动画图源
  const [waitingRadarStyle, setWaitingRadarStyle] = useState<any>({}); // 等待雷达动画样式
  const [waitingRadarVisible, setWaitingRadarVisible] = useState(true); // 等待雷达动画是否可见
  const [resetDetailVersion, setResetDetailVersion] = useState(0); // 重置详情版本号,用于触发组件更新
  const [priceUpdateVersion, setPriceUpdateVersion] = useState(0); // 价格更新版本号
  const [evaluateSubmitVersion, setEvaluateSubmitVersion] = useState(0); // 评价提交版本号
  const [evaluateCloseVersion, setEvaluateCloseVersion] = useState(0); // 评价关闭版本号
  const [originOpacity, setOriginOpacity] = useState(1); // 起点标记透明度
  const [originBoxHidden, setOriginBoxHidden] = useState(false); // 起点信息框是否隐藏
  const [mapBottomPadding, setMapBottomPadding] = useState(280); // 地图底部内边距(像素)
  const [carCalloutStyle, setCarCalloutStyle] = useState<any>({}); // 车辆气泡标注样式
  const [carCalloutVisible, setCarCalloutVisible] = useState(false); // 车辆气泡标注是否可见
  const [arriveCalloutStyle, setArriveCalloutStyle] = useState<any>({}); // 到达气泡标注样式
  const [arriveCalloutVisible, setArriveCalloutVisible] = useState(false); // 到达气泡标注是否可见
  const [distanceConfig, setDistanceConfig] = useState<any>({}); // 距离显示配置
  const [mapScale, setMapScale] = useState(14); // 地图缩放级别
  const [showLocationFlag, setShowLocationFlag] = useState(true); // 是否显示定位按钮
  const [trunkStatus, setTrunkStatus] = useState(false); // 后备箱开启状态
 
  const markersRef = useRef<any[]>([]); // 标记点列表引用,用于实时访问最新值
  const tripStatusRef = useRef(tripStatus); // 行程状态引用
  const lastTripStatusRef = useRef(tripStatus); // 上一次行程状态,用于检测状态变化
  const tripStatusForMapSyncRef = useRef(tripStatus); // 用于地图同步的行程状态引用
  const routeRequestKeyRef = useRef<string>(''); // 路线请求键
  const orderRouteInitializedRef = useRef(false); // 订单路线是否已初始化
  // 行程状态显示规则配置:showPickup-显示上车点,showDropoff-显示下车点,showCar-显示车辆,showRoute-显示路线,showWalking-显示步行路线,viewport-视口类型,translateCar-车辆是否平移
  const STATUS_RULES: Record<number, any> = {
    1: { showPickup: true, showDropoff: true, showCar: false, showRoute: true, showWalking: true, viewport: 'route_walking', translateCar: false },
    2: { showPickup: true, showDropoff: false, showCar: false, showRoute: false, showWalking: false, viewport: 'pickup', translateCar: false },
    3: { showPickup: true, showDropoff: false, showCar: false, showRoute: false, showWalking: false, viewport: 'pickup', translateCar: false },
    4: { showPickup: true, showDropoff: false, showCar: true, showRoute: true, showWalking: false, viewport: 'route', translateCar: true },
    5: { showPickup: true, showDropoff: false, showCar: true, showRoute: false, showWalking: false, viewport: 'car_user', translateCar: true },
    6: { showPickup: false, showDropoff: true, showCar: true, showRoute: true, showWalking: false, viewport: 'route', translateCar: true },
    7: { showPickup: false, showDropoff: true, showCar: true, showRoute: false, showWalking: false, viewport: 'dropoff', translateCar: false },
    8: { showPickup: true, showDropoff: true, showCar: false, showRoute: true, showWalking: false, viewport: 'order_detail', translateCar: false },
    9: { showPickup: true, showDropoff: true, showCar: false, showRoute: true, showWalking: false, viewport: 'order_detail', translateCar: false },
    10: { showPickup: true, showDropoff: false, showCar: false, showRoute: false, showWalking: false, viewport: 'pickup', translateCar: false },
  };
  const statusRule = useMemo(() => STATUS_RULES[tripStatus] || STATUS_RULES[1], [tripStatus]); // 当前行程状态对应的显示规则
  const shouldShowRoute = statusRule.showRoute; // 当前状态是否显示路线
  const authSuccessBound = useRef(false); // 认证成功是否绑定
  const messageBound = useRef(false); // 消息是否绑定
  const orderStatusBound = useRef(false); // 订单状态是否绑定
  const orderRouteBound = useRef(false); // 订单路线是否绑定
  const openTrunkBound = useRef(false); // 打开后备箱事件是否绑定
  const orderUpdatePriceBound = useRef(false); // 订单价格更新事件是否绑定
  const authSuccessHandlerRef = useRef<(data: any) => void>(); // 认证成功处理函数
  const messageHandlerRef = useRef<(data: any) => void>(); // 消息处理函数
  const orderStatusHandlerRef = useRef<(data: any) => void>(); // 订单状态处理函数
  const orderRouteHandlerRef = useRef<(data: any) => void>(); // 订单路线处理函数
  const openTrunkHandlerRef = useRef<(data: any) => void>(); // 打开后备箱事件处理函数
  const orderUpdatePriceHandlerRef = useRef<(data: any) => void>(); // 订单价格更新事件处理函数
  const socketOpenHandlerRef = useRef<(() => void) | null>(null); // WebSocket连接打开处理函数
  // 记录已为某订单拉取过车辆信息,避免重复
  const lastFetchedVehicleOrderIdRef = useRef<string | null>(null);
  const mapRectRef = useRef<any>(null); // 地图边界矩形区域引用
  const viewportKeyRef = useRef<string>(''); // 视口唯一键,用于标识视口状态
  const tripStatus6ViewportLockedRef = useRef(false); // 行程状态6视口是否锁定
  const tripStatus6MarkerRefreshedRef = useRef(false); // 行程状态6标记是否已刷新
  const polylineKeyRef = useRef<string>(''); // 路线唯一键
  const orderDetailRouteRequestIdRef = useRef(0); // 订单详情路线请求ID
  const lastRoutePointRef = useRef<{ latitude: number; longitude: number } | null>(null); // 最后一次路线点位置
  const lastRouteUpdateAtRef = useRef<number>(0); // 最后路线更新时间戳
  const lastVehiclePointRef = useRef<{ latitude: number; longitude: number } | null>(null); // 最后一次车辆位置
  const lastVehicleUpdateAtRef = useRef<number>(0); // 最后车辆位置更新时间戳
  const lastPolylineUpdateAtRef = useRef<number>(0); // 最后路线绘制更新时间戳
  const lastRouteAndFareRequestAtRef = useRef<number>(0); // 最后路线费用请求时间戳
  const markersSignatureRef = useRef<string>(''); // 标记点签名,用于检测变化
  const currentFullRouteRef = useRef<any[]>([]); // 当前完整路线点集合
  const lastErasedIndexRef = useRef<number>(0); // 最后擦除的路线点索引
  const isAndroid = useMemo(() => {
    try {
      const info = Taro.getSystemInfoSync();
      console.log('机型:', info);
      return info?.platform === 'android' || /android/i.test(info?.system || '');
    } catch (error) {
      return false;
    }
  }, []);
  const shouldShowWaitingRadar = isAndroid && [2, 3].includes(tripStatus); // 是否显示等待雷达动画(Android且状态2/3)
  const vehicleMarkerId = !isAndroid && tripStatus === 6 ? 30 : 3; // 车辆标记ID,iOS状态6使用不同ID
  const isCheckedEnter = useRef(false); // 是否已检查页面进入状态
  const router = Taro.useRouter(); // 路由对象
 
  useEffect(() => {
    const wasHold = [4, 6].includes(lastTripStatusRef.current);
    const isHold = [4, 6].includes(tripStatus);
    if ([6, 7].includes(tripStatus)) {
      setShowLocationFlag(false);
    } else {
      setShowLocationFlag(true);
    }
    if (tripStatus != 4) {
      Taro.removeStorageSync('pickupEndTime')
    }
    if (tripStatus != 7) {
      Taro.removeStorageSync('finishEndTime')
    }
    if (!wasHold && isHold) {
      orderRouteInitializedRef.current = false;
      tripStatus6ViewportLockedRef.current = false;
      tripStatus6MarkerRefreshedRef.current = false;
      currentFullRouteRef.current = [];
    }
    if (!isHold) {
      tripStatus6ViewportLockedRef.current = false;
      tripStatus6MarkerRefreshedRef.current = false;
    }
    lastTripStatusRef.current = tripStatus;
  }, [tripStatus]);
 
  useEffect(() => {
    markersRef.current = markers;
  }, [markers]);
 
  useEffect(() => {
    setFinishCountdownEnabled(false);
  }, [orderId]);
 
  const checkAndShowPassengerNotice = () => {
    const checkedTimeRaw = Taro.getStorageSync('passengerNoticeCheckedTime');
    if (!checkedTimeRaw) {
      setShowPassengerNotice(true);
      return;
    }
    const checkedTime = Number(checkedTimeRaw);
    const THREE_MONTH_MS = 3 * 30 * 24 * 60 * 60 * 1000;
    if (Number.isFinite(checkedTime) && Date.now() - checkedTime > THREE_MONTH_MS) {
      setShowPassengerNotice(true);
      Taro.removeStorageSync('passengerNoticeCheckedTime');
    }
  };
 
  // 加载等待弹窗图片
  useEffect(() => {
    if (tripStatus === 1) {
      checkAndShowPassengerNotice();
    }
    if (![2, 3].includes(tripStatus)) return;
    let cancelled = false;
    const load = async (url: string, setter: (value: string) => void) => {
      const local = await preloadImageToTemp(url);
      if (!cancelled) setter(local);
    }
    load(waitingCalloutBgUrl, setWaitingCalloutBgSrc);
    load(waitingRadarUrl, setWaitingRadarSrc);
    return () => {
      cancelled = true;
    };
  }, [tripStatus]);
 
  // 页面初始化预下载自定义气泡图标
  useEffect(() => {
    let cancelled = false;
    const run = async () => {
      const local = await preloadImageToTemp(customCalloutIconUrl);
      if (!cancelled) setCustomCalloutIconSrc(local);
    };
    run();
    return () => { cancelled = true; };
  }, []);
  // 更新等待雷达位置
  const updateWaitingRadarPosition = () => {
    if (!shouldShowWaitingRadar) {
      return;
    }
    const s = Taro.getStorageSync('startSite');
    if (!s?.latitude || !s?.longitude) {
      return;
    }
    const mapCtx = Taro.createMapContext('map');
    const resolveRect = (rect: any) => {
      if (!rect) {
        return;
      }
      mapCtx.getRegion({
        success: (res) => {
          const sw = res?.southwest;
          const ne = res?.northeast;
          const latRange = ne?.latitude - sw?.latitude;
          const lngRange = ne?.longitude - sw?.longitude;
          if (!latRange || !lngRange) {
            return;
          }
          const x = ((s.longitude - sw.longitude) / lngRange) * rect.width;
          const y = ((ne.latitude - s.latitude) / latRange) * rect.height;
          setWaitingRadarStyle({
            position: 'fixed',
            left: `${rect.left + x}px`,
            top: `${rect.top + y}px`,
            transform: 'translate(-50%, -55%)'
          });
        }
      });
    };
    if (mapRectRef.current) {
      resolveRect(mapRectRef.current);
      return;
    }
    Taro.createSelectorQuery()
      .select('#map')
      .boundingClientRect((rect) => {
        if (rect) {
          mapRectRef.current = rect;
        }
        resolveRect(rect);
      })
      .exec();
  };
 
  const updateCarCalloutPosition = () => {
    if (!isAndroid || !vehicleLocation || ![4, 6].includes(tripStatus)) {
      setCarCalloutVisible(false);
      return;
    }
    const mapCtx = Taro.createMapContext('map');
    const resolveRect = (rect: any) => {
      if (!rect) {
        return;
      }
      mapCtx.getRegion({
        success: (res) => {
          const sw = res?.southwest;
          const ne = res?.northeast;
          const latRange = ne?.latitude - sw?.latitude;
          const lngRange = ne?.longitude - sw?.longitude;
          if (!latRange || !lngRange) {
            return;
          }
          const x = ((vehicleLocation.longitude - sw.longitude) / lngRange) * rect.width;
          const y = ((ne.latitude - vehicleLocation.latitude) / latRange) * rect.height;
          setCarCalloutStyle({
            position: 'fixed',
            left: `${rect.left + x}px`,
            top: `${rect.top + y + 60}px`,
            transform: 'translate(-50%, -120%)'
          });
          setCarCalloutVisible(true);
        }
      });
    };
    if (mapRectRef.current) {
      resolveRect(mapRectRef.current);
      return;
    }
    Taro.createSelectorQuery()
      .select('#map')
      .boundingClientRect((rect) => {
        if (rect) {
          mapRectRef.current = rect;
        }
        resolveRect(rect);
      })
      .exec();
  };
  const updateArriveCalloutPosition = () => {
    if (!isAndroid) {
      return;
    }
    if (![7].includes(tripStatus)) {
      setArriveCalloutVisible(false);
      return;
    }
    const dropoffSite = endSite?.latitude && endSite?.longitude ? endSite : Taro.getStorageSync('endSite');
    if (!dropoffSite?.latitude || !dropoffSite?.longitude) {
      setArriveCalloutVisible(false);
      return;
    }
    const mapCtx = Taro.createMapContext('map');
    const resolveRect = (rect: any) => {
      if (!rect) {
        return;
      }
      mapCtx.getRegion({
        success: (res) => {
          const sw = res?.southwest;
          const ne = res?.northeast;
          const latRange = ne?.latitude - sw?.latitude;
          const lngRange = ne?.longitude - sw?.longitude;
          if (!latRange || !lngRange) {
            return;
          }
          const x = ((dropoffSite.longitude - sw.longitude) / lngRange) * rect.width;
          const y = ((ne.latitude - dropoffSite.latitude) / latRange) * rect.height;
          setArriveCalloutStyle({
            position: 'fixed',
            left: `${rect.left + x}px`,
            top: `${rect.top + y - 40}px`,
            transform: 'translate(-50%, -120%)'
          });
          setArriveCalloutVisible(true);
        }
      });
    };
    if (mapRectRef.current) {
      resolveRect(mapRectRef.current);
      return;
    }
    Taro.createSelectorQuery()
      .select('#map')
      .boundingClientRect((rect) => {
        if (rect) {
          mapRectRef.current = rect;
        }
        resolveRect(rect);
      })
      .exec();
  };
 
  // 更新等待雷达位置
  useEffect(() => {
    updateWaitingRadarPosition();
  }, [shouldShowWaitingRadar, startSite?.latitude, startSite?.longitude, longitude, latitude]);
 
  useEffect(() => {
    updateCarCalloutPosition();
  }, [isAndroid, vehicleLocation?.latitude, vehicleLocation?.longitude, tripStatus]);
  useEffect(() => {
    updateArriveCalloutPosition();
  }, [isAndroid, tripStatus, endSite?.latitude, endSite?.longitude]);
 
  const resolveSafeBottomInset = () => {
    try {
      const info = Taro.getSystemInfoSync();
      const screenHeight = info?.screenHeight;
      const safeBottom = info?.safeArea?.bottom;
      if (Number.isFinite(screenHeight) && Number.isFinite(safeBottom)) {
        return Math.max(0, screenHeight - safeBottom);
      }
    } catch (error) {
      return 0;
    }
    return 0;
  };
 
  const resolveSafeTopInset = () => {
    try {
      const info = Taro.getSystemInfoSync();
      const safeTop = info?.safeArea?.top;
      if (Number.isFinite(safeTop)) {
        return Math.max(0, safeTop);
      }
    } catch (error) {
      return 0;
    }
    return 0;
  };
 
  // 更新地图视口内边距
  const updateMapViewportPadding = () => {
    Taro.nextTick(() => {
      const query = Taro.createSelectorQuery();
      query.select('.container').boundingClientRect();
      query.select('.origin-box').boundingClientRect();
      query.select('.map-entry').boundingClientRect();
      query.exec((res) => {
        const rect = res?.[0];
        const originRect = res?.[1];
        const mapEntryRect = res?.[2];
        const safeInset = resolveSafeBottomInset();
        const measured = rect?.height ? rect.height + safeInset + 16 : 0;
        const nextPadding = Math.max(280, Math.round(measured));
        setMapBottomPadding(nextPadding);
        if (originRect && mapEntryRect) {
          const originLeft = originRect.left ?? 0;
          const originTop = originRect.top ?? 0;
          const originRight = originLeft + (originRect.width ?? 0);
          const originBottom = originTop + (originRect.height ?? 0);
          const entryLeft = mapEntryRect.left ?? 0;
          const entryTop = mapEntryRect.top ?? 0;
          const entryRight = entryLeft + (mapEntryRect.width ?? 0);
          const entryBottom = entryTop + (mapEntryRect.height ?? 0);
          const overlap = !(originRight < entryLeft || originLeft > entryRight || originBottom < entryTop || originTop > entryBottom);
          setOriginBoxHidden(overlap);
        } else {
          setOriginBoxHidden(false);
        }
      });
    });
  };
 
  const computeBottomPadding = (points: any[], viewportType: string) => {
    const basePadding = viewportType === 'order_detail' ? Math.max(200, mapBottomPadding) : mapBottomPadding;
    return computeAdaptiveBottomPadding(points, basePadding);
  };
 
  // 应用路线点
  const applyRoutePoints = (points: any[]) => {
    if (Array.isArray(points) && points.length > 0) {
      const firstPoint = points[0];
      const newLat = Number(firstPoint?.latitude);
      const newLng = Number(firstPoint?.longitude);
      const now = Date.now();
 
      if (Number.isFinite(newLat) && Number.isFinite(newLng)) {
        lastRoutePointRef.current = { latitude: newLat, longitude: newLng };
        lastRouteUpdateAtRef.current = now;
      } else {
        lastRoutePointRef.current = null;
        lastRouteUpdateAtRef.current = 0;
      }
      setRoutePoints(points);
      return true;
    } else {
      lastRoutePointRef.current = null;
      lastRouteUpdateAtRef.current = 0;
      setRoutePoints([]);
      return true;
    }
  };
 
  // 使用 eraseLines 擦除已行驶路段(状态4/6专用)
  const erasePassedRouteSegments = (newPoints: any[]) => {
    const oldPoints = currentFullRouteRef.current;
    if (!oldPoints?.length || !newPoints?.length) return;
 
    const newFirst = newPoints[0];
    let bestMatchIndex = -1;
    let bestDistance = Infinity;
    const startIndex = lastErasedIndexRef.current;
 
    for (let i = startIndex; i < oldPoints.length; i++) {
      const dist = getDistance(
        oldPoints[i].latitude, oldPoints[i].longitude,
        newFirst.latitude, newFirst.longitude
      );
      if (dist < bestDistance) {
        bestDistance = dist;
        bestMatchIndex = i;
      }
      // 已找到足够近的匹配点且距离开始增大,提前退出
      if (dist > bestDistance * 3 && bestDistance < 100) break;
    }
 
    if (bestMatchIndex >= startIndex && bestDistance < 500) {
      const mapCtx = Taro.createMapContext('map');
 
      const eraseIndex = Math.max(0, bestMatchIndex - 1);
      const erasePoint = oldPoints[bestMatchIndex];
 
      mapCtx.eraseLines({
        lines: [{
          id: 2001,
          index: eraseIndex,
          point: {
            latitude: erasePoint.latitude,
            longitude: erasePoint.longitude,
          },
          clear: true
        }],
        success: (res) => {
          console.log('擦除路线成功', res);
        },
        fail: (err) => {
          console.error('擦除路线失败', err);
        }
      });
 
      lastErasedIndexRef.current = bestMatchIndex;
    } else {
      // 路线发生较大变化,回退为全量重绘
      currentFullRouteRef.current = [...newPoints];
      lastErasedIndexRef.current = 0;
      lastRoutePointRef.current = null;
      lastRouteUpdateAtRef.current = 0;
      setRoutePoints([...newPoints]);
    }
  };
 
  // 更新车辆位置(移除节流,实时更新)
  const updateVehicleLocationThrottled = (lat: number, lng: number, force = false) => {
    const now = Date.now();
    if (Number.isFinite(lat) && Number.isFinite(lng)) {
      lastVehiclePointRef.current = { latitude: lat, longitude: lng };
      lastVehicleUpdateAtRef.current = now;
      setVehicleLocation({ latitude: lat, longitude: lng });
    }
  };
 
  const reducePoints = (points: any[], maxCount: number) => {
    if (!Array.isArray(points) || points.length <= maxCount) {
      return points;
    }
    const step = Math.ceil(points.length / maxCount);
    const reduced = [];
    for (let i = 0; i < points.length; i += step) {
      reduced.push(points[i]);
    }
    const last = points[points.length - 1];
    if (reduced[reduced.length - 1] !== last) {
      reduced.push(last);
    }
    return reduced;
  };
 
  // 归一化距离(公里或米)
  const normalizeDistanceKm = (value: any) => {
    const num = Number(value);
    if (Number.isNaN(num)) {
      return null;
    }
    if (num >= 1000) {
      return { value: Number((num / 1000).toFixed(1)), unit: 'km' as const };
    }
    return { value: Math.max(0, Math.round(num)), unit: 'm' as const };
  };
 
  // 归一化时间(秒)
  const normalizeDurationSeconds = (value: any) => {
    const num = Number(value);
    if (Number.isNaN(num)) {
      return null;
    }
    return Math.round(num);
  };
 
  // 格式化时间显示(分钟或秒)
  const formatDurationDisplay = (value: any) => {
    const num = Number(value);
    if (Number.isNaN(num)) {
      return { value: 0, unit: '分钟' };
    }
    if (num < 60) {
      return { value: Math.max(0, Math.round(num)), unit: '秒' };
    }
    return { value: Math.ceil(num / 60), unit: '分钟' };
  };
 
  const ensureSelectedCityForRoute = async (lng: number, lat: number) => {
    const cachedCity = Taro.getStorageSync('selectedCity');
    if (cachedCity?.id && Number(cachedCity.id) !== 0) {
      return cachedCity;
    }
    try {
      const data = await getAddressByLocation(lng, lat);
      const addressComponent = data?.regeocodeData?.addressComponent;
      if (addressComponent) {
        const { city, province, adcode } = addressComponent;
        const cityName = (city && typeof city === 'string' && city.length > 0) ? city : province;
        const cityCode = convertAdcodeToCityCode(adcode, cityName, province);
        const cityInfo = await getCityInfoWithId(cityCode, cityName);
        Taro.setStorageSync('selectedCity', cityInfo);
        return cityInfo;
      }
    } catch (error) {
    }
    return cachedCity;
  };
 
  // 请求路线和车费
  const requestRouteAndFare = async (originLat: number, originLng: number, destLat: number, destLng: number, force = false) => {
    const now = Date.now();
    if (now - lastRouteAndFareRequestAtRef.current < 1000) {
      return;
    }
    lastRouteAndFareRequestAtRef.current = now;
    const requestKey = `${originLng},${originLat}-${destLng},${destLat}`;
    if (!force && requestKey === routeRequestKeyRef.current) {
      return;
    }
    routeRequestKeyRef.current = requestKey;
    const selectedCity = await ensureSelectedCityForRoute(originLng, originLat);
    const openCityId = selectedCity ? selectedCity.id : 0;
    const cachedCouponId = Taro.getStorageSync('selectedCouponId');
    const params: any = {
      destination: {
        latitude: destLat,
        longitude: destLng
      },
      openCityId: openCityId,
      origin: {
        latitude: originLat,
        longitude: originLng
      },
    };
    if (cachedCouponId) {
      params.userCouponId = cachedCouponId;
    }
    queryRouteAndFare(params).then((res: any) => {
      setRouteAndFareError(false);
      if (res?.fareEstimate) {
        setFareEstimate(res.fareEstimate);
      }
      if (res?.xpPricingCard) {
        Taro.setStorageSync('xpPricingCard', res.xpPricingCard);
      }
      // 解析预估阶段返回的路线并展示
      const route = res?.route;
      const distance = Number(route?.distance);
      const duration = Number(route?.duration);
      const points = (Array.isArray(route?.polyline) ? route?.polyline : []);
      const distanceKm = normalizeDistanceKm(distance);
      if (distanceKm !== null) {
        setRouteDistance(distanceKm);
      }
      const durationSeconds = normalizeDurationSeconds(duration);
      if (durationSeconds !== null) {
        setRouteDuration(durationSeconds);
      }
      if (Array.isArray(points) && points.length > 0) {
        applyRoutePoints(points);
        if (tripStatusRef.current === 1) {
          const mapCtx = Taro.createMapContext('map');
          const allPoints = [...points, ...walkingPoints];
          if (allPoints.length > 0) {
            const topPadding = Math.max(24, resolveSafeTopInset() + 32);
            const bottomPadding = computeBottomPadding(allPoints, 'route_walking');
            mapCtx.includePoints({
              points: allPoints,
              padding: [topPadding, 100, bottomPadding, 100]
            });
          }
        }
      } else {
        applyRoutePoints([]);
      }
 
    }).catch(() => {
      setRouteAndFareError(true);
    });
  };
 
  const requestOrderRoute = (targetOrderId: string, status: number) => {
    const routeType = status <= 5 ? 1 : 2;
    const isTrajectoryStatus = [7, 8, 9].includes(status);
    const requestRoute = isTrajectoryStatus ? queryOrderTrajectory : queryOrderRoute;
    requestRoute({ orderId: targetOrderId, routeType })
      .then((res: any) => {
        const data = res;
        const rawPoints = Array.isArray(data?.polyline) ? data.polyline : [];
        const points = rawPoints
          .map((item: any) => ({
            longitude: Number(item?.longitude),
            latitude: Number(item?.latitude),
          }))
          .filter((item: any) => Number.isFinite(item.longitude) && Number.isFinite(item.latitude));
        if (points.length > 0) {
          if (status === 5) {
            const last = points[points.length - 1];
            updateVehicleLocationThrottled(last.latitude, last.longitude, true);
          } else {
            applyRoutePoints(points);
            const first = points[0];
            updateVehicleLocationThrottled(first.latitude, first.longitude, true);
            // 状态4/6:存储完整路线用于后续 eraseLines 对比
            if ([4, 6].includes(status)) {
              currentFullRouteRef.current = [...points];
              lastErasedIndexRef.current = 0;
              orderRouteInitializedRef.current = true;
            }
          }
        }
        const distance = Number(data?.distance);
        const distanceKm = normalizeDistanceKm(distance);
        if (distanceKm !== null) {
          setRouteDistance(distanceKm);
        }
        const duration = Number(data?.duration);
        const durationSeconds = normalizeDurationSeconds(duration);
        if (durationSeconds !== null) {
          setRouteDuration(durationSeconds);
        }
        setVehicleDirection(data?.direction);
      })
      .catch(() => { });
  };
 
  // 计算“当前位置→上车点”的步行路径
  const updateWalkingRouteForStart = async () => {
    try {
      const loc = await Taro.getLocation({ type: 'gcj02' });
      const originLat = loc.latitude;
      const originLng = loc.longitude;
      const targetLat = startSite?.latitude;
      const targetLng = startSite?.longitude;
      if (!originLat || !originLng || !targetLat || !targetLng) {
        setWalkingPoints([]);
        return;
      }
      const origin = `${originLng},${originLat}`;
      const destination = `${targetLng},${targetLat}`;
      const { points: wPoints, duration } = await getWalkingRoute(origin, destination);
      if (Array.isArray(wPoints) && wPoints.length > 0) {
        setWalkingPoints(wPoints);
        setWalkingTime(Math.ceil(duration / 60));
      } else {
        setWalkingPoints([]);
        setWalkingTime(0);
      }
    } catch (e) {
      setWalkingPoints([]);
      setWalkingTime(0);
    }
  };
 
  // 认证成功处理函数
  useEffect(() => {
    authSuccessHandlerRef.current = () => {
      if (!messageBound.current && messageHandlerRef.current) {
        wsManager.on('message', messageHandlerRef.current);
        messageBound.current = true;
      }
    };
    messageHandlerRef.current = (data) => {
      console.log('ws message:', data);
    };
    openTrunkHandlerRef.current = (payload) => {
      const isOpen = Number(payload?.isOpen);
      if (isOpen === 1) {
        setFinishCountdownEnabled(true);
      }
    };
    orderUpdatePriceHandlerRef.current = (payload) => {
      const incomingOrderId = payload?.orderId || payload?.content?.orderId || Taro.getStorageSync('orderId');
      const currentOrderId = orderId || Taro.getStorageSync('orderId');
      if (incomingOrderId && currentOrderId && String(incomingOrderId) !== String(currentOrderId)) {
        return;
      }
      setPriceUpdateVersion((v) => v + 1);
    };
    // 优化订单状态回调中的车辆信息拉取逻辑
    orderStatusHandlerRef.current = (payload) => {
      const changeStatusOld = tripStatusRef.current;
      const incomingOrderId = payload?.content?.orderId || payload?.orderId;
      const currentOrderId = orderId || Taro.getStorageSync('orderId');
      if (incomingOrderId && currentOrderId && String(incomingOrderId) !== String(currentOrderId)) {
        return;
      }
      const mappedTripStatus = payload?.tripStatus;
      if (typeof mappedTripStatus === 'number') {
        const currentLocalStatus = Number(Taro.getStorageSync('tripStatus'));
        // 如果本地状态已经比推送的状态新(状态递增原则),则忽略旧的推送消息
        if (currentLocalStatus > mappedTripStatus && currentLocalStatus !== 10) {
          return;
        }
        setTripStatus(mappedTripStatus);
        tripStatusRef.current = mappedTripStatus; // 同步更新ref,防止后续路由推送拿不到最新状态
        Taro.setStorageSync('tripStatus', mappedTripStatus);
      }
      // 车辆信息拉取:当收到有效的订单号时,在首次达到呼叫及后续阶段拉取车辆信息
      const effectiveOrderId = incomingOrderId || currentOrderId || Taro.getStorageSync('orderId');
      const vehicleInfoEmpty =
        !vehicleInfo ||
        (!vehicleInfo.plateNumber && !vehicleInfo.vehicleCode && !vehicleInfo.vehicleColor && !vehicleInfo.vehiclePictures);
      const shouldFetchVehicle =
        !!effectiveOrderId &&
        (lastFetchedVehicleOrderIdRef.current !== effectiveOrderId) &&
        (vehicleInfoEmpty || orderId !== effectiveOrderId);
      if (effectiveOrderId && orderId !== effectiveOrderId) {
        setOrderId(effectiveOrderId);
      }
      if (shouldFetchVehicle) {
        lastFetchedVehicleOrderIdRef.current = effectiveOrderId;
        queryVehicleByOrderId({ orderId: effectiveOrderId })
          .then((res: any) => {
            setVehicleInfo(res);
          })
          .catch(() => { });
      }
      if (mappedTripStatus === 6) {
        setShowAnnouncementsPopup(false);
      }
      if (mappedTripStatus === 5 && changeStatusOld !== 5) {
        setRoutePoints([]);
        setPolyline([]);
        polylineKeyRef.current = '';
        lastPolylineUpdateAtRef.current = 0;
        lastRoutePointRef.current = null;
        lastRouteUpdateAtRef.current = 0;
        lastVehiclePointRef.current = null;
        lastVehicleUpdateAtRef.current = 0;
        currentFullRouteRef.current = [];
        lastErasedIndexRef.current = 0;
        orderRouteInitializedRef.current = false;
      }
      if (mappedTripStatus === 4 && changeStatusOld !== 4) {
        setRoutePoints([]);
        setPolyline([]);
        polylineKeyRef.current = '';
        lastPolylineUpdateAtRef.current = 0;
        lastRoutePointRef.current = null;
        lastRouteUpdateAtRef.current = 0;
        lastVehiclePointRef.current = null;
        lastVehicleUpdateAtRef.current = 0;
        currentFullRouteRef.current = [];
        lastErasedIndexRef.current = 0;
        orderRouteInitializedRef.current = false;
      }
 
      if (payload?.showCancelPopup) {
        if (changeStatusOld == 4 || changeStatusOld == 5) {
          setOrderId('');
          clearOrderTripStorage();
          Taro.removeStorageSync('pickupEndTime');
          Taro.removeStorageSync('waitingTimerStartAt');
          Taro.removeStorageSync('waitingTimerElapsed');
          setCancelType(4);
        } else {
          setCancelType(5);
        }
        setTripStatus(10);
        setShowCancelPopup(true);
      }
      if (payload?.showPassengerNotice) {
        checkAndShowPassengerNotice();
      }
    };
 
    orderRouteHandlerRef.current = (payload) => {
      if (tripStatusRef.current === 5) {
        return;
      }
      const points = payload?.points || [];
      const direction = payload?.direction;
      if (typeof direction === 'number' && Number.isFinite(direction)) {
        setVehicleDirection(direction);
      }
      const distance = Number(JSON.parse(payload?.content?.route)?.distance);
      const duration = Number(JSON.parse(payload?.content?.route)?.duration);
      const distanceKm = normalizeDistanceKm(distance);
      if (distanceKm !== null) {
        setRouteDistance(distanceKm);
      }
      const durationSeconds = normalizeDurationSeconds(duration);
      if (durationSeconds !== null) {
        setRouteDuration(durationSeconds);
      }
 
      // 状态4/6:使用 eraseLines 擦除已行驶路段,不再全量重绘
      const isEraseStatus = [4, 6].includes(tripStatusRef.current);
      if (isEraseStatus) {
        const firstPoint = points?.[0];
        if (orderRouteInitializedRef.current && currentFullRouteRef.current.length > 0) {
          // 后续更新:擦除已行驶路段
          erasePassedRouteSegments(points);
        } else {
          // 首次绘制:全量渲染并存储完整路线
          orderRouteInitializedRef.current = true;
          currentFullRouteRef.current = [...points];
          lastErasedIndexRef.current = 0;
          Taro.nextTick(() => {
            applyRoutePoints(points);
          });
        }
        if (firstPoint && typeof firstPoint.latitude === 'number' && typeof firstPoint.longitude === 'number') {
          updateVehicleLocationThrottled(firstPoint.latitude, firstPoint.longitude, true);
        }
        return;
      }
 
      // 其他状态保持原有逻辑
      Taro.nextTick(() => {
        const updated = applyRoutePoints(points);
        if (updated && [4, 5, 6].includes(tripStatusRef.current)) {
          const firstPoint = points?.[0];
          if (firstPoint && typeof firstPoint.latitude === 'number' && typeof firstPoint.longitude === 'number') {
            updateVehicleLocationThrottled(firstPoint.latitude, firstPoint.longitude, true);
          }
        }
      });
    };
 
    return () => {
      if (authSuccessBound.current && authSuccessHandlerRef.current) {
        wsManager.off('auth_success', authSuccessHandlerRef.current);
        authSuccessBound.current = false;
      }
      if (messageBound.current && messageHandlerRef.current) {
        wsManager.off('message', messageHandlerRef.current);
        messageBound.current = false;
      }
      if (orderStatusBound.current && orderStatusHandlerRef.current) {
        wsManager.off('order_status', orderStatusHandlerRef.current);
        orderStatusBound.current = false;
      }
      if (orderRouteBound.current && orderRouteHandlerRef.current) {
        wsManager.off('order_route', orderRouteHandlerRef.current);
        orderRouteBound.current = false;
      }
      if (openTrunkBound.current && openTrunkHandlerRef.current) {
        wsManager.off('open_trunk', openTrunkHandlerRef.current);
        openTrunkBound.current = false;
      }
      if (orderUpdatePriceBound.current && orderUpdatePriceHandlerRef.current) {
        wsManager.off('order_update_price', orderUpdatePriceHandlerRef.current);
        orderUpdatePriceBound.current = false;
      }
    };
  }, []);
 
 
  // 监听行程状态,处理等待计时
  useEffect(() => {
    Taro.setStorageSync('tripStatus', tripStatus);
    tripStatusRef.current = tripStatus;
    const prevTripStatus = tripStatusForMapSyncRef.current;
    if (tripStatus === 1) {
      setCallSubmitting(false);
    }
    let timer: any = null;
    let requoteTimer: any = null;
    // tripStatus=1:开启发布行程停留计时,用于10分钟后提示需重新估价
    if (tripStatus == 1) {
      requoteTriggeredRef.current = false;
      const startAt = Date.now();
      const updateRequoteElapsed = () => {
        const nextElapsed = Math.max(0, Math.floor((Date.now() - startAt) / 1000));
        if (nextElapsed >= REQUOTE_EXPIRE_SECONDS) {
          if (!requoteTriggeredRef.current) {
            requoteTriggeredRef.current = true;
            const s = Taro.getStorageSync('startSite') || {};
            const e = Taro.getStorageSync('endSite') || {};
            if (s?.latitude && s?.longitude && e?.latitude && e?.longitude) {
              requestRouteAndFare(s.latitude, s.longitude, e.latitude, e.longitude, true);
            }
          }
        }
      };
      updateRequoteElapsed();
      requoteTimer = setInterval(updateRequoteElapsed, 1000);
    } else {
      requoteTriggeredRef.current = false;
      // 离开发布阶段后清空步行路线,避免在进行中/支付成功阶段仍显示步行线
      setWalkingPoints([]);
      setWalkingTime(0);
    }
    // tripStatus=2/3:等待计时
    if (tripStatus == 2 || tripStatus == 3) {
      const s = Taro.getStorageSync('startSite');
      const hasPlannedRoute = Array.isArray(routePoints) && routePoints.length > 0;
      if (!hasPlannedRoute && s && s.latitude && s.longitude) {
        setLatitude(s.latitude);
        setLongitude(s.longitude);
      }
 
      const cachedStartAt = Number(Taro.getStorageSync(WAITING_TIMER_START_KEY));
      const cachedElapsed = Number(Taro.getStorageSync(WAITING_TIMER_ELAPSED_KEY));
      let startAt = cachedStartAt;
      if (!Number.isFinite(startAt) || startAt <= 0) {
        if (Number.isFinite(cachedElapsed) && cachedElapsed >= 0) {
          startAt = Date.now() - cachedElapsed * 1000;
        } else {
          startAt = Date.now();
        }
        Taro.setStorageSync(WAITING_TIMER_START_KEY, startAt);
      }
      const updateElapsed = () => {
        const nextElapsed = Math.max(0, Math.floor((Date.now() - startAt) / 1000));
        setElapsedSeconds(nextElapsed);
      };
      updateElapsed();
      timer = setInterval(() => {
        updateElapsed();
      }, 1000);
    } else if (tripStatus == 7) {
      const e = Taro.getStorageSync('endSite');
      if (e && e.latitude && e.longitude) {
        setLatitude(e.latitude);
        setLongitude(e.longitude);
      }
      setElapsedSeconds(0);
      Taro.removeStorageSync(WAITING_TIMER_START_KEY);
      Taro.removeStorageSync(WAITING_TIMER_ELAPSED_KEY);
    } else if ([8, 9].includes(tripStatus)) {
      const shouldSkipOrderDetailRefresh = prevTripStatus === 8 && tripStatus === 9;
      if (!shouldSkipOrderDetailRefresh) {
        orderDetailRouteRequestIdRef.current += 1;
        const currentRequestId = orderDetailRouteRequestIdRef.current;
        const requestTripStatus = tripStatus;
        getOrderDetail(Taro.getStorageSync('orderId')).then((res: any) => {
          if (currentRequestId !== orderDetailRouteRequestIdRef.current) return;
          if (![8, 9].includes(tripStatusRef.current)) return;
          const mapCtx = Taro.createMapContext('map');
          if (res.trajectories) {
            const points = res.trajectories
              .map((item: any) => {
                const [lonStr, latStr] = String(item.location || '').split(',');
                const lon = Number(lonStr);
                const lat = Number(latStr);
                return { latitude: lat, longitude: lon };
              })
              .filter(p => Number.isFinite(p.latitude) && Number.isFinite(p.longitude));
            applyRoutePoints(points);
          } else {
            mapCtx.moveToLocation({
              latitude: 39.916527,
              longitude: 116.397128,
            });
          }
        });
      }
      setElapsedSeconds(0);
      Taro.removeStorageSync(WAITING_TIMER_START_KEY);
      Taro.removeStorageSync(WAITING_TIMER_ELAPSED_KEY);
    } else {
      setElapsedSeconds(0);
      Taro.removeStorageSync(WAITING_TIMER_START_KEY);
      Taro.removeStorageSync(WAITING_TIMER_ELAPSED_KEY);
    }
    tripStatusForMapSyncRef.current = tripStatus;
    return () => {
      if (timer) clearInterval(timer);
      if (requoteTimer) clearInterval(requoteTimer);
    };
  }, [tripStatus]);
 
  // 页面隐藏时保存等待时间并解绑事件
  useDidHide(() => {
    setResetDetailVersion(v => v + 1);
    const currentTripStatus = tripStatusRef.current;
    if (currentTripStatus === 2 || currentTripStatus === 3) {
      const startAt = Number(Taro.getStorageSync(WAITING_TIMER_START_KEY));
      if (Number.isFinite(startAt) && startAt > 0) {
        const currentElapsed = Math.max(0, Math.floor((Date.now() - startAt) / 1000));
        Taro.setStorageSync(WAITING_TIMER_ELAPSED_KEY, currentElapsed);
      } else {
        Taro.setStorageSync(WAITING_TIMER_ELAPSED_KEY, elapsedSeconds);
      }
    } else {
      Taro.removeStorageSync(WAITING_TIMER_START_KEY);
      Taro.removeStorageSync(WAITING_TIMER_ELAPSED_KEY);
    }
  });
 
  // 构建并更新地图标记点(与路线解耦,避免路线更新导致标记刷新)
  useEffect(() => {
    const pickupSite = startSite?.latitude && startSite?.longitude ? startSite : Taro.getStorageSync('startSite');
    const dropoffSite = endSite?.latitude && endSite?.longitude ? endSite : Taro.getStorageSync('endSite');
    const useAndroidNativeTrip1Callout = isAndroid && [1, 8, 9, 10].includes(tripStatus);
    const pickupMarker = pickupSite?.latitude && pickupSite?.longitude ? {
      id: 1,
      latitude: pickupSite.latitude,
      longitude: pickupSite.longitude,
      iconPath: 'https://huishou-1323682843.cos.ap-nanjing.myqcloud.com/images/51e7cb75-72af-4994-9d6e-d999efb2fbc7.png',
      width: 22,
      height: 40,
      anchor: { x: 0.5, y: 1 },
      zIndex: 1,
      name: pickupSite?.name || '上车点',
      ...(useAndroidNativeTrip1Callout
        ? {
          callout: {
            content: tripStatus === 1 ? `${pickupSite?.name || '上车点'} >` : (pickupSite?.name || '上车点'),
            color: '#000000',
            fontSize: 12,
            bgColor: '#FFFFFF',
            borderRadius: 8,
            padding: 8,
            display: 'ALWAYS',
            textAlign: 'center',
          },
        }
        : {
          customCallout: {
            anchorY: [2, 3].includes(tripStatus) ? 150 : -5,
            anchorX: 0,
            display: 'ALWAYS'
          },
        })
    } : null;
    const dropoffMarker = dropoffSite?.latitude && dropoffSite?.longitude ? {
      id: 2,
      latitude: dropoffSite.latitude,
      longitude: dropoffSite.longitude,
      iconPath: 'https://huishou-1323682843.cos.ap-nanjing.myqcloud.com/images/6a56b1eb-ec37-4839-8733-262942af070d.png',
      width: 22,
      height: 40,
      anchor: { x: 0.5, y: 1 },
      zIndex: 1,
      name: [7].includes(tripStatus) ? '已到达' : (dropoffSite.name || '目的地'),
      ...(useAndroidNativeTrip1Callout || tripStatus == 6
        ? {
          callout: {
            content: tripStatus === 1 ? `${[7].includes(tripStatus) ? '已到达' : (dropoffSite.name || '目的地')} >` : ([7].includes(tripStatus) ? '已到达' : (dropoffSite.name || '目的地')),
            color: '#000000',
            fontSize: 12,
            bgColor: '#FFFFFF',
            borderRadius: 8,
            padding: 8,
            display: 'ALWAYS',
            textAlign: 'center',
          },
        }
        : {
          customCallout: {
            anchorY: -5,
            anchorX: 0,
            display: 'ALWAYS'
          },
        })
    } : null;
    const carMarker = vehicleLocation ? {
      id: vehicleMarkerId,
      latitude: vehicleLocation.latitude,
      longitude: vehicleLocation.longitude,
      iconPath: 'https://huishou-1323682843.cos.ap-nanjing.myqcloud.com/images/e8c34535-f297-43da-8ab9-97f55939c0ae.png',
      width: 20,
      height: 40,
      anchor: { x: 0.5, y: 0.5 },
      zIndex: 2,
      rotate: typeof vehicleDirection === 'number' ? vehicleDirection : 0,
      name: '车辆位置',
      customCallout: { anchorY: 70, anchorX: 0, display: 'ALWAYS' }
    } : null;
 
    const nextMarkers: any[] = [];
    if (statusRule.showPickup && pickupMarker) nextMarkers.push(pickupMarker);
    if (statusRule.showCar && carMarker) nextMarkers.push(carMarker);
    if (statusRule.showDropoff && dropoffMarker) nextMarkers.push(dropoffMarker);
    const nextMarkersSignature = nextMarkers
      .map((m: any) => [
        m.id,
        Number(m.latitude).toFixed(6),
        Number(m.longitude).toFixed(6),
        m.name || '',
        typeof m.rotate === 'number' ? m.rotate : '',
        m?.customCallout?.anchorY ?? '',
      ].join('|'))
      .join(';');
    const hasDropoffMarker = markersRef.current.some((m: any) => m.id === 2);
    const shouldHoldMarkerByTranslate = [4, 6].includes(tripStatus) && carMarkerInitialized.current && statusRule.showCar && (!statusRule.showDropoff || hasDropoffMarker);
    const shouldSkipUpdate = shouldHoldMarkerByTranslate && (isAndroid || tripStatus6MarkerRefreshedRef.current);
    if (shouldSkipUpdate) {
    } else {
      if (markersSignatureRef.current !== nextMarkersSignature) {
        markersSignatureRef.current = nextMarkersSignature;
        setMarkers(nextMarkers);
      }
      if (!isAndroid && [4, 6].includes(tripStatus) && statusRule.showCar && !!carMarker && !tripStatus6MarkerRefreshedRef.current) {
        tripStatus6MarkerRefreshedRef.current = true;
      }
    }
    carMarkerInitialized.current = statusRule.showCar && !!carMarker;
  }, [tripStatus, startSite?.name, startSite?.latitude, startSite?.longitude, endSite.name, endSite?.latitude, endSite?.longitude, vehicleLocation, vehicleDirection, vehicleMarkerId]);
 
  // 绘制路线与视野适配
  useEffect(() => {
    // 状态4/6使用 eraseLines,不缩减点数以保证坐标匹配
    const isEraseMode = [4, 6].includes(tripStatus);
    const displayRoutePoints = isEraseMode ? routePoints : reducePoints(routePoints, isAndroid ? 120 : 200);
    const lastRoutePoint = displayRoutePoints[displayRoutePoints.length - 1];
    const lastWalkingPoint = walkingPoints[walkingPoints.length - 1];
    const now = Date.now();
    const nextKey = [
      shouldShowRoute ? 1 : 0,
      statusRule.showWalking ? 1 : 0,
      displayRoutePoints.length,
      walkingPoints.length,
      lastRoutePoint?.latitude ?? '',
      lastRoutePoint?.longitude ?? '',
      lastWalkingPoint?.latitude ?? '',
      lastWalkingPoint?.longitude ?? '',
    ].join('|');
    if (nextKey === polylineKeyRef.current) {
      return;
    }
    polylineKeyRef.current = nextKey;
    if (shouldShowRoute && (displayRoutePoints.length > 0 || (statusRule.showWalking && walkingPoints.length > 0))) {
      const lines: any[] = [];
      if (displayRoutePoints.length > 0) {
        lines.push({
          id: 2001,
          points: displayRoutePoints,
          color: '#7B91FF',
          width: 10,
          dottedLine: false,
          arrowLine: true,
        });
      }
      if (statusRule.showWalking && walkingPoints.length > 0) {
        lines.push({
          id: 2002,
          points: walkingPoints,
          color: '#7B91FF',
          width: 6,
          dottedLine: true,
          arrowLine: false,
        });
      }
      setPolyline(lines);
      lastPolylineUpdateAtRef.current = now;
    } else {
      if (![8, 9].includes(tripStatus)) {
        setPolyline([]);
      }
      lastPolylineUpdateAtRef.current = 0;
    }
  }, [tripStatus, shouldShowRoute, routePoints, walkingPoints, statusRule.showWalking, isAndroid]);
 
  useEffect(() => {
    const pickupSite = startSite?.latitude && startSite?.longitude ? startSite : Taro.getStorageSync('startSite');
    const dropoffSite = endSite?.latitude && endSite?.longitude ? endSite : Taro.getStorageSync('endSite');
    const viewportType = statusRule.viewport;
    const points: any[] = [];
    const keyParts: any[] = [viewportType === 'order_detail' ? 8 : tripStatus, viewportType];
 
    if (viewportType === 'route_walking') {
      if (routePoints.length > 0) {
        points.push(...routePoints);
      }
      if (walkingPoints.length > 0) {
        points.push(...walkingPoints);
      }
      keyParts.push(routePoints.length, walkingPoints.length);
    } else if (viewportType === 'pickup') {
      if (pickupSite?.latitude && pickupSite?.longitude) {
        points.push({ latitude: pickupSite.latitude, longitude: pickupSite.longitude });
      }
      keyParts.push(pickupSite?.latitude, pickupSite?.longitude);
    } else if (viewportType === 'route') {
      if (routePoints.length > 0) {
        points.push(...routePoints);
      }
      keyParts.push(routePoints.length);
    } else if (viewportType === 'car_user') {
      if (Number.isFinite(latitude) && Number.isFinite(longitude)) {
        points.push({ latitude, longitude });
      }
      if (vehicleLocation?.latitude && vehicleLocation?.longitude) {
        points.push({ latitude: vehicleLocation.latitude, longitude: vehicleLocation.longitude });
      }
      keyParts.push(latitude, longitude, vehicleLocation?.latitude, vehicleLocation?.longitude);
    } else if (viewportType === 'dropoff') {
      if (dropoffSite?.latitude && dropoffSite?.longitude) {
        points.push({ latitude: dropoffSite.latitude, longitude: dropoffSite.longitude });
      }
      keyParts.push(dropoffSite?.latitude, dropoffSite?.longitude);
    } else if (viewportType === 'order_detail') {
      if (routePoints.length > 0) {
        points.push(...routePoints);
      }
      if (pickupSite?.latitude && pickupSite?.longitude) {
        points.push({ latitude: pickupSite.latitude, longitude: pickupSite.longitude });
      }
      if (dropoffSite?.latitude && dropoffSite?.longitude) {
        points.push({ latitude: dropoffSite.latitude, longitude: dropoffSite.longitude });
      }
      keyParts.push(routePoints.length, pickupSite?.latitude, pickupSite?.longitude, dropoffSite?.latitude, dropoffSite?.longitude);
    }
 
    if (points.length === 0) return;
    if (tripStatus === 6 && viewportType === 'route' && tripStatus6ViewportLockedRef.current) {
      return;
    }
    const nextKey = keyParts.join('|');
    if (nextKey === viewportKeyRef.current) return;
    viewportKeyRef.current = nextKey;
    const mapCtx = Taro.createMapContext('map');
    const bottomPadding = computeBottomPadding(points, viewportType);
    const baseTopPadding = viewportType === 'order_detail' ? 60 : 24;
    const topPadding = Math.max(baseTopPadding, resolveSafeTopInset() + 32);
    const padding = viewportType === 'order_detail'
      ? [topPadding, 50, bottomPadding, 50]
      : [topPadding, 100, bottomPadding, 100];
    Taro.nextTick(() => {
      mapCtx.includePoints({
        points,
        padding
      });
      if (viewportType === 'dropoff') {
        setTimeout(() => {
          setMapScale(13);
        }, 50);
      }
    });
    if (tripStatus === 6 && viewportType === 'route') {
      tripStatus6ViewportLockedRef.current = true;
    }
  }, [tripStatus, statusRule, routePoints, walkingPoints, startSite?.latitude, startSite?.longitude, endSite?.latitude, endSite?.longitude, vehicleLocation, longitude, latitude, mapBottomPadding]);
 
  useEffect(() => {
    if (!statusRule.translateCar) return;
    if (!carMarkerInitialized.current) return;
    if (!vehicleLocation) return;
    const mapCtx = Taro.createMapContext('map');
    // Taro.nextTick(() => {
    mapCtx.translateMarker({
      markerId: vehicleMarkerId,
      destination: {
        latitude: vehicleLocation.latitude,
        longitude: vehicleLocation.longitude,
      },
      autoRotate: false,
      rotate: typeof vehicleDirection === 'number' ? vehicleDirection : 0,
      duration: 100,
      fail: (err) => {
        console.log(err);
 
      },
    });
    // });
  }, [tripStatus, vehicleLocation, vehicleDirection, vehicleMarkerId]);
 
  const bindSocketListeners = () => {
    if (!orderStatusBound.current && orderStatusHandlerRef.current) {
      wsManager.on('order_status', orderStatusHandlerRef.current);
      orderStatusBound.current = true;
    }
    if (!orderRouteBound.current && orderRouteHandlerRef.current) {
      wsManager.on('order_route', orderRouteHandlerRef.current);
      orderRouteBound.current = true;
    }
    if (!openTrunkBound.current && openTrunkHandlerRef.current) {
      wsManager.on('open_trunk', openTrunkHandlerRef.current);
      openTrunkBound.current = true;
    }
    if (!orderUpdatePriceBound.current && orderUpdatePriceHandlerRef.current) {
      wsManager.on('order_update_price', orderUpdatePriceHandlerRef.current);
      orderUpdatePriceBound.current = true;
    }
  };
 
  const ensureSocketListeners = () => {
    if (wsManager.isConnectedStatus()) {
      bindSocketListeners();
      return;
    }
    if (socketOpenHandlerRef.current) {
      return;
    }
    const handleOpen = () => {
      bindSocketListeners();
    };
    socketOpenHandlerRef.current = handleOpen;
    wsManager.on('open', handleOpen);
  };
 
  // 页面初始化
  useDidShow(() => {
    const { skipPageFlag } = router.params;
    if (skipPageFlag) {
      Taro.showToast({
        title: '您已有进行中的订单',
        icon: 'none',
      })
    }
    const s = Taro.getStorageSync('startSite');
    const e = Taro.getStorageSync('endSite');
    const cachedOrderId = Taro.getStorageSync('orderId');
    const cachedTripStatusStorage = Taro.getStorageSync('tripStatus');
    const cachedTripStatus = Number(cachedTripStatusStorage) || tripStatus;
    if (cachedOrderId) {
      setOrderId(cachedOrderId);
      queryVehicleByOrderId({ orderId: cachedOrderId })
        .then((res: any) => {
          setVehicleInfo(res);
        })
        .catch(() => { });
    }
    if (cachedTripStatusStorage && cachedTripStatusStorage != 1) {
      getOrderActive()
        .then((res: any) => {
          if (!res) {
            return;
          }
          setTrunkStatus([0, 2].includes(res.openTrunk) ? false : true);
          const nextStartSite = {
            id: res.startPointId || '',
            name: res.startPointName || '',
            latitude: res.startLat || 0,
            longitude: res.startLon || 0,
            electronicAreaId: res.xpElectronicFenceAreaId || '',
            time: res.startParkingTimeLimit || 0,
          };
          const nextEndSite = {
            id: res.endPointId || '',
            name: res.endPointName || '',
            latitude: res.endLat || 0,
            longitude: res.endLon || 0,
            electronicAreaId: res.xpElectronicFenceAreaId || '',
            time: res.endParkingTimeLimit || 0,
          };
          Taro.setStorageSync('tripStatus', mapOrderStatusToTripStatus(res.status || 1));
          setTripStatus(mapOrderStatusToTripStatus(res.status || 1));
          Taro.setStorageSync('startSite', nextStartSite);
          Taro.setStorageSync('endSite', nextEndSite);
          setStartSite(nextStartSite);
          setEndSite(nextEndSite);
        })
        .catch(() => { });
    } else {
      if (s) {
        setStartSite(s);
      }
      if (e) {
        setEndSite(e);
      }
    }
    if (cachedOrderId && [4, 5, 6, 7, 8, 9].includes(cachedTripStatus)) {
      requestOrderRoute(cachedOrderId, cachedTripStatus);
    }
 
    if (s && s.latitude && s.longitude) {
      setLatitude(s.latitude);
      setLongitude(s.longitude);
    } else {
      getLocationInfo();
    }
    const originLng = s?.longitude || longitude;
    const originLat = s?.latitude || latitude;
    if (cachedTripStatus === 1 && originLng && originLat && e?.longitude && e?.latitude) {
      requestRouteAndFare(originLat, originLng, e.latitude, e.longitude, true);
    }
    // 初始阶段尝试计算步行路线
    if (tripStatus === 1 && s?.latitude && s?.longitude) {
      updateWalkingRouteForStart();
    }
 
    ensureSocketListeners();
    updateMapViewportPadding();
  });
 
  useEffect(() => {
    const originLng = startSite?.longitude || longitude;
    const originLat = startSite?.latitude || latitude;
    if (tripStatus === 1 && originLng && originLat && endSite?.longitude && endSite?.latitude) {
      requestRouteAndFare(originLat, originLng, endSite.latitude, endSite.longitude);
    }
    // 选择或更新上车点后重新计算步行路线
    if (tripStatus === 1 && startSite?.latitude && startSite?.longitude) {
      updateWalkingRouteForStart();
    }
 
  }, [startSite?.longitude, startSite?.latitude, endSite?.longitude, endSite?.latitude, longitude, latitude]);
 
  useEffect(() => {
    updateMapViewportPadding();
  }, [tripStatus]);
 
  useEffect(() => {
    const timer = setTimeout(() => {
      updateMapViewportPadding();
    }, 50);
    return () => clearTimeout(timer);
  }, [
    tripStatus,
    startSite?.name,
    endSite?.name,
    walkingTime,
    fareEstimate?.waitingTime,
    fareEstimate?.finalFareStr,
    fareEstimate?.originalFareStr,
    fareEstimate?.discountAmount,
  ]);
 
 
  // 获取用户位置信息
  const getLocationInfo = () => {
    Taro.getLocation({ type: 'gcj02' })
      .then(res => {
        setLatitude(res.latitude);
        setLongitude(res.longitude);
      })
  }
 
  // 返回当前位置
  const toOrigin = () => {
    const mapCtx = Taro.createMapContext('map');
    mapCtx.moveToLocation();
  }
 
  const setPopupVisible = (setter: (value: boolean) => void, visible: boolean) => () => setter(visible);
  const handleCloseCustomerService = setPopupVisible(setShowCustomerService, false);
  const handleCloseTipPopup = () => {
    setShowTipPopup(false);
    setTimeout(() => {
      setTipType('');
    }, 600);
  };
 
  const openService = () => {
    const phoneNumber = Taro.getStorageSync('customerServicePhone');
    Taro.makePhoneCall({
      phoneNumber,
    })
  }
 
  // 立即呼叫
  const callImmediately = debounce(async () => {
    if (callSubmitting) {
      return;
    }
    setCallSubmitting(true);
    const otp = await checkOtp(false);
    if (!otp) {
      setCallSubmitting(false);
      jumpTo({ url: '/pages/user/login?hideBack=1' });
      return
    }
    if (!endSite.name) {
      Taro.showToast({
        title: '请选择站点',
        icon: 'none',
      })
      setCallSubmitting(false);
      return
    }
    if (routeAndFareError) {
      setCallSubmitting(false);
      return
    }
    const s = Taro.getStorageSync('startSite');
    if (!s?.latitude || !s?.longitude || !endSite?.latitude || !endSite?.longitude) {
      Taro.showToast({
        title: '请先选择起终点',
        icon: 'none',
      })
      setCallSubmitting(false);
      return
    }
    let maxDistance = distanceConfig?.maxDistance;
    let minDistance = distanceConfig?.minDistance;
    if (!maxDistance || !minDistance) {
      try {
        const res = await getOrderDistance();
        if (res) {
          const nextConfig = {
            maxDistance: res.maxDistance,
            minDistance: res.minDistance,
            adsorptionDistance: res.adsorptionDistance
          };
          setDistanceConfig(nextConfig);
          maxDistance = nextConfig.maxDistance;
          minDistance = nextConfig.minDistance;
        }
      } catch { }
    }
    if (maxDistance) {
      try {
        const loc = await Taro.getLocation({ type: 'gcj02' });
        const distance = getDistance(loc.latitude, loc.longitude, s.latitude, s.longitude);
        if (distance > maxDistance) {
          setTipType('2');
          setShowTipPopup(true);
          setCallSubmitting(false);
          return;
        }
      } catch { }
    }
    if (minDistance) {
      const distance = getDistance(s.latitude, s.longitude, endSite.latitude, endSite.longitude);
      if (distance < minDistance) {
        setTipType('1');
        setShowTipPopup(true);
        setCallSubmitting(false);
        return;
      }
    }
    const selectedCity = Taro.getStorageSync('selectedCity');
    let openCityId = selectedCity?.id || 0;
 
    // 如果缓存中没有城市ID,尝试通过定位重新匹配一次
    if (!openCityId) {
      try {
        const loc = await Taro.getLocation({ type: 'gcj02' });
        const data = await getAddressByLocation(loc.longitude, loc.latitude);
        const addressComponent = data?.regeocodeData?.addressComponent;
        if (addressComponent) {
          const { city, province, adcode } = addressComponent;
          const cityName = (city && typeof city === 'string' && city.length > 0) ? city : province;
          const cityCode = convertAdcodeToCityCode(adcode, cityName, province);
          const cityInfo = await getCityInfoWithId(cityCode, cityName);
          if (cityInfo?.id) {
            openCityId = cityInfo.id;
            Taro.setStorageSync('selectedCity', cityInfo);
          }
        }
      } catch (e) {
        console.error('Failed to fetch city info before order:', e);
      }
    }
 
    // 如果还是拿不到城市ID,拦截下单
    if (!openCityId) {
      Taro.showToast({
        title: '未能获取所在城市信息,请重试',
        icon: 'none',
      });
      setCallSubmitting(false);
      return;
    }
 
    const waitingTime = Number(fareEstimate?.waitingTime || 0);
    const estimatedTime = formatDateTime(new Date(Date.now() + waitingTime * 60 * 1000));
    const cachedCouponId = Taro.getStorageSync('selectedCouponId') || '';
    const payload: any = {
      endPointId: endSite.id,
      openCityId: openCityId,
      placementAddress: s?.name,
      placementLat: s?.latitude,
      placementLon: s?.longitude,
      startPointId: s?.id,
      xpElectronicFenceAreaId: s?.electronicAreaId || endSite?.electronicAreaId || '',
      estimatedTime: estimatedTime,
    };
    if (cachedCouponId) {
      payload.userCouponId = cachedCouponId;
    }
    try {
      const res = await saveOrder(payload);
      let status_code = res.orderId ? 1 : 0;
      reportEvent('RT_xcx_order_submit', {
        total_amount: fareEstimate.originalFare,
        payable_amount: fareEstimate.finalFare,
        coupon_id: cachedCouponId,
        status_code: status_code,
      })
      if (typeof res == 'string') {
        Taro.showToast({
          title: res,
          icon: 'none',
          mask: true,
        })
        setTimeout(() => {
          Taro.reLaunch({
            url: '/pages/home/index',
          })
        }, 1500);
        return
      }
      if (!res?.orderId) {
        Taro.showToast({
          title: '下单失败,请重试',
          icon: 'none',
        });
        setCallSubmitting(false);
        return;
      }
      Taro.removeStorageSync('selectedCouponId');
      Taro.setStorageSync('orderId', res.orderId);
      setOrderId(res.orderId);
    } catch (error) {
      setCallSubmitting(false);
      return
    }
    setTripStatus(2);
    if (!authSuccessBound.current && authSuccessHandlerRef.current) {
      wsManager.on('auth_success', authSuccessHandlerRef.current);
      authSuccessBound.current = true;
    }
    if (!orderStatusBound.current && orderStatusHandlerRef.current) {
      wsManager.on('order_status', orderStatusHandlerRef.current);
      orderStatusBound.current = true;
    }
    if (!orderRouteBound.current && orderRouteHandlerRef.current) {
      wsManager.on('order_route', orderRouteHandlerRef.current);
      orderRouteBound.current = true;
    }
    if (!orderUpdatePriceBound.current && orderUpdatePriceHandlerRef.current) {
      wsManager.on('order_update_price', orderUpdatePriceHandlerRef.current);
      orderUpdatePriceBound.current = true;
    }
  }, 500)
 
  // 确认取消
  const handleConfirmCancel = async () => {
    if (cancelType === 5) {
      handleOpenCancelPopupWithType(5);
      return;
    }
    const targetOrderId = orderId || Taro.getStorageSync('orderId');
    if (targetOrderId) {
      try {
        await cancelOrder(targetOrderId);
        Taro.showToast({
          title: '行程已取消',
          icon: 'success',
        });
        setOrderId('');
        clearOrderTripStorage();
        Taro.removeStorageSync('pickupEndTime');
        Taro.removeStorageSync('waitingTimerStartAt');
        Taro.removeStorageSync('waitingTimerElapsed');
        setTripStatus(10);
        setCancelType(4);
        return
      } catch (error) {
        Taro.showToast({
          title: '取消订单失败,请重试',
          icon: 'none',
        });
        return;
      }
    } else {
      setShowCancelPopup(false);
      setTripStatus(1);
      updateWalkingRouteForStart();
      const s = Taro.getStorageSync('startSite');
      const e = Taro.getStorageSync('endSite');
      if (s?.latitude && s?.longitude && e?.longitude && e?.latitude) {
        requestRouteAndFare(s.latitude, s.longitude, e.latitude, e.longitude, true);
      }
    }
  }
 
  // 弹窗操作
  const handleCloseCancelPopup = setPopupVisible(setShowCancelPopup, false);
  // 订单超时再来一单
  const handleOpenCancelPopupWithType = (type: number) => {
    setOrderId('');
    clearOrderTripStorage();
    setCancelType(type);
    setShowCancelPopup(false);
    setTripStatus(1);
    updateWalkingRouteForStart();
    const s = Taro.getStorageSync('startSite');
    const e = Taro.getStorageSync('endSite');
    if (s?.latitude && s?.longitude && e?.longitude && e?.latitude) {
      requestRouteAndFare(s.latitude, s.longitude, e.latitude, e.longitude, true);
    }
  };
  // 打开取消弹窗
  const handleOpenCancelPopupByTripStatus = (status: number, durationDisplay?: any) => {
    if (durationDisplay && ![3, 5].includes(status)) {
      setCancelType(2);
      setShowCancelPopup(true);
      return
    }
    if ([2, 3].includes(status)) {
      setCancelType(1);
    }
    if (status == 4) {
      setCancelType(2);
    }
    if (status == 5) {
      setCancelType(3);
    }
    setShowCancelPopup(true);
  };
  const handleCloseAnnouncementsPopup = setPopupVisible(setShowAnnouncementsPopup, false);
  const handleOpenAnnouncementsPopup = setPopupVisible(setShowAnnouncementsPopup, true);
  const handleOpenOverRoutePopup = setPopupVisible(setShowOverRoutePopup, true);
  const handleCloseOverRoutePopup = setPopupVisible(setShowOverRoutePopup, false);
 
  // 确认结束行程
  const handleConfirmOverRoute = () => {
    setShowOverRoutePopup(false);
    setTripStatus(8);
  }
  const handleFinishCountdownTimeout = async () => {
    const targetOrderId = orderId || Taro.getStorageSync('orderId');
    if (!targetOrderId) return;
    try {
      await endOrder(targetOrderId);
    } catch (error) {
    }
    setTripStatus(8);
  }
 
  // 确认支付
  const handlePay = async () => {
    const targetOrderId = orderId || Taro.getStorageSync('orderId');
    if (!targetOrderId) {
      Taro.showToast({
        title: '订单信息缺失,无法支付',
        icon: 'none',
      })
      return
    }
    const payload = {
      orderId: targetOrderId,
    };
    try {
      await getOrderPayment(payload);
      Taro.showToast({
        title: '支付成功',
        icon: 'none',
      })
      setTripStatus(9);
      Taro.setStorageSync('tripStatus', 9);
    } catch (error) {
      Taro.showToast({
        title: '支付失败,请重试',
        icon: 'none',
      })
      return
    }
  }
 
  const handleClosePassengerNotice = () => {
    setShowPassengerNotice(false);
  };
  const handleOpenPassengerNotice = () => {
    setShowPassengerNotice(true);
  };
 
  // 打开评价弹窗
  const handleOpenEvaluatePopup = setPopupVisible(setShowEvaluatePopup, true);
  const handleCloseEvaluatePopup = () => {
    setEvaluateCloseVersion(v => v + 1);
    setShowEvaluatePopup(false);
  };
 
  // 确认评价
  const handleConfirmEvaluate = () => {
    setEvaluateSubmitVersion(v => v + 1);
    handleCloseEvaluatePopup();
  };
 
  const toSelectSite = (pageType: 'start' | 'end') => {
    Taro.navigateTo({
      url: `/robotaxi/pages/site-search/index?pageType=${pageType}&longitude=${startSite.longitude}&latitude=${startSite.latitude}&electronicAreaId=${startSite.electronicAreaId}`
    })
  }
 
  // 点击气泡
  const handleCalloutTap = (e) => {
    if (isCheckedEnter.current) {
      isCheckedEnter.current = false;
      return;
    }
    if (tripStatus === 1) {
      // 仅在发布行程时,点击标记用于选择起点或终点
      const markerId = e.detail.markerId;
      toSelectSite(markerId === 1 ? 'start' : 'end');
    }
  }
 
  const toCoupon = () => {
    if (Taro.getStorageSync('has_show_privicy_Robotaxi') !== 'true') {
      Taro.showToast({
        title: '请先同意协议',
        icon: 'none'
      });
      return;
    }
    Taro.navigateTo({
      url: '/robotaxi/pages/coupon/index',
    })
  }
 
  const toOrder = () => {
    if (Taro.getStorageSync('has_show_privicy_Robotaxi') !== 'true') {
      Taro.showToast({
        title: '请先同意协议',
        icon: 'none'
      });
      return;
    }
    Taro.navigateTo({
      url: '/robotaxi/pages/order/index',
    })
  }
 
  const toBack = () => {
    if (tripStatus == 9 || tripStatus == 1) {
      clearOrderTripStorage();
      Taro.removeStorageSync('endSite');
    }
    Taro.reLaunch({
      url: '/pages/robotaxi/home/index'
    })
  }
 
  const handleRegionChange = (e) => {
    if (e?.type === 'begin') {
      setWaitingRadarVisible(false);
      setCarCalloutVisible(false);
      setArriveCalloutVisible(false);
      return;
    }
    if (e?.type === 'end') {
      setWaitingRadarVisible(true);
      updateWaitingRadarPosition();
      updateCarCalloutPosition();
      updateArriveCalloutPosition();
    }
  };
 
  const handleToggleDetailFade = (expanded: boolean, hasFare: boolean) => {
    if (expanded && hasFare) {
      setOriginOpacity(0);
    } else {
      setOriginOpacity(1);
    }
    updateMapViewportPadding();
  };
 
  const durationDisplay = formatDurationDisplay(routeDuration);
  const mapLongitude = longitude ?? 116.397128;
  const mapLatitude = latitude ?? 39.916527;
 
  return (
    <View className="home-container">
      <Map
        id="map"
        longitude={mapLongitude}
        latitude={mapLatitude}
        scale={mapScale}
        markers={markers}
        polyline={polyline}
        showLocation={!!longitude && showLocationFlag}
        onCalloutTap={handleCalloutTap}
        onRegionChange={handleRegionChange}
        style={{ width: '100%', height: '87vh' }}
      >
        {/* 自定义callout */}
        {
          !(isAndroid && [1, 8, 9].includes(tripStatus)) && markers.map((item, index) => {
            const calloutKey = `callout-${item.id}-${item.name || ''}`;
            const isWaiting = [2, 3].includes(tripStatus) && index === 0;
 
            if (isWaiting) {
              return (
                <CoverView slot="callout" marker-id={item.id} key={calloutKey} className="waiting-callout">
                  <CoverView className="waiting-callout-content">
                    {/* <CoverView className="waiting-callout-bg">
                      <CoverImage className="waiting-callout-bg-img" src={waitingCalloutBgSrc} />
                      <CoverView className="waiting-callout-bg-text">{formatDurationToClock(elapsedSeconds)}</CoverView>
                    </CoverView> */}
                    <CoverView className={`waiting-callout-txt ${!isAndroid && 'pr-6'}`}>
                      {item.name}
                      {
                        !isAndroid &&
                        <CoverView style={{ color: 'transparent' }}>占</CoverView>
                      }
                    </CoverView>
                  </CoverView>
                  <CoverImage className="waiting-radar" src={waitingRadarSrc} />
                </CoverView>
              )
            }
 
            if (item.name === '车辆位置' && isAndroid && [4, 6].includes(tripStatus)) {
              return null;
            }
            return (
              <CoverView slot="callout" marker-id={item.id} key={calloutKey} className="custom-callout">
                {
                  (item.name !== '车辆位置' && !(item.id === 2 && [7].includes(tripStatus))) &&
                  <CoverView className={`custom-callout-content ${isAndroid && 'txt-center '}`} style={{ zIndex: 1 }}>
                    <CoverView style={{ lineHeight: '22px', display: 'flex', alignItems: 'center' }}>{item.name}</CoverView>
                    {
                      isAndroid &&
                      <CoverView style={{ width: '2px' }}></CoverView>
                    }
                    {
                      tripStatus == 1 && <CoverImage className="custom-callout-icon" src={customCalloutIconSrc} />
                    }
                  </CoverView>
                }
                {
                  (item.name === '车辆位置' && [4, 6].includes(tripStatus) && !isAndroid) &&
                  <CoverView className="custom-callout-content" style={{ padding: '6px 10px', minWidth: '40px', justifyContent: 'center', zIndex: 2 }}>
                    <CoverView className="car-time">
                      <CoverView className="car-time-num">{routeDistance?.value ?? 0}</CoverView>
                      <CoverView>{routeDistance?.unit === 'm' ? '米' : '公里'}</CoverView>
                      <CoverView style={{ marginLeft: '2.5px' }} className="car-time-num">{durationDisplay.value}</CoverView>
                      <CoverView>{durationDisplay.unit}</CoverView>
                    </CoverView>
                  </CoverView>
                }
                {
                  (item.id === 2 && [7].includes(tripStatus) && !isAndroid) &&
                  <CoverView className="custom-callout-content">
                    已到达
                  </CoverView>
                }
              </CoverView>
            )
          })
        }
        {shouldShowWaitingRadar && waitingRadarVisible && (
          <Image className="waiting-radar-img" src={waitingRadarSrc} webp={true} style={waitingRadarStyle} />
        )}
        {isAndroid && carCalloutVisible && (
          <View className="car-callout-android" style={carCalloutStyle}>
            <View className="custom-callout-content" style={{ padding: '6px 10px' }}>
              <View className="car-time" style={{ alignItems: 'flex-end' }}>
                <View className="car-time-num">{routeDistance?.value ?? 0}</View>
                <View style={{ flexShrink: 0 }}>{routeDistance?.unit === 'm' ? '米' : '公里'}</View>
                <View style={{ marginLeft: '2.5px' }} className="car-time-num">{durationDisplay.value}</View>
                <View style={{ flexShrink: 0 }}>{durationDisplay.unit}</View>
              </View>
            </View>
          </View>
        )}
        {isAndroid && arriveCalloutVisible && (
          <View className="car-callout-android" style={arriveCalloutStyle}>
            <View className="custom-callout-content">
              已到达
            </View>
          </View>
        )}
        {/* 返回按钮 */}
        <View onClick={toBack} className="select-city">
          <Image className="select-city-icon" src={backIcon} />
        </View>
        {/* 地图浮层入口 */}
        <View className="map-entry">
          <Image onClick={(e) => { isCheckedEnter.current = true; openService() }} className="map-entry-icon" src={contactService} />
          <View className="split-line"></View>
          <Image onClick={(e) => { isCheckedEnter.current = true; toCoupon() }} className="map-entry-icon" src={coupon} />
          <View className="split-line"></View>
          <Image onClick={(e) => { isCheckedEnter.current = true; toOrder() }} className="map-entry-icon" src={suggest} />
        </View>
        <View className="container">
          <View className="container-inner">
            {/* 复位按钮 */}
            {
              ![7, 8, 9].includes(tripStatus) &&
              <View className="origin-box" style={{ opacity: originBoxHidden ? 0 : originOpacity, transition: 'opacity 0.2s ease-out', pointerEvents: originBoxHidden ? 'none' : 'auto' }}>
                <Image onClick={toOrigin} className="origin-icon" src={originIcon} />
              </View>
            }
            <View catchMove onClick={(e) => e.stopPropagation()}>
              {/* 发布路线 */}
              {
                (tripStatus == 1 && startSite && endSite) &&
                <ReleaseRoute
                  startSite={startSite}
                  endSite={endSite}
                  callImmediately={callImmediately}
                  fareEstimate={fareEstimate}
                  handleOpenPassengerNotice={handleOpenPassengerNotice}
                  walkingTime={walkingTime}
                  isCallDisabled={routeAndFareError || callSubmitting}
                />
              }
              {/* 发布中弹窗 */}
              {
                tripStatus == 2 &&
                <ReleaseBeBeing
                  handleOpenCancelPopup={() => handleOpenCancelPopupByTripStatus(2)}
                  onFinish={() => {
                    setTripStatus(3);
                    Taro.setStorageSync('tripStatus', 3);
                  }}
                />
              }
              {/* 呼叫车辆弹窗 */}
              {
                tripStatus >= 3 && tripStatus !== 10 &&
                <CallingCar
                  key={tripStatus}
                  orderId={orderId}
                  tripStatus={tripStatus}
                  finishCountdownEnabled={finishCountdownEnabled}
                  vehicleInfo={vehicleInfo}
                  handleOpenCancelPopup={(durationDisplay) => handleOpenCancelPopupByTripStatus(tripStatus, durationDisplay)}
                  handleCancelTimeout={() => handleOpenCancelPopupWithType(4)}
                  handleFinishTimeout={handleFinishCountdownTimeout}
                  resetDetailVersion={resetDetailVersion}
                  priceUpdateVersion={priceUpdateVersion}
                  evaluateSubmitVersion={evaluateSubmitVersion}
                  evaluateCloseVersion={evaluateCloseVersion}
                  handleOpenAnnouncementsPopup={handleOpenAnnouncementsPopup}
                  handleOpenOverRoutePopup={handleOpenOverRoutePopup}
                  handlePay={handlePay}
                  updateStatus={() => setTripStatus(prev => prev + 1)}
                  handleOpenEvaluatePopup={handleOpenEvaluatePopup}
                  estimatedWaitMinutes={fareEstimate?.waitingTime}
                  routeDurationSeconds={routeDuration}
                  onToggleDetailFade={handleToggleDetailFade}
                  orderTrunkStatus={trunkStatus}
                />
              }
            </View>
          </View>
        </View>
      </Map>
      {/* 客服弹窗 */}
      <CustomerServicePopup
        show={showCustomerService}
        onClose={handleCloseCustomerService}
      />
      {/* 取消弹窗 */}
      <CancelPopup
        show={showCancelPopup}
        cancelType={cancelType}
        startSite={startSite}
        endSite={endSite}
        waitMinutes={fareEstimate?.waitingTime}
        tripStatus={tripStatus}
        routeDurationSeconds={routeDuration}
        discountAmount={fareEstimate?.discountAmount}
        onClose={handleCloseCancelPopup}
        onConfirm={handleConfirmCancel}
      />
      {/* 安全注意事项弹窗 */}
      <AnnouncementsPopup
        show={showAnnouncementsPopup}
        onClose={handleCloseAnnouncementsPopup}
      />
      {/* 结束行程弹窗 */}
      <OverRoute
        show={showOverRoutePopup}
        onClose={handleCloseOverRoutePopup}
        onConfirm={handleConfirmOverRoute}
      />
      <TipPopup
        show={showTipPopup}
        onClose={handleCloseTipPopup}
        tipType={tipType}
      />
      {/* 乘车需知弹窗 */}
      {
        !showCancelPopup &&
        <PassengerNotice
          show={showPassengerNotice}
          onClose={handleClosePassengerNotice}
        />
      }
      {/* 评价弹窗 */}
      <EvaluatePopup
        show={showEvaluatePopup}
        orderId={orderId}
        orderRating={1}
        onClose={handleCloseEvaluatePopup}
        onConfirm={handleConfirmEvaluate}
      />
    </View>
  )
}