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
package com.mes.device.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mes.device.entity.GlassInfo;
import com.mes.device.mapper.DeviceGlassInfoMapper;
import com.mes.device.service.EngineeringSequenceService;
import com.mes.device.service.GlassInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
 
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
 
/**
 * 玻璃信息服务实现类
 * 
 * @author mes
 * @since 2024-11-20
 */
@Slf4j
@RefreshScope
@Service("deviceGlassInfoService")
public class GlassInfoServiceImpl extends ServiceImpl<DeviceGlassInfoMapper, GlassInfo> implements GlassInfoService {
 
    @Autowired
    private EngineeringSequenceService engineeringSequenceService;
 
    @Override
    public GlassInfo getGlassInfo(String glassId) {
        if (glassId == null || glassId.trim().isEmpty()) {
            return null;
        }
        try {
            return baseMapper.selectByGlassId(glassId.trim());
        } catch (Exception e) {
            log.error("查询玻璃信息失败, glassId={}", glassId, e);
            return null;
        }
    }
 
    @Override
    public Integer getGlassLength(String glassId) {
        GlassInfo glassInfo = getGlassInfo(glassId);
        return glassInfo != null ? glassInfo.getGlassLength() : null;
    }
 
    @Override
    public List<GlassInfo> getGlassInfos(List<String> glassIds) {
        if (glassIds == null || glassIds.isEmpty()) {
            return Collections.emptyList();
        }
        try {
            // 过滤空值并去重
            List<String> validIds = glassIds.stream()
                    .filter(id -> id != null && !id.trim().isEmpty())
                    .map(String::trim)
                    .distinct()
                    .collect(Collectors.toList());
            
            if (validIds.isEmpty()) {
                return Collections.emptyList();
            }
            
            return baseMapper.selectByGlassIds(validIds);
        } catch (Exception e) {
            log.error("批量查询玻璃信息失败, glassIds={}", glassIds, e);
            return Collections.emptyList();
        }
    }
 
    @Override
    public Map<String, Integer> getGlassLengthMap(List<String> glassIds) {
        Map<String, Integer> lengthMap = new HashMap<>();
        
        if (glassIds == null || glassIds.isEmpty()) {
            return lengthMap;
        }
        
        try {
            List<GlassInfo> glassInfos = getGlassInfos(glassIds);
            for (GlassInfo glassInfo : glassInfos) {
                if (glassInfo.getGlassId() != null && glassInfo.getGlassLength() != null) {
                    lengthMap.put(glassInfo.getGlassId(), glassInfo.getGlassLength());
                }
            }
        } catch (Exception e) {
            log.error("获取玻璃长度映射失败, glassIds={}", glassIds, e);
        }
        
        return lengthMap;
    }
 
    @Override
    public boolean saveOrUpdateGlassInfo(GlassInfo glassInfo) {
        if (glassInfo == null || glassInfo.getGlassId() == null) {
            return false;
        }
        try {
            // 检查是否已存在
            GlassInfo existing = baseMapper.selectByGlassId(glassInfo.getGlassId());
            if (existing != null) {
                glassInfo.setId(existing.getId());
                // 保留原始创建信息
                if (glassInfo.getCreatedTime() == null) {
                    glassInfo.setCreatedTime(existing.getCreatedTime());
                }
                if (glassInfo.getCreatedBy() == null) {
                    glassInfo.setCreatedBy(existing.getCreatedBy());
                }
                // 更新为当前时间
                if (glassInfo.getUpdatedTime() == null) {
                    glassInfo.setUpdatedTime(new Date());
                }
                if (glassInfo.getUpdatedBy() == null) {
                    glassInfo.setUpdatedBy("system");
                }
                return updateById(glassInfo);
            } else {
                Date now = new Date();
                if (glassInfo.getCreatedTime() == null) {
                    glassInfo.setCreatedTime(now);
                }
                if (glassInfo.getUpdatedTime() == null) {
                    glassInfo.setUpdatedTime(now);
                }
                if (glassInfo.getCreatedBy() == null) {
                    glassInfo.setCreatedBy("system");
                }
                if (glassInfo.getUpdatedBy() == null) {
                    glassInfo.setUpdatedBy("system");
                }
                return save(glassInfo);
            }
        } catch (Exception e) {
            log.error("保存或更新玻璃信息失败, glassInfo={}", glassInfo, e);
            return false;
        }
    }
 
