huminmin
6 小时以前 bdb10f17dd56fdb8dd8e3dca897c5cfb5e40a75d
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
package com.ruoyi.mock.service.impl;
 
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.ai.assistant.Assistant;
import com.ruoyi.approve.mapper.ApprovalInstanceMapper;
import com.ruoyi.approve.pojo.ApprovalInstance;
import com.ruoyi.approve.service.ApprovalInstanceService;
import com.ruoyi.basic.mapper.ProductMapper;
import com.ruoyi.basic.mapper.ProductModelMapper;
import com.ruoyi.basic.pojo.Customer;
import com.ruoyi.basic.pojo.SupplierManage;
import com.ruoyi.basic.service.ICustomerService;
import com.ruoyi.basic.service.ISupplierService;
import com.ruoyi.common.enums.ReviewStatusEnum;
import com.ruoyi.mock.dto.DataGenerateRequest;
import com.ruoyi.mock.prompt.MockDataPrompt;
import com.ruoyi.mock.service.DataGenerateService;
import com.ruoyi.mock.vo.DataGenerateResult;
import com.ruoyi.mock.vo.DataGenerateResult.ModuleSummary;
import com.ruoyi.production.pojo.ProductionOrder;
import com.ruoyi.production.pojo.ProductionPlan;
import com.ruoyi.production.service.ProductionOrderService;
import com.ruoyi.production.service.ProductionPlanService;
import com.ruoyi.purchase.dto.PurchaseLedgerDto;
import com.ruoyi.purchase.pojo.PurchaseLedger;
import com.ruoyi.purchase.service.IPurchaseLedgerService;
import com.ruoyi.quality.pojo.QualityInspect;
import com.ruoyi.quality.pojo.QualityTestStandard;
import com.ruoyi.quality.pojo.QualityTestStandardBinding;
import com.ruoyi.quality.service.IQualityInspectService;
import com.ruoyi.quality.service.IQualityTestStandardService;
import com.ruoyi.quality.service.QualityTestStandardBindingService;
import com.ruoyi.sales.dto.SalesLedgerDto;
import com.ruoyi.sales.pojo.SalesLedgerProduct;
import com.ruoyi.sales.service.ISalesLedgerService;
import com.ruoyi.stock.dto.StockInventoryDto;
import com.ruoyi.stock.service.StockInRecordService;
import com.ruoyi.stock.service.StockInventoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
 
@Slf4j
@Service
@RequiredArgsConstructor
public class DataGenerateServiceImpl implements DataGenerateService {
 
    private final Assistant assistant;
    private final ProductMapper productMapper;
    private final ProductModelMapper productModelMapper;
 
    private final ICustomerService customerService;
    private final ISalesLedgerService salesLedgerService;
    private final ISupplierService supplierService;
    private final IPurchaseLedgerService purchaseLedgerService;
    private final IQualityTestStandardService qualityTestStandardService;
    private final QualityTestStandardBindingService qualityTestStandardBindingService;
    private final ProductionPlanService productionPlanService;
    private final ProductionOrderService productionOrderService;
    private final StockInventoryService stockInventoryService;
 
    // 采购完整流程需要的service
    private final ApprovalInstanceService approvalInstanceService;
    private final ApprovalInstanceMapper approvalInstanceMapper;
    private final IQualityInspectService qualityInspectService;
    private final StockInRecordService stockInRecordService;
 
