647556386
2026-01-12 2654a849bcbbd03df38592b29c22df56d750fb27
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Core.BaseServices;
using WIDESEA_Core;
using WIDESEA_IInboundService;
using WIDESEA_Model.Models;
using WIDESEA_Common.OrderEnum;
using WIDESEA_Core.Helper;
using Microsoft.AspNetCore.Mvc.RazorPages;
using WIDESEA_Core.Enums;
using SqlSugar;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Common.StockEnum;
using Microsoft.AspNetCore.Mvc;
using WIDESEA_DTO.Inbound;
using WIDESEA_DTO.ReturnMES;
using MailKit.Search;
using static System.Collections.Specialized.BitVector32;
using WIDESEA_Common.CommonEnum;
using WIDESEA_Common.TaskEnum;
using WIDESEA_IBasicService;
using static HslCommunication.Profinet.Knx.KnxCode;
using System.Collections;
using WIDESEA_Common.AllocateEnum;
using WIDESEA_Model.Models.Basic;
using WIDESEA_IOutboundService;
using WIDESEA_DTO.CalcOut;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
 
namespace WIDESEA_InboundService
{
    public class TakeStockOrderService : ServiceBase<Dt_TakeStockOrder, IRepository<Dt_TakeStockOrder>>, ITakeStockOrderService
    {
        public IRepository<Dt_TakeStockOrder> Repository => BaseDal;
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        private readonly IRepository<Dt_TakeStockOrder> _takeStockOrder;
        private readonly IRepository<Dt_StockInfo> _stockInfoRepository;
        private readonly IRepository<Dt_TakeStockOrderDetail> _takeStockOrderDetail;
        private readonly IRepository<Dt_Task> _taskRepository;
        private readonly ILocationInfoService _locationInfoService;
        private readonly IRepository<Dt_InboundOrder> _inboundOrderRepository;
        private readonly IRepository<Dt_OutboundOrder> _outboundOrderRepository;
        private readonly IRepository<Dt_InboundOrderDetail> _inboundOrderDetailRepository;
        private readonly IRepository<Dt_OutboundOrderDetail> _outboundOrderDetailRepository;
        private readonly IOutboundPickingService _outboundPickingService;
        private readonly IRepository<Dt_StockInfoDetail> _stockInfoDetailRepository;
        private readonly IOutboundService _outboundService;
        private readonly IFeedbackMesService _feedbackMesService;
        public TakeStockOrderService(IRepository<Dt_TakeStockOrder> BaseDal, IUnitOfWorkManage unitOfWorkManage,IRepository<Dt_TakeStockOrder> takeStockOrder,IRepository<Dt_StockInfo> stockInfoRepository,IRepository<Dt_TakeStockOrderDetail> takeStockOrderDetail,IRepository<Dt_Task> taskRepository,ILocationInfoService locationInfoService, IRepository<Dt_InboundOrder> inboundOrderRepository,IRepository<Dt_OutboundOrder> outboundOrderRepository,IRepository<Dt_InboundOrderDetail> inboundOrderDetailRepository, IRepository<Dt_OutboundOrderDetail> outboundOrderDetailRepository, IOutboundPickingService outboundPickingService, IRepository<Dt_StockInfoDetail> stockInfoDetailRepository, IOutboundService outboundService,IFeedbackMesService feedbackMesService) : base(BaseDal)
        {
            _unitOfWorkManage = unitOfWorkManage;
            _takeStockOrder = takeStockOrder;
            _stockInfoRepository = stockInfoRepository;
            _takeStockOrderDetail = takeStockOrderDetail;
            _taskRepository = taskRepository;
            _locationInfoService = locationInfoService;
            _inboundOrderRepository = inboundOrderRepository;
            _outboundOrderRepository = outboundOrderRepository;
            _inboundOrderDetailRepository = inboundOrderDetailRepository;
            _outboundOrderDetailRepository = outboundOrderDetailRepository;
            _outboundPickingService = outboundPickingService;
            _stockInfoDetailRepository = stockInfoDetailRepository;
            _outboundService = outboundService;
            _feedbackMesService = feedbackMesService;
        }
 
