shiyunteng
2 天以前 96119ca3973d5ea643db6a87b6a23fe404ddb8cc
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
package com.by4cloud.platformx.business.service.impl;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.by4cloud.platformx.business.dto.OutBoundAddDTO;
import com.by4cloud.platformx.business.dto.OutSubjectMatterAddDTO;
import com.by4cloud.platformx.business.entity.*;
import com.by4cloud.platformx.business.mapper.*;
import com.by4cloud.platformx.business.service.OutBoundService;
import com.by4cloud.platformx.common.core.util.R;
import com.by4cloud.platformx.common.security.util.SecurityUtils;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * EPR出库记录
 *
 * @author syt
 * @date 2026-04-29 11:32:05
 */
@Service
@RequiredArgsConstructor
public class OutBoundServiceImpl extends ServiceImpl<OutBoundMapper, OutBound> implements OutBoundService {
 
    private final ContractPaymentScheduleMapper scheduleMapper;
    private final ContractSubjectMatterMapper contractSubjectMatterMapper;
    private final PaymentConfirmMapper paymentConfirmMapper;
    private final ContractMapper contractMapper;
    private final ContractPaymentScheduleProcessMapper scheduleProcessMapper;
    private final ContractOutBoundMapper contractOutBoundMapper;
    private final DeliveryOverdueMapper deliveryOverdueMapper;
    private final StringRedisTemplate redisTemplate;
 
    @Value("${dept.smj}")
    private String smj;
 
    @Value("${dept.sgb}")
    private String sgb;
 
    @Value("${dept.jxc}")
    private String jxc;
 
    @Value("${dept.tfgs}")
    private String tfgs;
 
    @Value("${dept.ymj}")
    private String ymj;
 