    @Override
    public DataGenerateResult generate(DataGenerateRequest request) {
        DataGenerateResult result = new DataGenerateResult();
        List<ModuleSummary> summaries = new ArrayList<>();
        List<String> errors = new ArrayList<>();
        int totalGenerated = 0;
 
        try {
            List<Long> productIds = productMapper.selectList(null).stream()
                    .map(p -> p.getId()).collect(Collectors.toList());
            List<Long> productModelIds = productModelMapper.selectList(null).stream()
                    .map(m -> m.getId()).collect(Collectors.toList());
 
            String systemPrompt = MockDataPrompt.buildSystemPrompt();
            String userMessage = MockDataPrompt.buildUserMessage(
                    request.getModules(), request.getIndustries(),
                    request.getCountMin(), request.getCountMax(),
                    request.getDateStart(), request.getDateEnd(),
                    request.getAdditionalInfo(),
                    productIds, productModelIds);
 
            String fullPrompt = systemPrompt + "\n\n" + userMessage;
            log.info("调用AI生成模拟数据, modules={}, industries={}", request.getModules(), request.getIndustries());
            String llmResponse = assistant.chat(fullPrompt);
            log.info("AI返回数据长度: {}", llmResponse != null ? llmResponse.length() : 0);
 
            if (llmResponse == null || llmResponse.isBlank()) {
                result.setStatus("FAILED");
                errors.add("AI未返回任何数据");
                result.setErrors(errors);
                return result;
            }
 
            List<JSONObject> entities = parseJsonResponse(llmResponse);
            if (entities.isEmpty()) {
                result.setStatus("FAILED");
                errors.add("无法解析AI返回的数据");
                result.setErrors(errors);
                return result;
            }
 
            Map<String, List<JSONObject>> grouped = entities.stream()
                    .collect(Collectors.groupingBy(e -> e.getString("entity")));
 
            // 名称→ID 映射表,用于创建业务单据时回填外键
            Map<String, Long> customerNameToId = new HashMap<>();
            Map<String, Long> supplierNameToId = new HashMap<>();
 
            // Tier 0: 基础数据
            if (grouped.containsKey("customer")) {
                ModuleSummary s = createCustomers(grouped.get("customer"), customerNameToId);
                summaries.add(s);
                totalGenerated += s.getSuccessCount();
            }
            if (grouped.containsKey("supplier")) {
                ModuleSummary s = createSuppliers(grouped.get("supplier"), supplierNameToId);
                summaries.add(s);
                totalGenerated += s.getSuccessCount();
            }
            if (grouped.containsKey("qualityTestStandard")) {
                ModuleSummary s = createQualityStandards(grouped.get("qualityTestStandard"));
                summaries.add(s);
                totalGenerated += s.getSuccessCount();
            }
 
            // Tier 1: 业务单据
            if (grouped.containsKey("salesLedger")) {
                ModuleSummary s = createSalesLedgers(grouped.get("salesLedger"), customerNameToId);
                summaries.add(s);
                totalGenerated += s.getSuccessCount();
            }
            if (grouped.containsKey("purchaseLedger")) {
                ModuleSummary s = createPurchaseLedgers(grouped.get("purchaseLedger"), supplierNameToId,
                        request.getAdditionalInfo(), request.getDateEnd());
                summaries.add(s);
                totalGenerated += s.getSuccessCount();
            }
            if (grouped.containsKey("productionPlan")) {
                ModuleSummary s = createProductionPlans(grouped.get("productionPlan"));
                summaries.add(s);
                totalGenerated += s.getSuccessCount();
            }
 
            // Tier 2
            if (grouped.containsKey("productionOrder")) {
                ModuleSummary s = createProductionOrders(grouped.get("productionOrder"));
                summaries.add(s);
                totalGenerated += s.getSuccessCount();
            }
            if (grouped.containsKey("qualityTestStandardBinding")) {
                ModuleSummary s = createQualityBindings(grouped.get("qualityTestStandardBinding"));
                summaries.add(s);
                totalGenerated += s.getSuccessCount();
            }
            if (grouped.containsKey("stockInventory")) {
                ModuleSummary s = createStockInventories(grouped.get("stockInventory"));
                summaries.add(s);
                totalGenerated += s.getSuccessCount();
            }
 
            result.setStatus(errors.isEmpty() ? "SUCCESS" : "PARTIAL");
            result.setTotalGenerated(totalGenerated);
            result.setModuleSummaries(summaries);
            result.setErrors(errors);
 
        } catch (Exception e) {
            log.error("数据生成失败", e);
            result.setStatus("FAILED");
            errors.add("数据生成异常: " + e.getMessage());
            result.setErrors(errors);
        }
 
        return result;
    }
 
