From 4506a1ed31e5d3c009ea5049f385ada6527bb595 Mon Sep 17 00:00:00 2001
From: wanshenmean <cathay_xy@163.com>
Date: 星期二, 21 四月 2026 00:18:08 +0800
Subject: [PATCH] refactor(StockService): MES调用改为Task.Run异步执行

---
 Code/WMS/WIDESEA_WMSServer/WIDESEA_StockService/StockSerivce.cs |  248 +++++++++++++++++++++++++++++++-----------------
 1 files changed, 159 insertions(+), 89 deletions(-)

diff --git a/Code/WMS/WIDESEA_WMSServer/WIDESEA_StockService/StockSerivce.cs b/Code/WMS/WIDESEA_WMSServer/WIDESEA_StockService/StockSerivce.cs
index 47d1605..81914e7 100644
--- a/Code/WMS/WIDESEA_WMSServer/WIDESEA_StockService/StockSerivce.cs
+++ b/Code/WMS/WIDESEA_WMSServer/WIDESEA_StockService/StockSerivce.cs
@@ -1,8 +1,10 @@
 锘縰sing Newtonsoft.Json;
 using SqlSugar;
+using System.Diagnostics;
 using WIDESEA_Common.Constants;
 using WIDESEA_Common.StockEnum;
 using WIDESEA_Core;
+using WIDESEA_Core.Helper;
 using WIDESEA_DTO.MES;
 using WIDESEA_DTO.Stock;
 using WIDESEA_IBasicService;
@@ -51,6 +53,8 @@
         /// </summary>
         public IMesService _mesService { get; }
 
+        private readonly IMesLogService _mesLogService;
+
         /// <summary>
         /// 鏋勯�犲嚱鏁�
         /// </summary>
@@ -65,7 +69,8 @@
             IStockInfo_HtyService stockInfo_HtyService,
             IMesService mesService,
             IWarehouseService warehouseService,
-            ISqlSugarClient sqlSugarClient)
+            ISqlSugarClient sqlSugarClient,
+            IMesLogService mesLogService)
         {
             StockInfoDetailService = stockInfoDetailService;
             StockInfoService = stockInfoService;
@@ -74,6 +79,7 @@
             _mesService = mesService;
             _warehouseService = warehouseService;
             SqlSugarClient = sqlSugarClient;
+            _mesLogService = mesLogService;
         }
 
         /// <summary>
@@ -145,20 +151,6 @@
                     Status = StockStatusEmun.缁勭洏鏆傚瓨.GetHashCode(),
                 }).ToList();
 
-                //var bindRequest = new BindContainerRequest
-                //{
-                //    ContainerCode = stock?.TargetPalletNo,
-                //    EquipmentCode = StockConstants.MES_EQUIPMENT_CODE,
-                //    ResourceCode = StockConstants.MES_RESOURCE_CODE,
-                //    LocalTime = now,
-                //    OperationType = StockConstants.MES_BIND_OPERATION_TYPE,
-                //    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);
@@ -187,11 +179,6 @@
                     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("缁勭洏鎴愬姛");
                 });
             }
@@ -253,44 +240,9 @@
                     if (await StockInfo_HtyService.Repository.AddDataAsync(CreateStockHistory(new[] { sourceStock, targetStock }, "鎹㈢洏")) <= 0)
                         return content.Error("鎹㈢洏鍘嗗彶璁板綍淇濆瓨澶辫触");
 
-                    // 璋冪敤MES瑙g粦婧愭墭鐩樼數鑺�
-                    //var unbindRequest = new UnBindContainerRequest
-                    //{
-                    //    EquipmentCode = StockConstants.MES_EQUIPMENT_CODE,
-                    //    ResourceCode = StockConstants.MES_RESOURCE_CODE,
-                    //    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瑙g粦澶辫触: {unbindResult?.Data?.Msg ?? unbindResult?.ErrorMessage ?? "鏈煡閿欒"}");
-                    //}
-
                     detailEntities.ForEach(d => d.StockId = targetStock.Id);
                     var result = await StockInfoDetailService.Repository.UpdateDataAsync(detailEntities);
                     if (!result) return content.Error("鎹㈢洏澶辫触");
-
-                    // 璋冪敤MES缁戝畾鐩爣鎵樼洏鐢佃姱
-                    //var bindRequest = new BindContainerRequest
-                    //{
-                    //    ContainerCode = stock.TargetPalletNo,
-                    //    EquipmentCode = StockConstants.MES_EQUIPMENT_CODE,
-                    //    ResourceCode = StockConstants.MES_RESOURCE_CODE,
-                    //    LocalTime = DateTime.Now,
-                    //    OperationType = StockConstants.MES_BIND_OPERATION_TYPE,
-                    //    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("鎹㈢洏鎴愬姛");
                 });
