pan
2025-11-17 5fc251a847ccc0540da8b112ed2bddba846455d8
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
using Dm.filter;
using MailKit.Search;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Common.LocationEnum;
using WIDESEA_Common.OrderEnum;
using WIDESEA_Common.StockEnum;
using WIDESEA_Common.TaskEnum;
using WIDESEA_Core;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.BaseServices;
using WIDESEA_Core.Helper;
using WIDESEA_DTO.Basic;
using WIDESEA_DTO.Outbound;
using WIDESEA_IBasicService;
using WIDESEA_IOutboundService;
using WIDESEA_IStockService;
using WIDESEA_Model.Models;
 
namespace WIDESEA_OutboundService
{
    /// <summary>
    ///   
    /// </summary>
    public class OutboundPickingService : ServiceBase<Dt_PickingRecord, IRepository<Dt_PickingRecord>>, IOutboundPickingService
    {
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        public IRepository<Dt_PickingRecord> Repository => BaseDal;
 
        private readonly IStockInfoService _stockInfoService;
        private readonly IStockService _stockService;
        private readonly IOutStockLockInfoService _outStockLockInfoService;
        private readonly IStockInfoDetailService _stockInfoDetailService;
        private readonly ILocationInfoService _locationInfoService;
        private readonly IOutboundOrderDetailService _outboundOrderDetailService;
        private readonly IOutboundOrderService _outboundOrderService;
        private readonly ISplitPackageService _splitPackageService;
        private readonly IRepository<Dt_Task> _taskRepository;
        private readonly IESSApiService _eSSApiService;
 
 
        private readonly ILogger<OutboundPickingService> _logger;
 
        private Dictionary<string, string> stations = new Dictionary<string, string>
        {
            {"2-1","2-9" },
            {"3-1","3-9" },
 
        };
 
        private Dictionary<string, string> movestations = new Dictionary<string, string>
        {
            {"2-1","2-5" },
            {"3-1","3-5" },
 
        };
 
