张世豪
8 小时以前 13d032241e1a2938a8be4f64c9171e1240e9ea1e
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
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
package zhuye;
 
import javax.swing.*;
import javax.swing.Timer;
 
import baseStation.BaseStation;
import set.Setsys;
import baseStation.BaseStationDialog;
 
import java.awt.*;
import java.awt.event.*;
 
import chuankou.dellmessage;
import chuankou.sendmessage;
import chuankou.SerialPortService;
import dikuai.Dikuai;
import dikuai.Dikuaiguanli;
import dikuai.addzhangaiwu;
import gecaoji.Device;
import gecaoji.Gecaoji;
import gecaoji.MowerBoundaryChecker;
import publicway.buttonset;
import set.Sets;
import set.debug;
import udpdell.UDPServer;
import zhangaiwu.AddDikuai;
import yaokong.RemoteControlDialog;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.awt.geom.Point2D;
 
import publicway.Gpstoxuzuobiao;
import publicway.Fanhuibutton;
 
/**
 * 首页界面 - 适配6.5寸竖屏,使用独立的MapRenderer进行绘制
 */
public class Shouye extends JPanel {
    private static final long serialVersionUID = 1L;
    private static Shouye instance;
 
    // 主题颜色
    private final Color THEME_COLOR = new Color(46, 139, 87);
    private final Color THEME_HOVER_COLOR = new Color(30, 107, 69);
    private final Color BACKGROUND_COLOR = new Color(250, 250, 250);
    private final Color PANEL_BACKGROUND = new Color(255, 255, 255);
    private final Color STATUS_PAUSE_COLOR = new Color(255, 165, 0);
 
    // 组件
    private JPanel headerPanel;
    private JPanel mainContentPanel;
    private JPanel controlPanel;
    private JPanel navigationPanel;
    private JPanel visualizationPanel;
 
    // 按钮
    private JButton startBtn;
    private JButton stopBtn;
    private JButton legendBtn;
    private JButton remoteBtn;
    private JButton areaSelectBtn;
    private JButton baseStationBtn;
    private JButton bluetoothBtn;
    private JLabel dataPacketCountLabel;
    private JLabel mowerSpeedValueLabel;
    private JLabel mowerSpeedUnitLabel;
    private JLabel mowingProgressLabel;
    private gpszhuangtai fixQualityIndicator;
 
    // 导航按钮
    private JButton homeNavBtn;
    private JButton areasNavBtn;
    private JButton settingsNavBtn;
 
    // 状态显示
    private JLabel statusLabel;
    private JLabel speedLabel;  // 速度显示标签
    private JLabel areaNameLabel;
    private JLabel drawingBoundaryLabel;  // 正在绘制边界状态标签
    private JLabel navigationPreviewLabel;  // 导航预览模式标签
    
    // 边界警告相关
    private Timer boundaryWarningTimer;  // 边界警告检查定时器
    private Timer warningBlinkTimer;  // 警告图标闪烁定时器
    private boolean isMowerOutsideBoundary = false;  // 割草机是否在边界外
    private boolean warningIconVisible = true;  // 警告图标显示状态(用于闪烁)
    
    // 以割草机为中心视图模式
    private boolean centerOnMowerMode = false;  // 是否处于以割草机为中心的模式
 
    // 当前选中的导航按钮
    private JButton currentNavButton;
 
    // 对话框引用
    private LegendDialog legendDialog;
    // 使用完全限定名以避免与同包的 RemoteControlDialog 冲突,确保使用 yaokong 包下的实现
    private yaokong.RemoteControlDialog remoteDialog;
    private AreaSelectionDialog areaDialog;
    private BaseStationDialog baseStationDialog;
    private Sets settingsDialog;
    private BaseStation baseStation;
 
    // 地图渲染器
    private MapRenderer mapRenderer;
    
    private boolean pathPreviewActive;
    
    private final Consumer<String> serialLineListener = line -> {
        SwingUtilities.invokeLater(() -> {
            updateDataPacketCountLabel();
            // 如果收到$GNGGA数据,立即更新拖尾
            if (line != null && line.trim().startsWith("$GNGGA")) {
                if (mapRenderer != null && !pathPreviewActive) {
                    mapRenderer.forceUpdateIdleMowerTrail();
                }
            }
        });
    };
    private static final int FLOAT_ICON_SIZE = 32;
    private JButton endDrawingButton;
    private JButton drawingPauseButton;
    private JPanel floatingButtonPanel;
    private JPanel floatingButtonColumn;
    private Runnable endDrawingCallback;
    private JButton pathPreviewReturnButton;
    private Runnable pathPreviewReturnAction;
    private JButton settingsReturnButton;  // 返回系统设置页面的悬浮按钮
    private JButton saveManualBoundaryButton;  // 保存手动绘制边界的按钮
    private String previewRestoreLandNumber;
    private String previewRestoreLandName;
    private boolean drawingPaused;
    private ImageIcon pauseIcon;
    private ImageIcon pauseActiveIcon;
    private ImageIcon endIcon;
    private ImageIcon bluetoothIcon;
    private ImageIcon bluetoothLinkedIcon;
    private JPanel circleGuidancePanel;
    private JLabel circleGuidanceLabel;
    private JButton circleGuidancePrimaryButton;
    private JButton circleGuidanceSecondaryButton;
    private int circleGuidanceStep;
    private JDialog circleGuidanceDialog;
    private boolean circleDialogMode;
    private ComponentAdapter circleDialogOwnerAdapter;
    private static final double METERS_PER_DEGREE_LAT = 111320.0d;
    private static final double HANDHELD_DUPLICATE_THRESHOLD_METERS = 0.01d;
    private final List<double[]> circleCapturedPoints = new ArrayList<>();
    private double[] circleBaseLatLon;
    private Timer circleDataMonitor;
    private Coordinate lastCapturedCoordinate;
    private boolean handheldCaptureActive;
    private int handheldCapturedPoints;
    private final List<Point2D.Double> handheldTemporaryPoints = new ArrayList<>();
    private final List<Point2D.Double> mowerTemporaryPoints = new ArrayList<>();
    private enum BoundaryCaptureMode { NONE, HANDHELD, MOWER }
    private BoundaryCaptureMode activeBoundaryMode = BoundaryCaptureMode.NONE;
    private boolean mowerBoundaryCaptureActive;
    private Timer mowerBoundaryMonitor;
    private Coordinate lastMowerCoordinate;
    private double[] mowerBaseLatLon;
    private boolean startButtonShowingPause = true;
    private boolean stopButtonActive = false;
    private boolean bluetoothConnected = false;
    private Timer mowerSpeedRefreshTimer;
    private boolean drawingControlModeActive;
    private boolean storedStartButtonShowingPause;
    private boolean storedStopButtonActive;
    private String storedStatusBeforeDrawing;
    private boolean handheldCaptureInlineUiActive;
    private WangfanDraw returnPathDrawer;  // 往返路径绘制管理器
    private Timer handheldCaptureStatusTimer;
    private String handheldCaptureStoredStatusText;
    private Color handheldStartButtonOriginalBackground;
    private Color handheldStartButtonOriginalForeground;
    private Color handheldStopButtonOriginalBackground;
    private Color handheldStopButtonOriginalForeground;
 
    public Shouye() {
        instance = this;
        baseStation = new BaseStation();
        baseStation.load();
        dellmessage.registerLineListener(serialLineListener);
        initializeUI();
        setupEventHandlers();
        scheduleIdentifierCheck();
    }
 
    public static Shouye getInstance() {
        return instance;
    }
 
    private void initializeUI() {
        setLayout(new BorderLayout());
        setBackground(BACKGROUND_COLOR);
 
        // 创建各个面板
        createHeaderPanel();
        createMainContentPanel();
        createControlPanel();
        createNavigationPanel();
 
        // 添加到主面板
        add(headerPanel, BorderLayout.NORTH);
        add(mainContentPanel, BorderLayout.CENTER);
        add(controlPanel, BorderLayout.SOUTH);
 
        // 初始化地图渲染器
        mapRenderer = new MapRenderer(visualizationPanel);
        applyIdleTrailDurationFromSettings();
        
        // 初始化往返路径绘制管理器
        returnPathDrawer = new WangfanDraw(this, mapRenderer, new WangfanDraw.DrawingHelper() {
            @Override
            public double[] resolveBaseLatLon() {
                return resolveCircleBaseLatLon();
            }
            
            @Override
            public Coordinate getLatestCoordinate() {
                return Shouye.this.getLatestCoordinate();
            }
            
            @Override
            public double parseDMToDecimal(String dmm, String direction) {
                return Shouye.this.parseDMToDecimal(dmm, direction);
            }
            
            @Override
            public double[] convertLatLonToLocal(double lat, double lon, double baseLat, double baseLon) {
                return Shouye.this.convertLatLonToLocal(lat, lon, baseLat, baseLon);
            }
            
            @Override
            public boolean arePointsClose(Point2D.Double a, Point2D.Double b) {
                return Shouye.this.arePointsClose(a, b);
            }
            
            @Override
            public void enterDrawingControlMode() {
                Shouye.this.enterDrawingControlMode();
            }
            
            @Override
            public void exitDrawingControlMode() {
                Shouye.this.exitDrawingControlMode();
            }
            
            @Override
            public boolean isDrawingPaused() {
                return drawingPaused;
            }
        });
        
        // 设置 MapRenderer 的往返路径绘制管理器
        if (mapRenderer != null) {
            mapRenderer.setReturnPathDrawer(returnPathDrawer);
        }
 
        // 初始化对话框引用为null,延迟创建
        legendDialog = null;
        remoteDialog = null;
        areaDialog = null;
        baseStationDialog = null;
        settingsDialog = null;
 
        // 设置默认状态
        setNavigationActive(homeNavBtn);
 
        initializeDefaultAreaSelection();
        refreshMapForSelectedArea();
        
        // 启动边界警告检查定时器
        startBoundaryWarningTimer();
    }
 
