zss
16 小时以前 ff6630afee64bd2def82e09a20896e9089f959b9
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
package com.ruoyi.approve.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.approve.mapper.ApproveNodeMapper;
import com.ruoyi.approve.mapper.ApproveProcessMapper;
import com.ruoyi.approve.pojo.ApproveNode;
import com.ruoyi.approve.pojo.ApproveProcess;
import com.ruoyi.approve.service.IApproveNodeService;
import com.ruoyi.approve.service.IApproveProcessService;
import com.ruoyi.approve.utils.DailyRedisCounter;
import com.ruoyi.approve.vo.ApproveGetAndUpdateVo;
import com.ruoyi.approve.vo.ApproveProcessVO;
import com.ruoyi.common.enums.FileNameType;
import com.ruoyi.common.utils.OrderUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.other.service.impl.TempFileServiceImpl;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysNotice;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysDeptMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.service.ISysNoticeService;
import com.ruoyi.purchase.mapper.PurchaseLedgerMapper;
import com.ruoyi.purchase.pojo.PurchaseLedger;
import com.ruoyi.quality.mapper.QualityInspectMapper;
import com.ruoyi.quality.pojo.QualityInspect;
import com.ruoyi.sales.mapper.CommonFileMapper;
import com.ruoyi.sales.mapper.SalesLedgerProductMapper;
import com.ruoyi.sales.mapper.ShippingInfoMapper;
import com.ruoyi.sales.mapper.SalesLedgerMapper;
import com.ruoyi.sales.pojo.SalesLedger;
import com.ruoyi.sales.pojo.SalesLedgerProduct;
import com.ruoyi.sales.pojo.CommonFile;
import com.ruoyi.sales.pojo.ShippingInfo;
import com.ruoyi.sales.service.impl.CommonFileServiceImpl;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
 
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
 
@Service
//@RequiredArgsConstructor
public class ApproveProcessServiceImpl extends ServiceImpl<ApproveProcessMapper, ApproveProcess> implements IApproveProcessService {
    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd");
 
    @Autowired
    private  StringRedisTemplate redisTemplate;
    @Autowired
    private  DailyRedisCounter dailyRedisCounter;
    @Autowired
    private  SysDeptMapper sysDeptMapper;
    @Autowired
    private  IApproveNodeService approveNodeService;
    @Autowired
    private  SysUserMapper sysUserMapper;
    @Autowired
    private  ApproveProcessMapper approveProcessMapper;
    @Autowired
    private  TempFileServiceImpl tempFileService;
    @Autowired
    private  CommonFileMapper commonFileMapper;
    @Autowired
    private  CommonFileServiceImpl commonFileService;
    @Autowired
    private  ISysNoticeService sysNoticeService;
 
    @Autowired
    private SalesLedgerMapper salesLedgerMapper;
 
