张世豪
6 天以前 8ce07ce9a4034fdc959d280dd38ecb3e05cbe6e1
src/zhangaiwu/AddDikuai.java
@@ -14,21 +14,25 @@
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Comparator;
import java.awt.geom.Point2D;
import baseStation.BaseStation;
import bianjie.jisuanmianjie;
import dikuai.Dikuai;
import dikuai.Dikuaiguanli;
import gecaoji.Device;
import bianjie.bianjieguihua2;
import lujing.Lunjingguihua;
import set.Setsys;
import ui.UIConfig;
import zhuye.MowerLocationData;
import zhuye.Shouye;
import zhuye.Coordinate;
import zhuye.buttonset;
/**
 * 新增地块对话框 - 多步骤表单设计
@@ -48,6 +52,9 @@
    private final Color LIGHT_TEXT = new Color(108, 117, 125);
    private final Color BORDER_COLOR = new Color(222, 226, 230);
    private final Color SUCCESS_COLOR = new Color(40, 167, 69);
    private final Color ERROR_COLOR = new Color(220, 53, 69);
    private static final String KEY_PATH_MESSAGE_TEXT = "__pathMessageText";
    private static final String KEY_PATH_MESSAGE_SUCCESS = "__pathMessageSuccess";
    
    // 步骤面板
    private JPanel mainPanel;
@@ -67,8 +74,12 @@
    private JButton prevButton;
    private JButton nextButton;
    private JButton createButton;
    private JButton previewButton;
    private Component previewButtonSpacer;
    private JLabel boundaryCountLabel;
    private JPanel obstacleListContainer;
    private JTextArea pathGenerationMessageArea;
    private JPanel pathMessageWrapper;
    
    // 地块数据
    private Map<String, String> dikuaiData = new HashMap<>();
@@ -281,10 +292,6 @@
        formGroup.add(areaNameField);
        formGroup.add(Box.createRigidArea(new Dimension(0, 8)));
        formGroup.add(hintLabel);
    formGroup.add(Box.createRigidArea(new Dimension(0, 20)));
    JPanel obstacleSection = createObstacleSummarySection();
    formGroup.add(obstacleSection);
        
        stepPanel.add(formGroup);
        stepPanel.add(Box.createVerticalGlue());
@@ -362,93 +369,105 @@
    private List<ObstacleSummary> loadExistingObstacles() {
        List<ObstacleSummary> summaries = new ArrayList<>();
        List<ExistingObstacle> obstacles = fetchExistingObstacleDetails();
        String landNumber = getPendingLandNumber();
        String raw = null;
        if (landNumber != null) {
            Dikuai dikuai = Dikuai.getDikuai(landNumber);
            if (dikuai != null) {
                raw = normalizeCoordinateValue(dikuai.getObstacleCoordinates());
            }
        }
        if (raw == null) {
            raw = normalizeCoordinateValue(dikuaiData.get("obstacleCoordinates"));
        }
        if (!isMeaningfulValue(raw)) {
        if (obstacles.isEmpty()) {
            return summaries;
        }
        String normalized = stripInlineComment(raw);
        if (normalized.isEmpty()) {
            return summaries;
        }
        List<String> entries = splitObstacleEntries(normalized);
        int defaultIndex = 1;
        for (String entry : entries) {
            String trimmedEntry = stripInlineComment(entry);
            if (trimmedEntry.isEmpty()) {
        for (ExistingObstacle obstacle : obstacles) {
            if (obstacle == null) {
                continue;
            }
            String nameToken = null;
            String shapeToken = null;
            String coordsSection = trimmedEntry;
            if (trimmedEntry.contains("::")) {
                String[] parts = trimmedEntry.split("::", 3);
                if (parts.length == 3) {
                    nameToken = parts[0].trim();
                    shapeToken = parts[1].trim();
                    coordsSection = parts[2].trim();
                }
            } else if (trimmedEntry.contains("@")) {
                String[] parts = trimmedEntry.split("@", 3);
                if (parts.length == 3) {
                    nameToken = parts[0].trim();
                    shapeToken = parts[1].trim();
                    coordsSection = parts[2].trim();
                } else if (parts.length == 2) {
                    shapeToken = parts[0].trim();
                    coordsSection = parts[1].trim();
                }
            } else if (trimmedEntry.contains(":")) {
                String[] parts = trimmedEntry.split(":", 3);
                if (parts.length == 3) {
                    nameToken = parts[0].trim();
                    shapeToken = parts[1].trim();
                    coordsSection = parts[2].trim();
                } else if (parts.length == 2) {
                    if (looksLikeShapeToken(parts[0])) {
                        shapeToken = parts[0].trim();
                        coordsSection = parts[1].trim();
                    } else {
                        nameToken = parts[0].trim();
                        coordsSection = parts[1].trim();
                    }
                }
            }
            String sanitizedCoords = sanitizeCoordinateString(coordsSection);
            if (!isMeaningfulValue(sanitizedCoords)) {
            String name = obstacle.getName();
            if (!isMeaningfulValue(name)) {
                continue;
            }
            String resolvedName;
            if (nameToken != null && !nameToken.isEmpty()) {
                resolvedName = nameToken;
            } else {
                resolvedName = "障碍物" + defaultIndex++;
            }
            String displayCoords = truncateCoordinateForDisplay(sanitizedCoords, 12);
            summaries.add(new ObstacleSummary(resolvedName, sanitizedCoords, displayCoords));
            String coords = obstacle.getDisplayCoordinates();
            String fullCoords = isMeaningfulValue(coords) ? coords.trim() : "";
            String preview = buildCoordinatePreview(fullCoords, 20);
            summaries.add(new ObstacleSummary(name.trim(), fullCoords, preview));
        }
        return summaries;
    }
    private List<ExistingObstacle> fetchExistingObstacleDetails() {
        File configFile = new File("Obstacledge.properties");
        if (!configFile.exists()) {
            return Collections.emptyList();
        }
        List<ExistingObstacle> result = new ArrayList<>();
        try {
            Obstacledge.ConfigManager manager = new Obstacledge.ConfigManager();
            if (!manager.loadFromFile(configFile.getAbsolutePath())) {
                return Collections.emptyList();
            }
            for (Obstacledge.Plot plot : manager.getPlots()) {
                if (plot == null) {
                    continue;
                }
                String landNumber = isMeaningfulValue(plot.getPlotId()) ? plot.getPlotId().trim() : "";
                List<Obstacledge.Obstacle> plotObstacles = plot.getObstacles();
                if (plotObstacles == null || plotObstacles.isEmpty()) {
                    continue;
                }
                for (Obstacledge.Obstacle obstacle : plotObstacles) {
                    if (obstacle == null) {
                        continue;
                    }
                    String name = obstacle.getObstacleName();
                    if (!isMeaningfulValue(name)) {
                        continue;
                    }
                    String coords = extractObstacleCoordinates(obstacle);
                    result.add(new ExistingObstacle(landNumber, name.trim(), coords));
                }
            }
        } catch (Exception ex) {
            System.err.println("加载已有障碍物失败: " + ex.getMessage());
            return Collections.emptyList();
        }
        if (result.isEmpty()) {
            return Collections.emptyList();
        }
        result.sort(Comparator.comparing(ExistingObstacle::getName, String.CASE_INSENSITIVE_ORDER));
        return result;
    }
    private String extractObstacleCoordinates(Obstacledge.Obstacle obstacle) {
        if (obstacle == null) {
            return "";
        }
        String xy = obstacle.getXyCoordsString();
        if (isMeaningfulValue(xy)) {
            return xy.trim();
        }
        String original = obstacle.getOriginalCoordsString();
        if (isMeaningfulValue(original)) {
            return original.trim();
        }
        return "";
    }
    private String buildCoordinatePreview(String coords, int keepLength) {
        if (!isMeaningfulValue(coords)) {
            return "无坐标";
        }
        String sanitized = sanitizeCoordinateString(coords);
        if (sanitized.length() <= keepLength) {
            return sanitized;
        }
        if (keepLength <= 0) {
            return "...";
        }
        return sanitized.substring(0, keepLength) + "...";
    }
    private List<String> splitObstacleEntries(String data) {
        List<String> entries = new ArrayList<>();
        if (data.indexOf('|') >= 0) {
@@ -543,6 +562,30 @@
            return displayCoords;
        }
    }
    private static final class ExistingObstacle {
        private final String landNumber;
        private final String name;
        private final String coordinates;
        ExistingObstacle(String landNumber, String name, String coordinates) {
            this.landNumber = landNumber != null ? landNumber : "";
            this.name = name != null ? name : "";
            this.coordinates = coordinates != null ? coordinates : "";
        }
        String getLandNumber() {
            return landNumber;
        }
        String getName() {
            return name;
        }
        String getDisplayCoordinates() {
            return coordinates;
        }
    }
    
    private JPanel createStep2Panel() {
        JPanel stepPanel = new JPanel();
@@ -696,8 +739,9 @@
                if (!optionPanel.isEnabled()) {
                    return;
                }
                selectDrawingOption(optionPanel, type);
                startEndDrawingBtn.setEnabled(true); // 选择后启用按钮
                if (selectDrawingOption(optionPanel, type, true)) {
                    startEndDrawingBtn.setEnabled(true); // 选择后启用按钮
                }
            }
            
            @Override
@@ -719,7 +763,15 @@
        return optionPanel;
    }
    
    private void selectDrawingOption(JPanel optionPanel, String type) {
    private boolean selectDrawingOption(JPanel optionPanel, String type, boolean userTriggered) {
        if (optionPanel == null) {
            return false;
        }
        if (userTriggered && "handheld".equalsIgnoreCase(type) && !hasConfiguredHandheldMarker()) {
            JOptionPane.showMessageDialog(this, "请先添加便携打点器编号", "提示", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        // 重置之前选中的选项
        if (selectedOptionPanel != null) {
            selectedOptionPanel.setBorder(BorderFactory.createLineBorder(BORDER_COLOR, 2));
@@ -729,7 +781,7 @@
                ((JLabel) oldTitle).setForeground(TEXT_COLOR);
            }
        }
        // 设置新的选中状态
        optionPanel.setBorder(BorderFactory.createLineBorder(PRIMARY_COLOR, 3));
        optionPanel.setBackground(PRIMARY_LIGHT);
@@ -738,9 +790,15 @@
            ((JLabel) titleObj).setForeground(PRIMARY_COLOR);
        }
        selectedOptionPanel = optionPanel;
        // 保存选择
        dikuaiData.put("drawingMethod", type);
        return true;
    }
    private boolean hasConfiguredHandheldMarker() {
        String handheldId = Setsys.getPropertyValue("handheldMarkerId");
        return handheldId != null && !handheldId.trim().isEmpty();
    }
    
    private void toggleDrawing() {
@@ -930,6 +988,29 @@
        stepPanel.add(Box.createRigidArea(new Dimension(0, 20)));
        stepPanel.add(generatePathButton);
        stepPanel.add(Box.createRigidArea(new Dimension(0, 12)));
        pathMessageWrapper = new JPanel(new BorderLayout());
        pathMessageWrapper.setAlignmentX(Component.LEFT_ALIGNMENT);
        pathMessageWrapper.setBackground(PRIMARY_LIGHT);
        pathMessageWrapper.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(PRIMARY_COLOR, 1),
            BorderFactory.createEmptyBorder(12, 12, 12, 12)
        ));
        pathMessageWrapper.setVisible(false);
        pathGenerationMessageArea = new JTextArea();
        pathGenerationMessageArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        pathGenerationMessageArea.setForeground(TEXT_COLOR);
        pathGenerationMessageArea.setOpaque(false);
        pathGenerationMessageArea.setEditable(false);
        pathGenerationMessageArea.setLineWrap(true);
        pathGenerationMessageArea.setWrapStyleWord(true);
        pathGenerationMessageArea.setFocusable(false);
        pathGenerationMessageArea.setBorder(null);
        pathMessageWrapper.add(pathGenerationMessageArea, BorderLayout.CENTER);
        stepPanel.add(pathMessageWrapper);
        stepPanel.add(Box.createVerticalGlue());
        return stepPanel;
@@ -989,6 +1070,9 @@
    private void generateMowingPath() {
        if (!dikuaiData.containsKey("boundaryDrawn")) {
            JOptionPane.showMessageDialog(this, "请先完成边界绘制后再生成路径", "提示", JOptionPane.WARNING_MESSAGE);
            dikuaiData.remove("plannedPath");
            showPathGenerationMessage("请先完成边界绘制后再生成路径。", false);
            setPathAvailability(false);
            showStep(2);
            return;
        }
@@ -1002,15 +1086,16 @@
        }
        if (boundaryCoords == null) {
            JOptionPane.showMessageDialog(this, "未找到有效的地块边界坐标,无法生成路径", "提示", JOptionPane.WARNING_MESSAGE);
            if (createButton != null) {
                createButton.setEnabled(false);
            }
            dikuaiData.remove("plannedPath");
            showPathGenerationMessage("未找到有效的地块边界坐标,无法生成路径。", false);
            setPathAvailability(false);
            return;
        }
        String obstacleCoords = null;
        if (dikuai != null) {
            obstacleCoords = normalizeCoordinateValue(dikuai.getObstacleCoordinates());
        String landNumber = getPendingLandNumber();
        if (isMeaningfulValue(landNumber)) {
            obstacleCoords = normalizeCoordinateValue(resolveObstaclePayloadFromConfig(landNumber));
        }
        if (obstacleCoords == null) {
            obstacleCoords = normalizeCoordinateValue(dikuaiData.get("obstacleCoordinates"));
@@ -1022,17 +1107,17 @@
        Object widthObj = mowingWidthSpinner.getValue();
        if (!(widthObj instanceof Number)) {
            JOptionPane.showMessageDialog(this, "割草宽度输入无效", "提示", JOptionPane.WARNING_MESSAGE);
            if (createButton != null) {
                createButton.setEnabled(false);
            }
            dikuaiData.remove("plannedPath");
            showPathGenerationMessage("割草宽度输入无效,请重新输入。", false);
            setPathAvailability(false);
            return;
        }
        double widthCm = ((Number) widthObj).doubleValue();
        if (widthCm <= 0) {
            JOptionPane.showMessageDialog(this, "割草宽度必须大于0", "提示", JOptionPane.WARNING_MESSAGE);
            if (createButton != null) {
                createButton.setEnabled(false);
            }
            dikuaiData.remove("plannedPath");
            showPathGenerationMessage("割草宽度必须大于0,请重新设置。", false);
            setPathAvailability(false);
            return;
        }
        dikuaiData.put("mowingWidth", widthObj.toString());
@@ -1050,46 +1135,152 @@
            String plannedPath = Lunjingguihua.formatPathSegments(segments);
            if (!isMeaningfulValue(plannedPath)) {
                JOptionPane.showMessageDialog(this, "生成割草路径失败: 生成结果为空", "错误", JOptionPane.ERROR_MESSAGE);
                if (createButton != null) {
                    createButton.setEnabled(false);
                }
                dikuaiData.remove("plannedPath");
                showPathGenerationMessage("生成割草路径失败:生成结果为空。", false);
                setPathAvailability(false);
                return;
            }
            dikuaiData.put("plannedPath", plannedPath);
            if (createButton != null) {
                createButton.setEnabled(true);
            if (isMeaningfulValue(boundaryCoords)) {
                dikuaiData.put("boundaryCoordinates", boundaryCoords);
            }
            JOptionPane.showMessageDialog(this,
                "已根据当前设置生成割草路径,共生成 " + segments.size() + " 段。",
                "成功",
                JOptionPane.INFORMATION_MESSAGE);
            if (isMeaningfulValue(obstacleCoords)) {
                dikuaiData.put("obstacleCoordinates", obstacleCoords);
            }
            dikuaiData.put("plannedPath", plannedPath);
            setPathAvailability(true);
            showPathGenerationMessage(
                "已根据当前设置生成割草路径,共生成 " + segments.size() + " 段。\n点击“预览”按钮可在主页面查看效果。",
                true);
        } catch (IllegalArgumentException ex) {
            JOptionPane.showMessageDialog(this, "生成割草路径失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            if (createButton != null) {
                createButton.setEnabled(false);
            }
            dikuaiData.remove("plannedPath");
            showPathGenerationMessage("生成割草路径失败:" + ex.getMessage(), false);
            setPathAvailability(false);
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "生成割草路径时发生异常: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            if (createButton != null) {
                createButton.setEnabled(false);
            dikuaiData.remove("plannedPath");
            showPathGenerationMessage("生成割草路径时发生异常:" + ex.getMessage(), false);
            setPathAvailability(false);
        }
    }
    private void previewMowingPath() {
        if (!hasGeneratedPath()) {
            showPathGenerationMessage("请先生成割草路径后再预览。", false);
            setPathAvailability(false);
            return;
        }
        persistStep3Inputs();
        String landNumber = getPendingLandNumber();
        String trimmedAreaName = areaNameField.getText() != null ? areaNameField.getText().trim() : "";
        String displayAreaName = isMeaningfulValue(trimmedAreaName) ? trimmedAreaName : landNumber;
        String plannedPath = dikuaiData.get("plannedPath");
        if (!isMeaningfulValue(plannedPath)) {
            showPathGenerationMessage("请先生成割草路径后再预览。", false);
            setPathAvailability(false);
            return;
        }
        String boundary = null;
        Dikuai pending = getOrCreatePendingDikuai();
        if (pending != null) {
            boundary = normalizeCoordinateValue(pending.getBoundaryCoordinates());
        }
        if (boundary == null) {
            boundary = normalizeCoordinateValue(dikuaiData.get("boundaryCoordinates"));
        }
        String obstacles = normalizeCoordinateValue(dikuaiData.get("obstacleCoordinates"));
        if (!isMeaningfulValue(obstacles)) {
            obstacles = resolveObstaclePayloadFromConfig(landNumber);
            if (isMeaningfulValue(obstacles)) {
                dikuaiData.put("obstacleCoordinates", obstacles);
            }
        }
        Shouye shouye = Shouye.getInstance();
        if (shouye == null) {
            JOptionPane.showMessageDialog(this, "无法打开主页面,请稍后重试", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        dikuaiData.put("areaName", trimmedAreaName);
        if (isMeaningfulValue(boundary)) {
            dikuaiData.put("boundaryCoordinates", boundary);
        }
        pendingLandNumber = landNumber;
        captureSessionSnapshot();
        resumeRequested = true;
        boolean started = shouye.startMowingPathPreview(
            landNumber,
            displayAreaName,
            boundary,
            obstacles,
            plannedPath,
            AddDikuai::resumeFromPreview
        );
        if (!started) {
            resumeRequested = false;
            JOptionPane.showMessageDialog(this, "无法启动预览,请稍后再试", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        closePreviewAndDispose();
    }
    private void persistStep3Inputs() {
        String trimmedName = areaNameField.getText() != null ? areaNameField.getText().trim() : "";
        dikuaiData.put("areaName", trimmedName);
        if (mowingPatternCombo != null) {
            Object selection = mowingPatternCombo.getSelectedItem();
            if (selection != null) {
                dikuaiData.put("mowingPattern", selection.toString());
            }
        }
        if (mowingWidthSpinner != null) {
            Object widthValue = mowingWidthSpinner.getValue();
            if (widthValue instanceof Number) {
                int widthInt = ((Number) widthValue).intValue();
                dikuaiData.put("mowingWidth", Integer.toString(widthInt));
            } else if (widthValue != null) {
                dikuaiData.put("mowingWidth", widthValue.toString());
            }
        }
    }
    private void captureSessionSnapshot() {
        if (activeSession == null) {
            activeSession = new DrawingSession();
        }
        String landNumber = getPendingLandNumber();
        activeSession.landNumber = landNumber;
        activeSession.areaName = areaNameField.getText() != null ? areaNameField.getText().trim() : "";
        activeSession.drawingCompleted = true;
        activeSession.data = new HashMap<>(dikuaiData);
    }
    private void closePreviewAndDispose() {
        setVisible(false);
        dispose();
    }
    
    private JButton createPrimaryButton(String text, int fontSize) {
        JButton button = new JButton(text);
        JButton button = buttonset.createStyledButton(text, PRIMARY_COLOR);
        button.setFont(new Font("微软雅黑", Font.BOLD, fontSize));
        button.setBackground(PRIMARY_COLOR);
        button.setForeground(WHITE);
        button.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(PRIMARY_DARK, 2),
            BorderFactory.createEmptyBorder(12, 25, 12, 25)
        ));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
        // 按钮悬停效果
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
@@ -1097,7 +1288,7 @@
                    button.setBackground(PRIMARY_DARK);
                }
            }
            @Override
            public void mouseExited(MouseEvent e) {
                if (button.isEnabled()) {
@@ -1105,9 +1296,47 @@
                }
            }
        });
        return button;
    }
    private void showPathGenerationMessage(String message, boolean success) {
        if (pathGenerationMessageArea == null || pathMessageWrapper == null) {
            return;
        }
        String display = message == null ? "" : message.trim();
        if (display.isEmpty()) {
            dikuaiData.remove(KEY_PATH_MESSAGE_TEXT);
            dikuaiData.remove(KEY_PATH_MESSAGE_SUCCESS);
        } else {
            dikuaiData.put(KEY_PATH_MESSAGE_TEXT, display);
            dikuaiData.put(KEY_PATH_MESSAGE_SUCCESS, success ? "true" : "false");
        }
        pathGenerationMessageArea.setText(display);
        Color borderColor = success ? PRIMARY_COLOR : ERROR_COLOR;
        Color textColor = success ? PRIMARY_DARK : ERROR_COLOR;
        Color backgroundColor = success ? PRIMARY_LIGHT : new Color(255, 235, 238);
        pathGenerationMessageArea.setForeground(textColor);
        pathMessageWrapper.setBackground(backgroundColor);
        pathMessageWrapper.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(borderColor, 1),
            BorderFactory.createEmptyBorder(12, 12, 12, 12)
        ));
        pathMessageWrapper.setVisible(!display.isEmpty());
        pathMessageWrapper.revalidate();
        pathMessageWrapper.repaint();
    }
    private void setPathAvailability(boolean available) {
        boolean effective = available && currentStep == 3;
        if (createButton != null) {
            createButton.setEnabled(effective);
        }
        if (previewButton != null) {
            boolean visible = previewButton.isVisible();
            previewButton.setEnabled(effective && visible);
        }
    }
    
    private JPanel createButtonPanel() {
        JPanel buttonPanel = new JPanel();
@@ -1115,25 +1344,32 @@
        buttonPanel.setBackground(WHITE);
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(20, 0, 0, 0));
        prevButton = new JButton("上一步");
        prevButton = buttonset.createStyledButton("上一步", MEDIUM_GRAY);
        prevButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
        prevButton.setBackground(MEDIUM_GRAY);
        prevButton.setForeground(TEXT_COLOR);
        prevButton.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(BORDER_COLOR, 2),
            BorderFactory.createEmptyBorder(10, 25, 10, 25)
        ));
        prevButton.setFocusPainted(false);
        prevButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        nextButton = createPrimaryButton("下一步", 16);
        createButton = createPrimaryButton("保存", 16);
        createButton.setVisible(false);
    createButton.setEnabled(false);
        createButton.setEnabled(false);
        previewButton = createPrimaryButton("预览", 16);
        previewButton.setVisible(false);
        previewButton.setEnabled(false);
        previewButtonSpacer = Box.createHorizontalStrut(15);
        previewButtonSpacer.setVisible(false);
        buttonPanel.add(prevButton);
        buttonPanel.add(Box.createHorizontalGlue());
        buttonPanel.add(nextButton);
        buttonPanel.add(previewButtonSpacer);
        buttonPanel.add(previewButton);
        buttonPanel.add(Box.createHorizontalStrut(15));
        buttonPanel.add(createButton);
@@ -1185,14 +1421,40 @@
        return true;
    }
    private static String buildOriginalBoundaryString() {
        if (Coordinate.coordinates == null || Coordinate.coordinates.isEmpty()) {
    private static List<Coordinate> sanitizeCoordinateList(List<Coordinate> source) {
        if (source == null || source.isEmpty()) {
            return Collections.emptyList();
        }
        List<Coordinate> snapshot = new ArrayList<>();
        for (Coordinate coordinate : source) {
            if (coordinate != null) {
                snapshot.add(coordinate);
            }
        }
        if (snapshot.isEmpty()) {
            return Collections.emptyList();
        }
        DecimalFormat latLonFormat = new DecimalFormat("0.000000");
        LinkedHashMap<String, Coordinate> unique = new LinkedHashMap<>();
        for (Coordinate coord : snapshot) {
            double lat = convertToDecimalDegree(coord.getLatitude(), coord.getLatDirection());
            double lon = convertToDecimalDegree(coord.getLongitude(), coord.getLonDirection());
            String key = latLonFormat.format(lat) + "," + latLonFormat.format(lon);
            unique.putIfAbsent(key, coord);
        }
        return new ArrayList<>(unique.values());
    }
    private static String buildOriginalBoundaryString(List<Coordinate> coordinates) {
        if (coordinates == null || coordinates.isEmpty()) {
            return "-1";
        }
        StringBuilder sb = new StringBuilder();
        DecimalFormat latLonFormat = new DecimalFormat("0.000000");
        DecimalFormat elevationFormat = new DecimalFormat("0.00");
        for (Coordinate coord : Coordinate.coordinates) {
        for (Coordinate coord : coordinates) {
            double lat = convertToDecimalDegree(coord.getLatitude(), coord.getLatDirection());
            double lon = convertToDecimalDegree(coord.getLongitude(), coord.getLonDirection());
            double elevation = coord.getElevation();
@@ -1259,6 +1521,30 @@
        return isMeaningfulValue(dikuaiData.get("plannedPath"));
    }
    private String resolveObstaclePayloadFromConfig(String landNumber) {
        if (!isMeaningfulValue(landNumber)) {
            return null;
        }
        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 null;
            }
            return Obstacledge.buildPlannerPayload(plot.getObstacles());
        } catch (Exception ex) {
            System.err.println("加载障碍物配置失败: " + ex.getMessage());
            return null;
        }
    }
    private static String normalizeCoordinateValue(String value) {
        return isMeaningfulValue(value) ? value.trim() : null;
    }
@@ -1272,8 +1558,14 @@
    }
    private static BoundarySnapshotResult computeBoundarySnapshot() {
        int count = Coordinate.coordinates != null ? Coordinate.coordinates.size() : 0;
        if (count < 3) {
        List<Coordinate> uniqueCoordinates;
        synchronized (Coordinate.coordinates) {
            uniqueCoordinates = sanitizeCoordinateList(Coordinate.coordinates);
            Coordinate.coordinates.clear();
            Coordinate.coordinates.addAll(uniqueCoordinates);
        }
        if (uniqueCoordinates.size() < 3) {
            return BoundarySnapshotResult.failure("采集的边界点不足,无法生成地块边界", JOptionPane.WARNING_MESSAGE);
        }
@@ -1282,9 +1574,9 @@
            return BoundarySnapshotResult.failure("当前地块面积为0,无法继续", JOptionPane.WARNING_MESSAGE);
        }
        Device device = new Device();
        device.initFromProperties();
        String baseStationCoordinates = normalizeCoordinateValue(device.getBaseStationCoordinates());
    BaseStation baseStation = new BaseStation();
    baseStation.load();
    String baseStationCoordinates = normalizeCoordinateValue(baseStation.getInstallationCoordinates());
        if (!isMeaningfulValue(baseStationCoordinates)) {
            return BoundarySnapshotResult.failure("未获取到有效的基准站坐标,请先在基准站管理中设置", JOptionPane.WARNING_MESSAGE);
        }
@@ -1297,7 +1589,7 @@
            return BoundarySnapshotResult.failure("生成地块边界失败: " + ex.getMessage(), JOptionPane.ERROR_MESSAGE);
        }
        String originalBoundary = buildOriginalBoundaryString();
    String originalBoundary = buildOriginalBoundaryString(uniqueCoordinates);
        DecimalFormat areaFormat = new DecimalFormat("0.00");
        String areaString = areaFormat.format(area);
@@ -1345,6 +1637,10 @@
        
        // 创建地块按钮
        createButton.addActionListener(e -> createDikuai());
        if (previewButton != null) {
            previewButton.addActionListener(e -> previewMowingPath());
        }
        
        // 关闭对话框
        addWindowListener(new WindowAdapter() {
@@ -1358,10 +1654,6 @@
    private void showStep(int step) {
        currentStep = step;
        cardLayout.show(stepsPanel, "step" + step);
        if (step == 1) {
            updateObstacleSummary();
        }
        // 更新按钮状态
        updateButtonState(step);
@@ -1373,11 +1665,24 @@
        if (step < 3) {
            nextButton.setVisible(true);
            createButton.setVisible(false);
            createButton.setEnabled(false);
            setPathAvailability(false);
            if (previewButton != null) {
                previewButton.setVisible(false);
                previewButton.setEnabled(false);
            }
            if (previewButtonSpacer != null) {
                previewButtonSpacer.setVisible(false);
            }
        } else {
            nextButton.setVisible(false);
            createButton.setVisible(true);
            createButton.setEnabled(hasGeneratedPath());
            if (previewButton != null) {
                previewButton.setVisible(true);
            }
            if (previewButtonSpacer != null) {
                previewButtonSpacer.setVisible(true);
            }
            setPathAvailability(hasGeneratedPath());
        }
        Container parent = prevButton.getParent();
@@ -1649,7 +1954,7 @@
        if (method != null) {
            JPanel panel = drawingOptionPanels.get(method);
            if (panel != null) {
                selectDrawingOption(panel, method);
                selectDrawingOption(panel, method, false);
            }
        }
@@ -1674,6 +1979,71 @@
            showStep(1);
            hideBoundaryPointSummary();
        }
        restoreGeneratedPathState(session);
    }
    private void restoreGeneratedPathState(DrawingSession session) {
        if (session == null || session.data == null) {
            showPathGenerationMessage("", true);
            return;
        }
        Map<String, String> data = session.data;
        if (mowingPatternCombo != null) {
            String pattern = data.get("mowingPattern");
            if (pattern != null) {
                ComboBoxModel<String> model = mowingPatternCombo.getModel();
                for (int i = 0; i < model.getSize(); i++) {
                    String candidate = model.getElementAt(i);
                    if (pattern.equals(candidate)) {
                        mowingPatternCombo.setSelectedIndex(i);
                        break;
                    }
                }
            }
        }
        if (mowingWidthSpinner != null) {
            String width = data.get("mowingWidth");
            if (isMeaningfulValue(width)) {
                try {
                    double parsed = Double.parseDouble(width.trim());
                    SpinnerNumberModel model = (SpinnerNumberModel) mowingWidthSpinner.getModel();
                    int min = ((Number) model.getMinimum()).intValue();
                    int max = ((Number) model.getMaximum()).intValue();
                    int rounded = (int) Math.round(parsed);
                    if (rounded < min) {
                        rounded = min;
                    } else if (rounded > max) {
                        rounded = max;
                    }
                    mowingWidthSpinner.setValue(rounded);
                } catch (NumberFormatException ignored) {
                    // 保持当前值
                }
            }
        }
        boolean hasPath = isMeaningfulValue(data.get("plannedPath"));
        if (!hasPath) {
            showPathGenerationMessage("", true);
            if (currentStep == 3) {
                setPathAvailability(false);
            }
            return;
        }
        String message = data.get(KEY_PATH_MESSAGE_TEXT);
        boolean success = !"false".equalsIgnoreCase(data.get(KEY_PATH_MESSAGE_SUCCESS));
        showStep(3);
        if (isMeaningfulValue(message)) {
            showPathGenerationMessage(message, success);
        } else {
            showPathGenerationMessage("已生成割草路径,可点击“预览”按钮查看效果。", true);
        }
        setPathAvailability(true);
    }
    public static void finishDrawingSession() {
@@ -1707,6 +2077,19 @@
        Component parent = shouye != null ? shouye : null;
        showAddDikuaiDialog(parent);
    }
    public static void resumeFromPreview() {
        Shouye shouye = Shouye.getInstance();
        if (shouye != null) {
            shouye.exitMowingPathPreview();
        }
        if (activeSession == null) {
            return;
        }
        resumeRequested = true;
        Component parent = shouye != null ? shouye : null;
        SwingUtilities.invokeLater(() -> showAddDikuaiDialog(parent));
    }
    
    private void createDikuai() {
        if (!validateCurrentStep()) {