    private List<JSONObject> parseJsonResponse(String response) {
        try {
            String trimmed = response.trim();
            if (trimmed.startsWith("```")) {
                int start = trimmed.indexOf("\n");
                int end = trimmed.lastIndexOf("```");
                if (start > 0 && end > start) {
                    trimmed = trimmed.substring(start + 1, end).trim();
                }
            }
            return JSON.parseArray(trimmed, JSONObject.class);
        } catch (Exception e) {
            log.warn("JSON解析失败,尝试提取数组片段: {}", e.getMessage());
            int start = response.indexOf('[');
            int end = response.lastIndexOf(']');
            if (start >= 0 && end > start) {
                return JSON.parseArray(response.substring(start, end + 1), JSONObject.class);
            }
            return List.of();
        }
    }
 
    // ---- Tier 0: 基础数据 ----
 
    private ModuleSummary createCustomers(List<JSONObject> items, Map<String, Long> nameToId) {
        int success = 0, fail = 0;
        for (JSONObject item : items) {
            try {
                Customer c = new Customer();
                c.setCustomerName(item.getString("customerName"));
                c.setCustomerType(item.getString("customerType"));
                c.setContactPerson(item.getString("contactPerson"));
                c.setContactPhone(item.getString("contactPhone"));
                c.setCompanyAddress(item.getString("companyAddress"));
                c.setCompanyPhone(item.getString("companyPhone"));
                c.setTaxpayerIdentificationNumber(item.getString("taxpayerIdentificationNumber"));
                c.setMaintainer(item.getString("maintainer"));
                if (item.containsKey("maintenanceTime")) {
                    c.setMaintenanceTime(java.sql.Date.valueOf(item.getString("maintenanceTime")));
                } else {
                    c.setMaintenanceTime(new java.sql.Date(System.currentTimeMillis()));
                }
                if (item.containsKey("bankAccount")) {
                    c.setBankAccount(item.getString("bankAccount"));
                }
                if (item.containsKey("basicBankAccount")) {
                    c.setBasicBankAccount(item.getString("basicBankAccount"));
                }
                if (item.containsKey("bankCode")) {
                    c.setBankCode(item.getString("bankCode"));
                }
                customerService.insertCustomer(c);
                if (c.getId() != null) {
                    nameToId.put(c.getCustomerName(), c.getId());
                }
                success++;
            } catch (Exception e) {
                log.warn("创建客户失败: {}", e.getMessage());
                fail++;
            }
        }
        return summary("sales", "客户", items.size(), success, fail);
    }
 
    private ModuleSummary createSuppliers(List<JSONObject> items, Map<String, Long> nameToId) {
        int success = 0, fail = 0;
        for (JSONObject item : items) {
            try {
                SupplierManage s = new SupplierManage();
                s.setSupplierName(item.getString("supplierName"));
                s.setSupplierType(item.getString("supplierType"));
                s.setContactUserName(item.getString("contactUserName"));
                s.setContactUserPhone(item.getString("contactUserPhone"));
                s.setCompanyAddress(item.getString("companyAddress"));
                s.setCompanyPhone(item.getString("companyPhone"));
                s.setTaxpayerIdentificationNum(item.getString("taxpayerIdentificationNum"));
                s.setBankAccountName(item.getString("bankAccountName"));
                s.setBankAccountNum(item.getString("bankAccountNum"));
                if (item.containsKey("isWhite")) {
                    s.setIsWhite(item.getInteger("isWhite"));
                }
                supplierService.saveSupplier(s);
                if (s.getId() != null) {
                    nameToId.put(s.getSupplierName(), s.getId());
                }
                success++;
            } catch (Exception e) {
                log.warn("创建供应商失败: {}", e.getMessage());
                fail++;
            }
        }
        return summary("purchase", "供应商", items.size(), success, fail);
    }
 
    private ModuleSummary createQualityStandards(List<JSONObject> items) {
        int success = 0, fail = 0;
        for (JSONObject item : items) {
            try {
                QualityTestStandard std = new QualityTestStandard();
                std.setStandardNo(item.getString("standardNo"));
                std.setStandardName(item.getString("standardName"));
                std.setInspectType(item.getInteger("inspectType"));
                std.setRemark(item.getString("remark"));
                qualityTestStandardService.save(std);
                success++;
            } catch (Exception e) {
                log.warn("创建检测标准失败: {}", e.getMessage());
                fail++;
            }
        }
        return summary("quality", "检测标准", items.size(), success, fail);
    }
 
    // ---- Tier 1: 业务单据 ----
 