    @Override
    public void addApprove(ApproveProcessVO approveProcessVO) throws Exception {
        SysUser sysUser = sysUserMapper.selectUserById(approveProcessVO.getApproveUser());
        SysDept sysDept = sysDeptMapper.selectDeptById(approveProcessVO.getApproveDeptId());
        String[] split = approveProcessVO.getApproveUserIds().split(",");
        List<Long> longList = Arrays.stream(split)
                .map(Long::valueOf)  // 将每个 String 转换为 Long
                .collect(Collectors.toList());
        List<SysUser> sysUsers = sysUserMapper.selectUserByIds(longList);
        if (CollectionUtils.isEmpty(sysUsers)) throw new RuntimeException("审核用户不存在");
        if (sysDept == null) throw new RuntimeException("部门不存在");
        if (sysUser == null) throw new RuntimeException("申请人不存在");
        String today = LocalDate.now().format(DATE_FORMAT);
        Long approveId = dailyRedisCounter.incrementAndGetByDb();
        String formattedCount = String.format("%03d", approveId);
        //流程 ID
        String approveID = today + formattedCount;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        ApproveProcess approveProcess = new ApproveProcess();
        approveProcess.setApproveId(approveID);
        approveProcess.setApproveUser(approveProcessVO.getApproveUser());
        approveProcess.setApproveUserName(sysUser.getNickName());
        approveProcess.setApproveDeptId(approveProcessVO.getApproveDeptId());
        approveProcess.setApproveDeptName(sysDept.getDeptName());
        approveProcess.setApproveUserNames(sysUsers.stream().map(SysUser::getNickName).collect(Collectors.joining(",")));
        approveProcess.setApproveTime(StringUtils.isEmpty(approveProcessVO.getApproveTime()) ? null : dateFormat.parse(approveProcessVO.getApproveTime()));
        approveProcess.setApproveReason(approveProcessVO.getApproveReason());
        approveProcess.setApproveRemark(approveProcessVO.getApproveRemark());
        approveProcess.setDeviceRepairId(approveProcessVO.getDeviceRepairId());
        approveProcess.setMaintenancePrice(approveProcessVO.getMaintenancePrice());
        approveProcess.setPrice(approveProcessVO.getPrice());
        approveProcess.setStartDate(approveProcessVO.getStartDate());
        approveProcess.setEndDate(approveProcessVO.getEndDate());
        approveProcess.setApproveStatus(0);
        approveProcess.setApproveDelete(0);
        approveProcess.setApproveType(approveProcessVO.getApproveType());
        approveProcess.setCreateTime(LocalDateTime.now());
        approveProcess.setTenantId(approveProcessVO.getApproveDeptId());
        approveProcess.setApproveUserIds(approveProcessVO.getApproveUserIds());
        approveProcess.setApproveUserCurrentId(longList.get(0));
        approveProcess.setApproveUserCurrentName(sysUsers
                .stream()
                .filter(SysUser -> SysUser.getUserId().equals(longList.get(0)))
                .collect(Collectors.toList())
                .get(0)
                .getNickName());
        // 设置状态为重新提交
        if (approveProcessVO.getId() != null) {
            ApproveProcess approveProcess1 = approveProcessMapper.selectById(approveProcessVO.getId());
            approveProcess1.setApproveStatus(4);
            approveProcessMapper.updateById(approveProcess1);
        }
        save(approveProcess);
        //初始化审批节点
        approveNodeService.initApproveNodes(approveProcessVO.getApproveUserIds(), approveID, approveProcessVO.getApproveDeptId());
        // 附件绑定
        tempFileService.migrateTempFilesToFormal(approveProcess.getId(), approveProcessVO.getTempFileIds(), FileNameType.ApproveProcess.getValue());
        /*消息通知*/
        String id = approveProcessVO.getApproveUserIds().split(",")[0];
        if (approveProcess.getApproveType()==8){
            sysNoticeService.simpleNoticeByUser(approveProcessType(approveProcess.getApproveType()),
                    approveProcess.getApproveId() + "流程编号的审批需要您审核!!!!!",
                    Arrays.asList(Long.valueOf(id)),
                    "/safeProduction/safeWorkApproval?approveType=" + approveProcess.getApproveType() + "&approveId=" + approveProcess.getApproveId());
        }else {
            sysNoticeService.simpleNoticeByUser(approveProcessType(approveProcess.getApproveType()),
                    approveProcess.getApproveId() + "流程编号的审批需要您审核!!!!!",
                    Arrays.asList(Long.valueOf(id)),
                    "/collaborativeApproval/approvalProcess?approveType=" + approveProcess.getApproveType() + "&approveId=" + approveProcess.getApproveId());
        }
    }
 
    @Override
    public List<SysDept> selectDeptListByDeptIds(Long[] deptIds) {
        List<SysDept> sysDeptList = new ArrayList<SysDept>();
        for (Long deptId : deptIds) {
            SysDept sysDept = sysDeptMapper.selectDeptById(deptId);
            sysDeptList.add(sysDept);
        }
        return sysDeptList;
    }
 
    @Autowired
    private PurchaseLedgerMapper purchaseLedgerMapper;
 
