Administrator
2023-06-19 49588f5a462ae7425e7eb030438a35fd80c246fa
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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
package com.gk.firework.Service.ServiceImpl;
 
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gk.firework.Domain.*;
import com.gk.firework.Domain.BO.DirectionProductBO;
import com.gk.firework.Domain.BO.ProductLocusInfoBO;
import com.gk.firework.Domain.BO.SaleOrderDetailInfoBO;
import com.gk.firework.Domain.DO.ProductDO;
import com.gk.firework.Domain.Exception.BusinessException;
import com.gk.firework.Domain.Extension.StockTotal;
import com.gk.firework.Domain.Utils.Msg;
import com.gk.firework.Domain.Utils.PageInfo;
import com.gk.firework.Domain.Utils.StringUtils;
import com.gk.firework.Domain.Vo.*;
import com.gk.firework.Mapper.ProductInfoMapper;
import com.gk.firework.Mapper.StockInfoMapper;
import com.gk.firework.Service.*;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
 
import java.math.BigDecimal;
import java.util.*;
 
import static com.gk.firework.Domain.Enum.ErrorCode.*;
 
/**
 * @author : jingjy
 * @date : 2021/3/24 14:04
 */
@Service("StockService")
public class StockServiceImpl extends ServiceImpl<StockInfoMapper, StockInfo> implements StockService {
    @Autowired
    private StockInfoMapper stockInfoMapper;
    @Autowired
    private ProductInfoMapper productInfoMapper;
    @Autowired
    private ProductLocusService productLocusService;
    @Autowired
    private ProductService productService;
    @Autowired
    private UserService userService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private SoldNoStockService soldNoStockService;
    @Autowired
    private EntryService entryService;
    @Autowired
    private SaleOrderService saleOrderService;
    @Autowired
    private SaleOrderDetailService saleOrderDetailService;
    @Autowired
    private DeliveryOrderService deliveryOrderService;
    @Autowired
    private WarnContentService warnContentService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private StaticStockService staticStockService;
 
    /** 入库 **/
    @Override
    public boolean putInStorage(UserInfo userInfo, List<ProductVo> productVos, Date datetime, String type) {
        boolean flag = false;
        for (ProductVo productVo : productVos){
            StockInfo stockInfo = selectStockByDirection(productVo.getDirectionCode());
            ProductInfo productInfo = productInfoMapper.selectProductByDirectionCode(productVo.getItemCode());
            ProductLocusInfo productLocusInfo = new ProductLocusInfo();
            //如果为空则创建
            if (stockInfo == null){
                stockInfo = new StockInfo();
                stockInfo.setDirectioncode(productVo.getDirectionCode());
                stockInfo.setCreateddate(new Date());
                stockInfo.setCreatedby(userInfo.getUsername());
                stockInfo.setDirectionboxcode(String.format("%03d",productVo.getBoxNumber()));
                stockInfo.setModifieddate(datetime);
                stockInfo.setNum(1);
                stockInfo.setOperator(userInfo.getUsername());
                stockInfo.setIndate(datetime);
                stockInfo.setProductid(productInfo.getId());
                stockInfo.setOwner(userInfo.getCompanyid().toString());
                stockInfo.setFlag((byte)0);
                stockInfo.setType(Byte.parseByte(type));
                int i = insertStockInfo(stockInfo);
                if (i == 1){ flag = true; }
                productLocusInfo = new ProductLocusInfo(productVo.getDirectionCode(),new Date(),
                        datetime,userInfo.getCompany(),null,ProductLocusInfo.ENTRY_STATUS,
                        productVo.getBoxNumber().toString());
                productLocusService.insertProductLocus(productLocusInfo);
            }else {
                //一般入库
                if (EntryUtils.RK_ENTRY.equals(type)){
                    // 判断入库是否大于修改时间,小于修改时间不做修改
                    if (stockInfo.getModifieddate().compareTo(datetime) > 0 ){
                        continue;
                    }
 
                    //如果不为空,判断flag,如果flag=1,则不进行修改,只记录流向,否则修改owner
                    if (stockInfo.getFlag() == 0){
                        stockInfo.setModifieddate(datetime);
                        stockInfo.setModifiedby(userInfo.getUsername());
                        stockInfo.setIndate(datetime);
                        stockInfo.setOwner(userInfo.getCompanyid().toString());
                        stockInfo.setFlag((byte)0);
                        stockInfo.setStatus("");
                    }
                    productLocusInfo = new ProductLocusInfo(productVo.getDirectionCode(),new Date(),
                            datetime,userInfo.getCompany(),null,ProductLocusInfo.ENTRY_STATUS,
                            productVo.getBoxNumber().toString());
 
                }else if (EntryUtils.TH_ENTRY.equals(type)){
                    //退货入库
                    //未使用
                    stockInfo.setOwner(userInfo.getCompanyid().toString());
                    stockInfo.setModifieddate(datetime);
                    stockInfo.setModifiedby(userInfo.getUsername());
                    stockInfo.setStatus("");
                    productLocusInfo = new ProductLocusInfo(productVo.getDirectionCode(),new Date(),
                            datetime,userInfo.getCompany(),null,ProductLocusInfo.RETURN_ENTRY_STATUS,
                            productVo.getBoxNumber().toString());
 
                }
                productLocusService.insertProductLocus(productLocusInfo);
                int i = updateStockInfo(stockInfo);
                if (i == 1){ flag = true; }
            }
        }
        return flag;
    }
 