@@ -360,23 +312,6 @@
                     if (await StockInfo_HtyService.Repository.AddDataAsync(CreateStockHistory(new[] { sourceStock }, "鎷嗙洏")) <= 0)
                         return content.Error("鎷嗙洏鍘嗗彶璁板綍淇濆瓨澶辫触");
 
-                    // 璋冪敤MES瑙g粦鐢佃姱
-                    //var unbindRequest = new UnBindContainerRequest
-                    //{
-                    //    EquipmentCode = StockConstants.MES_EQUIPMENT_CODE,
-                    //    ResourceCode = StockConstants.MES_RESOURCE_CODE,
-                    //    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瑙g粦澶辫触: {unbindResult?.Data?.Msg ?? unbindResult?.ErrorMessage ?? "鏈煡閿欒"}");
-                    //}
-
-                    //var result = await StockInfoDetailService.Repository.DeleteDataAsync(detailEntities);
-                    //if (!result) return content.Error("鎷嗙洏澶辫触");
                     return content.OK("鎷嗙洏鎴愬姛");
                 });
             }
@@ -463,8 +398,9 @@
         /// 鎵归噺鎷嗙洏纭 - 涓�娆℃�ц皟鐢∕ES瑙g粦鏁翠釜鎵樼洏
         /// </summary>
         /// <param name="palletCode">婧愭墭鐩樺彿</param>
+        /// <param name="deviceName">璁惧鍚嶇О锛堢敤浜庡姩鎬丮ES鍑瘉鏌ヨ锛�</param>
         /// <returns>鎿嶄綔缁撴灉</returns>
-        public async Task<WebResponseContent> SplitPalletConfirmAsync(string palletCode)
+        public async Task<WebResponseContent> SplitPalletConfirmAsync(string palletCode, string deviceName)
         {
             WebResponseContent content = new WebResponseContent();
             try
@@ -483,22 +419,70 @@
                 if (sfcList == null || !sfcList.Any())
                     return content.Error("涓存椂琛ㄤ腑鐢佃姱鍒楄〃涓虹┖");
 
-                // 2. 璋冪敤MES瑙g粦
+                // 2. 鑾峰彇MES璁惧閰嶇疆锛堝姩鎬佸嚟璇侊級
+                string equipmentCode = StockConstants.MES_EQUIPMENT_CODE;
+                string resourceCode = StockConstants.MES_RESOURCE_CODE;
+                string token = null;
+
+                if (!string.IsNullOrWhiteSpace(deviceName))
+                {
+                    var mesConfig = ResolveMesConfig(deviceName, palletCode);
+                    if (mesConfig != null)
+                    {
+                        equipmentCode = mesConfig.EquipmentCode;
+                        resourceCode = mesConfig.ResourceCode;
+                        token = mesConfig.Token;
+                    }
+                }
+
+                // 3. Fire-and-forget寮傛璋冪敤MES瑙g粦
                 var unbindRequest = new UnBindContainerRequest
                 {
-                    EquipmentCode = StockConstants.MES_EQUIPMENT_CODE,
-                    ResourceCode = StockConstants.MES_RESOURCE_CODE,
+                    EquipmentCode = equipmentCode,
+                    ResourceCode = resourceCode,
                     LocalTime = DateTime.Now,
                     ContainCode = palletCode,
                     SfcList = sfcList
                 };
-                var unbindResult = _mesService.UnBindContainer(unbindRequest);
-                if (unbindResult == null || unbindResult.Data == null || !unbindResult.Data.IsSuccess)
+                _ = Task.Run(() =>
                 {
-                    return content.Error($"MES瑙g粦澶辫触: {unbindResult?.Data?.Msg ?? unbindResult?.ErrorMessage ?? "鏈煡閿欒"}");
-                }
+                    var stopwatch = Stopwatch.StartNew();
+                    try
+                    {
+                        var unbindResult = string.IsNullOrWhiteSpace(token)
+                            ? _mesService.UnBindContainer(unbindRequest)
+                            : _mesService.UnBindContainer(unbindRequest, token);
+                        stopwatch.Stop();
 
-                // 3. 鍒犻櫎涓存椂琛ㄨ褰�
+                        bool isSuccess = unbindResult?.Data?.IsSuccess ?? false;
+                        int status = isSuccess
+                            ? (int)MesUploadStatusEnum.鎷嗙洏涓婁紶鎴愬姛
+                            : (int)MesUploadStatusEnum.鎷嗙洏涓婁紶澶辫触;
+
+                        // 鏇存柊MES涓婁紶鐘舵��
+                        StockInfoService.UpdateMesUploadStatusAsync(palletCode, status).ConfigureAwait(false);
+
+                        // 璁板綍MES鏃ュ織
+                        _mesLogService.LogAsync(new MesApiLogDto
+                        {
+                            PalletCode = palletCode,
+                            ApiType = "UnBindContainer",
+                            RequestJson = unbindRequest.ToJson(),
+                            ResponseJson = System.Text.Json.JsonSerializer.Serialize(unbindResult),
+                            IsSuccess = isSuccess,
+                            ErrorMessage = unbindResult?.Data?.Msg ?? unbindResult?.ErrorMessage ?? "鏈煡閿欒",
+                            ElapsedMs = (int)stopwatch.ElapsedMilliseconds,
+                            Creator = "System"
+                        }).ConfigureAwait(false);
+                    }
+                    catch (Exception ex)
+                    {
+                        // 璋冪敤澶辫触
+                        StockInfoService.UpdateMesUploadStatusAsync(palletCode, (int)MesUploadStatusEnum.鎷嗙洏涓婁紶澶辫触).ConfigureAwait(false);
+                    }
+                });
+
+                // 4. 鍒犻櫎涓存椂琛ㄨ褰�
                 await SqlSugarClient.Deleteable<Dt_SplitTemp>().Where(t => t.PalletCode == palletCode).ExecuteCommandAsync();
 
                 return content.OK("鎵归噺鎷嗙洏纭鎴愬姛");
