Cui Zhi Feng
2024-08-28 6b7dc98d1df2fe513b93f4ade4e97516bcbc75db
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
package com.mzl.flower.service.payment;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mzl.flower.config.exception.ValidationException;
import com.mzl.flower.config.security.SecurityUtils;
import com.mzl.flower.constant.Constants;
import com.mzl.flower.dto.request.payment.*;
import com.mzl.flower.dto.response.flower.ParamItemDTO;
import com.mzl.flower.dto.response.flower.StationStatisticDTO;
import com.mzl.flower.dto.response.payment.*;
import com.mzl.flower.dto.response.supplier.SupplierOrderDTO;
import com.mzl.flower.entity.payment.*;
import com.mzl.flower.entity.supplier.Station;
import com.mzl.flower.entity.supplier.Supplier;
import com.mzl.flower.entity.system.User;
import com.mzl.flower.mapper.flower.FlowerCategoryMapper;
import com.mzl.flower.mapper.flower.FlowerMapper;
import com.mzl.flower.mapper.payment.*;
import com.mzl.flower.mapper.supplier.StationMapper;
import com.mzl.flower.service.BaseService;
import com.mzl.flower.service.flower.FlowerParamService;
import com.mzl.flower.utils.UUIDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import static java.time.format.DateTimeFormatter.BASIC_ISO_DATE;
 
@Slf4j
@Service
@Transactional
public class DeliveryOrderService extends BaseService {
 
    @Autowired
    private DeliveryOrderMapper deliveryOrderMapper;
 
    @Autowired
    private DeliveryOrderItemMapper deliveryOrderItemMapper;
 
    @Autowired
    private OrderMapper orderMapper;
 
    @Autowired
    private OrderItemMapper orderItemMapper;
 
    @Autowired
    private StationMapper stationMapper;
 
    @Autowired
    private OrderSettlementMapper settlementMapper;
 
    @Autowired
    private OrderItemSalesMapper orderItemSalesMapper;
 
    @Autowired
    private OrderItemCheckMapper orderItemCheckMapper;
 
    @Autowired
    private OrderItemSettlementService orderItemSettlementService;
 
    public void createDeliveryOrder(Order order) {
        String orderId = order.getId();
        String orderNo = order.getOrderNo();
        List<OrderItem> ls = orderItemMapper.selectList(new QueryWrapper<OrderItem>()
                .eq("order_id", orderId));
        Map<Long, String> map = new HashMap<>();
        for (OrderItem item : ls) {
            Long supplierId = item.getSupplierId();
            String deliveryId = map.get(supplierId);
            if (deliveryId == null) {
                DeliveryOrder d = new DeliveryOrder();
                d.setId(UUIDGenerator.getUUID());
                d.setOrderId(orderId);
                d.setOrderNo(orderNo);
                d.setSupplierId(supplierId);
                d.setStatus(Constants.DELIVERY_ORDER_STATUS.NO_LOCATION.name());
                d.create("sys");
                d.setCreateTime(order.getCreateTime());//使用下单时间作为配送单时间
                deliveryOrderMapper.insert(d);
                map.put(supplierId, d.getId());
                deliveryId = d.getId();
            }
 
            DeliveryOrderItem di = new DeliveryOrderItem();
            di.setId(UUIDGenerator.getUUID());
            di.setDeliveryId(deliveryId);
            di.setOrderItemId(item.getId());
            di.setOrderId(orderId);
            di.create("sys");
            di.setCreateTime(order.getCreateTime());//使用下单时间作为配送单时间
            deliveryOrderItemMapper.insert(di);
 
            orderItemSettlementService.createItemSettlement(item);
        }
    }
 
    public void setDeliveryOrderPending(String orderId) {
        deliveryOrderMapper.setDeliveryOrderPending(orderId);
    }
 
    public void refundDelete(String orderId) {
        deliveryOrderMapper.deleteByOrderId(orderId);
    }
 