    @Override
    public void setProductEntryStatus(List<ProductVo> productVos, UserInfo userInfo) {
        if (productVos.size() != 0 && userInfo != null){
 
            for (ProductVo productVo : productVos) {
                if (isStockInfoExist(productVo.getDirectionCode(),userInfo.getCompanyid())){
                    productVo.setEntryFlag("历史入库");
                }else {
                    productVo.setEntryFlag("可以入库");
                }
            }
        }
    }
 
    @Override
    public void deliveryByDetail(Date datetime, List<DeliveryDetailInfo> deliveryDetailInfos, UserInfo userInfo) {
        List<ProductVo>productVos = new ArrayList<>();
        List<ProductLocusInfo>productLocusInfos = new ArrayList<>();
 
        for (DeliveryDetailInfo deliveryDetailInfo : deliveryDetailInfos){
            String dire = deliveryDetailInfo.getDirectioncode();
            DirectionDetail detail = FireworkDeal.dealDirectionCode(dire);
            ProductVo productVo = productInfoMapper.selectProductVoByDirectionCode(detail.getItemCode());
            if (FireworkDeal.is22Characters(dire)){
                FireworkDeal.getProductVos(dire,detail,detail,productVos,productVo);
                ProductLocusInfo productLocusInfo = new ProductLocusInfo(dire,new Date(),datetime,userInfo.getCompany()
                        ,null, ProductLocusInfo.DELIVERY_STATUS,detail.getBoxNo());
                productLocusInfos.add(productLocusInfo);
            }else if (FireworkDeal.is19Characters(dire)){
                productVos.add(productVo);
            }
 
 
        }
 
        for (ProductVo productVo : productVos){
            StockInfo stockInfo = selectStockByDirection(productVo.getDirectionCode());
            DirectionDetail detail = FireworkDeal.dealDirectionCode(productVo.getDirectionCode());
            ProductInfo productInfo = productService.selectByDirection(productVo.getDirectionCode());
            ProductLocusInfo productLocusInfo = new ProductLocusInfo(productVo.getDirectionCode(),new Date(),datetime,userInfo.getCompany()
                    ,null, ProductLocusInfo.DELIVERY_STATUS,detail.getBoxNo());
            productLocusInfos.add(productLocusInfo);
            if (stockInfo == null) {
                stockInfo = new StockInfo();
                stockInfo.setDirectioncode(productVo.getDirectionCode());
                stockInfo.setCreateddate(new Date());
                stockInfo.setDirectionboxcode(String.format("%03d", productVo.getBoxNumber()));
                stockInfo.setCreatedby(userInfo.getUsername());
                stockInfo.setNum(1);
                stockInfo.setOperator(userInfo.getUsername());
                stockInfo.setIndate(new Date());
                stockInfo.setProductid(productInfo.getId());
                stockInfo.setOwner("");
                stockInfo.setModifiedby(userInfo.getUsername());
                stockInfo.setModifieddate(datetime);
                stockInfo.setOutdate(datetime);
                stockInfo.setFlag((byte) 0);
                stockInfo.setType((byte) 1);
                insertStockInfo(stockInfo);
            }else {
                //库存修改原则,时间最近的修改才生效
                // 判断出库是否大于修改时间,小于修改时间不做库存修改
                if (stockInfo.getModifieddate().compareTo(datetime) > 0){
                    continue;
                }
                //出库后Owner设空
                stockInfo.setOwner("");
                stockInfo.setModifiedby(userInfo.getUsername());
                stockInfo.setModifieddate(datetime);
                stockInfo.setOutdate(datetime);
                updateStockInfo(stockInfo);
            }
 
        }
        productLocusService.insertBatch(productLocusInfos);
    }
 
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Msg changeStockBySale(CustomerInfo customerInfo, List<SaleOrderDetailInfoBO> detailInfoList, UserInfo userInfo, Date salesTime) {
        Msg msg = new Msg();
        if (customerInfo == null || userInfo == null
                || detailInfoList == null || detailInfoList.size() ==0){
            msg.setCode(ERROR_10002.getCode());
            msg.setMessage(ERROR_10002.getMsg()+":销售出库失败");
            return msg;
        }
        Date now = new Date();
        List<ProductLocusInfo> productLocuses = new ArrayList<>();
        List<SoldNoStockInfo> soldNoStockInfos = new ArrayList<>();
        List<WarnContentInfo> warnContentInfos = new ArrayList<>();
        for (SaleOrderDetailInfoBO detailInfo : detailInfoList){
            DirectionDetail directionDetail = FireworkDeal.dealDirectionCode(detailInfo.getDirectioncode());
            if (directionDetail.getLength().equals(FireworkDeal.DIRECTION_INSIDE)){
                ProductDO productInfo = detailInfo.getProductDO();
                //流向码为19位时
                StockInfo stockInfo = selectStockByDirectionAndSlice(directionDetail.getOriginalCode(),productInfo.getSlice());
                if (stockInfo == null){
                    //库存为空则插入
                    stockInfo = new StockInfo();
                    stockInfo.setDirectioncode(directionDetail.getOriginalCode());
                    stockInfo.setOwner(userInfo.getCompanyid().toString());
                    stockInfo.setCreateddate(now);
                    stockInfo.setCreatedby(userInfo.getUsername());
                    stockInfo.setDirectionboxcode(directionDetail.getBoxNo());
                    stockInfo.setModifieddate(salesTime);
                    stockInfo.setNum(1);
                    stockInfo.setOperator(userInfo.getUsername());
                    stockInfo.setIndate(new Date());
                    stockInfo.setProductid(productInfo.getId());
                    stockInfo.setOwner(userInfo.getCompanyid().toString());
                    stockInfo.setFlag((byte)0);
                    stockInfo.setType((byte)1);
 
                    //插入一条已销未入库
                    SoldNoStockInfo soldNoStockInfo = new SoldNoStockInfo();
                    soldNoStockInfo.setDirectioncode(stockInfo.getDirectioncode());
                    soldNoStockInfo.setItemcode(productInfo.getDirectionCode());
                    soldNoStockInfo.setItemname(productInfo.getName());
                    soldNoStockInfo.setSalestime(salesTime);
                    soldNoStockInfo.setSalesperson(userInfo.getUsername());
                    soldNoStockInfo.setCompanynumber(userInfo.getCompanynumber());
                    soldNoStockInfo.setCreatedat(new Date());
                    soldNoStockInfo.setCreatedby("系统生成");
                    soldNoStockInfo.setContent(productInfo.getManufacturer());
//                    soldNoStockService.save(soldNoStockInfo);
                    soldNoStockInfos.add(soldNoStockInfo);
                }
                if (stockInfo.getStatus() != null && stockInfo.getStatus().equals(StockInfo.STOCK_SOLD)
                        && !stockInfo.getOwner().equals(customerInfo.getId().toString())){
                    WarnContentInfo warnContentInfo = new WarnContentInfo();
                    warnContentInfo.setWarntype("多次售出");
                    warnContentInfo.setWarnlevel("预警");
                    warnContentInfo.setEnterpriseid(userInfo.getCompanyid());
                    warnContentInfo.setWarncontent(stockInfo.getDirectioncode()+"多次售出");
                    warnContentInfo.setIsmend((byte) 0);
                    warnContentInfo.setIsneed((byte) 0);
                    warnContentInfo.setIssend((byte) 0);
                    warnContentInfo.setModifiedby("系统生成");
                    warnContentInfo.setModifieddate(new Date());
                    warnContentInfo.setCreateddate(new Date());
                    warnContentInfos.add(warnContentInfo);
//                    warnContentService.save(warnContentInfo);
                }
                if (StringUtils.isNotBlank(stockInfo.getOwner()) && Long.parseLong(stockInfo.getOwner()) != userInfo.getCompanyid()
                    || StringUtils.isBlank(stockInfo.getOwner())){
                    //已销未入库信息插入
                    SoldNoStockInfo soldNoStockInfo = new SoldNoStockInfo();
                    soldNoStockInfo.setDirectioncode(stockInfo.getDirectioncode());
                    soldNoStockInfo.setItemcode(productInfo.getDirectionCode());
                    soldNoStockInfo.setItemname(productInfo.getName());
                    soldNoStockInfo.setSalestime(salesTime);
                    soldNoStockInfo.setSalesperson(userInfo.getUsername());
                    soldNoStockInfo.setCompanynumber(userInfo.getCompanynumber());
                    soldNoStockInfo.setCreatedat(new Date());
                    soldNoStockInfo.setCreatedby("系统生成");
                    soldNoStockInfo.setContent(productInfo.getManufacturer());
//                    soldNoStockService.save(soldNoStockInfo);
                    soldNoStockInfos.add(soldNoStockInfo);
                }
 
                stockInfo.setOwner(customerInfo.getId().toString());
                stockInfo.setModifieddate(salesTime);
                stockInfo.setModifiedby(userInfo.getUsername());
                stockInfo.setStatus(StockInfo.STOCK_SOLD);
                int flag;
                if (stockInfo.getId() == null){
                    flag = this.insertStockInfoBySlice(stockInfo,productInfo.getSlice());
                }else {
                    flag = this.updateStockInfoBySlice(stockInfo,productInfo.getSlice());
                }
                //插入流向轨迹
//                ProductLocusInfo productLocusInfo = new ProductLocusInfo(directionDetail.getOriginalCode(),new Date(),salesTime,
//                        userInfo.getCompany(),customerInfo.getId(),ProductLocusInfo.SALES_STATUS,null);
//                productLocusService.insertProductLocus(productLocusInfo);
                ProductLocusInfoBO productLocusInfoBO = new ProductLocusInfoBO();
                productLocusInfoBO.setSlice(productInfo.getSlice());
                productLocusInfoBO.setDirectioncode(directionDetail.getOriginalCode());
                productLocusInfoBO.setCreateddate(now);
                productLocusInfoBO.setModifieddate(salesTime);
                productLocusInfoBO.setContent(userInfo.getCompany());
                productLocusInfoBO.setCustomerid(customerInfo.getId());
                productLocusInfoBO.setType(ProductLocusInfo.SALES_STATUS);
                productLocusInfoBO.setBoxcode(null);
                productLocuses.add(productLocusInfoBO);
                // 判断是否更新库存成功
                if (flag == 0){
                    msg.setCode(ERROR_30001.getCode());
                    msg.setMessage(ERROR_30001.getMsg()+":流向码为:"+directionDetail.getOriginalCode()+" 库存更新失败,销售失败");
                    break;
                }else {
                    msg.setCode(SUCCESS.getCode());
                    msg.setMessage("出库成功!");
                }
            }
 
        }
 
        if (productLocuses.size() > 0) {
            productLocusService.saveBatchLocus(productLocuses);
        }
        if (warnContentInfos.size() > 0) {
            warnContentService.saveBatchInfo(warnContentInfos);
        }
        if (soldNoStockInfos.size() > 0) {
            soldNoStockService.saveBatchInfo(soldNoStockInfos);
        }
 
        if (!SUCCESS.getCode().equals(msg.getCode())){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return msg;
    }
 
    private boolean isStockInfoExist(String directionCode, Long id) {
        boolean flag = false;
        StockInfo stockInfo = selectStockByDireAndUser(id,directionCode);
        if (stockInfo != null){
            flag = true;
        }
        return flag;
    }
 
    private int insertStockInfo(StockInfo stockInfo){
        int i = 0;
        if (stockInfo == null){
            return i;
        }
        String slice = productService.getSlice(stockInfo.getDirectioncode());
        i = stockInfoMapper.insertStockInfo(stockInfo, slice);
        return i;
    }
 
    private int updateStockInfo(StockInfo stockInfo){
        int i = 0;
        if (stockInfo == null){
            return i;
        }
        String slice = productService.getSlice(stockInfo.getDirectioncode());
        i = stockInfoMapper.updateStockInfo(stockInfo,slice);
        return i;
    }
 
    @Override
    public StockInfo selectStockByDirection(String directionCode){
        String slice = productService.getSlice(directionCode);
        if (StringUtils.isBlank(slice)){
            return null;
        }
        return stockInfoMapper.selectStockByDirection(directionCode,slice);
    }
 
    @Override
    public int doReturn(StockInfo stockInfo, UserInfo userInfo, CustomerInfo customerInfo, Date date) {
        int flag = 0;
        if (stockInfo.getModifieddate().compareTo(date)>0){
            WarnContentInfo warnContentInfo = warnContentService.selectByWarnTypeAndContent("多次售出",stockInfo.getDirectioncode()+"多次售出");
            if (warnContentInfo != null){
                warnContentService.removeById(warnContentInfo.getId());
            }
        }else {
            stockInfo.setOwner(userInfo.getCompanyid().toString());
            stockInfo.setModifieddate(new Date());
            stockInfo.setModifiedby(userInfo.getUsername());
            stockInfo.setStatus("");
            flag = updateStockInfo(stockInfo);
        }
 
        //插入流向轨迹
        ProductLocusInfo productLocusInfo = new ProductLocusInfo(stockInfo.getDirectioncode(), new Date(), new Date(),
                userInfo.getCompany(), customerInfo == null ? null : customerInfo.getId(), ProductLocusInfo.RETURN_ENTRY_STATUS, null);
        productLocusService.insertProductLocus(productLocusInfo);
        return flag;
    }
 
    @Override
    public StockInfo selectStockByDireAndUser(Long companyId, String directionCode) {
        String slice = productService.getSlice(directionCode);
        if (StringUtils.isBlank(slice)){
            return new StockInfo();
        }
        return stockInfoMapper.selectStockByDireAndUser(directionCode,companyId,slice);
    }
 
    @Override
    public void updateStocks(List<StockInfo> stockInfos, UserInfo user) {
        for (StockInfo stockInfo : stockInfos){
            updateStockInfo(stockInfo);
 
            //插入流向轨迹
            ProductLocusInfo productLocusInfo = new ProductLocusInfo(stockInfo.getDirectioncode(),new Date(),new Date(),
                    user.getCompany(),null,ProductLocusInfo.RETURN_DELIVERY_STATUS,null);
            productLocusService.insertProductLocus(productLocusInfo);
        }
    }
 
    @Override
    public void selectDataGrid(PageInfo pageInfo) {
        Page<StockVo> page = new Page<>(pageInfo.getPageIndex(), pageInfo.getPageSize());
 
        List<OrderItem> orderItems = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtils.isNotBlank(pageInfo.getSort()) && StringUtils.isNotBlank(pageInfo.getOrder())) {
            orderItem.setAsc(pageInfo.getOrder().equalsIgnoreCase("ascending"));
            orderItem.setColumn(pageInfo.getSort());
        }else {
            orderItem.setAsc(false);
            orderItem.setColumn("createddate");
        }
        orderItems.add(orderItem);
        page.setOrders(orderItems);
        if (StringUtils.isBlank(pageInfo.getSort())){
            pageInfo.setSort("createddate");
        }
        if (StringUtils.isBlank(pageInfo.getOrder())){
            pageInfo.setOrder("desc");
        }
        List<Integer>list = new ArrayList<>();
        for (int i = 1; i<=20; i++){
            list.add(i);
        }
        List<StockVo> stockVos = stockInfoMapper.selectStockDataGrid(pageInfo.getCondition(),page,list);
        /*for (StockVo stockVo : stockVos){
            pageInfo.getCondition().put("companyNumber",stockVo.getEnterpriseNumber());
            pageInfo.getCondition().put("itemCode",stockVo.getDirectioncode());
            BigDecimal entryNum = entryService.getEntryNumByCondition(pageInfo.getCondition());
            BigDecimal returnNum = entryService.getReturnNumByCondition(pageInfo.getCondition());
            BigDecimal saleNum = saleOrderService.getSaleNumByCondition(pageInfo.getCondition());
            BigDecimal deliveryNum = deliveryOrderService.getDeliveryNum(pageInfo.getCondition());
            BigDecimal returnDeliveryNum = deliveryOrderService.getReturnDeliveryNum(pageInfo.getCondition());
            BigDecimal zero = new BigDecimal("0");
            stockVo.setEntryNum(entryNum == null ? zero:entryNum);
            stockVo.setReturnNum(returnNum == null ? zero : returnNum);
            stockVo.setSaleNum(saleNum == null ? zero: saleNum);
            stockVo.setDeliveryNum(deliveryNum == null ? zero: deliveryNum);
            stockVo.setReturnDeliveryNum(returnDeliveryNum == null ? zero : returnDeliveryNum);
        }*/
        pageInfo.setResult(stockVos);
        pageInfo.setTotalCount(page.getTotal());
    }
 
