heshaofeng
6 天以前 0ea40a1592de878592b2872b9c3005014233a136
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
using AutoMapper;
using SqlSugar;
using System.Dynamic;
using System.Threading.Tasks;
using WIDESEA_Common.CommonEnum;
using WIDESEA_Common.OrderEnum;
using WIDESEA_Common.StockEnum;
using WIDESEA_Core;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.BaseServices;
using WIDESEA_Core.CodeConfigEnum;
using WIDESEA_Core.DB;
using WIDESEA_Core.Enums;
using WIDESEA_Core.Helper;
using WIDESEA_Core.Seed;
using WIDESEA_Core.Utilities;
using WIDESEA_DTO.Inbound;
using WIDESEA_IBasicService;
using WIDESEA_IInboundService;
using WIDESEA_IRecordService;
using WIDESEA_IStockService;
using WIDESEA_Model.Models;
using WIDESEA_Model.Models.Basic;
 
namespace WIDESEA_InboundService
{
    public class InboundOrderService : ServiceBase<Dt_InboundOrder, IRepository<Dt_InboundOrder>>, IInboundOrderService
    {
        private readonly IMapper _mapper;
        private readonly IUnitOfWorkManage _unitOfWorkManage;
 
        private readonly IRepository<Dt_Task> _taskRepository;
 
        private IStockService _stockService;
        private readonly IMaterialUnitService _materialUnitService;
        private readonly IInboundOrderDetailService _inboundOrderDetailService;
        private readonly IRepository<Dt_InboundOrderDetail> _inboundOrderDetailRepository;
        private readonly IRepository<Dt_StockInfoDetail> _stockDetailRepository;
        private readonly IRepository<Dt_InboundOrder> _inboundOrderRepository;
        private readonly IRepository<Dt_WarehouseArea> _warehouseAreaRepository;
        private readonly IRepository<Dt_LocationType> _locationTypeRepository;
        private readonly IRepository<Dt_StockInfo> _stockRepository;
        public IRepository<Dt_InboundOrder> Repository => BaseDal;
 
        public InboundOrderService(IRepository<Dt_InboundOrder> BaseDal, IMapper mapper, IUnitOfWorkManage unitOfWorkManage, IRepository<Dt_InboundOrderDetail> inboundOrderDetailRepository, IRepository<Dt_Task> taskRepository, IStockService stockService, IInboundOrderDetailService inboundOrderDetailService, IMaterialUnitService materialUnitService, IRepository<Dt_StockInfoDetail> stockDetailRepository, IRepository<Dt_InboundOrder> inboundOrderRepository, IRepository<Dt_WarehouseArea> warehouseAreaRepository, IRepository<Dt_StockInfo> stockRepository, IRepository<Dt_LocationType> locationTypeRepository) : base(BaseDal)
        {
            _mapper = mapper;
            _unitOfWorkManage = unitOfWorkManage;
            _inboundOrderDetailRepository = inboundOrderDetailRepository;
            _taskRepository = taskRepository;
            _stockService = stockService;
            _inboundOrderDetailService = inboundOrderDetailService;
            _materialUnitService = materialUnitService;
            _stockDetailRepository = stockDetailRepository;
            _inboundOrderRepository = inboundOrderRepository;
            _warehouseAreaRepository = warehouseAreaRepository;
            _stockRepository = stockRepository;
            _locationTypeRepository = locationTypeRepository;
        }
 