    private ModuleSummary createSalesLedgers(List<JSONObject> items, Map<String, Long> customerNameToId) {
        int success = 0, fail = 0;
        for (JSONObject item : items) {
            try {
                String customerName = item.getString("customerName");
                Long customerId = customerNameToId.get(customerName);
 
                SalesLedgerDto dto = new SalesLedgerDto();
                dto.setCustomerId(customerId);
                dto.setCustomerName(customerName);
                dto.setProjectName(item.getString("projectName"));
                dto.setSalesman(item.getString("salesman"));
                dto.setPaymentMethod(item.getString("paymentMethod"));
                dto.setType(item.getInteger("type"));
                // 录入人:优先使用AI提供的数据,否则用当前登录用户
                if (item.containsKey("entryPerson")) {
                    dto.setEntryPerson(item.getString("entryPerson"));
                }
                if (item.containsKey("entryDate")) {
                    dto.setEntryDate(java.sql.Date.valueOf(item.getString("entryDate")));
                }
                if (item.containsKey("executionDate")) {
                    dto.setExecutionDate(LocalDate.parse(item.getString("executionDate")));
                }
                if (item.containsKey("deliveryDate")) {
                    dto.setDeliveryDate(LocalDate.parse(item.getString("deliveryDate")));
                }
                JSONArray productData = item.getJSONArray("productData");
                if (productData != null) {
                    List<SalesLedgerProduct> products = new ArrayList<>();
                    for (int i = 0; i < productData.size(); i++) {
                        JSONObject pd = productData.getJSONObject(i);
                        SalesLedgerProduct slp = new SalesLedgerProduct();
                        slp.setProductId(pd.getLong("productId"));
                        slp.setProductModelId(pd.getLong("productModelId"));
                        slp.setQuantity(pd.getBigDecimal("quantity"));
                        slp.setTaxInclusiveUnitPrice(pd.getBigDecimal("taxInclusiveUnitPrice"));
                        slp.setTaxInclusiveTotalPrice(pd.getBigDecimal("taxInclusiveTotalPrice"));
                        slp.setTaxRate(pd.getBigDecimal("taxRate"));
                        slp.setUnit(pd.getString("unit"));
                        slp.setType(pd.getInteger("type"));
                        if (pd.containsKey("taxExclusiveTotalPrice")) {
                            slp.setTaxExclusiveTotalPrice(pd.getBigDecimal("taxExclusiveTotalPrice"));
                        } else if (pd.getBigDecimal("taxInclusiveTotalPrice") != null && pd.getBigDecimal("taxRate") != null) {
                            // 不含税总价 = 含税总价 / (1 + 税率/100)
                            slp.setTaxExclusiveTotalPrice(
                                pd.getBigDecimal("taxInclusiveTotalPrice").divide(
                                    BigDecimal.ONE.add(pd.getBigDecimal("taxRate").divide(new BigDecimal("100"), 4, RoundingMode.HALF_UP)),
                                    2, RoundingMode.HALF_UP));
                        } else {
                            slp.setTaxExclusiveTotalPrice(BigDecimal.ZERO);
                        }
                        products.add(slp);
                    }
                    dto.setProductData(products);
                }
                salesLedgerService.addOrUpdateSalesLedger(dto);
                success++;
            } catch (Exception e) {
                log.warn("创建销售台账失败: {}", e.getMessage());
                fail++;
            }
        }
        return summary("sales", "销售台账", items.size(), success, fail);
    }
 
