1
zhang
2025-09-10 b1e74bb24e7785176e59699cfe8eb4f217c958c8
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
package com.algo.util;
 
import com.fasterxml.jackson.databind.ObjectMapper;
 
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * JSON文件读取工具类
 * 用于读取环境配置和路径映射文件
 */
public class JsonUtils {
 
    /**
     * 读取JSON文件内容
     *
     * @param filePath 文件路径
     * @return JSON字符串内容
     * @throws IOException 文件读取异常
     */
    public static String readJsonFile(String filePath) throws IOException {
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
        }
        return content.toString();
    }
 
    /**
     * 解析路径映射JSON内容
     * 正确解析path_mapping.json的实际格式:{"path_id_to_coordinates": {...}}
     *
     * @param jsonContent JSON内容
     * @return 路径映射Map,key为路径编号,value为坐标信息
     */
    public static Map<String, Map<String, Integer>> parsePathMapping(String jsonContent) {
        Map<String, Map<String, Integer>> pathMapping = new HashMap<>();
 
        try {
            // 找到path_id_to_coordinates部分
            String pathIdSection = extractJsonSection(jsonContent, "path_id_to_coordinates");
            if (pathIdSection == null) {
                System.err.println("未找到path_id_to_coordinates部分");
                return pathMapping;
            }
 
            String[] lines = pathIdSection.split("\n");
            String currentKey = null;
 
            for (String line : lines) {
                line = line.trim();
 
                // 查找路径ID
                if (line.startsWith("\"") && line.contains("\":[")) {
                    int endIndex = line.indexOf("\":[");
                    currentKey = line.substring(1, endIndex);
                    pathMapping.put(currentKey, new HashMap<>());
                }
 
                // 查找坐标信息
                if (currentKey != null && line.contains("\"x\":")) {
                    String xStr = line.substring(line.indexOf("\"x\":") + 4);
                    xStr = xStr.substring(0, xStr.indexOf(",")).trim();
                    try {
                        int x = Integer.parseInt(xStr);
                        pathMapping.get(currentKey).put("x", x);
                    } catch (NumberFormatException e) {
                        // 忽略解析错误
                    }
                }
 
                if (currentKey != null && line.contains("\"y\":")) {
                    String yStr = line.substring(line.indexOf("\"y\":") + 4);
                    if (yStr.contains(",")) {
                        yStr = yStr.substring(0, yStr.indexOf(",")).trim();
                    } else if (yStr.contains("}")) {
                        yStr = yStr.substring(0, yStr.indexOf("}")).trim();
                    }
                    try {
                        int y = Integer.parseInt(yStr);
                        pathMapping.get(currentKey).put("y", y);
                    } catch (NumberFormatException e) {
                        // 忽略解析错误
                    }
                }
            }
 
            System.out.println("成功解析路径映射,包含 " + pathMapping.size() + " 个路径点");
 
        } catch (Exception e) {
            System.err.println("解析路径映射JSON时发生错误: " + e.getMessage());
        }
 
        return pathMapping;
    }
 
    /**
     * 加载和解析路径映射文件
     * 正确解析path_mapping.json的实际格式:{"path_id_to_coordinates": {...}}
     *
     * @param filePath 文件地址
     * @return 路径映射Map,key为路径编号,value为坐标信息
     */
    public static Map<String, Map<String, Integer>> loadPathMapping(String filePath) {
        // 转换为目标结构 Map<String, Map<String, Integer>>
        Map<String, Map<String, Integer>> pathMapping = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 先解析为顶层Map<String, Object>
            Map<String, Object> topLevelMap = objectMapper.readValue(
                    new File(filePath),
                    Map.class
            );
 
            if (!topLevelMap.containsKey("path_id_to_coordinates")) {
                System.err.println("未找到path_id_to_coordinates部分");
                return pathMapping;
            }
 
            // 处理 path_id_to_coordinates(将坐标列表转换为第一个坐标的path_id映射)
            Map<String, Object> pathIdCoords = (Map<String, Object>) topLevelMap.get("path_id_to_coordinates");
            for (Map.Entry<String, Object> entry : pathIdCoords.entrySet()) {
                // 保存方式: 路径ID:{"x": , "y":}
                String pathId = entry.getKey();
                Object coordsObj = entry.getValue();
                if (coordsObj instanceof List) {
                    List<?> coordsList = (List<?>) coordsObj;
                    if (!coordsList.isEmpty()) {
                        Map<?, ?> coordMap = (Map<?, ?>) coordsList.get(0);
                        int x = ((Number) coordMap.get("x")).intValue();
                        int y = ((Number) coordMap.get("y")).intValue();
                        Map<String, Integer> pointMap = new HashMap<>();
                        pointMap.put("x", x);
                        pointMap.put("y", y);
                        pathMapping.put(pathId, pointMap);
                    }
                }
            }
 
            System.out.println("成功解析路径映射,包含 " + pathMapping.size() + " 个路径点");
        } catch (FileNotFoundException e) {
            System.err.println("路径映射文件不存在: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("路径映射文件读取错误: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("加载路径映射文件失败: " + e.getMessage());
        }
        return pathMapping;
    }
 
    /**
     * 解析环境配置JSON内容
     * 解析environment.json中的stations信息
     *
     * @param jsonContent JSON内容
     * @return 环境配置Map
     */
    public static Map<String, Object> parseEnvironmentConfig(String jsonContent) {
        Map<String, Object> config = new HashMap<>();
 
        try {
            // 解析width
            if (jsonContent.contains("\"width\":")) {
                String widthStr = jsonContent.substring(jsonContent.indexOf("\"width\":") + 8);
                widthStr = widthStr.substring(0, widthStr.indexOf(",")).trim();
                try {
                    config.put("width", Integer.parseInt(widthStr));
                } catch (NumberFormatException e) {
                    config.put("width", 78);
                }
            }
 
            // 解析height
            if (jsonContent.contains("\"height\":")) {
                String heightStr = jsonContent.substring(jsonContent.indexOf("\"height\":") + 9);
                heightStr = heightStr.substring(0, heightStr.indexOf(",")).trim();
                try {
                    config.put("height", Integer.parseInt(heightStr));
                } catch (NumberFormatException e) {
                    config.put("height", 50);
                }
            }
 
            // 解析stations信息
            Map<String, Map<String, Object>> stations = parseStations(jsonContent);
            config.put("stations", stations);
            config.put("stationCount", stations.size());
 
            System.out.println("成功解析环境配置,包含 " + stations.size() + " 个工作站");
 
        } catch (Exception e) {
            System.err.println("解析环境配置JSON时发生错误: " + e.getMessage());
        }
 
        return config;
    }
 
    /**
     * 加载和解析环境配置文件
     * 解析environment.json中的stations信息
     *
     * @param filePath 文件地址
     * @return 环境配置Map
     */
    public static Map<String, Object> loadEnvironment(String filePath) {
        // 转换为目标结构 Map<String, Object>
        Map<String, Object> environmentMap = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 先解析为顶层Map<String, Object>
            Map<String, Object> topLevelMap = objectMapper.readValue(
                    new File(filePath),
                    Map.class
            );
 
            // 解析width
            if (topLevelMap.containsKey("width")) {
                environmentMap.put("width", Integer.parseInt(topLevelMap.get("width").toString()));
            } else {
                environmentMap.put("width", 78);
            }
 
            // 解析height
            if (topLevelMap.containsKey("width")) {
                environmentMap.put("height", Integer.parseInt(topLevelMap.get("height").toString()));
            } else {
                environmentMap.put("height", 50);
            }
 
            // 解析stations信息
            if (topLevelMap.containsKey("stations")) {
                Map<String, Map<String, Object>> stations = new HashMap<>();
                Map<String, Object> stationMap = (Map<String, Object>) topLevelMap.get("stations");
                for (Map.Entry<String, Object> stationEntry : stationMap.entrySet()) {
                    // 工作站ID
                    String pathId = stationEntry.getKey();
                    Map<String, Object> stationInfo = (Map<String, Object>) stationEntry.getValue();
                    Map<String, Object> map = new HashMap<>();
                    // 解析capacity
                    if (stationInfo.containsKey("capacity")) {
                        map.put("capacity", Integer.parseInt(stationInfo.get("capacity").toString()));
                    }
                    // 解析load_position和unload_position
                    if (stationInfo.containsKey("load_position")) {
                        List<Integer> loadPos = (List<Integer>) stationInfo.get("load_position");
                        map.put("load_position", loadPos);
                    }
                    if (stationInfo.containsKey("unload_position")) {
                        List<Integer> unloadPos = (List<Integer>) stationInfo.get("unload_position");
                        map.put("unload_position", unloadPos);
                    }
                    stations.put(pathId, map);
                }
                environmentMap.put("stations", stations);
                environmentMap.put("stationCount", stations.size());
                System.out.println("成功解析环境配置,包含 " + stations.size() + " 个工作站");
            }
        } catch (FileNotFoundException e) {
            System.err.println("环境配置文件不存在: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("环境配置文件读取错误: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("加载环境配置文件失败: " + e.getMessage());
        }
        return environmentMap;
    }
 
    /**
     * 解析stations信息
     *
     * @param jsonContent JSON内容
     * @return stations Map
     */
    private static Map<String, Map<String, Object>> parseStations(String jsonContent) {
        Map<String, Map<String, Object>> stations = new HashMap<>();
 
        try {
            String stationsSection = extractJsonSection(jsonContent, "stations");
            if (stationsSection == null) {
                return stations;
            }
 
            String[] lines = stationsSection.split("\n");
            String currentStation = null;
 
            for (String line : lines) {
                line = line.trim();
 
                // 查找工作站ID
                if (line.startsWith("\"") && line.contains("\":{")) {
                    int endIndex = line.indexOf("\":{");
                    currentStation = line.substring(1, endIndex);
                    stations.put(currentStation, new HashMap<>());
                }
 
                // 解析capacity
                if (currentStation != null && line.contains("\"capacity\":")) {
                    String capacityStr = line.substring(line.indexOf("\"capacity\":") + 11);
                    capacityStr = capacityStr.substring(0, capacityStr.indexOf(",")).trim();
                    try {
                        int capacity = Integer.parseInt(capacityStr);
                        stations.get(currentStation).put("capacity", capacity);
                    } catch (NumberFormatException e) {
                        // 忽略解析错误
                    }
                }
 
                // 解析load_position和unload_position
                if (currentStation != null && line.contains("\"load_position\":")) {
                    List<Integer> loadPos = parsePosition(stationsSection, currentStation, "load_position");
                    if (loadPos != null) {
                        stations.get(currentStation).put("load_position", loadPos);
                    }
                }
 
                if (currentStation != null && line.contains("\"unload_position\":")) {
                    List<Integer> unloadPos = parsePosition(stationsSection, currentStation, "unload_position");
                    if (unloadPos != null) {
                        stations.get(currentStation).put("unload_position", unloadPos);
                    }
                }
            }
 
        } catch (Exception e) {
            System.err.println("解析stations信息时发生错误: " + e.getMessage());
        }
 
        return stations;
    }
 
    /**
     * 解析位置信息
     *
     * @param content      JSON内容
     * @param stationId    工作站ID
     * @param positionType 位置类型(load_position或unload_position)
     * @return 位置坐标列表
     */
    private static List<Integer> parsePosition(String content, String stationId, String positionType) {
        try {
            String stationSection = content.substring(content.indexOf("\"" + stationId + "\":{"));
            String positionSection = stationSection.substring(stationSection.indexOf("\"" + positionType + "\":"));
 
            String[] lines = positionSection.split("\n");
            List<Integer> position = new ArrayList<>();
 
            for (String line : lines) {
                line = line.trim();
                if (line.matches("\\d+,?")) {
                    String numStr = line.replaceAll("[,\\s]", "");
                    try {
                        position.add(Integer.parseInt(numStr));
                    } catch (NumberFormatException e) {
                        // 忽略解析错误
                    }
                }
                if (line.contains("]")) {
                    break;
                }
            }
 
            return position.size() == 2 ? position : null;
        } catch (Exception e) {
            return null;
        }
    }
 
    /**
     * 提取JSON中的特定部分
     *
     * @param jsonContent JSON内容
     * @param sectionName 部分名称
     * @return 提取的部分内容
     */
    private static String extractJsonSection(String jsonContent, String sectionName) {
        try {
            String startPattern = "\"" + sectionName + "\": {";
            int startIndex = jsonContent.indexOf(startPattern);
            if (startIndex == -1) {
                return null;
            }
 
            int braceCount = 0;
            int currentIndex = startIndex + startPattern.length() - 1;
 
            while (currentIndex < jsonContent.length()) {
                char ch = jsonContent.charAt(currentIndex);
                if (ch == '{') {
                    braceCount++;
                } else if (ch == '}') {
                    braceCount--;
                    if (braceCount == 0) {
                        break;
                    }
                }
                currentIndex++;
            }
 
            return jsonContent.substring(startIndex + startPattern.length() - 1, currentIndex + 1);
        } catch (Exception e) {
            return null;
        }
    }
 
    /**
     * 获取路径点的坐标
     *
     * @param pathId      路径点ID
     * @param pathMapping 路径映射
     * @return 坐标数组 [x, y],如果未找到返回null
     */
    public static int[] getCoordinate(String pathId, Map<String, Map<String, Integer>> pathMapping) {
        Map<String, Integer> coordMap = pathMapping.get(pathId);
        if (coordMap != null && coordMap.containsKey("x") && coordMap.containsKey("y")) {
            return new int[]{coordMap.get("x"), coordMap.get("y")};
        }
        return null;
    }
 
    /**
     * 获取工作站信息
     *
     * @param stationId         工作站ID
     * @param environmentConfig 环境配置
     * @return 工作站信息Map
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> getStationInfo(String stationId, Map<String, Object> environmentConfig) {
        Map<String, Map<String, Object>> stations =
                (Map<String, Map<String, Object>>) environmentConfig.get("stations");
 
        if (stations != null) {
            return stations.get(stationId);
        }
        return null;
    }
 
    /**
     * 判断位置是否为工作站
     *
     * @param position          位置字符串
     * @param environmentConfig 环境配置
     * @return 是否为工作站
     */
    public static boolean isStation(String position, Map<String, Object> environmentConfig) {
        return getStationInfo(position, environmentConfig) != null;
    }
 
    /**
     * 计算两点之间的曼哈顿距离
     *
     * @param coord1 坐标1 [x, y]
     * @param coord2 坐标2 [x, y]
     * @return 曼哈顿距离
     */
    public static double calculateManhattanDistance(int[] coord1, int[] coord2) {
        if (coord1 == null || coord2 == null || coord1.length != 2 || coord2.length != 2) {
            return Double.MAX_VALUE;
        }
 
        return Math.abs(coord1[0] - coord2[0]) + Math.abs(coord1[1] - coord2[1]);
    }
 
    /**
     * 计算两点之间的欧几里得距离
     *
     * @param coord1 坐标1 [x, y]
     * @param coord2 坐标2 [x, y]
     * @return 欧几里得距离
     */
    public static double calculateEuclideanDistance(int[] coord1, int[] coord2) {
        if (coord1 == null || coord2 == null || coord1.length != 2 || coord2.length != 2) {
            return Double.MAX_VALUE;
        }
 
        int dx = coord1[0] - coord2[0];
        int dy = coord1[1] - coord2[1];
        return Math.sqrt(dx * dx + dy * dy);
    }