    public Page<DeliveryOrderListDTO> selectDeliveryOrderList(Page page, DeliveryOrderQueryDTO dto) {
        Supplier s = getCurrentSupplier();
        dto.setStatusList(splitParam(dto.getStatus()));
        List<DeliveryOrderListDTO> ls = deliveryOrderMapper.selectDoList(page, s.getId(), dto);
        if (ls != null && ls.size() > 0) {
            List<String> dIds = new ArrayList<>();
            for (DeliveryOrderListDTO d : ls) {
                dIds.add(d.getId());
            }
            List<DeliveryOrderItem> dItems = deliveryOrderItemMapper.selectList(new QueryWrapper<DeliveryOrderItem>().in("delivery_id", dIds));
            List<String> itemIds = new ArrayList<>();
            for (DeliveryOrderItem di : dItems) {
                itemIds.add(di.getOrderItemId());
            }
            List<OrderItem> items = orderItemMapper.selectBatchIds(itemIds);
            Map<String, List<OrderItemListDTO>> itemMap = new HashMap<>();
            for (OrderItem oi : items) {
                String orderId = oi.getOrderId();
                List<OrderItemListDTO> ii = itemMap.computeIfAbsent(orderId, k -> new ArrayList<>());
                OrderItemListDTO dd = new OrderItemListDTO();
                BeanUtils.copyProperties(oi, dd);
                dd.setPrice(oi.getSupplierPrice());
                ii.add(dd);
            }
 
            for (DeliveryOrderListDTO d : ls) {
                d.setItems(itemMap.get(d.getOrderId()));
            }
        }
 
        page.setRecords(ls);
        return page;
    }
 
    public Page<DeliveryOrderItemStatisticsDTO> selectDoItemListByTime(Page page, String day){
        LocalDate date = parseLocalDate(day);
        Supplier s = getCurrentSupplier();
        LocalDateTime fivePm = date.atTime(17, 0, 0);
        List<DeliveryOrderItemStatisticsDTO> ls = deliveryOrderItemMapper.selectDoItemListByTime(page
                , s.getId(), fivePm.plusDays(-1), fivePm);
 
        page.setRecords(ls);
        return page;
    }
 
    public Page<DeliveryOrderItemSettlementDTO> selectSettlementListByTime(Page page, String day){
        LocalDate date = parseLocalDate(day);
        Supplier s = getCurrentSupplier();
        LocalDateTime fivePm = date.atTime(17, 0, 0);
        List<DeliveryOrderItemSettlementDTO> ls = deliveryOrderItemMapper.selectSettlementListByTime(page
                , s.getId(), fivePm.plusDays(-1), fivePm);
        if(ls != null && ls.size() > 0){
            for(DeliveryOrderItemSettlementDTO dto : ls){
                dto.setTotalAmount(dto.getPrice().multiply(new BigDecimal(dto.getNum())));
            }
        }
 
        page.setRecords(ls);
        return page;
    }
 
    public Page<DeliveryOrderStatisticsDTO> selectSupplierDoStatistics(Page page){
        LocalDate theDay = parseLocalDate("2024-08-03");
 
        long current = page.getCurrent();
        long size = page.getSize();
        LocalDate now = LocalDate.now();
        current = current == 0 ? 1 : current;
 
        long endDays = (current - 1) * size;
        long beginDays = endDays + size;
        LocalDate beginDate = now.plusDays(-beginDays);
        LocalDate endDate = now.plusDays(-endDays);
 
        if(endDate.isBefore(theDay)){
            return page;
        }
 
        if(beginDate.isBefore(theDay)){
            beginDate = theDay;
        }
 
        Supplier s = getCurrentSupplier();
        List<DeliveryOrderStatisticsDTO> ls = new ArrayList<>();
        while (!beginDate.isAfter(endDate)) {
            LocalDateTime fivePm = endDate.atTime(17, 0, 0);
            DeliveryOrderItemStatisticsDTO d = deliveryOrderItemMapper.getSupplierStatisticsByTime(s.getId()
                    , fivePm.plusDays(-1), fivePm);
 
            DeliveryOrderStatisticsDTO dto = new DeliveryOrderStatisticsDTO();
            dto.setDate(endDate);
            dto.setNum(0);
            dto.setPrice(new BigDecimal(0));
            if(d != null) {
                dto.setNum(d.getNum() == null ? 0 : d.getNum());
                dto.setPrice(d.getPrice() == null ? new BigDecimal(0) : d.getPrice());
            }
            ls.add(dto);
            endDate = endDate.plusDays(-1);
        }
 
        page.setRecords(ls);
        return page;
    }
 