    private void scheduleIdentifierCheck() {
        HierarchyListener listener = new HierarchyListener() {
            @Override
            public void hierarchyChanged(HierarchyEvent e) {
                if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0 && Shouye.this.isShowing()) {
                    Shouye.this.removeHierarchyListener(this);
                    SwingUtilities.invokeLater(() -> {
                        Shouye.this.checkIdentifiersAndPromptIfNeeded();
                        Shouye.this.showInitialMowerSelfCheckDialogIfNeeded();
                        // 设置窗口关闭监听器,在关闭时保存缩放比例
                        setupWindowCloseListener();
                    });
                }
            }
        };
        addHierarchyListener(listener);
    }
    
    /**
     * 设置窗口关闭监听器,在窗口关闭时保存当前缩放比例
     */
    private void setupWindowCloseListener() {
        Window window = SwingUtilities.getWindowAncestor(this);
        if (window != null && window instanceof JFrame) {
            JFrame frame = (JFrame) window;
            frame.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    // 保存当前缩放比例
                    saveCurrentScale();
                    // 停止边界警告定时器
                    if (boundaryWarningTimer != null && boundaryWarningTimer.isRunning()) {
                        boundaryWarningTimer.stop();
                    }
                    // 停止闪烁定时器
                    if (warningBlinkTimer != null && warningBlinkTimer.isRunning()) {
                        warningBlinkTimer.stop();
                    }
                }
            });
        }
    }
    
    /**
     * 保存当前地图缩放比例和视图中心坐标到配置文件
     */
    public void saveCurrentScale() {
        if (mapRenderer != null) {
            double currentScale = mapRenderer.getScale();
            double translateX = mapRenderer.getTranslateX();
            double translateY = mapRenderer.getTranslateY();
            Setsys setsys = new Setsys();
            // 保留2位小数
            setsys.updateProperty("mapScale", String.format("%.2f", currentScale));
            setsys.updateProperty("viewCenterX", String.format("%.2f", translateX));
            setsys.updateProperty("viewCenterY", String.format("%.2f", translateY));
        }
    }
    
    /**
     * 启动边界警告检查定时器
     */
    private void startBoundaryWarningTimer() {
        // 边界检查定时器:每500ms检查一次割草机是否在边界内
        boundaryWarningTimer = new Timer(500, e -> {
            checkMowerBoundaryStatus();
            // 同时更新蓝牙图标状态
            updateBluetoothButtonIcon();
        });
        boundaryWarningTimer.setInitialDelay(0);
        boundaryWarningTimer.start();
        
        // 闪烁定时器:每1秒切换一次警告图标显示状态
        warningBlinkTimer = new Timer(1000, e -> {
            if (isMowerOutsideBoundary) {
                warningIconVisible = !warningIconVisible;
                if (visualizationPanel != null) {
                    visualizationPanel.repaint();
                }
            }
        });
        warningBlinkTimer.setInitialDelay(0);
        warningBlinkTimer.start();
    }
    
    /**
     * 切换以割草机为中心的模式
     */
    private void toggleCenterOnMowerMode() {
        centerOnMowerMode = !centerOnMowerMode;
        
        if (centerOnMowerMode) {
            // 开启模式:立即将视图中心移动到割草机位置
            updateViewToCenterOnMower();
        }
        // 关闭模式时不需要做任何操作,用户已经可以自由移动地图
        
        // 更新图标显示(重绘以切换图标)
        if (visualizationPanel != null) {
            visualizationPanel.repaint();
        }
    }
    
    /**
     * 更新视图中心到割草机位置
     */
    private void updateViewToCenterOnMower() {
        if (mapRenderer == null) {
            return;
        }
        
        Gecaoji mower = mapRenderer.getMower();
        if (mower != null && mower.hasValidPosition()) {
            Point2D.Double mowerPosition = mower.getPosition();
            if (mowerPosition != null) {
                // 获取当前缩放比例
                double currentScale = mapRenderer.getScale();
                // 设置视图变换,使割草机位置对应到屏幕中心
                // translateX = -mowerX, translateY = -mowerY 可以让割草机在屏幕中心
                mapRenderer.setViewTransform(currentScale, -mowerPosition.x, -mowerPosition.y);
            }
        }
    }
    
    /**
     * 检查割草机边界状态
     */
    private void checkMowerBoundaryStatus() {
        // 如果处于以割草机为中心的模式,实时更新视图中心
        if (centerOnMowerMode) {
            updateViewToCenterOnMower();
        }
        
        // 检查是否在作业中
        if (statusLabel == null || !"作业中".equals(statusLabel.getText())) {
            // 不在作业中,重置状态
            if (isMowerOutsideBoundary) {
                isMowerOutsideBoundary = false;
                warningIconVisible = true;
                if (visualizationPanel != null) {
                    visualizationPanel.repaint();
                }
            }
            return;
        }
        
        // 在作业中,检查是否在边界内
        if (mapRenderer == null) {
            return;
        }
        
        // 获取当前边界
        List<Point2D.Double> boundary = mapRenderer.getCurrentBoundary();
        if (boundary == null || boundary.size() < 3) {
            // 没有边界,重置状态
            if (isMowerOutsideBoundary) {
                isMowerOutsideBoundary = false;
                warningIconVisible = true;
                if (visualizationPanel != null) {
                    visualizationPanel.repaint();
                }
            }
            return;
        }
        
        // 获取割草机位置
        Gecaoji mower = mapRenderer.getMower();
        if (mower == null || !mower.hasValidPosition()) {
            // 无法获取位置,重置状态
            if (isMowerOutsideBoundary) {
                isMowerOutsideBoundary = false;
                warningIconVisible = true;
                if (visualizationPanel != null) {
                    visualizationPanel.repaint();
                }
            }
            return;
        }
        
        Point2D.Double mowerPosition = mower.getPosition();
        if (mowerPosition == null) {
            return;
        }
        
        // 使用 MowerBoundaryChecker 检查是否在边界内
        boolean isInside = MowerBoundaryChecker.isInsideBoundaryPoints(
            boundary, 
            mowerPosition.x, 
            mowerPosition.y
        );
        
        // 更新状态
        boolean wasOutside = isMowerOutsideBoundary;
        isMowerOutsideBoundary = !isInside;
        
        // 如果状态改变,立即重绘
        if (wasOutside != isMowerOutsideBoundary) {
            warningIconVisible = true;
            if (visualizationPanel != null) {
                visualizationPanel.repaint();
            }
        }
    }
 
    private void showInitialMowerSelfCheckDialogIfNeeded() {
        // 已移除进入主页时的自检提示(按用户要求删除)
        // 以前这里会调用 zijian.showInitialPromptIfNeeded(...) 展示自检对话框,现已禁用。
    }
 
    private void applyIdleTrailDurationFromSettings() {
        if (mapRenderer == null) {
            return;
        }
        int durationSeconds = MapRenderer.DEFAULT_IDLE_TRAIL_DURATION_SECONDS;
        String configuredValue = Setsys.getPropertyValue("idleTrailDurationSeconds");
        if (configuredValue != null) {
            String trimmed = configuredValue.trim();
            if (!trimmed.isEmpty()) {
                try {
                    int parsed = Integer.parseInt(trimmed);
                    if (parsed >= 5 && parsed <= 600) {
                        durationSeconds = parsed;
                    }
                } catch (NumberFormatException ignored) {
                    durationSeconds = MapRenderer.DEFAULT_IDLE_TRAIL_DURATION_SECONDS;
                }
            }
        }
        mapRenderer.setIdleTrailDurationSeconds(durationSeconds);
        
        // 应用边界距离显示设置和测量模式设置
        Setsys setsys = new Setsys();
        setsys.initializeFromProperties();
        mapRenderer.setBoundaryLengthVisible(setsys.isBoundaryLengthVisible());
        // 初始化测量模式
        boolean measurementEnabled = setsys.isMeasurementModeEnabled();
        mapRenderer.setMeasurementMode(measurementEnabled);
        if (measurementEnabled) {
            celiangmoshi.start();
        } else {
            celiangmoshi.stop();
        }
        // 初始化手动绘制边界模式
        boolean manualBoundaryDrawingEnabled = setsys.isManualBoundaryDrawingMode();
        if (mapRenderer != null) {
            mapRenderer.setManualBoundaryDrawingMode(manualBoundaryDrawingEnabled);
        }
        // 更新返回设置按钮的显示状态
        updateSettingsReturnButtonVisibility();
    }
    
    /**
     * 更新返回系统设置按钮的显示状态
     * 当手动绘制边界模式、显示边界距离或开启测量模式任一开启时显示
     */
    public void updateSettingsReturnButtonVisibility() {
        Setsys setsys = new Setsys();
        setsys.initializeFromProperties();
        
        boolean manualBoundaryDrawingEnabled = setsys.isManualBoundaryDrawingMode();
        boolean shouldShow = manualBoundaryDrawingEnabled
            || setsys.isBoundaryLengthVisible() 
            || setsys.isMeasurementModeEnabled();
        
        if (shouldShow) {
            showSettingsReturnButton();
            // 如果手动绘制边界模式开启,显示保存按钮
            if (manualBoundaryDrawingEnabled) {
                showSaveManualBoundaryButton();
            } else {
                hideSaveManualBoundaryButton();
            }
        } else {
            hideSettingsReturnButton();
            hideSaveManualBoundaryButton();
        }
    }
    
    /**
     * 显示返回系统设置按钮
     */
    private void showSettingsReturnButton() {
        ensureFloatingButtonInfrastructure();
        if (settingsReturnButton == null) {
            settingsReturnButton = Fanhuibutton.createReturnButton(null);
            settingsReturnButton.setToolTipText("返回系统设置");
            settingsReturnButton.addActionListener(e -> {
                // 关闭所有相关模式
                Setsys setsys = new Setsys();
                setsys.initializeFromProperties();
                
                boolean modeChanged = false;
                
                // 关闭手动绘制边界模式
                if (setsys.isManualBoundaryDrawingMode()) {
                    setsys.setManualBoundaryDrawingMode(false);
                    setsys.updateProperty("manualBoundaryDrawingMode", "false");
                    // 清空手动绘制的边界点
                    if (mapRenderer != null) {
                        mapRenderer.clearManualBoundaryPoints();
                    }
                    modeChanged = true;
                }
                
                // 关闭显示边界距离
                if (setsys.isBoundaryLengthVisible()) {
                    setsys.setBoundaryLengthVisible(false);
                    setsys.updateProperty("boundaryLengthVisible", "false");
                    if (mapRenderer != null) {
                        mapRenderer.setBoundaryLengthVisible(false);
                    }
                    modeChanged = true;
                }
                
                // 关闭测量模式
                if (setsys.isMeasurementModeEnabled()) {
                    setsys.setMeasurementModeEnabled(false);
                    setsys.updateProperty("measurementModeEnabled", "false");
                    if (mapRenderer != null) {
                        mapRenderer.setMeasurementMode(false);
                    }
                    celiangmoshi.stop();
                    modeChanged = true;
                }
                
                // 如果关闭了任何模式,立即隐藏返回按钮并刷新界面
                if (modeChanged) {
                    // 立即隐藏返回按钮
                    if (settingsReturnButton != null) {
                        settingsReturnButton.setVisible(false);
                    }
                    // 更新按钮列(移除返回按钮)
                    rebuildFloatingButtonColumn();
                    // 如果所有按钮都隐藏了,隐藏悬浮按钮面板
                    if (floatingButtonPanel != null && floatingButtonColumn != null
                            && floatingButtonColumn.getComponentCount() == 0) {
                        floatingButtonPanel.setVisible(false);
                    }
                    // 刷新界面
                    if (visualizationPanel != null) {
                        visualizationPanel.revalidate();
                        visualizationPanel.repaint();
                    }
                }
                
                // 更新返回按钮显示状态(确保状态同步)
                updateSettingsReturnButtonVisibility();
                
                // 打开系统设置页面
                showSettingsDialog();
            });
        }
        settingsReturnButton.setVisible(true);
        // 隐藏绘制相关的按钮(暂停、结束绘制)
        if (drawingPauseButton != null) {
            drawingPauseButton.setVisible(false);
        }
        if (endDrawingButton != null) {
            endDrawingButton.setVisible(false);
        }
        if (floatingButtonPanel != null) {
            floatingButtonPanel.setVisible(true);
            if (floatingButtonPanel.getParent() != visualizationPanel) {
                visualizationPanel.add(floatingButtonPanel, BorderLayout.SOUTH);
            }
        }
        rebuildFloatingButtonColumn();
    }
    
    /**
     * 隐藏返回系统设置按钮
     */
    private void hideSettingsReturnButton() {
        if (settingsReturnButton != null) {
            settingsReturnButton.setVisible(false);
        }
        rebuildFloatingButtonColumn();
        if (floatingButtonPanel != null && floatingButtonColumn != null
                && floatingButtonColumn.getComponentCount() == 0) {
            floatingButtonPanel.setVisible(false);
        }
    }
    
    /**
     * 显示保存手动绘制边界按钮
     */
    private void showSaveManualBoundaryButton() {
        ensureFloatingButtonInfrastructure();
        if (saveManualBoundaryButton == null) {
            saveManualBoundaryButton = createFloatingTextButton("保存");
            saveManualBoundaryButton.setToolTipText("保存手动绘制的边界");
            saveManualBoundaryButton.addActionListener(e -> saveManualBoundary());
        }
        saveManualBoundaryButton.setVisible(true);
        if (floatingButtonPanel != null) {
            floatingButtonPanel.setVisible(true);
            if (floatingButtonPanel.getParent() != visualizationPanel) {
                visualizationPanel.add(floatingButtonPanel, BorderLayout.SOUTH);
            }
        }
        rebuildFloatingButtonColumn();
    }
    
    /**
     * 隐藏保存手动绘制边界按钮
     */
    private void hideSaveManualBoundaryButton() {
        if (saveManualBoundaryButton != null) {
            saveManualBoundaryButton.setVisible(false);
        }
        rebuildFloatingButtonColumn();
        if (floatingButtonPanel != null && floatingButtonColumn != null
                && floatingButtonColumn.getComponentCount() == 0) {
            floatingButtonPanel.setVisible(false);
        }
    }
    
    /**
     * 保存手动绘制的边界到文件
     */
    private void saveManualBoundary() {
        if (mapRenderer == null) {
            JOptionPane.showMessageDialog(this, "地图渲染器未初始化", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        List<Point2D.Double> points = mapRenderer.getManualBoundaryPoints();
        if (points == null || points.isEmpty()) {
            JOptionPane.showMessageDialog(this, "没有可保存的边界点,请先在地图上点击绘制边界", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 构建坐标字符串:x1,y1;x2,y2;...;xn,yn(单位:米,精确到小数点后2位)
        StringBuilder coordinates = new StringBuilder();
        for (int i = 0; i < points.size(); i++) {
            Point2D.Double point = points.get(i);
            if (i > 0) {
                coordinates.append(";");
            }
            coordinates.append(String.format(Locale.US, "%.2f,%.2f", point.x, point.y));
        }
        
        // 保存到 properties 文件
        try {
            java.util.Properties props = new java.util.Properties();
            java.io.File file = new java.io.File("shoudongbianjie.properties");
            
            // 如果文件存在,先加载现有内容
            if (file.exists()) {
                try (java.io.FileInputStream input = new java.io.FileInputStream(file)) {
                    props.load(input);
                }
            }
            
            // 保存坐标
            props.setProperty("boundaryCoordinates", coordinates.toString());
            props.setProperty("pointCount", String.valueOf(points.size()));
            
            // 写回文件
            try (java.io.FileOutputStream output = new java.io.FileOutputStream(file)) {
                props.store(output, "手动绘制边界坐标 - 格式: x1,y1;x2,y2;...;xn,yn (单位:米,精确到小数点后2位)");
            }
            
            JOptionPane.showMessageDialog(this, 
                String.format("边界已保存成功!\n共 %d 个点", points.size()), 
                "保存成功", 
                JOptionPane.INFORMATION_MESSAGE);
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, 
                "保存失败: " + ex.getMessage(), 
                "错误", 
                JOptionPane.ERROR_MESSAGE);
        }
    }
 
    private void createHeaderPanel() {
        headerPanel = new JPanel(new BorderLayout());
        headerPanel.setBackground(PANEL_BACKGROUND);
        headerPanel.setBorder(BorderFactory.createEmptyBorder(15, 20, 15, 20));
        headerPanel.setPreferredSize(new Dimension(0, 80));
 
    // 左侧信息区域(垂直排列:地块名称在上,状态行在下)
    JPanel leftInfoPanel = new JPanel();
    leftInfoPanel.setBackground(PANEL_BACKGROUND);
    leftInfoPanel.setLayout(new BoxLayout(leftInfoPanel, BoxLayout.Y_AXIS));
    // 保证子组件左对齐
    leftInfoPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
    areaNameLabel = new JLabel("未选择地块");
        areaNameLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        areaNameLabel.setForeground(Color.BLACK);
        areaNameLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        areaNameLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                Dikuaiguanli.showDikuaiManagement(Shouye.this, null);
            }
 
            @Override
            public void mouseEntered(MouseEvent e) {
                areaNameLabel.setForeground(THEME_COLOR);
            }
 
            @Override
            public void mouseExited(MouseEvent e) {
                areaNameLabel.setForeground(Color.BLACK);
            }
        });
 
        statusLabel = new JLabel("待机");
        statusLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        statusLabel.setForeground(Color.GRAY);
        statusLabel.addPropertyChangeListener("text", evt -> {
            Object newValue = evt.getNewValue();
            applyStatusLabelColor(newValue instanceof String ? (String) newValue : null);
        });
        applyStatusLabelColor(statusLabel.getText());
 
        // 添加速度显示标签
        speedLabel = new JLabel("");
    speedLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
    speedLabel.setForeground(Color.GRAY);
    speedLabel.setVisible(false);  // 默认隐藏
 
    // 正在绘制边界状态标签
    drawingBoundaryLabel = new JLabel("正在绘制边界");
    drawingBoundaryLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
    drawingBoundaryLabel.setForeground(new Color(46, 139, 87));
    drawingBoundaryLabel.setVisible(false);  // 默认隐藏
 
    // 导航预览模式标签
    navigationPreviewLabel = new JLabel("当前导航预览模式");
    navigationPreviewLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
    navigationPreviewLabel.setForeground(new Color(46, 139, 87));
    navigationPreviewLabel.setVisible(false);  // 默认隐藏
 
    // 将状态与速度放在同一行,显示在地块名称下面一行
    JPanel statusRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
    statusRow.setOpaque(false);
    statusRow.add(statusLabel);
    statusRow.add(drawingBoundaryLabel);
    statusRow.add(navigationPreviewLabel);
    statusRow.add(speedLabel);
 
    // 左对齐标签与状态行,确保它们在 BoxLayout 中靠左显示
    areaNameLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
    statusRow.setAlignmentX(Component.LEFT_ALIGNMENT);
 
    leftInfoPanel.add(areaNameLabel);
    leftInfoPanel.add(statusRow);
 
        // 右侧操作区域
        JPanel rightActionPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        rightActionPanel.setBackground(PANEL_BACKGROUND);
 
        bluetoothBtn = createBluetoothButton();
 
        // 修改设置按钮:使用图片替代Unicode图标
        JButton settingsBtn = new JButton();
        try {
            ImageIcon settingsIcon = new ImageIcon("image/sets.png");
            // 调整图片大小以适应按钮
            Image scaledImage = settingsIcon.getImage().getScaledInstance(30, 30, Image.SCALE_SMOOTH);
            settingsBtn.setIcon(new ImageIcon(scaledImage));
        } catch (Exception e) {
            // 如果图片加载失败,使用默认文本
            settingsBtn.setText("设置");
            System.err.println("无法加载设置图标: " + e.getMessage());
        }
        settingsBtn.setPreferredSize(new Dimension(40, 40));
        settingsBtn.setBackground(PANEL_BACKGROUND);
        settingsBtn.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        settingsBtn.setFocusPainted(false);
 
        // 添加悬停效果
        settingsBtn.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent e) {
                settingsBtn.setBackground(new Color(240, 240, 240));
            }
            public void mouseExited(MouseEvent e) {
                settingsBtn.setBackground(PANEL_BACKGROUND);
            }
        });
 
        // 添加设置按钮事件
        settingsBtn.addActionListener(e -> showSettingsDialog());
 
        rightActionPanel.add(bluetoothBtn);
        rightActionPanel.add(settingsBtn);
 
        headerPanel.add(leftInfoPanel, BorderLayout.WEST);
        headerPanel.add(rightActionPanel, BorderLayout.EAST);
    }
 
    private void createMainContentPanel() {
        mainContentPanel = new JPanel(new BorderLayout());
        mainContentPanel.setBackground(BACKGROUND_COLOR);
 
        // 可视化区域 - 使用MapRenderer进行绘制
        visualizationPanel = new JPanel() {
            private ImageIcon gecaojiIcon1 = null;  // 默认图标
            private ImageIcon gecaojiIcon2 = null;  // 以割草机为中心模式图标
            private static final int GECAOJI_ICON_X = 37;
            private static final int GECAOJI_ICON_Y = 10;
            private static final int GECAOJI_ICON_SIZE = 20;
            
            {
                // 加载割草机图标,大小20x20像素
                gecaojiIcon1 = loadScaledIcon("image/gecaojishijiao1.png", GECAOJI_ICON_SIZE, GECAOJI_ICON_SIZE);
                gecaojiIcon2 = loadScaledIcon("image/gecaojishijiao2.png", GECAOJI_ICON_SIZE, GECAOJI_ICON_SIZE);
            }
            
            /**
             * 检查鼠标位置是否在割草机图标区域内
             */
            private boolean isMouseOnGecaojiIcon(Point mousePoint) {
                return mousePoint.x >= GECAOJI_ICON_X && 
                       mousePoint.x <= GECAOJI_ICON_X + GECAOJI_ICON_SIZE &&
                       mousePoint.y >= GECAOJI_ICON_Y && 
                       mousePoint.y <= GECAOJI_ICON_Y + GECAOJI_ICON_SIZE;
            }
            
            @Override
            public String getToolTipText(MouseEvent event) {
                // 如果鼠标在割草机图标区域内,显示提示文字
                if (isMouseOnGecaojiIcon(event.getPoint())) {
                    // 根据当前模式显示不同的提示文字
                    return centerOnMowerMode ? "取消以割草机为中心" : "以割草机为中心";
                }
                // 不在图标上时返回null,不显示工具提示框
                return null;
            }
            
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                // 委托给MapRenderer进行绘制
                if (mapRenderer != null) {
                    mapRenderer.renderMap(g);
                }
                
                // 检查是否需要显示警告图标
                if (isMowerOutsideBoundary && warningIconVisible) {
                    // 绘制红色三角形警告图标(带叹号)
                    drawWarningIcon(g, GECAOJI_ICON_X, GECAOJI_ICON_Y, GECAOJI_ICON_SIZE);
                } else {
                    // 根据模式选择不同的图标
                    ImageIcon iconToDraw = centerOnMowerMode ? gecaojiIcon2 : gecaojiIcon1;
                    if (iconToDraw != null) {
                        // 绘制割草机图标
                        // 水平方向与速度指示器对齐(x=37)
                        // 垂直方向与卫星状态图标对齐(y=10,速度指示器面板顶部边距10像素,使图标中心对齐)
                        g.drawImage(iconToDraw.getImage(), GECAOJI_ICON_X, GECAOJI_ICON_Y, null);
                    }
                }
            }
            
            /**
             * 绘制红色三角形警告图标(带叹号)
             */
            private void drawWarningIcon(Graphics g, int x, int y, int size) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                
                // 绘制红色三角形
                int[] xPoints = {x + size / 2, x, x + size};
                int[] yPoints = {y, y + size, y + size};
                g2d.setColor(Color.RED);
                g2d.fillPolygon(xPoints, yPoints, 3);
                
                // 绘制白色边框
                g2d.setColor(Color.WHITE);
                g2d.setStroke(new BasicStroke(1.5f));
                g2d.drawPolygon(xPoints, yPoints, 3);
                
                // 绘制白色叹号
                g2d.setColor(Color.WHITE);
                g2d.setFont(new Font("Arial", Font.BOLD, size * 3 / 4));
                FontMetrics fm = g2d.getFontMetrics();
                String exclamation = "!";
                int textWidth = fm.stringWidth(exclamation);
                int textHeight = fm.getAscent();
                g2d.drawString(exclamation, x + (size - textWidth) / 2, y + (size + textHeight) / 2 - 2);
                
                g2d.dispose();
            }
        };
        visualizationPanel.setLayout(new BorderLayout());
        
        // 添加鼠标点击监听器,检测是否点击了割草机图标
        visualizationPanel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (SwingUtilities.isLeftMouseButton(e)) {
                    Point clickPoint = e.getPoint();
                    // 检查是否点击了割草机图标区域(37, 10, 20, 20)
                    if (clickPoint.x >= 37 && clickPoint.x <= 57 && 
                        clickPoint.y >= 10 && clickPoint.y <= 30) {
                        // 切换以割草机为中心的模式
                        toggleCenterOnMowerMode();
                    }
                }
            }
        });
 
        JPanel speedIndicatorPanel = createSpeedIndicatorPanel();
        visualizationPanel.add(speedIndicatorPanel, BorderLayout.NORTH);
 
        // 创建功能按钮面板
        JPanel functionButtonsPanel = new JPanel();
        functionButtonsPanel.setLayout(new BoxLayout(functionButtonsPanel, BoxLayout.Y_AXIS));
        functionButtonsPanel.setOpaque(false);
        functionButtonsPanel.setBorder(BorderFactory.createEmptyBorder(20, 5, 0, 0)); // 左边距改为5像素
 
        legendBtn = createFunctionButton("图例", "📖");
        baseStationBtn = createFunctionButton("基准站", "📡"); // 调整到第二位
        areaSelectBtn = createFunctionButton("地块", "🌿");    // 调整到第三位
        remoteBtn = createFunctionButton("遥控", "🎮");        // 调整到最后
 
        functionButtonsPanel.add(legendBtn);
        functionButtonsPanel.add(Box.createRigidArea(new Dimension(0, 10)));
        functionButtonsPanel.add(baseStationBtn);
        functionButtonsPanel.add(Box.createRigidArea(new Dimension(0, 10)));
        functionButtonsPanel.add(areaSelectBtn);
        functionButtonsPanel.add(Box.createRigidArea(new Dimension(0, 10)));
        functionButtonsPanel.add(remoteBtn);
 
        visualizationPanel.add(functionButtonsPanel, BorderLayout.WEST);
 
        JPanel zoomControlPanel = createZoomControlPanel();
        visualizationPanel.add(zoomControlPanel, BorderLayout.EAST);
 
        mainContentPanel.add(visualizationPanel, BorderLayout.CENTER);
 
        startMowerSpeedUpdates();
    }
 
    private JPanel createZoomControlPanel() {
        JPanel container = new JPanel(new BorderLayout());
        container.setOpaque(false);
        container.setBorder(BorderFactory.createEmptyBorder(0, 0, 20, 20));
 
        JPanel alignmentPanel = new JPanel();
        alignmentPanel.setOpaque(false);
        alignmentPanel.setLayout(new BoxLayout(alignmentPanel, BoxLayout.Y_AXIS));
        alignmentPanel.add(Box.createVerticalGlue());
 
        JPanel buttonStack = new JPanel();
        buttonStack.setOpaque(false);
        buttonStack.setLayout(new BoxLayout(buttonStack, BoxLayout.Y_AXIS));
 
        JButton zoomInButton = createZoomButton("+");
        JButton zoomOutButton = createZoomButton("-");
 
        AtomicBoolean skipZoomInClick = new AtomicBoolean(false);
        AtomicBoolean skipZoomOutClick = new AtomicBoolean(false);
 
        Timer zoomInHoldTimer = new Timer(120, event -> {
            if (mapRenderer == null || !zoomInButton.getModel().isPressed()) {
                ((Timer) event.getSource()).stop();
                return;
            }
            if (!mapRenderer.canZoomIn()) {
                ((Timer) event.getSource()).stop();
                return;
            }
            skipZoomInClick.set(true);
            mapRenderer.zoomInFromCenter();
            if (!mapRenderer.canZoomIn()) {
                ((Timer) event.getSource()).stop();
            }
        });
        zoomInHoldTimer.setInitialDelay(180);
        zoomInHoldTimer.setDelay(120);
 
        Timer zoomOutHoldTimer = new Timer(120, event -> {
            if (mapRenderer == null || !zoomOutButton.getModel().isPressed()) {
                ((Timer) event.getSource()).stop();
                return;
            }
            if (!mapRenderer.canZoomOut()) {
                ((Timer) event.getSource()).stop();
                return;
            }
            skipZoomOutClick.set(true);
            mapRenderer.zoomOutFromCenter();
            if (!mapRenderer.canZoomOut()) {
                ((Timer) event.getSource()).stop();
            }
        });
        zoomOutHoldTimer.setInitialDelay(180);
        zoomOutHoldTimer.setDelay(120);
 
        zoomInButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (!SwingUtilities.isLeftMouseButton(e) || mapRenderer == null || !zoomInButton.isEnabled()) {
                    return;
                }
                if (mapRenderer.canZoomIn()) {
                    skipZoomInClick.set(true);
                    mapRenderer.zoomInFromCenter();
                    if (mapRenderer.canZoomIn()) {
                        zoomInHoldTimer.restart();
                    } else {
                        zoomInHoldTimer.stop();
                    }
                } else {
                    skipZoomInClick.set(false);
                    zoomInHoldTimer.stop();
                }
            }
 
            @Override
            public void mouseReleased(MouseEvent e) {
                zoomInHoldTimer.stop();
                if (!zoomInButton.contains(e.getPoint())) {
                    skipZoomInClick.set(false);
                }
            }
 
            @Override
            public void mouseExited(MouseEvent e) {
                if (!zoomInButton.getModel().isPressed()) {
                    zoomInHoldTimer.stop();
                }
            }
        });
 
        zoomOutButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (!SwingUtilities.isLeftMouseButton(e) || mapRenderer == null || !zoomOutButton.isEnabled()) {
                    return;
                }
                if (mapRenderer.canZoomOut()) {
                    skipZoomOutClick.set(true);
                    mapRenderer.zoomOutFromCenter();
                    if (mapRenderer.canZoomOut()) {
                        zoomOutHoldTimer.restart();
                    } else {
                        zoomOutHoldTimer.stop();
                    }
                } else {
                    skipZoomOutClick.set(false);
                    zoomOutHoldTimer.stop();
                }
            }
 
            @Override
            public void mouseReleased(MouseEvent e) {
                zoomOutHoldTimer.stop();
                if (!zoomOutButton.contains(e.getPoint())) {
                    skipZoomOutClick.set(false);
                }
            }
 
            @Override
            public void mouseExited(MouseEvent e) {
                if (!zoomOutButton.getModel().isPressed()) {
                    zoomOutHoldTimer.stop();
                }
            }
        });
 
        zoomInButton.addActionListener(e -> {
            if (skipZoomInClick.getAndSet(false)) {
                return;
            }
            if (mapRenderer != null) {
                mapRenderer.zoomInFromCenter();
            }
        });
 
        zoomOutButton.addActionListener(e -> {
            if (skipZoomOutClick.getAndSet(false)) {
                return;
            }
            if (mapRenderer != null) {
                mapRenderer.zoomOutFromCenter();
            }
        });
 
        buttonStack.add(zoomInButton);
        buttonStack.add(Box.createRigidArea(new Dimension(0, 8)));
        buttonStack.add(zoomOutButton);
 
        buttonStack.setAlignmentX(Component.CENTER_ALIGNMENT);
        alignmentPanel.add(buttonStack);
 
        container.add(alignmentPanel, BorderLayout.CENTER);
        return container;
    }
 
    private JButton createZoomButton(String symbol) {
        JButton button = new JButton(symbol);
        Dimension size = new Dimension(44, 44);
        button.setPreferredSize(size);
        button.setMinimumSize(size);
        button.setMaximumSize(size);
        button.setFont(new Font("微软雅黑", Font.BOLD, 22));
        button.setMargin(new Insets(0, 0, 0, 0));
        button.setFocusPainted(false);
        button.setBackground(Color.WHITE);
        button.setForeground(Color.DARK_GRAY);
        button.setBorder(BorderFactory.createLineBorder(new Color(210, 210, 210), 1, true));
        button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        button.setOpaque(true);
 
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                button.setBackground(new Color(245, 245, 245));
            }
 
            @Override
            public void mouseExited(MouseEvent e) {
                button.setBackground(Color.WHITE);
            }
        });
 
        return button;
    }
 
    private void createControlPanel() {
        controlPanel = new JPanel(new BorderLayout());
        controlPanel.setBackground(PANEL_BACKGROUND);
        controlPanel.setBorder(BorderFactory.createEmptyBorder(15, 20, 15, 20));
        controlPanel.setPreferredSize(new Dimension(0, 100));
 
        JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 20, 0));
        buttonPanel.setBackground(PANEL_BACKGROUND);
 
        startBtn = createControlButton("暂停", THEME_COLOR);
        updateStartButtonAppearance();
 
        stopBtn = createControlButton("结束", Color.ORANGE);
        updateStopButtonIcon();
 
        buttonPanel.add(startBtn);
        buttonPanel.add(stopBtn);
 
        controlPanel.add(buttonPanel, BorderLayout.CENTER);
    }
 
    private void createNavigationPanel() {
        navigationPanel = new JPanel(new GridLayout(1, 3));
        navigationPanel.setBackground(PANEL_BACKGROUND);
        navigationPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
        navigationPanel.setPreferredSize(new Dimension(0, 70));
 
        homeNavBtn = createNavButton("首页", "🏠");
        areasNavBtn = createNavButton("地块", "🌿");
        settingsNavBtn = createNavButton("设置", "⚙️");
 
        navigationPanel.add(homeNavBtn);
        navigationPanel.add(areasNavBtn);
        navigationPanel.add(settingsNavBtn);
 
        // 添加到主界面底部
        add(navigationPanel, BorderLayout.SOUTH);
    }
 
    private JButton createIconButton(String icon, int size) {
        JButton button = new JButton(icon);
        button.setFont(new Font("Segoe UI Emoji", Font.PLAIN, 20));
        button.setPreferredSize(new Dimension(size, size));
        button.setBackground(PANEL_BACKGROUND);
        button.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        button.setFocusPainted(false);
 
        // 悬停效果
        button.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent e) {
                button.setBackground(new Color(240, 240, 240));
            }
            public void mouseExited(MouseEvent e) {
                button.setBackground(PANEL_BACKGROUND);
            }
        });
 
        return button;
    }
 
    private JButton createBluetoothButton() {
        JButton button = new JButton();
        button.setPreferredSize(new Dimension(40, 40));
        button.setBackground(PANEL_BACKGROUND);
        button.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        button.setFocusPainted(false);
        button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                button.setBackground(new Color(240, 240, 240));
            }
 
            @Override
            public void mouseExited(MouseEvent e) {
                button.setBackground(PANEL_BACKGROUND);
            }
        });
        ensureBluetoothIconsLoaded();
        // 根据串口连接状态显示图标
        SerialPortService service = sendmessage.getActiveService();
        boolean serialConnected = (service != null && service.isOpen());
        ImageIcon initialIcon = serialConnected ? bluetoothLinkedIcon : bluetoothIcon;
        if (initialIcon != null) {
            button.setIcon(initialIcon);
        } else {
            button.setText(serialConnected ? "已连" : "蓝牙");
        }
        return button;
    }
 
    private JButton createFunctionButton(String text, String icon) {
        JButton button = new JButton("<html><center>" + icon + "<br>" + text + "</center></html>");
        button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        button.setPreferredSize(new Dimension(80, 70));
        button.setBackground(new Color(0, 0, 0, 0)); // 完全透明背景
        button.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); // 只保留内边距
        button.setFocusPainted(false);
        button.setOpaque(false); // 设置为不透明,确保背景透明
 
        // 去掉悬停效果
        button.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent e) {
                // 悬停时不改变任何样式
            }
            public void mouseExited(MouseEvent e) {
                // 悬停时不改变任何样式
            }
        });
 
        return button;
    }
 
    private JButton createControlButton(String text, Color color) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 16));
        button.setBackground(color);
        button.setForeground(Color.WHITE);
        button.setBorder(BorderFactory.createEmptyBorder(15, 0, 15, 0));
        button.setFocusPainted(false);
 
        // 悬停效果
        button.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent e) {
                if (button.isEnabled()) {
                    if (color == THEME_COLOR) {
                        button.setBackground(THEME_HOVER_COLOR);
                    } else {
                        button.setBackground(new Color(255, 165, 0));
                    }
                }
            }
            public void mouseExited(MouseEvent e) {
                if (button.isEnabled()) {
                    button.setBackground(color);
                }
            }
        });
 
        return button;
    }
 
    private void applyButtonIcon(JButton button, String imagePath) {
        try {
            ImageIcon icon = new ImageIcon(imagePath);
            Image scaledImage = icon.getImage().getScaledInstance(28, 28, Image.SCALE_SMOOTH);
            button.setIcon(new ImageIcon(scaledImage));
            button.setHorizontalAlignment(SwingConstants.CENTER);
            button.setIconTextGap(10);
            button.setHorizontalTextPosition(SwingConstants.RIGHT);
            button.setVerticalTextPosition(SwingConstants.CENTER);
        } catch (Exception e) {
            System.err.println("无法加载按钮图标: " + imagePath + " -> " + e.getMessage());
        }
    }
 
    private JButton createNavButton(String text, String icon) {
        JButton button = new JButton("<html><center>" + icon + "<br>" + text + "</center></html>");
        button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        button.setBackground(PANEL_BACKGROUND);
        button.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5));
        button.setFocusPainted(false);
 
        // 悬停效果
        button.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent e) {
                if (button != currentNavButton) {
                    button.setBackground(new Color(240, 240, 240));
                }
            }
            public void mouseExited(MouseEvent e) {
                if (button != currentNavButton) {
                    button.setBackground(PANEL_BACKGROUND);
                }
            }
        });
 
        return button;
    }
 
    private void setNavigationActive(JButton navButton) {
        // 重置所有导航按钮样式
        for (Component comp : navigationPanel.getComponents()) {
            if (comp instanceof JButton) {
                JButton btn = (JButton) comp;
                btn.setBackground(PANEL_BACKGROUND);
                btn.setForeground(Color.BLACK);
            }
        }
 
        // 设置当前选中按钮样式
        navButton.setBackground(THEME_COLOR);
        navButton.setForeground(Color.WHITE);
        currentNavButton = navButton;
    }
 
    private void setupEventHandlers() {
        // 导航按钮事件
        homeNavBtn.addActionListener(e -> setNavigationActive(homeNavBtn));
        areasNavBtn.addActionListener(e -> setNavigationActive(areasNavBtn));
        settingsNavBtn.addActionListener(e -> setNavigationActive(settingsNavBtn));
 
        // 功能按钮事件
        legendBtn.addActionListener(e -> showLegendDialog());
        if (bluetoothBtn != null) {
            bluetoothBtn.addActionListener(e -> toggleBluetoothConnection());
        }
        remoteBtn.addActionListener(e -> showRemoteControlDialog());
        areaSelectBtn.addActionListener(e -> {
            // 点击“地块”直接打开地块管理对话框(若需要可传入特定地块编号)
//          Dikuaiguanli.showDikuaiManagement(this, null);
            // 直接进入地块管理界面
            Dikuaiguanli.showDikuaiManagement(this, null);
        });
        baseStationBtn.addActionListener(e -> showBaseStationDialog());
 
        // 控制按钮事件
        startBtn.addActionListener(e -> toggleStartPause());
        stopBtn.addActionListener(e -> handleStopAction());
    }
 
    private void showSettingsDialog() {
        if (settingsDialog == null) {
            Window parentWindow = SwingUtilities.getWindowAncestor(this);
            if (parentWindow instanceof JFrame) {
                settingsDialog = new Sets((JFrame) parentWindow, THEME_COLOR);
            } else if (parentWindow instanceof JDialog) {
                settingsDialog = new Sets((JDialog) parentWindow, THEME_COLOR);
            } else {
                // Fallback to a frameless dialog when no parent is available
                settingsDialog = new Sets((JFrame) null, THEME_COLOR);
            }
        }
        settingsDialog.setVisible(true);
    }
 
    private void showLegendDialog() {
        if (legendDialog == null) {
            Window parentWindow = SwingUtilities.getWindowAncestor(this);
            if (parentWindow != null) {
                legendDialog = new LegendDialog(this, THEME_COLOR);
            } else {
                // 如果没有父窗口,创建无父窗口的对话框
                legendDialog = new LegendDialog((JFrame) null, THEME_COLOR);
            }
        }
        legendDialog.setVisible(true);
    }
 
    private void showRemoteControlDialog() {
        if (remoteDialog == null) {
            Window parentWindow = SwingUtilities.getWindowAncestor(this);
            if (parentWindow != null) {
                // 使用 yaokong 包中的 RemoteControlDialog 实现
                remoteDialog = new yaokong.RemoteControlDialog(this, THEME_COLOR, speedLabel);
            } else {/*  */
                remoteDialog = new yaokong.RemoteControlDialog((JFrame) null, THEME_COLOR, speedLabel);
            }
        }
        if (remoteDialog != null) {
            positionRemoteDialogBottomCenter(remoteDialog);
            zijian.markSelfCheckCompleted();
            remoteDialog.setVisible(true);
        }
    }
 
    private void positionRemoteDialogBottomCenter(RemoteControlDialog dialog) {
        if (dialog == null) {
            return;
        }
        // 将对话框底部与整个首页(Shouye 面板)的下边框对齐,
        // 而不是与 visualizationPanel 对齐,以满足设计要求。
        Dimension dialogSize = dialog.getSize();
 
        // 获取当前 Shouye 面板在屏幕上的位置和尺寸
        Point parentOnScreen = null;
        try {
            parentOnScreen = this.getLocationOnScreen();
        } catch (IllegalComponentStateException ex) {
            // 如果组件尚未显示或无法获取屏幕位置,回退到窗口层级位置获取
            Window owner = SwingUtilities.getWindowAncestor(this);
            if (owner != null) {
                parentOnScreen = owner.getLocationOnScreen();
            }
        }
 
        int x = 0, y = 0;
        if (parentOnScreen != null) {
            int parentWidth = this.getWidth();
            int parentHeight = this.getHeight();
            x = parentOnScreen.x + (parentWidth - dialogSize.width) / 2;
            y = parentOnScreen.y + parentHeight - dialogSize.height;
        } else {
            // 作为最后的回退,使用屏幕中心对齐底部
            Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
            x = (screen.width - dialogSize.width) / 2;
            y = screen.height - dialogSize.height;
        }
 
        dialog.setLocation(Math.max(x, 0), Math.max(y, 0));
    }
 
    private Rectangle computeVisualizationBoundsOnScreen() {
        if (visualizationPanel == null || !visualizationPanel.isShowing()) {
            return null;
        }
        Point location = visualizationPanel.getLocationOnScreen();
        Dimension size = visualizationPanel.getSize();
        return new Rectangle(location.x, location.y, size.width, size.height);
    }
 
    private void showAreaSelectionDialog() {
        if (areaDialog == null) {
            Window parentWindow = SwingUtilities.getWindowAncestor(this);
            if (parentWindow != null) {
                areaDialog = new AreaSelectionDialog(this, THEME_COLOR, areaNameLabel, statusLabel);
            } else {
                areaDialog = new AreaSelectionDialog((JFrame) null, THEME_COLOR, areaNameLabel, statusLabel);
            }
        }
        areaDialog.setVisible(true);
    }
 
    private void showBaseStationDialog() {
        if (baseStation == null) {
            baseStation = new BaseStation();
        }
        baseStation.load();
 
        Component dialogParent = this;
 
        if (!hasValidBaseStationId()) {
            boolean recorded = promptForBaseStationId(dialogParent);
            if (!recorded) {
                return;
            }
        }
 
        Device device = Device.getGecaoji();
        if (device == null) {
            device = new Device();
            device.initFromProperties();
            Device.setGecaoji(device);
        }
 
        if (baseStationDialog == null) {
            baseStationDialog = new BaseStationDialog(dialogParent, THEME_COLOR, device, baseStation);
        } else {
            baseStationDialog.refreshData();
        }
        baseStationDialog.setVisible(true);
    }
 
    private void checkIdentifiersAndPromptIfNeeded() {
        if (baseStation == null) {
            baseStation = new BaseStation();
        }
        baseStation.load();
 
        String currentMowerId = Setsys.getPropertyValue("mowerId");
        String currentBaseStationId = baseStation.getDeviceId();
 
        if (!isIdentifierMissing(currentMowerId) && !isIdentifierMissing(currentBaseStationId)) {
            return;
        }
 
        Window owner = SwingUtilities.getWindowAncestor(this);
        promptForMissingIdentifiers(owner, currentMowerId, currentBaseStationId);
    }
 
    private void promptForMissingIdentifiers(Window owner, String currentMowerId, String currentBaseStationId) {
        while (true) {
            JTextField mowerField = new JTextField(10);
            JTextField baseField = new JTextField(10);
 
            if (!isIdentifierMissing(currentMowerId)) {
                mowerField.setText(currentMowerId.trim());
            }
            if (!isIdentifierMissing(currentBaseStationId)) {
                baseField.setText(currentBaseStationId.trim());
            }
 
            JPanel panel = new JPanel();
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            panel.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
 
            JLabel mowerLabel = new JLabel("割草机编号");
            JLabel baseLabel = new JLabel("差分基准站编号");
 
            mowerField.setMaximumSize(new Dimension(Integer.MAX_VALUE, mowerField.getPreferredSize().height));
            baseField.setMaximumSize(new Dimension(Integer.MAX_VALUE, baseField.getPreferredSize().height));
 
            panel.add(mowerLabel);
            panel.add(Box.createVerticalStrut(4));
            panel.add(mowerField);
            panel.add(Box.createVerticalStrut(10));
            panel.add(baseLabel);
            panel.add(Box.createVerticalStrut(4));
            panel.add(baseField);
 
            Object[] options = {"保存", "取消"};
            int result = JOptionPane.showOptionDialog(owner, panel, "完善设备信息",
                    JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
 
            if (result != 0) {
                break;
            }
 
            String mowerInput = mowerField.getText().trim();
            String baseInput = baseField.getText().trim();
 
            if (mowerInput.isEmpty()) {
                JOptionPane.showMessageDialog(owner, "割草机编号不能为空。", "提示", JOptionPane.WARNING_MESSAGE);
                continue;
            }
 
            if (baseInput.isEmpty()) {
                JOptionPane.showMessageDialog(owner, "差分基准站编号不能为空。", "提示", JOptionPane.WARNING_MESSAGE);
                continue;
            }
 
            boolean mowerSaved = persistMowerIdentifier(mowerInput);
            boolean baseSaved = persistBaseStationIdentifier(baseInput);
 
            if (mowerSaved && baseSaved) {
                JOptionPane.showMessageDialog(owner, "编号已保存。", "成功", JOptionPane.INFORMATION_MESSAGE);
                break;
            }
 
            StringBuilder errorBuilder = new StringBuilder();
            if (!mowerSaved) {
                errorBuilder.append("割草机编号保存失败。");
            }
            if (!baseSaved) {
                if (errorBuilder.length() > 0) {
                    errorBuilder.append('\n');
                }
                errorBuilder.append("差分基准站编号保存失败。");
            }
 
            JOptionPane.showMessageDialog(owner, errorBuilder.toString(), "保存失败", JOptionPane.ERROR_MESSAGE);
 
            currentMowerId = Setsys.getPropertyValue("mowerId");
            baseStation.load();
            currentBaseStationId = baseStation.getDeviceId();
        }
    }
 
    private boolean isIdentifierMissing(String value) {
        if (value == null) {
            return true;
        }
        String trimmed = value.trim();
        return trimmed.isEmpty() || "-1".equals(trimmed);
    }
 
    private boolean persistMowerIdentifier(String mowerId) {
        try {
            Setsys setsys = new Setsys();
            setsys.initializeFromProperties();
            boolean updated = setsys.updateProperty("mowerId", mowerId);
            if (updated) {
                Device.initializeActiveDevice(mowerId);
            }
            return updated;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
 
    private boolean persistBaseStationIdentifier(String baseStationId) {
        if (baseStation == null) {
            baseStation = new BaseStation();
        }
        try {
            baseStation.updateByDeviceId(baseStationId,
                    baseStation.getInstallationCoordinates(),
                    baseStation.getIotSimCardNumber(),
                    baseStation.getDeviceActivationTime(),
                    baseStation.getDataUpdateTime());
            baseStation.load();
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
 
    private boolean hasValidBaseStationId() {
        if (baseStation == null) {
            return false;
        }
        String deviceId = baseStation.getDeviceId();
        if (deviceId == null) {
            return false;
        }
        String trimmed = deviceId.trim();
        return !trimmed.isEmpty() && !"-1".equals(trimmed);
    }
 
    private boolean promptForBaseStationId(Component parentComponent) {
        if (baseStation == null) {
            baseStation = new BaseStation();
        }
 
        while (true) {
            String input = JOptionPane.showInputDialog(parentComponent,
                    "请输入基准站编号", "录入基准站编号", JOptionPane.PLAIN_MESSAGE);
 
            if (input == null) {
                return false;
            }
 
            String trimmed = input.trim();
            if (trimmed.isEmpty()) {
                JOptionPane.showMessageDialog(parentComponent,
                        "基准站编号不能为空,请重新输入。", "提示", JOptionPane.WARNING_MESSAGE);
                continue;
            }
 
            try {
                baseStation.updateByDeviceId(trimmed,
                        baseStation.getInstallationCoordinates(),
                        baseStation.getIotSimCardNumber(),
                        baseStation.getDeviceActivationTime(),
                        baseStation.getDataUpdateTime());
                baseStation.load();
                JOptionPane.showMessageDialog(parentComponent,
                        "基准站编号已保存。", "操作成功", JOptionPane.INFORMATION_MESSAGE);
                return true;
            } catch (IllegalArgumentException ex) {
                JOptionPane.showMessageDialog(parentComponent,
                        ex.getMessage(), "输入错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
 
    private void toggleStartPause() {
        if (handheldCaptureInlineUiActive) {
            handleHandheldConfirmAction();
            return;
        }
        if (drawingControlModeActive) {
            toggleDrawingPause();
            return;
        }
        if (startBtn == null) {
            return;
        }
        if (startButtonShowingPause) {
            // 点击开始按钮时不再弹出自检提示(按用户要求删除)
            // 旧逻辑:调用 zijian.ensureBeforeMowing(...) 并在未确认自检时阻止开始
            // 新逻辑:直接允许开始作业
        }
        startButtonShowingPause = !startButtonShowingPause;
        if (!startButtonShowingPause) {
            // 检查割草机是否在作业地块边界范围内
            if (!checkMowerInBoundary()) {
                startButtonShowingPause = true;
                statusLabel.setText("待机");
                updateStartButtonAppearance();
                return;
            }
            
            statusLabel.setText("作业中");
            if (stopButtonActive) {
                stopButtonActive = false;
                updateStopButtonIcon();
            }
        if (!beginMowingSession()) {
            startButtonShowingPause = true;
            statusLabel.setText("待机");
            updateStartButtonAppearance();
            return;
        }
        } else {
            statusLabel.setText("暂停中");
            pauseMowingSession();
        }
        updateStartButtonAppearance();
    }
 
    /**
     * 检查割草机是否在当前选中的作业地块边界范围内
     * @return 如果割草机在边界内返回true,否则返回false并显示提示
     */
    private boolean checkMowerInBoundary() {
        if (mapRenderer == null) {
            return true; // 如果没有地图渲染器,跳过检查
        }
 
        // 获取当前边界
        List<Point2D.Double> boundary = mapRenderer.getCurrentBoundary();
        if (boundary == null || boundary.size() < 3) {
            return true; // 如果没有边界或边界点不足,跳过检查
        }
 
        // 获取割草机位置
        Gecaoji mower = mapRenderer.getMower();
        if (mower == null || !mower.hasValidPosition()) {
            showCustomMessageDialog("无法获取割草机位置,请检查设备连接", "提示");
            return false;
        }
 
        Point2D.Double mowerPosition = mower.getPosition();
        if (mowerPosition == null) {
            showCustomMessageDialog("无法获取割草机位置,请检查设备连接", "提示");
            return false;
        }
 
        // 使用 MowerBoundaryChecker 检查是否在边界内
        boolean isInside = MowerBoundaryChecker.isInsideBoundaryPoints(
            boundary, 
            mowerPosition.x, 
            mowerPosition.y
        );
 
        if (!isInside) {
            showCustomMessageDialog("请将割草机开到作业地块内然后点击开始作业", "提示");
            return false;
        }
 
        return true;
    }
 
    /**
     * 显示自定义消息对话框,使用 buttonset 创建确定按钮
     * @param message 消息内容
     * @param title 对话框标题
     */
    private void showCustomMessageDialog(String message, String title) {
        Window parentWindow = SwingUtilities.getWindowAncestor(this);
        JDialog dialog = new JDialog(parentWindow, title, Dialog.ModalityType.APPLICATION_MODAL);
        dialog.setLayout(new BorderLayout(20, 20));
        dialog.setResizable(false);
        
        // 内容面板
        JPanel contentPanel = new JPanel(new BorderLayout(0, 15));
        contentPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 10, 20));
        contentPanel.setBackground(Color.WHITE);
        
        // 消息标签
        JLabel messageLabel = new JLabel("<html><div style='text-align: center;'>" + message + "</div></html>");
        messageLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        messageLabel.setHorizontalAlignment(SwingConstants.CENTER);
        contentPanel.add(messageLabel, BorderLayout.CENTER);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
        buttonPanel.setOpaque(false);
        
        // 使用 buttonset 创建确定按钮
        JButton okButton = buttonset.createStyledButton("确定", THEME_COLOR);
        okButton.addActionListener(e -> dialog.dispose());
        buttonPanel.add(okButton);
        
        contentPanel.add(buttonPanel, BorderLayout.SOUTH);
        dialog.add(contentPanel, BorderLayout.CENTER);
        
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
 
    private void handleStopAction() {
        if (handheldCaptureInlineUiActive) {
            handleHandheldFinishAction();
            return;
        }
        if (drawingControlModeActive) {
            handleDrawingStopFromControlPanel();
            return;
        }
        stopButtonActive = !stopButtonActive;
        updateStopButtonIcon();
        if (stopButtonActive) {
            statusLabel.setText("已结束");
            startButtonShowingPause = false;
            stopMowingSession();
        } else {
            statusLabel.setText("待机");
            startButtonShowingPause = true;
            pauseMowingSession();
        }
        updateStartButtonAppearance();
    }
 
    private void handleDrawingStopFromControlPanel() {
        // 如果是往返路径绘制模式,调用完成绘制回调
        if (returnPathDrawer != null && returnPathDrawer.isActive()) {
            returnPathDrawer.stop();
            returnPathDrawer.executeFinishCallback();
        } else if (endDrawingCallback != null) {
            endDrawingCallback.run();
        } else {
            addzhangaiwu.finishDrawingSession();
        }
    }
 
    private void handleHandheldConfirmAction() {
        if (!handheldCaptureInlineUiActive) {
            return;
        }
        if (!canConfirmHandheldPoint()) {
            refreshHandheldCaptureUiState();
            return;
        }
        int count = captureHandheldBoundaryPoint();
        if (count <= 0) {
            refreshHandheldCaptureUiState();
            return;
        }
        refreshHandheldCaptureUiState();
    }
 
    private void handleHandheldFinishAction() {
        if (!handheldCaptureInlineUiActive) {
            return;
        }
        if (stopBtn != null && !stopBtn.isEnabled()) {
            refreshHandheldCaptureUiState();
            return;
        }
        if (!finishHandheldBoundaryCapture()) {
            refreshHandheldCaptureUiState();
        }
    }
 
    private void enterHandheldCaptureInlineUi() {
        if (handheldCaptureInlineUiActive) {
            refreshHandheldCaptureUiState();
            return;
        }
        handheldCaptureInlineUiActive = true;
        handheldCaptureStoredStatusText = statusLabel != null ? statusLabel.getText() : null;
        if (statusLabel != null) {
            statusLabel.setText("手持采集中");
        }
        if (startBtn != null) {
            handheldStartButtonOriginalBackground = startBtn.getBackground();
            handheldStartButtonOriginalForeground = startBtn.getForeground();
            startBtn.setIcon(null);
            startBtn.setIconTextGap(0);
            startBtn.setHorizontalAlignment(SwingConstants.CENTER);
            startBtn.setHorizontalTextPosition(SwingConstants.CENTER);
            startBtn.setVerticalTextPosition(SwingConstants.CENTER);
        }
        if (stopBtn != null) {
            handheldStopButtonOriginalBackground = stopBtn.getBackground();
            handheldStopButtonOriginalForeground = stopBtn.getForeground();
            stopBtn.setIcon(null);
            stopBtn.setIconTextGap(0);
            stopBtn.setHorizontalAlignment(SwingConstants.CENTER);
            stopBtn.setHorizontalTextPosition(SwingConstants.CENTER);
            stopBtn.setVerticalTextPosition(SwingConstants.CENTER);
            stopBtn.setText("结束");
        }
        startHandheldCaptureStatusTimer();
        refreshHandheldCaptureUiState();
    }
 
    private void exitHandheldCaptureInlineUi() {
        if (!handheldCaptureInlineUiActive) {
            return;
        }
        handheldCaptureInlineUiActive = false;
        stopHandheldCaptureStatusTimer();
        if (statusLabel != null) {
            statusLabel.setText(handheldCaptureStoredStatusText != null ? handheldCaptureStoredStatusText : "待机");
        }
        if (startBtn != null) {
            startBtn.setToolTipText(null);
            if (handheldStartButtonOriginalBackground != null) {
                startBtn.setBackground(handheldStartButtonOriginalBackground);
            }
            if (handheldStartButtonOriginalForeground != null) {
                startBtn.setForeground(handheldStartButtonOriginalForeground);
            }
            startBtn.setEnabled(true);
            updateStartButtonAppearance();
        }
        if (stopBtn != null) {
            stopBtn.setToolTipText(null);
            if (handheldStopButtonOriginalBackground != null) {
                stopBtn.setBackground(handheldStopButtonOriginalBackground);
            }
            if (handheldStopButtonOriginalForeground != null) {
                stopBtn.setForeground(handheldStopButtonOriginalForeground);
            }
            stopBtn.setEnabled(true);
            stopBtn.setText("结束");
            updateStopButtonIcon();
        }
        handheldCaptureStoredStatusText = null;
        handheldStartButtonOriginalBackground = null;
        handheldStartButtonOriginalForeground = null;
        handheldStopButtonOriginalBackground = null;
        handheldStopButtonOriginalForeground = null;
    }
 
    private void startHandheldCaptureStatusTimer() {
        if (handheldCaptureStatusTimer == null) {
            handheldCaptureStatusTimer = new Timer(400, e -> refreshHandheldCaptureUiState());
            handheldCaptureStatusTimer.setRepeats(true);
        }
        if (!handheldCaptureStatusTimer.isRunning()) {
            handheldCaptureStatusTimer.start();
        }
    }
 
    private void stopHandheldCaptureStatusTimer() {
        if (handheldCaptureStatusTimer != null && handheldCaptureStatusTimer.isRunning()) {
            handheldCaptureStatusTimer.stop();
        }
    }
 
    // Update inline handheld capture buttons based on the current device reading.
    private void refreshHandheldCaptureUiState() {
        if (!handheldCaptureInlineUiActive) {
            return;
        }
        int nextIndex = handheldCapturedPoints + 1;
        boolean hasFix = hasHighPrecisionFix();
        boolean hasValid = hasValidRealtimeHandheldPosition();
        boolean duplicate = hasValid && isCurrentHandheldPointDuplicate();
        boolean canConfirm = handheldCaptureActive && hasFix && hasValid && !duplicate;
 
        if (startBtn != null) {
            String prompt = "<html><center>采集点" + nextIndex + "<br>确定</center></html>";
            startBtn.setText(prompt);
            startBtn.setEnabled(canConfirm);
            if (canConfirm) {
                if (handheldStartButtonOriginalBackground != null) {
                    startBtn.setBackground(handheldStartButtonOriginalBackground);
                }
                if (handheldStartButtonOriginalForeground != null) {
                    startBtn.setForeground(handheldStartButtonOriginalForeground);
                }
                startBtn.setToolTipText(null);
            } else {
                startBtn.setBackground(new Color(200, 200, 200));
                startBtn.setForeground(new Color(130, 130, 130));
                startBtn.setToolTipText(resolveHandheldConfirmTooltip(hasFix, hasValid, duplicate));
            }
        }
 
        if (stopBtn != null) {
            boolean canFinish = handheldCapturedPoints >= 3;
            stopBtn.setText("结束");
            stopBtn.setEnabled(canFinish);
            if (canFinish) {
                if (handheldStopButtonOriginalBackground != null) {
                    stopBtn.setBackground(handheldStopButtonOriginalBackground);
                }
                if (handheldStopButtonOriginalForeground != null) {
                    stopBtn.setForeground(handheldStopButtonOriginalForeground);
                }
                stopBtn.setToolTipText("结束采集并返回新增地块");
            } else {
                stopBtn.setBackground(new Color(220, 220, 220));
                stopBtn.setForeground(new Color(130, 130, 130));
                stopBtn.setToolTipText("至少采集三个点才能结束");
            }
        }
    }
 
    private String resolveHandheldConfirmTooltip(boolean hasFix, boolean hasValidPosition, boolean duplicate) {
        if (!hasFix) {
            return "当前定位质量不足,无法采集";
        }
        if (!hasValidPosition) {
            return "当前定位数据无效,请稍后再试";
        }
        if (duplicate) {
            return "当前坐标已采集,请移动到新的位置";
        }
        return null;
    }
 
    private boolean hasHighPrecisionFix() {
        Device device = Device.getGecaoji();
        if (device == null) {
            return false;
        }
        String status = device.getPositioningStatus();
        return status != null && "4".equals(status.trim());
    }
 
    private boolean canConfirmHandheldPoint() {
        return handheldCaptureActive
                && hasHighPrecisionFix()
                && hasValidRealtimeHandheldPosition()
                && !isCurrentHandheldPointDuplicate();
    }
 
    private void enterDrawingControlMode() {
        if (drawingControlModeActive) {
            return;
        }
        storedStartButtonShowingPause = startButtonShowingPause;
        storedStopButtonActive = stopButtonActive;
        storedStatusBeforeDrawing = statusLabel != null ? statusLabel.getText() : null;
        drawingControlModeActive = true;
        applyDrawingPauseState(false, false);
        updateDrawingControlButtonLabels();
    }
 
    private void exitDrawingControlMode() {
        if (!drawingControlModeActive) {
            return;
        }
        drawingControlModeActive = false;
        applyDrawingPauseState(false, false);
        drawingPaused = false;
        stopButtonActive = storedStopButtonActive;
        startButtonShowingPause = storedStartButtonShowingPause;
        if (startBtn != null) {
            updateStartButtonAppearance();
        }
        if (stopBtn != null) {
            stopBtn.setText("结束");
            updateStopButtonIcon();
        }
        if (statusLabel != null) {
            // 如果是往返路径绘制,退出时恢复为"待机"
            if (returnPathDrawer != null && returnPathDrawer.isActive()) {
                statusLabel.setText("待机");
            } else {
                statusLabel.setText(storedStatusBeforeDrawing != null ? storedStatusBeforeDrawing : "待机");
            }
        }
        storedStatusBeforeDrawing = null;
    }
 
    private void updateDrawingControlButtonLabels() {
        if (!drawingControlModeActive) {
            return;
        }
        configureButtonForDrawingMode(startBtn);
        configureButtonForDrawingMode(stopBtn);
        if (startBtn != null) {
            startBtn.setText(drawingPaused ? "开始绘制" : "暂停绘制");
        }
        if (stopBtn != null) {
            // 如果是往返路径绘制模式,显示"完成绘制",否则显示"结束绘制"
            stopBtn.setText((returnPathDrawer != null && returnPathDrawer.isActive()) ? "完成绘制" : "结束绘制");
        }
    }
 
    private void configureButtonForDrawingMode(JButton button) {
        if (button == null) {
            return;
        }
        button.setIcon(null);
        button.setIconTextGap(0);
        button.setHorizontalAlignment(SwingConstants.CENTER);
        button.setHorizontalTextPosition(SwingConstants.CENTER);
    }
 
    private void updateStartButtonAppearance() {
        if (startBtn == null) {
            return;
        }
        String iconPath = startButtonShowingPause ? "image/start0.png" : "image/start1.png";
        startBtn.setText(startButtonShowingPause ? "暂停" : "开始");
        applyButtonIcon(startBtn, iconPath);
    }
 
    private void updateStopButtonIcon() {
        if (stopBtn == null) {
            return;
        }
        String iconPath = stopButtonActive ? "image/stop1.png" : "image/stop0.png";
        applyButtonIcon(stopBtn, iconPath);
    }
 
    private void toggleBluetoothConnection() {
        if (bluetoothBtn == null) {
            return;
        }
        // 弹出系统调试页面
        showDebugDialog();
    }
    
    private void showDebugDialog() {
        Window parentWindow = SwingUtilities.getWindowAncestor(this);
        debug debugDialog = new debug(parentWindow, THEME_COLOR);
        debugDialog.setLocationRelativeTo(this); // 居中显示在首页
        debugDialog.setVisible(true);
    }
 
    private void updateBluetoothButtonIcon() {
        if (bluetoothBtn == null) {
            return;
        }
        ensureBluetoothIconsLoaded();
        // 根据串口连接状态显示图标
        SerialPortService service = sendmessage.getActiveService();
        boolean serialConnected = (service != null && service.isOpen());
        ImageIcon icon = serialConnected ? bluetoothLinkedIcon : bluetoothIcon;
        if (icon != null) {
            bluetoothBtn.setIcon(icon);
            bluetoothBtn.setText(null);
        } else {
            bluetoothBtn.setText(serialConnected ? "已连" : "蓝牙");
        }
    }
 
    private JPanel createSpeedIndicatorPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setOpaque(false);
        panel.setBorder(BorderFactory.createEmptyBorder(10, 20, 5, 20));
 
        JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 0));
        rightPanel.setOpaque(false);
 
    fixQualityIndicator = new gpszhuangtai(THEME_COLOR);
        fixQualityIndicator.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        fixQualityIndicator.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (SwingUtilities.isLeftMouseButton(e) && mapRenderer != null) {
                    mapRenderer.showMowerInfo();
                }
            }
        });
        mowingProgressLabel = new JLabel("--%");
        mowingProgressLabel.setFont(new Font("微软雅黑", Font.BOLD, 12));
        mowingProgressLabel.setForeground(THEME_COLOR);
 
        mowerSpeedValueLabel = new JLabel("--");
        mowerSpeedValueLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        mowerSpeedValueLabel.setForeground(THEME_COLOR);
 
        mowerSpeedUnitLabel = new JLabel("km/h");
        mowerSpeedUnitLabel.setFont(new Font("微软雅黑", Font.BOLD, 9));
        mowerSpeedUnitLabel.setForeground(THEME_COLOR);
 
        dataPacketCountLabel = new JLabel("--");
        dataPacketCountLabel.setFont(new Font("微软雅黑", Font.BOLD, 12));
        dataPacketCountLabel.setForeground(THEME_COLOR);
 
        rightPanel.add(fixQualityIndicator);
 
        JSeparator areaSeparator = new JSeparator(SwingConstants.VERTICAL);
        areaSeparator.setPreferredSize(new Dimension(1, 16));
        rightPanel.add(areaSeparator);
 
        rightPanel.add(mowingProgressLabel);
        JSeparator speedSeparator = new JSeparator(SwingConstants.VERTICAL);
        speedSeparator.setPreferredSize(new Dimension(1, 16));
        rightPanel.add(speedSeparator);
        rightPanel.add(mowerSpeedValueLabel);
        rightPanel.add(mowerSpeedUnitLabel);
 
        JSeparator separator = new JSeparator(SwingConstants.VERTICAL);
        separator.setPreferredSize(new Dimension(1, 16));
        rightPanel.add(separator);
 
        rightPanel.add(dataPacketCountLabel);
 
        panel.add(rightPanel, BorderLayout.EAST);
        updateFixQualityIndicator();
        updateDataPacketCountLabel();
        return panel;
    }
 
    private void startMowerSpeedUpdates() {
        if (mowerSpeedRefreshTimer == null) {
            mowerSpeedRefreshTimer = new Timer(1000, e -> refreshMowerSpeedLabel());
            mowerSpeedRefreshTimer.setRepeats(true);
        }
        if (!mowerSpeedRefreshTimer.isRunning()) {
            mowerSpeedRefreshTimer.start();
        }
        refreshMowerSpeedLabel();
    }
 
    private void refreshMowerSpeedLabel() {
        if (mowerSpeedValueLabel == null) {
            return;
        }
        String display = "--";
        Device device = Device.getGecaoji();
        if (device != null) {
            String sanitized = sanitizeSpeedValue(device.getRealtimeSpeed());
            if (sanitized != null) {
                display = sanitized;
            }
        }
        mowerSpeedValueLabel.setText(display);
        if (mowerSpeedUnitLabel != null) {
            mowerSpeedUnitLabel.setText("km/h");
        }
        updateMowingProgressLabel();
        updateFixQualityIndicator();
        updateDataPacketCountLabel();
    }
 
    private void updateDataPacketCountLabel() {
        if (dataPacketCountLabel == null) {
            return;
        }
        int udpCount = UDPServer.getReceivedPacketCount();
        int serialCount = dellmessage.getProcessedLineCount();
        int displayCount = Math.max(udpCount, serialCount);
 
        if (displayCount <= 0) {
            dataPacketCountLabel.setText("--");
            dataPacketCountLabel.setToolTipText(null);
        } else {
            dataPacketCountLabel.setText(String.valueOf(displayCount));
            dataPacketCountLabel.setToolTipText(String.format("串口: %d  UDP: %d", serialCount, udpCount));
        }
    }
 
    private void updateFixQualityIndicator() {
        if (fixQualityIndicator == null) {
            return;
        }
        Device device = Device.getGecaoji();
        String code = null;
        if (device != null) {
            code = sanitizeDeviceValue(device.getPositioningStatus());
        }
        fixQualityIndicator.setQuality(code);
    }
 
    private Color resolveFixQualityColor(String code) {
        if (code == null) {
            return new Color(160, 160, 160);
        }
        switch (code) {
        case "0":
            return new Color(160, 160, 160);
        case "1":
            return new Color(52, 152, 219);
        case "2":
            return new Color(26, 188, 156);
        case "3":
            return new Color(155, 89, 182);
        case "4":
            return THEME_COLOR;
        case "5":
            return new Color(241, 196, 15);
        case "6":
            return new Color(231, 76, 60);
        case "7":
            return new Color(230, 126, 34);
        default:
            return new Color(95, 95, 95);
        }
    }
 
    private String resolveFixQualityDescription(String code) {
        if (code == null) {
            return "未知";
        }
        switch (code) {
        case "0":
            return "未定位";
        case "1":
            return "单点定位";
        case "2":
            return "码差分";
        case "3":
            return "无效PPS";
        case "4":
            return "固定解";
        case "5":
            return "浮点解";
        case "6":
            return "正在估算";
        case "7":
            return "人工输入固定值";
        default:
            return "其他";
        }
    }
 
    private String sanitizeSpeedValue(String raw) {
        if (raw == null) {
            return null;
        }
        String trimmed = raw.trim();
        if (trimmed.isEmpty() || "-1".equals(trimmed)) {
            return null;
        }
        if (trimmed.toLowerCase().endsWith("km/h")) {
            trimmed = trimmed.substring(0, trimmed.length() - 4).trim();
        }
        return trimmed;
    }
 
    private String sanitizeDeviceValue(String raw) {
        if (raw == null) {
            return null;
        }
        String trimmed = raw.trim();
        if (trimmed.isEmpty() || "-1".equals(trimmed) || "null".equalsIgnoreCase(trimmed)) {
            return null;
        }
        return trimmed;
    }
 
    private void updateMowingProgressLabel() {
        if (mowingProgressLabel == null) {
            return;
        }
        if (mapRenderer == null) {
            mowingProgressLabel.setText("--%");
            mowingProgressLabel.setToolTipText(null);
            return;
        }
 
        double totalArea = mapRenderer.getTotalLandAreaSqMeters();
        double completedArea = mapRenderer.getCompletedMowingAreaSqMeters();
        double ratio = mapRenderer.getMowingCompletionRatio();
 
        if (totalArea <= 0) {
            mowingProgressLabel.setText("--%");
            mowingProgressLabel.setToolTipText("暂无地块面积数据");
            return;
        }
 
        double percent = Math.max(0.0, Math.min(1.0, ratio)) * 100.0;
        mowingProgressLabel.setText(String.format(Locale.US, "%.1f%%", percent));
        mowingProgressLabel.setToolTipText(String.format(Locale.US, "%.1f㎡ / %.1f㎡", completedArea, totalArea));
    }
 
    public void refreshMowingIndicators() {
        refreshMowerSpeedLabel();
    }
 
    public void setHandheldMowerIconActive(boolean active) {
        if (mapRenderer == null) {
            return;
        }
        mapRenderer.setHandheldMowerIconActive(active);
    }
 
    public void setStatusLabelText(String text) {
        if (statusLabel != null) {
            statusLabel.setText(text);
        }
    }
 
    public boolean startMowerBoundaryCapture() {
        if (mapRenderer == null) {
            return false;
        }
        double[] baseLatLonCandidate = resolveCircleBaseLatLon();
        if (baseLatLonCandidate == null) {
            return false;
        }
 
        mapRenderer.clearIdleTrail();
 
        activeBoundaryMode = BoundaryCaptureMode.MOWER;
        mowerBoundaryCaptureActive = true;
        mowerBaseLatLon = baseLatLonCandidate;
        lastMowerCoordinate = null;
 
        synchronized (Coordinate.coordinates) {
            Coordinate.coordinates.clear();
        }
        synchronized (mowerTemporaryPoints) {
            mowerTemporaryPoints.clear();
        }
 
        AddDikuai.recordTemporaryBoundaryPoints(Collections.emptyList());
        Coordinate.setStartSaveGngga(true);
 
        if (mapRenderer != null) {
            mapRenderer.setBoundaryPreviewMarkerScale(2.0d);
            mapRenderer.beginHandheldBoundaryPreview();
        }
 
        setHandheldMowerIconActive(false);
 
        startMowerBoundaryMonitor();
        return true;
    }
 
    public boolean startHandheldBoundaryCapture() {
        if (mapRenderer == null) {
            return false;
        }
        if (activeBoundaryMode == BoundaryCaptureMode.MOWER) {
            stopMowerBoundaryCapture();
        }
 
        mapRenderer.clearIdleTrail();
 
        activeBoundaryMode = BoundaryCaptureMode.HANDHELD;
        handheldCaptureActive = true;
        handheldCapturedPoints = 0;
        Coordinate.setStartSaveGngga(false);
        synchronized (Coordinate.coordinates) {
            Coordinate.coordinates.clear();
        }
        synchronized (handheldTemporaryPoints) {
            handheldTemporaryPoints.clear();
        }
        AddDikuai.recordTemporaryBoundaryPoints(Collections.emptyList());
        mapRenderer.setBoundaryPreviewMarkerScale(1.0d);
        mapRenderer.beginHandheldBoundaryPreview();
        setHandheldMowerIconActive(true);
        enterHandheldCaptureInlineUi();
        return true;
    }
 
    private void startMowerBoundaryMonitor() {
        if (mowerBoundaryMonitor == null) {
            mowerBoundaryMonitor = new Timer(600, e -> pollMowerBoundaryCoordinate());
            mowerBoundaryMonitor.setRepeats(true);
        }
        if (!mowerBoundaryMonitor.isRunning()) {
            mowerBoundaryMonitor.start();
        }
        pollMowerBoundaryCoordinate();
    }
 
    private void stopMowerBoundaryMonitor() {
        if (mowerBoundaryMonitor != null && mowerBoundaryMonitor.isRunning()) {
            mowerBoundaryMonitor.stop();
        }
    }
 
    private void pollMowerBoundaryCoordinate() {
        if (!mowerBoundaryCaptureActive) {
            return;
        }
 
        Coordinate latest = getLatestCoordinate();
        if (latest == null || latest == lastMowerCoordinate) {
            return;
        }
 
        double[] base = mowerBaseLatLon;
        if (base == null || base.length < 2) {
            discardLatestCoordinate(latest);
            lastMowerCoordinate = latest;
            return;
        }
 
        double lat = parseDMToDecimal(latest.getLatitude(), latest.getLatDirection());
        double lon = parseDMToDecimal(latest.getLongitude(), latest.getLonDirection());
        if (!Double.isFinite(lat) || !Double.isFinite(lon)) {
            discardLatestCoordinate(latest);
            lastMowerCoordinate = latest;
            return;
        }
 
        double[] local = convertLatLonToLocal(lat, lon, base[0], base[1]);
        Point2D.Double candidate = new Point2D.Double(local[0], local[1]);
        if (!Double.isFinite(candidate.x) || !Double.isFinite(candidate.y)) {
            discardLatestCoordinate(latest);
            lastMowerCoordinate = latest;
            return;
        }
 
        List<Point2D.Double> snapshot;
        synchronized (mowerTemporaryPoints) {
            for (Point2D.Double existing : mowerTemporaryPoints) {
                if (existing != null && arePointsClose(existing, candidate)) {
                    discardLatestCoordinate(latest);
                    lastMowerCoordinate = latest;
                    return;
                }
            }
            mowerTemporaryPoints.add(candidate);
            snapshot = new ArrayList<>(mowerTemporaryPoints.size() + 1);
            for (Point2D.Double point : mowerTemporaryPoints) {
                if (point != null) {
                    snapshot.add(new Point2D.Double(point.x, point.y));
                }
            }
        }
 
        ensureClosed(snapshot);
        AddDikuai.recordTemporaryBoundaryPoints(snapshot);
        if (mapRenderer != null) {
            mapRenderer.addHandheldBoundaryPoint(candidate.x, candidate.y);
        }
        lastMowerCoordinate = latest;
    }
 
    private void stopMowerBoundaryCapture() {
        stopMowerBoundaryMonitor();
        mowerBoundaryCaptureActive = false;
        lastMowerCoordinate = null;
        mowerBaseLatLon = null;
        if (mapRenderer != null) {
            mapRenderer.clearHandheldBoundaryPreview();
        }
        Coordinate.setStartSaveGngga(false);
        if (activeBoundaryMode == BoundaryCaptureMode.MOWER) {
            activeBoundaryMode = BoundaryCaptureMode.NONE;
        }
        setHandheldMowerIconActive(false);
    }
 
    private void discardLatestCoordinate(Coordinate coordinate) {
        if (coordinate == null) {
            return;
        }
        synchronized (Coordinate.coordinates) {
            int size = Coordinate.coordinates.size();
            if (size == 0) {
                return;
            }
            int lastIndex = size - 1;
            if (Coordinate.coordinates.get(lastIndex) == coordinate) {
                Coordinate.coordinates.remove(lastIndex);
            } else {
                Coordinate.coordinates.remove(coordinate);
            }
        }
    }
 
    private void ensureClosed(List<Point2D.Double> points) {
        if (points == null || points.size() < 3) {
            return;
        }
        Point2D.Double first = points.get(0);
        Point2D.Double last = points.get(points.size() - 1);
        if (first == null || last == null) {
            return;
        }
        if (!arePointsClose(first, last)) {
            points.add(new Point2D.Double(first.x, first.y));
        }
    }
 
    int captureHandheldBoundaryPoint() {
        if (!handheldCaptureActive) {
            return -1;
        }
        Device device = Device.getGecaoji();
        if (device == null) {
            JOptionPane.showMessageDialog(this, "未检测到采集设备,请检查连接。", "提示", JOptionPane.WARNING_MESSAGE);
            return -1;
        }
 
        String[] latParts = splitCoordinateComponents(device.getRealtimeLatitude(), true);
        String[] lonParts = splitCoordinateComponents(device.getRealtimeLongitude(), false);
        if (latParts == null || lonParts == null) {
            JOptionPane.showMessageDialog(this, "当前定位无效,请在定位稳定后再试。", "提示", JOptionPane.WARNING_MESSAGE);
            return -1;
        }
 
        double x = parseMetersValue(device.getRealtimeX());
        double y = parseMetersValue(device.getRealtimeY());
        if (!Double.isFinite(x) || !Double.isFinite(y)) {
            JOptionPane.showMessageDialog(this, "当前定位数据无效,请稍后再试。", "提示", JOptionPane.WARNING_MESSAGE);
            return -1;
        }
        if (isDuplicateHandheldPoint(x, y)) {
            JOptionPane.showMessageDialog(this, "当前坐标已采集,请移动到新的位置后再试。", "提示", JOptionPane.WARNING_MESSAGE);
            return -1;
        }
 
        double altitude = parseAltitudeValue(device.getRealtimeAltitude());
        Coordinate coordinate = new Coordinate(latParts[0], latParts[1], lonParts[0], lonParts[1], altitude);
        synchronized (Coordinate.coordinates) {
            Coordinate.coordinates.add(coordinate);
        }
 
        if (mapRenderer != null) {
            mapRenderer.addHandheldBoundaryPoint(x, y);
        }
 
        List<Point2D.Double> snapshot;
        synchronized (handheldTemporaryPoints) {
            handheldTemporaryPoints.add(new Point2D.Double(x, y));
            snapshot = new ArrayList<>(handheldTemporaryPoints);
        }
        AddDikuai.recordTemporaryBoundaryPoints(snapshot);
 
        handheldCapturedPoints++;
        return handheldCapturedPoints;
    }
 
    boolean finishHandheldBoundaryCapture() {
        if (!handheldCaptureActive) {
            return false;
        }
        if (handheldCapturedPoints < 3) {
            JOptionPane.showMessageDialog(this, "至少采集三个点才能生成边界。", "提示", JOptionPane.WARNING_MESSAGE);
            return false;
        }
 
        List<Point2D.Double> closedSnapshot = createClosedHandheldPointSnapshot();
        handheldCaptureActive = false;
        activeBoundaryMode = BoundaryCaptureMode.NONE;
        Coordinate.setStartSaveGngga(false);
        if (mapRenderer != null) {
            mapRenderer.clearHandheldBoundaryPreview();
        }
 
        AddDikuai.recordTemporaryBoundaryPoints(closedSnapshot);
 
        exitHandheldCaptureInlineUi();
 
        SwingUtilities.invokeLater(AddDikuai::finishDrawingSession);
        return true;
    }
 
    int getHandheldCapturedPointCount() {
        return handheldCapturedPoints;
    }
 
    public List<Point2D.Double> getHandheldTemporaryPointsSnapshot() {
        if (activeBoundaryMode == BoundaryCaptureMode.MOWER) {
            return createClosedMowerPointSnapshot();
        }
        if (!handheldCaptureActive) {
            return createClosedHandheldPointSnapshot();
        }
        synchronized (handheldTemporaryPoints) {
            return new ArrayList<>(handheldTemporaryPoints);
        }
    }
 
    public boolean isCurrentHandheldPointDuplicate() {
        Device device = Device.getGecaoji();
        if (device == null) {
            return false;
        }
        double x = parseMetersValue(device.getRealtimeX());
        double y = parseMetersValue(device.getRealtimeY());
        if (!Double.isFinite(x) || !Double.isFinite(y)) {
            return false;
        }
        return isDuplicateHandheldPoint(x, y);
    }
 
    public boolean hasValidRealtimeHandheldPosition() {
        Device device = Device.getGecaoji();
        if (device == null) {
            return false;
        }
        double x = parseMetersValue(device.getRealtimeX());
        double y = parseMetersValue(device.getRealtimeY());
        return Double.isFinite(x) && Double.isFinite(y);
    }
 
    private boolean isDuplicateHandheldPoint(double x, double y) {
        Point2D.Double candidate = new Point2D.Double(x, y);
        synchronized (handheldTemporaryPoints) {
            for (Point2D.Double existing : handheldTemporaryPoints) {
                if (existing == null) {
                    continue;
                }
                if (arePointsClose(existing, candidate)) {
                    return true;
                }
            }
        }
        return false;
    }
 
    private boolean arePointsClose(Point2D.Double a, Point2D.Double b) {
        if (a == null || b == null) {
            return false;
        }
        double dx = a.x - b.x;
        double dy = a.y - b.y;
        return Math.hypot(dx, dy) < HANDHELD_DUPLICATE_THRESHOLD_METERS;
    }
 
    private List<Point2D.Double> createClosedHandheldPointSnapshot() {
        List<Point2D.Double> copy = new ArrayList<>();
        synchronized (handheldTemporaryPoints) {
            for (Point2D.Double point : handheldTemporaryPoints) {
                if (point != null) {
                    copy.add(new Point2D.Double(point.x, point.y));
                }
            }
        }
        ensureClosed(copy);
        return copy;
    }
 
    private List<Point2D.Double> createClosedMowerPointSnapshot() {
        List<Point2D.Double> copy = new ArrayList<>();
        synchronized (mowerTemporaryPoints) {
            for (Point2D.Double point : mowerTemporaryPoints) {
                if (point != null) {
                    copy.add(new Point2D.Double(point.x, point.y));
                }
            }
        }
        ensureClosed(copy);
        return copy;
    }
 
    private String[] splitCoordinateComponents(String combined, boolean latitude) {
        if (combined == null) {
            return null;
        }
        String trimmed = combined.trim();
        if (trimmed.isEmpty() || "-1".equals(trimmed)) {
            return null;
        }
 
        String valuePart;
        String directionPart = null;
        String[] parts = trimmed.split(",");
        if (parts.length >= 2) {
            valuePart = parts[0].trim();
            directionPart = parts[1].trim();
        } else {
            valuePart = trimmed;
        }
 
        if (valuePart.isEmpty()) {
            return null;
        }
 
        if (directionPart == null || directionPart.isEmpty()) {
            char lastChar = valuePart.charAt(valuePart.length() - 1);
            if (Character.isLetter(lastChar)) {
                directionPart = String.valueOf(lastChar);
                valuePart = valuePart.substring(0, valuePart.length() - 1).trim();
            }
        }
 
        if (valuePart.isEmpty()) {
            return null;
        }
 
        directionPart = normalizeHemisphere(directionPart, latitude);
        return new String[]{valuePart, directionPart};
    }
 
    private String normalizeHemisphere(String direction, boolean latitude) {
        if (direction == null || direction.trim().isEmpty()) {
            return latitude ? "N" : "E";
        }
        String normalized = direction.trim().toUpperCase(Locale.ROOT);
        if (latitude) {
            if (!"N".equals(normalized) && !"S".equals(normalized)) {
                return "N";
            }
        } else {
            if (!"E".equals(normalized) && !"W".equals(normalized)) {
                return "E";
            }
        }
        return normalized;
    }
 
    private double parseMetersValue(String raw) {
        if (raw == null) {
            return Double.NaN;
        }
        String trimmed = raw.trim();
        if (trimmed.isEmpty() || "-1".equals(trimmed)) {
            return Double.NaN;
        }
        try {
            return Double.parseDouble(trimmed);
        } catch (NumberFormatException ex) {
            return Double.NaN;
        }
    }
 
    private double parseAltitudeValue(String raw) {
        if (raw == null) {
            return 0.0;
        }
        String trimmed = raw.trim();
        if (trimmed.isEmpty() || "-1".equals(trimmed)) {
            return 0.0;
        }
        try {
            return Double.parseDouble(trimmed);
        } catch (NumberFormatException ex) {
            return 0.0;
        }
    }
 
    private boolean beginMowingSession() {
        if (mapRenderer == null) {
            return false;
        }
        String landNumber = Dikuaiguanli.getCurrentWorkLandNumber();
        if (!isMeaningfulValue(landNumber)) {
            JOptionPane.showMessageDialog(this, "请先选择地块后再开始作业", "提示", JOptionPane.WARNING_MESSAGE);
            return false;
        }
 
        double widthMeters = resolveMowerWidthMeters(landNumber);
        if (widthMeters <= 0) {
            JOptionPane.showMessageDialog(this, "未配置割草宽度,将无法计算作业面积", "提示", JOptionPane.WARNING_MESSAGE);
        }
 
        mapRenderer.startRealtimeTrackRecording(landNumber, widthMeters);
        refreshMowerSpeedLabel();
        return true;
    }
 
    private void pauseMowingSession() {
        if (mapRenderer == null) {
            return;
        }
        mapRenderer.pauseRealtimeTrackRecording();
        refreshMowerSpeedLabel();
    }
 
    private void stopMowingSession() {
        if (mapRenderer == null) {
            return;
        }
        mapRenderer.stopRealtimeTrackRecording();
        refreshMowerSpeedLabel();
    }
 
    private double resolveMowerWidthMeters(String landNumber) {
        double width = 0.0;
        if (isMeaningfulValue(landNumber)) {
            Dikuai current = Dikuai.getDikuai(landNumber);
            if (current != null) {
                width = parseMowerWidthMeters(current.getMowingWidth());
            }
        }
        if (width > 0) {
            return width;
        }
        return parseMowerWidthFromDevice();
    }
 
    private double parseMowerWidthFromDevice() {
        Device device = Device.getGecaoji();
        if (device == null) {
            return 0.0;
        }
        return parseMowerWidthMeters(device.getMowingWidth());
    }
 
    private double parseMowerWidthMeters(String raw) {
        if (raw == null) {
            return 0.0;
        }
        String sanitized = raw.trim().toLowerCase(Locale.ROOT);
        if (sanitized.isEmpty() || "-1".equals(sanitized)) {
            return 0.0;
        }
        sanitized = sanitized.replace("厘米", "cm");
        sanitized = sanitized.replace("公分", "cm");
        sanitized = sanitized.replace("米", "m");
        sanitized = sanitized.replace("cm", "");
        sanitized = sanitized.replace("m", "");
        sanitized = sanitized.trim();
        if (sanitized.isEmpty()) {
            return 0.0;
        }
        try {
            double value = Double.parseDouble(sanitized);
            if (value <= 0) {
                return 0.0;
            }
            if (value > 10) {
                return value / 100.0;
            }
            return value;
        } catch (NumberFormatException ex) {
            return 0.0;
        }
    }
 
    private void applyStatusLabelColor(String statusText) {
        if (statusLabel == null) {
            return;
        }
        if ("作业中".equals(statusText) || "绘制中".equals(statusText)) {
            statusLabel.setForeground(THEME_COLOR);
        } else if ("暂停中".equals(statusText) || "绘制暂停".equals(statusText)) {
            statusLabel.setForeground(STATUS_PAUSE_COLOR);
        } else {
            statusLabel.setForeground(Color.GRAY);
        }
    }
 
    private void ensureBluetoothIconsLoaded() {
        if (bluetoothIcon == null) {
            bluetoothIcon = loadScaledIcon("image/blue.png", 28, 28);
        }
        if (bluetoothLinkedIcon == null) {
            bluetoothLinkedIcon = loadScaledIcon("image/bluelink.png", 28, 28);
        }
    }
 
    private JButton createFloatingIconButton() {
        JButton button = new JButton();
        button.setContentAreaFilled(false);
        button.setBorder(BorderFactory.createEmptyBorder());
        button.setFocusPainted(false);
        button.setOpaque(false);
        button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        int size = FLOAT_ICON_SIZE + 8;
        button.setPreferredSize(new Dimension(size, size));
        return button;
    }
 
    private JButton createFloatingTextButton(String text) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 15));
        button.setForeground(Color.WHITE);
        button.setBackground(THEME_COLOR);
        button.setBorder(BorderFactory.createEmptyBorder(10, 18, 10, 18));
        button.setFocusPainted(false);
        button.setOpaque(true);
        button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                button.setBackground(THEME_HOVER_COLOR);
            }
 
            @Override
            public void mouseExited(MouseEvent e) {
                button.setBackground(THEME_COLOR);
            }
        });
        return button;
    }
 
    private ImageIcon loadScaledIcon(String path, int width, int height) {
        try {
            ImageIcon icon = new ImageIcon(path);
            if (icon.getIconWidth() <= 0 || icon.getIconHeight() <= 0) {
                return null;
            }
            Image scaled = icon.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH);
            return new ImageIcon(scaled);
        } catch (Exception ex) {
            System.err.println("加载图标失败: " + path + " - " + ex.getMessage());
            return null;
        }
    }
 
    private void ensureFloatingIconsLoaded() {
        if (pauseIcon == null) {
            pauseIcon = loadScaledIcon("image/zanting.png", FLOAT_ICON_SIZE, FLOAT_ICON_SIZE);
        }
        if (pauseActiveIcon == null) {
            pauseActiveIcon = loadScaledIcon("image/zantingzhong.png", FLOAT_ICON_SIZE, FLOAT_ICON_SIZE);
        }
        if (endIcon == null) {
            endIcon = loadScaledIcon("image/end.png", FLOAT_ICON_SIZE, FLOAT_ICON_SIZE);
        }
    }
 
    private void updatePauseButtonVisual() {
        if (drawingPauseButton == null) {
            return;
        }
        if (drawingPaused) {
            if (pauseActiveIcon != null) {
                drawingPauseButton.setIcon(pauseActiveIcon);
                drawingPauseButton.setText(null);
            } else {
                drawingPauseButton.setText("暂停中");
                drawingPauseButton.setIcon(null);
            }
            drawingPauseButton.setToolTipText("点击恢复绘制");
        } else {
            if (pauseIcon != null) {
                drawingPauseButton.setIcon(pauseIcon);
                drawingPauseButton.setText(null);
            } else {
                drawingPauseButton.setText("暂停");
                drawingPauseButton.setIcon(null);
            }
            drawingPauseButton.setToolTipText("点击暂停绘制");
        }
    }
 
    private void applyDrawingPauseState(boolean paused, boolean notifyCoordinate) {
        drawingPaused = paused;
        updatePauseButtonVisual();
        if (notifyCoordinate) {
            Coordinate.setStartSaveGngga(!paused);
        }
        if (drawingControlModeActive) {
            updateDrawingControlButtonLabels();
            if (statusLabel != null) {
                if (returnPathDrawer != null && returnPathDrawer.isActive()) {
                    statusLabel.setText("正在绘制往返路径");
                } else {
                    statusLabel.setText(paused ? "绘制暂停" : "绘制中");
                }
            }
        }
    }
 
    private void toggleDrawingPause() {
        applyDrawingPauseState(!drawingPaused, true);
    }
 
    public void showEndDrawingButton(Runnable callback) {
        showEndDrawingButton(callback, null);
    }
 
    public void showEndDrawingButton(Runnable callback, String drawingShape) {
        endDrawingCallback = callback;
        circleDialogMode = false;
        hideCircleGuidancePanel();
        enterDrawingControlMode();
        
        // 隐藏返回设置按钮(如果显示绘制按钮,则不应该显示返回按钮)
//      if (settingsReturnButton != null) {
//          settingsReturnButton.setVisible(false);
//      }
        
        // 显示"正在绘制边界"提示
        if (drawingBoundaryLabel != null) {
            // 如果是往返路径绘制,不显示此标签(状态栏已显示"正在绘制往返路径")
//          boolean isReturnPathDrawing = returnPathDrawer != null && returnPathDrawer.isActive();
//          drawingBoundaryLabel.setVisible(!isReturnPathDrawing);
            drawingBoundaryLabel.setVisible(true);
        }
 
        boolean enableCircleGuidance = drawingShape != null
                && "circle".equalsIgnoreCase(drawingShape.trim());
        if (enableCircleGuidance) {
            ensureFloatingIconsLoaded();
            ensureFloatingButtonInfrastructure();
            if (drawingPauseButton != null) {
                drawingPauseButton.setVisible(false);
            }
            if (endDrawingButton != null) {
                endDrawingButton.setVisible(false);
            }
            prepareCircleGuidanceState();
            showCircleGuidanceStep(1);
            floatingButtonPanel.setVisible(true);
            if (floatingButtonPanel.getParent() != visualizationPanel) {
                visualizationPanel.add(floatingButtonPanel, BorderLayout.SOUTH);
            }
            rebuildFloatingButtonColumn();
        } else {
            clearCircleGuidanceArtifacts();
            hideFloatingDrawingControls();
        }
 
        visualizationPanel.revalidate();
        visualizationPanel.repaint();
    }
 
    private void ensureFloatingButtonInfrastructure() {
        if (endDrawingButton == null) {
            endDrawingButton = createFloatingIconButton();
            endDrawingButton.addActionListener(e -> {
                if (endDrawingCallback != null) {
                    endDrawingCallback.run();
                }
            });
        }
        if (endIcon != null) {
            endDrawingButton.setIcon(endIcon);
            endDrawingButton.setText(null);
        } else {
            endDrawingButton.setText("结束绘制");
        }
        endDrawingButton.setToolTipText("结束绘制");
 
        if (drawingPauseButton == null) {
            drawingPauseButton = createFloatingIconButton();
            drawingPauseButton.addActionListener(e -> toggleDrawingPause());
        }
        updatePauseButtonVisual();
 
        if (floatingButtonPanel == null) {
            floatingButtonPanel = new JPanel(new BorderLayout());
            floatingButtonPanel.setOpaque(false);
            floatingButtonPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 20, 20));
 
            floatingButtonColumn = new JPanel();
            floatingButtonColumn.setOpaque(false);
            floatingButtonColumn.setLayout(new BoxLayout(floatingButtonColumn, BoxLayout.Y_AXIS));
            floatingButtonPanel.add(floatingButtonColumn, BorderLayout.EAST);
        }
    }
 
    private void hideFloatingDrawingControls() {
        if (drawingPauseButton != null) {
            drawingPauseButton.setVisible(false);
        }
        if (endDrawingButton != null) {
            endDrawingButton.setVisible(false);
        }
        if (floatingButtonPanel != null) {
            floatingButtonPanel.setVisible(false);
        }
        if (!circleDialogMode) {
            rebuildFloatingButtonColumn();
        }
    }
 
    private void rebuildFloatingButtonColumn() {
        if (floatingButtonColumn == null) {
            return;
        }
        floatingButtonColumn.removeAll();
        boolean added = false;
        if (!circleDialogMode && circleGuidancePanel != null && circleGuidancePanel.isVisible()) {
            floatingButtonColumn.add(circleGuidancePanel);
            added = true;
        }
        if (!circleDialogMode && drawingPauseButton != null && drawingPauseButton.isVisible()) {
            if (added) {
                floatingButtonColumn.add(Box.createRigidArea(new Dimension(0, 10)));
            }
            floatingButtonColumn.add(drawingPauseButton);
            added = true;
        }
        if (!circleDialogMode && endDrawingButton != null && endDrawingButton.isVisible()) {
            if (added) {
                floatingButtonColumn.add(Box.createRigidArea(new Dimension(0, 10)));
            }
            floatingButtonColumn.add(endDrawingButton);
            added = true;
        }
        if (pathPreviewReturnButton != null && pathPreviewReturnButton.isVisible()) {
            if (added) {
                floatingButtonColumn.add(Box.createRigidArea(new Dimension(0, 10)));
            }
            floatingButtonColumn.add(pathPreviewReturnButton);
            added = true;
        }
        if (saveManualBoundaryButton != null && saveManualBoundaryButton.isVisible()) {
            if (added) {
                floatingButtonColumn.add(Box.createRigidArea(new Dimension(0, 10)));
            }
            floatingButtonColumn.add(saveManualBoundaryButton);
            added = true;
        }
        if (settingsReturnButton != null && settingsReturnButton.isVisible()) {
            if (added) {
                floatingButtonColumn.add(Box.createRigidArea(new Dimension(0, 10)));
            }
            floatingButtonColumn.add(settingsReturnButton);
            added = true;
        }
        floatingButtonColumn.revalidate();
        floatingButtonColumn.repaint();
    }
 
    private void showCircleGuidanceStep(int step) {
        ensureCircleGuidancePanel();
        if (circleGuidancePanel == null) {
            return;
        }
        circleGuidanceStep = step;
 
        if (step == 1) {
            circleGuidanceLabel.setText("采集第1个点");
            circleGuidancePrimaryButton.setText("确认第1点");
            circleGuidanceSecondaryButton.setText("返回");
            circleGuidanceSecondaryButton.setVisible(true);
        } else if (step == 2) {
            circleGuidanceLabel.setText("采集第2个点");
            circleGuidancePrimaryButton.setText("确认第2点");
            circleGuidanceSecondaryButton.setText("返回");
            circleGuidanceSecondaryButton.setVisible(true);
        } else if (step == 3) {
            circleGuidanceLabel.setText("采集第3个点");
            circleGuidancePrimaryButton.setText("确认第3点");
            circleGuidanceSecondaryButton.setText("返回");
            circleGuidanceSecondaryButton.setVisible(true);
        } else if (step == 4) {
            circleGuidanceLabel.setText("已采集三个点");
            circleGuidancePrimaryButton.setText("结束绘制");
            circleGuidanceSecondaryButton.setText("重新采集");
            circleGuidanceSecondaryButton.setVisible(true);
        } else {
            hideCircleGuidancePanel();
            return;
        }
        circleGuidancePanel.setVisible(true);
 
        refreshCircleGuidanceButtonAvailability();
 
        if (circleDialogMode) {
            ensureCircleGuidanceDialog();
            if (circleGuidanceDialog != null) {
                circleGuidanceDialog.pack();
                positionCircleGuidanceDialog();
                circleGuidanceDialog.setVisible(true);
                circleGuidanceDialog.toFront();
            }
        } else {
            rebuildFloatingButtonColumn();
        }
    }
 
    private void ensureCircleGuidancePanel() {
        if (circleGuidancePanel != null) {
            return;
        }
        circleGuidancePanel = new JPanel();
        circleGuidancePanel.setLayout(new BoxLayout(circleGuidancePanel, BoxLayout.Y_AXIS));
        circleGuidancePanel.setOpaque(true);
        circleGuidancePanel.setBackground(new Color(255, 255, 255, 235));
        circleGuidancePanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(THEME_COLOR, 1),
                BorderFactory.createEmptyBorder(10, 12, 10, 12)));
        circleGuidancePanel.setAlignmentX(Component.LEFT_ALIGNMENT);
 
        circleGuidanceLabel = new JLabel();
        circleGuidanceLabel.setFont(new Font("微软雅黑", Font.BOLD, 13));
        circleGuidanceLabel.setForeground(new Color(33, 37, 41));
        circleGuidanceLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
 
        JPanel buttonRow = new JPanel();
        buttonRow.setLayout(new BoxLayout(buttonRow, BoxLayout.X_AXIS));
        buttonRow.setOpaque(false);
        buttonRow.setAlignmentX(Component.LEFT_ALIGNMENT);
 
        circleGuidancePrimaryButton = createGuidanceButton("是", THEME_COLOR, Color.WHITE, true);
        circleGuidancePrimaryButton.addActionListener(e -> onCircleGuidancePrimary());
 
        circleGuidanceSecondaryButton = createGuidanceButton("否", Color.WHITE, THEME_COLOR, false);
        circleGuidanceSecondaryButton.addActionListener(e -> onCircleGuidanceSecondary());
 
        buttonRow.add(circleGuidancePrimaryButton);
        buttonRow.add(Box.createRigidArea(new Dimension(8, 0)));
        buttonRow.add(circleGuidanceSecondaryButton);
 
        circleGuidancePanel.add(circleGuidanceLabel);
        circleGuidancePanel.add(Box.createRigidArea(new Dimension(0, 8)));
        circleGuidancePanel.add(buttonRow);
        circleGuidancePanel.setVisible(false);
    }
 
    private void ensureCircleGuidanceDialog() {
        if (circleGuidancePanel == null) {
            return;
        }
        if (circleGuidanceDialog != null) {
            if (circleGuidancePanel.getParent() != circleGuidanceDialog.getContentPane()) {
                detachCircleGuidancePanel();
                circleGuidanceDialog.getContentPane().removeAll();
                circleGuidanceDialog.getContentPane().add(circleGuidancePanel, BorderLayout.CENTER);
                circleGuidanceDialog.pack();
            }
            return;
        }
 
        Window owner = SwingUtilities.getWindowAncestor(this);
        circleGuidanceDialog = new JDialog(owner, "绘制提示", Dialog.ModalityType.MODELESS);
        circleGuidanceDialog.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
        circleGuidanceDialog.setResizable(false);
        circleGuidanceDialog.setAlwaysOnTop(true);
 
        if (owner != null && circleDialogOwnerAdapter == null) {
            circleDialogOwnerAdapter = new ComponentAdapter() {
                @Override
                public void componentMoved(ComponentEvent e) {
                    positionCircleGuidanceDialog();
                }
 
                @Override
                public void componentResized(ComponentEvent e) {
                    positionCircleGuidanceDialog();
                }
            };
            owner.addComponentListener(circleDialogOwnerAdapter);
        }
 
        detachCircleGuidancePanel();
        circleGuidanceDialog.getContentPane().setLayout(new BorderLayout());
        circleGuidanceDialog.getContentPane().add(circleGuidancePanel, BorderLayout.CENTER);
        circleGuidanceDialog.pack();
    }
 
    private void detachCircleGuidancePanel() {
        if (circleGuidancePanel == null) {
            return;
        }
        Container parent = circleGuidancePanel.getParent();
        if (parent != null) {
            parent.remove(circleGuidancePanel);
            parent.revalidate();
            parent.repaint();
        }
    }
 
    private void positionCircleGuidanceDialog() {
        if (circleGuidanceDialog == null) {
            return;
        }
        Window owner = SwingUtilities.getWindowAncestor(this);
        if (owner == null || !owner.isShowing()) {
            return;
        }
        try {
            Point ownerLocation = owner.getLocationOnScreen();
            int x = ownerLocation.x + owner.getWidth() - circleGuidanceDialog.getWidth() - 30;
            int y = ownerLocation.y + owner.getHeight() - circleGuidanceDialog.getHeight() - 40;
            x = Math.max(ownerLocation.x, x);
            y = Math.max(ownerLocation.y, y);
            circleGuidanceDialog.setLocation(x, y);
        } catch (IllegalComponentStateException ex) {
            // Owner not yet displayable; skip positioning
        }
    }
 
    private JButton createGuidanceButton(String text, Color bg, Color fg, boolean filled) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 12));
        button.setForeground(fg);
        button.setBackground(bg);
        button.setOpaque(true);
        button.setFocusPainted(false);
        button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        button.setAlignmentX(Component.LEFT_ALIGNMENT);
        if (filled) {
            button.setBorder(BorderFactory.createEmptyBorder(6, 14, 6, 14));
        } else {
            button.setBackground(Color.WHITE);
            button.setOpaque(true);
            button.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(THEME_COLOR, 1),
                    BorderFactory.createEmptyBorder(5, 12, 5, 12)));
        }
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                if (!button.isEnabled()) {
                    return;
                }
                if (filled) {
                    button.setBackground(THEME_HOVER_COLOR);
                } else {
                    button.setBackground(new Color(245, 245, 245));
                }
            }
 
            @Override
            public void mouseExited(MouseEvent e) {
                if (!button.isEnabled()) {
                    return;
                }
                if (filled) {
                    button.setBackground(bg);
                } else {
                    button.setBackground(Color.WHITE);
                }
            }
        });
        return button;
    }
 
    private void onCircleGuidancePrimary() {
        if (circleGuidanceStep >= 1 && circleGuidanceStep <= 3) {
            if (!recordCircleSamplePoint()) {
                return;
            }
            if (circleGuidanceStep == 3) {
                showCircleGuidanceStep(4);
            } else {
                showCircleGuidanceStep(circleGuidanceStep + 1);
            }
        } else if (circleGuidanceStep == 4) {
            handleCircleCompletion();
        }
    }
 
    private void onCircleGuidanceSecondary() {
        if (circleGuidanceStep == 1 || circleGuidanceStep == 2 || circleGuidanceStep == 3) {
            handleCircleAbort(null);
        } else if (circleGuidanceStep == 4) {
            restartCircleCapture();
        }
    }
 
    private void hideCircleGuidancePanel() {
        circleGuidanceStep = 0;
        if (circleGuidancePanel != null) {
            circleGuidancePanel.setVisible(false);
        }
        if (circleGuidanceDialog != null) {
            circleGuidanceDialog.setVisible(false);
        }
        if (!circleDialogMode) {
            rebuildFloatingButtonColumn();
        }
    }
 
    private void handleCircleAbort(String message) {
        // Return the wizard to step 2 without committing any captured points
        hideEndDrawingButton();
        addzhangaiwu.abortCircleDrawingAndReturn(message);
    }
 
    private void handleCircleCompletion() {
        hideCircleGuidancePanel();
        clearCircleGuidanceArtifacts();
        if (endDrawingCallback != null) {
            endDrawingCallback.run();
        } else {
            addzhangaiwu.finishDrawingSession();
        }
    }
 
    private void prepareCircleGuidanceState() {
        clearCircleGuidanceArtifacts();
        circleBaseLatLon = resolveCircleBaseLatLon();
        startCircleDataMonitor();
    }
 
    private void clearCircleGuidanceArtifacts() {
        stopCircleDataMonitor();
        circleCapturedPoints.clear();
        circleBaseLatLon = null;
        lastCapturedCoordinate = null;
        if (mapRenderer != null) {
            mapRenderer.clearCircleCaptureOverlay();
            mapRenderer.clearCircleSampleMarkers();
        }
    }
 
    private void restartCircleCapture() {
        clearCircleGuidanceArtifacts();
        synchronized (Coordinate.coordinates) {
            Coordinate.coordinates.clear();
        }
        Coordinate.setStartSaveGngga(true);
        circleBaseLatLon = resolveCircleBaseLatLon();
        showCircleGuidanceStep(1);
        startCircleDataMonitor();
    }
 
    private boolean recordCircleSamplePoint() {
        Coordinate latest = getLatestCoordinate();
        if (latest == null) {
            JOptionPane.showMessageDialog(this, "未获取到当前位置坐标,请稍后重试。", "提示", JOptionPane.WARNING_MESSAGE);
            return false;
        }
 
        double[] base = ensureCircleBaseLatLon();
        if (base == null) {
            JOptionPane.showMessageDialog(this, "基准站坐标无效,请先在基准站管理中完成设置。", "提示", JOptionPane.WARNING_MESSAGE);
            return false;
        }
 
        double lat = parseDMToDecimal(latest.getLatitude(), latest.getLatDirection());
        double lon = parseDMToDecimal(latest.getLongitude(), latest.getLonDirection());
        if (!Double.isFinite(lat) || !Double.isFinite(lon)) {
            JOptionPane.showMessageDialog(this, "采集点坐标无效,请重新采集。", "提示", JOptionPane.WARNING_MESSAGE);
            return false;
        }
 
        double[] local = convertLatLonToLocal(lat, lon, base[0], base[1]);
        circleCapturedPoints.add(local);
        if (mapRenderer != null) {
            mapRenderer.updateCircleSampleMarkers(circleCapturedPoints);
        }
        lastCapturedCoordinate = latest;
        refreshCircleGuidanceButtonAvailability();
 
        if (circleCapturedPoints.size() >= 3) {
            CircleSolution solution = fitCircleFromPoints(circleCapturedPoints);
            if (solution == null) {
                circleCapturedPoints.remove(circleCapturedPoints.size() - 1);
                JOptionPane.showMessageDialog(this, "无法根据当前三个点生成圆,请重新采集点。", "提示", JOptionPane.WARNING_MESSAGE);
                restartCircleCapture();
                return false;
            }
            if (mapRenderer != null) {
                mapRenderer.showCircleCaptureOverlay(solution.centerX, solution.centerY, solution.radius, circleCapturedPoints);
            }
        }
 
        return true;
    }
 
    private void startCircleDataMonitor() {
        if (circleDataMonitor == null) {
            circleDataMonitor = new Timer(600, e -> refreshCircleGuidanceButtonAvailability());
            circleDataMonitor.setRepeats(true);
        }
        if (!circleDataMonitor.isRunning()) {
            circleDataMonitor.start();
        }
        refreshCircleGuidanceButtonAvailability();
    }
 
    private void stopCircleDataMonitor() {
        if (circleDataMonitor != null) {
            circleDataMonitor.stop();
        }
    }
 
    private void refreshCircleGuidanceButtonAvailability() {
        if (circleGuidancePrimaryButton == null) {
            return;
        }
        boolean shouldEnable = circleGuidanceStep >= 1 && circleGuidanceStep <= 3
                ? isCircleDataAvailable()
                        : true;
        applyCirclePrimaryButtonState(shouldEnable);
    }
 
    private boolean isCircleDataAvailable() {
        Coordinate latest = getLatestCoordinate();
        if (latest == null) {
            return false;
        }
        
        // 检查是否有新的坐标(与上次采集的不同)
        if (lastCapturedCoordinate != null && latest == lastCapturedCoordinate) {
            return false;
        }
        
        // 检查定位状态是否为4(固定解)
        // 当选择割草机绘制圆形障碍物时,需要检查设备编号和定位状态
        Device device = Device.getGecaoji();
        if (device == null) {
            return false;
        }
        
        String positioningStatus = device.getPositioningStatus();
        if (positioningStatus == null || !"4".equals(positioningStatus.trim())) {
            return false;
        }
        
        // 检查设备编号是否匹配割草机编号
        String mowerId = Setsys.getPropertyValue("mowerId");
        String deviceId = device.getMowerNumber();
        if (mowerId != null && !mowerId.trim().isEmpty()) {
            if (deviceId == null || !mowerId.trim().equals(deviceId.trim())) {
                return false;
            }
        }
        
        return true;
    }
 
    private void applyCirclePrimaryButtonState(boolean enabled) {
        if (circleGuidancePrimaryButton == null) {
            return;
        }
        if (circleGuidanceStep >= 4) {
            enabled = true;
        }
        circleGuidancePrimaryButton.setEnabled(enabled);
        if (enabled) {
            circleGuidancePrimaryButton.setBackground(THEME_COLOR);
            circleGuidancePrimaryButton.setForeground(Color.WHITE);
            circleGuidancePrimaryButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        } else {
            circleGuidancePrimaryButton.setBackground(new Color(200, 200, 200));
            circleGuidancePrimaryButton.setForeground(new Color(120, 120, 120));
            circleGuidancePrimaryButton.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }
    }
 
    private Coordinate getLatestCoordinate() {
        synchronized (Coordinate.coordinates) {
            int size = Coordinate.coordinates.size();
            if (size == 0) {
                return null;
            }
            return Coordinate.coordinates.get(size - 1);
        }
    }
 
    private double[] ensureCircleBaseLatLon() {
        if (circleBaseLatLon == null) {
            circleBaseLatLon = resolveCircleBaseLatLon();
        }
        return circleBaseLatLon;
    }
 
    private double[] resolveCircleBaseLatLon() {
        String coords = null;
 
        if (baseStation == null) {
            baseStation = new BaseStation();
        }
        baseStation.load();
        coords = baseStation.getInstallationCoordinates();
 
        if (!isMeaningfulValue(coords)) {
            String landNumber = Dikuaiguanli.getCurrentWorkLandNumber();
            if (isMeaningfulValue(landNumber)) {
                Dikuai current = Dikuai.getDikuai(landNumber);
                if (current != null) {
                    coords = current.getBaseStationCoordinates();
                }
            }
            if (!isMeaningfulValue(coords)) {
                coords = addzhangaiwu.getActiveSessionBaseStation();
            }
            if (!isMeaningfulValue(coords)) {
                return null;
            }
        }
        String[] parts = coords.split(",");
        if (parts.length < 4) {
            return null;
        }
        double baseLat = parseDMToDecimal(parts[0], parts[1]);
        double baseLon = parseDMToDecimal(parts[2], parts[3]);
        if (!Double.isFinite(baseLat) || !Double.isFinite(baseLon)) {
            return null;
        }
        return new double[]{baseLat, baseLon};
    }
 
    private double parseDMToDecimal(String dmm, String direction) {
        return Gpstoxuzuobiao.parseDMToDecimal(dmm, direction);
    }
 
    private double[] convertLatLonToLocal(double lat, double lon, double baseLat, double baseLon) {
        return Gpstoxuzuobiao.convertLatLonToLocal(lat, lon, baseLat, baseLon);
    }
 
    private CircleSolution fitCircleFromPoints(List<double[]> points) {
        if (points == null || points.size() < 3) {
            return null;
        }
        CircleSolution best = null;
        double bestScore = 0.0;
        int n = points.size();
        for (int i = 0; i < n - 2; i++) {
            double[] p1 = points.get(i);
            for (int j = i + 1; j < n - 1; j++) {
                double[] p2 = points.get(j);
                for (int k = j + 1; k < n; k++) {
                    double[] p3 = points.get(k);
                    CircleSolution candidate = circleFromThreePoints(p1, p2, p3);
                    if (candidate == null || candidate.radius <= 0) {
                        continue;
                    }
                    double minEdge = Math.min(distance(p1, p2), Math.min(distance(p2, p3), distance(p1, p3)));
                    if (minEdge > bestScore) {
                        bestScore = minEdge;
                        best = candidate;
                    }
                }
            }
        }
        return best;
    }
 
    private CircleSolution circleFromThreePoints(double[] p1, double[] p2, double[] p3) {
        if (p1 == null || p2 == null || p3 == null) {
            return null;
        }
        double x1 = p1[0];
        double y1 = p1[1];
        double x2 = p2[0];
        double y2 = p2[1];
        double x3 = p3[0];
        double y3 = p3[1];
 
        double a = x1 * (y2 - y3) - y1 * (x2 - x3) + x2 * y3 - x3 * y2;
        double d = 2.0 * a;
        if (Math.abs(d) < 1e-6) {
            return null;
        }
 
        double x1Sq = x1 * x1 + y1 * y1;
        double x2Sq = x2 * x2 + y2 * y2;
        double x3Sq = x3 * x3 + y3 * y3;
 
        double centerX = (x1Sq * (y2 - y3) + x2Sq * (y3 - y1) + x3Sq * (y1 - y2)) / d;
        double centerY = (x1Sq * (x3 - x2) + x2Sq * (x1 - x3) + x3Sq * (x2 - x1)) / d;
        double radius = Math.hypot(centerX - x1, centerY - y1);
        if (!Double.isFinite(centerX) || !Double.isFinite(centerY) || !Double.isFinite(radius)) {
            return null;
        }
        if (radius < 0.05) {
            return null;
        }
        return new CircleSolution(centerX, centerY, radius);
    }
 
    private double distance(double[] a, double[] b) {
        if (a == null || b == null) {
            return 0.0;
        }
        double dx = a[0] - b[0];
        double dy = a[1] - b[1];
        return Math.hypot(dx, dy);
    }
 
    private static final class CircleSolution {
        final double centerX;
        final double centerY;
        final double radius;
 
        CircleSolution(double centerX, double centerY, double radius) {
            this.centerX = centerX;
            this.centerY = centerY;
            this.radius = radius;
        }
    }
 
    public void hideEndDrawingButton() {
        hideCircleGuidancePanel();
        clearCircleGuidanceArtifacts();
        hideFloatingDrawingControls();
        circleDialogMode = false;
        exitHandheldCaptureInlineUi();
        handheldCaptureActive = false;
        exitDrawingControlMode();
        if (activeBoundaryMode == BoundaryCaptureMode.MOWER) {
            stopMowerBoundaryCapture();
        } else if (activeBoundaryMode == BoundaryCaptureMode.HANDHELD && !handheldCaptureActive) {
            activeBoundaryMode = BoundaryCaptureMode.NONE;
        }
        endDrawingCallback = null;
        
        // 隐藏"正在绘制边界"提示
        if (drawingBoundaryLabel != null) {
            drawingBoundaryLabel.setVisible(false);
        }
        
        visualizationPanel.revalidate();
        visualizationPanel.repaint();
        setHandheldMowerIconActive(false);
    }
 
    private void showPathPreviewReturnControls() {
        ensureFloatingButtonInfrastructure();
        if (drawingPauseButton != null) {
            drawingPauseButton.setVisible(false);
        }
        if (endDrawingButton != null) {
            endDrawingButton.setVisible(false);
        }
        if (pathPreviewReturnButton == null) {
            pathPreviewReturnButton = Fanhuibutton.createReturnButton(e -> handlePathPreviewReturn());
            pathPreviewReturnButton.setToolTipText("返回新增地块步骤");
        }
        pathPreviewReturnButton.setVisible(true);
        if (floatingButtonPanel != null) {
            floatingButtonPanel.setVisible(true);
            if (floatingButtonPanel.getParent() != visualizationPanel) {
                visualizationPanel.add(floatingButtonPanel, BorderLayout.SOUTH);
            }
        }
        rebuildFloatingButtonColumn();
    }
 
    private void hidePathPreviewReturnControls() {
        if (pathPreviewReturnButton != null) {
            pathPreviewReturnButton.setVisible(false);
        }
        rebuildFloatingButtonColumn();
        if (floatingButtonPanel != null && floatingButtonColumn != null
                && floatingButtonColumn.getComponentCount() == 0) {
            floatingButtonPanel.setVisible(false);
        }
    }
 
    private void handlePathPreviewReturn() {
        Runnable callback = pathPreviewReturnAction;
        exitMowingPathPreview();
        if (callback != null) {
            callback.run();
        }
    }
 
    public boolean startMowingPathPreview(String landNumber,
            String landName,
            String boundary,
            String obstacles,
            String plannedPath,
            Runnable returnAction) {
        if (mapRenderer == null) {
            return false;
        }
        // 允许没有路径的预览(例如障碍物预览),只要有返回回调即可
        if (!isMeaningfulValue(plannedPath) && returnAction == null) {
            return false;
        }
 
        if (pathPreviewActive) {
            exitMowingPathPreview();
        }
 
        exitDrawingControlMode();
        hideCircleGuidancePanel();
        clearCircleGuidanceArtifacts();
 
        pathPreviewReturnAction = returnAction;
        pathPreviewActive = true;
        mapRenderer.setPathPreviewSizingEnabled(true);
 
        previewRestoreLandNumber = Dikuaiguanli.getCurrentWorkLandNumber();
        previewRestoreLandName = null;
        if (isMeaningfulValue(previewRestoreLandNumber)) {
            Dikuai existing = Dikuai.getDikuai(previewRestoreLandNumber);
            if (existing != null) {
                previewRestoreLandName = existing.getLandName();
            }
        }
 
        mapRenderer.setCurrentBoundary(boundary, landNumber, landName);
        mapRenderer.setCurrentObstacles(obstacles, landNumber);
        // 只有在有路径时才设置路径
        if (isMeaningfulValue(plannedPath)) {
            mapRenderer.setCurrentPlannedPath(plannedPath);
        } else {
            mapRenderer.setCurrentPlannedPath(null);
        }
        mapRenderer.clearHandheldBoundaryPreview();
        mapRenderer.setBoundaryPointSizeScale(1.0d);
        mapRenderer.setBoundaryPointsVisible(isMeaningfulValue(boundary));
        // 启用障碍物边界点显示
        mapRenderer.setObstaclePointsVisible(isMeaningfulValue(obstacles));
 
        String displayName = isMeaningfulValue(landName) ? landName : landNumber;
        updateCurrentAreaName(displayName);
 
        showPathPreviewReturnControls();
        visualizationPanel.revalidate();
        visualizationPanel.repaint();
        return true;
    }
 
    public void exitMowingPathPreview() {
        if (!pathPreviewActive) {
            return;
        }
        pathPreviewActive = false;
        if (mapRenderer != null) {
            mapRenderer.setPathPreviewSizingEnabled(false);
        }
        hidePathPreviewReturnControls();
 
        String restoreNumber = previewRestoreLandNumber;
        String restoreName = previewRestoreLandName;
        previewRestoreLandNumber = null;
        previewRestoreLandName = null;
        pathPreviewReturnAction = null;
 
        if (restoreNumber != null) {
            Dikuaiguanli.setCurrentWorkLand(restoreNumber, restoreName);
        } else if (mapRenderer != null) {
            mapRenderer.setCurrentBoundary(null, null, null);
            mapRenderer.setCurrentObstacles((String) null, null);
            mapRenderer.setCurrentPlannedPath(null);
            mapRenderer.setBoundaryPointsVisible(false);
            mapRenderer.setBoundaryPointSizeScale(1.0d);
            mapRenderer.clearHandheldBoundaryPreview();
            mapRenderer.resetView();
            updateCurrentAreaName(null);
        }
 
        visualizationPanel.revalidate();
        visualizationPanel.repaint();
    }
 
    /**
     * 获取地图渲染器实例
     */
    public MapRenderer getMapRenderer() {
        return mapRenderer;
    }
 
    /**
     * 获取控制面板(用于导航预览时替换按钮)
     * @return 控制面板
     */
    public JPanel getControlPanel() {
        return controlPanel;
    }
 
    /**
     * 获取开始按钮(用于导航预览时隐藏)
     * @return 开始按钮
     */
    public JButton getStartButton() {
        return startBtn;
    }
 
    /**
     * 获取结束按钮(用于导航预览时隐藏)
     * @return 结束按钮
     */
    public JButton getStopButton() {
        return stopBtn;
    }
 
    /**
     * 设置导航预览模式标签的显示状态
     * @param visible 是否显示
     */
    public void setNavigationPreviewLabelVisible(boolean visible) {
        if (navigationPreviewLabel != null) {
            navigationPreviewLabel.setVisible(visible);
        }
    }
 
    /**
     * 更新导航预览状态显示
     * @param active 是否处于导航预览模式
     */
    public void updateNavigationPreviewStatus(boolean active) {
        setNavigationPreviewLabelVisible(active);
    }
 
    /**
     * 更新割草进度显示
     * @param percentage 完成百分比
     * @param completedArea 已完成面积(平方米)
     * @param totalArea 总面积(平方米)
     */
    public void updateMowingProgress(double percentage, double completedArea, double totalArea) {
        if (mowingProgressLabel == null) {
            return;
        }
        if (totalArea <= 0) {
            mowingProgressLabel.setText("--%");
            mowingProgressLabel.setToolTipText("暂无地块面积数据");
            return;
        }
        double percent = Math.max(0.0, Math.min(100.0, percentage));
        mowingProgressLabel.setText(String.format(Locale.US, "%.1f%%", percent));
        mowingProgressLabel.setToolTipText(String.format(Locale.US, "%.1f㎡ / %.1f㎡", completedArea, totalArea));
    }
 
    /**
     * 更新割草机速度显示
     * @param speed 速度值(单位:km/h)
     */
    public void updateMowerSpeed(double speed) {
        if (mowerSpeedValueLabel == null) {
            return;
        }
        if (speed < 0) {
            mowerSpeedValueLabel.setText("--");
        } else {
            mowerSpeedValueLabel.setText(String.format(Locale.US, "%.1f", speed));
        }
        if (mowerSpeedUnitLabel != null) {
            mowerSpeedUnitLabel.setText("km/h");
        }
    }
 
    /**
     * 获取可视化面板实例
     */
    public JPanel getVisualizationPanel() {
        return visualizationPanel;
    }
    
    /**
     * 获取主内容面板实例(用于添加浮动按钮)
     */
    public JPanel getMainContentPanel() {
        return mainContentPanel;
    }
 
 
    public void updateCurrentAreaName(String areaName) {
        if (areaNameLabel == null) {
            return;
        }
        if (areaName == null || areaName.trim().isEmpty()) {
            areaNameLabel.setText("未选择地块");
        } else {
            areaNameLabel.setText(areaName);
        }
    }
 
    /**
     * 重置地图视图
     */
    public void resetMapView() {
        if (mapRenderer != null) {
            mapRenderer.resetView();
        }
    }
 
    private void initializeDefaultAreaSelection() {
        Dikuai.initFromProperties();
        String persistedLandNumber = Dikuaiguanli.getPersistedWorkLandNumber();
        if (persistedLandNumber != null) {
            Dikuai stored = Dikuai.getDikuai(persistedLandNumber);
            if (stored != null) {
                Dikuaiguanli.setCurrentWorkLand(persistedLandNumber, stored.getLandName());
                return;
            }
            Dikuaiguanli.setCurrentWorkLand(null, null);
        }
 
        Map<String, Dikuai> all = Dikuai.getAllDikuai();
        if (all.isEmpty()) {
            Dikuaiguanli.setCurrentWorkLand(null, null);
        } else if (all.size() == 1) {
            Dikuai only = all.values().iterator().next();
            if (only != null) {
                Dikuaiguanli.setCurrentWorkLand(only.getLandNumber(), only.getLandName());
            }
        }
    }
 
    private void refreshMapForSelectedArea() {
        if (mapRenderer == null) {
            return;
        }
 
        String currentLandNumber = Dikuaiguanli.getCurrentWorkLandNumber();
        if (isMeaningfulValue(currentLandNumber)) {
            Dikuai current = Dikuai.getDikuai(currentLandNumber);
            String landName = current != null ? current.getLandName() : null;
            Dikuaiguanli.setCurrentWorkLand(currentLandNumber, landName);
            return;
        }
 
        String labelName = areaNameLabel != null ? areaNameLabel.getText() : null;
        if (!isMeaningfulAreaName(labelName)) {
            Dikuaiguanli.setCurrentWorkLand(null, null);
            return;
        }
 
        Map<String, Dikuai> all = Dikuai.getAllDikuai();
        for (Dikuai dikuai : all.values()) {
            if (dikuai == null) {
                continue;
            }
            String candidateName = dikuai.getLandName();
            if (candidateName != null && candidateName.trim().equals(labelName.trim())) {
                Dikuaiguanli.setCurrentWorkLand(dikuai.getLandNumber(), candidateName);
                return;
            }
        }
 
        Dikuaiguanli.setCurrentWorkLand(null, null);
    }
 
    private boolean isMeaningfulValue(String value) {
        if (value == null) {
            return false;
        }
        String trimmed = value.trim();
        return !trimmed.isEmpty() && !"-1".equals(trimmed);
    }
 
    private boolean isMeaningfulAreaName(String value) {
        if (value == null) {
            return false;
        }
        String trimmed = value.trim();
        if (trimmed.isEmpty()) {
            return false;
        }
        return !"未选择地块".equals(trimmed);
    }
 
    
    /**
     * 启动往返路径绘制
     * @param finishCallback 完成绘制时的回调
     * @param isHandheld 是否使用手持设备模式
     * @return 是否成功启动
     */
    public boolean startReturnPathDrawing(Runnable finishCallback, boolean isHandheld) {
        if (returnPathDrawer == null) {
            return false;
        }
        return returnPathDrawer.start(finishCallback, isHandheld);
    }
    
    /**
     * 停止往返路径绘制
     */
    public void stopReturnPathDrawing() {
        if (returnPathDrawer != null) {
            returnPathDrawer.stop();
        }
    }
    
    /**
     * 获取往返路径绘制管理器
     */
    public WangfanDraw getReturnPathDrawer() {
        return returnPathDrawer;
    }
    
    /**
     * 启动往返路径预览
     * @param coordinatesStr 路径坐标字符串 (x,y;x,y)
     * @param returnCallback 返回回调
     */
    public void startReturnPathPreview(String coordinatesStr, Runnable returnCallback) {
        if (returnPathDrawer == null || coordinatesStr == null || coordinatesStr.isEmpty()) {
            return;
        }
        
        // 解析坐标
        List<Point2D.Double> points = new ArrayList<>();
        String[] pairs = coordinatesStr.split(";");
        for (String pair : pairs) {
            String[] xy = pair.split(",");
            if (xy.length == 2) {
                try {
                    double x = Double.parseDouble(xy[0]);
                    double y = Double.parseDouble(xy[1]);
                    points.add(new Point2D.Double(x, y));
                } catch (NumberFormatException e) {
                    // 忽略无效坐标
                }
            }
        }
        
        if (points.isEmpty()) {
            JOptionPane.showMessageDialog(this, "没有有效的路径点可预览", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 设置预览点
        returnPathDrawer.setPoints(points);
        if (mapRenderer != null) {
            mapRenderer.setPreviewReturnPath(points);
        }
        
        // 开启预览模式
        pathPreviewActive = true;
        if (mapRenderer != null) {
            mapRenderer.clearIdleTrail();
        }
        pathPreviewReturnAction = returnCallback;
        
        // 确保悬浮按钮基础设施已创建
        ensureFloatingButtonInfrastructure();
        
        // 创建或显示返回按钮
        if (pathPreviewReturnButton == null) {
            // 使用 Fanhuibutton 创建返回按钮
            pathPreviewReturnButton = publicway.Fanhuibutton.createReturnButton(e -> {
                // 停止预览
                stopReturnPathPreview();
            });
            pathPreviewReturnButton.setToolTipText("返回绘制页面");
        }
        
        // 隐藏其他悬浮按钮
        hideFloatingDrawingControls();
        
        // 显示返回按钮
        pathPreviewReturnButton.setVisible(true);
        floatingButtonPanel.setVisible(true);
        if (floatingButtonPanel.getParent() != visualizationPanel) {
            visualizationPanel.add(floatingButtonPanel, BorderLayout.SOUTH);
        }
        rebuildFloatingButtonColumn();
        
        visualizationPanel.revalidate();
        visualizationPanel.repaint();
    }
    
    /**
     * 停止往返路径预览
     */
    private void stopReturnPathPreview() {
        pathPreviewActive = false;
        
        // 清空预览点
        if (returnPathDrawer != null) {
            returnPathDrawer.clearPoints();
        }
        if (mapRenderer != null) {
            mapRenderer.setPreviewReturnPath(null);
        }
        
        // 隐藏返回按钮
        if (pathPreviewReturnButton != null) {
            pathPreviewReturnButton.setVisible(false);
        }
        
        // 隐藏悬浮面板
        if (floatingButtonPanel != null) {
            floatingButtonPanel.setVisible(false);
        }
        
        // 执行返回回调
        if (pathPreviewReturnAction != null) {
            pathPreviewReturnAction.run();
        }
    }
    
    /**
     * 显示边界预览(原始边界-紫色,优化后边界-绿色)
     * @param dikuai 地块对象
     * @param optimizedBoundary 优化后的边界坐标字符串
     * @param returnCallback 返回回调
     */
    public static void showBoundaryPreview(dikuai.Dikuai dikuai, String optimizedBoundary, Runnable returnCallback) {
        Shouye shouye = getInstance();
        if (shouye == null || shouye.mapRenderer == null || dikuai == null) {
            return;
        }
        
        // 获取原始边界XY坐标
        String originalBoundaryXY = dikuai.getBoundaryOriginalXY();
        
        // 设置边界预览
        shouye.mapRenderer.setBoundaryPreview(originalBoundaryXY, optimizedBoundary);
        
        // 设置返回回调
        shouye.pathPreviewReturnAction = returnCallback;
        shouye.pathPreviewActive = true;
        
        // 确保悬浮按钮基础设施已创建
        shouye.ensureFloatingButtonInfrastructure();
        
        // 创建或显示返回按钮
        if (shouye.pathPreviewReturnButton == null) {
            shouye.pathPreviewReturnButton = publicway.Fanhuibutton.createReturnButton(e -> shouye.handleBoundaryPreviewReturn());
            shouye.pathPreviewReturnButton.setToolTipText("返回边界编辑页面");
        }
        
        // 隐藏其他悬浮按钮
        shouye.hideFloatingDrawingControls();
        
        // 显示返回按钮
        shouye.pathPreviewReturnButton.setVisible(true);
        if (shouye.floatingButtonPanel != null) {
            shouye.floatingButtonPanel.setVisible(true);
            if (shouye.floatingButtonPanel.getParent() != shouye.visualizationPanel) {
                shouye.visualizationPanel.add(shouye.floatingButtonPanel, BorderLayout.SOUTH);
            }
        }
        shouye.rebuildFloatingButtonColumn();
        
        shouye.visualizationPanel.revalidate();
        shouye.visualizationPanel.repaint();
    }
    
    /**
     * 处理边界预览返回
     */
    private void handleBoundaryPreviewReturn() {
        Runnable callback = pathPreviewReturnAction;
        exitBoundaryPreview();
        if (callback != null) {
            callback.run();
        }
    }
    
    /**
     * 退出边界预览
     */
    private void exitBoundaryPreview() {
        pathPreviewActive = false;
        
        // 清除边界预览
        if (mapRenderer != null) {
            mapRenderer.clearBoundaryPreview();
        }
        
        // 隐藏返回按钮
        if (pathPreviewReturnButton != null) {
            pathPreviewReturnButton.setVisible(false);
        }
        
        // 隐藏悬浮面板
        if (floatingButtonPanel != null) {
            floatingButtonPanel.setVisible(false);
        }
        
        visualizationPanel.revalidate();
        visualizationPanel.repaint();
    }
 
    // 测试方法
    public static void main(String[] args) {
        JFrame frame = new JFrame("AutoMow - 首页");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 800);
        frame.setLocationRelativeTo(null);
        
        Shouye shouye = new Shouye();
        frame.add(shouye);
        
        frame.setVisible(true);
        UDPServer.startAsync();//启动数据接收线程
    }
}