    private ModuleSummary createPurchaseLedgers(List<JSONObject> items, Map<String, Long> supplierNameToId,
                                                 String additionalInfo, String dateEnd) {
        // 是否需要质检,从补充信息判断,默认不需要
        boolean needQualityInspect = additionalInfo != null
                && (additionalInfo.contains("质检") || additionalInfo.contains("需要检验"));
        int success = 0, fail = 0;
        for (JSONObject item : items) {
            try {
                String supplierName = item.getString("supplierName");
                Long supplierId = supplierNameToId.get(supplierName);
 
                PurchaseLedgerDto dto = new PurchaseLedgerDto();
                dto.setSupplierId(supplierId);
                dto.setSupplierName(supplierName);
                dto.setPurchaseContractNumber(item.getString("purchaseContractNumber"));
                dto.setProjectName(item.getString("projectName"));
                dto.setContractAmount(item.getBigDecimal("contractAmount"));
                dto.setPaymentMethod(item.getString("paymentMethod"));
 
                String entryDateStr = item.getString("entryDate");
                LocalDate entryDate = null;
                if (item.containsKey("entryDate")) {
                    entryDate = LocalDate.parse(entryDateStr);
                    dto.setEntryDate(java.sql.Date.valueOf(entryDateStr));
                }
                if (item.containsKey("executionDate")) {
                    dto.setExecutionDate(java.sql.Date.valueOf(item.getString("executionDate")));
                }
                JSONArray productData = item.getJSONArray("productData");
                if (productData != null) {
                    List<SalesLedgerProduct> products = new ArrayList<>();
                    for (int i = 0; i < productData.size(); i++) {
                        JSONObject pd = productData.getJSONObject(i);
                        SalesLedgerProduct slp = new SalesLedgerProduct();
                        slp.setProductId(pd.getLong("productId"));
                        slp.setProductModelId(pd.getLong("productModelId"));
                        slp.setQuantity(pd.getBigDecimal("quantity"));
                        slp.setTaxInclusiveUnitPrice(pd.getBigDecimal("taxInclusiveUnitPrice"));
                        slp.setTaxInclusiveTotalPrice(pd.getBigDecimal("taxInclusiveTotalPrice"));
                        slp.setTaxRate(pd.getBigDecimal("taxRate"));
                        slp.setUnit(pd.getString("unit"));
                        slp.setType(2);
                        // 是否质检:从补充信息判断,默认不需要
                        slp.setIsChecked(needQualityInspect);
                        if (pd.containsKey("taxExclusiveTotalPrice")) {
                            slp.setTaxExclusiveTotalPrice(pd.getBigDecimal("taxExclusiveTotalPrice"));
                        } else if (pd.getBigDecimal("taxInclusiveTotalPrice") != null && pd.getBigDecimal("taxRate") != null) {
                            slp.setTaxExclusiveTotalPrice(
                                pd.getBigDecimal("taxInclusiveTotalPrice").divide(
                                    BigDecimal.ONE.add(pd.getBigDecimal("taxRate").divide(new BigDecimal("100"), 4, RoundingMode.HALF_UP)),
                                    2, RoundingMode.HALF_UP));
                        } else {
                            slp.setTaxExclusiveTotalPrice(BigDecimal.ZERO);
                        }
                        products.add(slp);
                    }
                    dto.setProductData(products);
                }
                purchaseLedgerService.addOrEditPurchase(dto);
                // 通过合同号找到刚创建的采购台账
                PurchaseLedger savedLedger = purchaseLedgerService.getOne(
                        new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<PurchaseLedger>()
                                .eq(PurchaseLedger::getPurchaseContractNumber, dto.getPurchaseContractNumber())
                                .last("limit 1"));
                if (savedLedger != null) {
                    // 走完整流程:审核通过 → 质检(可选) → 入库 + 入库审核通过
                    processPurchaseFullFlow(savedLedger, needQualityInspect, entryDate, dateEnd);
                }
                success++;
            } catch (Exception e) {
                log.warn("创建采购台账失败: {}", e.getMessage());
                fail++;
            }
        }
        return summary("purchase", "采购台账", items.size(), success, fail);
    }
 
