heshaofeng
2025-12-03 b4dfb1c5a0a3e6a682a98483e80ff372086aee8d
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
using Microsoft.Extensions.Logging;
using SqlSugar;
using WIDESEA_Common.LocationEnum;
using WIDESEA_Common.OrderEnum;
using WIDESEA_Common.StockEnum;
using WIDESEA_Core;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.BaseServices;
using WIDESEA_Core.Helper;
using WIDESEA_DTO.Stock;
using WIDESEA_IBasicService;
using WIDESEA_IOutboundService;
using WIDESEA_IRecordService;
using WIDESEA_IStockService;
using WIDESEA_Model.Models;
 
namespace WIDESEA_OutboundService
{
    public partial class OutboundOrderDetailService : ServiceBase<Dt_OutboundOrderDetail, IRepository<Dt_OutboundOrderDetail>>, IOutboundOrderDetailService
    {
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        public IRepository<Dt_OutboundOrderDetail> Repository => BaseDal;
 
 
        private readonly IStockService _stockService;
 
        private readonly IOutStockLockInfoService _outStockLockInfoService;
        private readonly ILocationInfoService _locationInfoService;
        private readonly IBasicService _basicService;
        private readonly IRecordService _recordService;
        private readonly IOutboundOrderService _outboundOrderService;
        private readonly ILocationStatusChangeRecordService _locationStatusChangeRecordService;
        private readonly ILogger<OutboundOrderDetailService> _logger;
        public OutboundOrderDetailService(IRepository<Dt_OutboundOrderDetail> BaseDal, IUnitOfWorkManage unitOfWorkManage, IStockService stockService, IOutStockLockInfoService outStockLockInfoService, IBasicService basicService, IRecordService recordService, ILocationInfoService locationInfoService, ILocationStatusChangeRecordService locationStatusChangeRecordService, IOutboundOrderService outboundOrderService, ILogger<OutboundOrderDetailService> logger) : base(BaseDal)
        {
            _unitOfWorkManage = unitOfWorkManage;
            _stockService = stockService;
            _outStockLockInfoService = outStockLockInfoService;
            _basicService = basicService;
            _recordService = recordService;
            _locationInfoService = locationInfoService;
            _locationStatusChangeRecordService = locationStatusChangeRecordService;
            _outboundOrderService = outboundOrderService;
            _logger = logger;
 
        }
 
 
        /// <summary>
        /// 分配出库库存  按先进先出原则分配
        /// </summary>
        public (List<Dt_StockInfo>, List<Dt_OutboundOrderDetail>, List<Dt_OutStockLockInfo>, List<Dt_LocationInfo>)
       AssignStockOutbound(List<Dt_OutboundOrderDetail> outboundOrderDetails)
        {
            if (!outboundOrderDetails.Any())
            {
                throw new Exception("未找到出库单明细信息");
            }
 
            if (outboundOrderDetails.GroupBy(x => x.OrderId).Count() > 1)
            {
                throw new Exception("请勿同时操作多个单据明细");
            }
 
            var orderId = outboundOrderDetails.First().OrderId;
            var outboundOrder = _outboundOrderService.Db.Queryable<Dt_OutboundOrder>()
                .First(x => x.Id == orderId);
 
            if (!CanReassignOrder(outboundOrder))
            {
                throw new Exception($"订单{outboundOrder.OrderNo}状态不允许重新分配库存");
            }
 
            List<Dt_StockInfo> outStocks = new List<Dt_StockInfo>();
            List<Dt_OutStockLockInfo> outStockLockInfos = new List<Dt_OutStockLockInfo>();
            List<Dt_LocationInfo> locationInfos = new List<Dt_LocationInfo>();
 
            // 按物料和批次分组处理
            var groupDetails = outboundOrderDetails
                .GroupBy(x => new { x.MaterielCode, x.BatchNo, x.SupplyCode })
                .Select(x => new
                {
                    MaterielCode = x.Key.MaterielCode,
                    BatchNo = x.Key.BatchNo,
                    SupplyCode = x.Key.SupplyCode,
                    Details = x.ToList(),
                    TotalNeedQuantity = CalculateReassignNeedQuantity(x.ToList())
                })
                .Where(x => x.TotalNeedQuantity > 0)
                .ToList();
 
            foreach (var item in groupDetails)
            {
                var needQuantity = item.TotalNeedQuantity;
 
                // 获取可用库存(按先进先出排序)
                List<Dt_StockInfo> stockInfos = _stockService.StockInfoService.GetUseableStocks(item.MaterielCode, item.BatchNo, item.SupplyCode);
 
                if (!stockInfos.Any())
                {
                    throw new Exception($"物料[{item.MaterielCode}]批次[{item.BatchNo}]供应商[{item.SupplyCode}]未找到可分配库存");
                }
 
                // 分配库存(按先进先出)
                var (autoAssignStocks, stockAllocations) = _stockService.StockInfoService.GetOutboundStocks(stockInfos, item.MaterielCode, needQuantity, out decimal residueQuantity);
 
                // 检查分配结果:如果完全无法分配(分配数量为0),则报错
                decimal allocatedQuantity = needQuantity - residueQuantity;
                if (allocatedQuantity <= 0)
                {
                    throw new Exception($"物料[{item.MaterielCode}]批次[{item.BatchNo}]库存不足,需要{needQuantity},但无法分配任何库存");
                }
 
                outStocks.AddRange(autoAssignStocks);
 
                // 按先进先出原则分配锁定数量到各个明细
                var distributionResult = DistributeLockQuantityByFIFO(item.Details, autoAssignStocks, stockAllocations, outStockLockInfos, outboundOrder);
 
                if (!distributionResult.success)
                {
                    throw new Exception(distributionResult.message);
                }
 
                // 更新出库单明细状态
                UpdateOrderDetailStatus(item.Details, allocatedQuantity, needQuantity);
            }
 
            if (outStocks.Any())
            {
                locationInfos.AddRange(_locationInfoService.GetLocationInfos(
                    outStocks.Select(x => x.LocationCode).Distinct().ToList()));
            }
 
            return (outStocks, outboundOrderDetails, outStockLockInfos, locationInfos);
        }
 