    @Override
    public boolean batchSaveOrUpdateGlassInfo(List<GlassInfo> glassInfos) {
        if (glassInfos == null || glassInfos.isEmpty()) {
            return true;
        }
        try {
            for (GlassInfo glassInfo : glassInfos) {
                saveOrUpdateGlassInfo(glassInfo);
            }
            return true;
        } catch (Exception e) {
            log.error("批量保存或更新玻璃信息失败", e);
            return false;
        }
    }
 
    @Override
    public List<String> getRecentScannedGlassIds(Integer minutesAgo, Integer maxCount, String workLine) {
        try {
            // 默认查询最近2分钟内的记录,最多返回20条
            int minutes = minutesAgo != null && minutesAgo > 0 ? minutesAgo : 2;
            int limit = maxCount != null && maxCount > 0 ? maxCount : 20;
            
            Date timeThreshold = new Date(System.currentTimeMillis() - minutes * 60 * 1000L);
            
            LambdaQueryWrapper<GlassInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(GlassInfo::getStatus, GlassInfo.Status.PENDING)
                   .ge(GlassInfo::getCreatedTime, timeThreshold)
                   .orderByDesc(GlassInfo::getCreatedTime)
                   .last("LIMIT " + limit);
            
            // 如果指定了workLine,则过滤description
            if (workLine != null && !workLine.trim().isEmpty()) {
                wrapper.like(GlassInfo::getDescription, "workLine=" + workLine);
            }
            
            List<GlassInfo> recentGlasses = baseMapper.selectList(wrapper);
            
            // 提取玻璃ID列表
            return recentGlasses.stream()
                    .map(GlassInfo::getGlassId)
                    .filter(id -> id != null && !id.trim().isEmpty())
                    .collect(Collectors.toList());
            
        } catch (Exception e) {
            log.error("查询最近扫码的玻璃ID失败, minutesAgo={}, maxCount={}, workLine={}", 
                    minutesAgo, maxCount, workLine, e);
            return Collections.emptyList();
        }
    }
 
    @Override
    public boolean updateGlassStatus(List<String> glassIds, String status) {
        if (CollectionUtils.isEmpty(glassIds) || status == null) {
            return true;
        }
        try {
            LambdaUpdateWrapper<GlassInfo> wrapper = new LambdaUpdateWrapper<>();
            wrapper.in(GlassInfo::getGlassId, glassIds);
            GlassInfo update = new GlassInfo();
            update.setStatus(status);
            update.setUpdatedTime(new Date());
            update.setUpdatedBy("system");
            return this.update(update, wrapper);
        } catch (Exception e) {
            log.error("批量更新玻璃状态失败, glassIds={}, status={}", glassIds, status, e);
            return false;
        }
    }
 
    @Value("${mes.engineering.import-url}")
    private String mesEngineeringImportUrl;
 
    @Override
    public String getMesEngineeringImportUrl() {
        return mesEngineeringImportUrl;
    }
 