    @Autowired
    private ShippingInfoMapper shippingInfoMapper;
 
    @Autowired
    private SalesLedgerProductMapper salesLedgerProductMapper;
 
    @Autowired
    private QualityInspectMapper qualityInspectMapper;
 
    @Override
    public IPage<ApproveProcess> listAll(Page page, ApproveProcess approveProcess) {
        IPage<ApproveProcess> approveProcessIPage = approveProcessMapper.listPage(page, approveProcess);
        List<ApproveProcess> records = approveProcessIPage.getRecords();
 
        for (ApproveProcess record : records) {
            List<CommonFile> allFiles = new ArrayList<>();
 
            //  采购审批查询
            if (record.getApproveType() == 5) {
                String contractNo = record.getApproveReason();
                PurchaseLedger ledger = purchaseLedgerMapper.selectOne(new LambdaQueryWrapper<PurchaseLedger>()
                        .eq(PurchaseLedger::getPurchaseContractNumber, contractNo)
                        .last("limit 1"));
 
                if (ledger != null) {
                    allFiles = commonFileMapper.selectList(new LambdaQueryWrapper<CommonFile>()
                            .eq(CommonFile::getCommonId, ledger.getId())
                            .eq(CommonFile::getType, FileNameType.PURCHASE.getValue()));
                }
            }
 
            //  发货审批查询
            else if (record.getApproveType() == 7) {
                String reason = record.getApproveReason(); // 格式为 "xx:CONTRACT_NO"
                if (StringUtils.hasText(reason) && reason.contains(":")) {
                    // 提取冒号后面的标识符 (可能是合同号或发货单号)
                    String identifier = reason.split(":")[1];
                    // 1. 优先尝试找销售台账 (新逻辑:合同号同步审批)
                    SalesLedger ledger = salesLedgerMapper.selectOne(new LambdaQueryWrapper<SalesLedger>()
                            .eq(SalesLedger::getSalesContractNo, identifier)
                            .last("limit 1"));
                    if (ledger != null) {
                        allFiles = commonFileMapper.selectList(new LambdaQueryWrapper<CommonFile>()
                                .eq(CommonFile::getCommonId, ledger.getId())
                                .eq(CommonFile::getType, FileNameType.SALE.getValue()));
                    } else {
                        // 2. 回退到旧逻辑:发货单号
                        ShippingInfo shippingInfo = shippingInfoMapper.selectOne(new LambdaQueryWrapper<ShippingInfo>()
                                .eq(ShippingInfo::getShippingNo, identifier)
                                .last("limit 1"));
                        if (shippingInfo != null) {
                            allFiles = commonFileMapper.selectList(new LambdaQueryWrapper<CommonFile>()
                                    .eq(CommonFile::getCommonId, shippingInfo.getSalesLedgerId())
                                    .eq(CommonFile::getType, FileNameType.SALE.getValue()));
                        }
                    }
                }
            }
 
            //  查询审批单自身的附件
            else {
                allFiles = commonFileMapper.selectList(new LambdaQueryWrapper<CommonFile>()
                        .eq(CommonFile::getCommonId, record.getId())
                        .eq(CommonFile::getType, FileNameType.ApproveProcess.getValue()));
            }
 
            record.setCommonFileList(allFiles);
        }
        return approveProcessIPage;
    }
 