        /// <summary>
        /// 检查订单是否允许重新分配
        /// </summary>
        private bool CanReassignOrder(Dt_OutboundOrder outboundOrder)
        {
            // 允许重新分配的状态
            var allowedStatus = new[] { OutOrderStatusEnum.未开始, OutOrderStatusEnum.出库中, OutOrderStatusEnum.部分完成 };
 
            return allowedStatus.Contains((OutOrderStatusEnum)outboundOrder.OrderStatus);
        }
 
        /// <summary>
        /// 重新计算需求数量(考虑重新分配的场景)
        /// </summary>
        private decimal CalculateReassignNeedQuantity(List<Dt_OutboundOrderDetail> details)
        {
            decimal totalNeed = 0;
 
            foreach (var detail in details)
            {
                // 关键修改:重新分配时,只考虑未出库的部分,忽略锁定数量
                // 因为锁定数量在回库时已经被重置
                decimal remainingNeed = detail.OrderQuantity - detail.OverOutQuantity - detail.MoveQty;
 
                if (remainingNeed > 0)
                {
                    totalNeed += remainingNeed;
                }
            }
 
            return totalNeed;
        }
        private (bool success, string message) DistributeLockQuantityByFIFO(
           List<Dt_OutboundOrderDetail> details,
           List<Dt_StockInfo> assignStocks,
           Dictionary<int, decimal> stockAllocations,
           List<Dt_OutStockLockInfo> outStockLockInfos,
           Dt_OutboundOrder outboundOrder)
        {
            // 按先进先出排序出库单明细(Id小的优先)
            var sortedDetails = details
                .Where(d => d.OrderQuantity - d.OverOutQuantity - d.LockQuantity - d.MoveQty > 0)
                .OrderBy(x => x.Id)
                .ToList();
 
            if (!sortedDetails.Any())
                return (true, "无需分配");
 
            // 获取所有分配了库存的明细,按先进先出排序
            var allocatedStockDetails = assignStocks
                .SelectMany(x => x.Details)
                .Where(x => stockAllocations.ContainsKey(x.Id) && stockAllocations[x.Id] > 0)
                .OrderBy(x => x.CreateDate)
                .ThenBy(x => x.StockId)
                .ToList();
 
            if (!allocatedStockDetails.Any())
            {
                return (false, "没有可分配的库存明细");
            }
 
            decimal totalNeedQuantity = sortedDetails.Sum(d =>
                d.OrderQuantity - d.OverOutQuantity - d.LockQuantity - d.MoveQty);
            decimal allocatedQuantity = 0;
 
            // 为每个库存明细创建分配记录
            foreach (var stockDetail in allocatedStockDetails)
            {
                if (!stockAllocations.TryGetValue(stockDetail.Id, out decimal allocatedQuantityForStock))
                    continue;
 
                if (allocatedQuantityForStock <= 0) continue;
 
                var stockInfo = assignStocks.First(x => x.Id == stockDetail.StockId);
                decimal remainingAllocate = allocatedQuantityForStock;
 
                // 按顺序分配给各个出库单明细
                foreach (var detail in sortedDetails)
                {
                    if (remainingAllocate <= 0) break;
 
                    // 计算这个明细还需要分配的数量
                    var detailNeed = detail.OrderQuantity - detail.OverOutQuantity - detail.LockQuantity - detail.MoveQty;
                    if (detailNeed <= 0) continue;
 
                    // 分配数量
                    var assignQuantity = Math.Min(remainingAllocate, detailNeed);
 
                    // 验证条码是否存在
                    if (string.IsNullOrEmpty(stockDetail.Barcode))
                    {
                        return (false, $"库存明细ID[{stockDetail.Id}]的条码为空");
                    }
 
                    // 创建出库锁定信息
                    var lockInfo = _outStockLockInfoService.GetOutStockLockInfo(
                        outboundOrder, detail, stockInfo, assignQuantity, stockDetail.Barcode);
                    outStockLockInfos.Add(lockInfo);
 
                    // 更新明细的锁定数量
                    detail.LockQuantity += assignQuantity;
                    remainingAllocate -= assignQuantity;
                    allocatedQuantity += assignQuantity;
                }
 
                // 如果还有剩余分配数量,记录警告
                if (remainingAllocate > 0)
                {
                    _logger.LogWarning($"库存分配后仍有剩余数量未分配: {remainingAllocate}, 条码: {stockDetail.Barcode}");
                }
            }
 
            // 验证是否至少分配了一部分
            if (allocatedQuantity <= 0)
            {
                return (false, "库存分配失败,无法分配任何数量");
            }
 
            // 记录分配结果
            if (allocatedQuantity < totalNeedQuantity)
            {
                _logger.LogWarning($"库存部分分配,需要{totalNeedQuantity},实际分配{allocatedQuantity}");
            }
            else
            {
                _logger.LogInformation($"库存完全分配,分配数量{allocatedQuantity}");
            }
 
            return (true, "分配成功");
        }
 
 
        /// <summary>
        /// 为分批分配库存
        /// </summary>
        public async Task<(List<Dt_StockInfo>, List<Dt_OutboundOrderDetail>, List<Dt_OutStockLockInfo>, List<Dt_LocationInfo>)>
            AssignStockForBatch(Dt_OutboundOrderDetail orderDetail, decimal batchQuantity, string batchNo)
        {
            if (orderDetail == null)
            {
                throw new Exception("未找到出库单明细信息");
            }
 
            var outboundOrder = await _outboundOrderService.Db.Queryable<Dt_OutboundOrder>()
                .FirstAsync(x => x.Id == orderDetail.OrderId);
 
            List<Dt_StockInfo> outStocks = new List<Dt_StockInfo>();
            List<Dt_OutStockLockInfo> outStockLockInfos = new List<Dt_OutStockLockInfo>();
            List<Dt_LocationInfo> locationInfos = new List<Dt_LocationInfo>();
 
            // 按物料和批次分组处理(这里只有一个明细)
            var groupDetails = new List<Dt_OutboundOrderDetail> { orderDetail }
                .GroupBy(x => new { x.MaterielCode, x.BatchNo, x.SupplyCode })
                .Select(x => new
                {
                    MaterielCode = x.Key.MaterielCode,
                    BatchNo = x.Key.BatchNo,
                    SupplyCode = x.Key.SupplyCode,
                    Details = x.ToList(),
                    TotalNeedQuantity = batchQuantity  // 使用分批数量
                })
                .Where(x => x.TotalNeedQuantity > 0)
                .ToList();
 
            foreach (var item in groupDetails)
            {
                var needQuantity = item.TotalNeedQuantity;
 
                // 获取可用库存(按先进先出排序)
                List<Dt_StockInfo> stockInfos = _stockService.StockInfoService.GetUseableStocks(item.MaterielCode, item.BatchNo, item.SupplyCode);
                if (!stockInfos.Any())
                {
                    throw new Exception($"物料[{item.MaterielCode}]批次[{item.BatchNo}]未找到可分配库存");
                }
 
                // 分配库存(按先进先出)
                var (autoAssignStocks, stockAllocations) = _stockService.StockInfoService.GetOutboundStocks(stockInfos, item.MaterielCode, needQuantity, out decimal residueQuantity);
 
                // 检查分配结果
                decimal allocatedQuantity = needQuantity - residueQuantity;
                if (allocatedQuantity <= 0)
                {
                    throw new Exception($"物料[{item.MaterielCode}]批次[{item.BatchNo}]库存不足,需要{needQuantity},但无法分配任何库存");
                }
 
                outStocks.AddRange(autoAssignStocks);
 
                // 按先进先出原则分配锁定数量到各个明细
                var distributionResult = DistributeLockQuantityByFIFO(item.Details, autoAssignStocks, stockAllocations, outStockLockInfos, outboundOrder, batchNo);
 
                if (!distributionResult.success)
                {
                    throw new Exception(distributionResult.message);
                }
 
                // 更新出库单明细状态
                UpdateOrderDetailStatus(item.Details, allocatedQuantity, needQuantity);
            }
 
            if (outStocks.Any())
            {
                locationInfos.AddRange(_locationInfoService.GetLocationInfos(
                  outStocks.Select(x => x.LocationCode).Distinct().ToList()));
 
 
            }
 
            return (outStocks, groupDetails.SelectMany(x => x.Details).ToList(), outStockLockInfos, locationInfos);
        }
 