    @Override
    public Map<String, Object> buildEngineerImportPayload(List<Map<String, Object>> excelRows) {
        Map<String, Object> result = new HashMap<>();
        if (excelRows == null || excelRows.isEmpty()) {
            return result;
        }
 
        // 工程号:代表整个Excel表,优先使用Excel中的工程号(从第一行或任意一行获取),如果所有行都没有则自动生成
        String engineerIdFromExcel = null;
        for (Map<String, Object> row : excelRows) {
            String engineeringId = str(row.get("engineeringId"));
            if (engineeringId != null && !engineeringId.trim().isEmpty()) {
                engineerIdFromExcel = engineeringId.trim();
                break; // 找到第一个非空的工程号就使用
            }
        }
        final String engineerId = engineerIdFromExcel != null 
                ? engineerIdFromExcel 
                : engineeringSequenceService.generateEngineeringId(new Date());
        final String filmsIdDefault = firstValue(excelRows, "filmsId", "白玻");
        final double thicknessDefault = parseDouble(firstValue(excelRows, "thickness"), 0d);
 
        // glassInfolList
        final String engineerIdFinal = engineerId;
        final String filmsIdDefaultFinal = filmsIdDefault;
        final double thicknessDefaultFinal = thicknessDefault;
 
        // 生成日期字符串(yyMMdd格式),用于流程卡ID生成
        LocalDate localDate = new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        String dateStr = localDate.format(DateTimeFormatter.ofPattern("yyMMdd"));
        
        // 检查是否有流程卡ID:如果所有行的流程卡ID都为空,则所有记录共享同一个流程卡ID
        boolean allFlowCardIdEmpty = excelRows.stream()
                .allMatch(row -> {
                    String flowCardId = str(row.get("flowCardId"));
                    return flowCardId == null || flowCardId.trim().isEmpty();
                });
        // 如果所有流程卡ID都为空,生成一个共享的流程卡ID
        String sharedFlowCardId = allFlowCardIdEmpty ? "NG" + dateStr + "01A001" : null;
        
        // 用于存储每个玻璃ID对应的流程卡ID(同一玻璃ID的多个玻璃共享同一个流程卡ID)
        Map<String, String> glassIdFlowCardIdMap = new HashMap<>();
        
        // 用于按 flowCardId 计数 temperingFeedSequence
        Map<String, Integer> temperingFeedSequenceCounter = new HashMap<>();
        // 用于按 flowCardId 分配 temperingLayoutId
        Map<String, Integer> temperingLayoutIdMap = new HashMap<>();
        AtomicInteger nextTemperingLayoutId = new AtomicInteger(1);
        
        // 先建立原片映射,用于后续匹配 rawSequence
        Map<String, Integer> rawSequenceMap = new HashMap<>();
        for (Map<String, Object> row : excelRows) {
            double width = parseDouble(row.get("width"), 0d);
            double height = parseDouble(row.get("length"), 0d);
            double thickness = parseDouble(row.get("thickness"), thicknessDefaultFinal);
            String filmsId = strOrDefault(row.get("filmsId"), filmsIdDefaultFinal);
            String key = width + "_" + height + "_" + thickness + "_" + filmsId;
            if (!rawSequenceMap.containsKey(key)) {
                rawSequenceMap.put(key, rawSequenceMap.size() + 1);
            }
        }
 
        List<Map<String, Object>> glassInfolList = new ArrayList<>();
        for (Map<String, Object> row : excelRows) {
            Object qtyObj = row.getOrDefault("quantity", 1);
            int qty = parseDouble(qtyObj, 1) > 0 ? (int) parseDouble(qtyObj, 1) : 1;
 
            String glassId = str(row.get("glassId"));
            String filmsId = strOrDefault(row.get("filmsId"), filmsIdDefaultFinal);
            // 流程卡ID:如果Excel中有,使用Excel的;如果为空,使用共享的流程卡ID
            String flowCardIdFromExcel = str(row.get("flowCardId"));
            String flowCardId;
            if (flowCardIdFromExcel != null && !flowCardIdFromExcel.trim().isEmpty()) {
                // Excel中有流程卡ID,使用Excel的
                flowCardId = flowCardIdFromExcel.trim();
            } else {
                // Excel中流程卡ID为空,使用共享的流程卡ID
                flowCardId = sharedFlowCardId != null ? sharedFlowCardId : getOrGenerateFlowCardId(glassId, dateStr, glassIdFlowCardIdMap);
            }
            // 去掉尾部 "/数字"(如果有)
            String baseFlowCardId = flowCardId.replaceFirst("/\\d+$", "");
            
            // 层号:如果Excel中有,使用Excel的;如果没有,默认1
            Object layerObj = row.get("layer");
            int layer = layerObj != null ? (int) parseDouble(layerObj, 1) : 1;
            if (layer <= 0) {
                layer = 1;
            }
            
            // orderNumber 是整型(玻璃类型),从 Excel 读取或使用默认值 1
            Object orderNumberObj = row.get("orderNumber");
            final Integer finalOrderNumber = orderNumberObj != null 
                    ? (int) parseDouble(orderNumberObj, 1) 
                    : 1;
            String productName = str(row.get("productName"));
            String customerName = str(row.get("customerName"));
            double width = parseDouble(row.get("width"), 0d);
            double height = parseDouble(row.get("length"), 0d);
            double thickness = parseDouble(row.get("thickness"), thicknessDefaultFinal);
            
            // 计算 rawSequence
            String rawKey = width + "_" + height + "_" + thickness + "_" + filmsId;
            Integer rawSequence = rawSequenceMap.get(rawKey);
 
            int finalQty = qty;
            log.info("解析到数量:row={}, quantity={}, 最终qty={}", row, qtyObj, finalQty);
            
            // 按 flowCardId 分配 temperingLayoutId
            Integer temperingLayoutId = temperingLayoutIdMap.computeIfAbsent(baseFlowCardId, k -> nextTemperingLayoutId.getAndIncrement());
            
            // 为同一行的多个玻璃生成数据
            for (int idx = 0; idx < qty; idx++) {
                String baseGlassId = engineerIdFinal + glassId;
                String finalGlassId = finalQty > 1 ? baseGlassId + (idx + 1) : baseGlassId;
                
                // 按 flowCardId 递增 temperingFeedSequence
                int temperingFeedSequence = temperingFeedSequenceCounter.compute(baseFlowCardId, (k, v) -> (v == null ? 0 : v) + 1);
                String finalFlowCardSequence = baseFlowCardId + "/" + 1;
                
                log.debug("生成玻璃信息: glassId={}, idx={}, baseFlowCardId={}, finalFlowCardSequence={}, temperingLayoutId={}, temperingFeedSequence={}", 
                        glassId, idx, baseFlowCardId, finalFlowCardSequence, temperingLayoutId, temperingFeedSequence);
 
                Map<String, Object> m = new HashMap<>();
                m.put("xAxis", 0);
                m.put("xCoordinate", 0);
                m.put("yAxis", 0);
                m.put("yCoordinate", 0);
                m.put("glassId", finalGlassId);
                m.put("engineerId", engineerIdFinal);
                m.put("flowCardId", baseFlowCardId);
                m.put("orderNumber", finalOrderNumber);
                m.put("productSortNumber", 1);
                m.put("hollowCombineDirection", "");
                m.put("width", width);
                m.put("height", height);
                m.put("thickness", thickness);
                m.put("filmsId", filmsId);
                m.put("layer", layer);
                m.put("totalLayer", 1);
                m.put("edgWidth", width);
                m.put("edgHeight", height);
                m.put("isMultiple", finalQty > 1 ? 1 : 0);
                m.put("maxWidth", width);
                m.put("maxHeight", height);
                m.put("isHorizontal", 0);
                m.put("rawSequence", rawSequence != null ? rawSequence : 0);
                m.put("temperingLayoutId", temperingLayoutId);
                m.put("temperingFeedSequence", temperingFeedSequence);
                m.put("angle", 0);
                m.put("ruleId", 0);
                m.put("combine", 0);
                m.put("markIcon", "");
                m.put("filmRemove", 0);
                m.put("flowCardSequence", finalFlowCardSequence);
                m.put("process", "");
                m.put("rawAngle", 0);
                m.put("graphNo", 0);
                m.put("processParam", "");
                glassInfolList.add(m);
            }
        }
 
        // 原片信息去重
        Map<String, Map<String, Object>> rawGlassMap = new HashMap<>();
        for (Map<String, Object> row : excelRows) {
            double width = parseDouble(row.get("width"), 0d);
            double height = parseDouble(row.get("length"), 0d);
            double thickness = parseDouble(row.get("thickness"), thicknessDefaultFinal);
            String filmsId = strOrDefault(row.get("filmsId"), filmsIdDefaultFinal);
            String key = width + "_" + height + "_" + thickness + "_" + filmsId;
            if (!rawGlassMap.containsKey(key)) {
                Map<String, Object> m = new HashMap<>();
                m.put("engineeringId", engineerIdFinal);
                m.put("filmsId", filmsId);
                m.put("rawGlassWidth", width);
                m.put("rawGlassHeight", height);
                m.put("rawGlassThickness", thickness);
                m.put("rawSequence", rawGlassMap.size() + 1);
                m.put("usageRate", "0.95");
                rawGlassMap.put(key, m);
            }
        }
 
        List<Map<String, Object>> engineeringRawQueueList = rawGlassMap.values().stream().collect(Collectors.toList());
 
        // 流程卡信息(需要统计每个 flowCardId 的实际玻璃数量,考虑 quantity)
        Map<String, Map<String, Object>> flowCardMap = new HashMap<>();
        for (Map<String, Object> row : excelRows) {
            String glassId = str(row.get("glassId"));
            // 流程卡ID:如果Excel中有,使用Excel的;如果为空,使用共享的流程卡ID(与glassInfolList逻辑一致)
            String flowCardIdFromExcel = str(row.get("flowCardId"));
            String flowCardId;
            if (flowCardIdFromExcel != null && !flowCardIdFromExcel.trim().isEmpty()) {
                // Excel中有流程卡ID,使用Excel的
                flowCardId = flowCardIdFromExcel.trim();
            } else {
                // Excel中流程卡ID为空,使用共享的流程卡ID
                flowCardId = sharedFlowCardId != null ? sharedFlowCardId : getOrGenerateFlowCardId(glassId, dateStr, glassIdFlowCardIdMap);
            }
            // 去掉尾部 "/数字"(如果有)
            flowCardId = flowCardId.replaceFirst("/\\d+$", "");
            // orderNumber 是整型(玻璃类型),从 Excel 读取或使用默认值 1
            Object orderNumberObj = row.get("orderNumber");
            Integer orderNumber = orderNumberObj != null 
                    ? (int) parseDouble(orderNumberObj, 1) 
                    : 1;
            Object qtyObj = row.getOrDefault("quantity", 1);
            int qty = parseDouble(qtyObj, 1) > 0 ? (int) parseDouble(qtyObj, 1) : 1;
            double width = parseDouble(row.get("width"), 0d);
            double height = parseDouble(row.get("length"), 0d);
            double thickness = parseDouble(row.get("thickness"), thicknessDefaultFinal);
            String filmsId = strOrDefault(row.get("filmsId"), filmsIdDefaultFinal);
            String productName = str(row.get("productName"));
            String customerName = str(row.get("customerName"));
 
            Map<String, Object> exist = flowCardMap.get(flowCardId);
            if (exist == null) {
                Map<String, Object> m = new HashMap<>();
                m.put("flowCardId", flowCardId);
                m.put("width", width);
                m.put("height", height);
                m.put("thickness", thickness);
                m.put("filmsId", filmsId);
                m.put("totalLayer", 1);
                m.put("layer", 1);
                m.put("glassTotal", qty); // 使用实际数量
                m.put("orderNumber", orderNumber);
                m.put("productName", productName);
                m.put("customerName", customerName);
                flowCardMap.put(flowCardId, m);
            } else {
                int count = (int) exist.getOrDefault("glassTotal", 0);
                exist.put("glassTotal", count + qty); // 累加数量
            }
        }
        List<Map<String, Object>> flowCardInfoList = flowCardMap.values().stream().collect(Collectors.toList());
 
        // 汇总
        int glassTotal = glassInfolList.size();
        double glassTotalArea = glassInfolList.stream()
                .mapToDouble(m -> parseDouble(m.get("width"), 0d) * parseDouble(m.get("height"), 0d) / 1_000_000d)
                .sum();
        double patternArea = engineeringRawQueueList.stream()
                .mapToDouble(m -> parseDouble(m.get("rawGlassWidth"), 0d) * parseDouble(m.get("rawGlassHeight"), 0d) / 1_000_000d)
                .sum();
 
        // 计算最大负载尺寸(用于钢化参数)
        double maxLoadWidth = glassInfolList.stream()
                .mapToDouble(m -> parseDouble(m.get("width"), 0d))
                .max().orElse(2000);
        double maxLoadLength = glassInfolList.stream()
                .mapToDouble(m -> parseDouble(m.get("height"), 0d))
                .max().orElse(3000);
        
        // 生成钢化参数
        List<Map<String, Object>> temperingParameterList = new ArrayList<>();
        Map<String, Object> temperingParam = new HashMap<>();
        temperingParam.put("engineerId", engineerIdFinal);
        temperingParam.put("heatMode", 1);
        temperingParam.put("chaosPct", 50);
        temperingParam.put("maxLoadPct", 100);
        temperingParam.put("loadWidth", (int) Math.round(maxLoadWidth));
        temperingParam.put("loadLength", (int) Math.round(maxLoadLength));
        temperingParam.put("xSpace", 50);
        temperingParam.put("ySpace", 50);
        temperingParam.put("rotateMode", 0);
        temperingParam.put("allowRotate", 0);
        temperingParam.put("tempering", 1);
        temperingParam.put("curtainWall", 0);
        temperingParameterList.add(temperingParam);
        
        result.put("engineerId", engineerIdFinal);
        result.put("engineerName", thicknessDefaultFinal + "mm" + filmsIdDefaultFinal);
        result.put("avgAvailability", "90");
        result.put("validAvailability", "90");
        result.put("lastAvailability", "90");
        result.put("glassTotal", glassTotal);
        result.put("glassTotalArea", round2(glassTotalArea));
        result.put("planPatternTotal", engineeringRawQueueList.size());
        result.put("planPatternTotalArea", round2(patternArea));
        result.put("realityPatternTotal", engineeringRawQueueList.size());
        result.put("realityPatternTotalArea", round2(patternArea));
        result.put("filmsId", filmsIdDefaultFinal);
        result.put("thickness", thicknessDefaultFinal);
        result.put("engineeringRawQueueList", engineeringRawQueueList);
        result.put("glassInfolList", glassInfolList);
        result.put("flowCardInfoList", flowCardInfoList);
        result.put("hollowFormulaDetailsList", null);
        result.put("temperingParameterList", null);
 
        return result;
    }
 
 
    /**
     * 提取List中第一个Map的指定key值(默认空字符串)
     *
     * @param rows 数据行列表(可为null/空)
     * @param key  要提取的键
     * @return 第一个Map的key对应值(空则返回"")
     */
    private String firstValue(List<Map<String, Object>> rows, String key) {
        return firstValue(rows, key, "");
    }
 
