wanshenmean
2026-03-30 1a8dc6279c478a1b8e4cea78fa91ee856a720e3a
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
using SqlSugar;
using WIDESEA_Common.StockEnum;
using WIDESEA_Core;
using WIDESEA_DTO.MES;
using WIDESEA_DTO.Stock;
using WIDESEA_IBasicService;
using WIDESEA_IStockService;
using WIDESEA_Model.Models;
 
namespace WIDESEA_StockService
{
    /// <summary>
    /// 库存服务聚合实现类
    /// </summary>
    public class StockService : IStockService
    {
        /// <summary>
        /// 库存明细服务
        /// </summary>
        public IStockInfoDetailService StockInfoDetailService { get; }
 
        /// <summary>
        /// 库存信息服务
        /// </summary>
        public IStockInfoService StockInfoService { get; }
 
        /// <summary>
        /// 库存明细历史服务
        /// </summary>
        public IStockInfoDetail_HtyService StockInfoDetail_HtyService { get; }
 
        /// <summary>
        /// 库存历史服务
        /// </summary>
        public IStockInfo_HtyService StockInfo_HtyService { get; }
 
        /// <summary>
        /// Mes接口服务
        /// </summary>
        public IMesService _mesService { get; }
 
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="stockInfoDetailService">库存明细服务</param>
        /// <param name="stockInfoService">库存信息服务</param>
        /// <param name="stockInfoDetail_HtyService">库存明细历史服务</param>
        /// <param name="stockInfo_HtyService">库存历史服务</param>
        public StockService(
            IStockInfoDetailService stockInfoDetailService,
            IStockInfoService stockInfoService,
            IStockInfoDetail_HtyService stockInfoDetail_HtyService,
            IStockInfo_HtyService stockInfo_HtyService,
            IMesService mesService)
        {
            StockInfoDetailService = stockInfoDetailService;
            StockInfoService = stockInfoService;
            StockInfoDetail_HtyService = stockInfoDetail_HtyService;
            StockInfo_HtyService = stockInfo_HtyService;
            _mesService = mesService;
        }
 
        /// <summary>
        /// 在事务中执行操作
        /// </summary>
        private async Task<WebResponseContent> ExecuteWithinTransactionAsync(Func<Task<WebResponseContent>> operation)
        {
            var db = StockInfoService.Repository.Db as SqlSugarClient;
            if (db == null)
            {
                return WebResponseContent.Instance.Error("Database context does not support transactions");
            }
 
            var ownsTransaction = db.Ado.Transaction == null;
            try
            {
                if (ownsTransaction)
                {
                    db.BeginTran();
                }
 
                var result = await operation();
                if (result?.Status == true)
                {
                    if (ownsTransaction)
                    {
                        db.CommitTran();
                    }
                    return result;
                }
 
                if (ownsTransaction)
                {
                    db.RollbackTran();
                }
                return result ?? WebResponseContent.Instance.Error("Transaction failed");
            }
            catch
            {
                if (ownsTransaction)
                {
                    db.RollbackTran();
                }
                throw;
            }
        }
 
        /// <summary>
        /// 组盘
        /// </summary>
        public async Task<WebResponseContent> GroupPalletAsync(StockDTO stock)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                var now = DateTime.Now;
                var details = stock.Details.Select(item => new Dt_StockInfoDetail
                {
                    MaterielCode = "电芯",
                    MaterielName = "电芯",
                    StockQuantity = item.Quantity,
                    Unit = "PCS",
                    Creater = "system",
                    OrderNo = "111",
                    ProductionDate = now.ToString(),
                    EffectiveDate = now.AddYears(1).ToString(),
                    SerialNumber = item.CellBarcode,
                    InboundOrderRowNo = item.Channel,
                    Status = StockStatusEmun.组盘暂存.GetHashCode(),
                }).ToList();
 
                var bindRequest = new BindContainerRequest
                {
                    ContainerCode = stock?.TargetPalletNo,
                    EquipmentCode = "STK-GROUP-001",
                    ResourceCode = "STK-GROUP-001",
                    LocalTime = now,
                    OperationType = 0, // 0代表组盘
                    ContainerSfcList = details.Select(d => new ContainerSfcItem
                    {
                        Sfc = d.SerialNumber,
                        Location = d.InboundOrderRowNo.ToString(),
                    }).ToList()
                };
 