    public List<DeliveryOrderItemListDTO> getDeliveryOrderItems(String id) {
        return deliveryOrderItemMapper.selectDoItemList(id);
    }
 
    public DeliveryOrderItemDTO getSupplierDeliveryOrderItem(String id) {
        DeliveryOrderItemDTO dto = new DeliveryOrderItemDTO();
 
        Supplier s = getCurrentSupplier();
        dto.setSupplierName(s.getName());
 
        DeliveryOrderItem item = deliveryOrderItemMapper.selectById(id);
        Order d = orderMapper.selectById(item.getOrderId());
        dto.setOrderNo(d.getOrderNo());
        dto.setWarehouseName(d.getWarehouseName());
        dto.setWarehouseLocationCode(d.getWarehouseLocationCode());
 
        OrderItem oi = orderItemMapper.selectById(item.getOrderItemId());
        if (!oi.getSupplierId().equals(s.getId())) {
            throw new ValidationException("商品分配有误");
        }
        dto.setFlowerName(oi.getFlowerName());
        dto.setFlowerColor(oi.getFlowerColor());
        dto.setFlowerUnit(oi.getFlowerUnit());
        dto.setFlowerLevel(oi.getFlowerLevel());
        dto.setFlowerCategory(oi.getFlowerCategory());
 
        dto.setParams(parseArray(oi.getFlowerParams(), ParamItemDTO.class));
 
        return dto;
    }
 
    public DeliveryOrderItemDTO getDeliveryOrderItem(String id) {
        DeliveryOrderItemDTO dto = new DeliveryOrderItemDTO();
 
        OrderItem oi = orderItemMapper.selectById(id);
        Order d = orderMapper.selectById(oi.getOrderId());
        dto.setOrderNo(d.getOrderNo());
        dto.setWarehouseName(d.getWarehouseName());
        dto.setWarehouseLocationCode(d.getWarehouseLocationCode());
 
        Supplier s = supplierMapper.selectById(oi.getSupplierId());
        dto.setSupplierName(s.getName());
 
        dto.setFlowerName(oi.getFlowerName());
        dto.setFlowerColor(oi.getFlowerColor());
        dto.setFlowerUnit(oi.getFlowerUnit());
        dto.setFlowerLevel(oi.getFlowerLevel());
        dto.setFlowerCategory(oi.getFlowerCategory());
 
        dto.setParams(parseArray(oi.getFlowerParams(), ParamItemDTO.class));
 
        return dto;
    }
 
    public void arrived(DeliveryOrderArriveDTO dto) {
        DeliveryOrder d = deliveryOrderMapper.selectById(dto.getId());
        Supplier s = getCurrentSupplier();
        if (s == null || !d.getSupplierId().equals(s.getId())) {
            throw new ValidationException("无权操作");
        }
 
        List<String> arriveImageList = dto.getArriveImageList();
        if (arriveImageList == null || arriveImageList.size() == 0) {
            throw new ValidationException("没有上传照片");
        }
 
        d.setArriveImages(toJSONString(arriveImageList));
        d.setArriveTime(LocalDateTime.now());
        d.setArriveRemarks(dto.getArriveRemarks());
        d.setStatus(Constants.DELIVERY_ORDER_STATUS.ARRIVED.name());
        d.update(SecurityUtils.getUserId());
        deliveryOrderMapper.updateById(d);
    }
 