    /**
     * 提取List中第一个Map的指定key值(自定义默认值)
     *
     * @param rows       数据行列表(可为null/空)
     * @param key        要提取的键
     * @param defaultVal 空值时的默认返回值
     * @return 第一个Map的key对应值(空则返回defaultVal)
     */
    private String firstValue(List<Map<String, Object>> rows, String key, String defaultVal) {
        if (rows == null || rows.isEmpty() || key == null) {
            return defaultVal;
        }
 
        Map<String, Object> firstRow = rows.get(0);
        Object value = firstRow.get(key);
        return value == null ? defaultVal : value.toString();
    }
 
    /**
     * 对象转字符串(null转空串,自动去除首尾空格)
     *
     * @param v 待转换对象
     * @return 处理后的字符串
     */
    private String str(Object v) {
        return v == null ? "" : v.toString().trim();
    }
 
    /**
     * 对象转字符串(空串时返回默认值,自动去除首尾空格)
     *
     * @param v   待转换对象
     * @param def 空值默认值
     * @return 处理后的字符串
     */
    private String strOrDefault(Object v, String def) {
        String result = str(v);
        return result.isEmpty() ? def : result;
    }
 
    /**
     * 解析对象为double(失败/空值返回默认值)
     *
     * @param v   待解析对象(支持数字/字符串类型)
     * @param def 解析失败时的默认值
     * @return 解析后的double值
     */
    private double parseDouble(Object v, double def) {
        if (v == null) {
            return def;
        }
 
        try {
            if (v instanceof Number) {
                return ((Number) v).doubleValue();
            }
            return Double.parseDouble(v.toString().trim());
        } catch (NumberFormatException e) {
            // 仅捕获数字格式化异常,避免吞掉其他异常
            return def;
        }
    }
    
