pan
9 天以前 75f5025e433763d32dffbade218a2ba8ab27ff35
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
using Dm.filter;
using MailKit.Search;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.Ocsp;
using SqlSugar;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection.Metadata;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Common.OrderEnum;
using WIDESEA_Common.StockEnum;
using WIDESEA_Core;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.Helper;
using WIDESEA_DTO.Allocate;
using WIDESEA_DTO.Basic;
using WIDESEA_DTO.Inbound;
using WIDESEA_DTO.Outbound;
using WIDESEA_IBasicService;
using WIDESEA_IOutboundService;
using WIDESEA_Model.Models;
using WIDESEA_Model.Models.Outbound;
 
namespace WIDESEA_BasicService
{
    public class InvokeMESService : IInvokeMESService
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly ILogger<InvokeMESService> _logger;
        private string UserName = "12312";
        private string Password = "1";
 
        private readonly IRepository<Dt_FeedbackToMes> _feedbacktomesRepository;
        private readonly IRepository<Dt_StockInfoDetail> _stockInfoDetailRepository;
        private readonly IRepository<Dt_StockInfo> _stockInfoRepository;
        private readonly IRepository<Dt_InboundOrder> _inboundOrderRepository;
        private readonly IRepository<Dt_PickingRecord> _pickingRecoreRepository;
        private readonly IMaterialUnitService _materialUnitService;
        private readonly IOutboundOrderService _outboundOrderService;
        private readonly IOutboundOrderDetailService _outboundOrderDetailService;
        private readonly IOutStockLockInfoService _outStockLockInfoService;
        private readonly IRepository<Dt_InterfaceLog> _interfacelogRepository;
 
        // 存储资源ID及其对应的锁对象。使用 ConcurrentDictionary 确保对字典操作本身的线程安全。
        private static readonly ConcurrentDictionary<string, object> _resourceLocks = new ConcurrentDictionary<string, object>();
 
        // 全局静态锁:用于保护 _resourceLocks 字典中 GetOrAdd 或 TryRemove 时的竞争
        private static readonly object _globalLocker = new object();
        public InvokeMESService(IHttpClientFactory httpClientFactory, ILogger<InvokeMESService> logger, IRepository<Dt_FeedbackToMes> feedbacktomesRepository, IRepository<Dt_StockInfoDetail> stockInfoDetailRepository, IRepository<Dt_StockInfo> stockInfoRepository, IRepository<Dt_InboundOrder> inboundOrderRepository, IOutboundOrderService outboundOrderService, IOutboundOrderDetailService outboundOrderDetailService, IOutStockLockInfoService outStockLockInfoService, IMaterialUnitService materialUnitService, IRepository<Dt_PickingRecord> pickingRecoreRepository, IRepository<Dt_InterfaceLog> interfacelogRepository)
        {
            _httpClientFactory = httpClientFactory;
            _logger = logger;
            _feedbacktomesRepository = feedbacktomesRepository;
            _stockInfoDetailRepository = stockInfoDetailRepository;
            _stockInfoRepository = stockInfoRepository;
            _inboundOrderRepository = inboundOrderRepository;
            _outboundOrderService = outboundOrderService;
            _outboundOrderDetailService = outboundOrderDetailService;
            _outStockLockInfoService = outStockLockInfoService;
            _materialUnitService = materialUnitService;
            _pickingRecoreRepository = pickingRecoreRepository;
            _interfacelogRepository = interfacelogRepository;
        }
 
        /// <summary>
        /// 入库反馈
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="HttpRequestException"></exception>
        public async Task<ResponseModel> FeedbackInbound(FeedbackInboundRequestModel model)
        {
            string json = JsonConvert.SerializeObject(model, new JsonSerializerSettings
            {
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            });
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            var _client = _httpClientFactory.CreateClient("MESUrl");
            _client.DefaultRequestHeaders.Clear();
            _client.DefaultRequestHeaders.Add("Accept", "application/json");
            _logger.LogInformation("InvokeMESService  FeedbackInbound :  " + json);
            var response = await _client.PostAsync("AldMaterialWarehousing/MaterialWarehousing", content);
            string body = await response.Content.ReadAsStringAsync();
            _logger.LogInformation("InvokeMESService  FeedbackInbound  body:  " + body);
            if (!response.IsSuccessStatusCode)
            {
 
                throw new HttpRequestException(body);
            }
 
            return JsonConvert.DeserializeObject<ResponseModel>(body);
        }
 