        public OutboundPickingService(IRepository<Dt_PickingRecord> BaseDal, IUnitOfWorkManage unitOfWorkManage, IStockInfoService stockInfoService, IStockService stockService, IOutStockLockInfoService outStockLockInfoService, IStockInfoDetailService stockInfoDetailService, ILocationInfoService locationInfoService, IOutboundOrderDetailService outboundOrderDetailService, ISplitPackageService splitPackageService, IOutboundOrderService outboundOrderService, IRepository<Dt_Task> taskRepository, IESSApiService eSSApiService, ILogger<OutboundPickingService> logger) : base(BaseDal)
        {
            _unitOfWorkManage = unitOfWorkManage;
            _stockInfoService = stockInfoService;
            _stockService = stockService;
            _outStockLockInfoService = outStockLockInfoService;
            _stockInfoDetailService = stockInfoDetailService;
            _locationInfoService = locationInfoService;
            _outboundOrderDetailService = outboundOrderDetailService;
            _splitPackageService = splitPackageService;
            _outboundOrderService = outboundOrderService;
            _taskRepository = taskRepository;
            _eSSApiService = eSSApiService;
            _logger = logger;
        }
 
 
        #region 查询出库详情列表
        public async Task<List<OutStockLockListResp>> GetOutStockLockListAsync(string orderNo)
        {
            var locks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                .Where(t => t.OrderNo == orderNo)
                .ToListAsync();
 
            return locks.Select(t => new OutStockLockListResp
            {
                Id = t.Id,
                // TaskNum = t.TaskNum,
                PalletCode = t.PalletCode,
                CurrentBarcode = t.CurrentBarcode,
                AssignQuantity = t.AssignQuantity,
                PickedQty = t.PickedQty,
                Status = t.Status,
                //  IsSplitted = t.IsSplitted
            }).ToList();
        }
        #endregion
        public async Task<WebResponseContent> ValidateBarcode(string barcode)
        {
            try
            {
                if (string.IsNullOrEmpty(barcode))
                {
                    return WebResponseContent.Instance.Error("条码不能为空");
                }
 
                // 根据条码查询库存明细
                var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
                    .Includes(x => x.StockInfo)
                    .Where(x => x.Barcode == barcode)
                    .FirstAsync();
 
                if (stockDetail == null)
                {
                    return WebResponseContent.Instance.Error("条码不存在");
                }
 
 
 
                var result = new
                {
                    Barcode = barcode,
                    MaterielCode = stockDetail.MaterielCode,
 
                    BatchNo = stockDetail.BatchNo,
                    AvailableQuantity = stockDetail.StockQuantity - stockDetail.OutboundQuantity,
                    LocationCode = stockDetail.StockInfo?.LocationCode,
                    PalletCode = stockDetail.StockInfo?.PalletCode
                };
 
                return WebResponseContent.Instance.OK(null, result);
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error($"条码验证失败: {ex.Message}");
            }
        }
 
 
        public async Task<WebResponseContent> ConfirmPicking(string orderNo, string palletCode, string barcode)
        {
            try
            {
                _unitOfWorkManage.BeginTran();
                var lockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                  .Where(it => it.OrderNo == orderNo &&
                             it.Status == (int)OutLockStockStatusEnum.出库中 &&
                             it.PalletCode == palletCode &&
                             it.CurrentBarcode == barcode)
                  .FirstAsync();
 
                if (lockInfo == null)
                {
                    var splitBarcode = await _splitPackageService.Db.Queryable<Dt_SplitPackageRecord>()
                   .Where(it => it.NewBarcode == barcode && it.Status == 1)
                   .FirstAsync();
 
                    if (splitBarcode != null)
                    {
                        // 通过拆包条码记录找到对应的出库锁定记录
                        lockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                            .Where(it => it.ParentLockId == splitBarcode.OutStockLockInfoId)
                            .FirstAsync();
 
                        if (lockInfo == null)
                            throw new Exception($"未找到拆包条码{barcode}对应的出库锁定记录");
                    }
                    else
                    {
                        throw new Exception($"条码{barcode}不属于托盘{palletCode}或不存在待分拣记录");
                    }
 
                }
                if (lockInfo.PalletCode != palletCode)
                    throw new Exception($"条码{barcode}不属于托盘{palletCode}");
 
                var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
                        .Where(x => x.Barcode == barcode && x.StockId == lockInfo.StockId)
                        .FirstAsync();
 
                if (stockDetail == null)
                    return WebResponseContent.Instance.Error("无效的条码或物料编码");
 
 
                decimal actualQty = lockInfo.AssignQuantity - lockInfo.PickedQty;
 
                // 4. 更新库存
                stockDetail.StockQuantity -= actualQty;
                stockDetail.OutboundQuantity -= actualQty;
                await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
 
                lockInfo.PickedQty += actualQty;
                lockInfo.Status = (int)OutLockStockStatusEnum.拣选完成;
                await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
 
                var splitBarcodeRecord = await _splitPackageService.Db.Queryable<Dt_SplitPackageRecord>()
               .Where(it => it.NewBarcode == barcode)
               .FirstAsync();
 
                if (splitBarcodeRecord != null)
                {
                    splitBarcodeRecord.Status = 2;
                    await _splitPackageService.Db.Updateable(splitBarcodeRecord).ExecuteCommandAsync();
                }
 
                await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
               .SetColumns(it => it.PickedQty == it.PickedQty + actualQty)
               .Where(it => it.Id == lockInfo.OrderDetailId)
               .ExecuteCommandAsync();
 
 
                await CheckAndUpdateOrderStatus(orderNo);
 
                //查询任务表 
                var task = _taskRepository.QueryData(x => x.OrderNo == orderNo && x.PalletCode == palletCode).FirstOrDefault();
                // 9. 记录拣选历史
                var pickingHistory = new Dt_PickingRecord
                {
                    FactoryArea = lockInfo.FactoryArea,
                    TaskNo = task?.TaskNum ?? 0,
                    LocationCode = task?.SourceAddress ?? "",
                    StockId = stockDetail.Id,
                    OrderNo = orderNo,
                    OrderDetailId = lockInfo.OrderDetailId,
                    PalletCode = palletCode,
                    Barcode = barcode,
                    MaterielCode = lockInfo.MaterielCode,
                    PickQuantity = lockInfo.AssignQuantity,
                    PickTime = DateTime.Now,
                    Operator = App.User.UserName,
                    OutStockLockId = lockInfo.Id
                };
                await Db.Insertable(pickingHistory).ExecuteCommandAsync();
 
                _unitOfWorkManage.CommitTran();
                return WebResponseContent.Instance.OK("拣选确认成功");
 
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error($"拣选确认失败:{ex.Message}");
            }
        }
        // 检查并更新订单状态
        private async Task CheckAndUpdateOrderStatus(string orderNo)
        {
 
 
            var orderDetails = await _stockInfoDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
                .Where(x => x.OrderId == orderNo.ObjToInt())
                .ToListAsync();
 
            bool allCompleted = true;
            foreach (var detail in orderDetails)
            {
                if (detail.OverOutQuantity < detail.NeedOutQuantity)
                {
                    allCompleted = false;
                    break;
                }
            }
 
            if (allCompleted)
            {
                await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
                    .SetColumns(x => x.OrderStatus == 2) // 已完成
                    .Where(x => x.OrderNo == orderNo)
                    .ExecuteCommandAsync();
            }
        }
 
 
        /// <summary>
        /// 回库操作  
        /// </summary>
        //public async Task<WebResponseContent> ReturnRemaining(string orderNo, string palletCode, string reason)
        //{
        //    try
        //    {
        //        // 1. 获取所有未分拣的出库锁定记录,包括拆包产生的记录
        //        var remainingLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
        //            .Where(it => it.OrderNo == orderNo && it.Status == 1)
        //            .ToListAsync();
 