    public Page<DeliveryOrderStationListDTO> selectDoStationList(Page page, DeliveryOrderStationQueryDTO dto) {
        List<DeliveryOrderStationListDTO> ls = deliveryOrderMapper.selectDoStationList(page, dto);
 
        page.setRecords(ls);
        return page;
    }
 
    public DeliveryOrderCheckDTO getDeliverOrderInfo(String id) {
        DeliveryOrderCheckDTO dto = new DeliveryOrderCheckDTO();
        DeliveryOrder d = deliveryOrderMapper.selectById(id);
        dto.setId(id);
        dto.setOrderNo(d.getOrderNo());
        dto.setArriveRemarks(d.getArriveRemarks());
        dto.setArriveImages(d.getArriveImages());
        dto.setArriveImageList(parseArray(d.getArriveImages(), String.class));
        dto.setArriveTime(d.getArriveTime());
 
        Supplier s = supplierMapper.selectById(d.getSupplierId());
        dto.setSupplierName(s.getName());
 
        Station st = stationMapper.selectById(s.getStationId());
        dto.setStationName(st.getName());
 
        List<DeliveryOrderItemCheckDTO> items = deliveryOrderItemMapper.selectDoItemCheckList(id);
 
        dto.setItems(items);
        return dto;
    }
 
    public void doCheck(OrderItemCheckDTO dto) {
        OrderItem oi = orderItemMapper.selectById(dto.getId());
        oi.setStatus(dto.getStatus());
        oi.setCheckImages(toJSONString(dto.getCheckImageList()));
        oi.setCheckRemarks(dto.getCheckRemarks());
        oi.setCheckTime(LocalDateTime.now());
        oi.setDeductAmount(dto.getDeductAmount());
        oi.update(SecurityUtils.getUserId());
        orderItemMapper.updateById(oi);
    }
 
    public String completeCheck(String id) {
        DeliveryOrder d = deliveryOrderMapper.selectById(id);
        return completeCheck(d);
    }
 
    private String completeCheck(DeliveryOrder d){
        d.setCheckTime(LocalDateTime.now());
        d.setStatus(Constants.DELIVERY_ORDER_STATUS.CHECKED.name());
        d.update(SecurityUtils.getUserId());
        deliveryOrderMapper.updateById(d);
 
        List<OrderItem> items = orderItemMapper.selectList(new QueryWrapper<OrderItem>()
                .eq("supplier_id", d.getSupplierId())
                .eq("order_id", d.getOrderId())
                .isNull("status")
        );
        if (items != null && items.size() > 0) {
            for (OrderItem i : items) {
                i.setStatus(Constants.CHECK_OPERATE.ok.name());
                i.setCheckTime(LocalDateTime.now());
                orderItemMapper.updateById(i);
            }
        }
 
        return d.getOrderId();
    }
 
    public void checkOrderStatus(String orderId) {
        int count = orderItemMapper.selectCount(new QueryWrapper<OrderItem>()
                .eq("order_id", orderId)
                .isNull("status")
        );
        if (count == 0) {
            Order o = orderMapper.selectById(orderId);
            o.setStatusBackend(Constants.ORDER_STATUS_BACKEND.SEND.name());
            o.update(SecurityUtils.getUserId());
            orderMapper.updateById(o);
        }
    }
 