        /// <summary>
        /// 出库反馈
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="HttpRequestException"></exception>
        public async Task<ResponseModel> FeedbackOutbound(FeedbackOutboundRequestModel model)
        {
            string json = JsonConvert.SerializeObject(model, new JsonSerializerSettings
            {
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            });
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            var _client = _httpClientFactory.CreateClient("MESUrl");
            _client.DefaultRequestHeaders.Clear();
            _client.DefaultRequestHeaders.Add("Accept", "application/json");
 
            _logger.LogInformation("InvokeMESService  FeedbackOutbound :  " + model.orderNo + "  , " + json);
 
            var response = await _client.PostAsync("AldMaterialOutbound/MaterialOutbound", content);
            string body = await response.Content.ReadAsStringAsync();
 
            if (!response.IsSuccessStatusCode)
            {
 
                throw new HttpRequestException(body);
            }
            _logger.LogInformation("InvokeMESService  FeedbackOutbound  body:  " + body);
 
            return JsonConvert.DeserializeObject<ResponseModel>(body);
        }
 
        public async Task<ResponseModel> FeedbackAllocate(AllocateDto model)
        {
            _logger.LogInformation($"InvokeMESService  FeedbackAllocate  序列化前: {JsonConvert.SerializeObject(model)}");
            string json = JsonConvert.SerializeObject(model, new JsonSerializerSettings
            {
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),
                NullValueHandling = NullValueHandling.Include
            });
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            var _client = _httpClientFactory.CreateClient("MESUrl");
            _client.DefaultRequestHeaders.Clear();
            _client.DefaultRequestHeaders.Add("Accept", "application/json");
            _logger.LogInformation("InvokeMESService  FeedbackAllocate :  " + json);
            var response = await _client.PostAsync("AldAllocationOperation/AllocationOperation", content);
            string body = await response.Content.ReadAsStringAsync();
            _logger.LogInformation("InvokeMESService  FeedbackAllocate  body:  " + body);
            if (!response.IsSuccessStatusCode)
            {
 
                throw new HttpRequestException(body);
            }
 
