pan
2025-11-11 c4e1a656954799267cbd61d3de3a040e8dc8e46a
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
using WIDESEA_Common.LocationEnum;
using WIDESEA_Common.StockEnum;
using WIDESEA_Core;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.BaseServices;
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;
 
        public OutboundOrderDetailService(IRepository<Dt_OutboundOrderDetail> BaseDal, IUnitOfWorkManage unitOfWorkManage, IStockService stockService, IOutStockLockInfoService outStockLockInfoService, IBasicService basicService, IRecordService recordService, ILocationInfoService locationInfoService, ILocationStatusChangeRecordService locationStatusChangeRecordService, IOutboundOrderService outboundOrderService) : base(BaseDal)
        {
            _unitOfWorkManage = unitOfWorkManage;
            _stockService = stockService;
            _outStockLockInfoService = outStockLockInfoService;
            _basicService = basicService;
            _recordService = recordService;
            _locationInfoService = locationInfoService;
            _locationStatusChangeRecordService = locationStatusChangeRecordService;
            _outboundOrderService = outboundOrderService;
        }
 
 
        /// <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 outboundOrder = _outboundOrderService.Db.Queryable<Dt_OutboundOrder>()
                .First(x => x.Id == outboundOrderDetails.First().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 = outboundOrderDetails
                .GroupBy(x => new { x.MaterielCode, x.BatchNo })
                .Select(x => new
                {
                    MaterielCode = x.Key.MaterielCode,
                    BatchNo = x.Key.BatchNo,
                    Details = x.ToList(),
                    TotalNeedQuantity = x.Sum(v => v.OrderQuantity - v.OverOutQuantity - v.LockQuantity)
                })
                .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);
                if (!stockInfos.Any())
                {
                    throw new Exception($"物料[{item.MaterielCode}]批次[{item.BatchNo}]未找到可分配库存");
                }
 
                // 分配库存(按先进先出)
                List<Dt_StockInfo> autoAssignStocks = _stockService.StockInfoService.GetOutboundStocks(
                    stockInfos, item.MaterielCode, needQuantity, out decimal residueQuantity);
 
                if (residueQuantity > 0)
                {
                    throw new Exception($"物料[{item.MaterielCode}]库存不足,需要{needQuantity},可用{needQuantity - residueQuantity}");
                }
 
                outStocks.AddRange(autoAssignStocks);
 
                // 按先进先出原则分配锁定数量到各个明细
                DistributeLockQuantityByFIFO(item.Details, autoAssignStocks, outStockLockInfos, outboundOrder);
            }
 
            locationInfos.AddRange(_locationInfoService.GetLocationInfos(outStocks.Select(x => x.LocationCode).Distinct().ToList()));
 
            return (outStocks, outboundOrderDetails, outStockLockInfos, locationInfos);
        }
 
        /// <summary>
        /// 按先进先出原则分配锁定数量到各个明细
        /// </summary>
        private void DistributeLockQuantityByFIFO(
            List<Dt_OutboundOrderDetail> details,
            List<Dt_StockInfo> assignStocks,
            List<Dt_OutStockLockInfo> outStockLockInfos,
            Dt_OutboundOrder outboundOrder)
        {
            // 按先进先出排序出库单明细(假设先创建的明细需要优先满足)
            var sortedDetails = details
                .OrderBy(x => x.Id) // 按ID排序,假设先创建的ID小
                .ToList();
 
            // 按先进先出排序库存(生产日期最早的优先)
            var sortedStockDetails = assignStocks
                .SelectMany(x => x.Details)
                .Where(x => details.Any(d => d.MaterielCode == x.MaterielCode))
                .OrderBy(x => x.ProductionDate)
                .ToList();
 
            // 为每个库存明细创建分配记录
            foreach (var stockDetail in sortedStockDetails)
            {
                var stockInfo = assignStocks.First(x => x.Id == stockDetail.StockId);
                var allocatedQuantity = stockDetail.OutboundQuantity; // 这个库存明细分配的数量
 
                if (allocatedQuantity <= 0) continue;
 
                // 按顺序分配给各个出库单明细
                decimal remainingAllocate = allocatedQuantity;
 
                foreach (var detail in sortedDetails)
                {
                    if (remainingAllocate <= 0) break;
 
                    // 计算这个明细还需要分配的数量
                    var alreadyAssigned = outStockLockInfos
                        .Where(x => x.OrderDetailId == detail.Id && x.StockId == stockInfo.Id)
                        .Sum(x => x.AssignQuantity);
 
                    var detailNeed = detail.OrderQuantity - detail.OverOutQuantity - detail.LockQuantity - alreadyAssigned;
 
                    if (detailNeed <= 0) continue;
 
                    // 分配数量
                    var assignQuantity = Math.Min(remainingAllocate, detailNeed);
 
                    // 创建出库锁定信息
                    var lockInfo = _outStockLockInfoService.GetOutStockLockInfo(
                        outboundOrder, detail, stockInfo, assignQuantity, stockDetail.Barcode);
                    outStockLockInfos.Add(lockInfo);
 
                    // 更新明细的锁定数量
                    detail.LockQuantity += assignQuantity;
                    remainingAllocate -= assignQuantity;
                }
 
                // 如果还有剩余分配数量,说明逻辑有误
                if (remainingAllocate > 0)
                {
                    throw new Exception($"库存分配逻辑错误,剩余未分配数量:{remainingAllocate}");
                }
            }
        }
 
 