    /**
     * 采购完整流程: 审核通过 → 质检(可选) → 入库审核通过
     */
    private void processPurchaseFullFlow(PurchaseLedger purchaseLedger, boolean needQualityInspect,
                                          LocalDate entryDate, String dateEnd) {
        try {
            // 1. 审批自动通过
            ApprovalInstance approvalInstance = approvalInstanceMapper.selectOne(
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ApprovalInstance>()
                            .eq(ApprovalInstance::getBusinessId, purchaseLedger.getId())
                            .eq(ApprovalInstance::getBusinessType, 5L)
                            .eq(ApprovalInstance::getDeleted, 0)
                            .orderByDesc(ApprovalInstance::getId)
                            .last("limit 1"));
            if (approvalInstance != null) {
                // 结算审批开始时间:基于录入日期,随机推0-3天
                LocalDate baseDate = entryDate != null ? entryDate : LocalDate.now();
                LocalDate approveDate = baseDate.plusDays(ThreadLocalRandom.current().nextInt(0, 4));
                // 使用autoApprove完成审批
                approvalInstanceService.autoApprove(approvalInstance.getId());
                log.info("采购台账[{}]审批通过, 审批日期: {}", purchaseLedger.getPurchaseContractNumber(), approveDate);
            }
 
            // 2. 质检流程(如果需要质检)
            if (needQualityInspect) {
                processQualityInspect(purchaseLedger, entryDate, dateEnd);
            }
 
            // 3. 入库审批通过
            processStockInApprove(purchaseLedger, dateEnd);
 
        } catch (Exception e) {
            log.warn("采购完整流程处理失败[{}]: {}", purchaseLedger.getPurchaseContractNumber(), e.getMessage());
        }
    }
 
    /**
     * 质检: 找到采购关联的质检单,自动提交为合格
     */
    private void processQualityInspect(PurchaseLedger purchaseLedger, LocalDate entryDate, String dateEnd) {
        try {
            List<QualityInspect> inspectList = qualityInspectService.list(
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<QualityInspect>()
                            .eq(QualityInspect::getPurchaseLedgerId, purchaseLedger.getId()));
            for (QualityInspect qi : inspectList) {
                if (qi.getInspectState() == null || qi.getInspectState() == 0) {
                    qualityInspectService.autoSubmit(qi.getId());
                    log.info("采购台账[{}]质检单[{}]自动提交合格", purchaseLedger.getPurchaseContractNumber(), qi.getId());
                }
            }
        } catch (Exception e) {
            log.warn("质检流程处理失败[{}]: {}", purchaseLedger.getPurchaseContractNumber(), e.getMessage());
        }
    }
 
    /**
     * 入库审核: 找到入库记录并审批通过
     */
    private void processStockInApprove(PurchaseLedger purchaseLedger, String dateEnd) {
        try {
            List<com.ruoyi.stock.pojo.StockInRecord> stockRecords = stockInRecordService.list(
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<com.ruoyi.stock.pojo.StockInRecord>()
                            .eq(com.ruoyi.stock.pojo.StockInRecord::getRecordId, purchaseLedger.getId())
                            .eq(com.ruoyi.stock.pojo.StockInRecord::getRecordType,
                                    String.valueOf(com.ruoyi.common.enums.StockInQualifiedRecordTypeEnum.PURCHASE_STOCK_IN.getCode())));
            // 如果按PURCHASE_STOCK_IN找不到,尝试CUSTOMIZATION_UNSTOCK_OUT(质检合格入库)
            if (stockRecords.isEmpty()) {
                stockRecords = stockInRecordService.list(
                        new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<com.ruoyi.stock.pojo.StockInRecord>()
                                .eq(com.ruoyi.stock.pojo.StockInRecord::getRecordId, purchaseLedger.getId())
                                .eq(com.ruoyi.stock.pojo.StockInRecord::getRecordType,
                                        String.valueOf(com.ruoyi.common.enums.StockInQualifiedRecordTypeEnum.CUSTOMIZATION_UNSTOCK_OUT.getCode())));
            }
            // 也尝试按质检单ID查找(质检单的recordId是质检单ID)
            for (QualityInspect qi : qualityInspectService.list(
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<QualityInspect>()
                            .eq(QualityInspect::getPurchaseLedgerId, purchaseLedger.getId()))) {
                List<com.ruoyi.stock.pojo.StockInRecord> qiRecords = stockInRecordService.list(
                        new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<com.ruoyi.stock.pojo.StockInRecord>()
                                .eq(com.ruoyi.stock.pojo.StockInRecord::getRecordId, qi.getId()));
                stockRecords.addAll(qiRecords);
            }
            // 去重
            stockRecords = stockRecords.stream()
                    .collect(Collectors.toMap(com.ruoyi.stock.pojo.StockInRecord::getId, r -> r, (a, b) -> a))
                    .values().stream().collect(Collectors.toList());
 
            if (!stockRecords.isEmpty()) {
                List<Long> recordIds = stockRecords.stream()
                        .filter(r -> r.getApprovalStatus() == null || r.getApprovalStatus() == 0)
                        .map(com.ruoyi.stock.pojo.StockInRecord::getId)
                        .collect(Collectors.toList());
                if (!recordIds.isEmpty()) {
                    stockInRecordService.batchApprove(recordIds, ReviewStatusEnum.APPROVED.getCode());
                    log.info("采购台账[{}]入库审批通过, 入库记录数: {}", purchaseLedger.getPurchaseContractNumber(), recordIds.size());
                }
            }
        } catch (Exception e) {
            log.warn("入库审批失败[{}]: {}", purchaseLedger.getPurchaseContractNumber(), e.getMessage());
        }
    }
 