    public void delByIds(List<Long> ids) {
        for (Long approveId : ids) {
 
            //  逻辑删除审批流程
            update(new UpdateWrapper<ApproveProcess>()
                    .lambda()
                    .set(ApproveProcess::getApproveDelete, 1)
                    .eq(ApproveProcess::getId, approveId));
            // 删除对应的附件
            commonFileService.deleteByBusinessId(approveId, FileNameType.ApproveProcess.getValue());
            ApproveProcess approveProcess = approveProcessMapper.selectById(approveId);
 
            //  删除审批节点
            approveNodeService.delApproveNodeByApproveId(approveProcess.getApproveId());
 
            //  只查最新一条审批流程
            ApproveProcess latestProcess = approveProcessMapper.selectOne(
                    new LambdaQueryWrapper<ApproveProcess>()
                            .eq(ApproveProcess::getApproveId, approveId)
                            .orderByDesc(ApproveProcess::getCreateTime)
                            .last("LIMIT 1"));
 
            if (latestProcess == null) {
                continue;
            }
 
 
            //  删除对应的消息通知
            sysNoticeService.remove(new LambdaQueryWrapper<SysNotice>()
                    .eq(SysNotice::getNoticeTitle, approveProcessType(latestProcess.getApproveType()))
                    .eq(SysNotice::getSenderId, latestProcess.getApproveUser())
                    .apply("CAST(notice_content AS CHAR) LIKE CONCAT('%', {0}, '%')", latestProcess.getApproveId()));
        }
 
    }
 
    @Override
    public void delApprove(List<Long> ids) {
        for (Long approveId : ids) {
            ApproveProcess approveProcess = approveProcessMapper.selectOne(new LambdaQueryWrapper<ApproveProcess>()
                    .eq(ApproveProcess::getApproveId, approveId)
                    .eq(ApproveProcess::getApproveDelete, 0)
                    .last("LIMIT 1"));
            //  逻辑删除审批流程
            update(new UpdateWrapper<ApproveProcess>()
                    .lambda()
                    .set(ApproveProcess::getApproveDelete, 1)
                    .eq(ApproveProcess::getApproveId, approveId));
            // 删除对应的附件
            commonFileService.deleteByBusinessId(approveProcess.getId(), FileNameType.ApproveProcess.getValue());
            //  删除审批节点
            approveNodeService.delApproveNodeByApproveId(approveId.toString());
 
            //  只查最新一条审批流程
            ApproveProcess latestProcess = approveProcessMapper.selectOne(
                    new LambdaQueryWrapper<ApproveProcess>()
                            .eq(ApproveProcess::getApproveId, approveId)
                            .orderByDesc(ApproveProcess::getCreateTime)
                            .last("LIMIT 1"));
 
            if (latestProcess == null) {
                continue;
            }
 
            //  删除对应的消息通知
            sysNoticeService.remove(new LambdaQueryWrapper<SysNotice>()
                            .eq(SysNotice::getNoticeTitle, approveProcessType(latestProcess.getApproveType()))
                            .eq(SysNotice::getSenderId, latestProcess.getApproveUser())
                            .apply("CAST(notice_content AS CHAR) LIKE CONCAT('%', {0}, '%')", latestProcess.getApproveId()));
        }
 
    }
 
    @Override
    public ApproveProcess getApproveById(String id) {
        ApproveProcess one = approveProcessMapper.selectList(Wrappers.<ApproveProcess>lambdaQuery()
                .eq(ApproveProcess::getApproveId,id)
                .eq(ApproveProcess::getApproveDelete,0)).get(0);
        one.setCommonFileList(commonFileMapper.selectList(new LambdaQueryWrapper<CommonFile>()
                .eq(CommonFile::getCommonId, one.getId())
                .eq(CommonFile::getType, FileNameType.ApproveProcess.getValue())));
        return one;
    }
 
    @Override
    public Map<String, Object> getStockInOrderInfo(String approveId) {
        ApproveProcess approveProcess = getStockInApproveProcess(approveId);
        StockInBusinessContext context = parseStockInContext(approveProcess);
        if (context == null) {
            throw new RuntimeException("当前审批单未绑定入库业务数据");
        }
        Map<String, Object> result = new HashMap<>();
        result.put("approveId", approveProcess.getApproveId());
        result.put("approveType", approveProcess.getApproveType());
        result.put("businessType", context.businessType);
        if (context.purchaseLedgerId != null) {
            PurchaseLedger purchaseLedger = purchaseLedgerMapper.selectById(context.purchaseLedgerId);
            if (purchaseLedger == null) {
                throw new RuntimeException("关联采购订单不存在");
            }
            result.put("orderInfo", purchaseLedger);
            return result;
        }
        if (context.salesLedgerId != null) {
            SalesLedger salesLedger = salesLedgerMapper.selectById(context.salesLedgerId);
            if (salesLedger == null) {
                throw new RuntimeException("关联销售订单不存在");
            }
            result.put("orderInfo", salesLedger);
            return result;
        }
        throw new RuntimeException("未解析到订单信息");
    }
 