                return await ExecuteWithinTransactionAsync(async () =>
                {
                    var existingStock = StockInfoService.Repository.QueryFirst(s => s.PalletCode == stock.TargetPalletNo);
                    var result = false;
                    if (existingStock != null)
                    {
                        details.ForEach(d => d.StockId = existingStock.Id);
                        result = await StockInfoDetailService.Repository.AddDataAsync(details) > 0;
                        return result ? content.OK("组盘成功") : content.Error("组盘失败");
                    }
 
                    var entity = new Dt_StockInfo
                    {
                        PalletCode = stock.TargetPalletNo,
                        //WarehouseId = stock.WarehouseId > 0 ? stock.WarehouseId : 1,
                        WarehouseId = 1,
                        StockStatus = StockStatusEmun.组盘暂存.GetHashCode(),
                        Creater = "system",
                        Details = details
                    };
                    result = StockInfoService.Repository.AddData(entity, x => x.Details);
                    if (!result) return content.Error("组盘失败");
 
                    var mesResult = _mesService.BindContainer(bindRequest);
                    if (mesResult == null || mesResult.Data == null || !mesResult.Data.IsSuccess)
                    {
                        return content.Error($"组盘成功,但MES绑定失败: {mesResult?.Data?.Msg ?? mesResult?.ErrorMessage ?? "未知错误"}");
                    }
                    return content.OK("组盘成功");
                });
            }
            catch (Exception ex)
            {
                return content.Error($"组盘失败: {ex.Message}");
            }
        }
 
        /// <summary>
        /// 换盘
        /// </summary>
        public async Task<WebResponseContent> ChangePalletAsync(StockDTO stock)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                if (stock == null ||
                    string.IsNullOrWhiteSpace(stock.TargetPalletNo) ||
                    string.IsNullOrWhiteSpace(stock.SourcePalletNo) ||
                    string.Equals(stock.SourcePalletNo, stock.TargetPalletNo, StringComparison.OrdinalIgnoreCase))
                {
                    return content.Error("源托盘号与目标托盘号相同");
                }
 
                return await ExecuteWithinTransactionAsync(async () =>
                {
                    var sourceStock = await StockInfoService.Repository.QueryDataNavFirstAsync(s => s.PalletCode == stock.SourcePalletNo);
                    if (sourceStock == null) return content.Error("源托盘不存在");
 
                    var targetStock = StockInfoService.Repository.QueryFirst(s => s.PalletCode == stock.TargetPalletNo);
                    if (targetStock == null)
                    {
                        var newStock = new Dt_StockInfo
                        {
                            PalletCode = stock.TargetPalletNo,
                            WarehouseId = sourceStock.WarehouseId,
                            StockStatus = StockStatusEmun.组盘暂存.GetHashCode(),
                            Creater = "system",
                        };
 
                        var newId = StockInfoService.Repository.AddData(newStock);
                        if (newId <= 0) return content.Error("换盘失败");
 
                        targetStock = newStock;
                        targetStock.Id = newId;
                    }
 
                    var serialNumbers = stock.Details.Select(d => d.Channel).Distinct().ToList();
                    if (!serialNumbers.Any()) return content.Error("未找到有效的序列号");
 
                    var detailEntities = StockInfoDetailService.Repository.QueryData(
                        d => d.StockId == sourceStock.Id && serialNumbers.Contains(d.InboundOrderRowNo));
                    if (!detailEntities.Any()) return content.Error("未找到有效的库存明细");
 
                    if (await StockInfoDetail_HtyService.Repository.AddDataAsync(CreateDetailHistory(detailEntities, "换盘")) <= 0)
                        return content.Error("换盘历史记录保存失败");
 
                    if (await StockInfo_HtyService.Repository.AddDataAsync(CreateStockHistory(new[] { sourceStock, targetStock }, "换盘")) <= 0)
                        return content.Error("换盘历史记录保存失败");
 
                    detailEntities.ForEach(d => d.StockId = targetStock.Id);
 
                    // 调用MES解绑源托盘电芯
                    var unbindRequest = new UnBindContainerRequest
                    {
                        EquipmentCode = "STK-GROUP-001",
                        ResourceCode = "STK-GROUP-001",
                        LocalTime = DateTime.Now,
                        ContainCode = stock.SourcePalletNo,
                        SfcList = detailEntities.Select(d => d.SerialNumber).ToList()
                    };
                    var unbindResult = _mesService.UnBindContainer(unbindRequest);
                    if (unbindResult == null || unbindResult.Data == null || !unbindResult.Data.IsSuccess)
                    {
                        return content.Error($"换盘成功,但MES解绑失败: {unbindResult?.Data?.Msg ?? unbindResult?.ErrorMessage ?? "未知错误"}");
                    }
 
                    var result = await StockInfoDetailService.Repository.UpdateDataAsync(detailEntities);
                    if (!result) return content.Error("换盘失败");
 
                    // 调用MES绑定目标托盘电芯
                    var bindRequest = new BindContainerRequest
                    {
                        ContainerCode = stock.TargetPalletNo,
                        EquipmentCode = "STK-GROUP-001",
                        ResourceCode = "STK-GROUP-001",
                        LocalTime = DateTime.Now,
                        OperationType = 0,
                        ContainerSfcList = detailEntities.Select(d => new ContainerSfcItem
                        {
                            Sfc = d.SerialNumber,
                            Location = d.InboundOrderRowNo.ToString()
                        }).ToList()
                    };
                    var bindResult = _mesService.BindContainer(bindRequest);
                    if (bindResult == null || bindResult.Data == null || !bindResult.Data.IsSuccess)
                    {
                        return content.Error($"换盘成功,但MES绑定失败: {bindResult?.Data?.Msg ?? bindResult?.ErrorMessage ?? "未知错误"}");
                    }
 
                    return content.OK("换盘成功");
                });
            }
            catch (Exception ex)
            {
                return content.Error($"换盘失败: {ex.Message}");
            }
        }
 
        /// <summary>
        /// 拆盘
        /// </summary>
        public async Task<WebResponseContent> SplitPalletAsync(StockDTO stock)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                if (stock == null || string.IsNullOrWhiteSpace(stock.SourcePalletNo))
                    return content.Error("源托盘号不能为空");
 
                return await ExecuteWithinTransactionAsync(async () =>
                {
                    var sourceStock = StockInfoService.Repository.QueryFirst(s => s.PalletCode == stock.SourcePalletNo);
                    if (sourceStock == null) return content.Error("源托盘不存在");
 
                    var serialNumbers = stock.Details.Select(d => d.CellBarcode).Distinct().ToList();
                    if (!serialNumbers.Any())
                    {
                        serialNumbers = sourceStock.Details
                                                    .Where(x => stock.Details.Any(d => d.Channel == x.InboundOrderRowNo))
                                                    .Select(x => x.SerialNumber)
                                                    .ToList();
                    }
 
                    var detailEntities = StockInfoDetailService.Repository.QueryData(
                        d => d.StockId == sourceStock.Id && serialNumbers.Contains(d.SerialNumber));
                    if (!detailEntities.Any()) return content.Error("未找到有效的库存明细");
 
                    if (await StockInfoDetail_HtyService.Repository.AddDataAsync(CreateDetailHistory(detailEntities, "拆盘")) <= 0)
                        return content.Error("拆盘历史记录保存失败");
 
                    if (await StockInfo_HtyService.Repository.AddDataAsync(CreateStockHistory(new[] { sourceStock }, "拆盘")) <= 0)
                        return content.Error("拆盘历史记录保存失败");
 
                    var result = await StockInfoDetailService.Repository.DeleteDataAsync(detailEntities);
                    if (!result) return content.Error("拆盘失败");
                    return content.OK("拆盘成功");
                });
            }
            catch (Exception ex)
            {
                return content.Error($"拆盘失败: {ex.Message}");
            }
        }
 
        /// <summary>
        /// 堆垛机换盘后更新库存信息(清空库位信息)
        /// </summary>
        /// <param name="stock"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> UpdateStockInfoAsync(StockInfoDTO stock)
        {
            WebResponseContent content = new WebResponseContent();
            if (string.IsNullOrWhiteSpace(stock.PalletCode)) return content.Error("托盘号不能为空");
 
            var existingStock = StockInfoService.Repository.QueryFirst(s => s.PalletCode == stock.PalletCode);
            if (existingStock == null) return content.Error("托盘信息不存在");
 
            existingStock.LocationCode = "";
            existingStock.LocationId = 0;
 
            var result = await StockInfoService.Repository.UpdateDataAsync(existingStock);
            if (!result) return content.Error("更新库存信息失败");
            return content.OK("更新库存信息成功");
        }
 
        private static List<Dt_StockInfoDetail_Hty> CreateDetailHistory(IEnumerable<Dt_StockInfoDetail> details, string operateType)
        {
            var now = DateTime.Now;
            return details.Select(d => new Dt_StockInfoDetail_Hty
            {
                SourceId = d.Id,
                OperateType = operateType,
                InsertTime = now,
                StockId = d.StockId,
                MaterielCode = d.MaterielCode,
                MaterielName = d.MaterielName,
                OrderNo = d.OrderNo,
                BatchNo = d.BatchNo,
                ProductionDate = d.ProductionDate,
                EffectiveDate = d.EffectiveDate,
                SerialNumber = d.SerialNumber,
                StockQuantity = d.StockQuantity,
                OutboundQuantity = d.OutboundQuantity,
                Status = d.Status,
                Unit = d.Unit,
                InboundOrderRowNo = d.InboundOrderRowNo,
                Remark = d.Remark,
                Creater = d.Creater,
                CreateDate = d.CreateDate,
                Modifier = d.Modifier,
                ModifyDate = d.ModifyDate
            }).ToList();
        }
 
        private static List<Dt_StockInfo_Hty> CreateStockHistory(IEnumerable<Dt_StockInfo> stocks, string operateType)
        {
            var now = DateTime.Now;
            return stocks.Select(s => new Dt_StockInfo_Hty
            {
                SourceId = s.Id,
                OperateType = operateType,
                InsertTime = now,
                PalletCode = s.PalletCode,
                PalletType = s.PalletType,
                LocationCode = s.LocationCode,
                WarehouseId = s.WarehouseId,
                StockStatus = s.StockStatus,
                Remark = s.Remark,
                Creater = s.Creater,
                CreateDate = s.CreateDate,
                Modifier = s.Modifier,
                ModifyDate = s.ModifyDate,
                LocationId = s.LocationId,
                OutboundDate = s.OutboundDate
            }).ToList();
        }
    }
}