    public SupplierOrderDTO getCurrentSupplierOrderStatistics() {
        Supplier supplier = getCurrentSupplier();
        SupplierOrderDTO dto = new SupplierOrderDTO();
        if (supplier != null) {
            Long supplierId = supplier.getId();
            String userId = SecurityUtils.getUserId();
            BigDecimal income = settlementMapper.getUserIncome(userId);
            dto.setIncome(income == null ? new BigDecimal(0) : income);
 
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime towAm = LocalDate.now().atTime(2, 0, 0);
            LocalDateTime fivePm = LocalDate.now().atTime(17, 0, 0);
            LocalDateTime startDate;
            LocalDateTime endDate;
            if (now.isAfter(towAm)) {
                startDate = fivePm.plusDays(-1);
                endDate = fivePm;
            } else {
                startDate = fivePm.plusDays(-2);
                endDate = fivePm.plusDays(-1);
            }
 
            Integer orderCountToday = deliveryOrderMapper.selectCount(new QueryWrapper<DeliveryOrder>()
                    .eq("supplier_id", supplierId)
                    .gt("create_time", startDate)
                    .le("create_time", endDate));
            dto.setOrderCountToday(orderCountToday == null ? 0 : orderCountToday);
 
            Integer orderCountYesterday = deliveryOrderMapper.selectCount(new QueryWrapper<DeliveryOrder>()
                    .eq("supplier_id", supplierId)
                    .gt("create_time", startDate.plusDays(-1))
                    .le("create_time", endDate.plusDays(-1)));
            dto.setOrderCountYesterday(orderCountYesterday == null ? 0 : orderCountYesterday);
 
            LocalDateTime ffPm = LocalDate.now().withDayOfMonth(1).atTime(17, 0, 0).plusDays(-1);
            Integer orderCountMonth = deliveryOrderMapper.selectCount(new QueryWrapper<DeliveryOrder>()
                    .eq("supplier_id", supplierId)
                    .gt("create_time", ffPm));
            dto.setOrderCountMonth(orderCountMonth == null ? 0 : orderCountMonth);
 
            BigDecimal salesRate = new BigDecimal(0);
            Integer orderTotal = deliveryOrderMapper.selectCount(new QueryWrapper<DeliveryOrder>()
                    .eq("supplier_id", supplierId));
            Integer salesCount = orderItemSalesMapper.getSupplierSalesCount(supplierId);
            if (orderTotal != null && orderTotal > 0) {
                BigDecimal rate = new BigDecimal(salesCount).divide(new BigDecimal(orderTotal), 2, RoundingMode.HALF_UP);
                salesRate = rate;
            }
            dto.setSalesRate(salesRate);
 
            Integer deliverCount = deliveryOrderItemMapper.getDoItemCount(supplierId, Constants.DELIVERY_ORDER_STATUS.NO_LOCATION.name(), startDate, endDate);
            dto.setDeliverCount(deliverCount == null ? 0 : deliverCount);
 
            Integer deliverTotal = deliveryOrderItemMapper.getDoItemCount(supplierId, null, startDate, endDate);
            dto.setDeliverTotal(deliverTotal == null ? 0 : deliverTotal);
            dto.setDealCountToday(deliverTotal);
 
            LocalDateTime e = LocalDate.now().withDayOfMonth(1).atTime(17, 0, 0).plusDays(-1);
            LocalDateTime s = e.plusMonths(-1);
            Integer dealCountLastMonth = deliveryOrderItemMapper.getDoItemCount(supplierId, null, s, e);
            dto.setDealCountLastMonth(dealCountLastMonth);
 
            LocalDateTime s1 = endDate.plusDays(-30);
            Integer dealCountDay30 = deliveryOrderItemMapper.getDoItemCount(supplierId, null, s1, endDate);
            dto.setDealCountDay30(dealCountDay30);
        }
 
        return dto;
    }
 