        /// <summary>
        /// 按先进先出原则分配锁定数量
        /// </summary>
        private (bool success, string message) DistributeLockQuantityByFIFO(
            List<Dt_OutboundOrderDetail> details,
            List<Dt_StockInfo> assignStocks,
            Dictionary<int, decimal> stockAllocations,
            List<Dt_OutStockLockInfo> outStockLockInfos,
            Dt_OutboundOrder outboundOrder,
            string batchNo)
        {
            var sortedDetails = details
                .Where(d => d.OrderQuantity - d.OverOutQuantity - d.AllocatedQuantity > 0)
                .OrderBy(x => x.Id)
                .ToList();
 
            if (!sortedDetails.Any())
                return (true, "无需分配");
 
            // 获取所有分配了库存的明细,按先进先出排序
            var allocatedStockDetails = assignStocks
                .SelectMany(x => x.Details)
                .Where(x => stockAllocations.ContainsKey(x.Id) && stockAllocations[x.Id] > 0)
                .OrderBy(x => x.CreateDate)
                .ThenBy(x => x.StockId)
                .ToList();
 
            if (!allocatedStockDetails.Any())
            {
                return (false, "没有可分配的库存明细");
            }
 
            decimal totalNeedQuantity = sortedDetails.Sum(d =>
                d.OrderQuantity - d.OverOutQuantity - d.AllocatedQuantity);
            decimal allocatedQuantity = 0;
 
            // 为每个库存明细创建分配记录
            foreach (var stockDetail in allocatedStockDetails)
            {
                if (!stockAllocations.TryGetValue(stockDetail.Id, out decimal allocatedQuantityForStock))
                    continue;
 
                if (allocatedQuantityForStock <= 0) continue;
 
                var stockInfo = assignStocks.First(x => x.Id == stockDetail.StockId);
                decimal remainingAllocate = allocatedQuantityForStock;
 
                // 按顺序分配给各个出库单明细
                foreach (var detail in sortedDetails)
                {
                    if (remainingAllocate <= 0) break;
 
                    // 计算这个明细还需要分配的数量
                    var detailNeed = detail.OrderQuantity - detail.OverOutQuantity - detail.AllocatedQuantity;
                    if (detailNeed <= 0) continue;
 
                    // 分配数量
                    var assignQuantity = Math.Min(remainingAllocate, detailNeed);
 
                    // 验证条码是否存在
                    if (string.IsNullOrEmpty(stockDetail.Barcode))
                    {
                        return (false, $"库存明细ID[{stockDetail.Id}]的条码为空");
                    }
 
 
                    // 创建出库锁定信息
                    var lockInfo = _outStockLockInfoService.GetOutStockLockInfo(
                        outboundOrder, detail, stockInfo, assignQuantity, stockDetail.Barcode, batchNo);
                    outStockLockInfos.Add(lockInfo);
 
                    // 更新明细的已分配数量
                    detail.AllocatedQuantity += assignQuantity;
                    detail.LockQuantity = detail.AllocatedQuantity;
                    remainingAllocate -= assignQuantity;
                    allocatedQuantity += assignQuantity;
                }
 
                // 如果还有剩余分配数量,记录警告
                if (remainingAllocate > 0)
                {
                    _logger.LogWarning($"库存分配后仍有剩余数量未分配: {remainingAllocate}, 条码: {stockDetail.Barcode}");
                }
            }
 
            // 验证是否至少分配了一部分
            if (allocatedQuantity <= 0)
            {
                return (false, "库存分配失败,无法分配任何数量");
            }
 
            // 记录分配结果
            if (allocatedQuantity < totalNeedQuantity)
            {
                _logger.LogWarning($"库存部分分配,需要{totalNeedQuantity},实际分配{allocatedQuantity}");
            }
            else
            {
                _logger.LogInformation($"库存完全分配,分配数量{allocatedQuantity}");
            }
 
            return (true, "分配成功");
        }
 
 
        private void UpdateOrderDetailStatus(List<Dt_OutboundOrderDetail> details,
    decimal allocatedQuantity, decimal needQuantity)
        {
            foreach (var detail in details)
            {
                var detailNeed = detail.OrderQuantity - detail.LockQuantity - detail.OverOutQuantity - detail.MoveQty;
 
                if (detailNeed <= 0)
                {
                    // 该明细已完全分配
                    detail.OrderDetailStatus = OrderDetailStatusEnum.AssignOver.ObjToInt();
                }
                else if (allocatedQuantity < needQuantity)
                {
                    // 整体部分分配,该明细可能还有需求
                    detail.OrderDetailStatus = OrderDetailStatusEnum.AssignOverPartial.ObjToInt();
                }
                else
                {
                    // 整体完全分配
                    detail.OrderDetailStatus = OrderDetailStatusEnum.AssignOver.ObjToInt();
                }
            }
        }
        /// <summary>
        /// 出库库存分配后,更新数据库数据
        /// </summary>
        /// <param name="stockInfos"></param>
        /// <param name="outboundOrderDetails"></param>
        /// <param name="outStockLockInfos"></param>
        /// <param name="locationInfos"></param>
        /// <param name="locationStatus"></param>
        /// <param name="tasks"></param>
        /// <returns></returns>
        public WebResponseContent LockOutboundStockDataUpdate(List<Dt_StockInfo> stockInfos, List<Dt_OutboundOrderDetail> outboundOrderDetails,
            List<Dt_OutStockLockInfo> outStockLockInfos, List<Dt_LocationInfo> locationInfos,
            LocationStatusEnum locationStatus = LocationStatusEnum.Lock, List<Dt_Task>? tasks = null)
        {
            try
            {
                // 更新库存状态
                stockInfos.ForEach(x => x.StockStatus = (int)StockStatusEmun.出库锁定);
                _stockService.StockInfoService.Repository.UpdateData(stockInfos);
 
                // 更新库存明细
                var stockDetails = stockInfos.SelectMany(x => x.Details).ToList();
                _stockService.StockInfoDetailService.Repository.UpdateData(stockDetails);
                BaseDal.UpdateData(outboundOrderDetails);
 
                List<Dt_OutStockLockInfo> addOutStockLockInfos = outStockLockInfos.Where(x => x.Id == 0).ToList();
                if (addOutStockLockInfos != null && addOutStockLockInfos.Any())
                {
                    if (tasks != null)
                    {
                        addOutStockLockInfos.ForEach(x =>
                        {
                            x.TaskNum = tasks.FirstOrDefault(v => v.PalletCode == x.PalletCode)?.TaskNum;
                        });
                    }
 
                    _outStockLockInfoService.Repository.AddData(addOutStockLockInfos);
                }
                List<Dt_OutStockLockInfo> updateOutStockLockInfos = outStockLockInfos.Where(x => x.Id > 0).ToList();
                if (updateOutStockLockInfos != null && updateOutStockLockInfos.Any())
                {
                    _outStockLockInfoService.Repository.UpdateData(updateOutStockLockInfos);
                }
 
                _locationStatusChangeRecordService.AddLocationStatusChangeRecord(locationInfos, locationStatus, LocationChangeType.OutboundAssignLocation, "", tasks?.Select(x => x.TaskNum).ToList());
                _locationInfoService.UpdateLocationStatus(locationInfos, locationStatus);
                return WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
 
 
 
        public override PageGridData<Dt_OutboundOrderDetail> GetPageData(PageDataOptions options)
        {
            //var  pageGridData = base.GetPageData(options);
 
            ISugarQueryable<Dt_OutboundOrderDetail> sugarQueryable1 = BaseDal.Db.Queryable<Dt_OutboundOrderDetail>();
            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_InboundOrderDetail.OrderId).FirstLetterToLower());
                        if (searchParameters != null)
                        {
                            sugarQueryable1 = sugarQueryable1.Where(x => x.OrderId == searchParameters.Value.ObjToInt());
                            var dataList = sugarQueryable1.ToPageList(options.Page, options.Rows, ref totalCount);
                            return new PageGridData<Dt_OutboundOrderDetail>(totalCount, dataList);
                        }
                    }
 
 
                }
            }
            return new PageGridData<Dt_OutboundOrderDetail>();
        }
 
 
        public (List<Dt_StockInfo>, Dt_OutboundOrderDetail, List<Dt_OutStockLockInfo>, List<Dt_LocationInfo>)AssignStockOutbound(Dt_OutboundOrderDetail outboundOrderDetail, List<StockSelectViewDTO> stockSelectViews)
        {
            // 验证用户选择
            (bool, string) checkResult = CheckSelectStockDeital(outboundOrderDetail, stockSelectViews);
            if (!checkResult.Item1) throw new Exception(checkResult.Item2);
 
            Dt_OutboundOrder outboundOrder = _outboundOrderService.Repository.QueryFirst(x => x.Id == outboundOrderDetail.OrderId);
            var originalNeedQuantity = outboundOrderDetail.OrderQuantity - outboundOrderDetail.LockQuantity - outboundOrderDetail.MoveQty;
 
            List<Dt_StockInfo> outStocks = new List<Dt_StockInfo>();
            List<Dt_OutStockLockInfo> outStockLockInfos = new List<Dt_OutStockLockInfo>();
 
            decimal remainingNeedQuantity = originalNeedQuantity;
            decimal totalAssignedFromUserSelection = 0;
 
            // 按先进先出排序用户选择的库存
            var userSelectedStocks = _stockService.StockInfoService.GetStockInfosByPalletCodes(stockSelectViews.Select(x => x.PalletCode).ToList());
 
            var sortedUserSelectedStocks = userSelectedStocks.OrderBy(x => x.CreateDate).ToList();
 
            // 分配用户选择的库存
            foreach (var stock in sortedUserSelectedStocks)
            {
                if (remainingNeedQuantity <= 0) break;
 
                // 获取用户对该托盘的选择数量
                var userSelection = stockSelectViews.FirstOrDefault(x => x.PalletCode == stock.PalletCode);
                if (userSelection == null) continue;
 
                // 计算该托盘实际可用数量
                var availableQuantity = CalculateAvailableQuantity(stock, outboundOrderDetail.MaterielCode,
                    outboundOrderDetail.BatchNo, outboundOrderDetail.SupplyCode);
 
                // 确定分配数量:取用户选择数量、可用数量和剩余需求的最小值
                var assignQuantity = Math.Min(Math.Min(userSelection.UseableQuantity, availableQuantity),remainingNeedQuantity);
 
                if (assignQuantity <= 0) continue;
 
                // 执行分配
                var actualAssigned = AssignStockQuantity(stock, outboundOrderDetail, assignQuantity);
                if (actualAssigned > 0)
                {
                    outStocks.Add(stock);
                    totalAssignedFromUserSelection += actualAssigned;
                    remainingNeedQuantity -= actualAssigned;
 
                    // 创建锁定记录
                    var lockInfo = CreateOutStockLockInfo(outboundOrder, outboundOrderDetail, stock, actualAssigned);
                    outStockLockInfos.Add(lockInfo);
                }
            }
 
            // 检查用户选择是否至少分配了一部分
            if (totalAssignedFromUserSelection <= 0)
            {
                throw new Exception("用户选择的库存无法分配任何数量");
            }
 
            // 如果用户选择的库存不够,自动分配剩余部分
          
            if (remainingNeedQuantity > 0)
            {
                //// 可选:这里可以根据业务需求决定是否允许自动分配
                //// 如果要求严格按用户选择出库,可以抛出异常
                //// throw new Exception($"用户选择的库存数量不足,还需{remainingNeedQuantity},请重新选择");
 
                //// 如果需要自动分配,记录日志
                //_logger.LogInformation($"用户选择的库存数量不足,还需{remainingNeedQuantity},系统将自动分配");
 
                //List<Dt_StockInfo> autoStocks = _stockService.StockInfoService.GetUseableStocks(
                //    outboundOrderDetail.MaterielCode,
                //    outboundOrderDetail.BatchNo,
                //    "");
 
                //// 排除用户已选择且已分配的托盘
                //var assignedPalletCodes = outStocks.Select(x => x.PalletCode).ToList();
                //autoStocks = autoStocks
                //    .Where(x => !assignedPalletCodes.Contains(x.PalletCode))
                //    .ToList();
 
                //var (autoAssignStocks, stockAllocations) = _stockService.StockInfoService.GetOutboundStocks(
                //    autoStocks,
                //    outboundOrderDetail.MaterielCode,
                //    remainingNeedQuantity,
                //    out decimal residueQuantity);
 
                //if (autoAssignStocks != null && autoAssignStocks.Any())
                //{
                //    outStocks.AddRange(autoAssignStocks);
 
                //    // 为自动分配的库存创建锁定记录
                //    var autoLockInfos = CreateLockInfosForAutoAssign(outboundOrder, outboundOrderDetail, autoAssignStocks, stockAllocations);
                //    outStockLockInfos.AddRange(autoLockInfos);
 
                //    // 更新已分配数量
                //    decimal autoAssignedQuantity = remainingNeedQuantity - residueQuantity;
                //    totalAssignedFromUserSelection += autoAssignedQuantity;
                //    remainingNeedQuantity = residueQuantity; // 更新剩余需求
                //}
                //else if (remainingNeedQuantity > 0)
                //{
                //    _logger.LogWarning($"自动分配失败,剩余需求{remainingNeedQuantity}无法满足");
                //}
            }
 
            // 更新锁定数量
            outboundOrderDetail.LockQuantity += totalAssignedFromUserSelection + totalAssignedFromUserSelection;
 
            // 更新状态
            UpdateOrderDetailStatus(outboundOrderDetail, remainingNeedQuantity);
 
            List<Dt_LocationInfo> locationInfos = _locationInfoService.GetLocationInfos(outStocks.Select(x => x.LocationCode).ToList());
 
            return (outStocks, outboundOrderDetail, outStockLockInfos, locationInfos);
        }
 
        // 辅助方法
        private decimal CalculateAvailableQuantity(Dt_StockInfo stock, string materielCode, string batchNo, string supplyCode)
        {
            var relevantDetails = stock.Details
                .Where(d => d.MaterielCode == materielCode &&
                           (string.IsNullOrEmpty(batchNo) || d.BatchNo == batchNo) &&
                           (string.IsNullOrEmpty(supplyCode) || d.SupplyCode == supplyCode))
                .ToList();
 
            return relevantDetails.Sum(d => d.StockQuantity - d.OutboundQuantity);
        }
 
        private decimal AssignStockQuantity(Dt_StockInfo stock, Dt_OutboundOrderDetail detail, decimal assignQuantity)
        {
            decimal remainingAssign = assignQuantity;
 
            // 按先进先出分配库存明细
            var query = stock.Details.AsQueryable()
                .Where(d => d.MaterielCode == detail.MaterielCode &&
                           (d.StockQuantity - d.OutboundQuantity) > 0);
               // .OrderBy(d => d.CreateDate);             
 
            if (!string.IsNullOrEmpty(detail.BatchNo))
            {
                query = query.Where(x => x.BatchNo == detail.BatchNo);
            }
            // 如果出库单有供应商要求,按供应商过滤
            if (!string.IsNullOrEmpty(detail.SupplyCode))
            {
                query = query.Where(d => d.SupplyCode == detail.SupplyCode);
            }
            var sortedDetails= query.ToList().OrderBy(d => d.CreateDate);
 
 
            foreach (var stockDetail in sortedDetails)
            {
                if (remainingAssign <= 0) break;
 
                var available = stockDetail.StockQuantity - stockDetail.OutboundQuantity;
                var assign = Math.Min(available, remainingAssign);
 
                stockDetail.OutboundQuantity += assign;
                remainingAssign -= assign;
            }
 
            return assignQuantity - remainingAssign; // 返回实际分配数量
        }
 
        private Dt_OutStockLockInfo CreateOutStockLockInfo(Dt_OutboundOrder outboundOrder, Dt_OutboundOrderDetail detail,
            Dt_StockInfo stock, decimal quantity)
        {
            var barcode = stock.Details
                .Where(d => !string.IsNullOrEmpty(d.Barcode))
                .Select(d => d.Barcode)
                .FirstOrDefault();
 
            return _outStockLockInfoService.GetOutStockLockInfo(outboundOrder, detail, stock, quantity, barcode);
        }
 
        private List<Dt_OutStockLockInfo> CreateLockInfosForAutoAssign(Dt_OutboundOrder outboundOrder,
            Dt_OutboundOrderDetail detail, List<Dt_StockInfo> stocks, Dictionary<int, decimal> allocations)
        {
            var lockInfos = new List<Dt_OutStockLockInfo>();
 
            foreach (var stock in stocks.OrderBy(x => x.CreateDate))
            {
                if (allocations.TryGetValue(stock.Id, out decimal quantity) && quantity > 0)
                {
                    var lockInfo = CreateOutStockLockInfo(outboundOrder, detail, stock, quantity);
                    lockInfos.Add(lockInfo);
                }
            }
 
            return lockInfos;
        }
 
        private void UpdateOrderDetailStatus(Dt_OutboundOrderDetail detail, decimal remainingQuantity)
        {
            if (remainingQuantity <= 0)
            {
                detail.OrderDetailStatus = OrderDetailStatusEnum.AssignOver.ObjToInt();
            }
            else
            {
                detail.OrderDetailStatus = OrderDetailStatusEnum.AssignOverPartial.ObjToInt();
            }
        }
 
        private (bool, string) CheckSelectStockDeital(Dt_OutboundOrderDetail outboundOrderDetail, List<StockSelectViewDTO> stockSelectViews)
        {
            var needQuantity = outboundOrderDetail.OrderQuantity - outboundOrderDetail.LockQuantity - outboundOrderDetail.MoveQty;
 
            if (needQuantity <= 0)
            {
                return (false, "出库单明细无需分配库存");
            }
 
            // 检查总选择数量是否大于0
            var totalSelected = stockSelectViews.Sum(x => x.UseableQuantity);
            if (totalSelected <= 0)
            {
                return (false, "用户选择的库存数量必须大于0");
            }
 
            // 检查每个托盘的可用数量
            foreach (var selection in stockSelectViews)
            {
                if (selection.UseableQuantity <= 0)
                {
                    return (false, $"托盘[{selection.PalletCode}]的选择数量必须大于0");
                }
 
                var stock = _stockService.StockInfoService.GetStockInfoByPalletCode(selection.PalletCode);
                if (stock == null)
                {
                    return (false, $"托盘[{selection.PalletCode}]不存在");
                }
 
                var available = CalculateAvailableQuantity(stock, outboundOrderDetail.MaterielCode,
                    outboundOrderDetail.BatchNo, outboundOrderDetail.SupplyCode);
 
                if (available <= 0)
                {
                    return (false, $"托盘[{selection.PalletCode}]没有可用库存");
                }
            }
 
            return (true, "验证通过");
        }
    }
}