    /**
     * 获取或生成流程卡ID
     * 如果已存在则返回,否则生成新的流程卡ID并缓存
     * 前端格式:原始glassId + 两位序号(如"101"、"102"、"201"),通过除以100去掉最后两位提取原始glassId
     * 
     * @param glassId 玻璃ID(如"101"、"102"、"201")
     * @param dateStr 日期字符串(yyMMdd格式)
     * @param glassIdFlowCardIdMap 玻璃ID到流程卡ID的映射缓存
     * @return 流程卡ID(格式:NG + yyMMdd + 序号(两位) + A001)
     */
    private String getOrGenerateFlowCardId(String glassId, String dateStr, Map<String, String> glassIdFlowCardIdMap) {
        String flowCardId = glassIdFlowCardIdMap.get(glassId);
        if (flowCardId == null) {
            // 从glassId中提取原始数字:101 -> 1, 102 -> 1, 201 -> 2
            int sequence = 1;
            if (glassId != null && !glassId.trim().isEmpty()) {
                try {
                    String cleaned = glassId.trim().split("[\\r\\n\\t\\s]+")[0];
                    if (cleaned.matches("\\d+")) {
                        int num = Integer.parseInt(cleaned);
                        // 如果长度>=3,除以100去掉最后两位(前端追加的序号)
                        sequence = (cleaned.length() >= 3 && num >= 100) ? num / 100 : (num > 0 ? num : 1);
                    }
                } catch (Exception e) {
                    log.error("从glassId中提取原始数字失败: glassId={}", glassId, e);
                }
            }
            flowCardId = "NG" + dateStr + String.format("%02d", sequence) + "A001";
            glassIdFlowCardIdMap.put(glassId, flowCardId);
            log.info("为玻璃ID {} 生成流程卡ID: flowCardId={}", glassId, flowCardId);
        }
        return flowCardId;
    }
 