    private ModuleSummary createProductionPlans(List<JSONObject> items) {
        int success = 0, fail = 0;
        for (JSONObject item : items) {
            try {
                ProductionPlan plan = new ProductionPlan();
                plan.setProductModelId(item.getLong("productModelId"));
                plan.setQtyRequired(item.getBigDecimal("qtyRequired"));
                plan.setSource(item.getString("source"));
                plan.setRemark(item.getString("remark"));
                if (item.containsKey("requiredDate")) {
                    plan.setRequiredDate(LocalDate.parse(item.getString("requiredDate")));
                }
                if (item.containsKey("promisedDeliveryDate")) {
                    plan.setPromisedDeliveryDate(LocalDate.parse(item.getString("promisedDeliveryDate")));
                }
                productionPlanService.save(plan);
                success++;
            } catch (Exception e) {
                log.warn("创建生产计划失败: {}", e.getMessage());
                fail++;
            }
        }
        return summary("production", "生产计划", items.size(), success, fail);
    }
 
    // ---- Tier 2: 后续单据 ----
 
    private ModuleSummary createProductionOrders(List<JSONObject> items) {
        int success = 0, fail = 0;
        for (JSONObject item : items) {
            try {
                ProductionOrder order = new ProductionOrder();
                order.setProductModelId(item.getLong("productModelId"));
                order.setQuantity(item.getBigDecimal("quantity"));
                if (item.containsKey("planCompleteTime")) {
                    order.setPlanCompleteTime(LocalDate.parse(item.getString("planCompleteTime")));
                }
                productionOrderService.saveProductionOrder(order);
                success++;
            } catch (Exception e) {
                log.warn("创建生产订单失败: {}", e.getMessage());
                fail++;
            }
        }
        return summary("production", "生产订单", items.size(), success, fail);
    }
 
    private ModuleSummary createQualityBindings(List<JSONObject> items) {
        int success = 0, fail = 0;
        for (JSONObject item : items) {
            try {
                QualityTestStandardBinding binding = new QualityTestStandardBinding();
                binding.setProductId(item.getLong("productId"));
                binding.setTestStandardId(item.getInteger("testStandardId"));
                qualityTestStandardBindingService.add(List.of(binding));
                success++;
            } catch (Exception e) {
                log.warn("创建指标绑定失败: {}", e.getMessage());
                fail++;
            }
        }
        return summary("quality", "指标绑定", items.size(), success, fail);
    }
 
    private ModuleSummary createStockInventories(List<JSONObject> items) {
        int success = 0, fail = 0;
        for (JSONObject item : items) {
            try {
                StockInventoryDto dto = new StockInventoryDto();
                dto.setProductModelId(item.getLong("productModelId"));
                dto.setQualitity(item.getBigDecimal("qualitity"));
                dto.setBatchNo(item.getString("batchNo"));
                dto.setWarnNum(item.getBigDecimal("warnNum"));
                dto.setRemark(item.getString("remark"));
                stockInventoryService.addstockInventory(dto);
                success++;
            } catch (Exception e) {
                log.warn("创建库存记录失败: {}", e.getMessage());
                fail++;
            }
        }
        return summary("stock", "库存记录", items.size(), success, fail);
    }
 
    private ModuleSummary summary(String module, String entityName, int total, int success, int fail) {
        ModuleSummary s = new ModuleSummary();
        s.setModule(module);
        s.setEntityName(entityName);
        s.setGeneratedCount(total);
        s.setSuccessCount(success);
        s.setFailCount(fail);
        return s;
    }
}