        //        if (!remainingLocks.Any())
        //        {
        //            return WebResponseContent.Instance.Error("没有需要回库的剩余货物");
        //        }
        //        var tasks = new List<Dt_Task>();
        //        // 按托盘分组
        //        var palletGroups = remainingLocks.GroupBy(x => x.PalletCode);
        //        //查询任务表 
        //        var task = _taskRepository.QueryData(x => x.TaskNum == remainingLocks.First().TaskNum).FirstOrDefault();
        //        foreach (var group in palletGroups)
        //        {
        //            if (group.Key == palletCode)
        //            {
        //                var totalReturnQty = group.Sum(x => x.AssignQuantity - x.PickedQty);
 
        //                if (totalReturnQty <= 0) continue;
 
        //                // 分配新货位
        //                var newLocation = _locationInfoService.AssignLocation();
 
        //                // 更新出库锁定记录状态
        //                var lockIds = group.Where(x => x.PalletCode == palletCode).Select(x => x.Id).ToList();
        //                await _outStockLockInfoService.Db.Updateable<Dt_OutStockLockInfo>()
        //                    .SetColumns(it => new Dt_OutStockLockInfo { Status = OutLockStockStatusEnum.回库中.ObjToInt() })
        //                    .Where(it => lockIds.Contains(it.Id))
        //                    .ExecuteCommandAsync();
 
        //                // 更新拆包条码记录状态
        //                var splitBarcodes = await _splitPackageService.Db.Queryable<Dt_SplitPackageRecord>()
        //                    .Where(it => lockIds.Contains(it.OutStockLockInfoId))
        //                    .ToListAsync();
 
        //                foreach (var splitBarcode in splitBarcodes)
        //                {
        //                    splitBarcode.Status = 3;
        //                    await _splitPackageService.Db.Updateable(splitBarcode).ExecuteCommandAsync();
        //                }
 
        //                foreach (var lockInfo in group)
        //                {
        //                    if (lockInfo.PalletCode == palletCode)
        //                    {
        //                        decimal returnQty = lockInfo.AssignQuantity - lockInfo.PickedQty;
 
        //                        // 检查库存记录是否存在
        //                        var existingStock = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
        //                            .Where(it => it.Barcode == lockInfo.CurrentBarcode && it.StockId == lockInfo.StockId)
        //                            .FirstAsync();
 
        //                        if (existingStock != null)
        //                        {
        //                            // 库存记录存在,恢复锁定数量
        //                            await _stockInfoDetailService.Db.Updateable<Dt_StockInfoDetail>()
        //                                .SetColumns(it => new Dt_StockInfoDetail
        //                                {
        //                                    OutboundQuantity = it.OutboundQuantity - returnQty
        //                                })
        //                                .Where(it => it.Barcode == lockInfo.CurrentBarcode && it.StockId == lockInfo.StockId)
        //                                .ExecuteCommandAsync();
        //                        }
        //                        else
        //                        {
        //                            // 库存记录不存在(可能是拆包产生的新条码),创建新的库存记录
        //                            var newStockDetail = new Dt_StockInfoDetail
        //                            {
        //                                StockId = lockInfo.StockId,
        //                                MaterielCode = lockInfo.MaterielCode,
        //                                OrderNo = lockInfo.OrderNo,
        //                                BatchNo = lockInfo.BatchNo,
        //                                StockQuantity = returnQty, // 实际库存数量
        //                                OutboundQuantity = 0, // 回库后不再锁定
        //                                Barcode = lockInfo.CurrentBarcode,
        //                                InboundOrderRowNo = "0",
        //                                Status = StockStatusEmun.入库确认.ObjToInt(),
 