        public WebResponseContent ValidateBoxNo(string orderNo, string boxNo)
        {
            try
            {
                Dt_StockInfo stockInfo = _stockInfoRepository.QueryFirst(x => x.PalletCode == boxNo);
                if (stockInfo == null) {
                    return WebResponseContent.Instance.Error("未找到该托盘库存");
                }
                if(stockInfo.StockStatus != StockStatusEmun.盘点出库完成.ObjToInt() && stockInfo.StockStatus != StockStatusEmun.盘点库存完成.ObjToInt())
                {
                    return WebResponseContent.Instance.Error("该托盘处于非盘点状态,请检查盘点任务");
                }
                Dt_TakeStockOrder takeStockOrder = _takeStockOrder.QueryFirst(x=>x.AllPalletCode.Contains(boxNo)&& x.TakeStockStatus == TakeStockStatusEnum.盘点中.ObjToInt());
                if (takeStockOrder == null)
                {
                    return WebResponseContent.Instance.Error("该托盘未找到该盘点单据");
                }
                if (takeStockOrder.AllPalletCode.Contains(","))
                {
                    var remarkValues = takeStockOrder.AllPalletCode
                        .Split(',')
                        .Select(s => s.Trim()) 
                        .Where(s => !string.IsNullOrWhiteSpace(s)) 
                        .ToList();
                    if (remarkValues.Count == 0)
                    {
                        return WebResponseContent.Instance.Error("盘点单箱号仅包含逗号,无有效箱号数据");
                    }
 
                    bool isMatch = remarkValues.Any(val => val.Equals(boxNo, StringComparison.OrdinalIgnoreCase));
                    if (!isMatch)
                    {
                        return WebResponseContent.Instance.Error($"箱号【{boxNo}】未在盘点单箱号【{takeStockOrder.AllPalletCode}】中找到匹配项");
                    }
                }
                var resultData = new { takeStockOrder = takeStockOrder.OrderNo };
                return WebResponseContent.Instance.OK(data:resultData);
            }
            catch(Exception ex)
            {
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
 
        public WebResponseContent ValidateBarcode(string boxNo, string barcode)
        {
            try
            {
                Dt_StockInfo stockInfo = _stockInfoRepository.Db.Queryable<Dt_StockInfo>().Where(x => x.PalletCode == boxNo).Includes(x => x.Details).First();
                if(stockInfo == null)
                {
                    return WebResponseContent.Instance.Error("未找到该料箱库存信息");
                }
                if(stockInfo.Details == null)
                {
                    return WebResponseContent.Instance.Error("未找到该料箱库存");
                }
                List<string> barcodes = stockInfo.Details.Select(x => x.Barcode).ToList();
 
                bool isMatch = barcodes.Any(val => val.Equals(barcode, StringComparison.OrdinalIgnoreCase));
                if (!isMatch)
                {
                    return WebResponseContent.Instance.Error($"条码【{barcode}】未在【{boxNo}】料箱条码中找到匹配项");
                }
                var stockDetail = stockInfo.Details.FirstOrDefault(x=>x.Barcode == barcode);
 
                var resultData = new { stockQuantity = stockDetail.StockQuantity };
 
                return WebResponseContent.Instance.OK(data:resultData);
            }
            catch(Exception ex)
            {
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
 
        public WebResponseContent CompleteStockTake([FromBody] CompleteStockTakeDTO completeStockTakeDTO)
        {
            try
            {
                Dt_TakeStockOrder takeStockOrder = _takeStockOrder.QueryFirst(x=>x.OrderNo == completeStockTakeDTO.orderNo);
                if (takeStockOrder == null)
                {
                    return WebResponseContent.Instance.Error("未找到该盘点单据");
                }
                Dt_StockInfo stockInfo = _stockInfoRepository.Db.Queryable<Dt_StockInfo>().Where(x => x.PalletCode == completeStockTakeDTO.boxNo).Includes(x=>x.Details).First();
                if(stockInfo == null)
                {
                    return WebResponseContent.Instance.Error("未找到该托盘库存");
                }
                Dt_StockInfoDetail stockInfoDetail = stockInfo.Details.FirstOrDefault(x => x.Barcode == completeStockTakeDTO.barcode);
                if(stockInfoDetail == null)
                {
                    return WebResponseContent.Instance.Error("条码库存数据未找到匹配数据");
                }
                Dt_TakeStockOrderDetail takeStockOrderDetail = new Dt_TakeStockOrderDetail()
                {
                    TakeStockId = takeStockOrder.Id,
                    MaterielCode = stockInfoDetail.MaterielCode,
                    MaterielName = stockInfoDetail.MaterielName ?? "",
                    BatchNo = stockInfoDetail.BatchNo,
                    TakePalletCode = completeStockTakeDTO.boxNo,
                    TakeDetalStatus = TakeStockDetailStatusEnum.未进行平账处理.ObjToInt(),
                    Unit = stockInfoDetail.Unit,
                    SysQty = completeStockTakeDTO.stockQuantity,
                    Qty = completeStockTakeDTO.actualQuantity,
                    Remark = "盘亏",
                    barcode = completeStockTakeDTO.barcode,
                    WarehouseCode = stockInfoDetail.WarehouseCode ?? "",
                    FactoryArea = stockInfoDetail.FactoryArea,
                    SupplyCode = stockInfoDetail.SupplyCode ?? "",
                    TakeStockNo = takeStockOrder.OrderNo,
                    DifferenceQty = completeStockTakeDTO.actualQuantity - completeStockTakeDTO.stockQuantity
 
                };
                stockInfoDetail.StockId = 0;
                stockInfoDetail.OrderNo = takeStockOrder.OrderNo;
                stockInfo.StockStatus = StockStatusEmun.盘点库存完成.ObjToInt();
                _unitOfWorkManage.BeginTran();
                _takeStockOrderDetail.AddData(takeStockOrderDetail);
                _stockInfoDetailRepository.UpdateData(stockInfoDetail);
                _stockInfoRepository.UpdateData(stockInfo);
                _unitOfWorkManage.CommitTran();
                return WebResponseContent.Instance.OK("盘点完成,请取走该异常料箱进行平账处理!");
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
 
        public WebResponseContent ReturnBox(string orderNo, string boxNo, string sourceAddress)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                Dt_TakeStockOrder takeStockOrder = _takeStockOrder.QueryFirst(x=>x.OrderNo == orderNo);
                if(takeStockOrder == null)
                {
                    return content.Error("未找到该盘点单据");
                }
                var stock = _stockInfoRepository.QueryFirst(x => x.PalletCode == boxNo);
 
                if (stock == null)
                {
                    return content.Error($"未找到托盘{boxNo}库存信息不允许回库");
                }
 
                var task = _taskRepository.QueryFirst(x => x.PalletCode == boxNo);
                if (task != null)
                {
                    return content.Error($"托盘{boxNo}存在任务,回库失败!");
                }
                if(stock.StockStatus != StockStatusEmun.盘点出库完成.ObjToInt() && stock.StockStatus != StockStatusEmun.盘点库存完成.ObjToInt())
                {
                    return content.Error("该托盘状态不对,不允许盘点入库");
                }
                var palletCodes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                if (!string.IsNullOrEmpty(takeStockOrder.AllPalletCode))
                {
                    palletCodes = takeStockOrder.AllPalletCode
                        .Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(p => p.Trim())
                        .ToHashSet(StringComparer.OrdinalIgnoreCase);
                }
                int overPalletCodeCount = _stockInfoRepository.QueryData(x => palletCodes.Contains(x.PalletCode) && (x.StockStatus == StockStatusEmun.出库完成.ObjToInt() || x.StockStatus == StockStatusEmun.入库完成.ObjToInt() || x.StockStatus == StockStatusEmun.出库锁定.ObjToInt()|| x.StockStatus == StockStatusEmun.入库确认.ObjToInt())).Count();
                bool hasRelatedTasks = palletCodes.Count == overPalletCodeCount + 1;
 
                if (hasRelatedTasks)
                {
                    takeStockOrder.TakeStockStatus = (int)TakeStockStatusEnum.盘点完成;
                }
                stock.StockStatus = StockStatusEmun.入库确认.ObjToInt();
                // 分配新货位
                var newLocation = _locationInfoService.AssignLocation(stock.LocationType);
 
                var newTask = new Dt_Task()
                {
                    CurrentAddress = takeStockOrder.Remark,
                    Grade = 0,
                    PalletCode = boxNo,
                    NextAddress = "",
                    OrderNo = takeStockOrder.OrderNo,
                    Roadway = newLocation.RoadwayNo,
                    SourceAddress = sourceAddress,
                    TargetAddress = newLocation.LocationCode,
                    TaskStatus = (int)TaskStatusEnum.New,
                    TaskType = TaskTypeEnum.InInventory.ObjToInt(),
                    PalletType = stock.PalletType,
                    WarehouseId = stock.WarehouseId
                };
                _unitOfWorkManage.BeginTran();
                _stockInfoRepository.UpdateData(stock);
                _takeStockOrder.UpdateData(takeStockOrder);
                _taskRepository.AddData(newTask);
                _unitOfWorkManage.CommitTran();
 
                //var moveResult = await _eSSApiService.MoveContainerAsync(new MoveContainerRequest
                //{
                //    slotCode = movestations[station],
                //    containerCode = palletCode
                //});
                return content.OK();
 
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                return content.Error(ex.Message);
            }
        }
 
        public WebResponseContent ManualReconciliation(int id)
        {
            try
            {
                Dt_TakeStockOrderDetail takeStockOrderDetail = _takeStockOrderDetail.QueryFirst(x=>x.Id == id);
                if(takeStockOrderDetail == null)
                {
                    return WebResponseContent.Instance.Error("未找到该盘点差异记录");
                }
                else
                {
                    if(takeStockOrderDetail.TakeDetalStatus != TakeStockDetailStatusEnum.未进行平账处理.ObjToInt())
                    {
                        return WebResponseContent.Instance.Error("该记录已经进行了平账操作");
                    }
                    takeStockOrderDetail.DifferenceQty = 0;
                    takeStockOrderDetail.TakeDetalStatus = TakeStockDetailStatusEnum.已进行平账处理.ObjToInt();
                }
                _takeStockOrderDetail.UpdateData(takeStockOrderDetail);
                return WebResponseContent.Instance.OK();
            }
            catch(Exception ex)
            {
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
 
        public WebResponseContent SelectOrder(string remark, int id)
        {
            try
            {
                Dt_TakeStockOrderDetail takeStockOrderDetail = _takeStockOrderDetail.QueryFirst(x => x.Id == id);
                if (takeStockOrderDetail == null)
                {
                    return WebResponseContent.Instance.Error("未找到该盘点差异记录");
                }
                else
                {
                    //查杂收单
                    if (takeStockOrderDetail.Remark == "盘盈")
                    {
                        List<Dt_InboundOrderDetail> inboundOrderDetails = new List<Dt_InboundOrderDetail>();
                        List<Dt_InboundOrder> inboundOrders = _inboundOrderRepository.Db.Queryable<Dt_InboundOrder>().Where(x => x.BusinessType == "12" && x.OrderStatus != InOrderStatusEnum.入库完成.ObjToInt()).Includes(x => x.Details).ToList();
                        foreach (var inboundOrder in inboundOrders)
                        {
 
                            var matchedDetails = inboundOrder.Details
 
                                .Where(detail => !string.IsNullOrEmpty(detail.MaterielCode)
                                              && detail.MaterielCode == takeStockOrderDetail.MaterielCode && detail.OrderDetailStatus != OrderDetailStatusEnum.Over.ObjToInt())
 
                                .WhereIF(!string.IsNullOrEmpty(takeStockOrderDetail.FactoryArea),
                                         detail => !string.IsNullOrEmpty(inboundOrder.FactoryArea)
                                              && inboundOrder.FactoryArea == takeStockOrderDetail.FactoryArea)
                                .WhereIF(!string.IsNullOrEmpty(takeStockOrderDetail.WarehouseCode),
                                         detail => !string.IsNullOrEmpty(detail.WarehouseCode)
                                         && detail.WarehouseCode == takeStockOrderDetail.WarehouseCode)
                                .WhereIF(!string.IsNullOrEmpty(takeStockOrderDetail.BatchNo),
                                         detail => !string.IsNullOrEmpty(detail.BatchNo)
                                         && detail.BatchNo == takeStockOrderDetail.BatchNo)
 
                                .ToList();
 
                            // 将匹配的明细添加到总列表
                            if (matchedDetails.Any())
                            {
                                inboundOrderDetails.AddRange(matchedDetails);
                            }
                        }
                        return WebResponseContent.Instance.OK("成功",data: inboundOrderDetails);
                    }
                    else
                    {
                        List<Dt_OutboundOrderDetail> outboundOrderDetails = new List<Dt_OutboundOrderDetail>();
                        List<Dt_OutboundOrder> outboundOrders = _outboundOrderRepository.Db.Queryable<Dt_OutboundOrder>().Where(x => x.BusinessType == "23" && x.OrderStatus != OutOrderStatusEnum.出库完成.ObjToInt()).Includes(x => x.Details).ToList();
                        foreach (var outboundOrder in outboundOrders)
                        {
                            var matchedDetails = outboundOrder.Details
                                .Where(detail => !string.IsNullOrWhiteSpace(detail.MaterielCode)
                                              && detail.MaterielCode == takeStockOrderDetail.MaterielCode && detail.OrderQuantity-detail.MoveQty-detail.OverOutQuantity>0)
                                .WhereIF(!string.IsNullOrWhiteSpace(takeStockOrderDetail.FactoryArea),
                                         detail => !string.IsNullOrWhiteSpace(outboundOrder.FactoryArea)
                                              && outboundOrder.FactoryArea == takeStockOrderDetail.FactoryArea)
                                .WhereIF(!string.IsNullOrWhiteSpace(takeStockOrderDetail.WarehouseCode),
                                         detail => !string.IsNullOrWhiteSpace(detail.WarehouseCode)
                                              && detail.WarehouseCode == takeStockOrderDetail.WarehouseCode)
                                .Where(detail => string.IsNullOrWhiteSpace(detail.BatchNo)||
                                         detail.BatchNo == takeStockOrderDetail.BatchNo)
 
                                .Where(detail => string.IsNullOrWhiteSpace(detail.SupplyCode) ||
                                         detail.SupplyCode == takeStockOrderDetail.SupplyCode)
                                .ToList();
 
                            if (matchedDetails.Any())
                            {
                                outboundOrderDetails.AddRange(matchedDetails);
                            }
                        }
                        return WebResponseContent.Instance.OK("成功", data: outboundOrderDetails);
                    }
                }
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
 
        public WebResponseContent DocumentReconciliation(string barcode)
        {
            WebResponseContent webResponseContent = new WebResponseContent();
            try
            {
                Dt_TakeStockOrderDetail takeStockOrderDetail = _takeStockOrderDetail.QueryFirst(x => x.barcode == barcode);
                if (takeStockOrderDetail == null)
                {
                    return WebResponseContent.Instance.Error("未找到该盘点差异数据");
                }
                //if(takeStockOrderDetail.Remark == "盘盈")
                //{
                //    Dt_InboundOrderDetail inboundOrderDetail = _inboundOrderDetailRepository.QueryFirst(x => x.Id == orderId);
                //    if(inboundOrderDetail == null)
                //    {
                //        return WebResponseContent.Instance.Error("未找到选择的杂收平账单据");
                //    }
                //    Dt_InboundOrder inboundOrder = _inboundOrderRepository.Db.Queryable<Dt_InboundOrder>().Where(x=>x.Id == inboundOrderDetail.OrderId).Includes(x=>x.Details).First();
                //    Dt_StockInfo  stockInfo = _stockInfoRepository.Db.Queryable<Dt_StockInfo>().Where(x=>x.PalletCode == takeStockOrderDetail.TakePalletCode && x.StockStatus == StockStatusEmun.盘点库存完成.ObjToInt()).Includes(x=>x.Details).First();
                //    if(stockInfo== null)
                //    {
                //        return WebResponseContent.Instance.Error($"盘点托盘{takeStockOrderDetail.TakePalletCode}的库存信息未找到,或托盘状态不正确");
                //    }
                //    var datevaliDate = _inboundOrderRepository.Db.Queryable<Dt_MaterialExpirationDate>().Where(x => x.MaterialCode.Contains(inboundOrderDetail.MaterielCode.Substring(0, 6))).First();
                //    var newStockDetail = new Dt_StockInfoDetail
                //    {
                //        StockId = stockInfo == null ? 0 : stockInfo.Id,
                //        Barcode = inboundOrderDetail.Barcode,
                //        MaterielCode = inboundOrderDetail.MaterielCode,
                //        MaterielName = inboundOrderDetail.MaterielName,
                //        BatchNo = inboundOrderDetail.BatchNo,
                //        Unit = inboundOrderDetail.Unit,
                //        InboundOrderRowNo = inboundOrderDetail.lineNo,
                //        SupplyCode = inboundOrderDetail.SupplyCode,
                //        WarehouseCode = inboundOrderDetail.WarehouseCode,
                //        StockQuantity = inboundOrderDetail.OrderQuantity,
                //        BarcodeQty = inboundOrderDetail.BarcodeQty,
                //        BarcodeUnit = inboundOrderDetail.BarcodeUnit,
                //        FactoryArea = inboundOrder.FactoryArea,
                //        Status = 0,
                //        OrderNo = inboundOrder.InboundOrderNo,
                //        BusinessType = inboundOrder.BusinessType,
                //        ValidDate = inboundOrder.BusinessType == BusinessTypeEnum.外部仓库调智仓.ToString() ? inboundOrderDetail.ValidDate : datevaliDate == null ? null : Convert.ToDateTime(DateTime.Now).AddDays(Convert.ToDouble(datevaliDate.ValidityDays)),
                //    };
                //    stockInfo.Details.Add(newStockDetail);
 
                //    inboundOrderDetail.ReceiptQuantity = inboundOrderDetail.OrderQuantity;
                //    inboundOrderDetail.OverInQuantity = inboundOrderDetail.OrderQuantity;
                //    inboundOrderDetail.OrderDetailStatus = OrderDetailStatusEnum.Over.ObjToInt();
                //    int overCount = 1;
                //    int moreOverCount = inboundOrder.Details.Count(x => x.OrderDetailStatus == OrderDetailStatusEnum.Over.ObjToInt());
                //    if (inboundOrder.Details.Count() == overCount + moreOverCount)
                //    {
                //        inboundOrder.OrderStatus = InOrderStatusEnum.入库完成.ObjToInt();
                //    }
                //    else
                //    {
                //        inboundOrder.OrderStatus = InOrderStatusEnum.入库中.ObjToInt();
                //    }
                //    takeStockOrderDetail.DifferenceQty -= inboundOrderDetail.OrderQuantity;
                //    if(takeStockOrderDetail.DifferenceQty > 0)
                //    {
                //        takeStockOrderDetail.TakeDetalStatus = TakeStockDetailStatusEnum.杂收杂发平账处理中.ObjToInt();
                //    }
                //    else if (takeStockOrderDetail.DifferenceQty == 0)
                //    {
                //        takeStockOrderDetail.TakeDetalStatus = TakeStockDetailStatusEnum.杂收杂发平账处理.ObjToInt();
                //    }
                //    else
                //    {
                //        return WebResponseContent.Instance.Error("该杂收单据明细条码数量大于待平账数量,请另选其他单据平账");
                //    }
 
                //    _unitOfWorkManage.BeginTran();
                //    _inboundOrderRepository.UpdateData(inboundOrder);
                //    _inboundOrderDetailRepository.UpdateData(inboundOrderDetail);
                //    _takeStockOrderDetail.UpdateData(takeStockOrderDetail);
                //    BaseDal.Db.Insertable(newStockDetail).ExecuteCommand();
                //    _unitOfWorkManage.CommitTran();
                //    List<string> barcodes = new List<string>();
                //    barcodes.Add(inboundOrderDetail.Barcode);
                //    _outboundPickingService.NoStockOutBatchInOrderFeedbackToMes(inboundOrder.Id, barcodes);
 
 
                //}
                //else
                //{
                Dt_OutboundOrderDetail outboundOrderDetail = _outboundOrderDetailRepository.QueryFirst(x => x.Remark == takeStockOrderDetail.TakeStockNo && (x.OrderQuantity-x.LockQuantity-x.MoveQty)>0);
                if (outboundOrderDetail == null)
                {
                    return WebResponseContent.Instance.Error("未找到选择的杂发平账单据");
                }
                if(outboundOrderDetail.MaterielCode != takeStockOrderDetail.MaterielCode)
                {
                    return WebResponseContent.Instance.Error("与杂发平账单据物料编码不匹配");
                }
                if (!string.IsNullOrWhiteSpace(outboundOrderDetail.BatchNo)&& outboundOrderDetail.BatchNo != takeStockOrderDetail.BatchNo)
                {
                    return WebResponseContent.Instance.Error("与杂发平账单据物料批次不匹配");
                }
                if (!string.IsNullOrWhiteSpace(outboundOrderDetail.SupplyCode) && outboundOrderDetail.SupplyCode != takeStockOrderDetail.SupplyCode)
                {
                    return WebResponseContent.Instance.Error("与杂发平账单据供应商不匹配");
                }
                Dt_OutboundOrder outboundOrder = _outboundOrderRepository.Db.Queryable<Dt_OutboundOrder>().Where(x => x.Id == outboundOrderDetail.OrderId).Includes(x => x.Details).First();
 
                takeStockOrderDetail.TakeDetalStatus = TakeStockDetailStatusEnum.杂收杂发平账处理.ObjToInt();
                OutboundCompleteRequestDTO request = new OutboundCompleteRequestDTO()
                {
                    OrderNo = outboundOrder.OrderNo,
                    PalletCode = takeStockOrderDetail.TakePalletCode,
                    Barcode = takeStockOrderDetail.barcode,
                    Operator = App.User.UserName
                };
                webResponseContent = CompleteOutboundWithBarcode(request,outboundOrderDetail.Id);
                takeStockOrderDetail.DifferenceQty = 0;
                _takeStockOrderDetail.UpdateData(takeStockOrderDetail);
                return WebResponseContent.Instance.OK(data: webResponseContent);
            }
            catch(Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                return WebResponseContent.Instance.Error(ex.Message);
 
            }
        }
        public WebResponseContent CompleteOutboundWithBarcode(OutboundCompleteRequestDTO request ,int orderDetailId)
        {
            WebResponseContent content = WebResponseContent.Instance;
 
            OutboundCompleteResponseDTO response = new();
            try
            {
                // 1. 根据托盘号查找库存信息
                Dt_StockInfo stockInfo = _stockInfoRepository.QueryFirst(x => x.PalletCode == request.PalletCode);
                if (stockInfo == null)
                {
                    response.Success = false;
                    response.Message = $"托盘号 {request.PalletCode} 对应的库存不存在";
                    return WebResponseContent.Instance.Error($"托盘号 {request.PalletCode} 对应的库存不存在");
                }
 
                // 2. 根据条码查找库存明细
                Dt_StockInfoDetail stockDetail = _stockInfoDetailRepository.QueryFirst(x => x.Barcode == request.Barcode);
                if (stockDetail == null)
                {
                    response.Success = false;
                    response.Message = $"条码 {request.Barcode} 对应的库存明细不存在";
                    return WebResponseContent.Instance.Error($"条码 {request.Barcode} 对应的库存明细不存在");
                }
 
 
 
                // 4. 查找出库单信息
                Dt_OutboundOrder outboundOrder = _outboundOrderRepository.QueryFirst(o => o.OrderNo == request.OrderNo);
                if (outboundOrder == null)
                {
                    response.Success = false;
                    response.Message = $"出库单 {request.OrderNo} 不存在";
                    return WebResponseContent.Instance.Error($"出库单 {request.OrderNo} 不存在");
                }
 
                Dt_OutboundOrderDetail outboundOrderDetail = _outboundOrderDetailRepository.QueryFirst(x => x.Id == orderDetailId);
                if (outboundOrderDetail == null)
                {
                    return WebResponseContent.Instance.Error("未找到出库单明细");
                }
                // 实际出库量
                decimal actualOutboundQuantity = outboundOrderDetail.OrderQuantity-outboundOrderDetail.LockQuantity-outboundOrderDetail.MoveQty;
 
 
                // 8. 判断是否需要拆包(当出库数量小于库存数量时需要拆包)
                bool isUnpacked = actualOutboundQuantity < stockDetail.StockQuantity;
                List<MaterialCodeReturnDTO> returnDTOs = new List<MaterialCodeReturnDTO>();
                string newBarcode = string.Empty;
                // 9. 开启事务
                _unitOfWorkManage.BeginTran();
                try
                {
                    decimal beforeQuantity = stockDetail.StockQuantity; // 原始库存量
 
                    Dt_AllocateMaterialInfo allocateMaterialInfo = new Dt_AllocateMaterialInfo();
 
                    // 根据是否拆包执行不同的操作
                    if (isUnpacked)
                    {
                        (string NewBarcode, List<MaterialCodeReturnDTO> MaterialCodeReturnDTOs) result = _outboundService.PerformUnpackOperation(stockDetail, stockInfo, actualOutboundQuantity, request, beforeQuantity, 0, outboundOrder.Id, outboundOrder.OrderNo);
 
                        returnDTOs = result.MaterialCodeReturnDTOs;
                        newBarcode = result.NewBarcode;
 
                        MaterialCodeReturnDTO returnDTO = returnDTOs.First(x => x.Barcode == newBarcode);
 
                        if (outboundOrder.OrderType != 0)
                        {
                            allocateMaterialInfo = new Dt_AllocateMaterialInfo()
                            {
                                Barcode = returnDTO.Barcode,
                                BatchNo = returnDTO.BatchNo,
                                FactoryArea = returnDTO.FactoryArea,
                                MaterialCode = returnDTO.MaterialCode,
                                MaterialName = returnDTO.MaterialName,
                                OrderId = outboundOrder.Id,
                                OrderNo = outboundOrder.OrderNo,
                                Quantity = returnDTO.Quantity,
                                SupplyCode = returnDTO.SuplierCode,
                                Unit = stockDetail.Unit
                            };
                        }
 
                    }
                    else
                    {
                       _outboundService.PerformFullOutboundOperation(stockDetail, stockInfo, actualOutboundQuantity, request, beforeQuantity, 0);
 
                        if (outboundOrder.OrderType != 0)
                        {
                            allocateMaterialInfo = new Dt_AllocateMaterialInfo()
                            {
                                Barcode = stockDetail.Barcode,
                                BatchNo = stockDetail.BatchNo,
                                FactoryArea = stockDetail.FactoryArea,
                                MaterialCode = stockDetail.MaterielCode,
                                MaterialName = stockDetail.MaterielName,
                                OrderId = outboundOrder.Id,
                                OrderNo = outboundOrder.OrderNo,
                                Quantity = stockDetail.StockQuantity,
                                SupplyCode = stockDetail.SupplyCode,
                                Unit = stockDetail.Unit
                            };
                        }
 
                    }
                    
                    List<Dt_OutboundOrderDetail> outboundOrderDetails = new List<Dt_OutboundOrderDetail>();
 
                    outboundOrderDetails.Add(outboundOrderDetail);
 
                    decimal allocatedQuantity = actualOutboundQuantity;
                    List<Dt_OutboundOrderDetail> updateDetails = new();
                    foreach (var item in outboundOrderDetails)
                    {
                        if (allocatedQuantity <= 0) break;
 
                        decimal barcodeQuantity = allocatedQuantity;
 
                        if (item.LockQuantity - item.OverOutQuantity >= allocatedQuantity)
                        {
                            item.OverOutQuantity += allocatedQuantity;
                            item.CurrentDeliveryQty += allocatedQuantity;
                            allocatedQuantity = 0;
                        }
                        else
                        {
                            barcodeQuantity = allocatedQuantity;
                            allocatedQuantity -= (item.LockQuantity - item.OverOutQuantity);
                            item.OverOutQuantity = allocatedQuantity;
                            item.LockQuantity = allocatedQuantity;
                            item.CurrentDeliveryQty = allocatedQuantity;
                        }
 
                        updateDetails.Add(item);
 
                        List<Barcodes> barcodesList = new List<Barcodes>();
                        Barcodes barcodes = new Barcodes
                        {
                            Barcode = isUnpacked ? newBarcode : stockDetail?.Barcode,
                            Qty = barcodeQuantity,
                            SupplyCode = stockDetail?.SupplyCode ?? "",
                            BatchNo = stockDetail?.BatchNo ?? "",
                            Unit = stockDetail?.Unit ?? ""
                        };
                        if (!string.IsNullOrEmpty(item.ReturnJsonData))
                        {
                            barcodesList = JsonConvert.DeserializeObject<List<Barcodes>>(item.ReturnJsonData) ?? new List<Barcodes>();
                        }
                        barcodesList.Add(barcodes);
                        JsonSerializerSettings settings = new JsonSerializerSettings
                        {
                            ContractResolver = new CamelCasePropertyNamesContractResolver()
                        };
                        item.ReturnJsonData = JsonConvert.SerializeObject(barcodesList, settings);
                    }
 
                    // 更新出库单明细的已出库数量
                    _outboundOrderDetailRepository.UpdateData(updateDetails);
 
                    // 更新锁定记录的累计已出库数量(需要更新该托盘该物料的所有相关记录)
                    //UpdateLockInfoAllocatedQuantity(stockInfo.Id, stockDetail.MaterielCode, stockDetail.BatchNo, actualOutboundQuantity);
 
                    // 提交事务
                    _unitOfWorkManage.CommitTran();
 
                    // 构建返回信息
                    ScannedStockDetailDTO scannedDetail = new ScannedStockDetailDTO
                    {
                        StockDetailId = stockDetail.Id,
                        PalletCode = stockInfo.PalletCode,
                        MaterielCode = stockDetail.MaterielCode,
                        MaterielName = stockDetail.MaterielName,
                        BatchNo = stockDetail.BatchNo,
                        OriginalBarcode = request.Barcode,
                        BeforeQuantity = beforeQuantity,
                        AfterQuantity = isUnpacked ? actualOutboundQuantity : 0,
                        ChangeQuantity = -actualOutboundQuantity,
                        IsUnpacked = isUnpacked,
                        MaterialCodes = returnDTOs
                    };
 
                    response.Success = true;
                    response.Message = "出库完成";
                    response.ScannedDetail = scannedDetail;
                    response.UpdatedDetails = updateDetails;
 
                    if (!string.IsNullOrEmpty(newBarcode))
                    {
                        // 物料新条码回传
                        _feedbackMesService.BarcodeFeedback(newBarcode);
                    }
                    List<Dt_OutboundOrderDetail> details = _outboundOrderDetailRepository.QueryData(x => x.OrderId == outboundOrder.Id);
                    if(details.All(x => x.OverOutQuantity >= x.OrderQuantity - x.MoveQty))
                    {
                        outboundOrder.OrderStatus = OutOrderStatusEnum.出库完成.ObjToInt();
                        _outboundOrderRepository.UpdateData(outboundOrder);
                    }
                    _feedbackMesService.OutboundFeedback(outboundOrder.OrderNo);
 
                }
                catch (Exception ex)
                {
                    _unitOfWorkManage.RollbackTran();
                    response.Success = false;
                    response.Message = $"出库处理失败:{ex.Message}";
                    return WebResponseContent.Instance.Error(ex.Message);
                }
 
                content = WebResponseContent.Instance.OK(data: response);
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error("处理出库完成失败:" + ex.Message);
            }
            return content;
        }
 
        public WebResponseContent StockTakeGroupPallet(string barcode, string boxNo)
        {
            throw new NotImplementedException();
        }
    }
    
}