张世豪
2025-12-02 6799351be12deb2f713f2c0a2b4c467a6d1098c3
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
package dikuai;
 
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.awt.datatransfer.StringSelection;
import java.io.File;
import java.math.BigDecimal;
import ui.UIConfig;
import ui.UIUtils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
 
import zhangaiwu.AddDikuai;
import zhangaiwu.Obstacledge;
import zhuye.MapRenderer;
import zhuye.Shouye;
import zhuye.Coordinate;
 
/**
 * 地块管理面板 - 卡片式布局设计
 * 改为JPanel以适应主界面嵌入,参考Shouye尺寸
 */
public class Dikuaiguanli extends JPanel {
    private static final long serialVersionUID = 1L;
    private static Dikuaiguanli latestInstance;
    // 6.5寸竖屏尺寸
    private final int SCREEN_WIDTH = 400;
    private final int SCREEN_HEIGHT = 800;
 
    // 主题颜色
    private final Color PRIMARY_COLOR = new Color(46, 139, 87);
    private final Color PRIMARY_DARK = new Color(30, 107, 69);
    private final Color RED_COLOR = new Color(255, 107, 107);
    private final Color RED_DARK = new Color(255, 82, 82);
    private final Color TEXT_COLOR = new Color(51, 51, 51);
    private final Color LIGHT_TEXT = new Color(119, 119, 119);
    private final Color WHITE = Color.WHITE;
    private final Color BORDER_COLOR = new Color(200, 200, 200);
    private final Color BACKGROUND_COLOR = new Color(250, 250, 250);
    private final Color CARD_BACKGROUND = new Color(255, 255, 255);
    private final Color CARD_SHADOW = new Color(220, 220, 220);
 
    // 组件
    private JPanel mainPanel;
    private JPanel cardsPanel;
    private JScrollPane scrollPane;
 
    // 按钮
    private JButton addLandBtn;
 
    private static String currentWorkLandNumber;
    private static final Map<String, Boolean> boundaryPointVisibility = new HashMap<>();
    private ImageIcon workSelectedIcon;
    private ImageIcon workUnselectedIcon;
    private ImageIcon boundaryVisibleIcon;
    private ImageIcon boundaryHiddenIcon;
    private static final int BOUNDARY_TOGGLE_ICON_SIZE = 48;
    private Map<String, ObstacleSummary> obstacleSummaryCache = Collections.emptyMap();
 
    public Dikuaiguanli(String landNumber) {
        latestInstance = this;
        initializeUI(landNumber);
        setupEventHandlers();
    }
 