        public async Task<WebResponseContent> ReceiveInboundOrder(List<Dt_InboundOrder> models, int operateType)
        {
            try
            {
                return operateType switch
                {
                    1 => await AddInboundOrder(models),
                    2 => await UpdateInboundOrder(models),
                    3 => DeleteInboundOrder(models),
 
                    _ => WebResponseContent.Instance.OK(),
                };
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
 
        public async Task<WebResponseContent> AddInboundOrder(List<Dt_InboundOrder> models)
        {
            try
            {
                foreach (var model in models)
                {
                    if (BaseDal.QueryFirst(x => x.UpperOrderNo == model.UpperOrderNo) != null)
                    {
                        return WebResponseContent.Instance.Error($"入库单号重复");
                    }
                }
 
                foreach (var model in models)
                {
                    foreach (var item in model.Details)
                    {
                        var purchaseToStockResult = await _materialUnitService.ConvertPurchaseToStockAsync(item.MaterielCode, item.BarcodeQty);
                        item.Unit = purchaseToStockResult.Unit;
                        item.OrderQuantity = purchaseToStockResult.Quantity;
                    }
                    if (model.OrderType != InOrderTypeEnum.AllocatInbound.ObjToInt())
                    {
                        model.InboundOrderNo = CreateCodeByRule(nameof(RuleCodeEnum.InboundOrderRule));
                    }
 
                    Db.InsertNav(model).Include(x => x.Details).ExecuteCommand();
                }
                return WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
        public async Task<WebResponseContent> UpdateInboundOrder(List<Dt_InboundOrder> models)
        {
            try
            {
                foreach (var model in models)
                {
                    Dt_InboundOrder inboundOrder = Db.Queryable<Dt_InboundOrder>().Where(x => x.UpperOrderNo == model.UpperOrderNo).Includes(x => x.Details).First();
                    if (inboundOrder == null)
                    {
                        return WebResponseContent.Instance.Error($"未找到入库单信息");
                    }
                    if (inboundOrder.Details == null || inboundOrder.Details.Count == 0)
                    {
                        return WebResponseContent.Instance.Error($"未找到入库单明细信息");
                    }
                    if (inboundOrder.OrderStatus != InOrderStatusEnum.未开始.ObjToInt())
                    {
                        return WebResponseContent.Instance.Error($"该订单状态不允许修改");
                    }
                    List<Dt_InboundOrderDetail> inboundOrderDetails = new List<Dt_InboundOrderDetail>();
                    List<Dt_InboundOrderDetail> updateInboundOrderDetails = new List<Dt_InboundOrderDetail>();
                    List<int> detailIds = new List<int>();
                    foreach (var item in model.Details)
                    {
                        if (string.IsNullOrEmpty(item.Barcode))
                        {
 
                        }
                        else
                        {
                            Dt_InboundOrderDetail? inboundOrderDetail = inboundOrder.Details.FirstOrDefault(x => x.Barcode == item.Barcode);
                            if (inboundOrderDetail == null)
                            {
                                inboundOrderDetail = new Dt_InboundOrderDetail()
                                {
                                    OrderId = inboundOrder.Id,
                                    lineNo = item.lineNo,
                                    MaterielCode = item.MaterielCode,
                                    SupplyCode = item.SupplyCode,
                                    BatchNo = item.BatchNo,
                                    Unit = item.Unit,
                                    WarehouseCode = item.WarehouseCode,
                                    Barcode = item.Barcode,
                                    OutBoxbarcodes = item.OutBoxbarcodes,
                                    BarcodeUnit = item.BarcodeUnit,
                                    BarcodeQty = item.BarcodeQty,
                                    OrderQuantity = item.OrderQuantity
                                };
                                var purchaseToStockResult = await _materialUnitService.ConvertPurchaseToStockAsync(item.MaterielCode, item.BarcodeQty);
                                inboundOrderDetail.Unit = purchaseToStockResult.Unit;
                                inboundOrderDetail.OrderQuantity = purchaseToStockResult.Quantity;
 
                                inboundOrderDetails.Add(inboundOrderDetail);
                            }
                            else
                            {
                                inboundOrderDetail.lineNo = item.lineNo;
                                inboundOrderDetail.MaterielCode = item.MaterielCode;
                                inboundOrderDetail.SupplyCode = item.SupplyCode;
                                inboundOrderDetail.BatchNo = item.BatchNo;
                                inboundOrderDetail.Unit = item.Unit;
                                inboundOrderDetail.WarehouseCode = item.WarehouseCode;
                                inboundOrderDetail.Barcode = item.Barcode;
                                inboundOrderDetail.OutBoxbarcodes = item.OutBoxbarcodes;
                                inboundOrderDetail.BarcodeUnit = item.BarcodeUnit;
                                inboundOrderDetail.BarcodeQty = item.BarcodeQty;
                                inboundOrderDetail.OrderQuantity = item.OrderQuantity;
                                var purchaseToStockResult = await _materialUnitService.ConvertPurchaseToStockAsync(item.MaterielCode, item.BarcodeQty);
                                inboundOrderDetail.Unit = purchaseToStockResult.Unit;
                                inboundOrderDetail.OrderQuantity = purchaseToStockResult.Quantity;
 
                                updateInboundOrderDetails.Add(inboundOrderDetail);
                                detailIds.Add(inboundOrderDetail.Id);
                            }
                        }
                    }
 
                    inboundOrder.UpperOrderNo = model.UpperOrderNo;
                    inboundOrder.BusinessType = model.BusinessType;
                    inboundOrder.IsBatch = model.IsBatch;
                    inboundOrder.FactoryArea = model.FactoryArea;
 
                    List<Dt_InboundOrderDetail> deletePurchaseOrderDetails = inboundOrder.Details.Where(x => !detailIds.Contains(x.Id)).ToList();
 
                    _unitOfWorkManage.BeginTran();
                    foreach (var item in deletePurchaseOrderDetails)
                    {
                        _inboundOrderDetailRepository.DeleteData(item);
                        //_inboundOrderDetailRepository.DeleteAndMoveIntoHty(item, OperateTypeEnum.自动删除);
                    }
 
                    _inboundOrderDetailRepository.UpdateData(updateInboundOrderDetails);
                    _inboundOrderDetailRepository.AddData(inboundOrderDetails);
 
                    BaseDal.UpdateData(inboundOrder);
                    _unitOfWorkManage.CommitTran();
 
 
                }
                return WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
 
        public WebResponseContent DeleteInboundOrder(List<Dt_InboundOrder> models)
        {
            try
            {
                foreach (var model in models)
                {
                    Dt_InboundOrder inboundOrder = Db.Queryable<Dt_InboundOrder>().Where(x => x.UpperOrderNo == model.UpperOrderNo).Includes(x => x.Details).First();
                    if (inboundOrder == null)
                    {
                        return WebResponseContent.Instance.Error($"未找到入库单信息");
                    }
                    if (inboundOrder.Details == null || inboundOrder.Details.Count == 0)
                    {
                        return WebResponseContent.Instance.Error($"未找到入库单明细信息");
                    }
                    if (inboundOrder.OrderStatus != InOrderStatusEnum.未开始.ObjToInt())
                    {
                        return WebResponseContent.Instance.Error($"该订单状态不允许删除");
                    }
                    //Db.DeleteNav(inboundOrder).Include(x => x.Details).ExecuteCommand();
                    _unitOfWorkManage.BeginTran();
                    //BaseDal.DeleteAndMoveIntoHty(inboundOrder, OperateTypeEnum.自动删除);
                    foreach (var item in inboundOrder.Details)
                    {
                        _inboundOrderDetailRepository.DeleteData(item);
                        //_inboundOrderDetailRepository.DeleteAndMoveIntoHty(item, OperateTypeEnum.自动删除);
                    }
                    BaseDal.DeleteData(inboundOrder);
                    _unitOfWorkManage.CommitTran();
                }
                return WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
 
        static object lock_code = new object();
        public string CreateCodeByRule(string ruleCode)
        {
            lock (lock_code)
            {
 
                string code = string.Empty;
                DateTime dateTime = DateTime.Now;
                DateTime now = DateTime.Now;
                try
                {
                    if (string.IsNullOrEmpty(ruleCode))
                        throw new ArgumentNullException(nameof(ruleCode));
                    SqlSugarClient sugarClient = new SqlSugarClient(new ConnectionConfig
                    {
                        IsAutoCloseConnection = true,
                        DbType = DbType.SqlServer,
                        ConnectionString = DBContext.ConnectionString
                    });
                    Dt_CodeRuleConfig codeRuleConfig = sugarClient.Queryable<Dt_CodeRuleConfig>().Where(x => x.RuleCode == ruleCode).First();
                    if (codeRuleConfig == null)
                        throw new ArgumentNullException(nameof(codeRuleConfig));
                    if (codeRuleConfig.ModifyDate != null)
                    {
                        dateTime = Convert.ToDateTime(codeRuleConfig.ModifyDate);
                    }
                    else
                    {
                        dateTime = Convert.ToDateTime(codeRuleConfig.CreateDate);
                    }
 
                    if (now.Year == dateTime.Year && now.Month == dateTime.Month && now.Day == dateTime.Day)
                    {
                        now = dateTime;
                        codeRuleConfig.CurrentVal = Convert.ToInt32(codeRuleConfig.CurrentVal) + 1;
                    }
                    else
                    {
                        codeRuleConfig.CurrentVal = 1;
                    }
                    codeRuleConfig.ModifyDate = DateTime.Now;
                    code = codeRuleConfig.StartStr + codeRuleConfig.Format;
                    code = code.Replace($"[{CodeFormatTypeEnum.YYYY}]", now.Year.ToString().PadLeft(4, '0'));
                    code = code.Replace($"[{CodeFormatTypeEnum.MM}]", now.Month.ToString().PadLeft(2, '0'));
                    code = code.Replace($"[{CodeFormatTypeEnum.DD}]", now.Day.ToString().PadLeft(2, '0'));
                    code = code.Replace($"[{CodeFormatTypeEnum.ST}]", codeRuleConfig.StartStr?.ToString() ?? "");
                    code = code.Replace($"[{CodeFormatTypeEnum.NUM}]", codeRuleConfig.CurrentVal.ToString().PadLeft(codeRuleConfig.Length, '0'));
                    Dictionary<string, object> keyValuePairs = new Dictionary<string, object>() { { nameof(codeRuleConfig.CurrentVal), codeRuleConfig.CurrentVal }, { nameof(codeRuleConfig.Id), codeRuleConfig.Id }, { nameof(codeRuleConfig.ModifyDate), DateTime.Now } };
                    sugarClient.Updateable(keyValuePairs).AS(MainDb.CodeRuleConfig).WhereColumns(nameof(codeRuleConfig.Id)).ExecuteCommand();
                    sugarClient.Updateable(codeRuleConfig);
 
                }
                catch (Exception ex)
                {
 
                }
                return code;
            }
        }
 
 
 
        /// <summary>
        /// 根据入库单号获取入库单(含明细)
        /// </summary>
        /// <param name="inboundOrderNo"></param>
        /// <returns></returns>
        public Dt_InboundOrder GetInboundOrder(string inboundOrderNo)
        {
            return BaseDal.Db.Queryable<Dt_InboundOrder>().Includes(x => x.Details).First(x => x.InboundOrderNo == inboundOrderNo); ;
        }
 
 
 
        public WebResponseContent BarcodeMaterielGroup(BarcodeMaterielGroupDTO materielGroupDTO)
        {
 
            WebResponseContent content = new WebResponseContent();
            try
            {
                (bool, string, object?) result2 = ModelValidate.ValidateModelData(materielGroupDTO);
                if (!result2.Item1) return content = WebResponseContent.Instance.Error(result2.Item2);
 
                //  materielGroupDTO.WarehouseCode
                var code = _warehouseAreaRepository.Db.Queryable<Dt_WarehouseArea>().Where(x => x.Code == materielGroupDTO.WarehouseType).Select(x => x.Code).First();
                if (string.IsNullOrEmpty(code))
                {
                    return content = WebResponseContent.Instance.Error($"仓库中没有该{materielGroupDTO.WarehouseType}编号。");
                }
 
 
                Dt_InboundOrder inboundOrder = GetInboundOrder(materielGroupDTO.OrderNo);
 
                var dbinboundOrderDetails = _inboundOrderDetailService.GetByBarcode(materielGroupDTO.Barcodes);
 
                if (dbinboundOrderDetails != null && !dbinboundOrderDetails.Any())
                {
                    return content = WebResponseContent.Instance.Error($"单据中没有该{materielGroupDTO.Barcodes}条码数据。");
                }
 
                List<string?> materielCodes = dbinboundOrderDetails.GroupBy(x => x.Barcode).Select(x => x.Key).ToList();
 
                Dt_StockInfo? stockInfo = _stockService.StockInfoService.GetStockByPalletCode(materielGroupDTO.PalletCode);
 
 
 
                (bool, string, object?) result = CheckMaterielGroupParam(materielGroupDTO, materielCodes, inboundOrder, stockInfo);
                if (!result.Item1) return content = WebResponseContent.Instance.Error(result.Item2);
 
                if (stockInfo == null)
                {
                    stockInfo = new Dt_StockInfo() { PalletType = (int)PalletTypeEnum.None, LocationType = materielGroupDTO.locationType.ObjToInt() };
                    stockInfo.Details = new List<Dt_StockInfoDetail>();
                }
 
                foreach (var item in dbinboundOrderDetails)
                {
                    stockInfo.Details.Add(new Dt_StockInfoDetail
                    {
                        StockId = stockInfo == null ? 0 : stockInfo.Id,
                        Barcode = item.Barcode,
                        MaterielCode = item.MaterielCode,
                        BatchNo = item.BatchNo,
                        Unit = item.Unit,
                        InboundOrderRowNo = item.lineNo,
                        SupplyCode = item.SupplyCode,
                        WarehouseCode = materielGroupDTO.WarehouseType,
                        StockQuantity = item.OrderQuantity,
                        BarcodeQty = item.BarcodeQty,
                        BarcodeUnit = item.BarcodeUnit,
                        FactoryArea = inboundOrder.FactoryArea,
                        Status = 0,
                        OrderNo = inboundOrder.InboundOrderNo,
                        BusinessType = inboundOrder.BusinessType,
 
                    });
 
                    item.ReceiptQuantity = item.BarcodeQty;
                    item.OrderDetailStatus = OrderDetailStatusEnum.Over.ObjToInt();
                    item.WarehouseCode = materielGroupDTO.WarehouseType;
                }
 
                if (stockInfo.Id == 0)
                {
                    stockInfo.PalletCode = materielGroupDTO.PalletCode;
                    stockInfo.StockStatus = StockStatusEmun.组盘暂存.ObjToInt();
                }
                stockInfo.PalletType = (int)PalletTypeEnum.None;
 
                List<int> updateDetailIds = dbinboundOrderDetails.Select(x => x.Id).ToList();
                if (inboundOrder.OrderStatus == InOrderStatusEnum.未开始.ObjToInt())
                {
                    inboundOrder.OrderStatus = InOrderStatusEnum.入库中.ObjToInt();
                }
                inboundOrder.Operator = App.User.UserName;
                content = MaterielGroupUpdateData(inboundOrder, dbinboundOrderDetails, stockInfo);
                if (content.Status)
                {
                    return WebResponseContent.Instance.OK("", stockInfo.Details);
                }
                else
                {
                    content = WebResponseContent.Instance.Error(content.Message);
                }
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            finally
            {
 
            }
            return content;
 
        }
 
 
        public WebResponseContent EmptyMaterielGroup(EmptyBarcodeMaterielGroupDTO materielGroupDTO)
        {
 
            WebResponseContent content = new WebResponseContent();
            try
            {
                (bool, string, object?) result2 = ModelValidate.ValidateModelData(materielGroupDTO);
                if (!result2.Item1) return content = WebResponseContent.Instance.Error(result2.Item2);
 
                bool code = _locationTypeRepository.Db.Queryable<Dt_LocationType>().Where(x => x.LocationType == materielGroupDTO.WarehouseCode).Any();
                if (!code)
                {
                    return content = WebResponseContent.Instance.Error($"区域中没有该{materielGroupDTO.WarehouseCode}编号。");
                }
 
                if (_stockRepository.QueryFirst(x => x.PalletCode == materielGroupDTO.PalletCode) != null)
                {
                    return WebResponseContent.Instance.Error("该托盘已经组过盘");
                }
 
                Dt_StockInfo? stockInfo = _stockService.StockInfoService.GetStockByPalletCode(materielGroupDTO.PalletCode);
                if (stockInfo != null && !string.IsNullOrEmpty(stockInfo.LocationCode) && stockInfo.StockStatus != StockStatusEmun.组盘暂存.ObjToInt())
                {
                    return WebResponseContent.Instance.Error("已上架的托盘不能再次组盘");
                }
 
                if (_taskRepository.QueryFirst(x => x.PalletCode == materielGroupDTO.PalletCode) != null)
                {
                    return WebResponseContent.Instance.Error("该托盘号已有任务");
                }
 
                try
                {
                    if (stockInfo == null)
                    {
                        stockInfo = new Dt_StockInfo() { PalletType = PalletTypeEnum.Empty.ObjToInt(), StockStatus = StockStatusEmun.组盘暂存.ObjToInt(), PalletCode = materielGroupDTO.PalletCode, LocationType = materielGroupDTO.WarehouseCode.ObjToInt() };
                        stockInfo.Details = new List<Dt_StockInfoDetail>();
                    }
                    else
                    {
                        stockInfo.PalletType = PalletTypeEnum.Empty.ObjToInt();
                        stockInfo.StockStatus = StockStatusEmun.组盘暂存.ObjToInt();
                        stockInfo.LocationType = materielGroupDTO.WarehouseCode.ObjToInt();
                    }
 
                    _unitOfWorkManage.BeginTran();
 
                    _stockService.StockInfoService.AddMaterielGroup(stockInfo);
                    _unitOfWorkManage.CommitTran();
                    return WebResponseContent.Instance.OK();
                }
                catch (Exception ex)
                {
                    _unitOfWorkManage.RollbackTran();
                    return WebResponseContent.Instance.Error(ex.Message);
                }
 
 
 
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            finally
            {
 
            }
            return content;
 
        }
 
        /// <summary>
        /// 验证组盘数据
        /// </summary>
        /// <param name="materielGroupDTO">物料组盘DTO</param>
        /// <param name="matSerialNumberDTOs">扫码序列号</param>
        /// <param name="materielInfos">物料信息</param>
        /// <param name="materielCodes">物料编号</param>
        /// <param name="inboundOrder">入库单据</param>
        /// <param name="stockInfo">组盘信息</param>
        /// <returns></returns>
        public (bool, string, object?) CheckMaterielGroupParam(BarcodeMaterielGroupDTO materielGroupDTO, List<string> barcodeCodes, Dt_InboundOrder inboundOrder, Dt_StockInfo stockInfo)
        {
            (bool, string, object?) result = ModelValidate.ValidateModelData(materielGroupDTO);
            if (!result.Item1) return result;
 
            if (_taskRepository.QueryFirst(x => x.PalletCode == materielGroupDTO.PalletCode) != null)
            {
                return (false, "该托盘号已有任务", materielGroupDTO);
            }
 
            if (stockInfo != null && !string.IsNullOrEmpty(stockInfo.LocationCode) && stockInfo.StockStatus != StockStatusEmun.组盘暂存.ObjToInt())
            {
                return (false, "已上架的托盘不能再次组盘", materielGroupDTO);
            }
 
            if (_stockService.StockInfoDetailService.ExistBarcodes(barcodeCodes))
            {
                return (false, $"{barcodeCodes[0]} 条码在库存中已存在", materielGroupDTO);
            }
            //if (materielInfos.Count != materielCodes.Count)
            //{
            //    return (false, "有物料信息未录入,请录入物料信息", materielGroupDTO);
            //}       
 
            if (inboundOrder == null)
            {
                return (false, "单据不存在", materielGroupDTO);
            }
 
            if (inboundOrder.Details == null || inboundOrder.Details.Count == 0)
            {
                return (false, "无单据明细信息", materielGroupDTO);
            }
 
            if (inboundOrder.OrderStatus != InOrderStatusEnum.未开始.ObjToInt() && inboundOrder.OrderStatus != InOrderStatusEnum.入库中.ObjToInt())
            {
                return (false, "该单据不可再组盘", materielGroupDTO);
            }
 
            List<Dt_InboundOrderDetail> inboundOrderDetails = inboundOrder.Details.Where(x => barcodeCodes.Contains(x.Barcode)).ToList();
 
            if (inboundOrderDetails.GroupBy(x => x.Barcode).Count() != barcodeCodes.Count)
            {
                return (false, "有物料不在单据内", materielGroupDTO);
            }
 
            IGrouping<string, Dt_InboundOrderDetail>? temp = inboundOrder.Details.Where(x => barcodeCodes.Contains(x.Barcode)).GroupBy(x => x.Barcode).FirstOrDefault(x => x.Sum(v => v.OverInQuantity) >= x.Sum(v => v.OrderQuantity) || x.Sum(v => v.ReceiptQuantity) >= x.Sum(v => v.OrderQuantity));
            if (temp != null)
            {
                return (false, "有物料超出单据数量", materielGroupDTO);
            }
 
            return (true, "成功", materielGroupDTO);
        }
 
        /// <summary>
        /// 组盘数据更新
        /// </summary>
        /// <param name="inboundOrder">入库单</param>
        /// <param name="inboundOrderDetails">入库单明细</param>
        /// <param name="stockInfo">组盘数据</param>
        /// <returns></returns>
        public WebResponseContent MaterielGroupUpdateData(Dt_InboundOrder inboundOrder, List<Dt_InboundOrderDetail> inboundOrderDetails, Dt_StockInfo stockInfo)
        {
            try
            {
                _unitOfWorkManage.BeginTran();
                UpdateData(inboundOrder);
                _inboundOrderDetailService.UpdateData(inboundOrderDetails);
                _stockService.StockInfoService.AddMaterielGroup(stockInfo);
                _unitOfWorkManage.CommitTran();
                return WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
 
 
        public WebResponseContent UnPalletQuantity(string orderNo)
        {
            // 初始化返回DTO(默认值都为0,避免null)
            var resultDTO = new PalletSumQuantityDTO
            {
                StockSumQuantity = 0,
                StockCount = 0,
                UniqueUnit = ""
            };
            WebResponseContent content = new WebResponseContent();
            try
            {
                if (string.IsNullOrWhiteSpace(orderNo))
                {
                    return content.Error("传入的订单号orderNo为空或空白");
                }
                var orderDetail = _inboundOrderRepository.Db.Queryable<Dt_InboundOrder>().Includes(x => x.Details).Where(s => s.InboundOrderNo == orderNo).First();
                if (orderDetail == null)
                {
                    return content.Error("未找到单据");
                }
                var unitGroups = orderDetail.Details.GroupBy(d => d.Unit).ToList();
                if (unitGroups.Count == 1)
                {
                    resultDTO.UniqueUnit = unitGroups.First().Key;
                }
                else
                {
                    resultDTO.UniqueUnit = "";
                }
                var validDetails = _stockDetailRepository.Db.Queryable<Dt_StockInfoDetail>().Where(s => s.OrderNo == orderNo).ToList();
                resultDTO.StockSumQuantity = orderDetail.Details.Sum(d => d.OrderQuantity);
                resultDTO.StockCount = orderDetail.Details.Count;
                if (validDetails.Any())
                {
                    resultDTO.StockSumQuantity -= validDetails.Sum(d => d.StockQuantity);
                    // 明细记录数:符合条件的有效记录条数
                    resultDTO.StockCount -= validDetails.Count;
                }
                return content.OK("", resultDTO);
            }
            catch (Exception ex)
            {
                return content.Error("SumQuantity 统计库存数量失败,订单号:{OrderNo}");
            }
        }
 
        public WebResponseContent UndoPalletGroup(string palletCode, string barcode = "")
        {
            
            if (string.IsNullOrWhiteSpace(palletCode))
            {
                return WebResponseContent.Instance.Error("托盘号不能为空");
            }
 
            
            try
            {
                _unitOfWorkManage.BeginTran(); 
 
                // 2. 查询托盘库存主记录(避免无数据抛异常)
                var stock = _stockRepository.Db.Queryable<Dt_StockInfo>()
                    .Includes(o => o.Details)
                    .First(x => x.PalletCode == palletCode
                                         && (x.StockStatus == (int)StockStatusEmun.组盘暂存
                                             || x.StockStatus == StockStatusEmun.入库确认.ObjToInt()));
 
                if (stock == null)
                {
                    return WebResponseContent.Instance.Error($"未找到托盘号{palletCode}对应的库存记录");
                }
 
                // 3. 场景1:删除指定条码
                if (!string.IsNullOrWhiteSpace(barcode))
                {
                    var targetDetail = stock.Details?.FirstOrDefault(x => x.Barcode == barcode);
                    if (targetDetail == null)
                    {
                        _unitOfWorkManage.RollbackTran();
                        return WebResponseContent.Instance.Error($"托盘{palletCode}下未找到条码{barcode}的明细记录");
                    }
 
                    // 删除指定明细
                    _stockDetailRepository.DeleteData(targetDetail);
 
                    // 重新查询剩余明细(保证数据准确性)
                    var remainingDetails = _stockDetailRepository.Db.Queryable<Dt_StockInfoDetail>()
                        .Where(x => x.StockId == stock.Id)
                        .ToList();
 
                    // 剩余明细为空 → 删除主表 + 重置入库单及明细状态
                    if (!remainingDetails.Any())
                    {
                        // 重置入库单及明细状态
                        ResetInboundOrderStatus(stock.Details.Select(d => d.OrderNo).Distinct().ToList());
 
                        _stockRepository.DeleteData(stock);
                        _unitOfWorkManage.CommitTran();
                        return WebResponseContent.Instance.OK($"条码{barcode}撤销成功,托盘无剩余明细,已删除托盘并重置关联入库单状态");
                    }
 
                    _unitOfWorkManage.CommitTran();
                    return WebResponseContent.Instance.OK($"条码{barcode}撤销成功,托盘仍有剩余明细");
                }
 
                // 删除整托盘(无条码传入)
                if (stock.Details == null || !stock.Details.Any())
                {
                    _stockRepository.DeleteData(stock);
                    _unitOfWorkManage.CommitTran();
                    return WebResponseContent.Instance.OK("托盘无明细记录,已直接删除托盘主数据");
                }
 
                // 有明细 → 重置入库单及明细状态 + 删除库存
                var relatedOrderNos = stock.Details.Select(d => d.OrderNo).Distinct().ToList();
                if (!relatedOrderNos.Any())
                {
                    _unitOfWorkManage.RollbackTran();
                    return WebResponseContent.Instance.Error("库存明细未关联任何入库单号,无法完成撤销");
                }
 
                // 重置入库单主状态 + 明细状态
                ResetInboundOrderStatus(relatedOrderNos, stock.Details.Select(d => d.Barcode).ToList());
 
                // 4.3 删除库存明细和主表
                _stockDetailRepository.DeleteData(stock.Details);
                _stockRepository.DeleteData(stock);
 
                _unitOfWorkManage.CommitTran();
                return WebResponseContent.Instance.OK("托盘撤销成功,已重置关联入库单及明细状态");
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran(); 
                return WebResponseContent.Instance.Error($"托盘撤销失败:{ex.Message}");
            }
        }
 
 
        private void ResetInboundOrderStatus(List<string> orderNos, List<string> barcodes = null)
        {
            foreach (var orderNo in orderNos)
            {
                var inboundOrder = _inboundOrderRepository.Db.Queryable<Dt_InboundOrder>()
                    .Includes(x => x.Details)
                    .First(x => x.InboundOrderNo == orderNo);
 
                if (inboundOrder == null) continue;
 
                inboundOrder.OrderStatus = 0;
                _inboundOrderRepository.UpdateData(inboundOrder);
 
                // 重置入库单明细状态
                if (inboundOrder.Details == null || !inboundOrder.Details.Any()) continue;
 
                var targetDetails = barcodes == null
                    ? inboundOrder.Details.ToList() // 不传条码则重置整单明细
                    : inboundOrder.Details.Where(d => barcodes.Contains(d.Barcode)).ToList();
 
                foreach (var detail in targetDetails)
                {
                    detail.ReceiptQuantity = 0;
                    detail.OrderDetailStatus = 0;
                    _inboundOrderDetailRepository.UpdateData(detail);
                }
            }
        }
 
        public override PageGridData<Dt_InboundOrder> GetPageData(PageDataOptions options)
        {
            string wheres = ValidatePageOptions(options);
            //获取排序字段
            Dictionary<string, SqlSugar.OrderByType> orderbyDic = GetPageDataSort(options, TProperties);
            List<OrderByModel> orderByModels = new List<OrderByModel>();
            foreach (var item in orderbyDic)
            {
                OrderByModel orderByModel = new()
                {
                    FieldName = item.Key,
                    OrderByType = item.Value
                };
                orderByModels.Add(orderByModel);
            }
            ISugarQueryable<Dt_InboundOrder> sugarQueryable1 = BaseDal.Db.Queryable<Dt_InboundOrder>();
 
            int totalCount = 0;
            List<SearchParameters> searchParametersList = new List<SearchParameters>();
            if (!string.IsNullOrEmpty(options.Wheres))
            {
                try
                {
                    searchParametersList = options.Wheres.DeserializeObject<List<SearchParameters>>();
                    if (searchParametersList.Count > 0)
                    {
 
                        SearchParameters? searchParameters = searchParametersList.FirstOrDefault(x => x.Name == nameof(Dt_InboundOrder.InboundOrderNo).FirstLetterToLower());
                        if (searchParameters != null)
                        {
                            sugarQueryable1 = sugarQueryable1.Where(x => x.InboundOrderNo.Contains(searchParameters.Value.ToString())
                            || x.UpperOrderNo.Contains(searchParameters.Value.ToString()) ||
                            x.Details.Any(d => d.Barcode == searchParameters.Value.ToString()));
                        }
                        searchParameters = searchParametersList.FirstOrDefault(x => x.Name == nameof(Dt_InboundOrder.OrderType).FirstLetterToLower());
                        if (searchParameters != null)
                        {
                            sugarQueryable1 = sugarQueryable1.Where(x => x.OrderType.Equals(searchParameters.Value.ToString()));
                        }
                        //var dataList = sugarQueryable1.ToPageList(options.Page, options.Rows, ref totalCount);
                        //return new PageGridData<Dt_InboundOrder>(totalCount, dataList);
                    }
                    options.Filter = searchParametersList;
                }
                catch { }
            }
            var data = sugarQueryable1
                .WhereIF(!wheres.IsNullOrEmpty(), wheres)
                .Where(x => x.OrderType == 0)
                .OrderBy(orderByModels).Includes(x => x.Details)
                .ToPageList(options.Page, options.Rows, ref totalCount);
 
            return new PageGridData<Dt_InboundOrder>(totalCount, data);
        }
 
        //public override PageGridData<Dt_InboundOrder> GetPageData(PageDataOptions options)
        //{
        //    //var  pageGridData = base.GetPageData(options);
 
        //    ISugarQueryable<Dt_InboundOrder> sugarQueryable1 = BaseDal.Db.Queryable<Dt_InboundOrder>();
        //    if (!string.IsNullOrEmpty(options.Wheres))
        //    {
 
        //        List<SearchParameters> searchParametersList = options.Wheres.DeserializeObject<List<SearchParameters>>();
        //        int totalCount = 0;
        //        if (searchParametersList.Count > 0)
        //        {
 
        //            SearchParameters? searchParameters = searchParametersList.FirstOrDefault(x => x.Name == nameof(Dt_InboundOrder.InboundOrderNo).FirstLetterToLower());
        //            if (searchParameters != null)
        //            {
        //                sugarQueryable1 = sugarQueryable1.Where(x => x.InboundOrderNo.Contains(searchParameters.Value.ToString())
        //                || x.UpperOrderNo.Contains(searchParameters.Value.ToString()) ||
        //                x.Details.Any(d => d.Barcode == searchParameters.Value.ToString()));
        //            }
        //            searchParameters = searchParametersList.FirstOrDefault(x => x.Name == nameof(Dt_InboundOrder.OrderType).FirstLetterToLower());
        //            if (searchParameters != null)
        //            {
        //                sugarQueryable1 = sugarQueryable1.Where(x => x.OrderType.Equals(searchParameters.Value.ToString()));
        //            }
        //            var dataList = sugarQueryable1.ToPageList(options.Page, options.Rows, ref totalCount);
        //            return new PageGridData<Dt_InboundOrder>(totalCount, dataList);
        //        }
        //    }
        //    return new PageGridData<Dt_InboundOrder>();
        //}
 
    }
}