    @Override
    public void selectEnterpriseStockDataGrid(PageInfo pageInfo) {
        Page<StockVo> page = new Page<>(pageInfo.getPageIndex(), pageInfo.getPageSize());
 
        List<OrderItem> orderItems = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtils.isNotBlank(pageInfo.getSort()) && StringUtils.isNotBlank(pageInfo.getOrder())) {
            orderItem.setAsc("ascending".equalsIgnoreCase(pageInfo.getOrder()));
            orderItem.setColumn(pageInfo.getSort());
        }else {
            orderItem.setAsc(false);
            orderItem.setColumn("owner");
        }
        orderItems.add(orderItem);
        page.setOrders(orderItems);
        if (StringUtils.isBlank(pageInfo.getSort())){
            pageInfo.setSort("owner");
        }
        if (StringUtils.isBlank(pageInfo.getOrder())){
            pageInfo.setOrder("desc");
        }
        List<Integer>list = new ArrayList<>();
        for (int i = 1; i<=20; i++){
            list.add(i);
        }
        List<StockVo> stockVos = stockInfoMapper.selectEnterpriseStockDataGrid(pageInfo.getCondition(),page,list);
        pageInfo.setResult(stockVos);
        pageInfo.setTotalCount(page.getTotal());
    }
 
    @Override
    public List<NoEntryVo> selectNoEntryCount(Date time, Integer warnPeriod) {
        List<Integer>list = new ArrayList<>();
        for (int i = 1; i<=20; i++){
            list.add(i);
        }
        return stockInfoMapper.selectNoEntryCount(time,list,warnPeriod);
    }
 
    @Override
    public void selectNoEntryDetail(PageInfo pageInfo) {
        Page<StockVo> page = new Page<>(pageInfo.getPageIndex(), pageInfo.getPageSize());
        List<OrderItem> orderItems = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtils.isNotBlank(pageInfo.getSort()) && StringUtils.isNotBlank(pageInfo.getOrder())) {
            orderItem.setAsc(pageInfo.getOrder().equalsIgnoreCase("ascending"));
            orderItem.setColumn(pageInfo.getSort());
        }else {
            orderItem.setAsc(false);
            orderItem.setColumn("modifieddate");
        }
        orderItems.add(orderItem);
        page.setOrders(orderItems);
        List<Integer>list = new ArrayList<>();
        for (int i = 1; i<=20; i++){
            list.add(i);
        }
        pageInfo.getCondition().put("list",list);
        List<StockVo> stockVoList = stockInfoMapper.selectNoEntryDetail(page,pageInfo.getCondition());
        pageInfo.setResult(stockVoList);
        pageInfo.setTotalCount(page.getTotal());
    }
 
    @Override
    public void doReturnBatch(UserInfo userInfo, List<EntryDetailInfo> entryDetailInfos, Date date) {
        for (EntryDetailInfo entryDetailInfo : entryDetailInfos){
            String directionCode = entryDetailInfo.getDirectioncode();
            SaleOrderDetailInfo detailInfo = saleOrderService.selectOrderByDirectionReturnflag(directionCode,(byte) 0, null);
            CustomerInfo customerInfo = customerService.getCustomerBySaleOrder(detailInfo.getOrdercode());
            byte flag = 1;
            detailInfo.setReturnflag(flag);
            saleOrderDetailService.updateById(detailInfo);
            StockInfo stockInfo = selectStockByDirection(directionCode);
 
            if (stockInfo.getModifieddate().compareTo(date)>0){
                WarnContentInfo warnContentInfo = warnContentService.selectByWarnTypeAndContent("多次售出",stockInfo.getDirectioncode()+"多次售出");
                if (warnContentInfo != null){
                    warnContentService.removeById(warnContentInfo.getId());
                }
            }else {
                stockInfo.setOwner(userInfo.getCompanyid().toString());
                stockInfo.setModifieddate(new Date());
                stockInfo.setModifiedby(userInfo.getUsername());
                stockInfo.setStatus("");
                updateStockInfo(stockInfo);
            }
            //插入流向轨迹
            ProductLocusInfo productLocusInfo = new ProductLocusInfo(stockInfo.getDirectioncode(), new Date(), new Date(),
                    userInfo.getCompany(), customerInfo == null ? null : customerInfo.getId(), ProductLocusInfo.RETURN_ENTRY_STATUS, null);
            productLocusService.insertProductLocus(productLocusInfo);
        }
    }
 
    @Override
    public List<StockInfo> selectStockByProductId(Long id) {
        String slice = productService.getSlice(id);
        List<StockInfo>stockInfos = new ArrayList<>();
        if (StringUtils.isBlank(slice)){
            return stockInfos;
        }
        return stockInfoMapper.selectStockByProductId(id,slice);
    }
 
    @Override
    public PageInfoExtension<Map> selectEnterpriseSaleDataGrid(PageInfo pageInfo) {
        Page<StockVo> page = new Page<>(pageInfo.getPageIndex(), pageInfo.getPageSize());
 
        List<OrderItem> orderItems = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtils.isNotBlank(pageInfo.getSort()) && StringUtils.isNotBlank(pageInfo.getOrder())) {
            orderItem.setAsc("ascending".equalsIgnoreCase(pageInfo.getOrder()));
            orderItem.setColumn(pageInfo.getSort());
        }else {
            orderItem.setAsc(false);
            orderItem.setColumn("companynumber");
        }
        orderItems.add(orderItem);
        page.setOrders(orderItems);
        if (StringUtils.isBlank(pageInfo.getSort())){
            pageInfo.setSort("companynumber");
        }
        if (StringUtils.isBlank(pageInfo.getOrder())){
            pageInfo.setOrder("desc");
        }
        List<Integer>list = new ArrayList<>();
        for (int i = 1; i<=20; i++){
            list.add(i);
        }
        List<StockVo> stockVos = stockInfoMapper.selectEnterpriseSaleDataGrid(pageInfo.getCondition(),page,list);
        Map total = stockInfoMapper.selectEnterpriseSaleDataCount(pageInfo.getCondition(), list);
        pageInfo.setResult(stockVos);
        pageInfo.setTotalCount(page.getTotal());
        PageInfoExtension<Map> extension = new PageInfoExtension<>(pageInfo);
        extension.setExtension(total);
        return extension;
 
    }
 
    @Override
    public void selectStockDetailByItemCode(PageInfo pageInfo) {
        Page<StockVo> page = new Page<>(pageInfo.getPageIndex(), pageInfo.getPageSize());
 
        List<OrderItem> orderItems = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtils.isNotBlank(pageInfo.getSort()) && StringUtils.isNotBlank(pageInfo.getOrder())) {
            orderItem.setAsc("ascending".equalsIgnoreCase(pageInfo.getOrder()));
            orderItem.setColumn(pageInfo.getSort());
        }else {
            orderItem.setAsc(false);
            orderItem.setColumn("stock.id");
        }
        orderItems.add(orderItem);
        page.setOrders(orderItems);
        if (StringUtils.isBlank(pageInfo.getSort())){
            pageInfo.setSort("stock.id");
        }
        if (StringUtils.isBlank(pageInfo.getOrder())){
            pageInfo.setOrder("desc");
        }
        String itemCode = pageInfo.getCondition().get("itemCode").toString();
        ProductInfo productInfo = productService.selectByDirection(itemCode);
        if (productInfo != null){
            String slice = productService.getSlice(itemCode);
            pageInfo.getCondition().put("slice",slice);
            List<StockVo> stockVos = stockInfoMapper.selectStockVoByItemCode(pageInfo.getCondition(),page);
            pageInfo.setResult(stockVos);
            pageInfo.setTotalCount(page.getTotal());
        }
 
 
    }
 
    @Override
    public void selectSaleDetailDataGrid(PageInfo pageInfo) {
        Page<StockVo> page = new Page<>(pageInfo.getPageIndex(), pageInfo.getPageSize());
 
        List<OrderItem> orderItems = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtils.isNotBlank(pageInfo.getSort()) && StringUtils.isNotBlank(pageInfo.getOrder())) {
            orderItem.setAsc(pageInfo.getOrder().equalsIgnoreCase("ascending"));
            orderItem.setColumn(pageInfo.getSort());
        }else {
            orderItem.setAsc(false);
            orderItem.setColumn("companynumber");
        }
        orderItems.add(orderItem);
        page.setOrders(orderItems);
        if (StringUtils.isBlank(pageInfo.getSort())){
            pageInfo.setSort("companynumber");
        }
        if (StringUtils.isBlank(pageInfo.getOrder())){
            pageInfo.setOrder("desc");
        }
        List<StockVo>stockVoList = stockInfoMapper.selectSaleDetailDataGrid(pageInfo.getCondition(),page);
        pageInfo.setResult(stockVoList);
        pageInfo.setTotalCount(page.getTotal());
    }
 
    @Override
    public PageInfoExtension<StockTotal> selectDataGridExtensions(PageInfo pageInfo) {
 
        List<Integer> slices = new ArrayList<Integer>(){{
            for (int i = 1; i <= 20; i++) {
                add(i);
            }
        }};
 
        List<StockVo> stockVos = stockInfoMapper.selectStockDataGrid(pageInfo.getCondition(),null,slices);
        pageInfo.setResult(stockVos);
        pageInfo.setTotalCount((long) stockVos.size());
        StockTotal stockTotal = new StockTotal(BigDecimal.ZERO);
        if (stockVos.size() > 0) {
            stockVos.forEach(item->{
                BigDecimal toAdd = BigDecimal.ZERO;
                if (item.getCountNum() != null )
                    toAdd = item.getCountNum();
                stockTotal.setCountNum(stockTotal.getCountNum().add(toAdd));
            });
        }
 
        PageInfoExtension<StockTotal> extension = new PageInfoExtension<>(pageInfo);
        extension.setExtension(stockTotal);
        return extension;
    }
 
    @Override
    public PageInfoExtension<ProductVo> selectCurrentFireStatus(Integer pageIndex,Integer pageSize, Map filter, UserInfo user) {
        String directioncode = (String) filter.get("directioncode");
        if (StringUtils.isBlank(directioncode) || FireworkDeal.isNotDirectionCode(directioncode))
            throw new BusinessException("请输入合法的流向码");
 
        DirectionDetail directionDetail = FireworkDeal.dealDirectionCode(directioncode);
 
        ProductVo productVo = productService.selectVoByDirection(directioncode);
        if (productVo == null)  throw new BusinessException("产品不存在");
 
        //分表
        String slice = productService.getSlice(directioncode);
        List<ProductVo> productVos = new ArrayList<>();
        List<StockInfo> records;
        List<String> codes = null;
        PageInfoExtension<ProductVo> extension = new PageInfoExtension<>();
        //22位
        if (FireworkDeal.is22Characters(directioncode)) {
            FireworkDeal.getProductVos(directioncode,directionDetail,directionDetail,productVos,productVo);
            if (productVos.size() < 1) throw new BusinessException("产品流向码出现问题");
 
             codes = new ArrayList<String>() {{
                for (ProductVo product : productVos) {
                    add(product.getDirectionCode());
                }
            }};
        }
        //19位
        if (FireworkDeal.is19Characters(directioncode)) {
             codes = new ArrayList<String>(){{
                add(directioncode);
            }};
        }
 
        //条件准备
        Map<String, Object> params = new HashMap<>();
        String status = (String) filter.get("status");
        //1.已售出
        if ("已售出".equals(status))
            params.put("status", status);
 
        if ("未入库".equals(status)) {
            params.put("status", "");
            params.put("owner", "");
        }
 
        if ("已入库".equals(status)) {
            params.put("status", "");
            params.put("owner", "库存owner");
        }
 
 
        params.put("directioncode", directioncode);
        //查询结果集
        records = stockInfoMapper.selectCurrentFireStatus(codes,params,slice);
 
 
        extension.setExtension(productVo);
        extension.setResult(records);
        extension.setPageIndex(pageIndex);
        extension.setPageSize(pageSize);
        //总数
        assert codes != null;
        extension.setTotalCount((long) codes.size());
        return extension;
    }
 
    @Override
    public List<StockVo> selectEnterpriseStocks(Map<String, Object> condition) {
        List<Integer>list = new ArrayList<>();
        for (int i = 1; i<=20; i++){
            list.add(i);
        }
        return stockInfoMapper.selectEnterpriseStocks(condition,list);
    }
 
    @Override
    public void saveOrUpdateCurrentStock(String updatedBy) {
        Map<String, Object> condition = new HashMap<>(16);
        List<StockVo>stockVos = selectEnterpriseStocks(condition);
        List<StaticStock>staticStocks = new ArrayList<>();
        for (StockVo stockVo : stockVos){
            Enterprise enterprise = enterpriseService.getById(stockVo.getOwner());
            StaticStock staticStock = new StaticStock(Long.parseLong(stockVo.getOwner()),stockVo.getEnterpriseName(),stockVo.getEnterpriseNumber(),
                    enterprise.getSafetysupervision(),stockVo.getProvince(),stockVo.getCity(),stockVo.getDistrict(),
                    stockVo.getStockNum(), stockVo.getFirecracker(),stockVo.getSpray(),stockVo.getRotation(),stockVo.getBead(),
                    stockVo.getToy(),stockVo.getCombined(),updatedBy,new Date(),(byte)0 );
            StaticStock staticStock1 = staticStockService.getByOwner(Long.parseLong(stockVo.getOwner()));
            if (staticStock1 != null){
                staticStock.setId(staticStock1.getId());
            }
            staticStocks.add(staticStock);
        }
        staticStockService.saveOrUpdateBatch(staticStocks);
    }
 
    @Override
    public boolean clearStock(Enterprise enterprise) {
        /*List<StockInfo>stocks = selectEnterpriseAllStock(enterprise);
 
        stocks.forEach(item->{
            item.setRemark();
            item.setOwner("");
            item.setModifieddate(date);
        });*/
        Date date = new Date();
 
        String remark = "系统管理员清空,清空前归属:"+enterprise.getId()+",清空时间:"+new DateTime(date).toString("yyyy-MM-dd HH:mm:ss");
 
        for (int i = 1; i<=20; i++){
            int flag = stockInfoMapper.clearStock(enterprise.getId(),remark,date,"_slice"+i);
        }
 
        /*for (StockInfo stockInfo : stocks){
            updateStockInfo(stockInfo);
        }*/
        StaticStock staticStock = staticStockService.getByOwner(enterprise.getId());
        staticStock.setStockNum(new BigDecimal("0"));
        staticStock.setFirecracker(new BigDecimal("0"));
        staticStock.setSpray(new BigDecimal("0"));
        staticStock.setRotation(new BigDecimal("0"));
        staticStock.setBead(new BigDecimal("0"));
        staticStock.setToy(new BigDecimal("0"));
        staticStock.setCombined(new BigDecimal("0"));
        staticStock.setUpdateat(date);
        staticStockService.updateById(staticStock);
        return true;
    }
 
    @Override
    public boolean clearStockByItems(Enterprise enterprise, List<String> list) {
        Date date = new Date();
 
        String remark = "系统管理员清空,清空前归属:"+enterprise.getId()+",清空时间:"+new DateTime(date).toString("yyyy-MM-dd HH:mm:ss");
 
        for (int i = 1; i<=20; i++){
            int flag = stockInfoMapper.clearStockByItem(enterprise.getId(),list,remark,date,"_slice"+i);
        }
 
        /*StaticStock staticStock = staticStockService.getByOwner(enterprise.getId());
        staticStock.setStockNum(new BigDecimal("0"));
        staticStock.setFirecracker(new BigDecimal("0"));
        staticStock.setSpray(new BigDecimal("0"));
        staticStock.setRotation(new BigDecimal("0"));
        staticStock.setBead(new BigDecimal("0"));
        staticStock.setToy(new BigDecimal("0"));
        staticStock.setCombined(new BigDecimal("0"));
        staticStock.setUpdateat(date);
        staticStockService.updateById(staticStock);*/
        return true;
    }
 
    @Override
    public StockInfo selectStockByDirectionAndSlice(String directionCodeStr, String slice) {
        if (slice == null || StringUtils.isBlank(directionCodeStr)) {
            throw new BusinessException("系统入参为空");
        }
        return stockInfoMapper.selectStockByDirection(directionCodeStr,slice);
    }
 
    @Override
    public int insertStockInfoBySlice(StockInfo stockInfo, String slice) {
        if (stockInfo == null || StringUtils.isBlank(slice)) {
            throw new BusinessException("系统入参为空");
        }
        return stockInfoMapper.insertStockInfo(stockInfo, slice);
    }
 
    @Override
    public int updateStockInfoBySlice(StockInfo stockInfo, String slice) {
        if (stockInfo == null || StringUtils.isBlank(slice)) {
            throw new BusinessException("系统入参为空");
        }
        return stockInfoMapper.updateStockInfo(stockInfo, slice);
    }
 
 
    private List<StockInfo> selectEnterpriseAllStock(Enterprise enterprise) {
        List<Integer>list = new ArrayList<>();
        for (int i = 1; i<=20; i++){
            list.add(i);
        }
        return stockInfoMapper.selectEnterpriseAllStock(enterprise.getId(),list);
    }
 
    @Override
    public List<StockInfo> selectEarlyWarn(Integer min, Integer max, String enterprisetype,List<Integer> slices) {
        return stockInfoMapper.selectEarlyWarn(min, max, enterprisetype,slices);
    }
 
    @Override
    public List<StockInfo> selectAlarm(Integer max, String enterprisetype, List<Integer> slices) {
        return stockInfoMapper.selectAlarm(max, enterprisetype, slices);
    }
 
}