    public List<StationStatisticDTO> statisticStationList(String name, LocalDateTime startDate, LocalDateTime endDate) {
        String userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<Station> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(Station::getUserIds, userId);
        lambdaQueryWrapper.eq(Station::getType, "0");
        boolean hasZc = stationMapper.selectCount(lambdaQueryWrapper)>0;//当前用户是否有总仓权限,总仓能查看到所有集货站的数据
        if(hasZc){
            List<StationStatisticDTO> stationStatisticDTOS = deliveryOrderMapper.statisticStationList(startDate, endDate,name,null);
            return stationStatisticDTOS;
        }else{
            List<StationStatisticDTO> stationStatisticDTOS = deliveryOrderMapper.statisticStationList(startDate, endDate,name,userId);
            return stationStatisticDTOS;
        }
    }
 
    //////////////////////////////////////////////////////////////新接口
    public Page<DeliveryOrderList4CheckDTO> selectSupplierDoList4Check(Page page, DeliveryOrderStationQueryDTO dto) {
        List<DeliveryOrderList4CheckDTO> ls = deliveryOrderMapper.selectSupplierDoList4Check(page, dto);
 
        page.setRecords(ls);
        return page;
    }
 
    public Page<DeliveryOrder4CheckDTO> selectSupplierDoInfo4Check(Page page, DeliveryOrderInfoSpQueryDTO dto) {
        if(dto.getSupplierId() == null){
            throw new ValidationException("供应商id不能为空");
        }
        List<DeliveryOrder4CheckDTO> ls = deliveryOrderMapper.selectSupplierDoInfo4Check(page, dto);
 
        if(ls != null && ls.size() > 0){
            List<String> deliveryIds = new ArrayList<>();
            for(DeliveryOrder4CheckDTO c : ls){
                deliveryIds.add(c.getId());
            }
 
            List<DeliveryOrderItem4CheckDTO> itemList = deliveryOrderItemMapper.selectDoItemList4Check(deliveryIds);
            Map<String, List<DeliveryOrderItem4CheckDTO>> itemsMap = new HashMap<>();
            for(DeliveryOrderItem4CheckDTO d : itemList){
                String deliveryId = d.getDeliveryId();
                List<DeliveryOrderItem4CheckDTO> cc = itemsMap.computeIfAbsent(deliveryId, k -> new ArrayList<>());
                cc.add(d);
            }
 
            for(DeliveryOrder4CheckDTO c : ls){
                c.setArriveImageList(parseArray(c.getArriveImages(), String.class));
                c.setItems(itemsMap.get(c.getId()));
            }
        }
 
        page.setRecords(ls);
        return page;
    }
 
    public String setCheckAuditStatus(String id, String auditStatus){
        OrderItemCheck c = orderItemCheckMapper.selectById(id);
        if(StringUtils.isNotEmpty(c.getAuditStatus())){
            throw new ValidationException("不可重复审核");
        }
        c.setAuditStatus(auditStatus);
        c.setAuditTime(LocalDateTime.now());
        c.update(SecurityUtils.getUserId());
        orderItemCheckMapper.updateById(c);
 
        return c.getOrderItemId();
    }
 
    public void doAfterCheckAudit(String orderItemId){
        OrderItem oi = orderItemMapper.selectById(orderItemId);
        oi.setDeductAmount(calculateOrderItemDeduct(orderItemId));//设置应该退款的金额
        orderItemMapper.updateById(oi);
 
        orderItemSettlementService.saveItemSettlementInfo(oi, SecurityUtils.getUserId(), Constants.S_TYPE.CHECK);
    }
 
    private BigDecimal calculateOrderItemDeduct(String id){
        List<OrderItemCheck> cLs = orderItemCheckMapper.selectList(new QueryWrapper<OrderItemCheck>()
                .eq("order_item_id", id)
                .eq("audit_status", Constants.CHECK_AUDIT_STATUS.AGREED.name())
        );
        BigDecimal deduct = new BigDecimal(0);
 
        if(cLs != null && cLs.size() > 0){
            for(OrderItemCheck c : cLs){
                if(Constants.CHECK_TYPE.reduce.name().equals(c.getType())){
                    deduct = deduct.add(c.getDeductAmount());
                } else if(Constants.CHECK_TYPE.lack.name().equals(c.getType())){
                    deduct = deduct.add(c.getDeductAmount());
                }
            }
        }
 
        return deduct;
    }
 