            return JsonConvert.DeserializeObject<ResponseModel>(body);
        }
 
        public async Task<ResponseModel> NewMaterielToMes(MaterielToMesDTO model)
        {
            string json = JsonConvert.SerializeObject(model, new JsonSerializerSettings
            {
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            });
 
 
            //string userDataEncoded = Uri.EscapeDataString(json);
            ////string baseUrl = "http://mestest.ald.com//OrBitWCFServiceR15/orbitwebapi.ashx?"; 
            //string userTicket = await GetToken(UserName, Password);
            //string api = "WMS_BarcodeInformation";
 
 
            var client = _httpClientFactory.CreateClient("MESUrl");
            // 拼接 URL 参数
            // string url = $"{client.BaseAddress}UserTicket={userTicket}&API={api}&UserData={userDataEncoded}";
 
 
            client.DefaultRequestHeaders.Clear();
 
            client.DefaultRequestHeaders.Add("Accept", "application/json");
 
 
            var content = new StringContent(json, Encoding.UTF8, "application/json");
 
            _logger.LogInformation("InvokeMESService  NewMaterielToMes :  " + json);
 
            using var response = await client.PostAsync("AldBarcodeInformation/BarcodeInformation", content);
            var responseText = await response.Content.ReadAsStringAsync();
            _logger.LogInformation("InvokeMESService  NewMaterielToMes  body:  " + responseText);
            if (!response.IsSuccessStatusCode)
            {
                throw new HttpRequestException(responseText);
            }
 
            return JsonConvert.DeserializeObject<ResponseModel>(responseText);
        }
 
        public async Task<string> GetToken(String username, string password)
        {
 
            var clientHandler = new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
            };
            //var client = new HttpClient(clientHandler);
            var client = _httpClientFactory.CreateClient("MESUrl");
            client.DefaultRequestHeaders.Clear();
 
 
 
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri($"{client.BaseAddress}UserName={username}&UserPassword={password}"),
                Headers ={
                    { "Accept", "*/*" },
                    { "User-Agent", "PostmanRuntime-ApipostRuntime/1.1.0" },
                    { "Connection", "keep-alive" },
                },
                Content = new MultipartFormDataContent
                {
                },
            };
            using (var response = await client.SendAsync(request))
            {
                response.EnsureSuccessStatusCode();
                var body = await response.Content.ReadAsStringAsync();
                if (!response.IsSuccessStatusCode)
                {
 
                    throw new HttpRequestException(body);
                }
 
                return body;
            }
        }
 
 
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="orderNos"></param>
        /// <param name="inout">入库传1  出库传2</param>
        /// <returns></returns>
        public async Task<WebResponseContent> BatchOrderFeedbackToMes(List<string> orderNos, int inout)
        {
            try
            {             // 1. 【内存锁抢占】
                //if (MemoryLockManager.TryAcquireLock(orderNos[0]))
                //{
                   
                        if (inout == 1)
                        {
                            foreach (var orderNo in orderNos)
                            {
                                try
                                {
                                    var stockinfos = _stockInfoRepository.Db.Queryable<Dt_StockInfo>("info").Where(info => info.StockStatus == 6)
                                                    .Where(it => SqlFunc.Subqueryable<Dt_StockInfoDetail>().Where(s => s.StockId == it.Id && s.OrderNo == orderNo).Any())
                                                    .ToList();
                                    var feeds = _feedbacktomesRepository.Db.Queryable<Dt_FeedbackToMes>().Where(x => x.OrderNo == orderNo && x.ReportStatus == 1).Select(o => o.PalletCode).ToList();
                                    var unreports = stockinfos.Where(x => !feeds.Contains(x.PalletCode)).ToList();
                                    if (unreports != null && !unreports.Any())
                                    {
                                        return WebResponseContent.Instance.Error("没有需要回传的数据");
                                    }
                                    foreach (var item in unreports)
                                    {
                                        var lists = _stockInfoDetailRepository.Db.Queryable<Dt_StockInfoDetail>().Where(x => x.StockId == item.Id).ToList();
                                        if (lists.Any())
                                        {
                                            var inboundOrder = _inboundOrderRepository.Db.Queryable<Dt_InboundOrder>().First(x => x.InboundOrderNo == lists.FirstOrDefault().OrderNo);
                                            if (inboundOrder != null)
                                            {
                                                if (inboundOrder.OrderType == (int)InOrderTypeEnum.AllocatInbound)//调拨入库
                                                {
                                                    var allocate = SqlSugarHelper.DbWMS.Queryable<Dt_AllocateOrder>().Where(x => x.OrderNo == inboundOrder.InboundOrderNo).First();
                                                    var allocatefeedmodel = new AllocateDto
                                                    {
                                                        ReqCode = Guid.NewGuid().ToString(),
                                                        ReqTime = DateTime.Now.ToString(),
                                                        BusinessType = "2",
                                                        FactoryArea = inboundOrder.FactoryArea,
                                                        OperationType = 1,
                                                        Operator = inboundOrder.Operator,
                                                        OrderNo = inboundOrder.UpperOrderNo,
                                                        fromWarehouse = allocate?.FromWarehouse ?? "",
                                                        toWarehouse = allocate?.ToWarehouse ?? "",
                                                        Details = new List<AllocateDtoDetail>()
 
                                                    };
 
                                                    var groupedData = lists.GroupBy(item => new { item.MaterielCode, item.InboundOrderRowNo, item.BarcodeUnit, item.WarehouseCode })
                                                       .Select(group => new AllocateDtoDetail
                                                       {
                                                           MaterialCode = group.Key.MaterielCode,
                                                           LineNo = group.Key.InboundOrderRowNo,
                                                           WarehouseCode = group.Key.WarehouseCode,
                                                           Qty = group.Sum(x => x.BarcodeQty),
                                                           Unit = group.Key.BarcodeUnit,
                                                           Barcodes = group.Select(row => new BarcodeInfo
                                                           {
                                                               Barcode = row.Barcode,
                                                               Qty = row.BarcodeQty,
                                                               BatchNo = row.BatchNo,
                                                               SupplyCode = row.SupplyCode,
                                                               Unit = row.BarcodeUnit
                                                           }).ToList()
                                                       }).ToList();
                                                    allocatefeedmodel.Details = groupedData;
 
                                                    var result = await FeedbackAllocate(allocatefeedmodel);
                                                    if (result != null && result.code == 200)
                                                    {
                                                        _feedbacktomesRepository.Db.Insertable(new Dt_FeedbackToMes { OrderNo = orderNo, PalletCode = item.PalletCode, ReportStatus = 1 }).ExecuteCommand();
                                                    }
                                                }
                                                else
                                                {
                                                    var feedmodel = new FeedbackInboundRequestModel
                                                    {
                                                        reqCode = Guid.NewGuid().ToString(),
                                                        reqTime = DateTime.Now.ToString(),
                                                        business_type = inboundOrder.BusinessType,
                                                        factoryArea = inboundOrder.FactoryArea,
                                                        operationType = 1,
                                                        Operator = inboundOrder.Operator,
                                                        orderNo = inboundOrder.UpperOrderNo,
                                                        status = inboundOrder.OrderStatus,
                                                        details = new List<FeedbackInboundDetailsModel>()
 
                                                    };
 
                                                    var groupedData = lists.GroupBy(item => new { item.MaterielCode, item.SupplyCode, item.BatchNo, item.InboundOrderRowNo, item.BarcodeUnit, item.WarehouseCode })
                                                       .Select(group => new FeedbackInboundDetailsModel
                                                       {
                                                           materialCode = group.Key.MaterielCode,
                                                           supplyCode = group.Key.SupplyCode,
                                                           batchNo = group.Key.BatchNo,
                                                           lineNo = group.Key.InboundOrderRowNo,
                                                           qty = group.Sum(x => x.BarcodeQty),
                                                           // warehouseCode = group.Key.WarehouseCode=="0"?"1072": group.Key.WarehouseCode,
                                                           warehouseCode = group.Key.WarehouseCode,
                                                           unit = group.Key.BarcodeUnit,
                                                           barcodes = group.Select(row => new FeedbackBarcodesModel
                                                           {
                                                               barcode = row.Barcode,
                                                               qty = row.BarcodeQty
                                                           }).ToList()
                                                       }).ToList();
                                                    feedmodel.details = groupedData;
                                                    var result = await FeedbackInbound(feedmodel);
                                                    if (result != null && result.code == 200)
                                                    {
                                                        _feedbacktomesRepository.Db.Insertable(new Dt_FeedbackToMes { OrderNo = orderNo, PalletCode = item.PalletCode, ReportStatus = 1 }).ExecuteCommand();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    _logger.LogInformation("InvokeMESService  BatchOrderFeedbackToMes 回写MES失败:  " + ex.Message);
                                    return WebResponseContent.Instance.Error(ex.Message);
                                }
 
                            }
                        }
                        else if (inout == 2)
                        {
                            foreach (var orderNo in orderNos)
                            {
                                var outboundOrder = await _outboundOrderService.Db.Queryable<Dt_OutboundOrder>().FirstAsync(x => x.OrderNo == orderNo);
                                if (outboundOrder != null && outboundOrder.IsBatch == 0)
                                {
                                    var result = await HandleOutboundOrderToMESCompletion(outboundOrder, orderNo);
                                    return result;
                                }
                                else if (outboundOrder != null && outboundOrder.IsBatch == 1)
                                {
                                    var result = await HandleOutboundOrderBatchToMESCompletion(outboundOrder, orderNo);
                                    return result;
                                }
                            }
 
                        }
                     
                //}
                //else
                //{
                //    // 抢锁失败:说明有另一个线程(WCS回调或人工操作)正在处理
 
                //    return WebResponseContent.Instance.Error("WMS正在处理此回传任务,请勿重复操作。");
                //}
            }
            catch(Exception ex)
            {
                _logger.LogInformation("InvokeMESService  BatchOrderFeedbackToMes :  " +ex.Message);
            }
            finally
            {
                // 2. 【释放内存锁】无论成功失败,必须释放
               // MemoryLockManager.ReleaseLock(orderNos[0]);
            }
            return WebResponseContent.Instance.OK();
        }
 
        private async Task<WebResponseContent> HandleOutboundOrderBatchToMESCompletion(Dt_OutboundOrder outboundOrder, string orderNo)
        {
            // 定义默认返回(成功态)
            WebResponseContent response = WebResponseContent.Instance.OK("回传MES处理完成");
            //0 = 未回传,1 = 已回传成功,2 = 回传失败 
            try
            {
                // 校验:已回传直接返回错误
                //if (outboundOrder.ReturnToMESStatus == 1)
                //{
                //    return WebResponseContent.Instance.Error("该单已经回传!");
                //}
 
                // 查询订单明细(仅查询未回传成功的)
                var orderDetails = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
                    .LeftJoin<Dt_OutboundOrder>((o, item) => o.OrderId == item.Id)
                    .Where((o, item) => item.OrderNo == orderNo && item.ReturnToMESStatus != 1)
                    .Select((o, item) => o)
                    .ToListAsync();
 
                if (!orderDetails.Any())
                {
                    return WebResponseContent.Instance.Error("暂无需要处理的订单明细");
                }
 
 
                var pickingRecords = await _pickingRecoreRepository.Db.Queryable<Dt_PickingRecord>().Where(x => x.OrderNo == orderNo && x.ReturnToMESStatus != 1 && !x.IsCancelled).ToListAsync();
 
                if (!pickingRecords.Any())
                    return WebResponseContent.Instance.Error("没有需要回传的分拣记录");
 
 
                var groups = pickingRecords.GroupBy(x => x.FeedBackMesDocumentNo).ToList();
                foreach (var group in groups)
                {
 
                    List<Dt_PickingRecord> records = group.ToList(); // 该分组下的所有记录
                    if (string.IsNullOrEmpty(group.Key))
                    {
                        var emptydocumentNo = UniqueValueGenerator.Generate();
                        records.ForEach(x => { x.FeedBackMesDocumentNo = emptydocumentNo; });
                        var result = await _pickingRecoreRepository.Db.Updateable(records).ExecuteCommandAsync();
 
                        var interfacelog = new Dt_InterfaceLog
                        {
                            Content = JsonConvert.SerializeObject(records),
                            DocumentNo = emptydocumentNo,
                            OrderNo = orderNo,
                            OrderType = "2",
                        };
                        _interfacelogRepository.AddData(interfacelog);
 
                        if (result > 0)
                        {
                            (bool _flowControl, WebResponseContent _value) = await FeedBackBatchToMes(outboundOrder, orderNo, orderDetails, pickingRecords, emptydocumentNo);
 
                            return _value;
 
                        }
                    }
                    else
                    {
                        var ilog = _interfacelogRepository.QueryFirst(x => x.DocumentNo == group.Key);
                        if (ilog == null)
                        {
                            var interfacelog = new Dt_InterfaceLog
                            {
                                Content = JsonConvert.SerializeObject(records),
                                DocumentNo = group.Key,
                                OrderNo = orderNo,
                                OrderType = "2",
                            };
                            _interfacelogRepository.AddData(interfacelog);
                        }
                        (bool _flowControl, WebResponseContent _value) = await FeedBackBatchToMes(outboundOrder, orderNo, orderDetails, pickingRecords, group.Key);
 
                        return _value;
 
                    }
                }
 
 
                //var documentNo = UniqueValueGenerator.Generate();
 
                //(bool flowControl, WebResponseContent value) = await FeedBackBatchToMes(outboundOrder, orderNo, orderDetails, pickingRecords, documentNo);
                //if (!flowControl)
                //{
                //    return value;
                //}
 
                // 回传成功的最终返回
                response = WebResponseContent.Instance.OK($"回传MES成功,单据号:{orderNo}");
            }
            catch (Exception ex)
            {
                // 全局异常捕获:记录详细日志 + 返回错误
                string errorMsg = $"处理出库单回传MES时发生异常 - OrderNo: {orderNo}, Error: {ex.Message}, StackTrace: {ex.StackTrace}";
                _logger.LogError(ex, errorMsg); // 记录带异常堆栈的日志
 
                // 异常返回(给前端的友好提示,隐藏堆栈信息)
                response = WebResponseContent.Instance.Error("处理回传MES时发生异常,请联系管理员");
            }
 
            return response;
        }
 
        private async Task<(bool flowControl, WebResponseContent value)> FeedBackBatchToMes(Dt_OutboundOrder outboundOrder, string orderNo, List<Dt_OutboundOrderDetail> orderDetails, List<Dt_PickingRecord> pickingRecords, string documentNo)
        {
            var feedModel = new FeedbackOutboundRequestModel
            {
                reqCode = Guid.NewGuid().ToString(),
                reqTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                business_type = outboundOrder.BusinessType,
                factoryArea = outboundOrder.FactoryArea,
                operationType = 1,
                Operator = outboundOrder.Operator != "" ? outboundOrder.Operator : App.User.UserName,
                orderNo = outboundOrder.UpperOrderNo,
                documentsNO = documentNo,
                status = outboundOrder.OrderStatus,
                details = new List<FeedbackOutboundDetailsModel>()
            };
            var detailIds = new List<int>();
            // 填充明细和条码信息
            foreach (var detail in orderDetails)
            {
                // 查询该明细对应的锁定条码记录
                var detailPicks = pickingRecords.Where(x => x.OrderNo == orderNo
                               && detail.Id == x.OrderDetailId).ToList();
                if (!detailPicks.Any())
                {
                    continue;
                }
                var detailModel = new FeedbackOutboundDetailsModel
                {
                    materialCode = detail.MaterielCode,
                    lineNo = detail.lineNo,
                    warehouseCode = detail.WarehouseCode,
                    qty = detail.BarcodeQty,
                    currentDeliveryQty = 0,
                    unit = detail.BarcodeUnit,
                    barcodes = new List<WIDESEA_DTO.Outbound.BarcodesModel>()
                };
 
                // 填充条码信息(含单位转换)
                foreach (var item in detailPicks)
                {
                    if (item.PickQuantity <= 0)
                    {
                        continue;
                    }
                    var barModel = new WIDESEA_DTO.Outbound.BarcodesModel
                    {
                        barcode = item.Barcode,
                        supplyCode = item.SupplyCode,
                        batchNo = item.BatchNo,
                        unit = item.BarcodeUnit,
                        qty = item.PickQuantity
                    };
 
                    // 单位不一致时转换
                    if (detail.BarcodeUnit != detail.Unit)
                    {
                        var convertResult = await _materialUnitService.ConvertAsync(
                            item.MaterielCode, item.PickQuantity, detail.Unit, detail.BarcodeUnit);
                        barModel.unit = convertResult.Unit;
                        barModel.qty = convertResult.Quantity;
                    }
                    else
                    {
                        barModel.qty = item.PickQuantity;
                    }
                    detailModel.currentDeliveryQty += barModel.qty;
                    detailModel.barcodes.Add(barModel);
                }
                detailIds.Add(detail.Id);
                feedModel.details.Add(detailModel);
            }
 
            feedModel.details = feedModel.details.GroupBy(item => new { item.materialCode, item.lineNo, item.warehouseCode, item.unit, item.qty }).Select(group => new FeedbackOutboundDetailsModel
            {
                materialCode = group.Key.materialCode,
                lineNo = group.Key.lineNo,
                warehouseCode = group.Key.warehouseCode,
                qty = group.Key.qty,
                currentDeliveryQty = group.Sum(x => x.currentDeliveryQty),
                unit = group.Key.unit,
                barcodes = group.SelectMany(x => x.barcodes.GroupBy(o => new { o.barcode, o.supplyCode, o.batchNo, o.unit }).Select(row => new WIDESEA_DTO.Outbound.BarcodesModel
                {
                    barcode = row.Key.barcode,
                    supplyCode = row.Key.supplyCode,
                    batchNo = row.Key.batchNo,
                    unit = row.Key.unit,
                    qty = row.Sum(y => y.qty)
                })).ToList()
            }).ToList();
 
            var allCompleted = true;
 
            // 筛选待回传的明细(ReturnToMESStatus=0)
            var pendingDetails = orderDetails.Where(x => x.ReturnToMESStatus == 0).ToList();
            foreach (var detail in pendingDetails)
            {
                if (detail.OverOutQuantity < detail.NeedOutQuantity)
                {
                    allCompleted = false;
                }
            }
 
            // 存在回传失败的明细(ReturnToMESStatus=2),标记未完成
            if (orderDetails.Any(x => x.ReturnToMESStatus == 2))
            {
                allCompleted = false;
            }
 
            //  更新订单状态
            int newStatus = allCompleted ? (int)OutOrderStatusEnum.出库完成 : (int)OutOrderStatusEnum.出库中;
            if (allCompleted && outboundOrder.OrderStatus != newStatus)
            {
 
                int updateCount = await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
                    .SetColumns(x => x.OrderStatus == newStatus)
                    .Where(x => x.OrderNo == orderNo)
                    .ExecuteCommandAsync();
 
                if (updateCount <= 0)
                {
                    _logger.LogWarning($"更新出库单状态失败 - OrderNo: {orderNo}, 目标状态: {newStatus}");
 
                }
            }
 
 
            // 调用MES回传接口
            var mesResult = await FeedbackOutbound(feedModel);
            if (mesResult == null || mesResult.code != 200)
            {
 
                // 更新明细为回传失败(ReturnToMESStatus=2)
                await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
                    .SetColumns(it => new Dt_OutboundOrderDetail
                    {
                        ReturnToMESStatus = 2,
                        documentsNO = documentNo,
                    })
                    .Where(x => detailIds.Contains(x.Id))
                    .ExecuteCommandAsync();
 
                return (flowControl: false, value: WebResponseContent.Instance.Error($"回传MES失败"));
            }
            foreach (var record in pickingRecords.Where(x => detailIds.Contains(x.OrderDetailId)).ToList())
            {
                record.ReturnToMESStatus = 1;
            }
            var updates = pickingRecords.Where(x => detailIds.Contains(x.OrderDetailId)).ToList();
            updates.ForEach(x =>
            {
                x.ReturnToMESStatus = 1;
            });
            await _pickingRecoreRepository.Db.Updateable(updates).ExecuteCommandAsync();
            await _interfacelogRepository.Db.Updateable<Dt_InterfaceLog>()
                                             .SetColumns(x => x.ReturnToMESStatus == 1)
                                             .Where(x => x.OrderNo == orderNo)
                                             .ExecuteCommandAsync();
 
            if (allCompleted)
            {
                //MES回传成功:更新明细为回传成功状态
                await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
                    .SetColumns(it => new Dt_OutboundOrderDetail
                    {
                        ReturnToMESStatus = 1,
                        documentsNO = documentNo,
                    })
                    .Where(x => detailIds.Contains(x.Id))
                    .ExecuteCommandAsync();
            }
            // 校验是否所有明细都完成,更新订单最终状态
            if (allCompleted && newStatus == (int)OutOrderStatusEnum.出库完成)
            {
                await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
                    .SetColumns(x => new Dt_OutboundOrder
                    {
                        ReturnToMESStatus = 1,
                        OrderStatus = newStatus
                    })
                    .Where(x => x.OrderNo == orderNo)
                    .ExecuteCommandAsync();
            }
            else
            {
                // 二次校验是否所有未回传明细都已完成
                var dbOrderDetails = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
                    .LeftJoin<Dt_OutboundOrder>((o, item) => o.OrderId == item.Id)
                    .Where((o, item) => item.OrderNo == orderNo && item.ReturnToMESStatus != 1)
                    .Select((o, item) => o)
                    .ToListAsync();
 
                var secAllCompleted = true;
                foreach (var detail in dbOrderDetails.Where(x => x.ReturnToMESStatus == 0).ToList())
                {
                    if (detail.OverOutQuantity < detail.NeedOutQuantity)
                    {
                        secAllCompleted = false;
                        break;
                    }
                }
 
                if (secAllCompleted)
                {
                    await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
                        .SetColumns(it => new Dt_OutboundOrder
                        {
                            ReturnToMESStatus = 1,
                            OrderStatus = OutOrderStatusEnum.出库完成.ObjToInt(),
                        })
                        .Where(x => x.OrderNo == orderNo)
                        .ExecuteCommandAsync();
                }
            }
 
            return (flowControl: true, value: null);
        }
 
        private async Task<WebResponseContent> HandleOutboundOrderToMESCompletion(Dt_OutboundOrder outboundOrder, string orderNo)
        {
            // 前置参数校验:空值直接返回错误
            if (outboundOrder == null)
            {
                return WebResponseContent.Instance.Error("出库单实体为空,无法处理回传MES");
            }
 
            if (string.IsNullOrWhiteSpace(orderNo))
            {
                return WebResponseContent.Instance.Error("订单号为空,无法处理回传MES");
            }
 
            try
            {
 
                if (outboundOrder.ReturnToMESStatus == 1)
                {
                    return WebResponseContent.Instance.Error($"OrderNo: {orderNo}, 该单已经回传!");
                }
 
 
                var orderDetails = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
                    .LeftJoin<Dt_OutboundOrder>((o, item) => o.OrderId == item.Id)
                    .Where((o, item) => item.OrderNo == orderNo)
                    .Select((o, item) => o)
                    .ToListAsync();
 
                // 无明细场景返回警告
                if (!orderDetails.Any())
                {
                    return WebResponseContent.Instance.Error($"OrderNo: {orderNo} 未查询到订单明细");
                }
 
                // 判断是否所有明细完成出库
                bool allCompleted = true;
                foreach (var detail in orderDetails)
                {
                    if (detail.OverOutQuantity < detail.NeedOutQuantity)
                    {
                        allCompleted = false;
                        break;
                    }
                }
 
                //  更新订单状态(修正语法错误:== → =)
                int newStatus = allCompleted ? (int)OutOrderStatusEnum.出库完成 : (int)OutOrderStatusEnum.出库中;
                if (outboundOrder.OrderStatus != newStatus)
                {
                    await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
                        .SetColumns(x => x.OrderStatus == newStatus) // 关键修正:赋值而非判断
                        .Where(x => x.OrderNo == orderNo)
                        .ExecuteCommandAsync();
                }
 
                // 仅分拣完成时向MES反馈
                if (allCompleted && newStatus == (int)OutOrderStatusEnum.出库完成)
                {
                    var feedmodel = new FeedbackOutboundRequestModel
                    {
                        reqCode = Guid.NewGuid().ToString(),
                        reqTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        business_type = outboundOrder.BusinessType,
                        factoryArea = outboundOrder.FactoryArea,
                        operationType = 1,
                        Operator = outboundOrder.Operator,
                        orderNo = outboundOrder.UpperOrderNo,
                        documentsNO = outboundOrder.OrderNo,
                        status = outboundOrder.OrderStatus,
                        details = new List<FeedbackOutboundDetailsModel>()
                    };
 
                    // 构建明细数据
                    foreach (var detail in orderDetails)
                    {
                        var detailLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                            .Where(x => x.OrderNo == orderNo &&
                                       x.OrderDetailId == detail.Id &&
                                       (x.Status == (int)OutLockStockStatusEnum.拣选完成 || x.Status == (int)OutLockStockStatusEnum.已回库))
                            .ToListAsync();
 
                        var groupdata = detailLocks.GroupBy(item => new { item.MaterielCode, item.lineNo, item.BarcodeUnit, item.WarehouseCode })
                            .Select(group => new FeedbackOutboundDetailsModel
                            {
                                materialCode = group.Key.MaterielCode,
                                lineNo = group.Key.lineNo,
                                warehouseCode = group.Key.WarehouseCode,
                                qty = group.Sum(x => x.PickedQty),
                                currentDeliveryQty = group.Sum(x => x.PickedQty),
                                unit = group.Key.BarcodeUnit,
                                barcodes = group.Select(lockInfo => new WIDESEA_DTO.Outbound.BarcodesModel
                                {
                                    barcode = lockInfo.CurrentBarcode,
                                    supplyCode = lockInfo.SupplyCode,
                                    batchNo = lockInfo.BatchNo,
                                    unit = lockInfo.BarcodeUnit,
                                    qty = lockInfo.PickedQty
                                }).ToList()
                            }).ToList();
 
                        feedmodel.details.AddRange(groupdata);
                    }
 
                    //  调用MES接口
                    var result = await FeedbackOutbound(feedmodel);
                    if (result == null)
                    {
                        return WebResponseContent.Instance.Error($"OrderNo: {orderNo} MES回传接口返回空");
                    }
 
                    if (result.code == 200)
                    {
                        //  回传成功:更新回传状态
                        await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
                            .SetColumns(x => x.ReturnToMESStatus == 1)
                            .Where(x => x.OrderId == outboundOrder.Id)
                            .ExecuteCommandAsync();
 
                        await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
                            .SetColumns(x => x.ReturnToMESStatus == 1)
                            .Where(x => x.OrderNo == orderNo)
                            .ExecuteCommandAsync();
 
                        await _pickingRecoreRepository.Db.Updateable<Dt_PickingRecord>()
                                 .SetColumns(x => x.ReturnToMESStatus == 1)
                            .Where(x => x.OrderNo == orderNo)
                            .ExecuteCommandAsync();
 
                        return WebResponseContent.Instance.OK("回传MES成功");
                    }
                    else
                    {
                        var errorMsg = $"OrderNo: {orderNo} 回传MES失败,错误码:{result.code},错误信息:{result.message ?? "无"}";
                        _logger.LogError(errorMsg);
                        return WebResponseContent.Instance.Error(errorMsg);
                    }
                }
                return WebResponseContent.Instance.OK("订单状态已更新,未完全完成分拣无需回传MES");
            }
            catch (Exception ex)
            {
                // 全局异常捕获:返回错误+记录详细日志
                var errorMsg = $"OrderNo: {orderNo} 处理回传MES时发生异常:{ex.Message}";
                _logger.LogError(ex, errorMsg); // 记录堆栈信息便于排查
                return WebResponseContent.Instance.Error("处理回传MES时发生异常,请联系管理员");
            }
        }
    }
 
    public static class UniqueValueGenerator
    {
        // 原子计数器(线程安全,每次递增1,避免同一Ticks重复)
        private static long _counter = 0;
 
        /// <summary>
        /// 生成唯一值(支持高并发)
        /// </summary>
        /// <returns>格式:yyyyMMdd + Ticks + 3位计数器(如2025112563867890123001)</returns>
        public static string Generate()
        {
            var now = DateTime.Now;
            string datePart = now.ToString("MMdd");
            long ticksPart = now.Ticks;
            // 拼接:计数器补0为3位(避免位数不一致)
            return $"{datePart}{ticksPart}";
        }
 
        public static string GenerateCount()
        {
            var now = DateTime.Now;
            string datePart = now.ToString("yyyyMMddHHmmss");
 
 
            // 原子递增计数器(取模1000,确保计数器仅3位,控制长度)
            long counterPart = Interlocked.Increment(ref _counter) % 1000;
 
            // 拼接:计数器补0为3位(避免位数不一致)
            return $"{datePart}{counterPart:D3}";
        }
    }
 
 
    public static class MemoryLockManager
    {
        // 存储资源ID及其对应的锁对象。使用 ConcurrentDictionary 确保对字典操作本身的线程安全。
        private static readonly ConcurrentDictionary<string, object> _resourceLocks = new ConcurrentDictionary<string, object>();
 
        // 全局静态锁:用于保护 _resourceLocks 字典中 GetOrAdd 或 TryRemove 时的竞争
        private static readonly object _globalLocker = new object();
 
        /// <summary>
        /// 尝试锁定一个资源ID。
        /// </summary>
        /// <param name="resourceId">要锁定的资源ID(例如 InboundRecord ID)</param>
        /// <returns>是否成功获取锁</returns>
        public static bool TryAcquireLock(string resourceId)
        {
            object lockObject = null;
 
            // 核心思路:为每个资源创建一个唯一的锁对象
            lock (_globalLocker)
            {
                // 如果资源ID不在字典中,则添加一个新的锁对象
                // 否则,使用已存在的锁对象
                lockObject = _resourceLocks.GetOrAdd(resourceId, new object());
            }
 
            // 尝试获取资源特定的锁
            // 使用 Monitor.TryEnter 避免阻塞,并实现非阻塞的抢锁
            return Monitor.TryEnter(lockObject);
        }
 
        /// <summary>
        /// 释放资源ID的锁定。
        /// </summary>
        /// <param name="resourceId">要释放的资源ID</param>
        public static void ReleaseLock(string resourceId)
        {
            if (_resourceLocks.TryGetValue(resourceId, out object lockObject))
            {
                // 确保释放的是当前线程持有的锁
                if (Monitor.IsEntered(lockObject))
                {
                    Monitor.Exit(lockObject);
 
                    // 释放锁后,尝试从字典中移除这个锁对象,清理内存。
                    // 必须在 Monitor.Exit 之后执行。
                    lock (_globalLocker)
                    {
                        _resourceLocks.TryRemove(resourceId, out _);
                    }
                }
            }
        }
    }
}