    private void copyCoordinatesAction(String title, String coordinates) {
        if (coordinates == null || coordinates.equals("-1") || coordinates.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, title + " 未设置", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
 
        try {
            StringSelection selection = new StringSelection(coordinates);
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(selection, selection);
            JOptionPane.showMessageDialog(this, title + " 已复制到剪贴板", "提示", JOptionPane.INFORMATION_MESSAGE);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "复制失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
 
    private void initializeUI(String landNumber) {
        setLayout(new BorderLayout());
        setBackground(BACKGROUND_COLOR);
        // 使用与Shouye相同的6.5寸竖屏尺寸
        setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
 
        createMainPanel();
 
        // 添加到主面板
        add(mainPanel, BorderLayout.CENTER);
 
        // 加载地块数据
        loadDikuaiData();
    }
 
    private void createMainPanel() {
        mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        mainPanel.setBackground(BACKGROUND_COLOR);
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
 
        // 顶部:新增按钮
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        topPanel.setBackground(BACKGROUND_COLOR);
        
        addLandBtn = createActionButton("+ 新增地块", PRIMARY_COLOR);
        addLandBtn.setPreferredSize(new Dimension(120, 40));
        addLandBtn.setFont(new Font("微软雅黑", Font.BOLD, 14));
        
        topPanel.add(addLandBtn);
 
        mainPanel.add(topPanel, BorderLayout.NORTH);
 
        // 中部:卡片区域
        cardsPanel = new JPanel();
        cardsPanel.setLayout(new BoxLayout(cardsPanel, BoxLayout.Y_AXIS));
        cardsPanel.setBackground(BACKGROUND_COLOR);
 
        scrollPane = new JScrollPane(cardsPanel);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        scrollPane.getVerticalScrollBar().setUnitIncrement(16);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
 
        mainPanel.add(scrollPane, BorderLayout.CENTER);
    }
 
    private void loadDikuaiData() {
        Dikuai.initFromProperties();
        // 清空现有卡片
        cardsPanel.removeAll();
        
        Map<String, Dikuai> allDikuai = Dikuai.getAllDikuai();
    
        if (allDikuai.isEmpty()) {
            obstacleSummaryCache = Collections.emptyMap();
            // 显示空状态
            JPanel emptyPanel = createEmptyStatePanel();
            cardsPanel.add(emptyPanel);
            setCurrentWorkLand(null, null);
        } else {
            obstacleSummaryCache = loadObstacleSummaries();
            if (allDikuai.size() == 1) {
                Dikuai onlyDikuai = allDikuai.values().iterator().next();
                setCurrentWorklandIfNeeded(onlyDikuai);
            }
            // 为每个地块创建卡片
            for (Dikuai dikuai : allDikuai.values()) {
                JPanel card = createDikuaiCard(dikuai);
                cardsPanel.add(card);
                cardsPanel.add(Box.createRigidArea(new Dimension(0, 15)));
            }
        }
        
        cardsPanel.revalidate();
        cardsPanel.repaint();
    }
 
    private JPanel createEmptyStatePanel() {
        JPanel emptyPanel = new JPanel();
        emptyPanel.setLayout(new BorderLayout());
        emptyPanel.setBackground(BACKGROUND_COLOR);
        emptyPanel.setBorder(BorderFactory.createEmptyBorder(50, 0, 0, 0));
        
        JLabel emptyLabel = new JLabel("暂无地块数据", JLabel.CENTER);
        emptyLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        emptyLabel.setForeground(LIGHT_TEXT);
        
        emptyPanel.add(emptyLabel, BorderLayout.CENTER);
        
        return emptyPanel;
    }
 
    private JPanel createDikuaiCard(Dikuai dikuai) {
        JPanel card = new JPanel();
        card.setLayout(new BorderLayout());
        card.setBackground(CARD_BACKGROUND);
        card.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(CARD_SHADOW, 1),
            BorderFactory.createEmptyBorder(15, 15, 15, 15)
        ));
    card.setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
 
        // 卡片头部:地块名称和删除按钮
        JPanel headerPanel = new JPanel(new BorderLayout());
        headerPanel.setBackground(CARD_BACKGROUND);
        
        // 地块名称
        String landName = dikuai.getLandName();
        if (landName == null || landName.equals("-1")) {
            landName = "未知地块";
        }
        JLabel nameLabel = new JLabel(landName);
        nameLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        nameLabel.setForeground(TEXT_COLOR);
 
        headerPanel.add(nameLabel, BorderLayout.WEST);
 
        JButton workToggleBtn = createWorkToggleButton(dikuai);
        headerPanel.add(workToggleBtn, BorderLayout.EAST);
        
        card.add(headerPanel, BorderLayout.NORTH);
        
        // 卡片内容:地块信息
        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
        contentPanel.setBackground(CARD_BACKGROUND);
        contentPanel.setBorder(BorderFactory.createEmptyBorder(15, 0, 0, 0));
        
        // 地块编号
        contentPanel.add(createCardInfoItem("地块编号:", getDisplayValue(dikuai.getLandNumber(), "未知")));
    contentPanel.add(Box.createRigidArea(new Dimension(0, 20)));
        
        // 添加时间
        contentPanel.add(createCardInfoItem("添加时间:", getDisplayValue(dikuai.getCreateTime(), "未知")));
    contentPanel.add(Box.createRigidArea(new Dimension(0, 20)));
        
        // 地块面积
        String landArea = dikuai.getLandArea();
        if (landArea != null && !landArea.equals("-1")) {
            landArea += "㎡";
        } else {
            landArea = "未知";
        }
        contentPanel.add(createCardInfoItem("地块面积:", landArea));
    contentPanel.add(Box.createRigidArea(new Dimension(0, 20)));
        
        // 返回点坐标(带修改按钮)
        contentPanel.add(createCardInfoItemWithButton("返回点坐标:", 
            getDisplayValue(dikuai.getReturnPointCoordinates(), "未设置"), 
            "修改", e -> editReturnPoint(dikuai)));
    contentPanel.add(Box.createRigidArea(new Dimension(0, 20)));
        
        // 地块边界坐标(带显示顶点按钮)
        JPanel boundaryPanel = createBoundaryInfoItem(dikuai,
            getTruncatedValue(dikuai.getBoundaryCoordinates(), 12, "未设置"));
        setInfoItemTooltip(boundaryPanel, dikuai.getBoundaryCoordinates());
        contentPanel.add(boundaryPanel);
    contentPanel.add(Box.createRigidArea(new Dimension(0, 20)));
        
        ObstacleSummary obstacleSummary = getObstacleSummaryFromCache(dikuai.getLandNumber());
        JPanel obstaclePanel = createCardInfoItemWithButton("障碍物:",
            obstacleSummary.buildDisplayValue(),
            "新增",
            e -> addNewObstacle(dikuai));
        setInfoItemTooltip(obstaclePanel, obstacleSummary.buildTooltip());
        contentPanel.add(obstaclePanel);
    contentPanel.add(Box.createRigidArea(new Dimension(0, 20)));
 
        // 路径坐标(带查看按钮)
        JPanel pathPanel = createCardInfoItemWithButton("路径坐标:", 
            getTruncatedValue(dikuai.getPlannedPath(), 12, "未设置"), 
            "复制", e -> copyCoordinatesAction("路径坐标", dikuai.getPlannedPath()));
        setInfoItemTooltip(pathPanel, dikuai.getPlannedPath());
        contentPanel.add(pathPanel);
    contentPanel.add(Box.createRigidArea(new Dimension(0, 20)));
 
        JPanel baseStationPanel = createCardInfoItemWithButton("基站坐标:",
            getTruncatedValue(dikuai.getBaseStationCoordinates(), 12, "未设置"),
            "复制", e -> copyCoordinatesAction("基站坐标", dikuai.getBaseStationCoordinates()));
        setInfoItemTooltip(baseStationPanel, dikuai.getBaseStationCoordinates());
        contentPanel.add(baseStationPanel);
    contentPanel.add(Box.createRigidArea(new Dimension(0, 20)));
 
        JPanel boundaryOriginalPanel = createCardInfoItemWithButton("边界原始坐标:",
            getTruncatedValue(dikuai.getBoundaryOriginalCoordinates(), 12, "未设置"),
            "复制", e -> copyCoordinatesAction("边界原始坐标", dikuai.getBoundaryOriginalCoordinates()));
        setInfoItemTooltip(boundaryOriginalPanel, dikuai.getBoundaryOriginalCoordinates());
        contentPanel.add(boundaryOriginalPanel);
        contentPanel.add(Box.createRigidArea(new Dimension(0, 20)));
 
        JPanel mowingPatternPanel = createCardInfoItemWithButton("割草模式:",
            getTruncatedValue(dikuai.getMowingPattern(), 12, "未设置"),
            "复制", e -> copyCoordinatesAction("割草模式", dikuai.getMowingPattern()));
        setInfoItemTooltip(mowingPatternPanel, dikuai.getMowingPattern());
        contentPanel.add(mowingPatternPanel);
        contentPanel.add(Box.createRigidArea(new Dimension(0, 20)));
 
        String mowingWidthValue = dikuai.getMowingWidth();
        String widthSource = null;
        if (mowingWidthValue != null && !"-1".equals(mowingWidthValue) && !mowingWidthValue.trim().isEmpty()) {
            widthSource = mowingWidthValue + "厘米";
        }
        String displayWidth = getTruncatedValue(widthSource, 12, "未设置");
        JPanel mowingWidthPanel = createCardInfoItemWithButton("割草宽度:",
            displayWidth,
            "编辑", e -> editMowingWidth(dikuai));
        setInfoItemTooltip(mowingWidthPanel, widthSource);
        contentPanel.add(mowingWidthPanel);
 
        card.add(contentPanel, BorderLayout.CENTER);
 
        JButton deleteBtn = createDeleteButton();
        deleteBtn.addActionListener(e -> deleteDikuai(dikuai));
 
        JPanel footerPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        footerPanel.setBackground(CARD_BACKGROUND);
        footerPanel.setBorder(BorderFactory.createEmptyBorder(15, 0, 0, 0));
        footerPanel.add(deleteBtn);
        card.add(footerPanel, BorderLayout.SOUTH);
 
        return card;
    }
 
    private JPanel createCardInfoItem(String label, String value) {
        JPanel itemPanel = new JPanel(new BorderLayout());
        itemPanel.setBackground(CARD_BACKGROUND);
        itemPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 20));
        
