张世豪
4 天以前 32c98d4855b6178554c787103dc956d161e152b3
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
package lujing;
 
import javax.swing.*;
import javax.swing.SwingUtilities;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
 
import dikuai.Dikuai;
import lujing.Lunjingguihua;
import lujing.ObstaclePathPlanner;
import lujing.Qufenxingzhuang;
import lujing.AoxinglujingNoObstacle;
import lujing.YixinglujingNoObstacle;
import lujing.AoxinglujingHaveObstacel;
import lujing.YixinglujingHaveObstacel;
import org.locationtech.jts.geom.Coordinate;
import gecaoji.Device;
import java.util.Locale;
 
/**
 * 生成割草路径页面
 * 独立的对话框类,用于生成和编辑割草路径
 */
public class MowingPathGenerationPage extends JDialog {
    private static final long serialVersionUID = 1L;
    
    // 尺寸常量
    private static final int SCREEN_WIDTH = 400;
    private static final int SCREEN_HEIGHT = 800;
    
    // 颜色常量
    private static final Color PRIMARY_COLOR = new Color(46, 139, 87);
    private static final Color PRIMARY_DARK = new Color(30, 107, 69);
    private static final Color TEXT_COLOR = new Color(51, 51, 51);
    private static final Color WHITE = Color.WHITE;
    private static final Color BORDER_COLOR = new Color(200, 200, 200);
    private static final Color BACKGROUND_COLOR = new Color(250, 250, 250);
    
    // 数据保存回调接口
    public interface PathSaveCallback {
        boolean saveBaseStationCoordinates(Dikuai dikuai, String value);
        boolean saveBoundaryCoordinates(Dikuai dikuai, String value);
        boolean saveObstacleCoordinates(Dikuai dikuai, String baseStationValue, String obstacleValue);
        boolean saveMowingWidth(Dikuai dikuai, String value);
        boolean savePlannedPath(Dikuai dikuai, String value);
    }
    
    private final Dikuai dikuai;
    private final PathSaveCallback saveCallback;
    
    // UI组件
    private JTextField baseStationField;
    private JTextArea boundaryArea;
    private JTextArea obstacleArea;
    private JTextField widthField;
    private JTextArea pathArea;
    
    /**
     * 构造函数
     * @param owner 父窗口
     * @param dikuai 地块对象
     * @param baseStationValue 基站坐标
     * @param boundaryValue 地块边界
     * @param obstacleValue 障碍物坐标
     * @param widthValue 割草宽度
     * @param modeValue 割草模式
     * @param initialGeneratedPath 初始生成的路径
     * @param saveCallback 保存回调接口
     */
    public MowingPathGenerationPage(Window owner, 
                                    Dikuai dikuai,
                                    String baseStationValue,
                                    String boundaryValue,
                                    String obstacleValue,
                                    String widthValue,
                                    String modeValue,
                                    String initialGeneratedPath,
                                    PathSaveCallback saveCallback) {
        super(owner, "路径规划页面", Dialog.ModalityType.APPLICATION_MODAL);
        this.dikuai = dikuai;
        this.saveCallback = saveCallback;
        
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(new BorderLayout());
        getContentPane().setBackground(BACKGROUND_COLOR);
        
        initializeUI(baseStationValue, boundaryValue, obstacleValue, 
                     widthValue, modeValue, initialGeneratedPath);
        
        pack();
        setSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
        setLocationRelativeTo(owner);
    }
    
