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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
package com.consum.base.controller;
 
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
 
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.fastjson.JSONObject;
import com.consum.base.pojo.*;
import com.consum.base.pojo.excel.ImportProcureOrderTemplate;
import com.consum.base.pojo.excel.LWhFormTransferTemplate;
import com.consum.base.pojo.query.WarehouseQry;
import com.consum.base.service.*;
import com.consum.base.util.DateUtil;
import com.consum.base.util.ExcelStyleUtil;
import com.consum.model.po.*;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.consum.base.BaseController;
import com.consum.base.core.WhBusinessEnum;
import com.consum.base.core.type.StatesType;
import com.consum.base.core.type.TransferStatesType;
import com.consum.base.core.utils.CommonUtil;
import com.consum.base.core.utils.IdUtil;
import com.consum.base.pojo.dto.GoodsInfoDTO;
import com.consum.base.pojo.dto.UseRecordDTO;
import com.consum.base.pojo.excel.TransferExcelTemplate;
import com.consum.base.pojo.query.TransferQry;
import com.consum.base.pojo.request.LWhFormTransferParam;
import com.consum.base.pojo.request.ProcureModelInfoParam;
import com.consum.base.pojo.request.RecordInfoParam;
import com.consum.base.pojo.response.FormTransferVO;
import com.consum.base.pojo.response.GoodsTemplateCountVO;
import com.consum.base.pojo.response.LWHFromTransferExtendVO;
import com.consum.base.pojo.response.TransferInfoVO;
import com.consum.base.service.core.LWhFormTransferCoreService;
import com.iplatform.model.po.S_user_core;
import com.walker.db.page.GenericPager;
import com.walker.infrastructure.utils.CollectionUtils;
import com.walker.infrastructure.utils.DateUtils;
import com.walker.web.ResponseValue;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.util.ReflectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;
 
/**
 * @Description 调拨管理
 * @Author 卢庆阳
 * @Date 2023/10/30
 */
@RestController
@RequestMapping("/pc/l/wh/form/transfer")
@Api(value = "调拨分发管理", tags = "调拨分发管理")
public class LWhFormTransferController extends BaseController {
 
    @Autowired
    private LWhFormTransferService lWhFormTransferService;
    @Autowired
    private LWhProcureModelService lWhProcureModelService;
    @Autowired
    private LWhFormTransferCoreService lWhFormTransferCoreService;
    @Autowired
    private LWhProcureModelUserService lWhProcureModelUserService;
    @Autowired
    private LWhProcureModelUserRecordService lWhProcureModelUserRecordService;
    @Autowired
    private LGoodsUserRecordCoreService lGoodsUserRecordCoreService;
    @Autowired
    private LWhGoodsService lWhGoodsService;
    @Autowired
    private BaseWarehouseService baseWarehouseService;
    @Autowired
    private FinSysTenantDepartmentService departmentService;
    @Autowired
    private BaseCategoryService baseCategoryService;
    @Autowired
    private BaseGoodsTemplateService baseGoodsTemplateService;
    @Autowired
    private BaseGoodsModelsService baseGoodsModelsService;
 