/// <summary>
    /// 创建出库锁定信息
    /// </summary>
    private void CreateOutStockLockInfos(Dt_OutboundOrder outboundOrder,List<Dt_OutboundOrderDetail> details,
        List<Dt_StockInfo> assignStocks,List<Dt_OutStockLockInfo> outStockLockInfos)
        {
            foreach (var stock in assignStocks)
            {
                // 获取该库存中相关物料的可用条码信息
                var stockDetails = stock.Details
                    .Where(x => details.Any(d => d.MaterielCode == x.MaterielCode) &&
                               x.StockQuantity > x.OutboundQuantity)
                    .OrderBy(x => x.ProductionDate) // 先进先出
                    .ToList();
                if (!stockDetails.Any()) continue;
 
                var stockAssignQuantity = stockDetails.Sum(x => x.OutboundQuantity);
 
 
                // 查找这个库存已经分配的数量
                var existingAssign = outStockLockInfos
                    .Where(x => x.StockId == stock.Id &&
                               details.Any(d => d.Id == x.OrderDetailId))
                    .Sum(x => x.AssignQuantity);
 
                var availableAssign = stockAssignQuantity - existingAssign;
 
                if (availableAssign <= 0) continue;
 
                // 按先进先出原则分配条码
                var barcodeAllocation = AllocateBarcodes(stockDetails, availableAssign);
 
 
                // 分配给各个明细
                foreach (var detail in details.Where(d => d.LockQuantity > 0))
                {
                    var alreadyAssigned = outStockLockInfos
                        .Where(x => x.OrderDetailId == detail.Id && x.StockId == stock.Id)
                        .Sum(x => x.AssignQuantity);
 
                    var canAssign = Math.Min(detail.LockQuantity - alreadyAssigned, availableAssign);
 
                    if (canAssign > 0)
                    {
                        // 为这个分配确定条码
                        var (barcode, barcodeQuantity) = GetBarcodeForAllocation(barcodeAllocation, canAssign);
 
                        var lockInfo = _outStockLockInfoService.GetOutStockLockInfo(
                            outboundOrder, detail, stock, canAssign, barcode,null);
                        outStockLockInfos.Add(lockInfo);
 
                        availableAssign -= canAssign;
 
                        // 更新条码分配记录
                        UpdateBarcodeAllocation(barcodeAllocation, barcode, barcodeQuantity);
                    }
 
                    if (availableAssign <= 0) break;
                }
            }
        }
 
        /// <summary>
        /// 按先进先出原则分配条码
        /// </summary>
        private Dictionary<string, decimal> AllocateBarcodes(List<Dt_StockInfoDetail> stockDetails, decimal totalQuantity)
        {
            var allocation = new Dictionary<string, decimal>();
            decimal remainingQuantity = totalQuantity;
 
            foreach (var detail in stockDetails.OrderBy(x => x.ProductionDate))
            {
                if (remainingQuantity <= 0) break;
 
                decimal available = detail.StockQuantity - detail.OutboundQuantity;
                decimal allocate = Math.Min(available, remainingQuantity);
 
                allocation[detail.Barcode] = allocate;
                remainingQuantity -= allocate;
            }
 
            return allocation;
        }
 
        /// <summary>
        /// 为分配获取合适的条码
        /// </summary>
        private (string barcode, decimal quantity) GetBarcodeForAllocation(Dictionary<string, decimal> barcodeAllocation, decimal requiredQuantity)
        {
            foreach (var (barcode, quantity) in barcodeAllocation)
            {
                if (quantity >= requiredQuantity)
                {
                    return (barcode, requiredQuantity);
                }
            }
 
            // 如果单个条码数量不足,使用第一个条码
            var first = barcodeAllocation.First();
            return (first.Key, Math.Min(first.Value, requiredQuantity));
        }
 
        /// <summary>
        /// 更新条码分配记录
        /// </summary>
        private void UpdateBarcodeAllocation(Dictionary<string, decimal> barcodeAllocation, string barcode, decimal usedQuantity)
        {
            if (barcodeAllocation.ContainsKey(barcode))
            {
                barcodeAllocation[barcode] -= usedQuantity;
                if (barcodeAllocation[barcode] <= 0)
                {
                    barcodeAllocation.Remove(barcode);
                }
            }
        }
        /// <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);
            }
        }
 
    }
}