@@ -513,10 +497,12 @@
         /// 鎵归噺缁勭洏纭 - 涓�娆℃�ц皟鐢∕ES缁戝畾鏁翠釜鎵樼洏
         /// </summary>
         /// <param name="palletCode">鐩爣鎵樼洏鍙�</param>
+        /// <param name="deviceName">璁惧鍚嶇О锛堢敤浜庡姩鎬丮ES鍑瘉鏌ヨ锛�</param>
         /// <returns>鎿嶄綔缁撴灉</returns>
-        public async Task<WebResponseContent> GroupPalletConfirmAsync(string palletCode)
+        public async Task<WebResponseContent> GroupPalletConfirmAsync(string palletCode, string deviceName)
         {
             WebResponseContent content = new WebResponseContent();
+            var stopwatch = Stopwatch.StartNew();
             try
             {
                 if (string.IsNullOrWhiteSpace(palletCode))
@@ -531,12 +517,28 @@
                 if (details == null || !details.Any())
                     return content.Error("鎵樼洏涓嬫棤鐢佃姱鏁版嵁");
 
-                // 2. 璋冪敤MES缁戝畾
+                // 2. 鑾峰彇MES璁惧閰嶇疆锛堝姩鎬佸嚟璇侊級
+                string equipmentCode = StockConstants.MES_EQUIPMENT_CODE;
+                string resourceCode = StockConstants.MES_RESOURCE_CODE;
+                string token = null;
+
+                if (!string.IsNullOrWhiteSpace(deviceName))
+                {
+                    var mesConfig = ResolveMesConfig(deviceName, palletCode);
+                    if (mesConfig != null)
+                    {
+                        equipmentCode = mesConfig.EquipmentCode;
+                        resourceCode = mesConfig.ResourceCode;
+                        token = mesConfig.Token;
+                    }
+                }
+
+                // 3. 璋冪敤MES缁戝畾
                 var bindRequest = new BindContainerRequest
                 {
                     ContainerCode = palletCode,
-                    EquipmentCode = StockConstants.MES_EQUIPMENT_CODE,
-                    ResourceCode = StockConstants.MES_RESOURCE_CODE,
+                    EquipmentCode = equipmentCode,
+                    ResourceCode = resourceCode,
                     LocalTime = DateTime.Now,
                     OperationType = StockConstants.MES_BIND_OPERATION_TYPE,
                     ContainerSfcList = details.Select(d => new ContainerSfcItem
@@ -545,11 +547,45 @@
                         Location = d.InboundOrderRowNo.ToString()
                     }).ToList()
                 };
-                var bindResult = _mesService.BindContainer(bindRequest);
-                if (bindResult == null || bindResult.Data == null || !bindResult.Data.IsSuccess)
+                string requestJson = bindRequest.ToJson();
+                // 3. Fire-and-forget寮傛璋冪敤MES缁戝畾
+                _ = Task.Run(() =>
                 {
-                    return content.Error($"MES缁戝畾澶辫触: {bindResult?.Data?.Msg ?? bindResult?.ErrorMessage ?? "鏈煡閿欒"}");
-                }
+                    var stopwatch = Stopwatch.StartNew();
+                    try
+                    {
+                        var bindResult = string.IsNullOrWhiteSpace(token)
+                            ? _mesService.BindContainer(bindRequest)
+                            : _mesService.BindContainer(bindRequest, token);
+                        stopwatch.Stop();
+
+                        bool isSuccess = bindResult?.Data?.IsSuccess ?? false;
+                        int status = isSuccess
+                            ? (int)MesUploadStatusEnum.缁勭洏涓婁紶鎴愬姛
+                            : (int)MesUploadStatusEnum.缁勭洏涓婁紶澶辫触;
+
+                        // 鏇存柊MES涓婁紶鐘舵��
+                        StockInfoService.UpdateMesUploadStatusAsync(palletCode, status).ConfigureAwait(false);
+
+                        // 璁板綍MES鏃ュ織
+                        _mesLogService.LogAsync(new MesApiLogDto
+                        {
+                            PalletCode = palletCode,
+                            ApiType = "BindContainer",
+                            RequestJson = requestJson,
+                            ResponseJson = System.Text.Json.JsonSerializer.Serialize(bindResult),
+                            IsSuccess = isSuccess,
+                            ErrorMessage = bindResult?.ErrorMessage ?? "鏈煡閿欒",
+                            ElapsedMs = (int)stopwatch.ElapsedMilliseconds,
+                            Creator = "System"
+                        }).ConfigureAwait(false);
+                    }
+                    catch (Exception ex)
+                    {
+                        // 璋冪敤澶辫触
+                        StockInfoService.UpdateMesUploadStatusAsync(palletCode, (int)MesUploadStatusEnum.缁勭洏涓婁紶澶辫触).ConfigureAwait(false);
+                    }
+                });
 
                 return content.OK("鎵归噺缁勭洏纭鎴愬姛");
             }