    /**
     * @Description 新增
     */
    @ApiOperation(value = "单据新增", notes = "单据新增")
    @ApiImplicitParam(name = "param", value = "单据新增", required = true, dataType = "LWhFormTransferParam")
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public ResponseValue add() throws Exception {
        LWhFormTransferParam param = CommonUtil.getObjFromReqBody(LWhFormTransferParam.class);
        LWhFormTransferParam param2 = new LWhFormTransferParam();
        CommonUtil.copyProperties(param, param2);
        param = param2;
 
        S_user_core currentUser = this.getCurrentUser();
        if (currentUser == null) {
            return ResponseValue.error("登录用户信息不存在");
        }
        List<LWhFormTransferGoodsInfoParam> transferGoods = param.getTransferGoods();
        if (CollectionUtils.isEmpty(transferGoods)) {
            return ResponseValue.error("调拨单不能为空");
        }
        long id = this.lWhFormTransferService.add(param, this.getSysInfo(), StrUtil.isEmpty(param.getProcureDoc()));
        if (id == -1L) {
            return ResponseValue.error("您不是库管员");
        }
        if (id == -2L) {
            return ResponseValue.error("仓库不存在");
        }
 
        Integer transferBusinessType = param.getTransferBusinessType();
        // 部门分发业务需要处理
        // 拆分 新逻辑
        if (transferBusinessType == 1 && !StrUtil.isEmpty(param.getProcureDoc())) {
            // 先出库,再入库
            // 出库前 设置出库仓库
            List<LWhProcureModel> modelByForm = lWhProcureModelService.getModelByForm(WhBusinessEnum.BUMENFENFA, id);
            Set<Long> baseModelIds =
                    modelByForm.stream().map(LWhProcureModel::getBaseGoodsModelsId).collect(Collectors.toSet());
 
            FinSysTenantUser sysTenantUser = this.getSysInfo();
            String agencyId = sysTenantUser.getTenantId();
            List<BaseWarehouse> baseWarehouseList =
                    baseWarehouseService.getBaseWareHouseList(Long.valueOf(agencyId), StatesType.NORMAL.getValue());
            Set<Long> wareHouseIds = baseWarehouseList.stream().map(BaseWarehouse::getId).collect(Collectors.toSet());
            // 通过调拨单中的型号id查询出该型号物品所在的仓库位置
            List<GoodsInfoDTO> goodsInfoDTOS = lWhGoodsService.queryGoodsInfo(baseModelIds, wareHouseIds, null);
            GoodsInfoDTO goodsInfoDTO = goodsInfoDTOS.stream().findFirst().orElse(null);
            if (ObjectUtils.isEmpty(goodsInfoDTO)) {
                return ResponseValue.error("该型号没有库存可使用");
            }
 
            Long wareHouseId = goodsInfoDTO.getWarehouseId();
            String warehouseName = goodsInfoDTO.getWarehouseName();
            LWhFormTransfer lWhFormTransfer = new LWhFormTransfer(id);
            lWhFormTransfer.setOutWarehouseId(wareHouseId);
            lWhFormTransfer.setOutWarehouseName(warehouseName);
            lWhFormTransferService.update(lWhFormTransfer);
            Long l = lWhFormTransferCoreService.doTransferOutPutNew(id, getCurrentUser(), WhBusinessEnum.BUMENFENFA);
            if (l == -1L) {
                return ResponseValue.error("仓库数量不足");
            }
            lWhFormTransferCoreService.doTransferInPut(id, getCurrentUser(), param.getOperatorName());
        }
 
        return ResponseValue.success();
    }
 
 
    public ResponseValue add2(LWhFormTransferParam param) throws Exception {
        S_user_core currentUser = this.getCurrentUser();
        if (currentUser == null) {
            return ResponseValue.error("登录用户信息不存在");
        }
        List<LWhFormTransferGoodsInfoParam> transferGoods = param.getTransferGoods();
        if (CollectionUtils.isEmpty(transferGoods)) {
            return ResponseValue.error("调拨单不能为空");
        }
 
        FinSysTenantUser sysInfo = this.getSysInfo();
 
        long id = this.lWhFormTransferService.add(param, sysInfo, true);
        if (id == -1L) {
            return ResponseValue.error("您不是库管员");
        }
        if (id == -2L) {
            return ResponseValue.error("仓库不存在");
        }
 
        Integer transferBusinessType = param.getTransferBusinessType();
        // 部门分发业务需要处理
        // todo 拆分 新逻辑
        if (transferBusinessType == 1 && !StrUtil.isEmpty(param.getProcureDoc())) {
            // 先出库,再入库
            // 出库前 设置出库仓库
            List<LWhProcureModel> modelByForm = lWhProcureModelService.getModelByForm(WhBusinessEnum.BUMENFENFA, id);
            Set<Long> baseModelIds =
                    modelByForm.stream().map(LWhProcureModel::getBaseGoodsModelsId).collect(Collectors.toSet());
 
            FinSysTenantUser sysTenantUser = this.getSysInfo();
            String agencyId = sysTenantUser.getTenantId();
            List<BaseWarehouse> baseWarehouseList =
                    baseWarehouseService.getBaseWareHouseList(Long.valueOf(agencyId), StatesType.NORMAL.getValue());
            Set<Long> wareHouseIds = baseWarehouseList.stream().map(BaseWarehouse::getId).collect(Collectors.toSet());
            // 通过调拨单中的型号id查询出该型号物品所在的仓库位置
            List<GoodsInfoDTO> goodsInfoDTOS = lWhGoodsService.queryGoodsInfo(baseModelIds, wareHouseIds, null);
            GoodsInfoDTO goodsInfoDTO = goodsInfoDTOS.stream().findFirst().orElse(null);
            if (ObjectUtils.isEmpty(goodsInfoDTO)) {
                return ResponseValue.error("该型号没有库存可使用");
            }
 
            Long wareHouseId = goodsInfoDTO.getWarehouseId();
            String warehouseName = goodsInfoDTO.getWarehouseName();
            LWhFormTransfer lWhFormTransfer = new LWhFormTransfer(id);
            lWhFormTransfer.setOutWarehouseId(wareHouseId);
            lWhFormTransfer.setOutWarehouseName(warehouseName);
            lWhFormTransferService.update(lWhFormTransfer);
            Long l = lWhFormTransferCoreService.doTransferOutPutNew(id, getCurrentUser(), WhBusinessEnum.BUMENFENFA);
            if (l == -1L) {
                return ResponseValue.error("仓库数量不足");
            }
            lWhFormTransferCoreService.doTransferInPut(id, getCurrentUser(), param.getOperatorName());
        }
 
        return ResponseValue.success();
    }
 
 
    /**
     * 上传分发单(流程修改)
     *
     * @param idStr 调拨单id json
     * @return
     * @throws Exception
     */
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "调拨单id", required = true, dataType = "Long"),})
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("import")
    public ResponseValue upload(@RequestBody String idStr) throws Exception {
        Map<String, Object> map = JSONObject.parseObject(idStr, Map.class);
        String type = map.get("type").toString();
        Long id = Convert.toLong(map.get("idStr"));
        String procureDoc = map.get("procureDoc").toString();
        // [调拨]
        if ("0".equals(type)) {
            // 修改
            LWhFormTransfer addLWhFormTransfer = new LWhFormTransfer();
            addLWhFormTransfer.setId(id);
            addLWhFormTransfer.setProcureDoc(procureDoc);
            int update = lWhFormTransferService.update(addLWhFormTransfer);
            if (update < 1) {
                return ResponseValue.error();
            }
            return ResponseValue.success();
        }
 
        // [分发]
        Long opTime = Convert.toLong(map.get("opTime"));
        // 修改表的文件逻辑
        LWHFromTransferExtendVO lwhFromTransferExtendVO = lWhFormTransferService.getById(id);
        // 修改
        LWhFormTransfer addLWhFormTransfer = new LWhFormTransfer();
        addLWhFormTransfer.setId(id);
        addLWhFormTransfer.setProcureDoc(procureDoc);
        addLWhFormTransfer.setInTime(opTime);
        addLWhFormTransfer.setOutputTime(opTime);
        int update = lWhFormTransferService.update(addLWhFormTransfer);
        if (update < 1) {
            return ResponseValue.error();
        }
        // 主分发逻辑
        // 先出库,再入库
        // 出库前 设置出库仓库
        List<LWhProcureModel> modelByForm = lWhProcureModelService.getModelByForm(WhBusinessEnum.BUMENFENFA, id);
        Set<Long> baseModelIds =
                modelByForm.stream().map(LWhProcureModel::getBaseGoodsModelsId).collect(Collectors.toSet());
        FinSysTenantUser sysTenantUser = this.getSysInfo();
        String agencyId = sysTenantUser.getTenantId();
        List<BaseWarehouse> baseWarehouseList =
                baseWarehouseService.getBaseWareHouseList(Long.valueOf(agencyId), StatesType.NORMAL.getValue());
        Set<Long> wareHouseIds = baseWarehouseList.stream().map(BaseWarehouse::getId).collect(Collectors.toSet());
        // 通过调拨单中的型号id查询出该型号物品所在的仓库位置
        List<GoodsInfoDTO> goodsInfoDTOS = lWhGoodsService.queryGoodsInfo(baseModelIds, wareHouseIds, null);
        GoodsInfoDTO goodsInfoDTO = goodsInfoDTOS.stream().findFirst().orElse(null);
        if (ObjectUtils.isEmpty(goodsInfoDTO)) {
            return ResponseValue.error("该型号没有库存可使用");
        }
        Long wareHouseId = goodsInfoDTO.getWarehouseId();
        String warehouseName = goodsInfoDTO.getWarehouseName();
        LWhFormTransfer lWhFormTransfer = new LWhFormTransfer(id);
        lWhFormTransfer.setOutWarehouseId(wareHouseId);
        lWhFormTransfer.setOutWarehouseName(warehouseName);
        lWhFormTransferService.update(lWhFormTransfer);
        lWhFormTransferCoreService.doTransferOutPutNew(id, getCurrentUser(), WhBusinessEnum.BUMENFENFA);
        lWhFormTransferCoreService.doTransferInPut(id, getCurrentUser(), lwhFromTransferExtendVO.getOperatorName());
        return ResponseValue.success();
    }
 
 
    /**
     * @Description 列表查询(调拨明细)
     * @Author 卢庆阳
     * @Date 2023/10/30
     * <p>
     * 1.查询调拨单
     * <p>
     * 2.查询物品型号
     */
    @ApiOperation(value = "单据列表查询", notes = "单据列表查询")
    @ApiImplicitParams({@ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = true, dataType = "int"),
            @ApiImplicitParam(name = "param", value = "条件参数", required = true, dataType = "TransferQry"),})
    @GetMapping("/list")
    public ResponseValue queryFormTransferList() {
        TransferQry param = CommonUtil.getObjFromReq(TransferQry.class);
        TransferQry param2 = new TransferQry();
        CommonUtil.copyProperties(param, param2);
        param = param2;
 
        S_user_core currentUser = this.getCurrentUser();
        if (currentUser == null) {
            return ResponseValue.error("登录用户信息不存在");
        }
        /*当前登录人只能看到自己机构下的列表*/
        GenericPager genericPager = lWhFormTransferService.queryFormTransferList(param);
        List<LWhFormTransfer> datas = genericPager.getDatas();
        ArrayList<FormTransferVO> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(datas)) {
            datas.forEach(item -> {
                FormTransferVO formTransferVO = new FormTransferVO();
                BeanUtils.copyProperties(item, formTransferVO);
 
                // 查询型号数量
                List<GoodsTemplateCountVO> goodsTemplateCount =
                        lWhProcureModelService.getGoodsTemplateCountByBusinessId(item.getId());
                formTransferVO.setFromTransferTemplateInfoList(goodsTemplateCount);
 
                result.add(formTransferVO);
            });
        }
        try {
            Field fieldDatas = GenericPager.class.getDeclaredField("datas");
            // fieldDatas.setAccessible(true);
            // fieldDatas.set(genericPager, result);
            ReflectUtil.setFieldValue(genericPager, fieldDatas, result);
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseValue.success(genericPager);
    }
 
    /**
     * @Description 根据id查询详情
     * @Author 卢庆阳
     * @Date 2023/10/30
     */
    @ApiOperation(value = "根据id查询详情", notes = "根据id查询详情")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "调拨单id", required = true, dataType = "Long"),})
    @GetMapping("/detail")
    public ResponseValue getById(Long id) {
        if (id == null) {
            return ResponseValue.error("调拨单id为空");
        }
        LWHFromTransferExtendVO vo = this.lWhFormTransferService.getById(id);
        return ResponseValue.success(vo);
    }
 
    @ApiOperation(value = "调拨明细列表", notes = "调拨明细列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "param", value = "条件", required = true, dataType = "TransferQry"),})
    @GetMapping("/detail/list")
    public ResponseValue queryFormTransferDetailList() {
        TransferQry param = CommonUtil.getObjFromReq(TransferQry.class);
        TransferQry param2 = new TransferQry();
        CommonUtil.copyProperties(param, param2);
        param = param2;
 
        FinSysTenantUser sysInfo = this.getSysInfo();
        if (sysInfo == null) {
            return ResponseValue.error("登录用户信息不存在");
        }
        String tenantId = sysInfo.getTenantId();
        if (param.getInAgencyId() == null) {
            param.setInAgencyId(Long.valueOf(tenantId));
        }
        GenericPager<Map<String, Object>> mapGenericPager = lWhFormTransferService.queryFormTransferDetailList(param);
 
        return ResponseValue.success(mapGenericPager);
    }
 
    /**
     * 撤销
     *
     * @author 卢庆阳
     * @date 2023/10/31
     */
    @ApiOperation(value = "撤销", notes = "撤销")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "调拨单id", required = true, dataType = "Long"),})
    @PostMapping("/updStatus")
    public ResponseValue updateStatus(Long id) {
        if (id == null) {
            return ResponseValue.error("参数错误");
        }
        LWhFormTransfer lWhFormTransfer = lWhFormTransferService.selectById(id);
        if (lWhFormTransfer.getStates() != TransferStatesType.OUT_PENDING.getValue()) {
            return ResponseValue.error("状态错误,不能撤销");
        }
 
        int num = this.lWhFormTransferService.updateStatus(id);
        return num > 0 ? ResponseValue.success(1) : ResponseValue.error("修改失败!");
    }
 
    /**
     * @Description 调拨入库
     * @Author 卢庆阳
     * @Date 2023/10/31
     */
    @ApiOperation(value = "调拨入库", notes = "调拨入库")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "调拨单id", required = true, dataType = "Long"),})
    @PostMapping("/income")
    public ResponseValue income(Long id) throws Exception {
        lWhFormTransferCoreService.doTransferInPut(id, getCurrentUser(), null);
        return ResponseValue.success();
    }
 
    /**
     * @Description 调拨出库
     * @Author 卢庆阳
     * @Date 2023/10/31
     */
    @ApiOperation(value = "调拨出库", notes = "调拨出库")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "调拨单id", required = true, dataType = "Long"),})
    @PostMapping("/output")
    public ResponseValue output(Long id) throws Exception {
 
        List<LWhProcureModel> modelByForm = lWhProcureModelService.getModelByForm(WhBusinessEnum.DIAOBO, id);
        Set<Long> baseModelIds =
                modelByForm.stream().map(LWhProcureModel::getBaseGoodsModelsId).collect(Collectors.toSet());
 
        FinSysTenantUser sysTenantUser = this.getSysInfo();
        String agencyId = sysTenantUser.getTenantId();
        List<BaseWarehouse> baseWarehouseList =
                baseWarehouseService.getBaseWareHouseList(Long.valueOf(agencyId), StatesType.NORMAL.getValue());
        Set<Long> wareHouseIds = baseWarehouseList.stream().map(BaseWarehouse::getId).collect(Collectors.toSet());
 
        // 通过调拨单中的型号id查询出该型号物品所在的仓库位置
        List<GoodsInfoDTO> goodsInfoDTOS = lWhGoodsService.queryGoodsInfo(baseModelIds, wareHouseIds, 1);
        GoodsInfoDTO goodsInfoDTO = goodsInfoDTOS.stream().findFirst().orElse(null);
        if (ObjectUtils.isEmpty(goodsInfoDTO)) {
            return ResponseValue.error("该型号没有库存可使用");
        }
        Long wareHouseId = goodsInfoDTO.getWarehouseId();
        String warehouseName = goodsInfoDTO.getWarehouseName();
        LWhFormTransfer lWhFormTransfer = new LWhFormTransfer(id);
        lWhFormTransfer.setOutWarehouseId(wareHouseId);
        lWhFormTransfer.setOutWarehouseName(warehouseName);
        lWhFormTransferService.update(lWhFormTransfer);
        // lWhFormTransferCoreService.doTransferOutPut(id, getCurrentUser());
        lWhFormTransferCoreService.doTransferOutPutNew(id, getCurrentUser(), WhBusinessEnum.DIAOBO);
        return ResponseValue.success();
    }
 
    @ApiOperation(value = "调拨单导出", notes = "调拨单导出")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "调拨单id", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "type", value = "导出类型 1 入库 2 出库", required = true, dataType = "Integer"),})
    @GetMapping("/list/export")
    public ResponseValue<String> export(Long id, Integer type, HttpServletResponse response) throws Exception {
 
        TemplateExportParams params;
        String fileName;
        if (type == 0) {
            params = new TemplateExportParams("import/调拨入库单.xls");
            fileName = "调拨入库单";
        } else if (type == 1) {
            params = new TemplateExportParams("import/调拨入库单1.xls");
            fileName = "调拨入库单";
        } else {
            params = new TemplateExportParams("import/调拨出库单.xls");
            fileName = "调拨出库单";
        }
        params.setHeadingStartRow(2);
        params.setStyle(ExcelStyleUtil.class);
        List<TransferExcelTemplate> export = this.lWhFormTransferService.export(id, type);
 
        int countNum =
                export.stream().filter(item -> item.getNum() != null).mapToInt(TransferExcelTemplate::getNum).sum();
        double totalAmount = export.stream().filter(item -> item.getTotalAmount() != null)
                .mapToDouble(TransferExcelTemplate::getAmount).sum();
        Optional<TransferExcelTemplate> first = export.stream().findFirst();
        TransferExcelTemplate entity = first.get();
        String businessFormCode = entity.getBusinessFormCode();
        Long createTime = entity.getCreateTime();
        String operatorName = entity.getOperatorName();
        String tenantName = entity.getTenantName();
 
        Map<String, Object> map = new HashMap<>();
        map.put("code", businessFormCode);
        map.put("date", DateUtils.toShowDate(createTime));
        map.put("tenantName", tenantName);
        map.put("name", operatorName);
        map.put("countNum", countNum);
        map.put("totalAmount", totalAmount);
 
        Workbook workbook = ExcelExportUtil.exportExcel(params, TransferExcelTemplate.class, export, map);
        String filePath = downLoadExcel(fileName, workbook);
        return ResponseValue.success("导出成功", filePath);
 
    }
 
    /**
     * 部门物品分发列表明细
     *
     * @param
     * @return
     */
    @ApiOperation(value = "部门物品分发列表明细", notes = "部门物品分发列表明细")
    @ApiImplicitParams({@ApiImplicitParam(name = "transferQryDto", value = "调拨单查询条件", required = true)})
    @GetMapping("/department/list")
    public ResponseValue departmentTransferList() {
        TransferQry param = CommonUtil.getObjFromReq(TransferQry.class);
        TransferQry param2 = new TransferQry();
        CommonUtil.copyProperties(param, param2);
        param = param2;
 
        FinSysTenantUser sysInfo = this.getSysInfo();
        if (sysInfo == null) {
            return ResponseValue.error("登录用户信息不存在");
        }
        String tenantId = sysInfo.getTenantId();
        if (param.getOutAgencyId() == null) {
            param.setOutAgencyId(Long.valueOf(tenantId));
        }
        GenericPager<Map<String, Object>> transferInfoDetailsVoGenericPager =
                this.lWhFormTransferService.queryTransferInfo(param);
        return ResponseValue.success(transferInfoDetailsVoGenericPager);
    }
 
    @ApiOperation(value = "使用人修改", notes = "使用人修改")
    @ApiImplicitParams({@ApiImplicitParam(name = "procureModelInfoDto", value = "使用信息", required = true)})
    @PostMapping("/useInfo/update")
    public ResponseValue infoUpdate() {
 
        RecordInfoParam param = CommonUtil.getObjFromReqBody(RecordInfoParam.class);
        RecordInfoParam recordInfoParam = new RecordInfoParam();
        CommonUtil.copyProperties(param, recordInfoParam);
        param = recordInfoParam;
 
        S_user_core currentUser = this.getCurrentUser();
        if (currentUser == null) {
            return ResponseValue.error("登录用户信息不存在");
        }
        if (CollectionUtils.isEmpty(param.getRecordInfoList())) {
            return ResponseValue.error("参数错误");
        }
 
        Map<Long, List<ProcureModelInfoParam>> collect = param.getRecordInfoList().stream()
                .collect(Collectors.groupingBy(ProcureModelInfoParam::getBaseGoodModelId));
        for (Map.Entry<Long, List<ProcureModelInfoParam>> entry : collect.entrySet()) {
            Long baseGoodModelId = entry.getKey();
 
            List<ProcureModelInfoParam> procureModelInfoList = entry.getValue();
            Optional<ProcureModelInfoParam> first = procureModelInfoList.stream().findFirst();
            ProcureModelInfoParam procureModelInf = first.get();
            Long businessId = procureModelInf.getBusinessId();
            LWhProcureModelUserRecord lWhProcureModelUserRecord = new LWhProcureModelUserRecord();
            lWhProcureModelUserRecord.setId(IdUtil.generateId());
            lWhProcureModelUserRecord.setTransBusinessId(businessId);
            FinSysTenantUser sysInfo = getSysInfo();
            lWhProcureModelUserRecord.setOperatorId(sysInfo.getId());
            lWhProcureModelUserRecord.setOperatorName(sysInfo.getUserName());
            lWhProcureModelUserRecord.setDealTime(DateUtils.getDateTimeNumber(System.currentTimeMillis()));
            lWhProcureModelUserRecordService.insert(lWhProcureModelUserRecord);
 
            List<LWhProcureModelUser> procureModelUserList = Lists.newArrayList();
            if (!CollectionUtils.isEmpty(procureModelInfoList)) {
                for (ProcureModelInfoParam item : procureModelInfoList) {
                    LWhProcureModelUser lWhProcureModelUser = new LWhProcureModelUser();
                    lWhProcureModelUser.setId(IdUtil.generateId());
                    lWhProcureModelUser.setTransBusinessId(businessId);
                    lWhProcureModelUser.setProcureModelUserRecordId(lWhProcureModelUserRecord.getId());
                    lWhProcureModelUser.setWhProcureModelId(procureModelInf.getProcureModelId());
                    lWhProcureModelUser.setBaseGoodsModelsId(baseGoodModelId);
                    lWhProcureModelUser.setNowUserPhone(item.getPhone());
                    lWhProcureModelUser.setNowUserName(item.getUserName());
                    lWhProcureModelUser.setGoodsNum(item.getCount());
 
                    // 设置一下在用数量
                    Long oldProcureModelId = item.getOldProcureModelId();
                    LWhProcureModelUser oldInfo =
                            lWhProcureModelUserService.get(new LWhProcureModelUser(oldProcureModelId));
                    lWhProcureModelUser.setUseCount(oldInfo.getUseCount());
                    procureModelUserList.add(lWhProcureModelUser);
                }
 
                lWhProcureModelUserService.insert(procureModelUserList);
            }
            // 使用人修改调用
            lGoodsUserRecordCoreService.modifyGoodsUser(null, lWhProcureModelUserRecord.getId());
        }
 
        return ResponseValue.success();
    }
 
    /**
     * 部门物品使用记录
     *
     * @param transferOrderId
     * @return
     */
    @ApiOperation(value = "部门物品使用人记录", notes = "部门物品使用人记录")
    @ApiImplicitParams({@ApiImplicitParam(name = "transferOrderId", value = "调拨单id", required = true)})
    @GetMapping("/use/record")
    public ResponseValue useRecord(Long transferOrderId) {
        S_user_core currentUser = this.getCurrentUser();
        if (currentUser == null) {
            return ResponseValue.error("登录用户信息不存在");
        }
 
        List<UseRecordDTO> useRecordDTOList = lWhProcureModelUserService.selectUseRecord(transferOrderId);
        if (CollectionUtils.isEmpty(useRecordDTOList)) {
            return ResponseValue.error("未查询到使用记录");
        }
 
        List<GoodsUseRecordVO> goodsUseRecordList = useRecordDTOList.stream()
                .collect(Collectors.groupingBy(UseRecordDTO::getId)).entrySet().stream().map(entry -> {
                    Long id = entry.getKey();
                    List<UseRecordDTO> useRecordList = entry.getValue();
                    UseRecordDTO useRecordDto = useRecordList.get(0);
 
                    GoodsUseRecordVO goodsUseRecordVO = new GoodsUseRecordVO();
                    goodsUseRecordVO.setId(id);
                    goodsUseRecordVO.setUpdateUserName(useRecordDto.getUpdateUserName());
                    goodsUseRecordVO.setUpdateTime(useRecordDto.getUpdateTime());
 
                    List<UseRecordSkuVO> useRecordSkuList =
                            useRecordList.stream().collect(Collectors.groupingBy(UseRecordDTO::getProcureModelId)).values()
                                    .stream().map(recordList -> {
                                        UseRecordDTO useRecordDTO = recordList.get(0);
                                        UseRecordSkuVO useRecordSkuVO = new UseRecordSkuVO();
                                        useRecordSkuVO.setBaseGoodModelId(useRecordDTO.getBaseGoodsModelsId());
                                        useRecordSkuVO.setBaseGoodModelName(useRecordDTO.getBaseGoodsModelsName());
                                        useRecordSkuVO.setUnit(useRecordDTO.getUnit());
                                        useRecordSkuVO.setProcureModelId(useRecordDTO.getProcureModelId());
 
                                        List<RecordUserInfoVO> recordUserInfoList = recordList.stream().map(userInfo -> {
                                            RecordUserInfoVO recordUserInfoVO = new RecordUserInfoVO();
                                            recordUserInfoVO.setOldProcureModelId(userInfo.getOldProcureModelId());
                                            recordUserInfoVO.setUseName(userInfo.getUseName());
                                            recordUserInfoVO.setPhone(userInfo.getPhone());
                                            recordUserInfoVO.setNum(userInfo.getNum());
                                            return recordUserInfoVO;
                                        }).collect(Collectors.toList());
 
                                        useRecordSkuVO.setRecordUserInfos(recordUserInfoList);
                                        return useRecordSkuVO;
                                    }).collect(Collectors.toList());
 
                    goodsUseRecordVO.setRecordSkuDtoList(useRecordSkuList);
                    return goodsUseRecordVO;
 
                }).sorted(Comparator.comparing(GoodsUseRecordVO::getUpdateTime, Comparator.nullsFirst(Long::compareTo))
                        .reversed())
                .collect(Collectors.toList());
 
        return ResponseValue.success(goodsUseRecordList);
    }
 
    @ApiOperation(value = "查询部门下的分发单", notes = "查询部门下的分发单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "agencyId", value = "机构id", required = true, dataType = "Long", paramType = "query")})
    @GetMapping("/query/transfList")
    public ResponseValue queryDepartmentTransferOrderList() {
 
        TransferInfoVO transferInfoVO = new TransferInfoVO();
 
        lWhFormTransferService.queryDepartmentTransferOrder();
        return ResponseValue.success(transferInfoVO);
    }
 
    /**
     * 分发单导入
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "分发单导入", notes = "分发单导入")
    @PostMapping("/import2")
    public ResponseValue import2(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        // 文件格式校验
//        if (!".xls".endsWith(originalFilename)) {
//            return ResponseValue.error("文件格式有误!");
//        }
        FinSysTenantUser sysInfo = this.getSysInfo();
        if (sysInfo == null) {
            return ResponseValue.error("当前登录用户为空");
        }
        try {
            EasyExcelFactory.read(file.getInputStream(), LWhFormTransferTemplate.class,
                    new AnalysisEventListener<LWhFormTransferTemplate>() {
                        /**
                         * 分发单主数据
                         */
                        final List<LWhFormTransferGoodsInfoParam> list = Lists.newArrayList();
 
                        /**
                         * 分发单的外层的主数据
                         */
                        final LWhFormTransferParam lWhFormTransferParam = new LWhFormTransferParam();
 
                        /**
                         * 行索引
                         */
                        Integer index = 0;
 
                        /**
                         * 表头信息
                         * @param headMap
                         * @param context
                         */
                        @Override
                        public void invokeHeadMap(Map headMap, AnalysisContext context) {
                            // 验证表头数量
                            logger.info("解析分发单的表头长度: {}", headMap.size());
                            if (headMap.size() != 15) {
                                throw new ExcelAnalysisException("上传的文件不符!");
                            }
                        }
 
                        /**
                         * 导入主(文件数据处理)
                         * @param data
                         * @param analysisContext
                         */
                        @Override
                        public void invoke(LWhFormTransferTemplate data, AnalysisContext analysisContext) {
                            index++;
                            String categoryOne = data.getCategoryOne();
                            String categoryTwo = data.getCategoryTwo();
                            String categoryThree = data.getCategoryThree();
                            if (StrUtil.isEmpty(categoryThree)) {
                                throw new ExcelAnalysisException("第" + index + "条数据,品类名称不能为空:" + categoryThree);
                            }
                            String goodsName = data.getGoodsName();
                            if (StrUtil.isEmpty(goodsName)) {
                                throw new ExcelAnalysisException("第" + index + "条数据,品名不能为空:" + goodsName);
                            }
                            String goodModelName = data.getGoodModelName();
                            if (StrUtil.isEmpty(goodModelName)) {
                                throw new ExcelAnalysisException("第" + index + "条数据,规格型号不能为空:" + goodModelName);
                            }
                            String unit = data.getUnit();
                            String type = data.getType();
                            if (StrUtil.isEmpty(type)) {
                                throw new ExcelAnalysisException("第" + index + "条数据,管理分类不能为空:" + type);
                            }
                            String agencyName = data.getAgencyName();
                            if (StrUtil.isEmpty(agencyName)) {
                                throw new ExcelAnalysisException("第" + index + "条数据,创建机构不能为空:" + agencyName);
                            }
                            //String warehouseName = data.getWarehouseName();
                            String supplierName = data.getSupplierName();
                            //String price = data.getPrice();
                            String num = data.getNum();
                            if (StrUtil.isEmpty(num)) {
                                throw new ExcelAnalysisException("第" + index + "条数据,领用数量不能为空:" + num);
                            }
                            // 物品类型(自采集采)
                            //String goodsType = data.getGoodsType();
                            // 使用人部门
                            String userDepartment = data.getUserDepartment();
                            if (StrUtil.isEmpty(userDepartment)) {
                                throw new ExcelAnalysisException("第" + index + "条数据,使用人部门不能为空:" + userDepartment);
                            }
                            // 填报人
                            String reportedBy = data.getReportedBy();
                            if (StrUtil.isEmpty(reportedBy)) {
                                throw new ExcelAnalysisException("第" + index + "条数据,填报人不能为空:" + reportedBy);
                            }
                            // 使用人
                            String user = data.getUser();
                            if (StrUtil.isEmpty(user) && type.equals("A")) {
                                throw new ExcelAnalysisException("第" + index + "条数据,管理分类为A的物品,使用人不能为空:" + user);
                            }
                            // 联系电话
                            String userContactPhone = data.getUserContactPhone();
                            if (StrUtil.isEmpty(userContactPhone)) {
                                throw new ExcelAnalysisException("第" + index + "条数据,联系电话不能为空:" + userContactPhone);
                            }
                            // 第一次进来把外层的值设置一下
                            if (StrUtil.isEmpty(lWhFormTransferParam.getDepartmentName())) {
                                // 机构id (根据 机构名称和部门名称 查找对应的id)
                                FinSysTenantDepartment finSysTenantDepartment = departmentService.queryIdByTenDepName(agencyName, userDepartment);
                                if (finSysTenantDepartment == null) {
                                    throw new ExcelAnalysisException("第" + index + "条数据 " + "机构-部门未找到:[" + agencyName + "-" + userDepartment + "]");
                                }
                                lWhFormTransferParam.setTransferBusinessType(1);
                                lWhFormTransferParam.setDepartmentId(finSysTenantDepartment.getId());
                                lWhFormTransferParam.setDepartmentName(userDepartment);
                                lWhFormTransferParam.setOperatorName(reportedBy);
                                lWhFormTransferParam.setTel(0L);
                                lWhFormTransferParam.setCreateTime(DateUtil.getNowDate());
                                lWhFormTransferParam.setProcureDoc("");
                                lWhFormTransferParam.setOutAgencyId(finSysTenantDepartment.getTenantId());
                            }
                            // 查询分类id
                            BaseCategory baseCategory = baseCategoryService.getByCategoryByName(categoryThree);
                            if (baseCategory == null) {
                                throw new ExcelAnalysisException("第" + index + "条数据" + "此分类未找到:" + categoryThree);
                            }
                            Long categoryId = baseCategory.getId();
                            // 不同采集类型,不同筛选
                            Optional<LWhFormTransferGoodsInfoParam> optional = null;
                            // 筛选类型
                            optional = list.stream().filter(item -> item.getBaseCategoryId().equals(categoryId)).findFirst();
                            // 筛选物品名
                            Optional<LWhFormTransferGoodsInfoParam> optional2 =
                                    list.stream().filter(item -> item.getGoodsTemplateName().equals(goodsName)).findFirst();
                            // 数据第二层-物品的id
                            BaseGoodsTemplate goodsTemplate = baseGoodsTemplateService.getByGoodsNameAndCategoryId(goodsName, categoryId);
                            if (goodsTemplate == null) {
                                throw new ExcelAnalysisException("第" + index + "条数据" + "此物品未找到:" + goodsName);
                            }
                            if (optional.isPresent() && optional2.isPresent()) {
                                // 内层list(领用人)
                                List<LWhTransferModelParam> models3 = optional.get().getModels();
                                // 找型号名字一样的
                                Optional<LWhTransferModelParam> optional3 =
                                        models3.stream().filter(item -> item.getBaseGoodsModelsName().equals(goodModelName)).findFirst();
                                int counts = 0;
                                for (LWhTransferModelParam m : models3) {
                                    int addNum = 0;
                                    if (m.getNum() != null) {
                                        addNum = m.getCounts();
                                    }
                                    counts += addNum;
                                }
                                // 同一个型号的
                                if (optional3.isPresent()) {
                                    if ("A".equals(type)) {
                                        LWhProcureModelUserParam lWhProcureModelUserParam = new LWhProcureModelUserParam();
                                        lWhProcureModelUserParam.setGoodsNum(Integer.valueOf(num));
                                        lWhProcureModelUserParam.setNowUserName(user);
                                        lWhProcureModelUserParam.setNowUserPhone(new Long(userContactPhone));
                                        Integer counts1 = optional3.get().getCounts();
                                        Integer num1 = optional3.get().getNum();
                                        optional3.get().setCounts(Integer.valueOf(num) + counts1);
                                        optional3.get().setNum(Integer.valueOf(num) + num1);
                                        optional3.get().getProcureModelUserList().add(lWhProcureModelUserParam);
                                    } else {
                                        Integer counts1 = optional3.get().getCounts();
                                        Integer num1 = optional3.get().getNum();
                                        optional3.get().setCounts(Integer.valueOf(num) + counts1);
                                        optional3.get().setNum(Integer.valueOf(num) + num1);
                                    }
                                } else {
                                    // 此物品另外的规格型号
                                    LWhTransferModelParam lWhTransferModelParam = new LWhTransferModelParam();
                                    // 模板的id
                                    BaseGoodsModels selBaseGoodsModels = new BaseGoodsModels();
                                    selBaseGoodsModels.setModelName(goodModelName);
                                    selBaseGoodsModels.setGoodsTemplatesId(goodsTemplate.getId());
                                    BaseGoodsModels selByModelNameAndGoodsTemplatesId = baseGoodsModelsService.getByModelNameAndGoodsTemplatesId(selBaseGoodsModels);
                                    if (selByModelNameAndGoodsTemplatesId == null) {
                                        throw new ExcelAnalysisException("第" + index + "条数据" + "品名:" + goodsName + ",规格型号:" + goodModelName + "未找到");
                                    }
                                    lWhTransferModelParam.setBaseGoodsModelsId(selByModelNameAndGoodsTemplatesId.getId());
                                    // 内层list的数量之和
                                    lWhTransferModelParam.setCounts(Integer.valueOf(num));
                                    // 模板名称
                                    lWhTransferModelParam.setBaseGoodsModelsName(goodModelName);
                                    List<LWhProcureModelUserParam> addLWhProcureModelUserParam = new ArrayList<>();
                                    LWhProcureModelUserParam lWhProcureModelUserParam = new LWhProcureModelUserParam();
                                    lWhProcureModelUserParam.setGoodsNum(Integer.valueOf(num));
 
                                    // 查询库存数量
                                    Integer nowNum = selectAllNumber(lWhFormTransferParam.getOutAgencyId(), selByModelNameAndGoodsTemplatesId.getId());
                                    if(nowNum<new Integer(num)){
                                        throw new ExcelAnalysisException("第" + index + "条数据" + "品名:[" + goodsName + "] 规格型号:[" + goodModelName + "] 库存数量不足:["+nowNum+"]");
                                    }
                                    lWhProcureModelUserParam.setNowUserName(user);
                                    lWhProcureModelUserParam.setNowUserPhone(new Long(userContactPhone));
                                    addLWhProcureModelUserParam.add(lWhProcureModelUserParam);
                                    lWhTransferModelParam.setProcureModelUserList(addLWhProcureModelUserParam);
                                    optional.get().getModels().add(lWhTransferModelParam);
                                }
                            } else {
                                LWhFormTransferGoodsInfoParam lWhFormTransferGoodsInfoParam = new LWhFormTransferGoodsInfoParam();
                                // 分类id
                                lWhFormTransferGoodsInfoParam.setBaseCategoryId(categoryId);
                                // 数据第二层-物品的id
                                //BaseGoodsTemplate goodsTemplate = baseGoodsTemplateService.getByGoodsNameAndCategoryId(goodsName, categoryId);
                                BaseGoodsModels selBaseGoodsModels = new BaseGoodsModels();
                                selBaseGoodsModels.setModelName(goodModelName);
                                selBaseGoodsModels.setGoodsTemplatesId(goodsTemplate.getId());
                                BaseGoodsModels selByModelNameAndGoodsTemplatesId = baseGoodsModelsService.getByModelNameAndGoodsTemplatesId(selBaseGoodsModels);
                                if (selByModelNameAndGoodsTemplatesId == null) {
                                    throw new ExcelAnalysisException("第" + index + "条数据 " + "品名:" + goodsName + ",规格型号:" + goodModelName + "未找到");
                                }
                                // 物品的id :爱玛电动车
                                lWhFormTransferGoodsInfoParam.setBaseGoodsTemplateId(goodsTemplate.getId());
                                lWhFormTransferGoodsInfoParam.setGoodsTemplateName(goodsName);
                                // 内层
                                LWhTransferModelParam lWhTransferModelParam = new LWhTransferModelParam();
                                // 规格id
                                lWhTransferModelParam.setBaseGoodsModelsId(selByModelNameAndGoodsTemplatesId.getId());
                                // 新增的时候默认一条
                                lWhTransferModelParam.setCounts(new Integer(num));
                                lWhTransferModelParam.setNum(new Integer(num));
                                List<LWhProcureModelUserParam> lWhFormProcureGoodsInfoParam = new ArrayList<>();
                                LWhProcureModelUserParam lWhProcureModelUserParam = new LWhProcureModelUserParam();
                                lWhProcureModelUserParam.setGoodsNum(Integer.valueOf(num));
 
                                // 查询库存数量
                                Integer nowNum = selectAllNumber(lWhFormTransferParam.getOutAgencyId(), selByModelNameAndGoodsTemplatesId.getId());
                                if(nowNum<new Integer(num)){
                                    throw new ExcelAnalysisException("第" + index + "条数据 " + "品名:[" + goodsName + "] 规格型号:[" + goodModelName + "] 库存数量不足:["+nowNum+"]");
                                }
 
                                lWhProcureModelUserParam.setNowUserName(user);
                                lWhProcureModelUserParam.setNowUserPhone(new Long(userContactPhone));
                                lWhFormProcureGoodsInfoParam.add(lWhProcureModelUserParam);
                                lWhTransferModelParam.setProcureModelUserList(lWhFormProcureGoodsInfoParam);
                                lWhTransferModelParam.setBaseGoodsModelsName(goodModelName);
                                List<LWhTransferModelParam> lWhTransferModelParams = new ArrayList<>();
                                lWhTransferModelParams.add(lWhTransferModelParam);
                                lWhFormTransferGoodsInfoParam.setModels(lWhTransferModelParams);
                                lWhFormTransferGoodsInfoParam.setType(type);
                                list.add(lWhFormTransferGoodsInfoParam);
                            }
                        }
 
                        /**
                         * 分发单导入主方法
                         * @param analysisContext
                         */
                        @Override
                        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                            lWhFormTransferParam.setTransferGoods(list);
                            long id = IdUtil.generateId();
                            //lWhFormTransferParam.setProcureDoc("[{\"fileType\":\"png\",\"id\":\"883654049218335\",\"name\":\"微信截图_20240426143552.png\",\"url\":\"http://172.16.60.172:8083/lowConsum/file/2024/5/883654049218335.png\",\"path\":\"2024/5/883654049218335.png\",\"attSize\":6772}]");
                            lWhFormTransferParam.setProcureDoc("-");
                            lWhFormTransferParam.setId(id);
                            String jsonString = JSONObject.toJSONString(lWhFormTransferParam);
                            logger.info("导入分发单json数据 --------------------");
                            logger.info(jsonString);
                            // 分发单据
                            try {
                                ResponseValue responseValue = add2(lWhFormTransferParam);
                                logger.info(responseValue.toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                                throw new RuntimeException(e);
                            }
                        }
 
                        @Override
                        public void onException(Exception exception, AnalysisContext analysisContext) throws Exception {
                            if (exception instanceof ExcelDataConvertException) {
                                ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
                                Integer row = excelDataConvertException.getRowIndex() + 1;
                                Integer column = excelDataConvertException.getColumnIndex() + 1;
                                throw new ExcelAnalysisException("第" + row + "行,第" + column + "列解析异常,请正确填写");
                            } else {
                                throw new ExcelAnalysisException(exception.getMessage());
                            }
                        }
                    }).sheet(0).doRead();
        } catch (ExcelAnalysisException e) {
            return ResponseValue.error(e.getMessage());
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResponseValue.error("系统错误");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseValue.error("系统错误");
        }
        return ResponseValue.success("导入成功!");
    }
 
 
    /**
     * 查询库存Id
     * @param agencyId
     * @param baseGoodsModelsId
     * @return
     */
    public Integer selectAllNumber(Long agencyId,Long baseGoodsModelsId) {
        WarehouseQry warehouseQry = new WarehouseQry();
        warehouseQry.setAgencyId(agencyId);
        warehouseQry.setBaseGoodsModelsId(baseGoodsModelsId);
        List<BaseWarehouse> baseWarehouseList =
                baseWarehouseService.getBaseWareHouseList(agencyId, StatesType.NORMAL.getValue());
        List<Long> warehouseIdList = baseWarehouseList.stream().map(BaseWarehouse::getId).collect(Collectors.toList());
        Integer warehouseType = warehouseQry.getWarehouseType();
        Integer states = warehouseQry.getStates();
        Integer buyType = warehouseQry.getBuyType();
        // 调拨时只查机构类型的集采仓库库存
        // 部门分发时不分机构和部门,因为调拨进来的物品也算在库存里只是类型为部门,同样检视所有仓库该型号的数量
        int num = lWhGoodsService.queryGoodsModelInWareHouseNum(warehouseType, warehouseIdList, baseGoodsModelsId,
                states, buyType);
        return num;
    }
 
}