    public OrderItemCheckReduceDTO getReduceCheck(String itemId){
        OrderItemCheck c = orderItemCheckMapper.selectOne(new QueryWrapper<OrderItemCheck>()
                .eq("type", Constants.CHECK_TYPE.reduce.name())
                .eq("order_item_id", itemId)
        );
        OrderItemCheckReduceDTO dto = new OrderItemCheckReduceDTO();
        dto.setOrderItemId(itemId);
        dto.setType(Constants.CHECK_TYPE.reduce.name());
        if(c != null){
            BeanUtils.copyProperties(c, dto);
            dto.setPictureList(parseArray(c.getPictures(), String.class));
            User user = userMapper.selectById(c.getCreateBy());
            dto.setCreateName(user.getNickName());
        }
 
        return dto;
    }
 
    public OrderItemCheckNumDTO getOtherCheck(String itemId, String type){
        OrderItemCheck c = orderItemCheckMapper.selectOne(new QueryWrapper<OrderItemCheck>()
                .eq("type", type)
                .eq("order_item_id", itemId)
        );
        OrderItemCheckNumDTO dto = new OrderItemCheckNumDTO();
        dto.setOrderItemId(itemId);
        dto.setType(type);
        if(c != null){
            BeanUtils.copyProperties(c, dto);
            User user = userMapper.selectById(c.getCreateBy());
            dto.setCreateName(user.getNickName());
        }
 
        return dto;
    }
 
    public void doReduceCheck(OrderItemCheckCommitReduceDTO dto){
        dto.setType(Constants.CHECK_TYPE.reduce.name());
        doCheck(dto, dto.getPictureList(), dto.getTargetLevel(), dto.getDeductAmount());
    }
 
    public void doCheck(OrderItemCheckCommitDTO dto
            , List<String> pictureList, String targetLevel, BigDecimal deductAmount) {
        if(dto.getNum() == null || dto.getNum() == 0){
            throw new ValidationException("处理数量不能为0");
        }
 
        OrderItem oi = orderItemMapper.selectById(dto.getOrderItemId());
        if(dto.getNum() > oi.getNum()){
            throw new ValidationException("处理数量不能大于商品数量");
        }
 
        BigDecimal deduct = new BigDecimal(0);
        if(Constants.CHECK_TYPE.replace.name().equals(dto.getType())){
            deduct = oi.getSupplierPrice().multiply(new BigDecimal(dto.getNum()));
        } else if(Constants.CHECK_TYPE.lack.name().equals(dto.getType())){
            deduct = oi.getPrice().multiply(new BigDecimal(dto.getNum()));
        } else if (Constants.CHECK_TYPE.reduce.name().equals(dto.getType())) {
            if(deductAmount == null){
                throw new ValidationException("降级金额不能为空");
            }
            deduct = deductAmount.multiply(new BigDecimal(dto.getNum()));
            if(deduct.doubleValue() > oi.getTotal().doubleValue()){
                throw new ValidationException("降级金额不能大于商品总金额");
            }
        }
 
        OrderItemCheck c = orderItemCheckMapper.selectOne(new QueryWrapper<OrderItemCheck>()
                .eq("type", dto.getType())
                .eq("order_item_id", dto.getOrderItemId())
        );
        if(c != null){
            if(StringUtils.isNotEmpty(c.getAuditStatus())){
                throw new ValidationException("已审核,不可修改");
            }
            c.setCheckTime(LocalDateTime.now());
            c.setNum(dto.getNum());
            c.setRemarks(dto.getRemarks());
            c.setPictures(toJSONString(pictureList));
            c.setTargetLevel(targetLevel);
            c.setDeductAmount(deduct);
            c.update(SecurityUtils.getUserId());
            orderItemCheckMapper.updateById(c);
        } else {
            c = new OrderItemCheck();
            c.setId(UUIDGenerator.getUUID());
            c.setOrderItemId(dto.getOrderItemId());
            c.setType(dto.getType());
            c.setOrderId(oi.getOrderId());
            c.setCheckTime(LocalDateTime.now());
            c.setNum(dto.getNum());
            c.setRemarks(dto.getRemarks());
            c.setPictures(toJSONString(pictureList));
            c.setTargetLevel(targetLevel);
            c.setDeductAmount(deduct);
            c.create(SecurityUtils.getUserId());
            orderItemCheckMapper.insert(c);
        }
    }
 