    /**
     * 保留两位小数(四舍五入)
     *
     * @param v 原始数值
     * @return 保留两位小数后的数值
     */
    private double round2(double v) {
        return Math.round(v * 100.0) / 100.0;
    }
 
    @Override
    public List<GlassInfo> getGlassInfosByEngineeringId(String engineeringId) {
        if (engineeringId == null || engineeringId.trim().isEmpty()) {
            return Collections.emptyList();
        }
        try {
            return baseMapper.selectByEngineeringId(engineeringId.trim());
        } catch (Exception e) {
            log.error("根据工程号查询玻璃信息失败, engineeringId={}", engineeringId, e);
            return Collections.emptyList();
        }
    }
 
    @Override
    public void saveGlassInfosFromExcel(List<Map<String, Object>> excelRows, String engineeringId) {
        if (excelRows == null || excelRows.isEmpty() || engineeringId == null || engineeringId.trim().isEmpty()) {
            return;
        }
 
        // 如果工程号已存在,先删除该工程号下的旧数据,实现覆盖更新
        List<GlassInfo> existingGlassInfos = getGlassInfosByEngineeringId(engineeringId.trim());
        if (!existingGlassInfos.isEmpty()) {
            log.info("检测到工程号 {} 已存在 {} 条记录,将删除旧数据并更新", engineeringId, existingGlassInfos.size());
            deleteGlassInfosByEngineeringId(engineeringId.trim());
        }
 
        List<GlassInfo> glassInfos = new ArrayList<>();
        Date now = new Date();
 
        for (Map<String, Object> row : excelRows) {
            String glassId = str(row.get("glassId"));
            if (glassId == null || glassId.trim().isEmpty()) {
                continue;
            }
 
            int qty = (int) parseDouble(row.getOrDefault("quantity", 1), 1);
            if (qty <= 0) qty = 1;
 
            double width = parseDouble(row.get("width"), 0d);
            double length = parseDouble(row.get("length"), 0d);
            double thickness = parseDouble(row.get("thickness"), 0d);
 
            // 与导入规则保持一致:glassId 前加工程号前缀,数量>1时追加序号
            String baseGlassId = engineeringId.trim() + glassId;
            for (int idx = 0; idx < qty; idx++) {
                String finalGlassId = qty > 1 ? baseGlassId + (idx + 1) : baseGlassId;
 
                GlassInfo glassInfo = new GlassInfo();
                glassInfo.setGlassId(finalGlassId);
                glassInfo.setEngineeringId(engineeringId.trim());
                glassInfo.setGlassLength((int) Math.round(length));
                glassInfo.setGlassWidth((int) Math.round(width));
                glassInfo.setGlassThickness(BigDecimal.valueOf(thickness));
                glassInfo.setStatus(GlassInfo.Status.ACTIVE);
                glassInfo.setState(0);
                glassInfo.setCreatedTime(now);
                glassInfo.setUpdatedTime(now);
                glassInfo.setCreatedBy("system");
                glassInfo.setUpdatedBy("system");
 
                glassInfos.add(glassInfo);
            }
        }
 
        if (!glassInfos.isEmpty()) {
            batchSaveOrUpdateGlassInfo(glassInfos);
            log.info("已保存 {} 条玻璃信息到本地数据库,工程号: {}", glassInfos.size(), engineeringId);
        }
    }
 