    /**
     * 初始化UI
     */
    private void initializeUI(String baseStationValue, String boundaryValue, 
                              String obstacleValue, String widthValue, 
                              String modeValue, String initialGeneratedPath) {
        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
        contentPanel.setBackground(BACKGROUND_COLOR);
        contentPanel.setBorder(BorderFactory.createEmptyBorder(12, 16, 12, 16));
        
        // 标题
        String landName = getDisplayValue(dikuai.getLandName(), "未知地块");
        String landNumber = getDisplayValue(dikuai.getLandNumber(), "未知编号");
        JLabel headerLabel = new JLabel(landName + " / " + landNumber);
        headerLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        headerLabel.setForeground(TEXT_COLOR);
        headerLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        contentPanel.add(headerLabel);
        contentPanel.add(Box.createVerticalStrut(12));
        
        // 基站坐标
        baseStationField = createInfoTextField(baseStationValue != null ? baseStationValue : "", true);
        contentPanel.add(createTextFieldSection("基站坐标", baseStationField));
        
        // 地块边界
        boundaryArea = createInfoTextArea(boundaryValue != null ? boundaryValue : "", true, 6);
        contentPanel.add(createTextAreaSection("地块边界", boundaryArea));
        
        // 障碍物坐标
        obstacleArea = createInfoTextArea(obstacleValue != null ? obstacleValue : "", true, 6);
        contentPanel.add(createTextAreaSection("障碍物坐标", obstacleArea));
        
        // 割草宽度
        widthField = createInfoTextField(widthValue != null ? widthValue : "", true);
        contentPanel.add(createTextFieldSection("割草宽度 (厘米)", widthField));
        
        // 割草安全距离(只读显示)
        String displaySafetyDistance = "未设置";
        Device device = Device.getActiveDevice();
        if (device != null) {
            String safetyDistanceValue = device.getMowingSafetyDistance();
            if (safetyDistanceValue != null && !"-1".equals(safetyDistanceValue) && !safetyDistanceValue.trim().isEmpty()) {
                try {
                    double distanceMeters = Double.parseDouble(safetyDistanceValue.trim());
                    // 如果值大于100,认为是厘米,需要转换为米
                    if (distanceMeters > 100) {
                        distanceMeters = distanceMeters / 100.0;
                    }
                    displaySafetyDistance = String.format("%.2f米", distanceMeters);
                } catch (NumberFormatException e) {
                    displaySafetyDistance = "未设置";
                }
            }
        }
        contentPanel.add(createInfoValueSection("割草安全距离", displaySafetyDistance));
        
        // 割草模式(只读显示)
        contentPanel.add(createInfoValueSection("割草模式", formatMowingPatternForDialog(modeValue)));
        
        // 割草路径坐标
        String existingPath = prepareCoordinateForEditor(dikuai.getPlannedPath());
        String pathSeed = initialGeneratedPath != null ? initialGeneratedPath : existingPath;
        pathArea = createInfoTextArea(pathSeed != null ? pathSeed : "", true, 10);
        contentPanel.add(createTextAreaSection("割草路径坐标", pathArea));
        
        JScrollPane dialogScrollPane = new JScrollPane(contentPanel);
        dialogScrollPane.setBorder(BorderFactory.createEmptyBorder());
        dialogScrollPane.getVerticalScrollBar().setUnitIncrement(16);
        add(dialogScrollPane, BorderLayout.CENTER);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 12, 12));
        buttonPanel.setBackground(BACKGROUND_COLOR);
        
        JButton generateBtn = createPrimaryFooterButton("生成割草路径");
        JButton previewBtn = createPrimaryFooterButton("预览");
        JButton saveBtn = createPrimaryFooterButton("保存路径");
        JButton cancelBtn = createPrimaryFooterButton("取消");
        
        generateBtn.addActionListener(e -> generatePath(modeValue));
        previewBtn.addActionListener(e -> previewPath());
        saveBtn.addActionListener(e -> savePath());
        cancelBtn.addActionListener(e -> dispose());
        
        buttonPanel.add(generateBtn);
        buttonPanel.add(previewBtn);
        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);
        add(buttonPanel, BorderLayout.SOUTH);
    }
    
    /**
     * 生成路径
     */
    private void generatePath(String modeValue) {
        String sanitizedWidth = sanitizeWidthString(widthField.getText());
        if (sanitizedWidth != null) {
            try {
                double widthCm = Double.parseDouble(sanitizedWidth);
                widthField.setText(formatWidthForStorage(widthCm));
                sanitizedWidth = formatWidthForStorage(widthCm);
            } catch (NumberFormatException ex) {
                widthField.setText(sanitizedWidth);
            }
        }
        
        String generated = attemptMowingPathPreview(
            boundaryArea.getText(),
            obstacleArea.getText(),
            sanitizedWidth,
            modeValue,
            this,
            true
        );
        
        if (generated != null) {
            pathArea.setText(generated);
            pathArea.setCaretPosition(0);
        }
    }
    
    /**
     * 预览路径
     */
    private void previewPath() {
        // 先保存当前路径到地块(临时保存,用于预览)
        String pathNormalized = normalizeCoordinateInput(pathArea.getText());
        if (!"-1".equals(pathNormalized)) {
            pathNormalized = pathNormalized
                .replace("\r\n", ";")
                .replace('\r', ';')
                .replace('\n', ';')
                .replaceAll(";+", ";")
                .replaceAll("\\s*;\\s*", ";")
                .trim();
            if (pathNormalized.isEmpty()) {
                pathNormalized = "-1";
            }
        }
        
        if ("-1".equals(pathNormalized)) {
            JOptionPane.showMessageDialog(this, "请先生成割草路径", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        // 临时保存路径到地块对象(不持久化)
        if (saveCallback != null) {
            saveCallback.savePlannedPath(dikuai, pathNormalized);
        }
        
        // 保存当前页面状态,用于返回时恢复
        String currentBaseStation = baseStationField.getText();
        String currentBoundary = boundaryArea.getText();
        String currentObstacle = obstacleArea.getText();
        String currentWidth = widthField.getText();
        String currentPath = pathArea.getText();
        
        // 获取地块信息
        String landNumber = dikuai.getLandNumber();
        String landName = dikuai.getLandName();
        
        // 处理边界坐标,确保变量是 effectively final
        String boundaryInput = normalizeCoordinateInput(boundaryArea.getText());
        final String boundary;
        if (!"-1".equals(boundaryInput)) {
            String processed = boundaryInput.replace("\r\n", ";")
                .replace('\r', ';')
                .replace('\n', ';')
                .replaceAll(";+", ";")
                .replaceAll("\\s*;\\s*", ";")
                .trim();
            if (processed.isEmpty()) {
                boundary = dikuai.getBoundaryCoordinates();
            } else {
                boundary = processed;
            }
        } else {
            boundary = dikuai.getBoundaryCoordinates();
        }
        
        // 处理障碍物坐标,确保变量是 effectively final
        String obstaclesInput = normalizeCoordinateInput(obstacleArea.getText());
        final String obstacles;
        if (!"-1".equals(obstaclesInput)) {
            String processed = obstaclesInput.replace("\r\n", " ")
                .replace('\r', ' ')
                .replace('\n', ' ')
                .replaceAll("\\s{2,}", " ")
                .trim();
            if (processed.isEmpty()) {
                obstacles = null;
            } else {
                obstacles = processed;
            }
        } else {
            obstacles = null;
        }
        
        // 保存最终值到 final 变量,以便在 lambda 中使用
        final String finalPathNormalized = pathNormalized;
        final String finalLandNumber = landNumber;
        final String finalLandName = landName;
        
        // 关闭路径规划页面
        setVisible(false);
        
        // 打开主页面并显示路径预览
        SwingUtilities.invokeLater(() -> {
            zhuye.Shouye shouye = zhuye.Shouye.getInstance();
            if (shouye != null) {
                // 显示路径预览,并设置返回回调
                shouye.startMowingPathPreview(
                    finalLandNumber,
                    finalLandName,
                    boundary,
                    obstacles,
                    finalPathNormalized,
                    () -> {
                        // 返回回调:重新打开路径规划页面
                        SwingUtilities.invokeLater(() -> {
                            setVisible(true);
                            // 恢复之前的状态
                            baseStationField.setText(currentBaseStation);
                            boundaryArea.setText(currentBoundary);
                            obstacleArea.setText(currentObstacle);
                            widthField.setText(currentWidth);
                            pathArea.setText(currentPath);
                        });
                    }
                );
            } else {
                // 如果主页面不存在,提示用户并重新显示路径规划页面
                JOptionPane.showMessageDialog(null, "无法打开主页面进行预览", "提示", JOptionPane.WARNING_MESSAGE);
                setVisible(true);
            }
        });
    }
    
    /**
     * 保存路径
     */
    private void savePath() {
        String baseStationNormalized = normalizeCoordinateInput(baseStationField.getText());
        String boundaryNormalized = normalizeCoordinateInput(boundaryArea.getText());
        if (!"-1".equals(boundaryNormalized)) {
            boundaryNormalized = boundaryNormalized
                .replace("\r\n", ";")
                .replace('\r', ';')
                .replace('\n', ';')
                .replaceAll(";+", ";")
                .replaceAll("\\s*;\\s*", ";")
                .trim();
            if (boundaryNormalized.isEmpty()) {
                boundaryNormalized = "-1";
            }
        }
        
        String obstacleNormalized = normalizeCoordinateInput(obstacleArea.getText());
        if (!"-1".equals(obstacleNormalized)) {
            obstacleNormalized = obstacleNormalized
                .replace("\r\n", " ")
                .replace('\r', ' ')
                .replace('\n', ' ')
                .replaceAll("\\s{2,}", " ")
                .trim();
            if (obstacleNormalized.isEmpty()) {
                obstacleNormalized = "-1";
            }
        }
        
        String rawWidthInput = widthField.getText() != null ? widthField.getText().trim() : "";
        String widthSanitized = sanitizeWidthString(widthField.getText());
        if (widthSanitized == null) {
            String message = rawWidthInput.isEmpty() ? "请先设置割草宽度(厘米)" : "割草宽度格式不正确";
            JOptionPane.showMessageDialog(this, message, "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        double widthCm;
        try {
            widthCm = Double.parseDouble(widthSanitized);
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "割草宽度格式不正确", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        if (widthCm <= 0) {
            JOptionPane.showMessageDialog(this, "割草宽度必须大于0", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        String widthNormalized = formatWidthForStorage(widthCm);
        widthField.setText(widthNormalized);
        
        String pathNormalized = normalizeCoordinateInput(pathArea.getText());
        if (!"-1".equals(pathNormalized)) {
            pathNormalized = pathNormalized
                .replace("\r\n", ";")
                .replace('\r', ';')
                .replace('\n', ';')
                .replaceAll(";+", ";")
                .replaceAll("\\s*;\\s*", ";")
                .trim();
            if (pathNormalized.isEmpty()) {
                pathNormalized = "-1";
            }
        }
        
        if ("-1".equals(pathNormalized)) {
            JOptionPane.showMessageDialog(this, "请先生成割草路径", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        // 调用回调保存数据
        if (saveCallback != null) {
            if (!saveCallback.saveBaseStationCoordinates(dikuai, baseStationNormalized)) {
                JOptionPane.showMessageDialog(this, "无法保存基站坐标", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            if (!saveCallback.saveBoundaryCoordinates(dikuai, boundaryNormalized)) {
                JOptionPane.showMessageDialog(this, "无法保存地块边界", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            if (!saveCallback.saveObstacleCoordinates(dikuai, baseStationNormalized, obstacleNormalized)) {
                JOptionPane.showMessageDialog(this, "无法保存障碍物坐标", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            if (!saveCallback.saveMowingWidth(dikuai, widthNormalized)) {
                JOptionPane.showMessageDialog(this, "无法保存割草宽度", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            if (!saveCallback.savePlannedPath(dikuai, pathNormalized)) {
                JOptionPane.showMessageDialog(this, "无法保存割草路径", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
        
        JOptionPane.showMessageDialog(this, "割草路径已保存", "成功", JOptionPane.INFORMATION_MESSAGE);
        dispose();
    }
    
    /**
     * 尝试生成路径预览
     */
    private String attemptMowingPathPreview(String boundaryInput, String obstacleInput,
                                            String widthCmInput, String modeInput,
                                            Component parentComponent, boolean showMessages) {
        String boundary = sanitizeValueOrNull(boundaryInput);
        if (boundary == null) {
            if (showMessages) {
                JOptionPane.showMessageDialog(parentComponent, "当前地块未设置边界坐标,无法生成路径", 
                    "提示", JOptionPane.WARNING_MESSAGE);
            }
            return null;
        }
        
        String rawWidth = widthCmInput != null ? widthCmInput.trim() : "";
        String widthStr = sanitizeWidthString(widthCmInput);
        if (widthStr == null) {
            if (showMessages) {
                String message = rawWidth.isEmpty() ? "请先设置割草宽度(厘米)" : "割草宽度格式不正确";
                JOptionPane.showMessageDialog(parentComponent, message, "提示", JOptionPane.WARNING_MESSAGE);
            }
            return null;
        }
        
        double widthCm;
        try {
            widthCm = Double.parseDouble(widthStr);
        } catch (NumberFormatException ex) {
            if (showMessages) {
                JOptionPane.showMessageDialog(parentComponent, "割草宽度格式不正确", 
                    "提示", JOptionPane.WARNING_MESSAGE);
            }
            return null;
        }
        
        if (widthCm <= 0) {
            if (showMessages) {
                JOptionPane.showMessageDialog(parentComponent, "割草宽度必须大于0", 
                    "提示", JOptionPane.WARNING_MESSAGE);
            }
            return null;
        }
        
        double widthMeters = widthCm / 100.0d;
        String plannerWidth = BigDecimal.valueOf(widthMeters)
            .setScale(3, RoundingMode.HALF_UP)
            .stripTrailingZeros()
            .toPlainString();
        
        // 检查原始输入是否有障碍物(在sanitize之前检查,避免丢失信息)
        String rawObstacleInput = obstacleInput != null ? obstacleInput.trim() : "";
        boolean hasObstacleInput = !rawObstacleInput.isEmpty() && !"-1".equals(rawObstacleInput);
        
        String obstacles = sanitizeValueOrNull(obstacleInput);
        if (obstacles != null) {
            obstacles = obstacles.replace("\r\n", " ").replace('\r', ' ').replace('\n', ' ');
        }
 
        // 获取安全距离
        String safetyMarginStr = getSafetyDistanceString();
        if (safetyMarginStr == null) {
            // 如果没有设置安全距离,使用默认值:割草宽度的一半 + 0.2米
            double defaultSafetyDistance = widthMeters / 2.0 + 0.2;
            safetyMarginStr = BigDecimal.valueOf(defaultSafetyDistance)
                .setScale(3, RoundingMode.HALF_UP)
                .stripTrailingZeros()
                .toPlainString();
        }
 
        String mode = normalizeExistingMowingPattern(modeInput);
        try {
            // 1. 首先判断地块类型(凸形还是异形)
            Qufenxingzhuang shapeJudger = new Qufenxingzhuang();
            int grassType = shapeJudger.judgeGrassType(boundary);
            // grassType: 0=无法判断, 1=凸形, 2=异形
            
            // 解析障碍物列表
            List<List<Coordinate>> obstacleList = Lunjingguihua.parseObstacles(obstacles);
            if (obstacleList == null) {
                obstacleList = new ArrayList<>();
            }
 
            // 判断是否有有效的障碍物:只有当解析成功且列表不为空时,才认为有障碍物
            boolean hasValidObstacles = !obstacleList.isEmpty();
            
            String generated = null;
            
            // 2. 根据地块类型和是否有障碍物,调用不同的路径生成类
            if (!hasValidObstacles) {
                // 无障碍物的情况
                if (grassType == 1) {
                    // 凸形地块,无障碍物 -> 调用 AoxinglujingNoObstacle
                    List<AoxinglujingNoObstacle.PathSegment> segments = 
                        AoxinglujingNoObstacle.planPath(boundary, plannerWidth, safetyMarginStr);
                    generated = formatAoxingPathSegments(segments);
                } else if (grassType == 2) {
                    // 异形地块,无障碍物 -> 调用 YixinglujingNoObstacle
                    // 注意:如果该类还没有实现,这里会抛出异常或返回null
                    try {
                        // 假设 YixinglujingNoObstacle 有类似的方法签名
                        // 如果类还没有实现,可能需要使用原来的方法作为后备
                        generated = YixinglujingNoObstacle.planPath(boundary, plannerWidth, safetyMarginStr);
                    } catch (Exception e) {
                        // 如果类还没有实现,使用原来的方法作为后备
                        if (showMessages) {
                            System.err.println("YixinglujingNoObstacle 尚未实现,使用默认方法: " + e.getMessage());
                        }
                        generated = Lunjingguihua.generatePathFromStrings(
                            boundary, obstacles != null ? obstacles : "", plannerWidth, safetyMarginStr, mode);
                    }
                } else {
                    // 无法判断地块类型,使用原来的方法作为后备
                    if (showMessages) {
                        JOptionPane.showMessageDialog(parentComponent, "无法判断地块类型,使用默认路径生成方法", 
                            "提示", JOptionPane.WARNING_MESSAGE);
                    }
                    generated = Lunjingguihua.generatePathFromStrings(
                        boundary, obstacles != null ? obstacles : "", plannerWidth, safetyMarginStr, mode);
                }
            } else {
                // 有障碍物的情况
                if (grassType == 1) {
                    // 凸形地块,有障碍物 -> 调用 AoxinglujingHaveObstacel
                    try {
                        // 假设 AoxinglujingHaveObstacel 有类似的方法签名
                        generated = AoxinglujingHaveObstacel.planPath(boundary, obstacles, plannerWidth, safetyMarginStr);
                    } catch (Exception e) {
                        // 如果类还没有实现,使用原来的方法作为后备
                        if (showMessages) {
                            System.err.println("AoxinglujingHaveObstacel 尚未实现,使用默认方法: " + e.getMessage());
                        }
                        List<Coordinate> polygon = Lunjingguihua.parseCoordinates(boundary);
                        if (polygon.size() < 4) {
                            if (showMessages) {
                                JOptionPane.showMessageDialog(parentComponent, "多边形坐标数量不足,至少需要三个点",
                                    "错误", JOptionPane.ERROR_MESSAGE);
                            }
                            return null;
                        }
                        double safetyDistance = Double.parseDouble(safetyMarginStr);
                        ObstaclePathPlanner pathPlanner = new ObstaclePathPlanner(
                            polygon, widthMeters, mode, obstacleList, safetyDistance);
                        List<Lunjingguihua.PathSegment> segments = pathPlanner.generate();
                        generated = Lunjingguihua.formatPathSegments(segments);
                    }
                } else if (grassType == 2) {
                    // 异形地块,有障碍物 -> 调用 YixinglujingHaveObstacel
                    try {
                        // 假设 YixinglujingHaveObstacel 有类似的方法签名
                        generated = YixinglujingHaveObstacel.planPath(boundary, obstacles, plannerWidth, safetyMarginStr);
                    } catch (Exception e) {
                        // 如果类还没有实现,使用原来的方法作为后备
                        if (showMessages) {
                            System.err.println("YixinglujingHaveObstacel 尚未实现,使用默认方法: " + e.getMessage());
                        }
                        List<Coordinate> polygon = Lunjingguihua.parseCoordinates(boundary);
                        if (polygon.size() < 4) {
                            if (showMessages) {
                                JOptionPane.showMessageDialog(parentComponent, "多边形坐标数量不足,至少需要三个点",
                                    "错误", JOptionPane.ERROR_MESSAGE);
                            }
                            return null;
                        }
                        double safetyDistance = Double.parseDouble(safetyMarginStr);
                        ObstaclePathPlanner pathPlanner = new ObstaclePathPlanner(
                            polygon, widthMeters, mode, obstacleList, safetyDistance);
                        List<Lunjingguihua.PathSegment> segments = pathPlanner.generate();
                        generated = Lunjingguihua.formatPathSegments(segments);
                    }
                } else {
                    // 无法判断地块类型,使用原来的方法作为后备
                    if (showMessages) {
                        JOptionPane.showMessageDialog(parentComponent, "无法判断地块类型,使用默认路径生成方法", 
                            "提示", JOptionPane.WARNING_MESSAGE);
                    }
                    List<Coordinate> polygon = Lunjingguihua.parseCoordinates(boundary);
                    if (polygon.size() < 4) {
                        if (showMessages) {
                            JOptionPane.showMessageDialog(parentComponent, "多边形坐标数量不足,至少需要三个点",
                                "错误", JOptionPane.ERROR_MESSAGE);
                        }
                        return null;
                    }
                    double safetyDistance = Double.parseDouble(safetyMarginStr);
                    ObstaclePathPlanner pathPlanner = new ObstaclePathPlanner(
                        polygon, widthMeters, mode, obstacleList, safetyDistance);
                    List<Lunjingguihua.PathSegment> segments = pathPlanner.generate();
                    generated = Lunjingguihua.formatPathSegments(segments);
                }
            }
            
            String trimmed = generated != null ? generated.trim() : "";
            if (trimmed.isEmpty()) {
                if (showMessages) {
                    JOptionPane.showMessageDialog(parentComponent, "未生成有效的割草路径,请检查地块数据", 
                        "提示", JOptionPane.INFORMATION_MESSAGE);
                }
                return null;
            }
            if (showMessages) {
                JOptionPane.showMessageDialog(parentComponent, "割草路径已生成", 
                    "成功", JOptionPane.INFORMATION_MESSAGE);
            }
            return trimmed;
        } catch (IllegalArgumentException ex) {
            if (showMessages) {
                JOptionPane.showMessageDialog(parentComponent, "生成割草路径失败: " + ex.getMessage(), 
                    "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            if (showMessages) {
                JOptionPane.showMessageDialog(parentComponent, "生成割草路径时发生异常: " + ex.getMessage(), 
                    "错误", JOptionPane.ERROR_MESSAGE);
            }
            ex.printStackTrace();
        }
        return null;
    }
    
    /**
     * 获取安全距离字符串(米)
     */
    private String getSafetyDistanceString() {
        Device device = Device.getActiveDevice();
        if (device != null) {
            String safetyDistanceValue = device.getMowingSafetyDistance();
            if (safetyDistanceValue != null && !"-1".equals(safetyDistanceValue) && !safetyDistanceValue.trim().isEmpty()) {
                try {
                    double distanceMeters = Double.parseDouble(safetyDistanceValue.trim());
                    // 如果值大于100,认为是厘米,需要转换为米
                    if (distanceMeters > 100) {
                        distanceMeters = distanceMeters / 100.0;
                    }
                    return BigDecimal.valueOf(distanceMeters)
                        .setScale(3, RoundingMode.HALF_UP)
                        .stripTrailingZeros()
                        .toPlainString();
                } catch (NumberFormatException e) {
                    // 解析失败,返回null,使用默认值
                }
            }
        }
        return null;
    }
    
    /**
     * 格式化 AoxinglujingNoObstacle.PathSegment 列表为坐标字符串
     */
    private String formatAoxingPathSegments(List<AoxinglujingNoObstacle.PathSegment> segments) {
        if (segments == null || segments.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        AoxinglujingNoObstacle.Point last = null;
        for (AoxinglujingNoObstacle.PathSegment segment : segments) {
            // 只添加割草工作段,跳过过渡段
            if (segment.isMowing) {
                // 如果起点与上一个终点不同,添加起点
                if (last == null || !equals2D(last, segment.start)) {
                    appendPoint(sb, segment.start);
                }
                // 添加终点
                appendPoint(sb, segment.end);
                last = segment.end;
            }
        }
        return sb.toString();
    }
    
    /**
     * 比较两个点是否相同(使用小的容差)
     */
    private boolean equals2D(AoxinglujingNoObstacle.Point p1, AoxinglujingNoObstacle.Point p2) {
        if (p1 == null || p2 == null) {
            return p1 == p2;
        }
        double tolerance = 1e-6;
        return Math.abs(p1.x - p2.x) < tolerance && Math.abs(p1.y - p2.y) < tolerance;
    }
    
    /**
     * 添加点到字符串构建器
     */
    private void appendPoint(StringBuilder sb, AoxinglujingNoObstacle.Point point) {
        if (sb.length() > 0) {
            sb.append(";");
        }
        sb.append(String.format(Locale.US, "%.6f,%.6f", point.x, point.y));
    }
    
    // ========== UI辅助方法 ==========
    
    private JTextArea createInfoTextArea(String text, boolean editable, int rows) {
        JTextArea area = new JTextArea(text);
        area.setEditable(editable);
        area.setLineWrap(true);
        area.setWrapStyleWord(true);
        area.setFont(new Font("微软雅黑", Font.PLAIN, 13));
        area.setRows(Math.max(rows, 2));
        area.setCaretPosition(0);
        area.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
        area.setBackground(editable ? WHITE : new Color(245, 245, 245));
        return area;
    }
    
    private JPanel createTextAreaSection(String title, JTextArea textArea) {
        JPanel section = new JPanel(new BorderLayout(0, 6));
        section.setBackground(BACKGROUND_COLOR);
        section.setAlignmentX(Component.LEFT_ALIGNMENT);
        
        // 创建标题面板,包含标题和复制图标
        JPanel titlePanel = new JPanel(new BorderLayout());
        titlePanel.setBackground(BACKGROUND_COLOR);
        titlePanel.setOpaque(false);
        
        JLabel titleLabel = new JLabel(title);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        titleLabel.setForeground(TEXT_COLOR);
        titlePanel.add(titleLabel, BorderLayout.WEST);
        
        // 创建复制按钮
        JButton copyButton = createCopyButton(title, () -> {
            String text = textArea.getText();
            if (text == null || text.trim().isEmpty()) {
                JOptionPane.showMessageDialog(this, title + " 未设置", "提示", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            copyToClipboard(text, title);
        });
        titlePanel.add(copyButton, BorderLayout.EAST);
        
        section.add(titlePanel, BorderLayout.NORTH);
        
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setBorder(BorderFactory.createLineBorder(BORDER_COLOR));
        scrollPane.getVerticalScrollBar().setUnitIncrement(12);
        section.add(scrollPane, BorderLayout.CENTER);
        
        section.setBorder(BorderFactory.createEmptyBorder(4, 0, 12, 0));
        return section;
    }
    
    private JTextField createInfoTextField(String text, boolean editable) {
        JTextField field = new JTextField(text);
        field.setEditable(editable);
        field.setFont(new Font("微软雅黑", Font.PLAIN, 13));
        field.setForeground(TEXT_COLOR);
        field.setBackground(editable ? WHITE : new Color(245, 245, 245));
        field.setCaretPosition(0);
        field.setBorder(BorderFactory.createEmptyBorder(4, 6, 4, 6));
        field.setFocusable(true);
        field.setOpaque(true);
        return field;
    }
    
    private JPanel createTextFieldSection(String title, JTextField textField) {
        JPanel section = new JPanel(new BorderLayout(0, 6));
        section.setBackground(BACKGROUND_COLOR);
        section.setAlignmentX(Component.LEFT_ALIGNMENT);
        
        // 创建标题面板,包含标题和复制图标
        JPanel titlePanel = new JPanel(new BorderLayout());
        titlePanel.setBackground(BACKGROUND_COLOR);
        titlePanel.setOpaque(false);
        
        JLabel titleLabel = new JLabel(title);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        titleLabel.setForeground(TEXT_COLOR);
        titlePanel.add(titleLabel, BorderLayout.WEST);
        
        // 创建复制按钮
        JButton copyButton = createCopyButton(title, () -> {
            String text = textField.getText();
            if (text == null || text.trim().isEmpty()) {
                JOptionPane.showMessageDialog(this, title + " 未设置", "提示", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            copyToClipboard(text, title);
        });
        titlePanel.add(copyButton, BorderLayout.EAST);
        
        section.add(titlePanel, BorderLayout.NORTH);
        
        JPanel fieldWrapper = new JPanel(new BorderLayout());
        fieldWrapper.setBackground(textField.isEditable() ? WHITE : new Color(245, 245, 245));
        fieldWrapper.setBorder(BorderFactory.createLineBorder(BORDER_COLOR));
        fieldWrapper.add(textField, BorderLayout.CENTER);
        section.add(fieldWrapper, BorderLayout.CENTER);
        
        section.setBorder(BorderFactory.createEmptyBorder(4, 0, 12, 0));
        return section;
    }
    
    private JPanel createInfoValueSection(String title, String value) {
        JPanel section = new JPanel();
        section.setLayout(new BoxLayout(section, BoxLayout.X_AXIS));
        section.setBackground(BACKGROUND_COLOR);
        section.setAlignmentX(Component.LEFT_ALIGNMENT);
        section.setBorder(BorderFactory.createEmptyBorder(4, 0, 4, 0));
        
        JLabel titleLabel = new JLabel(title + ":");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        titleLabel.setForeground(TEXT_COLOR);
        section.add(titleLabel);
        section.add(Box.createHorizontalStrut(8));
        
        JLabel valueLabel = new JLabel(value);
        valueLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        valueLabel.setForeground(TEXT_COLOR);
        section.add(valueLabel);
        section.add(Box.createHorizontalGlue());
        return section;
    }
    
    private JButton createPrimaryFooterButton(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(6, 12, 6, 12));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent e) {
                button.setBackground(PRIMARY_DARK);
            }
            
            public void mouseExited(java.awt.event.MouseEvent e) {
                button.setBackground(PRIMARY_COLOR);
            }
        });
        
        return button;
    }
    
    // ========== 数据处理辅助方法 ==========
    
    private String getDisplayValue(String value, String defaultValue) {
        if (value == null || value.equals("-1") || value.trim().isEmpty()) {
            return defaultValue;
        }
        return value;
    }
    
    private String prepareCoordinateForEditor(String value) {
        if (value == null) {
            return "";
        }
        String trimmed = value.trim();
        if (trimmed.isEmpty() || "-1".equals(trimmed)) {
            return "";
        }
        return trimmed;
    }
    
    private String normalizeCoordinateInput(String input) {
        if (input == null) {
            return "-1";
        }
        String trimmed = input.trim();
        return trimmed.isEmpty() ? "-1" : trimmed;
    }
    
    private String sanitizeValueOrNull(String input) {
        if (input == null) {
            return null;
        }
        String trimmed = input.trim();
        if (trimmed.isEmpty() || "-1".equals(trimmed)) {
            return null;
        }
        return trimmed;
    }
    
    private String sanitizeWidthString(String input) {
        if (input == null) {
            return null;
        }
        String trimmed = input.trim();
        if (trimmed.isEmpty() || "-1".equals(trimmed)) {
            return null;
        }
        String cleaned = trimmed.replaceAll("[^0-9.+-]", "");
        return cleaned.isEmpty() ? null : cleaned;
    }
    
    private String formatWidthForStorage(double widthCm) {
        return BigDecimal.valueOf(widthCm)
            .setScale(2, RoundingMode.HALF_UP)
            .stripTrailingZeros()
            .toPlainString();
    }
    
    private String formatMowingPatternForDialog(String patternValue) {
        String sanitized = sanitizeValueOrNull(patternValue);
        if (sanitized == null) {
            return "未设置";
        }
        String normalized = normalizeExistingMowingPattern(sanitized);
        if ("parallel".equals(normalized)) {
            return "平行模式 (parallel)";
        }
        if ("spiral".equals(normalized)) {
            return "螺旋模式 (spiral)";
        }
        return sanitized;
    }
    
    private String normalizeExistingMowingPattern(String patternValue) {
        if (patternValue == null) {
            return "parallel";
        }
        String trimmed = patternValue.trim().toLowerCase();
        if ("1".equals(trimmed) || "spiral".equals(trimmed)) {
            return "spiral";
        }
        return "parallel";
    }
    
    /**
     * 创建复制按钮
     */
    private JButton createCopyButton(String title, Runnable copyAction) {
        JButton copyButton = new JButton();
        Font titleFont = new Font("微软雅黑", Font.BOLD, 14);
        FontMetrics metrics = getFontMetrics(titleFont);
        int iconSize = metrics.getHeight(); // 使用标题字体高度作为图标大小
        
        // 加载复制图标
        ImageIcon copyIcon = null;
        ImageIcon successIcon = null;
        try {
            ImageIcon originalCopyIcon = new ImageIcon("image/fuzhi.png");
            Image scaledCopyImage = originalCopyIcon.getImage().getScaledInstance(iconSize, iconSize, Image.SCALE_SMOOTH);
            copyIcon = new ImageIcon(scaledCopyImage);
            
            // 加载成功图标
            ImageIcon originalSuccessIcon = new ImageIcon("image/fuzhisucc.png");
            Image scaledSuccessImage = originalSuccessIcon.getImage().getScaledInstance(iconSize, iconSize, Image.SCALE_SMOOTH);
            successIcon = new ImageIcon(scaledSuccessImage);
        } catch (Exception e) {
            // 如果图片加载失败,使用文本
            copyButton.setText("复制");
            copyButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));
            System.err.println("无法加载复制图标: " + e.getMessage());
        }
        
        final ImageIcon finalCopyIcon = copyIcon;
        final ImageIcon finalSuccessIcon = successIcon;
        
        copyButton.setIcon(finalCopyIcon);
        copyButton.setContentAreaFilled(false);
        copyButton.setBorder(null);
        copyButton.setFocusPainted(false);
        copyButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        copyButton.setToolTipText("复制" + title);
        
        // 添加点击事件
        copyButton.addActionListener(e -> {
            copyAction.run();
            // 复制成功后切换图标
            if (finalSuccessIcon != null) {
                copyButton.setIcon(finalSuccessIcon);
                // 1秒后恢复原图标
                Timer timer = new Timer(1000, evt -> {
                    copyButton.setIcon(finalCopyIcon);
                });
                timer.setRepeats(false);
                timer.start();
            }
        });
        
        return copyButton;
    }
    
    /**
     * 复制文本到剪贴板
     */
    private void copyToClipboard(String text, String title) {
        if (text == null || text.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, title + " 未设置", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        try {
            StringSelection selection = new StringSelection(text);
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(selection, selection);
            // 去掉成功提示弹窗
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "复制失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}