        //                            };
        //                            await _stockInfoDetailService.Db.Insertable(newStockDetail).ExecuteCommandAsync();
        //                        }
        //                    }
        //                }
 
 
        //                Dt_Task newtask = new()
        //                {
        //                    CurrentAddress = stations[task.TargetAddress],
        //                    Grade = 0,
        //                    PalletCode = palletCode,
        //                    NextAddress = "",
        //                    OrderNo= task.OrderNo,
        //                    Roadway = newLocation.RoadwayNo,
        //                    SourceAddress = stations[task.TargetAddress],
        //                    TargetAddress = newLocation.LocationCode,
        //                    TaskStatus = TaskStatusEnum.New.ObjToInt(),
        //                    TaskType = TaskTypeEnum.InPick.ObjToInt(),
        //                    // TaskNum = BaseDal.GetTaskNum(nameof(SequenceEnum.SeqTaskNum)),
        //                    PalletType = task.PalletType,
        //                    WarehouseId = task.WarehouseId,
        //                };
        //                tasks.Add(newtask);
 
        //            }
        //        }
        //        try
        //        {
        //            await _taskRepository.Db.Insertable(tasks).ExecuteCommandAsync();
        //            //删除 出库的  task
 
 
        //            //给 ess  流动信号  和创建任务
 
 
        //        }
        //        catch (Exception ex)
        //        {
 
        //        }
 
 
 
 
        //        return WebResponseContent.Instance.OK();
        //    }
        //    catch (Exception ex)
        //    {
        //        return WebResponseContent.Instance.Error($"回库操作失败: {ex.Message}");
        //    }
        //}
 