    @Override
    public boolean updateGlassStateAfterScan(String glassId, Integer width, Integer height, Integer workLine) {
        if (glassId == null || glassId.trim().isEmpty()) {
            return false;
        }
 
        try {
            // 查询已存在的玻璃信息
            GlassInfo existing = baseMapper.selectByGlassId(glassId.trim());
            if (existing == null) {
                log.debug("玻璃信息不存在,无法更新状态: glassId={}", glassId);
                return false;
            }
 
            // 更新状态为1(已扫码交互)
            LambdaUpdateWrapper<GlassInfo> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(GlassInfo::getGlassId, glassId.trim())
                   .eq(GlassInfo::getIsDeleted, 0)
                   .set(GlassInfo::getState, 1)
                   .set(GlassInfo::getUpdatedTime, new Date())
                   .set(GlassInfo::getUpdatedBy, "system");
 
            // 如果提供了尺寸信息,也更新尺寸
            if (width != null) {
                wrapper.set(GlassInfo::getGlassWidth, width);
            }
            if (height != null) {
                wrapper.set(GlassInfo::getGlassLength, height);
            }
            if (workLine != null) {
                wrapper.set(GlassInfo::getWorkLine, workLine);
            }
 
            boolean updated = this.update(wrapper);
            if (updated) {
                log.info("已更新玻璃信息状态为已扫码交互: glassId={}, state=1", glassId);
            }
            return updated;
        } catch (Exception e) {
            log.error("更新玻璃信息状态失败: glassId={}", glassId, e);
            return false;
        }
    }
 