    @Override
    public List<?> getStockInProductList(String approveId) {
        ApproveProcess approveProcess = getStockInApproveProcess(approveId);
        StockInBusinessContext context = parseStockInContext(approveProcess);
        if (context == null) {
            throw new RuntimeException("当前审批单未绑定入库产品数据");
        }
        List<SalesLedgerProduct> matchedProducts;
        if (context.purchaseLedgerId != null) {
            matchedProducts = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>()
                    .eq(SalesLedgerProduct::getSalesLedgerId, context.purchaseLedgerId)
                    .eq(SalesLedgerProduct::getType, 2)
                    .orderByAsc(SalesLedgerProduct::getId));
            return matchedProducts;
        }
        if (context.salesLedgerId != null) {
            LambdaQueryWrapper<SalesLedgerProduct> wrapper = new LambdaQueryWrapper<SalesLedgerProduct>()
                    .eq(SalesLedgerProduct::getSalesLedgerId, context.salesLedgerId)
                    .eq(SalesLedgerProduct::getType, 1)
                    .orderByAsc(SalesLedgerProduct::getId);
            if (!context.productIds.isEmpty()) {
                wrapper.in(SalesLedgerProduct::getId, context.productIds);
            }
            matchedProducts = salesLedgerProductMapper.selectList(wrapper);
            attachRequestedQty(matchedProducts, context);
            return matchedProducts;
        }
        if (!context.productIds.isEmpty()) {
            matchedProducts = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>()
                    .in(SalesLedgerProduct::getId, context.productIds)
                    .orderByAsc(SalesLedgerProduct::getId));
            attachRequestedQty(matchedProducts, context);
            return matchedProducts;
        }
        return Collections.emptyList();
    }
 
    private ApproveProcess getStockInApproveProcess(String approveId) {
        if (!StringUtils.hasText(approveId)) {
            throw new RuntimeException("审批编号不能为空");
        }
        ApproveProcess approveProcess = approveProcessMapper.selectOne(new LambdaQueryWrapper<ApproveProcess>()
                .eq(ApproveProcess::getApproveId, approveId)
                .eq(ApproveProcess::getApproveDelete, 0)
                .orderByDesc(ApproveProcess::getCreateTime)
                .last("limit 1"));
        if (approveProcess == null) {
            throw new RuntimeException("审批单不存在");
        }
        if (!Objects.equals(approveProcess.getApproveType(), 9)) {
            throw new RuntimeException("当前审批单不是入库审批");
        }
        return approveProcess;
    }
 
    private StockInBusinessContext parseStockInContext(ApproveProcess approveProcess) {
        if (approveProcess == null) {
            return null;
        }
        String remark = approveProcess.getApproveRemark();
        if (StringUtils.hasText(remark) && remark.startsWith("qualityQualifiedInbound:")) {
            String[] split = remark.split(":");
            if (split.length >= 3) {
                StockInBusinessContext context = new StockInBusinessContext();
                context.businessType = "PURCHASE_QUALITY";
                context.purchaseLedgerId = parseLongSafely(split[2]);
                return context;
            }
        }
        if (StringUtils.hasText(remark) && remark.startsWith("salesStock:")) {
            String[] split = remark.split(":");
            if (split.length >= 3) {
                StockInBusinessContext context = new StockInBusinessContext();
                context.businessType = "SALES_STOCK";
                context.salesLedgerId = parseLongSafely(split[1]);
                context.productIds = Arrays.stream(split[2].split(","))
                        .filter(StringUtils::hasText)
                        .map(this::parseLongSafely)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
                return context;
            }
        }
        if (StringUtils.hasText(remark) && (remark.startsWith("scanQualified:") || remark.startsWith("scanUnqualified:"))) {
            String[] split = remark.split(":");
            if (split.length >= 3) {
                StockInBusinessContext context = new StockInBusinessContext();
                context.businessType = remark.startsWith("scanQualified:") ? "SALES_SCAN_QUALIFIED" : "SALES_SCAN_UNQUALIFIED";
                context.salesLedgerId = parseLongSafely(split[1]);
                parseProductLineQty(split[2], context);
                return context;
            }
        }
        String reason = approveProcess.getApproveReason();
        if (!StringUtils.hasText(reason)) {
            return null;
        }
        if (reason.startsWith("原材料质检入库审批:")) {
            String[] split = reason.split(":");
            if (split.length >= 3) {
                StockInBusinessContext context = new StockInBusinessContext();
                context.businessType = "PURCHASE_QUALITY";
                context.purchaseLedgerId = parseLongSafely(split[2]);
                return context;
            }
            if (split.length >= 2) {
                Long inspectId = parseLongSafely(split[1]);
                if (inspectId != null) {
                    QualityInspect inspect = qualityInspectMapper.selectById(inspectId);
                    if (inspect != null) {
                        StockInBusinessContext context = new StockInBusinessContext();
                        context.businessType = "PURCHASE_QUALITY";
                        context.purchaseLedgerId = inspect.getPurchaseLedgerId();
                        return context;
                    }
                }
            }
        }
        if (reason.startsWith("入库审批:")) {
            String[] split = reason.split(":");
            if (split.length >= 4) {
                StockInBusinessContext context = new StockInBusinessContext();
                context.businessType = "SALES_STOCK";
                context.salesLedgerId = parseLongSafely(split[2]);
                context.productIds = Arrays.stream(split[3].split(","))
                        .filter(StringUtils::hasText)
                        .map(this::parseLongSafely)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
                return context;
            }
        }
        return null;
    }
 
    private void parseProductLineQty(String lines, StockInBusinessContext context) {
        if (!StringUtils.hasText(lines) || context == null) {
            return;
        }
        String[] items = lines.split(",");
        for (String item : items) {
            if (!StringUtils.hasText(item)) {
                continue;
            }
            String[] pair = item.split("@");
            Long lineId = parseLongSafely(pair[0]);
            if (lineId == null) {
                continue;
            }
            context.productIds.add(lineId);
            if (pair.length >= 2 && StringUtils.hasText(pair[1])) {
                context.requestedQtyByProductId.put(lineId, pair[1]);
            }
        }
    }
 
    private void attachRequestedQty(List<SalesLedgerProduct> products, StockInBusinessContext context) {
        if (products == null || products.isEmpty() || context == null || context.requestedQtyByProductId.isEmpty()) {
            return;
        }
        for (SalesLedgerProduct product : products) {
            if (product == null || product.getId() == null) {
                continue;
            }
            String requestedQty = context.requestedQtyByProductId.get(product.getId());
            if (requestedQty != null) {
                product.setRemark(StringUtils.hasText(product.getRemark())
                        ? product.getRemark() + ";审批申请数量:" + requestedQty
                        : "审批申请数量:" + requestedQty);
            }
        }
    }
 
    private Long parseLongSafely(String value) {
        if (!StringUtils.hasText(value)) {
            return null;
        }
        try {
            return Long.valueOf(value);
        } catch (Exception ignored) {
            return null;
        }
    }
 
    private static class StockInBusinessContext {
        private String businessType;
        private Long purchaseLedgerId;
        private Long salesLedgerId;
        private List<Long> productIds = new ArrayList<>();
        private final Map<Long, String> requestedQtyByProductId = new HashMap<>();
    }
 
    @Autowired
    private ApproveNodeMapper approveNodeMapper;
 
    // 报价审批编辑审核人
    public void updateApproveUser(ApproveGetAndUpdateVo approveGetAndUpdateVo) {
        LambdaQueryWrapper<ApproveProcess> approveProcessLambdaQueryWrapper = new LambdaQueryWrapper<>();
        approveProcessLambdaQueryWrapper.eq(ApproveProcess::getApproveType, approveGetAndUpdateVo.getApproveType())
                .eq(ApproveProcess::getApproveReason, approveGetAndUpdateVo.getApproveReason())
                .last("limit 1");
        ApproveProcess approveProcess = approveProcessMapper.selectOne(approveProcessLambdaQueryWrapper);
        if (approveProcess == null) throw new RuntimeException("请选择审批人");
        String[] split = approveGetAndUpdateVo.getApproveUserIds().split(",");
        if (split.length == 0) {
            throw new RuntimeException("请选择审批人");
        }
        List<SysUser> sysUsers = sysUserMapper.selectUserByIds(Arrays.asList(split).stream().map(Long::parseLong).collect(Collectors.toList()));
        if (CollectionUtils.isEmpty(sysUsers)) throw new RuntimeException("请选择审批人");
        //审核中不可以编辑审核人
        if (approveProcess.getApproveStatus() != 1) {
            approveProcess.setApproveUserCurrentId(Long.parseLong(split[0]));
            approveProcess.setApproveUserCurrentName(sysUsers.stream().filter(user -> user.getUserId().equals(Long.parseLong(split[0]))).collect(Collectors.toList()).get(0).getNickName());
        }
        if (approveGetAndUpdateVo.getApproveStatus() != null) {
            approveProcess.setApproveStatus(approveGetAndUpdateVo.getApproveStatus());
        }
        approveProcess.setApproveUserIds(approveGetAndUpdateVo.getApproveUserIds());
        updateById(approveProcess);
        //修改审批人
        // 先删除 后新增
        LambdaQueryWrapper<ApproveNode> approveNodeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        approveNodeLambdaQueryWrapper.eq(ApproveNode::getApproveProcessId, approveProcess.getApproveId())
                .eq(ApproveNode::getDeleteFlag, 0)
//                .eq(ApproveNode::getTenantId, SecurityUtils.getLoginUser().getTenantId())
                .orderByAsc(ApproveNode::getApproveNodeOrder);
        approveNodeMapper.delete(approveNodeLambdaQueryWrapper);
        approveNodeService.initApproveNodes(approveGetAndUpdateVo.getApproveUserIds(), approveProcess.getApproveId(), approveProcess.getTenantId());
        /*消息通知*/
        String id = approveProcess.getApproveUserIds().split(",")[0];
        if (approveProcess.getApproveType()==8){
            sysNoticeService.simpleNoticeByUser(approveProcessType(approveProcess.getApproveType()),
                    approveProcess.getApproveId() + "流程编号的审批需要您审核!!!!!",
                    Arrays.asList(Long.valueOf(id)),
                    "/safeProduction/safeWorkApproval?approveType=" + approveProcess.getApproveType() + "&approveId=" + approveProcess.getApproveId());
        }else {
            sysNoticeService.simpleNoticeByUser(approveProcessType(approveProcess.getApproveType()),
                    approveProcess.getApproveId() + "流程编号的审批需要您审核!!!!!",
                    Arrays.asList(Long.valueOf(id)),
                    "/collaborativeApproval/approvalProcess?approveType=" + approveProcess.getApproveType() + "&approveId=" + approveProcess.getApproveId());
        }
    }
 
 
    @Override
    public void updateByApproveId(ApproveGetAndUpdateVo approveGetAndUpdateVo) throws IOException {
        ApproveProcess approve = approveProcessMapper.selectById(approveGetAndUpdateVo.getId());
        BeanUtils.copyProperties(approveGetAndUpdateVo, approve);
        approve.setApproveUserIds(approveGetAndUpdateVo.getApproveUserIds());
        approve.setApproveReason(approveGetAndUpdateVo.getApproveReason());
        SysUser sysUser = sysUserMapper.selectUserById(approveGetAndUpdateVo.getApproveUser());
        String[] split = approveGetAndUpdateVo.getApproveUserIds().split(",");
        if (split.length == 0) {
            throw new RuntimeException("请选择审批人");
        }
        List<SysUser> sysUsers = sysUserMapper.selectUserByIds(Arrays.asList(split).stream().map(Long::parseLong).collect(Collectors.toList()));
        if (CollectionUtils.isEmpty(sysUsers)) throw new RuntimeException("请选择审批人");
        if (sysUser == null) throw new RuntimeException("申请人不存在");
        approve.setApproveUserName(sysUser.getNickName());
        approve.setApproveUser(sysUser.getUserId());
        //审核中不可以编辑审核人
        if (approve.getApproveStatus() != 1) {
            approve.setApproveUserCurrentId(Long.parseLong(split[0]));
            approve.setApproveUserCurrentName(sysUsers.stream().filter(user -> user.getUserId().equals(Long.parseLong(split[0]))).collect(Collectors.toList()).get(0).getNickName());
        }
        updateById(approve);
        //修改审批人
        // 先删除 后新增
        LambdaQueryWrapper<ApproveNode> approveNodeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        approveNodeLambdaQueryWrapper.eq(ApproveNode::getApproveProcessId, approve.getApproveId())
                .eq(ApproveNode::getDeleteFlag, 0)
//                .eq(ApproveNode::getTenantId, SecurityUtils.getLoginUser().getTenantId())
                .orderByAsc(ApproveNode::getApproveNodeOrder);
        approveNodeMapper.delete(approveNodeLambdaQueryWrapper);
        approveNodeService.initApproveNodes(approveGetAndUpdateVo.getApproveUserIds(), approve.getApproveId(), approve.getTenantId());
 
//        int i = 0;
//        for (ApproveNode approveNode : list) {
//            int finalI = i;
//            if(i >= split.length){
//                approveNode.setDeleteFlag(1);
//            }else{
//                List<SysUser> collect = sysUsers.stream().filter(user -> user.getUserId().equals(Long.parseLong(split[finalI]))).collect(Collectors.toList());
//                if(CollectionUtils.isEmpty(collect)){
//                    throw new RuntimeException("请选择正确的审批人");
//                }
//                approveNode.setApproveNodeUserId(collect.get(0).getUserId());
//                approveNode.setApproveNodeUser(collect.get(0).getNickName());
//            }
//            approveNodeMapper.updateById(approveNode);
//            i++;
//        }
        tempFileService.migrateTempFilesToFormal(approve.getId(), approveGetAndUpdateVo.getTempFileIds(), FileNameType.ApproveProcess.getValue());
        /*消息通知*/
        String id = approve.getApproveUserIds().split(",")[0];
        if (approve.getApproveType()==8){
            sysNoticeService.simpleNoticeByUser(approveProcessType(approve.getApproveType()),
                    approve.getApproveId() + "流程编号的审批需要您审核!!!!!",
                    Arrays.asList(Long.valueOf(id)),
                    "/safeProduction/safeWorkApproval?approveType=" + approve.getApproveType() + "&approveId=" + approve.getApproveId());
        }else {
            sysNoticeService.simpleNoticeByUser(approveProcessType(approve.getApproveType()),
                    approve.getApproveId() + "流程编号的审批需要您审核!!!!!",
                    Arrays.asList(Long.valueOf(id)),
                    "/collaborativeApproval/approvalProcess?approveType=" + approve.getApproveType() + "&approveId=" + approve.getApproveId());
        }
 
    }
 
 
    //审批类型获取(与前端页面对应)
    private String approveProcessType(Integer approveType) {
        switch (approveType) {
            case 1:
                return "公出管理";
            case 2:
                return "请假管理";
            case 3:
                return "出差管理";
            case 4:
                return "报销管理";
            case 5:
                return "采购审批";
            case 6:
                return "报价审批";
            case 7:
                return "发货审批";
            case 8:
                return "危险作业审批";
            case 9:
                return "入库审批";
        }
        return null;
    }
}