    @Override
    public R add(OutBoundAddDTO addDTO) {
        if (ArrayUtil.isEmpty(addDTO.getSubjectMatterList().toArray())) {
            return R.failed("出库标的物不能为空");
        }
        MPJLambdaWrapper<ContractSubjectMatter> wrapper = new MPJLambdaWrapper<ContractSubjectMatter>()
                .selectAll(ContractSubjectMatter.class)
                .ne(ContractSubjectMatter::getDeliveryStatus, 2)
                .in(ContractSubjectMatter::getMaterialCode, addDTO.getSubjectMatterList().stream().map(item -> item.getSubjectMatterCode()).collect(Collectors.toList()))
                .exists(Contract.class, contractQuery ->
                        contractQuery.select(ContractSubjectMatter::getId)
                                .eq(Contract::getContractStatus, 2)
                                .eq(Contract::getId, ContractSubjectMatter::getContractId)
                                .eq(StrUtil.isNotBlank(addDTO.getBusGuestName()), Contract::getPartyA, addDTO.getBusGuestName())
                                .eq(ObjUtil.isNotNull(addDTO.getBusGuestId()), Contract::getPartyAId, addDTO.getBusGuestId())
                )
                .orderByAsc(ContractSubjectMatter::getCreateTime);
        List<ContractSubjectMatter> subjectMatterList = contractSubjectMatterMapper.selectList(wrapper);
        if (ArrayUtil.isEmpty(subjectMatterList.toArray())) {
            return R.failed("没有查询到相关合同订单");
        }
        List<String> erpCodeList = subjectMatterList.stream().map(ContractSubjectMatter::getMaterialCode).collect(Collectors.toList());
        BigDecimal orderNum = subjectMatterList.stream().filter(item -> item.getDeliveryStatus() != 2)
                .map(item -> item.getDeliveryStatus() == 0 ? item.getQuantity() : item.getRemainingQuantity())
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal outTotal = addDTO.getSubjectMatterList().stream()
                .filter(item -> erpCodeList.contains(item.getSubjectMatterCode()))
                .map(OutSubjectMatterAddDTO::getOutBoundNum)
                .filter(num -> num != null) // 过滤掉 null 值,防止 NullPointerException
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        if (outTotal.compareTo(orderNum) > 0) {
            return R.failed("出库数量超出合同订单数量");
        }
        //当前入库标的物
        Map<Long, Object> currentOutMap = new HashMap<>();
        //出库批次
        String batchNumber = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN);
        //出库
        addDTO.getSubjectMatterList().stream().forEach(outSubjectMatterAddDTO -> {
            OutBound outBound = BeanUtil.copyProperties(outSubjectMatterAddDTO, OutBound.class);
            if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",smj)){
                outBound.setBatchNumber(generateSMJContractNo());
            }
            if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",sgb)){
                outBound.setBatchNumber(generateGYBContractNo());
            }
            if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",ymj)){
                outBound.setBatchNumber(generateYMJContractNo());
            }
            if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",tfgs)){
                outBound.setBatchNumber(generateTFContractNo());
            }
            if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",jxc)){
                outBound.setBatchNumber(generateJXCContractNo());
            }
            outBound.setBusGuestName(addDTO.getBusGuestName());
            outBound.setBusGuestId(addDTO.getBusGuestId());
            outBound.setOutBoundTime(addDTO.getOutBoundTime());
            baseMapper.insert(outBound);
            BigDecimal remainNum = outSubjectMatterAddDTO.getOutBoundNum();
            for (ContractSubjectMatter subjectMatter : subjectMatterList) {
                if (outSubjectMatterAddDTO.getSubjectMatterCode().equals(subjectMatter.getMaterialCode())) {
                    Contract contract = contractMapper.selectById(subjectMatter.getContractId());
                    if (subjectMatter.getDeliveredQuantity().compareTo(new BigDecimal("0")) > 0) {
                        remainNum = remainNum.subtract(subjectMatter.getRemainingQuantity());
                        //部分交付状态下 全部出库
                        if (remainNum.compareTo(new BigDecimal("0")) > 0) {
                            BigDecimal currentOut = subjectMatter.getRemainingQuantity();
                            subjectMatter.setDeliveredQuantity(subjectMatter.getQuantity());
                            subjectMatter.setRemainingQuantity(new BigDecimal("0"));
                            subjectMatter.setActualDeliveryDate(addDTO.getOutBoundTime());
                            subjectMatter.setDeliveryStatus(2);
                            subjectMatter.setLastDeliveredQuantity(currentOut);
                            contractSubjectMatterMapper.updateById(subjectMatter);
                            currentOutMap.put(subjectMatter.getContractId(), subjectMatter);
                            //新增合同出库历史
                            saveContractOutBound(contract, addDTO, subjectMatter, outBound.getId());
                        } else {
                            BigDecimal currentOut = remainNum.add(subjectMatter.getRemainingQuantity());
                            subjectMatter.setDeliveredQuantity(subjectMatter.getQuantity().add(remainNum));
                            subjectMatter.setRemainingQuantity(subjectMatter.getRemainingQuantity().subtract(currentOut));
                            subjectMatter.setActualDeliveryDate(addDTO.getOutBoundTime());
                            subjectMatter.setDeliveryStatus(1);
                            subjectMatter.setLastDeliveredQuantity(currentOut);
                            contractSubjectMatterMapper.updateById(subjectMatter);
                            currentOutMap.put(subjectMatter.getContractId(), subjectMatter);
                            //新增合同出库历史
                            saveContractOutBound(contract, addDTO, subjectMatter, outBound.getId());
                            break;
                        }
 
                    } else {
                        //未交付状态下
                        remainNum = remainNum.subtract(subjectMatter.getQuantity());
                        if (remainNum.compareTo(new BigDecimal("0")) > 0) {
                            subjectMatter.setDeliveredQuantity(subjectMatter.getQuantity());
                            subjectMatter.setRemainingQuantity(new BigDecimal("0"));
                            subjectMatter.setActualDeliveryDate(addDTO.getOutBoundTime());
                            subjectMatter.setDeliveryStatus(2);
                            subjectMatter.setLastDeliveredQuantity(subjectMatter.getQuantity());
                            contractSubjectMatterMapper.updateById(subjectMatter);
                            currentOutMap.put(subjectMatter.getContractId(), subjectMatter);
                            //新增合同出库历史
                            saveContractOutBound(contract, addDTO, subjectMatter, outBound.getId());
                        } else {
                            BigDecimal currentOut = remainNum.add(subjectMatter.getQuantity());
                            subjectMatter.setDeliveredQuantity(subjectMatter.getQuantity().add(remainNum));
                            subjectMatter.setRemainingQuantity(remainNum.multiply(new BigDecimal("-1")));
                            subjectMatter.setActualDeliveryDate(addDTO.getOutBoundTime());
                            subjectMatter.setDeliveryStatus(1);
                            subjectMatter.setLastDeliveredQuantity(currentOut);
                            contractSubjectMatterMapper.updateById(subjectMatter);
                            currentOutMap.put(subjectMatter.getContractId(), subjectMatter);
                            //新增合同出库历史
                            saveContractOutBound(contract, addDTO, subjectMatter, outBound.getId());
                            break;
                        }
                    }
                }
            }
 
        });
 
        //出库应收款明细
        if (ArrayUtil.isNotEmpty(currentOutMap.keySet())) {
            for (Long contractId : currentOutMap.keySet()) {
                //当前出库合同出库标的物
                List<ContractSubjectMatter> contractSubjectMatterList = contractSubjectMatterMapper.selectList(Wrappers.<ContractSubjectMatter>lambdaQuery()
                        .eq(ContractSubjectMatter::getContractId, contractId).ne(ContractSubjectMatter::getDeliveryStatus, 0));
                //查询合同是否有出库阶段
                ContractPaymentSchedule schedule = scheduleMapper.selectOne(Wrappers.<ContractPaymentSchedule>lambdaQuery().eq(ContractPaymentSchedule::getContractId, contractId)
                        .eq(ContractPaymentSchedule::getStageName, "发货前"));
                //存在出库阶段
                if (ObjUtil.isNotNull(schedule)) {
                    //当前出库金额
                    BigDecimal outPirce = contractSubjectMatterList.stream()
                            .map(item -> (item.getDeliveryStatus() == 1 ? item.getDeliveredQuantity().multiply(item.getUnitPrice()) : item.getQuantity().multiply(item.getUnitPrice())))
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    //合同金额
                    Contract contract = contractMapper.selectById(contractId);
                    //出库是否完成
                    if (outPirce.compareTo(contract.getAmount()) < 0) {
                        contract.setBillingStatus("1");
                        contractMapper.updateById(contract);
                    }
                    if (outPirce.compareTo(contract.getAmount()) == 0) {
                        contract.setBillingStatus("2");
                        contractMapper.updateById(contract);
                    }
                    //计算发货前应收更新资金明细
                    PaymentConfirm paymentConfirm = new PaymentConfirm();
                    paymentConfirm.setBusinessType("发货前应收");
                    paymentConfirm.setBusGuestId(contract.getPartyAId());
                    paymentConfirm.setBusGuestName(contract.getPartyA());
                    paymentConfirm.setContractId(contract.getId());
                    paymentConfirm.setContractName(contract.getContractName());
                    paymentConfirm.setContractNo(contract.getContractNo());
                    paymentConfirm.setScheduleId(schedule.getId());
                    paymentConfirm.setScheduleName(schedule.getStageName());
                    paymentConfirm.setConfirmTime(addDTO.getOutBoundTime());
                    //按出库资金比例 计算发货前应收
                    paymentConfirm.setTransationAmount(outPirce.divide(contract.getAmount(), 10, RoundingMode.HALF_UP).multiply(schedule.getPlannedAmount()));
                    paymentConfirm.setReceivableAmount(paymentConfirm.getTransationAmount());
 
                    //最近应收
                    PaymentConfirm lastConfirm = paymentConfirmMapper.selectOne(Wrappers.<PaymentConfirm>lambdaQuery().eq(PaymentConfirm::getContractId, contract.getId())
                            .orderByDesc(PaymentConfirm::getCreateTime).last("limit 1"));
 
                    if (ObjUtil.isNotNull(lastConfirm)) {
                        //已存在发货应收
                        if (StrUtil.equals(lastConfirm.getBusinessType(), paymentConfirm.getBusinessType())) {
 
                            //查询之前所有发货前应收
                            List<PaymentConfirm> fhConfirmList = paymentConfirmMapper.selectList(Wrappers.<PaymentConfirm>lambdaQuery().eq(PaymentConfirm::getContractId, contract.getId())
                                    .eq(PaymentConfirm::getScheduleId, schedule.getId()).orderByDesc(PaymentConfirm::getCreateTime));
                            BigDecimal fhTotalAmount = fhConfirmList.stream().map(item -> item.getTransationAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
                            //本次发货前应收 出库总额 - 所有发货前应收
                            paymentConfirm.setTransationAmount(paymentConfirm.getTransationAmount().subtract(fhTotalAmount));
                            paymentConfirm.setReceivableAmount(paymentConfirm.getTransationAmount());
                            paymentConfirm.setTotalAmount(lastConfirm.getTotalAmount().subtract(paymentConfirm.getTransationAmount()));
                            if (schedule.getPaymentRatio().compareTo(new BigDecimal("0")) > 0) {
                                paymentConfirmMapper.insert(paymentConfirm);
                            }
                        } else {
                            //不存在发货应收 出库总额
                            paymentConfirm.setTotalAmount(lastConfirm.getTotalAmount().subtract(paymentConfirm.getTransationAmount()));
                            if (schedule.getPaymentRatio().compareTo(new BigDecimal("0")) > 0) {
                                paymentConfirmMapper.insert(paymentConfirm);
                            }
                        }
                    } else {
                        //无之前阶段应收
                        paymentConfirm.setTotalAmount(paymentConfirm.getTransationAmount().multiply(new BigDecimal("-1")));
                        if (schedule.getPaymentRatio().compareTo(new BigDecimal("0")) > 0) {
                            paymentConfirmMapper.insert(paymentConfirm);
                            //客户付款完成合同
                            List<Contract> customerCompleteContractList = contractMapper.selectList(Wrappers.<Contract>lambdaQuery().eq(Contract::getPartyAId, contract.getPartyAId())
                                    .eq(Contract::getPartyBId, SecurityUtils.getUser().getCompId()).apply(" amount = paid_amount"));
                            if (ArrayUtil.isNotEmpty(customerCompleteContractList)) {
                                List<BigDecimal> outAmountList = new ArrayList<>();
                                for (Contract completeContract : customerCompleteContractList
                                ) {
                                    PaymentConfirm contractLastConfirm = paymentConfirmMapper.selectOne(Wrappers.<PaymentConfirm>lambdaQuery().eq(PaymentConfirm::getContractId, completeContract.getId())
                                            .orderByDesc(PaymentConfirm::getCreateTime).last("limit 1"));
                                    //查询客户付款完成合同中最后明细金额 有预收转入当前合同
                                    if (contractLastConfirm.getTotalAmount().compareTo(new BigDecimal("0")) > 0) {
                                        //新增完成付款合同 资金转出
                                        PaymentConfirm outConfirm = BeanUtil.copyProperties(contractLastConfirm, PaymentConfirm.class, "id", "transationAmount",
                                                "advanceAmount", "receivableAmount", "overdueAmount", "totalAmount");
                                        outConfirm.setBusinessType("资金转出");
                                        outConfirm.setConfirmTime(new Date());
                                        outConfirm.setTransationAmount(contractLastConfirm.getTotalAmount());
                                        outConfirm.setTotalAmount(new BigDecimal("0"));
                                        paymentConfirmMapper.insert(outConfirm);
                                        outAmountList.add(outConfirm.getTransationAmount());
                                    }
                                }
                                if (ArrayUtil.isNotEmpty(outAmountList.toArray())) {
                                    BigDecimal currentInSum = outAmountList.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
                                    //新增当前合同 资金转入
                                    PaymentConfirm inConfirm = BeanUtil.copyProperties(paymentConfirm, PaymentConfirm.class, "id", "transationAmount",
                                            "advanceAmount", "receivableAmount", "overdueAmount", "totalAmount");
                                    inConfirm.setBusinessType("资金转入");
                                    inConfirm.setConfirmTime(new Date());
                                    inConfirm.setTransationAmount(currentInSum);
                                    inConfirm.setTotalAmount(paymentConfirm.getTotalAmount().add(currentInSum));
                                    //更新当前阶段实际收款 和 收款状态
                                    schedule.setActualAmount(inConfirm.getTransationAmount());
                                    schedule.setPaymentStatus(2);
                                    if (inConfirm.getTotalAmount().compareTo(new BigDecimal("0")) > 0) {
                                        inConfirm.setAdvanceAmount(inConfirm.getTotalAmount());
                                    } else if (inConfirm.getTotalAmount().compareTo(new BigDecimal("0")) < 0) {
                                        inConfirm.setReceivableAmount(inConfirm.getTotalAmount().multiply(new BigDecimal("-1")));
                                        schedule.setActualAmount(paymentConfirm.getTotalAmount().subtract(currentInSum));
                                        schedule.setPaymentStatus(1);
                                    }
                                    paymentConfirmMapper.insert(inConfirm);
                                    //更新当前阶段实际收款 和 收款状态
                                    scheduleMapper.updateById(schedule);
                                }
                            }
                        }
                    }
 
                    //更新发货前收款生效时间
                    if (ObjUtil.isNull(schedule.getEffectiveDate())) {
                        schedule.setEffectiveEndDate(DateUtil.offsetDay(addDTO.getOutBoundTime(), schedule.getAgreedDays()));
                        //查询是否有后续阶段
//                        List<ContractPaymentSchedule> afterSchedule = scheduleMapper.selectList(Wrappers.<ContractPaymentSchedule>lambdaQuery().eq(ContractPaymentSchedule::getContractId, contractId)
//                                .gt(ContractPaymentSchedule::getStageOrder, schedule.getStageOrder()));
//                        if (ArrayUtil.isEmpty(afterSchedule.toArray())) {
//                            schedule.setEffectiveEndDate(contract.getExpirationDate());
//                        }
                        scheduleMapper.updateById(schedule);
                        //查询是否有之前阶段
//                        ContractPaymentSchedule beforeSchedule = scheduleMapper.selectOne(Wrappers.<ContractPaymentSchedule>lambdaQuery().eq(ContractPaymentSchedule::getContractId, schedule.getContractId())
//                                .lt(ContractPaymentSchedule::getStageOrder, schedule.getStageOrder()).orderByDesc(ContractPaymentSchedule::getCreateTime).last("limit 1"));
//                        if (ObjUtil.isNotNull(beforeSchedule)) {
//                            beforeSchedule.setEffectiveEndDate(schedule.getEffectiveDate());
//                            scheduleMapper.updateById(beforeSchedule);
//                        }
                        //更新履约
                        ContractPaymentScheduleProcess contractPaymentScheduleProcess = new ContractPaymentScheduleProcess();
                        contractPaymentScheduleProcess.setContractId(schedule.getContractId());
                        contractPaymentScheduleProcess.setContractName(schedule.getContractName());
                        contractPaymentScheduleProcess.setScheduleId(schedule.getId());
                        contractPaymentScheduleProcess.setScheduleName(schedule.getStageName());
                        contractPaymentScheduleProcess.setProcessDate(addDTO.getOutBoundTime());
                        ContractPaymentScheduleProcess lastProcess = scheduleProcessMapper.selectOne(Wrappers.<ContractPaymentScheduleProcess>lambdaQuery().eq(ContractPaymentScheduleProcess::getContractId, schedule.getContractId())
                                .eq(ContractPaymentScheduleProcess::getScheduleId, schedule.getId()).last("limit 1"));
                        if (ObjUtil.isNull(lastProcess)) {
                            scheduleProcessMapper.insert(contractPaymentScheduleProcess);
                        }
                    }
 
                    //查询是否有后续阶段
                    List<ContractPaymentSchedule> afterSchedule = scheduleMapper.selectList(Wrappers.<ContractPaymentSchedule>lambdaQuery()
                            .eq(ContractPaymentSchedule::getContractId, schedule.getContractId())
                            .gt(ContractPaymentSchedule::getStageOrder, schedule.getStageOrder())
                            .orderByAsc(ContractPaymentSchedule::getCreateTime));
                    if (ArrayUtil.isNotEmpty(afterSchedule.toArray()) && afterSchedule.size() == 1) {
                        //最后阶段生效时间
                        ContractPaymentSchedule endSchedule = afterSchedule.get(0);
                        if (StrUtil.equals(endSchedule.getStageName(), "质保金")) {
//                            endSchedule.setEffectiveEndDate(DateUtil.offsetDay(addDTO.getOutBoundTime(), endSchedule.getAgreedDays()));
//                            scheduleMapper.updateById(endSchedule);
                            //当前阶段生效时间
//                            schedule.setEffectiveEndDate(DateUtil.offsetDay(addDTO.getOutBoundTime(), schedule.getAgreedDays()));
//                            scheduleMapper.updateById(schedule);
                            //最后阶段应收
                            PaymentConfirm newConfim = new PaymentConfirm();
                            newConfim.setBusinessType(endSchedule.getStageName() + "应收");
                            newConfim.setBusGuestId(contract.getPartyAId());
                            newConfim.setBusGuestName(contract.getPartyA());
                            newConfim.setContractId(contract.getId());
                            newConfim.setContractName(contract.getContractName());
                            newConfim.setContractNo(contract.getContractNo());
                            newConfim.setScheduleId(endSchedule.getId());
                            newConfim.setScheduleName(schedule.getStageName());
                            newConfim.setConfirmTime(addDTO.getOutBoundTime());
                            newConfim.setTransationAmount(endSchedule.getPlannedAmount());
                            newConfim.setReceivableAmount(endSchedule.getPlannedAmount());
                            PaymentConfirm lastNewConfirm = paymentConfirmMapper.selectOne(Wrappers.<PaymentConfirm>lambdaQuery().eq(PaymentConfirm::getContractId, contract.getId())
                                    .orderByDesc(PaymentConfirm::getCreateTime).last("limit 1"));
                            BigDecimal lastNewTotal = new BigDecimal("0");
                            if (ObjUtil.isNotNull(lastNewConfirm)) {
                                lastNewTotal = lastNewConfirm.getTotalAmount();
                            }
                            newConfim.setTotalAmount(lastNewTotal.subtract(newConfim.getReceivableAmount()));
                            if (endSchedule.getPaymentRatio().compareTo(new BigDecimal("0")) > 0) {
                                paymentConfirmMapper.insert(newConfim);
                            }
                        }
                        //更新合同下个阶段
                        contract.setNextScheduleName(endSchedule.getStageName());
                        contractMapper.updateById(contract);
                    }
                    if (ArrayUtil.isNotEmpty(afterSchedule.toArray()) && afterSchedule.size() > 1) {
                        //更新合同下个阶段
                        contract.setNextScheduleName(afterSchedule.get(0).getStageName());
                        contractMapper.updateById(contract);
                    }
                    if (ArrayUtil.isEmpty(afterSchedule.toArray())) {
//                        schedule.setEffectiveEndDate(contract.getExpirationDate());
//                        scheduleMapper.updateById(schedule);
                        //更新合同下个阶段
                        contract.setNextScheduleName("无");
                        contractMapper.updateById(contract);
                        //当前为合同最后阶段
                        PaymentConfirm lastNewConfirm = paymentConfirmMapper.selectOne(Wrappers.<PaymentConfirm>lambdaQuery().eq(PaymentConfirm::getContractId, contract.getId())
                                .orderByDesc(PaymentConfirm::getCreateTime).last("limit 1"));
                        if (lastNewConfirm.getTotalAmount().compareTo(new BigDecimal("0")) >= 0) {
                            //有预付且超过应收 关闭合同状态
                            contract.setContractStatus(3);
                            contractMapper.updateById(contract);
                        }
                    }
                }
            }
        }
 
        return R.ok();
    }
 
    private void saveContractOutBound(Contract contract, OutBoundAddDTO addDTO, ContractSubjectMatter subjectMatter, Long outBoundId) {
        ContractOutBound contractOutBound = new ContractOutBound();
        contractOutBound.setContractId(contract.getId());
        contractOutBound.setContractName(contract.getContractName());
        contractOutBound.setBusGuestId(contract.getPartyAId());
        contractOutBound.setBusGuestName(contract.getPartyA());
        contractOutBound.setSubjectMatterCode(subjectMatter.getMaterialCode());
        contractOutBound.setSubjectMatterName(subjectMatter.getMaterialInternalName());
        contractOutBound.setOutBoundTime(addDTO.getOutBoundTime());
        contractOutBound.setOutBoundNum(subjectMatter.getLastDeliveredQuantity());
        contractOutBound.setOutBoundAttNames(addDTO.getOutBoundAttNames());
        contractOutBound.setOutBoundAttPaths(addDTO.getOutBoundAttPaths());
        contractOutBound.setOutBoundId(outBoundId);
        contractOutBound.setInvoiceStatus("0");
        contractOutBound.setInvoiceNum(new BigDecimal("0"));
        contractOutBoundMapper.insert(contractOutBound);
        if (!StrUtil.equals(contract.getContractCategory(),"water_house")) {
            // 1. 确定用于比较的基准日期(优先级:计划交货日期 > 合同到期日期)
            Date deadline = subjectMatter.getPlannedDeliveryDate();
            if (ObjUtil.isNull(deadline)) {
                deadline = contract.getExpirationDate();
            }
 
            // 2. 统一判断是否逾期
            // 注意:需确保 deadline 不为 null,防止空指针异常
            if (deadline != null && DateUtil.compare(addDTO.getOutBoundTime(), deadline) > 0) {
                saveOverdueOutBound(contract, addDTO, subjectMatter);
            }
 
        }
    }
 
    private void saveOverdueOutBound(Contract contract, OutBoundAddDTO addDTO, ContractSubjectMatter subjectMatter) {
        DeliveryOverdue overdue = new DeliveryOverdue();
        overdue.setContractId(contract.getId());
        overdue.setContractName(contract.getContractName());
        overdue.setBusGuestId(contract.getPartyAId());
        overdue.setBusGuestName(contract.getPartyA());
        overdue.setMaterialName(subjectMatter.getMaterialName());
        overdue.setMaterialInternalName(subjectMatter.getMaterialInternalName());
        overdue.setMaterialCode(subjectMatter.getMaterialCode());
        overdue.setOverdueNum(subjectMatter.getLastDeliveredQuantity());
        overdue.setTotalAmount(subjectMatter.getUnitPrice().multiply(subjectMatter.getLastDeliveredQuantity()));
        overdue.setOverdueDuration(new BigDecimal(DateUtil.betweenDay(addDTO.getOutBoundTime(), contract.getExpirationDate(), true)));
        deliveryOverdueMapper.insert(overdue);
    }
 
    @Override
    public R addContractOut(OutBoundAddDTO addDTO) {
        if (ArrayUtil.isEmpty(addDTO.getSubjectMatterList().toArray())) {
            return R.failed("出库标的物不能为空");
        }
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getContractNo, addDTO.getContractNo()).eq(Contract::getContractStatus, 2)
                .last("limit 1"));
        if (ObjUtil.isNull(contract)) {
            return R.failed("合同信息查询失败");
        }
        //出库批次
        String batchNumber = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN);
 
        addDTO.getSubjectMatterList().stream().forEach(outSubjectMatterAddDTO -> {
            ContractSubjectMatter subjectMatter = contractSubjectMatterMapper.selectById(outSubjectMatterAddDTO.getId());
            subjectMatter.setLastDeliveredQuantity(outSubjectMatterAddDTO.getOutBoundNum());
            if (subjectMatter.getDeliveryStatus() == 0) {
                subjectMatter.setDeliveredQuantity(outSubjectMatterAddDTO.getOutBoundNum());
                subjectMatter.setRemainingQuantity(subjectMatter.getQuantity().subtract(outSubjectMatterAddDTO.getOutBoundNum()));
            }
            if (subjectMatter.getDeliveryStatus() == 1) {
                subjectMatter.setDeliveredQuantity(subjectMatter.getDeliveredQuantity().add(outSubjectMatterAddDTO.getOutBoundNum()));
                subjectMatter.setRemainingQuantity(subjectMatter.getRemainingQuantity().subtract(outSubjectMatterAddDTO.getOutBoundNum()));
            }
            subjectMatter.setDeliveryStatus(1);
            if (subjectMatter.getRemainingQuantity().compareTo(new BigDecimal("0")) == 0) {
                subjectMatter.setDeliveryStatus(2);
            }
            subjectMatter.setActualDeliveryDate(addDTO.getOutBoundTime());
            contractSubjectMatterMapper.updateById(subjectMatter);
            //
            OutBound outBound = new OutBound();
            if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",smj)){
                outBound.setBatchNumber(generateSMJContractNo());
            }
            if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",sgb)){
                outBound.setBatchNumber(generateGYBContractNo());
            }
            if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",ymj)){
                outBound.setBatchNumber(generateYMJContractNo());
            }
            if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",tfgs)){
                outBound.setBatchNumber(generateTFContractNo());
            }
            if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",jxc)){
                outBound.setBatchNumber(generateJXCContractNo());
            }
            outBound.setOutBoundNum(outSubjectMatterAddDTO.getOutBoundNum());
            outBound.setOutBoundAttNames(addDTO.getOutBoundAttNames());
            outBound.setOutBoundAttPaths(addDTO.getOutBoundAttPaths());
            outBound.setBusGuestName(contract.getPartyA());
            outBound.setBusGuestId(contract.getPartyAId());
            outBound.setOutBoundTime(addDTO.getOutBoundTime());
            outBound.setSubjectMatterCode(outSubjectMatterAddDTO.getSubjectMatterCode());
            outBound.setSubjectMatterName(outSubjectMatterAddDTO.getSubjectMatterName());
            baseMapper.insert(outBound);
            //
            saveContractOutBound(contract, addDTO, subjectMatter, outBound.getId());
        });
        //当前出库合同出库标的物
        List<ContractSubjectMatter> contractSubjectMatterList = contractSubjectMatterMapper.selectList(Wrappers.<ContractSubjectMatter>lambdaQuery()
                .eq(ContractSubjectMatter::getContractId, contract.getId()).ne(ContractSubjectMatter::getDeliveryStatus, 0));
        //查询合同是否有出库阶段
        ContractPaymentSchedule schedule = scheduleMapper.selectOne(Wrappers.<ContractPaymentSchedule>lambdaQuery().eq(ContractPaymentSchedule::getContractId, contract.getId())
                .eq(ContractPaymentSchedule::getStageName, "发货前"));
        //存在出库阶段
        if (ObjUtil.isNotNull(schedule)) {
            //当前出库金额
            BigDecimal outPirce = contractSubjectMatterList.stream()
                    .map(item -> (item.getDeliveryStatus() == 1 ? item.getDeliveredQuantity().multiply(item.getUnitPrice()) : item.getQuantity().multiply(item.getUnitPrice())))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            //出库是否完成
            if (outPirce.compareTo(contract.getAmount()) < 0) {
                contract.setBillingStatus("1");
                contractMapper.updateById(contract);
            }
            if (outPirce.compareTo(contract.getAmount()) == 0) {
                contract.setBillingStatus("2");
                contractMapper.updateById(contract);
            }
            //计算发货前应收更新资金明细
            PaymentConfirm paymentConfirm = new PaymentConfirm();
            paymentConfirm.setBusinessType("发货前应收");
            paymentConfirm.setBusGuestId(contract.getPartyAId());
            paymentConfirm.setBusGuestName(contract.getPartyA());
            paymentConfirm.setContractId(contract.getId());
            paymentConfirm.setContractName(contract.getContractName());
            paymentConfirm.setContractNo(contract.getContractNo());
            paymentConfirm.setScheduleId(schedule.getId());
            paymentConfirm.setScheduleName(schedule.getStageName());
            paymentConfirm.setConfirmTime(addDTO.getOutBoundTime());
            //按出库资金比例 计算发货前应收
            paymentConfirm.setTransationAmount(outPirce.divide(contract.getAmount(), 10, RoundingMode.HALF_UP).multiply(schedule.getPlannedAmount()));
            paymentConfirm.setReceivableAmount(paymentConfirm.getTransationAmount());
 
            //最近应收
            PaymentConfirm lastConfirm = paymentConfirmMapper.selectOne(Wrappers.<PaymentConfirm>lambdaQuery().eq(PaymentConfirm::getContractId, contract.getId())
                    .orderByDesc(PaymentConfirm::getCreateTime).last("limit 1"));
 
            if (ObjUtil.isNotNull(lastConfirm)) {
                //已存在发货应收
                if (StrUtil.equals(lastConfirm.getBusinessType(), paymentConfirm.getBusinessType())) {
 
                    //查询之前所有发货前应收
                    List<PaymentConfirm> fhConfirmList = paymentConfirmMapper.selectList(Wrappers.<PaymentConfirm>lambdaQuery().eq(PaymentConfirm::getContractId, contract.getId())
                            .eq(PaymentConfirm::getScheduleId, schedule.getId()).orderByDesc(PaymentConfirm::getCreateTime));
                    BigDecimal fhTotalAmount = fhConfirmList.stream().map(item -> item.getTransationAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
                    //本次发货前应收 出库总额 - 所有发货前应收
                    paymentConfirm.setTransationAmount(paymentConfirm.getTransationAmount().subtract(fhTotalAmount));
                    paymentConfirm.setReceivableAmount(paymentConfirm.getTransationAmount());
                    paymentConfirm.setTotalAmount(lastConfirm.getTotalAmount().subtract(paymentConfirm.getTransationAmount()));
                    if (schedule.getPaymentRatio().compareTo(new BigDecimal("0")) > 0) {
                        paymentConfirmMapper.insert(paymentConfirm);
                    }
                } else {
                    //不存在发货应收 出库总额
                    paymentConfirm.setTotalAmount(lastConfirm.getTotalAmount().subtract(paymentConfirm.getTransationAmount()));
                    if (schedule.getPaymentRatio().compareTo(new BigDecimal("0")) > 0) {
                        paymentConfirmMapper.insert(paymentConfirm);
                    }
                }
            } else {
                //无之前阶段应收
                paymentConfirm.setTotalAmount(paymentConfirm.getTransationAmount().multiply(new BigDecimal("-1")));
                if (schedule.getPaymentRatio().compareTo(new BigDecimal("0")) > 0) {
                    paymentConfirmMapper.insert(paymentConfirm);
                    //客户付款完成合同
                    List<Contract> customerCompleteContractList = contractMapper.selectList(Wrappers.<Contract>lambdaQuery().eq(Contract::getPartyAId, contract.getPartyAId())
                            .eq(Contract::getPartyBId, SecurityUtils.getUser().getCompId()).apply(" amount = paid_amount"));
                    if (ArrayUtil.isNotEmpty(customerCompleteContractList)) {
                        List<BigDecimal> outAmountList = new ArrayList<>();
                        for (Contract completeContract : customerCompleteContractList
                        ) {
                            PaymentConfirm contractLastConfirm = paymentConfirmMapper.selectOne(Wrappers.<PaymentConfirm>lambdaQuery().eq(PaymentConfirm::getContractId, completeContract.getId())
                                    .orderByDesc(PaymentConfirm::getCreateTime).last("limit 1"));
                            //查询客户付款完成合同中最后明细金额 有预收转入当前合同
                            if (contractLastConfirm.getTotalAmount().compareTo(new BigDecimal("0")) > 0) {
                                //新增完成付款合同 资金转出
                                PaymentConfirm outConfirm = BeanUtil.copyProperties(contractLastConfirm, PaymentConfirm.class, "id", "transationAmount",
                                        "advanceAmount", "receivableAmount", "overdueAmount", "totalAmount");
                                outConfirm.setBusinessType("资金转出");
                                outConfirm.setConfirmTime(new Date());
                                outConfirm.setTransationAmount(contractLastConfirm.getTotalAmount());
                                outConfirm.setTotalAmount(new BigDecimal("0"));
                                paymentConfirmMapper.insert(outConfirm);
                                outAmountList.add(outConfirm.getTransationAmount());
                            }
                        }
                        if (ArrayUtil.isNotEmpty(outAmountList.toArray())) {
                            BigDecimal currentInSum = outAmountList.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
                            //新增当前合同 资金转入
                            PaymentConfirm inConfirm = BeanUtil.copyProperties(paymentConfirm, PaymentConfirm.class, "id", "transationAmount",
                                    "advanceAmount", "receivableAmount", "overdueAmount", "totalAmount");
                            inConfirm.setBusinessType("资金转入");
                            inConfirm.setConfirmTime(new Date());
                            inConfirm.setTransationAmount(currentInSum);
                            inConfirm.setTotalAmount(paymentConfirm.getTotalAmount().add(currentInSum));
                            //更新当前阶段实际收款 和 收款状态
                            schedule.setActualAmount(inConfirm.getTransationAmount());
                            schedule.setPaymentStatus(2);
                            if (inConfirm.getTotalAmount().compareTo(new BigDecimal("0")) > 0) {
                                inConfirm.setAdvanceAmount(inConfirm.getTotalAmount());
                            } else if (inConfirm.getTotalAmount().compareTo(new BigDecimal("0")) < 0) {
                                inConfirm.setReceivableAmount(inConfirm.getTotalAmount().multiply(new BigDecimal("-1")));
                                schedule.setActualAmount(paymentConfirm.getTotalAmount().subtract(currentInSum));
                                schedule.setPaymentStatus(1);
                            }
                            paymentConfirmMapper.insert(inConfirm);
                            //更新当前阶段实际收款 和 收款状态
                            scheduleMapper.updateById(schedule);
                        }
                    }
                }
            }
 
            //更新发货前收款生效时间
            if (ObjUtil.isNull(schedule.getEffectiveDate())) {
                schedule.setEffectiveEndDate(DateUtil.offsetDay(addDTO.getOutBoundTime(), schedule.getAgreedDays()));
                //查询是否有后续阶段
//                        List<ContractPaymentSchedule> afterSchedule = scheduleMapper.selectList(Wrappers.<ContractPaymentSchedule>lambdaQuery().eq(ContractPaymentSchedule::getContractId, contractId)
//                                .gt(ContractPaymentSchedule::getStageOrder, schedule.getStageOrder()));
//                        if (ArrayUtil.isEmpty(afterSchedule.toArray())) {
//                            schedule.setEffectiveEndDate(contract.getExpirationDate());
//                        }
                scheduleMapper.updateById(schedule);
                //查询是否有之前阶段
//                        ContractPaymentSchedule beforeSchedule = scheduleMapper.selectOne(Wrappers.<ContractPaymentSchedule>lambdaQuery().eq(ContractPaymentSchedule::getContractId, schedule.getContractId())
//                                .lt(ContractPaymentSchedule::getStageOrder, schedule.getStageOrder()).orderByDesc(ContractPaymentSchedule::getCreateTime).last("limit 1"));
//                        if (ObjUtil.isNotNull(beforeSchedule)) {
//                            beforeSchedule.setEffectiveEndDate(schedule.getEffectiveDate());
//                            scheduleMapper.updateById(beforeSchedule);
//                        }
                //更新履约
                ContractPaymentScheduleProcess contractPaymentScheduleProcess = new ContractPaymentScheduleProcess();
                contractPaymentScheduleProcess.setContractId(schedule.getContractId());
                contractPaymentScheduleProcess.setContractName(schedule.getContractName());
                contractPaymentScheduleProcess.setScheduleId(schedule.getId());
                contractPaymentScheduleProcess.setScheduleName(schedule.getStageName());
                contractPaymentScheduleProcess.setProcessDate(addDTO.getOutBoundTime());
                ContractPaymentScheduleProcess lastProcess = scheduleProcessMapper.selectOne(Wrappers.<ContractPaymentScheduleProcess>lambdaQuery().eq(ContractPaymentScheduleProcess::getContractId, schedule.getContractId())
                        .eq(ContractPaymentScheduleProcess::getScheduleId, schedule.getId()).last("limit 1"));
                if (ObjUtil.isNull(lastProcess)) {
                    scheduleProcessMapper.insert(contractPaymentScheduleProcess);
                }
            }
 
            //查询是否有后续阶段
            List<ContractPaymentSchedule> afterSchedule = scheduleMapper.selectList(Wrappers.<ContractPaymentSchedule>lambdaQuery()
                    .eq(ContractPaymentSchedule::getContractId, schedule.getContractId())
                    .gt(ContractPaymentSchedule::getStageOrder, schedule.getStageOrder())
                    .orderByAsc(ContractPaymentSchedule::getCreateTime));
            if (ArrayUtil.isNotEmpty(afterSchedule.toArray()) && afterSchedule.size() == 1) {
                //最后阶段生效时间
                ContractPaymentSchedule endSchedule = afterSchedule.get(0);
                if (StrUtil.equals(endSchedule.getStageName(), "质保金")) {
//                            endSchedule.setEffectiveEndDate(DateUtil.offsetDay(addDTO.getOutBoundTime(), endSchedule.getAgreedDays()));
//                            scheduleMapper.updateById(endSchedule);
                    //当前阶段生效时间
//                            schedule.setEffectiveEndDate(DateUtil.offsetDay(addDTO.getOutBoundTime(), schedule.getAgreedDays()));
//                            scheduleMapper.updateById(schedule);
                    //最后阶段应收
                    PaymentConfirm newConfim = new PaymentConfirm();
                    newConfim.setBusinessType(endSchedule.getStageName() + "应收");
                    newConfim.setBusGuestId(contract.getPartyAId());
                    newConfim.setBusGuestName(contract.getPartyA());
                    newConfim.setContractId(contract.getId());
                    newConfim.setContractName(contract.getContractName());
                    newConfim.setContractNo(contract.getContractNo());
                    newConfim.setScheduleId(endSchedule.getId());
                    newConfim.setScheduleName(schedule.getStageName());
                    newConfim.setConfirmTime(addDTO.getOutBoundTime());
                    newConfim.setTransationAmount(endSchedule.getPlannedAmount());
                    newConfim.setReceivableAmount(endSchedule.getPlannedAmount());
                    PaymentConfirm lastNewConfirm = paymentConfirmMapper.selectOne(Wrappers.<PaymentConfirm>lambdaQuery().eq(PaymentConfirm::getContractId, contract.getId())
                            .orderByDesc(PaymentConfirm::getCreateTime).last("limit 1"));
                    BigDecimal lastNewTotal = new BigDecimal("0");
                    if (ObjUtil.isNotNull(lastNewConfirm)) {
                        lastNewTotal = lastNewConfirm.getTotalAmount();
                    }
                    newConfim.setTotalAmount(lastNewTotal.subtract(newConfim.getReceivableAmount()));
                    if (endSchedule.getPaymentRatio().compareTo(new BigDecimal("0")) > 0) {
                        paymentConfirmMapper.insert(newConfim);
                    }
                }
                //更新合同下个阶段
                contract.setNextScheduleName(endSchedule.getStageName());
                contractMapper.updateById(contract);
            }
            if (ArrayUtil.isNotEmpty(afterSchedule.toArray()) && afterSchedule.size() > 1) {
                //更新合同下个阶段
                contract.setNextScheduleName(afterSchedule.get(0).getStageName());
                contractMapper.updateById(contract);
            }
            if (ArrayUtil.isEmpty(afterSchedule.toArray())) {
//                        schedule.setEffectiveEndDate(contract.getExpirationDate());
//                        scheduleMapper.updateById(schedule);
                //更新合同下个阶段
                contract.setNextScheduleName("无");
                contractMapper.updateById(contract);
                //当前为合同最后阶段
                PaymentConfirm lastNewConfirm = paymentConfirmMapper.selectOne(Wrappers.<PaymentConfirm>lambdaQuery().eq(PaymentConfirm::getContractId, contract.getId())
                        .orderByDesc(PaymentConfirm::getCreateTime).last("limit 1"));
                if (lastNewConfirm.getTotalAmount().compareTo(new BigDecimal("0")) >= 0) {
                    //有预付且超过应收 关闭合同状态
                    contract.setContractStatus(3);
                    contractMapper.updateById(contract);
                }
            }
        }
        return R.ok();
    }
 
    /**
     * 生成格式为: yyyyMMdd + 4位序列号 (例如: 20260629000001)
     */
    public  String generateSMJContractNo() {
        // 1. 获取当前日期字符串
        String dateStr = DateUtil.format(new Date(), "yyyyMMdd");
 
        // 2. 构建 Redis Key,按天隔离,例如: order:no:20260629
        String key = "ZB-SMJ-CK:" + dateStr;
 
        // 3. Redis 原子递增,设置过期时间为2天(防止Key堆积,同时覆盖跨天边界情况)
        Long sequence = redisTemplate.opsForValue().increment(key, 1);
        redisTemplate.expire(key, 1, java.util.concurrent.TimeUnit.DAYS);
 
        // 4. 格式化序列号,不足6位前补0
        String seqStr = String.format("%04d", sequence);
 
        // 5. 拼接返回
        return "ZB-SMJ-CK-"+dateStr + seqStr;
    }
 
    public  String generateYMJContractNo() {
        // 1. 获取当前日期字符串
        String dateStr = DateUtil.format(new Date(), "yyyyMMdd");
 
        // 2. 构建 Redis Key,按天隔离,例如: order:no:20260629
        String key = "ZB-YMJ-CK:" + dateStr;
 
        // 3. Redis 原子递增,设置过期时间为2天(防止Key堆积,同时覆盖跨天边界情况)
        Long sequence = redisTemplate.opsForValue().increment(key, 1);
        redisTemplate.expire(key, 1, java.util.concurrent.TimeUnit.DAYS);
 
        // 4. 格式化序列号,不足6位前补0
        String seqStr = String.format("%04d", sequence);
 
        // 5. 拼接返回
        return "ZB-YMJ-CK-"+dateStr + seqStr;
    }
 
    public  String generateJXCContractNo() {
        // 1. 获取当前日期字符串
        String dateStr = DateUtil.format(new Date(), "yyyyMMdd");
 
        // 2. 构建 Redis Key,按天隔离,例如: order:no:20260629
        String key = "ZB-JXC-CK:" + dateStr;
 
        // 3. Redis 原子递增,设置过期时间为2天(防止Key堆积,同时覆盖跨天边界情况)
        Long sequence = redisTemplate.opsForValue().increment(key, 1);
        redisTemplate.expire(key, 1, java.util.concurrent.TimeUnit.DAYS);
 
        // 4. 格式化序列号,不足6位前补0
        String seqStr = String.format("%04d", sequence);
 
        // 5. 拼接返回
        return "ZB-JXC-CK-"+dateStr + seqStr;
    }
 
    public  String generateTFContractNo() {
        // 1. 获取当前日期字符串
        String dateStr = DateUtil.format(new Date(), "yyyyMMdd");
 
        // 2. 构建 Redis Key,按天隔离,例如: order:no:20260629
        String key = "ZB-TF-CK:" + dateStr;
 
        // 3. Redis 原子递增,设置过期时间为2天(防止Key堆积,同时覆盖跨天边界情况)
        Long sequence = redisTemplate.opsForValue().increment(key, 1);
        redisTemplate.expire(key, 1, java.util.concurrent.TimeUnit.DAYS);
 
        // 4. 格式化序列号,不足6位前补0
        String seqStr = String.format("%04d", sequence);
 
        // 5. 拼接返回
        return "ZB-TF-CK-"+dateStr + seqStr;
    }
 
    public  String generateGYBContractNo() {
        // 1. 获取当前日期字符串
        String dateStr = DateUtil.format(new Date(), "yyyyMMdd");
 
        // 2. 构建 Redis Key,按天隔离,例如: order:no:20260629
        String key = "ZB-GYB-CK:" + dateStr;
 
        // 3. Redis 原子递增,设置过期时间为2天(防止Key堆积,同时覆盖跨天边界情况)
        Long sequence = redisTemplate.opsForValue().increment(key, 1);
        redisTemplate.expire(key, 1, java.util.concurrent.TimeUnit.DAYS);
 
        // 4. 格式化序列号,不足6位前补0
        String seqStr = String.format("%04d", sequence);
 
        // 5. 拼接返回
        return "ZB-GYB-CK-"+dateStr + seqStr;
    }
}