    @Override
    public int deleteGlassInfosByEngineeringId(String engineeringId) {
        if (engineeringId == null || engineeringId.trim().isEmpty()) {
            return 0;
        }
 
        try {
            // 先查询要删除的数量(删除前)
            LambdaQueryWrapper<GlassInfo> countWrapper = new LambdaQueryWrapper<>();
            countWrapper.eq(GlassInfo::getEngineeringId, engineeringId.trim())
                       .eq(GlassInfo::getIsDeleted, 0); // 查询未删除的记录
            long count = this.count(countWrapper);
            
            // 使用MyBatis-Plus的remove方法,会根据@TableLogic自动进行逻辑删除
            LambdaQueryWrapper<GlassInfo> removeWrapper = new LambdaQueryWrapper<>();
            removeWrapper.eq(GlassInfo::getEngineeringId, engineeringId.trim())
                        .eq(GlassInfo::getIsDeleted, 0); // 只删除未删除的记录
            
            boolean result = this.remove(removeWrapper);
            if (result) {
                log.info("已删除工程号下的玻璃信息: engineeringId={}, count={}", engineeringId, count);
                return (int) count;
            }
            return 0;
        } catch (Exception e) {
            log.error("删除工程号下的玻璃信息失败: engineeringId={}", engineeringId, e);
            return 0;
        }
    }
 
}