        public async Task<WebResponseContent> ReturnRemaining(string orderNo, string palletCode, string reason)
        {
            try
            {
                // 1. 获取所有未分拣的出库锁定记录,包括拆包产生的记录
                var remainingLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                    .Where(it => it.OrderNo == orderNo && it.Status == 1)
                    .ToListAsync();
 
                var stockinfo = _stockInfoService.Db.Queryable<Dt_StockInfo>().First(x => x.PalletCode == palletCode);
 
                // 2. 检查托盘上是否有其他非出库货物(库存货物)
                var palletStockGoods = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
                    .Where(it => it.StockId == stockinfo.Id && it.Status == StockStatusEmun.入库确认.ObjToInt())
                    .Where(it => it.OutboundQuantity == 0 || it.OutboundQuantity < it.StockQuantity) // 未完全出库的
                    .ToListAsync();
 
                // 3. 如果没有需要回库的货物(既无未分拣出库货物,也无其他库存货物)
                if (!remainingLocks.Any() && !palletStockGoods.Any())
                {
                    return WebResponseContent.Instance.Error("没有需要回库的剩余货物");
                }
 
                var tasks = new List<Dt_Task>();
 
                // 查询任务表
                var task = remainingLocks.Any()
                    ? _taskRepository.QueryData(x => x.TaskNum == remainingLocks.First().TaskNum).FirstOrDefault()
                    : _taskRepository.QueryData(x => x.PalletCode == palletCode).FirstOrDefault();
 
                if (task == null)
                {
                    return WebResponseContent.Instance.Error("未找到对应的任务信息");
                }
                var firstlocation = _locationInfoService.Db.Queryable<Dt_LocationInfo>().First(x => x.LocationCode == task.SourceAddress);
                decimal totalReturnQty = 0;
                var hasRemainingLocks = remainingLocks.Any(x => x.PalletCode == palletCode);
 
                // 情况1:处理未分拣的出库锁定记录
                if (hasRemainingLocks)
                {
                    var palletLocks = remainingLocks.Where(x => x.PalletCode == palletCode).ToList();
                    totalReturnQty = palletLocks.Sum(x => x.AssignQuantity - x.PickedQty);
 
                    if (totalReturnQty > 0)
                    {
                        // 分配新货位
                        var newLocation = _locationInfoService.AssignLocation(firstlocation.LocationType);
 
                        // 更新出库锁定记录状态
                        var lockIds = palletLocks.Select(x => x.Id).ToList();
                        await _outStockLockInfoService.Db.Updateable<Dt_OutStockLockInfo>()
                            .SetColumns(it => new Dt_OutStockLockInfo { Status = OutLockStockStatusEnum.回库中.ObjToInt() })
                            .Where(it => lockIds.Contains(it.Id))
                            .ExecuteCommandAsync();
 
                        // 更新拆包条码记录状态
                        var splitBarcodes = await _splitPackageService.Db.Queryable<Dt_SplitPackageRecord>()
                            .Where(it => lockIds.Contains(it.OutStockLockInfoId))
                            .ToListAsync();
 
                        foreach (var splitBarcode in splitBarcodes)
                        {
                            splitBarcode.Status = 3;
                            await _splitPackageService.Db.Updateable(splitBarcode).ExecuteCommandAsync();
                        }
 
                        // 处理库存记录
                        foreach (var lockInfo in palletLocks)
                        {
                            decimal returnQty = lockInfo.AssignQuantity - lockInfo.PickedQty;
 
                            // 检查库存记录是否存在
                            var existingStock = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
                                .Where(it => it.Barcode == lockInfo.CurrentBarcode && it.StockId == lockInfo.StockId)
                                .FirstAsync();
 
                            if (existingStock != null)
                            {
                                // 库存记录存在,恢复锁定数量
                                await _stockInfoDetailService.Db.Updateable<Dt_StockInfoDetail>()
                                    .SetColumns(it => new Dt_StockInfoDetail
                                    {
                                        OutboundQuantity = it.OutboundQuantity - returnQty
                                    })
                                    .Where(it => it.Barcode == lockInfo.CurrentBarcode && it.StockId == lockInfo.StockId)
                                    .ExecuteCommandAsync();
                            }
                            else
                            {
                                // 库存记录不存在(可能是拆包产生的新条码),创建新的库存记录
                                var newStockDetail = new Dt_StockInfoDetail
                                {
                                    StockId = lockInfo.StockId,
                                    MaterielCode = lockInfo.MaterielCode,
                                    OrderNo = lockInfo.OrderNo,
                                    BatchNo = lockInfo.BatchNo,
                                    StockQuantity = returnQty,
                                    OutboundQuantity = 0,
                                    Barcode = lockInfo.CurrentBarcode,
                                    InboundOrderRowNo = "0",
                                    Status = StockStatusEmun.入库确认.ObjToInt(),
 
                                };
                                await _stockInfoDetailService.Db.Insertable(newStockDetail).ExecuteCommandAsync();
                            }
                        }
 
                        // 创建回库任务
                        CreateReturnTask(tasks, task, palletCode, newLocation);
                    }
                }
 
                // 情况2:出库货物已分拣完,但托盘上还有其他库存货物需要回库
                if (!hasRemainingLocks && palletStockGoods.Any())
                {
                    // 分配新货位
                    var newLocation = _locationInfoService.AssignLocation(firstlocation.LocationType);
 
                    // 创建回库任务
                    CreateReturnTask(tasks, task, palletCode, newLocation);
 
                    totalReturnQty = palletStockGoods.Sum(x => x.StockQuantity - x.OutboundQuantity);
                }
 
                // 保存任务
                if (tasks.Any())
                {
                    try
                    {
                        await _taskRepository.Db.Insertable(tasks).ExecuteCommandAsync();
                        var targetAddress = task.TargetAddress;
                        _taskRepository.DeleteData(task);
                        // 给 ESS 流动信号和创建任务
                        try
                        {
                            var result = await _eSSApiService.MoveContainerAsync(new WIDESEA_DTO.Basic.MoveContainerRequest
                            {
                                slotCode = movestations[targetAddress],
                                containerCode = palletCode
                            });
                            if (result)
                            {
                                TaskModel esstask = new TaskModel()
                                {
                                    taskType = "putaway",
                                    taskGroupCode = "",
                                    groupPriority = 0,
                                    tasks = new List<TasksType>
                                    {
                                        new()
                                        {
                                            taskCode = tasks.First().TaskNum.ToString(),
                                            taskPriority = 0,
                                            taskDescribe = new TaskDescribeType {
                                                containerCode = palletCode,
                                                containerType = "CT_KUBOT_STANDARD",
                                                fromLocationCode = stations.GetValueOrDefault(targetAddress) ?? "",
                                                toStationCode = "",
                                                toLocationCode = tasks.First().TargetAddress,
                                                deadline = 0, storageTag = ""
                                            }
                                        }
                                    }
                                };
 
 
                                var resulttask = await _eSSApiService.CreateTaskAsync(esstask);
 
                                _logger.LogInformation("ReturnRemaining 创建任务返回:  " + resulttask);
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.LogInformation("ReturnRemaining 创建任务返回 catch err:  " + ex.Message);
 
                        }
 
 
                        return WebResponseContent.Instance.OK($"回库操作成功,共回库数量:{totalReturnQty}");
                    }
                    catch (Exception ex)
                    {
                        return WebResponseContent.Instance.Error($"创建回库任务失败: {ex.Message}");
                    }
                }
 
                return WebResponseContent.Instance.Error("未创建任何回库任务");
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error($"回库操作失败: {ex.Message}");
            }
        }
 
        /// <summary>
        /// 创建回库任务
        /// </summary>
        private void CreateReturnTask(List<Dt_Task> tasks, Dt_Task originalTask, string palletCode, Dt_LocationInfo newLocation)
        {
            Dt_Task newTask = new()
            {
                CurrentAddress = stations[originalTask.TargetAddress],
                Grade = 0,
                PalletCode = palletCode,
                NextAddress = "",
                OrderNo = originalTask.OrderNo,
                Roadway = newLocation.RoadwayNo,
                SourceAddress = stations[originalTask.TargetAddress],
                TargetAddress = newLocation.LocationCode,
                TaskStatus = TaskStatusEnum.New.ObjToInt(),
                TaskType = TaskTypeEnum.InPick.ObjToInt(),
                PalletType = originalTask.PalletType,
                WarehouseId = originalTask.WarehouseId,
 
            };
            tasks.Add(newTask);
        }
 
        /// <summary>
        /// 检查托盘是否需要回库的辅助方法
        /// </summary>
        public async Task<bool> CheckPalletNeedReturn(string orderNo, string palletCode)
        {
            // 1. 检查是否有未分拣的出库记录
            var hasUnpickedLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                .Where(it => it.OrderNo == orderNo && it.PalletCode == palletCode && it.Status == 1)
                .AnyAsync();
 
            if (hasUnpickedLocks)
                return true;
 
            // 2. 检查出库是否已完成但托盘还有库存货物
            var outboundFinished = !await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                .Where(it => it.PalletCode == palletCode && it.Status == 1)
                .AnyAsync();
 
            var stockinfo = _stockInfoService.Db.Queryable<Dt_StockInfo>().First(x => x.PalletCode == palletCode);
 
 
            var hasRemainingGoods = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
                .Where(it => it.StockId == stockinfo.Id && it.Status == StockStatusEmun.入库确认.ObjToInt())
                .Where(it => it.OutboundQuantity == 0 || it.OutboundQuantity < it.StockQuantity)
                .AnyAsync();
 
            return outboundFinished && hasRemainingGoods;
        }
 
        // 取消拣选功能
        public async Task<WebResponseContent> CancelPicking(string orderNo, string palletCode, string barcode)
        {
            try
            {
                _unitOfWorkManage.BeginTran();
                // 查找拣选记录
                var outStockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                        .Where(x => x.OrderNo == orderNo &&
                                   x.PalletCode == palletCode &&
                                   x.CurrentBarcode == barcode &&
                                   x.Status == 6)
                        .FirstAsync();
 
                if (outStockInfo == null)
                    return WebResponseContent.Instance.Error("未找到已拣选记录");
 
                // 还原出库详情状态
                outStockInfo.PickedQty = 0;
                outStockInfo.Status = 1;
                await _outStockLockInfoService.Db.Updateable(outStockInfo).ExecuteCommandAsync();
 
 
                var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
                       .Where(x => x.Barcode == barcode && x.StockId == outStockInfo.StockId)
                       .FirstAsync();
           
                stockDetail.StockQuantity += outStockInfo.AssignQuantity;
                stockDetail.OutboundQuantity += outStockInfo.AssignQuantity;
                await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
         
 
                // 还原出库单明细
                var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
                    .Where(x => x.Id == outStockInfo.OrderDetailId)
                    .FirstAsync();
 
                orderDetail.OverOutQuantity -= outStockInfo.AssignQuantity;
                await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
 
                // 删除拣选历史
                await Db.Deleteable<Dt_PickingRecord>()
                    .Where(x => x.OutStockLockId == outStockInfo.Id)
                    .ExecuteCommandAsync();
 
                _unitOfWorkManage.CommitTran();
                return WebResponseContent.Instance.OK("取消拣选成功");
 
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error($"取消拣选失败:{ex.Message}");
            }
        }
 
        // 获取未拣选列表
        public async Task<List<Dt_OutStockLockInfo>> GetUnpickedList(string orderNo, string palletCode)
        {
            var list = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                .Where(x => x.OrderNo == orderNo &&
                           x.PalletCode == palletCode &&
                           x.Status == 1)
                .ToListAsync();
            return list.Where(x => x.RemainQuantity > 0).ToList();
        }
 
        // 获取已拣选列表
        public async Task<List<Dt_OutStockLockInfo>> GetPickedList(string orderNo, string palletCode)
        {
            var list = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                .Where(x => x.OrderNo == orderNo &&
                           x.PalletCode == palletCode &&
                           x.Status == 6)
                .ToListAsync();
            return list;
        }
        // 获取拣选汇总
        public async Task<object> GetPickingSummary(ConfirmPickingDto dto)
        {
            var picked = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
             .WhereIF(!string.IsNullOrEmpty(dto.OrderNo), x => x.OrderNo == dto.OrderNo)
             .WhereIF(!string.IsNullOrEmpty(dto.PalletCode), x => x.PalletCode == dto.PalletCode)
             .Where(x => x.Status == 6)
             .GroupBy(x => new { x.PalletCode, x.MaterielCode })
             .Select(x => new SummaryPickingDto
             {
                 PalletCode = x.PalletCode,
                 MaterielCode = x.MaterielCode,
                 pickedCount = SqlFunc.AggregateCount(x.Id)
             }).FirstAsync();
            if (picked == null)
            {
                picked = new SummaryPickingDto { pickedCount = 0 };
            }
 
            var summary = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                .WhereIF(!string.IsNullOrEmpty(dto.OrderNo), x => x.OrderNo == dto.OrderNo)
                .WhereIF(!string.IsNullOrEmpty(dto.PalletCode), x => x.PalletCode == dto.PalletCode)
                .Where(x => x.Status == 1)
                .GroupBy(x => new { x.PalletCode, x.MaterielCode })
                .Select(x => new SummaryPickingDto
                {
                    PalletCode = x.PalletCode,
                    MaterielCode = x.MaterielCode,
                    UnpickedCount = SqlFunc.AggregateCount(x.Id),
                    UnpickedQuantity = SqlFunc.AggregateSum(x.AssignQuantity) - SqlFunc.AggregateSum(x.PickedQty),
 
                }).FirstAsync();
            if (summary == null)
            {
                summary = new SummaryPickingDto { pickedCount = 0 };
            }
            summary.pickedCount = picked.pickedCount;
 
            return summary;
        }
        /// <summary>
        /// 获取拣选历史
        /// </summary>
        public async Task<List<Dt_PickingRecord>> GetPickingHistory(int orderId)
        {
            // 通过出库单ID查询相关的拣选历史
            // 注意:Dt_PickingRecord 中没有直接存储OrderId,需要通过出库单明细关联
            var detailIds = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
                .Where(d => d.OrderId == orderId)
                .Select(d => d.Id)
                .ToListAsync();
 
            return await Db.Queryable<Dt_PickingRecord>()
                .Where(p => detailIds.Contains(p.OrderDetailId))
                .OrderByDescending(p => p.PickTime)
                .ToListAsync();
        }
 
 
        /// <summary>
        /// 获取托盘的出库状态信息
        /// </summary>
        public async Task<WebResponseContent> GetPalletOutboundStatus(string palletCode)
        {
            // 获取托盘的锁定信息
            var lockInfos = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                .Where(x => x.PalletCode == palletCode)
                .ToListAsync();
 
            // 获取托盘库存信息
            var stockInfo = await _stockInfoService.Db.Queryable<Dt_StockInfo>()
                .Includes(x => x.Details)
                .Where(x => x.PalletCode == palletCode)
                .FirstAsync();
 
            if (stockInfo == null)
                return WebResponseContent.Instance.Error("未找到托盘信息");
 
            // 计算各种数量
            var totalStockQuantity = stockInfo.Details.Sum(x => x.StockQuantity);
            var totalOutboundQuantity = stockInfo.Details.Sum(x => x.OutboundQuantity);
            var totalLockedQuantity = lockInfos.Where(x => x.Status == (int)OutLockStockStatusEnum.出库中)
                .Sum(x => x.AssignQuantity - x.PickedQty);
            var totalPickedQuantity = lockInfos.Sum(x => x.PickedQty);
 
            var result = new
            {
                PalletCode = palletCode,
                LocationCode = stockInfo.LocationCode,
                StockStatus = stockInfo.StockStatus,
                TotalStockQuantity = totalStockQuantity,
                TotalOutboundQuantity = totalOutboundQuantity,
                TotalLockedQuantity = totalLockedQuantity,
                TotalPickedQuantity = totalPickedQuantity,
                AvailableQuantity = totalStockQuantity - totalOutboundQuantity,
                LockInfos = lockInfos.Select(x => new
                {
                    x.Id,
                    x.MaterielCode,
                    x.OrderDetailId,
                    x.AssignQuantity,
                    x.PickedQty,
                    x.Status,
                    x.CurrentBarcode,
                    x.IsSplitted
                }).ToList(),
                StockDetails = stockInfo.Details.Select(x => new
                {
                    x.Barcode,
                    x.MaterielCode,
                    StockQuantity = x.StockQuantity,
                    OutboundQuantity = x.OutboundQuantity,
                    AvailableQuantity = x.StockQuantity - x.OutboundQuantity
                }).ToList()
            };
 
            return WebResponseContent.Instance.OK(null, result);
        }
 
        /// <summary>
        /// 直接出库 - 整个托盘出库,清空库存
        /// </summary>
        public async Task<WebResponseContent> DirectOutbound(DirectOutboundRequest request)
        {
            try
            {
                _unitOfWorkManage.BeginTran();
 
                var stockInfo = await _stockInfoService.Db.Queryable<Dt_StockInfo>()
                    .Includes(x => x.Details)
                    .Where(x => x.PalletCode == request.PalletCode).FirstAsync();
 
                if (stockInfo == null)
                    return WebResponseContent.Instance.Error("未找到托盘库存信息");
 
 
                var lockInfos = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                    .Where(x => x.OrderNo == request.OrderNo && x.PalletCode == request.PalletCode)
                    .ToListAsync();
 
 
                foreach (var lockInfo in lockInfos)
                {
                    if (lockInfo.Status == (int)OutLockStockStatusEnum.出库中)
                    {
                        lockInfo.PickedQty = lockInfo.AssignQuantity;
                    }
                    lockInfo.Status = (int)OutLockStockStatusEnum.已出库;
                    await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
 
                    var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
                    .Where(x => x.Id == lockInfo.OrderDetailId)
                    .FirstAsync();
                    if (orderDetail != null)
                    {
                        orderDetail.OverOutQuantity += lockInfo.PickedQty;
                        orderDetail.LockQuantity -= lockInfo.PickedQty;
                        orderDetail.OrderDetailStatus = (int)OrderDetailStatusEnum.Over;
                        orderDetail.LockQuantity = 0;
                        await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
                    }
                }
                var groupDetails = lockInfos.GroupBy(x => x.OrderDetailId).Select(x => new
                {
                    OrderDetailId = x.Key,
                    TotalQuantity = x.Sum(o => o.PickedQty)
                }).ToList();
                foreach (var item in groupDetails)
                {
                    var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>().Where(x => x.Id == item.OrderDetailId).FirstAsync();
                    if (orderDetail != null)
                    {
                        orderDetail.OverOutQuantity = item.TotalQuantity;
                        orderDetail.LockQuantity = 0;
                        orderDetail.OrderDetailStatus = (int)OrderDetailStatusEnum.Over;
                        await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
                    }
                }
 
                await CheckAndUpdateOrderStatus(request.OrderNo);
 
                var lockInfoIds = lockInfos.Select(x => x.Id).ToList();
                var splitRecords = await _splitPackageService.Db.Queryable<Dt_SplitPackageRecord>()
                    .Where(x => lockInfoIds.Contains(x.OutStockLockInfoId) &&
                               x.Status == (int)SplitPackageStatusEnum.已拆包)
                    .ToListAsync();
 
                foreach (var record in splitRecords)
                {
                    record.Status = (int)SplitPackageStatusEnum.已拣选;
                    await _splitPackageService.Db.Updateable(record).ExecuteCommandAsync();
                }
 
 
                var location = await _locationInfoService.Db.Queryable<Dt_LocationInfo>()
                    .Where(x => x.LocationCode == stockInfo.LocationCode)
                    .FirstAsync();
                if (location != null)
                {
                    location.LocationStatus = (int)LocationStatusEnum.Free;
                    await _locationInfoService.Db.Updateable(location).ExecuteCommandAsync();
                }
 
                foreach (var detail in stockInfo.Details)
                {
                    await _stockInfoDetailService.Db.Deleteable(detail).ExecuteCommandAsync();
                }
                await _stockInfoService.Db.Deleteable(stockInfo).ExecuteCommandAsync();
 
 
 
                _unitOfWorkManage.CommitTran();
                return WebResponseContent.Instance.OK("直接出库成功");
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                return WebResponseContent.Instance.Error($"直接出库失败: {ex.Message}");
            }
        }
    }
 
}