@@ -558,5 +594,39 @@
                 return content.Error($"鎵归噺缁勭洏纭澶辫触: {ex.Message}");
             }
         }
+
+        /// <summary>
+        /// 鏍规嵁璁惧鍚嶇О鍜屾墭鐩樺彿瑙f瀽MES璁惧閰嶇疆
+        /// </summary>
+        /// <param name="deviceName">璁惧鍚嶇О</param>
+        /// <param name="palletCode">鎵樼洏鍙凤紙鐢ㄤ簬鏌ヨ浠撳簱缂栫爜锛�</param>
+        /// <returns>MES璁惧閰嶇疆锛屼笉瀛樺湪鏃惰繑鍥瀗ull</returns>
+        private Dt_MESDeviceConfig ResolveMesConfig(string deviceName, string palletCode)
+        {
+            // 鎹㈢洏鏈烘鎵嬮渶瑕佸尯鍒嗕粨搴�
+            if (deviceName.Contains("鎹㈢洏"))
+            {
+                // 鏌ヨ鎵樼洏瀵瑰簲鐨勪粨搴撶紪鐮�
+                var stockInfo = StockInfoService.Repository.QueryFirst(s => s.PalletCode == palletCode);
+                if (stockInfo != null && stockInfo.WarehouseId > 0)
+                {
+                    var warehouse = _warehouseService.Repository.QureyDataById(stockInfo.WarehouseId);
+                    if (warehouse != null && !string.IsNullOrWhiteSpace(warehouse.WarehouseCode))
+                    {
+                        // 鍏堟寜璁惧鍚�+浠撳簱缂栫爜鏌ヨ
+                        var config = SqlSugarClient.Queryable<Dt_MESDeviceConfig>()
+                            .Where(c => c.DeviceName == deviceName && c.WarehouseCode == warehouse.WarehouseCode)
+                            .First();
+                        if (config != null)
+                            return config;
+                    }
+                }
+            }
+
+            // 鎸夎澶囧悕绉版煡璇紙閫傜敤浜庣粍鐩樻満姊版墜鎴栨崲鐩樻満姊版墜鏈壘鍒颁粨搴撳尮閰嶇殑鎯呭喌锛�
+            return SqlSugarClient.Queryable<Dt_MESDeviceConfig>()
+                .Where(c => c.DeviceName == deviceName)
+                .First();
+        }
     }
 }
\ No newline at end of file

--
Gitblit v1.9.3