        JLabel labelComp = new JLabel(label);
        labelComp.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        labelComp.setForeground(LIGHT_TEXT);
        
        JLabel valueComp = new JLabel(value);
        valueComp.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        valueComp.setForeground(TEXT_COLOR);
        
        itemPanel.add(labelComp, BorderLayout.WEST);
        itemPanel.add(valueComp, BorderLayout.EAST);
        
        return itemPanel;
    }
 
    private JPanel createCardInfoItemWithButton(String label, String value, String buttonText, ActionListener listener) {
        JPanel itemPanel = new JPanel(new BorderLayout());
        itemPanel.setBackground(CARD_BACKGROUND);
        itemPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 20));
        
        JLabel labelComp = new JLabel(label);
        labelComp.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        labelComp.setForeground(LIGHT_TEXT);
        
        JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
        rightPanel.setBackground(CARD_BACKGROUND);
        
        JLabel valueComp = new JLabel(value);
        valueComp.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        valueComp.setForeground(TEXT_COLOR);
        
        JButton button = createSmallButton(buttonText);
        button.addActionListener(listener);
        
        rightPanel.add(valueComp);
        rightPanel.add(button);
        
        itemPanel.add(labelComp, BorderLayout.WEST);
        itemPanel.add(rightPanel, BorderLayout.CENTER);
        itemPanel.putClientProperty("valueLabel", valueComp);
        
        return itemPanel;
    }
 
        private JPanel createBoundaryInfoItem(Dikuai dikuai, String displayValue) {
            JPanel itemPanel = new JPanel(new BorderLayout());
            itemPanel.setBackground(CARD_BACKGROUND);
            int rowHeight = Math.max(36, BOUNDARY_TOGGLE_ICON_SIZE + 12);
            Dimension rowDimension = new Dimension(Integer.MAX_VALUE, rowHeight);
            itemPanel.setMaximumSize(rowDimension);
            itemPanel.setPreferredSize(rowDimension);
            itemPanel.setMinimumSize(new Dimension(0, 32));
 
            JLabel labelComp = new JLabel("地块边界:");
            labelComp.setFont(new Font("微软雅黑", Font.PLAIN, 14));
            labelComp.setForeground(LIGHT_TEXT);
 
            int verticalPadding = Math.max(0, (rowHeight - BOUNDARY_TOGGLE_ICON_SIZE) / 2);
            JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
            rightPanel.setBackground(CARD_BACKGROUND);
            rightPanel.setBorder(BorderFactory.createEmptyBorder(verticalPadding, 0, verticalPadding, 0));
 
            JLabel valueComp = new JLabel(displayValue);
            valueComp.setFont(new Font("微软雅黑", Font.PLAIN, 14));
            valueComp.setForeground(TEXT_COLOR);
 
            JButton toggleButton = createBoundaryToggleButton(dikuai);
 
            rightPanel.add(valueComp);
            rightPanel.add(toggleButton);
 
            itemPanel.add(labelComp, BorderLayout.WEST);
            itemPanel.add(rightPanel, BorderLayout.CENTER);
            itemPanel.putClientProperty("valueLabel", valueComp);
 
            return itemPanel;
        }
 
        private JButton createBoundaryToggleButton(Dikuai dikuai) {
            JButton button = new JButton();
            button.setContentAreaFilled(false);
            button.setBorder(BorderFactory.createEmptyBorder());
            button.setFocusPainted(false);
            button.setOpaque(false);
            button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            button.setMargin(new Insets(0, 0, 0, 0));
            button.setIconTextGap(0);
            button.setPreferredSize(new Dimension(56, 56));
 
            String landNumber = dikuai.getLandNumber();
            boolean isVisible = boundaryPointVisibility.getOrDefault(landNumber, false);
            updateBoundaryToggleButton(button, isVisible);
 
            button.addActionListener(e -> toggleBoundaryPointVisualization(dikuai, button));
 
            return button;
        }
 
        private void updateBoundaryToggleButton(JButton button, boolean active) {
            ensureBoundaryToggleIconsLoaded();
            ImageIcon icon = active ? boundaryVisibleIcon : boundaryHiddenIcon;
            if (icon != null) {
                button.setIcon(icon);
                button.setText(null);
                button.setContentAreaFilled(false);
                button.setOpaque(false);
            } else {
                button.setIcon(null);
                button.setText(active ? "关闭" : "开启");
                button.setContentAreaFilled(true);
                button.setBackground(PRIMARY_COLOR);
                button.setForeground(WHITE);
                button.setOpaque(true);
            }
            button.setToolTipText(active ? "隐藏边界点序号" : "显示边界点序号");
        }
 
        private void ensureBoundaryToggleIconsLoaded() {
            if (boundaryVisibleIcon == null) {
                boundaryVisibleIcon = loadIcon("image/open.png", BOUNDARY_TOGGLE_ICON_SIZE, BOUNDARY_TOGGLE_ICON_SIZE);
            }
            if (boundaryHiddenIcon == null) {
                boundaryHiddenIcon = loadIcon("image/close.png", BOUNDARY_TOGGLE_ICON_SIZE, BOUNDARY_TOGGLE_ICON_SIZE);
            }
        }
 
        private void toggleBoundaryPointVisualization(Dikuai dikuai, JButton button) {
            if (dikuai == null) {
                return;
            }
 
            String landNumber = dikuai.getLandNumber();
            if (landNumber == null || landNumber.trim().isEmpty()) {
                return;
            }
 
            boolean currentState = boundaryPointVisibility.getOrDefault(landNumber, false);
            boolean desiredState = !currentState;
 
            if (desiredState) {
                String boundary = dikuai.getBoundaryCoordinates();
                if (boundary == null || boundary.trim().isEmpty() || "-1".equals(boundary.trim())) {
                    JOptionPane.showMessageDialog(this, "当前地块暂无边界数据", "提示", JOptionPane.INFORMATION_MESSAGE);
                    desiredState = false;
                }
            }
 
            boundaryPointVisibility.put(landNumber, desiredState);
            updateBoundaryToggleButton(button, desiredState);
 
            Shouye shouye = Shouye.getInstance();
            if (shouye != null) {
                MapRenderer renderer = shouye.getMapRenderer();
                if (renderer != null) {
                    boolean isCurrent = currentWorkLandNumber != null && currentWorkLandNumber.equals(landNumber);
                    if (isCurrent) {
                        renderer.setBoundaryPointsVisible(desiredState);
                    }
                }
            }
        }
 
    private void setInfoItemTooltip(JPanel itemPanel, String rawValue) {
        if (itemPanel == null || rawValue == null || rawValue.trim().isEmpty() || "-1".equals(rawValue.trim())) {
            return;
        }
        Object valueComp = itemPanel.getClientProperty("valueLabel");
        if (valueComp instanceof JLabel) {
            ((JLabel) valueComp).setToolTipText(rawValue);
        }
    }
 
    private String getDisplayValue(String value, String defaultValue) {
        if (value == null || value.equals("-1") || value.trim().isEmpty()) {
            return defaultValue;
        }
        return value;
    }
 
    private String getTruncatedValue(String value, int maxLength, String defaultValue) {
        if (value == null || value.equals("-1") || value.trim().isEmpty()) {
            return defaultValue;
        }
        
        if (value.length() > maxLength) {
            return value.substring(0, maxLength) + "...";
        }
        return value;
    }
 
    private JButton createSmallButton(String text) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        button.setBackground(PRIMARY_COLOR);
        button.setForeground(WHITE);
        button.setBorder(BorderFactory.createEmptyBorder(2, 10, 2, 10));
        button.setMargin(new Insets(0, 0, 0, 0));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
 
        // 悬停效果
        button.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent e) {
                button.setBackground(PRIMARY_DARK);
            }
            public void mouseExited(MouseEvent e) {
                button.setBackground(PRIMARY_COLOR);
            }
        });
 
        return button;
    }
 
    private JButton createActionButton(String text, Color color) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        button.setBackground(color);
        button.setForeground(WHITE);
        button.setBorder(BorderFactory.createEmptyBorder(8, 16, 8, 16));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
 
        // 悬停效果
        button.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent e) {
                if (color == RED_COLOR) {
                    button.setBackground(RED_DARK);
                } else {
                    button.setBackground(PRIMARY_DARK);
                }
            }
            public void mouseExited(MouseEvent e) {
                if (color == RED_COLOR) {
                    button.setBackground(RED_COLOR);
                } else {
                    button.setBackground(PRIMARY_COLOR);
                }
            }
        });
 
        return button;
    }
 
    private JButton createDeleteButton() {
        JButton button = new JButton("删除");
        button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        button.setBackground(RED_COLOR);
        button.setForeground(WHITE);
        button.setBorder(BorderFactory.createEmptyBorder(6, 12, 6, 12));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
 
        ImageIcon deleteIcon = loadIcon("image/delete.png", 16, 16);
        if (deleteIcon != null) {
            button.setIcon(deleteIcon);
            button.setIconTextGap(6);
        }
 
        // 悬停效果
        button.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent e) {
                button.setBackground(RED_DARK);
            }
            public void mouseExited(MouseEvent e) {
                button.setBackground(RED_COLOR);
            }
        });
 
        return button;
    }
 
    private JButton createWorkToggleButton(Dikuai dikuai) {
        JButton button = new JButton();
        button.setContentAreaFilled(false);
        button.setBorder(BorderFactory.createEmptyBorder());
        button.setFocusPainted(false);
        button.setOpaque(false);
        button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        button.setPreferredSize(new Dimension(56, 56));
 
        boolean isCurrent = dikuai.getLandNumber() != null && dikuai.getLandNumber().equals(currentWorkLandNumber);
        updateWorkToggleButton(button, isCurrent);
 
        button.addActionListener(e -> handleWorkToggle(dikuai));
 
        return button;
    }
 
    private void updateWorkToggleButton(JButton button, boolean isCurrent) {
        ensureWorkIconsLoaded();
        ImageIcon icon = isCurrent ? workSelectedIcon : workUnselectedIcon;
        if (icon != null) {
            button.setIcon(icon);
            button.setText(null);
        } else {
            button.setText(isCurrent ? "当前地块" : "设为当前");
        }
        button.setToolTipText(isCurrent ? "取消当前作业地块" : "设为当前作业地块");
    }
 
    private void ensureWorkIconsLoaded() {
        if (workSelectedIcon == null) {
            workSelectedIcon = loadIcon("image/open.png", 48, 48);
        }
        if (workUnselectedIcon == null) {
            workUnselectedIcon = loadIcon("image/close.png", 48, 48);
        }
    }
 
    private void handleWorkToggle(Dikuai dikuai) {
        String landNumber = dikuai.getLandNumber();
        if (landNumber == null || landNumber.trim().isEmpty()) {
            return;
        }
        boolean isCurrent = landNumber.equals(currentWorkLandNumber);
        if (isCurrent) {
            setCurrentWorkLand(null, null);
        } else {
            setCurrentWorkLand(landNumber, dikuai.getLandName());
        }
        loadDikuaiData();
    }
 
    private void setCurrentWorklandIfNeeded(Dikuai dikuai) {
        if (dikuai == null) {
            return;
        }
        String landNumber = dikuai.getLandNumber();
        if (landNumber == null || landNumber.trim().isEmpty()) {
            return;
        }
        setCurrentWorkLand(landNumber, dikuai.getLandName());
    }
 
    public static void setCurrentWorkLand(String landNumber, String landName) {
        currentWorkLandNumber = landNumber;
        Dikuai dikuai = null;
        if (landNumber != null) {
            dikuai = Dikuai.getDikuai(landNumber);
            if (dikuai != null && (landName == null || "-1".equals(landName) || landName.trim().isEmpty())) {
                landName = dikuai.getLandName();
            }
        }
        if (landName != null && ("-1".equals(landName) || landName.trim().isEmpty())) {
            landName = "未知地块";
        }
 
        Shouye shouye = Shouye.getInstance();
        if (shouye != null) {
            if (landNumber == null) {
                shouye.updateCurrentAreaName(null);
            } else {
                shouye.updateCurrentAreaName(landName);
            }
            MapRenderer renderer = shouye.getMapRenderer();
            if (renderer != null) {
                String boundary = (dikuai != null) ? dikuai.getBoundaryCoordinates() : null;
                String plannedPath = (dikuai != null) ? dikuai.getPlannedPath() : null;
                String obstacles = (dikuai != null) ? dikuai.getObstacleCoordinates() : null;
                List<Obstacledge.Obstacle> configuredObstacles = (landNumber != null) ? loadObstaclesFromConfig(landNumber) : null;
                renderer.setCurrentBoundary(boundary, landNumber, landNumber == null ? null : landName);
                renderer.setCurrentPlannedPath(plannedPath);
                if (configuredObstacles != null) {
                    renderer.setCurrentObstacles(configuredObstacles, landNumber);
                } else {
                    renderer.setCurrentObstacles(obstacles, landNumber);
                }
                boolean showBoundaryPoints = landNumber != null && boundaryPointVisibility.getOrDefault(landNumber, false);
                renderer.setBoundaryPointsVisible(showBoundaryPoints);
            }
        }
    }
 
    public static String getCurrentWorkLandNumber() {
        return currentWorkLandNumber;
    }
 
    private ImageIcon loadIcon(String path, int width, int height) {
        try {
            ImageIcon rawIcon = new ImageIcon(path);
            if (rawIcon.getIconWidth() <= 0 || rawIcon.getIconHeight() <= 0) {
                return null;
            }
            Image scaled = rawIcon.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH);
            return new ImageIcon(scaled);
        } catch (Exception ex) {
            System.err.println("无法加载图标: " + path + " - " + ex.getMessage());
            return null;
        }
    }
 
    private void setupEventHandlers() {
        // 新增地块按钮
        addLandBtn.addActionListener(e -> {
            Window ownerWindow = SwingUtilities.getWindowAncestor(this);
            Window addDialogOwner = ownerWindow != null ? ownerWindow.getOwner() : null;
            Component parentComponent = addDialogOwner instanceof Component ? (Component) addDialogOwner : ownerWindow;
            if (ownerWindow instanceof JDialog) {
                ownerWindow.dispose();
            }
            Coordinate.coordinates.clear();
            latestInstance = null;
            SwingUtilities.invokeLater(() -> AddDikuai.showAddDikuaiDialog(parentComponent));
        });
    }
 
    private void editReturnPoint(Dikuai dikuai) {
        FanhuiDialog fd = new FanhuiDialog(SwingUtilities.getWindowAncestor(this), dikuai);
        fd.setVisible(true);
        // 如果对话框已更新数据,刷新显示
        if (fd.isUpdated()) {
            loadDikuaiData();
        }
    }
 
    private void addNewObstacle(Dikuai dikuai) {
        if (dikuai == null) {
            JOptionPane.showMessageDialog(this, "未找到当前地块,无法新增障碍物", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        Window windowAncestor = SwingUtilities.getWindowAncestor(this);
        if (windowAncestor instanceof JDialog) {
            windowAncestor.dispose();
        }
        Component parent = windowAncestor != null ? windowAncestor.getOwner() instanceof Component ? (Component) windowAncestor.getOwner() : windowAncestor : null;
        List<String> existingObstacleNames = loadObstacleNamesForLand(dikuai.getLandNumber());
        addzhangaiwu.showDialog(parent, dikuai, existingObstacleNames);
        loadDikuaiData();
    }
 
    private Map<String, ObstacleSummary> loadObstacleSummaries() {
        Map<String, ObstacleSummary> summaries = new HashMap<>();
        try {
            File configFile = new File("Obstacledge.properties");
            if (!configFile.exists()) {
                return summaries;
            }
            Obstacledge.ConfigManager manager = new Obstacledge.ConfigManager();
            if (!manager.loadFromFile(configFile.getAbsolutePath())) {
                return summaries;
            }
            for (Obstacledge.Plot plot : manager.getPlots()) {
                if (plot == null) {
                    continue;
                }
                String plotId = plot.getPlotId();
                if (plotId == null || plotId.trim().isEmpty()) {
                    continue;
                }
                List<String> names = new ArrayList<>();
                for (Obstacledge.Obstacle obstacle : plot.getObstacles()) {
                    if (obstacle == null) {
                        continue;
                    }
                    String name = obstacle.getObstacleName();
                    if (name == null) {
                        continue;
                    }
                    String trimmed = name.trim();
                    if (!trimmed.isEmpty()) {
                        names.add(trimmed);
                    }
                }
                summaries.put(plotId.trim(), ObstacleSummary.of(names));
            }
        } catch (Exception ex) {
            System.err.println("读取障碍物配置失败: " + ex.getMessage());
        }
        return summaries;
    }
 
    private static List<Obstacledge.Obstacle> loadObstaclesFromConfig(String landNumber) {
        if (landNumber == null || landNumber.trim().isEmpty()) {
            return Collections.emptyList();
        }
        try {
            File configFile = new File("Obstacledge.properties");
            if (!configFile.exists()) {
                return null;
            }
            Obstacledge.ConfigManager manager = new Obstacledge.ConfigManager();
            if (!manager.loadFromFile(configFile.getAbsolutePath())) {
                return null;
            }
            Obstacledge.Plot plot = manager.getPlotById(landNumber.trim());
            if (plot == null) {
                return Collections.emptyList();
            }
            List<Obstacledge.Obstacle> obstacles = plot.getObstacles();
            if (obstacles == null || obstacles.isEmpty()) {
                return Collections.emptyList();
            }
            return new ArrayList<>(obstacles);
        } catch (Exception ex) {
            System.err.println("读取障碍物配置失败: " + ex.getMessage());
            return null;
        }
    }
 
    private ObstacleSummary getObstacleSummaryFromCache(String landNumber) {
        if (landNumber == null || landNumber.trim().isEmpty()) {
            return ObstacleSummary.empty();
        }
        if (obstacleSummaryCache == null || obstacleSummaryCache.isEmpty()) {
            return ObstacleSummary.empty();
        }
        ObstacleSummary summary = obstacleSummaryCache.get(landNumber.trim());
        return summary != null ? summary : ObstacleSummary.empty();
    }
 
    private List<String> loadObstacleNamesForLand(String landNumber) {
        List<String> names = new ArrayList<>();
        if (landNumber == null || landNumber.trim().isEmpty()) {
            return names;
        }
        ObstacleSummary cached = getObstacleSummaryFromCache(landNumber);
        if (!cached.isEmpty()) {
            names.addAll(cached.copyNames());
            return names;
        }
        Map<String, ObstacleSummary> latest = loadObstacleSummaries();
        if (!latest.isEmpty()) {
            obstacleSummaryCache = latest;
        }
        ObstacleSummary refreshed = getObstacleSummaryFromCache(landNumber);
        if (!refreshed.isEmpty()) {
            names.addAll(refreshed.copyNames());
        }
        return names;
    }
 
    private void editMowingWidth(Dikuai dikuai) {
        String currentWidth = dikuai.getMowingWidth();
        if (currentWidth == null || "-1".equals(currentWidth)) {
            currentWidth = "";
        }
        String input = JOptionPane.showInputDialog(this, "请输入割草宽度(单位: 厘米)", currentWidth);
        if (input == null) {
            return;
        }
        String trimmed = input.trim();
        if (trimmed.isEmpty()) {
            JOptionPane.showMessageDialog(this, "割草宽度不能为空", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        String sanitized = trimmed;
        if (sanitized.endsWith("厘米")) {
            sanitized = sanitized.substring(0, sanitized.length() - 2).trim();
        }
        if (sanitized.endsWith("cm") || sanitized.endsWith("CM")) {
            sanitized = sanitized.substring(0, sanitized.length() - 2).trim();
        }
        double widthValue;
        try {
            widthValue = Double.parseDouble(sanitized);
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "请输入有效的数字", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (widthValue <= 0) {
            JOptionPane.showMessageDialog(this, "割草宽度必须大于0", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        String normalized = BigDecimal.valueOf(widthValue).stripTrailingZeros().toPlainString();
        if (!Dikuai.updateField(dikuai.getLandNumber(), "mowingWidth", normalized)) {
            JOptionPane.showMessageDialog(this, "无法更新割草宽度", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        Dikuai.updateField(dikuai.getLandNumber(), "updateTime", getCurrentTime());
        Dikuai.saveToProperties();
        loadDikuaiData();
        JOptionPane.showMessageDialog(this, "割草宽度已更新", "成功", JOptionPane.INFORMATION_MESSAGE);
    }
 
    private void deleteDikuai(Dikuai dikuai) {
        int result = JOptionPane.showConfirmDialog(this, 
                "确定要删除地块 \"" + dikuai.getLandName() + "\" 吗?此操作无法撤销。", 
                "确认删除", 
                JOptionPane.YES_NO_OPTION, 
                JOptionPane.WARNING_MESSAGE);
 
        if (result == JOptionPane.YES_OPTION) {
            // 从内存中移除并同步到文件
            if (Dikuai.removeDikuai(dikuai.getLandNumber())) {
                if (dikuai.getLandNumber() != null && dikuai.getLandNumber().equals(currentWorkLandNumber)) {
                    setCurrentWorkLand(null, null);
                }
                boundaryPointVisibility.remove(dikuai.getLandNumber());
                Dikuai.saveToProperties();
                loadDikuaiData();
                JOptionPane.showMessageDialog(this, "地块删除成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "未找到要删除的地块。", "提示", JOptionPane.WARNING_MESSAGE);
            }
        }
    }
 
    private String getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }
 
    /**
     * 获取地块管理面板实例
     * @param landNumber 地块编号
     */
    public static Dikuaiguanli createDikuaiManagementPanel(String landNumber) {
        // 确保地块数据已初始化
        Dikuai.initFromProperties();
 
        return new Dikuaiguanli(landNumber);
    }
 
    /**
     * 显示地块管理对话框(向后兼容)
     * @param parent 父组件
     * @param landNumber 地块编号
     */
    public static void showDikuaiManagement(Component parent, String landNumber) {
        // 确保地块数据已初始化
        Dikuai.initFromProperties();
 
        JDialog dialog = new JDialog();
        dialog.setTitle("地块管理");
        dialog.setModal(true);
        dialog.setSize(400, 800);
        dialog.setLocationRelativeTo(parent);
        dialog.setResizable(false);
 
        Dikuaiguanli managementPanel = new Dikuaiguanli(landNumber);
        dialog.add(managementPanel);
        dialog.setVisible(true);
    }
 
    public static void notifyExternalCreation(String landNumber) {
        if (latestInstance == null) {
            return;
        }
        SwingUtilities.invokeLater(() -> latestInstance.loadDikuaiData());
    }
 
    public static void updateBoundaryPointVisibility(String landNumber, boolean visible) {
        if (landNumber == null || landNumber.trim().isEmpty()) {
            return;
        }
        boundaryPointVisibility.put(landNumber, visible);
    }
 
    private static final class ObstacleSummary {
        private static final ObstacleSummary EMPTY = new ObstacleSummary(Collections.emptyList());
        private final List<String> names;
 
        private ObstacleSummary(List<String> names) {
            this.names = names;
        }
 
        static ObstacleSummary of(List<String> originalNames) {
            if (originalNames == null || originalNames.isEmpty()) {
                return empty();
            }
            List<String> cleaned = new ArrayList<>();
            for (String name : originalNames) {
                if (name == null) {
                    continue;
                }
                String trimmed = name.trim();
                if (trimmed.isEmpty()) {
                    continue;
                }
                boolean duplicated = false;
                for (String existing : cleaned) {
                    if (existing.equalsIgnoreCase(trimmed)) {
                        duplicated = true;
                        break;
                    }
                }
                if (!duplicated) {
                    cleaned.add(trimmed);
                }
            }
            if (cleaned.isEmpty()) {
                return empty();
            }
            cleaned.sort(String::compareToIgnoreCase);
            return new ObstacleSummary(Collections.unmodifiableList(cleaned));
        }
 
        static ObstacleSummary empty() {
            return EMPTY;
        }
 
        boolean isEmpty() {
            return names.isEmpty();
        }
 
        int count() {
            return names.size();
        }
 
        String buildDisplayValue() {
            return count() > 0 ? String.format("障碍物%d个", count()) : "暂无障碍物";
        }
 
        String buildTooltip() {
            return count() > 0 ? String.join(",", names) : "暂无障碍物";
        }
 
        List<String> copyNames() {
            return new ArrayList<>(names);
        }
    }
}