    public void checkOrderItemStatus(String id){
        OrderItem oi = orderItemMapper.selectById(id);
        List<OrderItemCheck> cLs = orderItemCheckMapper.selectList(new QueryWrapper<OrderItemCheck>()
                .eq("order_item_id", id)
        );
        if(cLs != null && cLs.size() > 0){
            oi.setStatus(Constants.ORDER_ITEM_STATUS.abnormal.name());
            oi.setDeductAmount(new BigDecimal(0));
            oi.update(SecurityUtils.getUserId());
            oi.setCheckTime(LocalDateTime.now());
            orderItemMapper.updateById(oi);
        } else {
            oi.setStatus(Constants.ORDER_ITEM_STATUS.ok.name());
            oi.setCheckTime(LocalDateTime.now());
            oi.setDeductAmount(new BigDecimal(0));
            oi.update(SecurityUtils.getUserId());
            orderItemMapper.updateById(oi);
        }
 
        DeliveryOrderItem di = deliveryOrderItemMapper.selectOne(new QueryWrapper<DeliveryOrderItem>()
                .eq("order_item_id", id));
        if(di != null) {
            Integer count = deliveryOrderItemMapper.getUnCheckCount(di.getDeliveryId());
            if(count == 0) {
                DeliveryOrder d = deliveryOrderMapper.selectById(di.getDeliveryId());
                d.setCheckTime(LocalDateTime.now());
                d.setStatus(Constants.DELIVERY_ORDER_STATUS.CHECKED.name());
                d.update(SecurityUtils.getUserId());
                deliveryOrderMapper.updateById(d);
            }
        }
    }
 
    public void deleteCheckInfo(String itemId, String type){
        orderItemCheckMapper.delete(new QueryWrapper<OrderItemCheck>()
                .eq("type", type)
                .eq("order_item_id", itemId)
        );
    }
 
    public void setCheckOk(String itemId){
        int count = orderItemCheckMapper.selectCount(new QueryWrapper<OrderItemCheck>()
                .eq("order_item_id", itemId));
        if(count > 0){
            throw new ValidationException("有其他质检结果,不可设置成无异常");
        }
        OrderItem oi = orderItemMapper.selectById(itemId);
        oi.setStatus(Constants.ORDER_ITEM_STATUS.ok.name());
        oi.setCheckTime(LocalDateTime.now());
        oi.update(SecurityUtils.getUserId());
        orderItemMapper.updateById(oi);
    }
 
    public List<String> completeSupplierCheck(Long supplierId
            , LocalDateTime startDate, LocalDateTime endDate) {
        List<DeliveryOrder> dLs = deliveryOrderMapper.selectSupplierDoEntity4Check(supplierId, startDate, endDate);
        List<String> orderIds = new ArrayList<>();
 
        if(dLs != null && dLs.size() > 0){
            for(DeliveryOrder d : dLs){
                completeCheck(d);
                orderIds.add(d.getOrderId());
            }
        }
 
        return orderIds;
    }
 
    public void checkOrdersStatus(List<String> orderIds) {
        if(orderIds != null && orderIds.size() > 0){
            for(String orderId : orderIds){
                checkOrderStatus(orderId);
            }
        }
    }
}