From d5475839cb9628c655c8c73264bbba0be964640d Mon Sep 17 00:00:00 2001
From: pan <antony1029@163.com>
Date: 星期四, 11 十二月 2025 13:57:34 +0800
Subject: [PATCH] 提交

---
 项目代码/WMS无仓储版/WIDESEA_WMSServer/WIDESEA_OutboundService/OutboundBatchPickingService.cs | 3395 ++++++++++++++++++++++++++++++++++++++++++++++++++--------
 1 files changed, 2,897 insertions(+), 498 deletions(-)

diff --git "a/\351\241\271\347\233\256\344\273\243\347\240\201/WMS\346\227\240\344\273\223\345\202\250\347\211\210/WIDESEA_WMSServer/WIDESEA_OutboundService/OutboundBatchPickingService.cs" "b/\351\241\271\347\233\256\344\273\243\347\240\201/WMS\346\227\240\344\273\223\345\202\250\347\211\210/WIDESEA_WMSServer/WIDESEA_OutboundService/OutboundBatchPickingService.cs"
index c7b468a..a1e6320 100644
--- "a/\351\241\271\347\233\256\344\273\243\347\240\201/WMS\346\227\240\344\273\223\345\202\250\347\211\210/WIDESEA_WMSServer/WIDESEA_OutboundService/OutboundBatchPickingService.cs"
+++ "b/\351\241\271\347\233\256\344\273\243\347\240\201/WMS\346\227\240\344\273\223\345\202\250\347\211\210/WIDESEA_WMSServer/WIDESEA_OutboundService/OutboundBatchPickingService.cs"
@@ -9,14 +9,19 @@
 using WIDESEA_Common.CommonEnum;
 using WIDESEA_Common.OrderEnum;
 using WIDESEA_Common.StockEnum;
+using WIDESEA_Common.TaskEnum;
 using WIDESEA_Core;
 using WIDESEA_Core.BaseRepository;
 using WIDESEA_Core.BaseServices;
+using WIDESEA_Core.Enums;
+using WIDESEA_Core.Helper;
+using WIDESEA_DTO.Basic;
 using WIDESEA_DTO.Outbound;
 using WIDESEA_IAllocateService;
 using WIDESEA_IBasicService;
 using WIDESEA_IOutboundService;
 using WIDESEA_IStockService;
+using WIDESEA_ITaskInfoService;
 using WIDESEA_Model.Models;
 using WIDESEA_Model.Models.Basic;
 using WIDESEA_Model.Models.Outbound;
@@ -45,6 +50,7 @@
         private readonly IDailySequenceService _dailySequenceService;
         private readonly IAllocateService _allocateService;
         private readonly IRepository<Dt_OutboundBatch> _outboundBatchRepository;
+        private readonly ITask_HtyService _task_HtyService;
         private readonly ILogger<OutboundPickingService> _logger;
 
         private Dictionary<string, string> stations = new Dictionary<string, string>
@@ -64,7 +70,7 @@
         public OutboundBatchPickingService(IRepository<Dt_PickingRecord> BaseDal, IUnitOfWorkManage unitOfWorkManage, IStockInfoService stockInfoService, IStockService stockService,
             IOutStockLockInfoService outStockLockInfoService, IStockInfoDetailService stockInfoDetailService, ILocationInfoService locationInfoService,
             IOutboundOrderDetailService outboundOrderDetailService, ISplitPackageService splitPackageService, IOutboundOrderService outboundOrderService,
-            IRepository<Dt_Task> taskRepository, IESSApiService eSSApiService, ILogger<OutboundPickingService> logger, IInvokeMESService invokeMESService, IDailySequenceService dailySequenceService, IAllocateService allocateService, IRepository<Dt_OutboundBatch> outboundBatchRepository) : base(BaseDal)
+            IRepository<Dt_Task> taskRepository, IESSApiService eSSApiService, ILogger<OutboundPickingService> logger, IInvokeMESService invokeMESService, IDailySequenceService dailySequenceService, IAllocateService allocateService, IRepository<Dt_OutboundBatch> outboundBatchRepository, ITask_HtyService task_HtyService) : base(BaseDal)
         {
             _unitOfWorkManage = unitOfWorkManage;
             _stockInfoService = stockInfoService;
@@ -82,6 +88,7 @@
             _dailySequenceService = dailySequenceService;
             _allocateService = allocateService;
             _outboundBatchRepository = outboundBatchRepository;
+            _task_HtyService = task_HtyService;
         }
 
         // <summary>
@@ -216,7 +223,7 @@
                 .Where(x => x.OrderNo == orderNo &&
                            x.PalletCode == palletCode &&
                            x.CurrentBarcode == barcode
-                        //&& x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�
+                          //&& x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�
                           )
                 .FirstAsync();
 
@@ -240,204 +247,99 @@
 
         #endregion
 
-        #region 鍙栬蛋绌虹閫昏緫
-
-        
-
-        /// <summary>
-        /// 鍙栬蛋绌虹 - 娓呯悊宸插畬鎴愭嫞閫夌殑鎵樼洏鏁版嵁
-        /// </summary>
-        public async Task<WebResponseContent> RemoveEmptyPallet(string orderNo, string palletCode)
-        {
-            try
-            {
-                _unitOfWorkManage.BeginTran();
-
-                // 楠岃瘉鎵樼洏鏄惁鍙互鍙栬蛋锛堝繀椤诲叏閮ㄥ畬鎴愭嫞閫夛級
-                var validationResult = await ValidateEmptyPalletRemoval(orderNo, palletCode);
-                if (!validationResult.IsValid)
-                    return WebResponseContent.Instance.Error(validationResult.ErrorMessage);
-
-                var completedLocks = validationResult.Data;
-
-                // 娓呯悊閿佸畾璁板綍锛堟爣璁颁负宸插畬鎴愶級
-                await CleanupCompletedLocks(completedLocks);
-
-                // 鏇存柊鐩稿叧璁㈠崟鐘舵��
-                await UpdateOrderStatusAfterPalletRemoval(orderNo);
-
-                // 璁板綍鎿嶄綔鍘嗗彶
-                await RecordEmptyPalletRemoval(orderNo, palletCode, completedLocks);
-
-                _unitOfWorkManage.CommitTran();
-
-                return WebResponseContent.Instance.OK("鍙栬蛋绌虹鎴愬姛");
-            }
-            catch (Exception ex)
-            {
-                _unitOfWorkManage.RollbackTran();
-                _logger.LogError($"鍙栬蛋绌虹澶辫触 - OrderNo: {orderNo}, PalletCode: {palletCode}, Error: {ex.Message}");
-                return WebResponseContent.Instance.Error($"鍙栬蛋绌虹澶辫触锛歿ex.Message}");
-            }
-        }
-
-        /// <summary>
-        /// 楠岃瘉绌虹鍙栬蛋鏉′欢
-        /// </summary>
-        private async Task<ValidationResult<List<Dt_OutStockLockInfo>>> ValidateEmptyPalletRemoval(string orderNo, string palletCode)
-        {
-            // 鑾峰彇鎵樼洏鐨勬墍鏈夐攣瀹氳褰�
-            var lockInfos = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                .Where(x => x.OrderNo == orderNo && x.PalletCode == palletCode)
-                .ToListAsync();
-
-            if (!lockInfos.Any())
-                return ValidationResult<List<Dt_OutStockLockInfo>>.Error("璇ユ墭鐩樻病鏈夐攣瀹氳褰�");
-
-            // 妫�鏌ユ槸鍚︽湁鏈畬鎴愮殑閿佸畾璁板綍
-            var unfinishedLocks = lockInfos.Where(x =>
-                x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓� ||
-                x.Status == (int)OutLockStockStatusEnum.鍥炲簱涓�).ToList();
-
-            if (unfinishedLocks.Any())
-            {
-                var unfinishedCount = unfinishedLocks.Count;
-                var unfinishedQty = unfinishedLocks.Sum(x => x.AssignQuantity - x.PickedQty);
-                return ValidationResult<List<Dt_OutStockLockInfo>>.Error(
-                    $"鎵樼洏杩樻湁{unfinishedCount}鏉℃湭瀹屾垚璁板綍锛屽墿浣欐暟閲弡unfinishedQty}锛屼笉鑳藉彇璧扮┖绠�");
-            }
-
-            // 鑾峰彇宸插畬鎴愮殑閿佸畾璁板綍
-            var completedLocks = lockInfos.Where(x =>
-                x.Status == (int)OutLockStockStatusEnum.鎷i�夊畬鎴�).ToList();
-
-            if (!completedLocks.Any())
-                return ValidationResult<List<Dt_OutStockLockInfo>>.Error("璇ユ墭鐩樻病鏈夊凡瀹屾垚鎷i�夌殑璁板綍");
-
-            return ValidationResult<List<Dt_OutStockLockInfo>>.Success(completedLocks);
-        }
-
-        /// <summary>
-        /// 娓呯悊宸插畬鎴愮殑閿佸畾璁板綍
-        /// </summary>
-        private async Task CleanupCompletedLocks(List<Dt_OutStockLockInfo> completedLocks)
-        {
-            foreach (var lockInfo in completedLocks)
-            {
-                // 鏍囪閿佸畾璁板綍涓哄凡鍙栬蛋
-                lockInfo.Status = (int)OutLockStockStatusEnum.宸插彇璧�;
-                lockInfo.Operator = App.User.UserName;
-                await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
-
-                // 娓呯悊瀵瑰簲鐨勫簱瀛樿褰曠姸鎬�
-                await CleanupStockInfo(lockInfo);
-            }
-        }
-
-        /// <summary>
-        /// 娓呯悊搴撳瓨淇℃伅
-        /// </summary>
-        private async Task CleanupStockInfo(Dt_OutStockLockInfo lockInfo)
-        {
-            var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
-                .FirstAsync(x => x.Barcode == lockInfo.CurrentBarcode && x.StockId == lockInfo.StockId);
-
-            if (stockDetail != null && stockDetail.Status == (int)StockStatusEmun.鍑哄簱瀹屾垚)
-            {
-                stockDetail.Status = (int)StockStatusEmun.宸叉竻鐞�;
-                await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
-            }
-        }
- 
-
-        /// <summary>
-        /// 鏇存柊璁㈠崟鐘舵��
-        /// </summary>
-        private async Task UpdateOrderStatusAfterPalletRemoval(string orderNo)
-        {
-            // 妫�鏌ヨ鍗曟槸鍚︽墍鏈夋墭鐩橀兘宸插畬鎴�
-            var allLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                .Where(x => x.OrderNo == orderNo)
-                .ToListAsync();
-
-            var unfinishedPallets = allLocks
-                .GroupBy(x => x.PalletCode)
-                .Where(g => g.Any(x => x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓� ||
-                                      x.Status == (int)OutLockStockStatusEnum.鍥炲簱涓�))
-                .ToList();
-
-            // 濡傛灉娌℃湁鏈畬鎴愮殑鎵樼洏锛屾洿鏂拌鍗曠姸鎬佷负鍑哄簱瀹屾垚
-            if (!unfinishedPallets.Any())
-            {
-                await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
-                    .SetColumns(x => new Dt_OutboundOrder
-                    {
-                        OrderStatus = (int)OutOrderStatusEnum.鍑哄簱瀹屾垚,
-                    })
-                    .Where(x => x.OrderNo == orderNo)
-                    .ExecuteCommandAsync();
-            }
-        }
-
-        /// <summary>
-        /// 璁板綍绌虹鍙栬蛋鍘嗗彶
-        /// </summary>
-        private async Task RecordEmptyPalletRemoval(string orderNo, string palletCode, List<Dt_OutStockLockInfo> completedLocks)
-        {
-            var removalRecord = new Dt_EmptyPalletRemoval
-            {
-                OrderNo = orderNo,
-                PalletCode = palletCode,
-                RemovalTime = DateTime.Now,
-                Operator = App.User.UserName,
-                CompletedItemsCount = completedLocks.Count,
-                TotalPickedQuantity = completedLocks.Sum(x => x.PickedQty)
-            };
-
-            await Db.Insertable(removalRecord).ExecuteCommandAsync();
-        }
-
-        #endregion
-
-  
         #region 鍒嗘壒鍒嗘嫞
 
+
         /// <summary>
-        /// 鍒嗘壒鍒嗘嫞纭
+        /// 鍒嗘壒鍒嗘嫞纭 - 淇鐗堬紙鍖呭惈鎷嗗寘鍚庨獙璇侊級
         /// </summary>
         public async Task<WebResponseContent> ConfirmBatchPicking(string orderNo, string palletCode, string barcode)
         {
             try
             {
+                _logger.LogInformation($"銆愬垎鎷e紑濮嬨�戣鍗�: {orderNo}, 鎵樼洏: {palletCode}, 鏉$爜: {barcode}");
+
                 _unitOfWorkManage.BeginTran();
 
-                // 1. 楠岃瘉鍒嗘嫞璇锋眰
+                // 楠岃瘉鍒嗘嫞璇锋眰
                 var validationResult = await ValidatePickingRequest(orderNo, palletCode, barcode);
                 if (!validationResult.IsValid)
+                {
+                    _unitOfWorkManage.RollbackTran();
                     return WebResponseContent.Instance.Error(validationResult.ErrorMessage);
+                }
 
                 var (lockInfo, orderDetail, stockDetail, batch) = validationResult.Data;
 
-                // 浣跨敤閿佸畾淇℃伅鐨勫垎閰嶆暟閲忎綔涓哄疄闄呭垎鎷f暟閲�
-                var actualPickedQty = lockInfo.AssignQuantity;
+                _logger.LogInformation($"楠岃瘉閫氳繃 - 閿佸畾ID: {lockInfo.Id}, 鍒嗛厤鏁伴噺: {lockInfo.AssignQuantity}, 宸叉嫞閫�: {lockInfo.PickedQty}");
+                _logger.LogInformation($"搴撳瓨淇℃伅 - 鏉$爜: {stockDetail.Barcode}, 搴撳瓨鏁伴噺: {stockDetail.StockQuantity}, 鍑哄簱鏁伴噺: {stockDetail.OutboundQuantity}");
 
-                // 2. 鎵ц鍒嗘嫞閫昏緫
+
+                decimal originalStockQtyBeforeSplit = stockDetail.StockQuantity;
+                decimal originalOutboundQtyBeforeSplit = stockDetail.OutboundQuantity;
+
+                // 璁板綍鎷嗗寘鍓嶇殑鍏抽敭鏁版嵁锛堢敤浜庡悗缁獙璇侊級
+                decimal originalAllocatedQty = orderDetail.AllocatedQuantity;
+                decimal originalLockQty = orderDetail.LockQuantity;
+                decimal originalStockQty = stockDetail.StockQuantity;
+                decimal originalOutboundQty = stockDetail.OutboundQuantity;
+
+                // 妫�鏌ユ槸鍚﹂渶瑕佽嚜鍔ㄦ媶鍖�
+                var autoSplitResult = await CheckAndAutoSplitIfNeeded(lockInfo, stockDetail, palletCode);
+                if (autoSplitResult != null)
+                {
+                    _logger.LogInformation($"鎵ц浜嗚嚜鍔ㄦ媶鍖咃紝閲嶆柊鑾峰彇鏁版嵁");
+
+                    // 閲嶆柊鑾峰彇鏈�鏂扮殑閿佸畾淇℃伅鍜屽簱瀛樹俊鎭�
+                    var refreshedValidation = await ValidatePickingRequest(orderNo, palletCode, barcode);
+                    if (!refreshedValidation.IsValid)
+                    {
+                        _unitOfWorkManage.RollbackTran();
+                        return WebResponseContent.Instance.Error(refreshedValidation.ErrorMessage);
+                    }
+
+                    (lockInfo, orderDetail, stockDetail, batch) = refreshedValidation.Data;
+                                
+
+                    // 璋冪敤鑷姩鎷嗗寘鍚庨獙璇� 
+                    decimal splitQuantity =  autoSplitResult.FirstOrDefault()?.quantityTotal.ObjToDecimal()??0 ;
+                    bool autoSplitValid = await ValidateAfterAutoSplit(lockInfo, orderDetail, stockDetail, splitQuantity,originalStockQtyBeforeSplit);
+
+                    if (!autoSplitValid)
+                    {
+                        _unitOfWorkManage.RollbackTran();
+                        return WebResponseContent.Instance.Error("鑷姩鎷嗗寘鍚庢暟鎹獙璇佸け璐ワ紝璇锋鏌ョ郴缁熸棩蹇�");
+                    }
+
+                    _logger.LogInformation($"鑷姩鎷嗗寘楠岃瘉閫氳繃锛岀户缁墽琛屽垎鎷�");
+                }
+
+                // 璁$畻瀹為檯鎷i�夋暟閲�
+                decimal actualPickedQty = lockInfo.AssignQuantity - lockInfo.PickedQty;
+
+                if (actualPickedQty <= 0)
+                {
+                    _unitOfWorkManage.RollbackTran();
+                    return WebResponseContent.Instance.Error("璇ユ潯鐮佸凡鎷i�夊畬鎴愶紝鏃犻渶閲嶅鎷i��");
+                }
+
+                _logger.LogInformation($"寮�濮嬫嫞閫� - 鏁伴噺: {actualPickedQty}");
+
+                // 鎵ц鍒嗘嫞閫昏緫
                 var pickingResult = await ExecutePickingLogic(lockInfo, orderDetail, stockDetail, actualPickedQty);
 
-                // 3. 鏇存柊鎵规鍜岃鍗曟暟鎹�
+                // 鏇存柊鎵规鍜岃鍗曟暟鎹�
                 await UpdateBatchAndOrderData(batch, orderDetail, actualPickedQty, orderNo);
 
-                // 4. 璁板綍鎷i�夊巻鍙�
+                //璁板綍鎷i�夊巻鍙�
                 await RecordPickingHistory(pickingResult, orderNo, palletCode);
+
+                // 鎷i�夊悗楠岃瘉
+                await ValidateAfterPicking(orderNo, palletCode, barcode, actualPickedQty);
 
                 _unitOfWorkManage.CommitTran();
 
-                return WebResponseContent.Instance.OK("鍒嗘嫞鎴愬姛", new
-                {
-                    PickedQuantity = actualPickedQty,
-                    Barcode = barcode,
-                    MaterialCode = lockInfo.MaterielCode
-                });
+                return WebResponseContent.Instance.OK("鍒嗘嫞鎴愬姛", autoSplitResult);
             }
             catch (Exception ex)
             {
@@ -446,6 +348,258 @@
                 return WebResponseContent.Instance.Error($"鍒嗘嫞澶辫触锛歿ex.Message}");
             }
         }
+
+
+        /// <summary>
+        /// 鑷姩鎷嗗寘鍚庨獙璇佹暟鎹竴鑷存��
+        /// </summary>
+        private async Task<bool> ValidateAfterAutoSplit(Dt_OutStockLockInfo lockInfo, Dt_OutboundOrderDetail orderDetail,
+            Dt_StockInfoDetail originalStockDetail, decimal splitQuantity, decimal originalStockQtyBeforeSplit)
+        {
+            try
+            {
+                _logger.LogInformation($"寮�濮嬭嚜鍔ㄦ媶鍖呭悗楠岃瘉 - 鍘熸潯鐮�: {originalStockDetail.Barcode}, 鎷嗗寘鏁伴噺: {splitQuantity}");
+                _logger.LogInformation($"鎷嗗寘鍓嶅師搴撳瓨鏁伴噺: {originalStockQtyBeforeSplit}, 鍒嗛厤鏁伴噺: {lockInfo.AssignQuantity}");
+
+                bool allValid = true;
+                List<string> validationErrors = new List<string>();
+
+                // 閲嶆柊鑾峰彇鏈�鏂扮殑鏁版嵁锛堟媶鍖呭悗鐨勫綋鍓嶇姸鎬侊級
+                var refreshedOrderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
+                    .FirstAsync(x => x.Id == orderDetail.Id);
+
+                var refreshedLockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                    .FirstAsync(x => x.Id == lockInfo.Id);
+
+                var refreshedStockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                    .FirstAsync(x => x.Id == originalStockDetail.Id);
+
+                // 楠岃瘉鍘熷簱瀛樻槑缁嗘暟鎹�
+                decimal expectedOriginalStockQty = lockInfo.AssignQuantity;
+
+                _logger.LogInformation($"搴撳瓨楠岃瘉鍩哄噯:");
+                _logger.LogInformation($"  鎷嗗寘鍓嶅師搴撳瓨: {originalStockQtyBeforeSplit}");
+                _logger.LogInformation($"  鍒嗛厤鏁伴噺: {lockInfo.AssignQuantity}");
+                _logger.LogInformation($"  鎷嗗寘鏁伴噺: {splitQuantity}");
+                _logger.LogInformation($"  鏈熸湜鍘熷簱瀛�: {expectedOriginalStockQty}");
+                _logger.LogInformation($"  瀹為檯鍘熷簱瀛�: {refreshedStockDetail.StockQuantity}");
+
+                // 鍏佽灏戦噺璇樊鐨勯獙璇�
+                if (Math.Abs(refreshedStockDetail.StockQuantity - expectedOriginalStockQty) > 0.01m)
+                {
+                    // 棰濆妫�鏌ワ細濡傛灉鍘熷簱瀛樻暟閲忎笉鍚堢悊锛屽彲鑳芥槸鏁版嵁闂
+                    if (refreshedStockDetail.StockQuantity < 0)
+                    {
+                        string error = $"鍘熷簱瀛樻暟閲忓紓甯革紙璐熸暟锛夛紒瀹為檯: {refreshedStockDetail.StockQuantity}";
+                        validationErrors.Add(error);
+                        allValid = false;
+                        _logger.LogError(error);
+                    }
+                    else if (refreshedStockDetail.StockQuantity > originalStockQtyBeforeSplit)
+                    {
+                        string error = $"鍘熷簱瀛樻暟閲忓紓甯革紙澶т簬鎷嗗寘鍓嶏級锛佹媶鍖呭墠: {originalStockQtyBeforeSplit}, 褰撳墠: {refreshedStockDetail.StockQuantity}";
+                        validationErrors.Add(error);
+                        allValid = false;
+                        _logger.LogError(error);
+                    }
+                    else
+                    {
+                        // 鍙兘鏄悎鐞嗙殑璇樊锛岃褰曡鍛婁絾涓嶆爣璁颁负澶辫触
+                        _logger.LogWarning($"鍘熷簱瀛樻暟閲忎笌鏈熸湜鍊兼湁宸紓锛屾湡鏈�: {expectedOriginalStockQty}, 瀹為檯: {refreshedStockDetail.StockQuantity}");
+                    }
+                }
+
+                // 楠岃瘉鍘熷簱瀛樼殑鍑哄簱鏁伴噺鏄惁淇濇寔涓嶅彉
+                if (Math.Abs(refreshedStockDetail.OutboundQuantity - originalStockDetail.OutboundQuantity) > 0.01m)
+                {
+                    string error = $"鍘熷簱瀛樺嚭搴撴暟閲忎笉搴斿彉鍖栵紒鎷嗗寘鍓�: {originalStockDetail.OutboundQuantity}, 鎷嗗寘鍚�: {refreshedStockDetail.OutboundQuantity}";
+                    validationErrors.Add(error);
+                    allValid = false;
+                    _logger.LogError(error);
+                }
+
+                // 楠岃瘉鏂板簱瀛樻槑缁嗭紙鎷嗗寘浜х敓鐨勶級
+                // 鏌ユ壘鏂版潯鐮侊紙閫氳繃鎷嗗寘璁板綍锛�
+                var splitRecords = await _splitPackageService.Db.Queryable<Dt_SplitPackageRecord>()
+                    .Where(x => x.OutStockLockInfoId == lockInfo.Id &&
+                               !x.IsReverted &&
+                               x.IsAutoSplit == true)
+                    .OrderByDescending(x => x.SplitTime)
+                    .ToListAsync();
+
+                if (splitRecords.Any())
+                {
+                    var latestSplit = splitRecords.First();
+                    if (!string.IsNullOrEmpty(latestSplit.NewBarcode))
+                    {
+                        var newStockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                            .FirstAsync(x => x.Barcode == latestSplit.NewBarcode && x.StockId == originalStockDetail.StockId);
+
+                        if (newStockDetail != null)
+                        {
+                            // 鏂板簱瀛樼殑鏈熸湜鍊� = 鎷嗗寘鏁伴噺
+                            decimal expectedNewStockQty = splitQuantity;
+
+                            _logger.LogInformation($"鏂板簱瀛橀獙璇�:");
+                            _logger.LogInformation($"  鏂版潯鐮�: {newStockDetail.Barcode}");
+                            _logger.LogInformation($"  鏈熸湜鏁伴噺: {expectedNewStockQty}");
+                            _logger.LogInformation($"  瀹為檯鏁伴噺: {newStockDetail.StockQuantity}");
+                            _logger.LogInformation($"  鍑哄簱鏁伴噺: {newStockDetail.OutboundQuantity} (搴斾负0)");
+
+                            if (Math.Abs(newStockDetail.StockQuantity - expectedNewStockQty) > 0.01m)
+                            {
+                                string error = $"鏂板簱瀛樻暟閲忎笉姝g‘锛佹湡鏈�: {expectedNewStockQty}, 瀹為檯: {newStockDetail.StockQuantity}";
+                                validationErrors.Add(error);
+                                allValid = false;
+                                _logger.LogError(error);
+                            }
+
+                            // 鏂板簱瀛樺嚭搴撴暟閲忓簲涓�0
+                            if (Math.Abs(newStockDetail.OutboundQuantity - 0) > 0.01m)
+                            {
+                                string error = $"鏂板簱瀛樺嚭搴撴暟閲忎笉涓�0锛佸疄闄�: {newStockDetail.OutboundQuantity}";
+                                validationErrors.Add(error);
+                                allValid = false;
+                                _logger.LogError(error);
+                            }
+                        }
+                    }
+                }
+
+                // 4. 楠岃瘉鏈垎閰嶉攣瀹氳褰�
+                var unallocatedLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                    .Where(x => x.ParentLockId == lockInfo.Id &&
+                               x.IsUnallocated == 1 &&
+                               x.OrderDetailId == 0)
+                    .ToListAsync();
+
+                if (!unallocatedLocks.Any())
+                {
+                    string error = $"鏈壘鍒拌嚜鍔ㄦ媶鍖呭垱寤虹殑鏈垎閰嶉攣瀹氳褰�";
+                    validationErrors.Add(error);
+                    allValid = false;
+                    _logger.LogError(error);
+                }
+
+                // 楠岃瘉璁㈠崟鏄庣粏鏁版嵁鏈敼鍙�
+                if (Math.Abs(refreshedOrderDetail.AllocatedQuantity - orderDetail.AllocatedQuantity) > 0.01m)
+                {
+                    string error = $"璁㈠崟鏄庣粏鍒嗛厤鏁伴噺寮傚父鍙樺寲锛佹媶鍖呭墠: {orderDetail.AllocatedQuantity}, 鎷嗗寘鍚�: {refreshedOrderDetail.AllocatedQuantity}";
+                    validationErrors.Add(error);
+                    allValid = false;
+                    _logger.LogError(error);
+                }
+
+                // 楠岃瘉鍘熼攣瀹氳褰曟暟鎹湭鏀瑰彉锛堝垎閰嶆暟閲忎笉鍙橈級
+                if (Math.Abs(refreshedLockInfo.AssignQuantity - lockInfo.AssignQuantity) > 0.01m)
+                {
+                    string error = $"閿佸畾璁板綍鍒嗛厤鏁伴噺寮傚父鍙樺寲锛佹媶鍖呭墠: {lockInfo.AssignQuantity}, 鎷嗗寘鍚�: {refreshedLockInfo.AssignQuantity}";
+                    validationErrors.Add(error);
+                    allValid = false;
+                    _logger.LogError(error);
+                }
+
+                // 鏂板銆戦獙璇佹�诲簱瀛樺畧鎭�
+                // 鎷嗗寘鍓嶆�诲簱瀛� = 鍘熷簱瀛樻暟閲�
+                // 鎷嗗寘鍚庢�诲簱瀛� = 鍘熷簱瀛樼幇鏈夋暟閲� + 鏂板簱瀛樻暟閲�
+                decimal totalStockAfterSplit = refreshedStockDetail.StockQuantity;
+                if (splitRecords.Any() && !string.IsNullOrEmpty(splitRecords.First().NewBarcode))
+                {
+                    var newStock = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                        .FirstAsync(x => x.Barcode == splitRecords.First().NewBarcode);
+                    if (newStock != null)
+                    {
+                        totalStockAfterSplit += newStock.StockQuantity;
+                    }
+                }
+
+                _logger.LogInformation($"搴撳瓨瀹堟亽楠岃瘉:");
+                _logger.LogInformation($"  鎷嗗寘鍓嶆�诲簱瀛�: {originalStockQtyBeforeSplit}");
+                _logger.LogInformation($"  鎷嗗寘鍚庢�诲簱瀛�: {totalStockAfterSplit}");
+                _logger.LogInformation($"  宸紓: {originalStockQtyBeforeSplit - totalStockAfterSplit}");
+
+                // 鍏佽寰堝皬鐨勬诞鐐规暟璇樊
+                if (Math.Abs(originalStockQtyBeforeSplit - totalStockAfterSplit) > 0.02m)
+                {
+                    string error = $"搴撳瓨涓嶅畧鎭掞紒鎷嗗寘鍓�: {originalStockQtyBeforeSplit}, 鎷嗗寘鍚庢�诲簱瀛�: {totalStockAfterSplit}";
+                    validationErrors.Add(error);
+                    allValid = false;
+                    _logger.LogError(error);
+                }
+
+                // 姹囨�婚獙璇佺粨鏋�
+                if (allValid)
+                {
+                    _logger.LogInformation($"鉁� 鑷姩鎷嗗寘鍚庨獙璇佸叏閮ㄩ�氳繃");
+                }
+                else
+                {
+                    string errorSummary = $"鑷姩鎷嗗寘鍚庨獙璇佸け璐ワ紝鍙戠幇{validationErrors.Count}涓棶棰橈細" +
+                                         string.Join("; ", validationErrors.Take(3));
+                    _logger.LogError(errorSummary);
+
+                    // 璁板綍璇︾粏闂鍒版棩蹇�
+                    for (int i = 0; i < validationErrors.Count; i++)
+                    {
+                        _logger.LogError($"闂{i + 1}: {validationErrors[i]}");
+                    }
+                }
+
+                return allValid;
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"鑷姩鎷嗗寘鍚庨獙璇佸紓甯�: {ex.Message}");
+                return false;
+            }
+        }
+
+
+        /// <summary>
+        /// 鎷i�夊悗楠岃瘉
+        /// </summary>
+        private async Task ValidateAfterPicking(string orderNo, string palletCode, string barcode, decimal pickedQty)
+        {
+            try
+            {
+                _logger.LogInformation($"寮�濮嬫嫞閫夊悗楠岃瘉");
+
+                // 楠岃瘉搴撳瓨鏄庣粏
+                var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                    .FirstAsync(x => x.Barcode == barcode);
+
+                // 鏌ユ壘璇ユ潯鐮佺殑鎵�鏈夋嫞閫夎褰�
+                var pickingRecords = await Db.Queryable<Dt_PickingRecord>()
+                    .Where(x => x.Barcode == barcode && x.OrderNo == orderNo && !x.IsCancelled)
+                    .ToListAsync();
+
+                decimal totalPickedFromRecords = pickingRecords.Sum(x => x.PickQuantity);
+
+                _logger.LogInformation($"鎷i�夐獙璇� - 鏉$爜: {barcode}");
+                _logger.LogInformation($"  搴撳瓨鍑哄簱鏁伴噺: {stockDetail.OutboundQuantity}");
+                _logger.LogInformation($"  鎷i�夎褰曟�诲拰: {totalPickedFromRecords}");
+
+                if (Math.Abs(stockDetail.OutboundQuantity - totalPickedFromRecords) > 0.01m)
+                {
+                    _logger.LogError($"鎷i�夋暟鎹笉涓�鑷达紒搴撳瓨鍑哄簱鏁伴噺({stockDetail.OutboundQuantity}) 鈮� 鎷i�夎褰曟�诲拰({totalPickedFromRecords})");
+
+                    // 鑷姩淇锛氫互鎷i�夎褰曟�诲拰涓哄噯
+                    decimal originalOutbound = stockDetail.OutboundQuantity;
+                    stockDetail.OutboundQuantity = totalPickedFromRecords;
+                    await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+
+                    _logger.LogWarning($"宸茶嚜鍔ㄤ慨澶嶅嚭搴撴暟閲�: {originalOutbound} -> {totalPickedFromRecords}");
+                }
+
+                _logger.LogInformation($"鎷i�夊悗楠岃瘉瀹屾垚");
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"鎷i�夊悗楠岃瘉澶辫触: {ex.Message}");
+            }
+        }
+
+
         /// <summary>
         /// 鍙栨秷鍒嗘嫞
         /// </summary>
@@ -492,7 +646,165 @@
         }
         #endregion
 
-        #region 鎵嬪姩鎷嗗寘
+
+        #region 鍙栬蛋绌虹閫昏緫
+         /// <summary>
+        /// 娓呯悊搴撳瓨淇℃伅 - 瀹屾暣淇鐗�
+        /// 纭繚OutboundQuantity姝g‘娓呴浂
+        /// </summary>
+        private async Task CleanupStockInfo(Dt_OutStockLockInfo lockInfo)
+        {
+            try
+            {
+                _logger.LogInformation($"娓呯悊搴撳瓨淇℃伅 - 閿佸畾ID: {lockInfo.Id}, 鏉$爜: {lockInfo.CurrentBarcode}");
+
+                // 鏌ユ壘閿佸畾鐨勫簱瀛樻槑缁�
+                var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                    .FirstAsync(x => x.Barcode == lockInfo.CurrentBarcode && x.StockId == lockInfo.StockId);
+
+                if (stockDetail != null)
+                {
+                    // 璁板綍娓呯悊鍓嶇殑鐘舵��
+                    decimal originalStockQty = stockDetail.StockQuantity;
+                    decimal originalOutboundQty = stockDetail.OutboundQuantity;
+                    int originalStatus = stockDetail.Status;
+
+                    _logger.LogInformation($"娓呯悊鍓嶇姸鎬� - 搴撳瓨: {originalStockQty}, 鍑哄簱: {originalOutboundQty}, 鐘舵��: {GetStockStatusName(originalStatus)}");
+
+                    // 銆愰噸瑕併�戞鏌ュ簱瀛樻暟閲忔槸鍚﹀簲璇ヤ负0
+                    if (lockInfo.Status == (int)OutLockStockStatusEnum.鎷i�夊畬鎴�)
+                    {
+                        if (stockDetail.StockQuantity > 0)
+                        {
+                            _logger.LogWarning($"鎷i�夊畬鎴愪絾搴撳瓨涓嶄负0 - 鏉$爜: {stockDetail.Barcode}, 搴撳瓨: {stockDetail.StockQuantity}");
+                        }
+                    }
+
+                    // 娓呯悊搴撳瓨鍜屽嚭搴撴暟閲�
+                    stockDetail.StockQuantity = 0;
+                    stockDetail.OutboundQuantity = 0; 
+                    stockDetail.Status = (int)StockStatusEmun.宸叉竻鐞�;
+
+                    await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+
+                    _logger.LogInformation($"娓呯悊搴撳瓨鏄庣粏瀹屾垚");
+                    _logger.LogInformation($"  搴撳瓨鏁伴噺: {originalStockQty} -> 0");
+                    _logger.LogInformation($"  鍑哄簱鏁伴噺: {originalOutboundQty} -> 0");
+                    _logger.LogInformation($"  鐘舵��: {GetStockStatusName(originalStatus)} -> 宸叉竻鐞�");
+                }
+                else
+                {
+                    _logger.LogWarning($"鏈壘鍒版潯鐮佸搴旂殑搴撳瓨鏄庣粏: {lockInfo.CurrentBarcode}");
+                }
+
+                // 娓呯悊璇ユ墭鐩樹笂鐨勬墍鏈夊簱瀛橈紙閬垮厤閬楁紡锛�
+                var allStockDetails = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                    .Where(x => x.StockId == lockInfo.StockId && x.StockQuantity > 0)
+                    .ToListAsync();
+
+                if (allStockDetails.Any())
+                {
+                    _logger.LogInformation($"娓呯悊鎵樼洏涓婂叾浠栧簱瀛� - 鍏� {allStockDetails.Count} 鏉¤褰�");
+
+                    foreach (var stock in allStockDetails)
+                    {
+                        decimal originalQty = stock.StockQuantity;
+                        decimal originalOutbound = stock.OutboundQuantity;
+
+                        stock.StockQuantity = 0;
+                        stock.OutboundQuantity = 0;  
+                        stock.Status = (int)StockStatusEmun.宸叉竻鐞�;
+
+                        await _stockInfoDetailService.Db.Updateable(stock).ExecuteCommandAsync();
+                        _logger.LogInformation($"娓呯悊閬楁紡搴撳瓨 - 鏉$爜: {stock.Barcode}, 搴撳瓨: {originalQty}->0, 鍑哄簱: {originalOutbound}->0");
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"娓呯悊搴撳瓨淇℃伅澶辫触 - 閿佸畾ID: {lockInfo.Id}, 鏉$爜: {lockInfo.CurrentBarcode}, Error: {ex.Message}");
+                // 涓嶆姏鍑哄紓甯革紝缁х画澶勭悊鍏朵粬璁板綍
+            }
+        }
+
+        /// <summary>
+        /// 鏇存柊璁㈠崟鐘舵��
+        /// </summary>
+        private async Task UpdateOrderStatusAfterPalletRemoval(string orderNo)
+        {
+            // 妫�鏌ヨ鍗曟槸鍚︽墍鏈夋墭鐩橀兘宸插畬鎴�
+            var allLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                .Where(x => x.OrderNo == orderNo)
+                .ToListAsync();
+
+            var unfinishedPallets = allLocks
+                .GroupBy(x => x.PalletCode)
+                .Where(g => g.Any(x => x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓� ||
+                                      x.Status == (int)OutLockStockStatusEnum.鍥炲簱涓�))
+                .ToList();
+
+            // 濡傛灉娌℃湁鏈畬鎴愮殑鎵樼洏锛屾洿鏂拌鍗曠姸鎬佷负鍑哄簱瀹屾垚
+            if (!unfinishedPallets.Any())
+            {
+                await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
+                    .SetColumns(x => new Dt_OutboundOrder
+                    {
+                        OrderStatus = (int)OutOrderStatusEnum.鍑哄簱瀹屾垚,
+                    })
+                    .Where(x => x.OrderNo == orderNo)
+                    .ExecuteCommandAsync();
+            }
+        }
+
+        /// <summary>
+        /// 璁板綍绌虹鍙栬蛋鍘嗗彶
+        /// </summary>
+        private async Task RecordEmptyPalletRemoval(string orderNo, string palletCode, List<Dt_OutStockLockInfo> completedLocks)
+        {
+            //var removalRecord = new Dt_EmptyPalletRemoval
+            //{
+            //    OrderNo = orderNo,
+            //    PalletCode = palletCode,
+            //    RemovalTime = DateTime.Now,
+            //    Operator = App.User.UserName,
+            //    CompletedItemsCount = completedLocks.Count,
+            //    TotalPickedQuantity = completedLocks.Sum(x => x.PickedQty)
+            //};
+
+            //await Db.Insertable(removalRecord).ExecuteCommandAsync();
+        }
+
+        #endregion
+
+        private List<SplitResult> CreateSplitResults(Dt_OutStockLockInfo lockInfo, decimal splitQty, decimal remainQty, string newBarcode, string originalBarcode)
+        {
+            return new List<SplitResult>
+        {
+            new SplitResult
+            {
+                materialCode = lockInfo.MaterielCode,
+                supplierCode = lockInfo.SupplyCode,
+                quantityTotal = splitQty.ToString("F2"),
+                batchNumber = newBarcode,
+                batch = lockInfo.BatchNo,
+                factory = lockInfo.FactoryArea,
+                date = DateTime.Now.ToString("yyyy-MM-dd"),
+            },
+            new SplitResult
+            {
+                materialCode = lockInfo.MaterielCode,
+                supplierCode = lockInfo.SupplyCode,
+                quantityTotal = remainQty.ToString("F2"),
+                batchNumber = originalBarcode,
+                batch = lockInfo.BatchNo,
+                factory = lockInfo.FactoryArea,
+                date = DateTime.Now.ToString("yyyy-MM-dd"),
+            }
+        };
+        }
+
+
+        #region 鎵嬪姩鎷嗗寘   
 
         /// <summary>
         /// 鎵嬪姩鎷嗗寘
@@ -503,24 +815,19 @@
             {
                 _unitOfWorkManage.BeginTran();
 
-                //  楠岃瘉鎷嗗寘璇锋眰
+                // 楠岃瘉鎷嗗寘璇锋眰
                 var validationResult = await ValidateSplitRequest(orderNo, palletCode, originalBarcode, splitQuantity);
                 if (!validationResult.IsValid)
                     return WebResponseContent.Instance.Error(validationResult.ErrorMessage);
 
                 var (lockInfo, stockDetail) = validationResult.Data;
 
-                // . 鎵ц鎷嗗寘閫昏緫
-                var splitResult = await ExecuteSplitLogic(lockInfo, stockDetail, splitQuantity, palletCode);
+                // 鎵ц鎷嗗寘閫昏緫
+                var splitResult = await ExecuteManualSplitLogic(lockInfo, stockDetail, splitQuantity, palletCode);
 
                 _unitOfWorkManage.CommitTran();
 
-                return WebResponseContent.Instance.OK("鎵嬪姩鎷嗗寘鎴愬姛", new
-                {
-                    NewBarcode = splitResult.NewBarcode,
-                    OriginalBarcode = originalBarcode,
-                    SplitQuantity = splitQuantity
-                });
+                return WebResponseContent.Instance.OK("鎵嬪姩鎷嗗寘鎴愬姛", splitResult);
             }
             catch (Exception ex)
             {
@@ -530,9 +837,302 @@
             }
         }
 
-        #endregion
+        /// <summary>
+        /// 楠岃瘉鎷嗗寘璇锋眰 - 澧炲己鍒嗛厤鏁伴噺鎺у埗
+        /// </summary>
+        private async Task<ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>> ValidateSplitRequest(
+            string orderNo, string palletCode, string originalBarcode, decimal splitQuantity)
+        {
+            _logger.LogInformation($"寮�濮嬮獙璇佹媶鍖呰姹� - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}, 鍘熸潯鐮�: {originalBarcode}, 鎷嗗寘鏁伴噺: {splitQuantity}");
 
- 
+            // 鏌ユ壘閿佸畾淇℃伅
+            var lockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                .Where(x => x.OrderNo == orderNo &&
+                           x.PalletCode == palletCode &&
+                           x.CurrentBarcode == originalBarcode &&
+                           x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�)
+                .FirstAsync();
+
+            if (lockInfo == null)
+            {
+                _logger.LogWarning($"鏈壘鍒版湁鏁堢殑閿佸畾淇℃伅 - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}, 鏉$爜: {originalBarcode}");
+                return ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error("鏈壘鍒版湁鏁堢殑閿佸畾淇℃伅");
+            }
+
+            _logger.LogInformation($"鎵惧埌閿佸畾淇℃伅 - 鍒嗛厤鏁伴噺: {lockInfo.AssignQuantity}, 宸叉嫞閫�: {lockInfo.PickedQty}, 璁㈠崟鏁伴噺: {lockInfo.OrderQuantity}");
+
+            // 鑾峰彇璁㈠崟鏄庣粏
+            var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
+                .FirstAsync(x => x.Id == lockInfo.OrderDetailId);
+
+            if (orderDetail == null)
+            {
+                _logger.LogWarning($"鏈壘鍒拌鍗曟槑缁� - OrderDetailId: {lockInfo.OrderDetailId}");
+                return ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error("鏈壘鍒拌鍗曟槑缁�");
+            }
+
+            _logger.LogInformation($"鎵惧埌璁㈠崟鏄庣粏 - 宸插垎閰嶆暟閲�: {orderDetail.AllocatedQuantity}, 閿佸畾鏁伴噺: {orderDetail.LockQuantity}");
+
+            // 鑾峰彇搴撳瓨淇℃伅
+            var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                .FirstAsync(x => x.Barcode == originalBarcode && x.StockId == lockInfo.StockId);
+
+            if (stockDetail == null)
+            {
+                _logger.LogWarning($"鏈壘鍒板簱瀛樹俊鎭� - 鏉$爜: {originalBarcode}, StockId: {lockInfo.StockId}");
+                return ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error("鏈壘鍒板搴旂殑搴撳瓨淇℃伅");
+            }
+
+            _logger.LogInformation($"鎵惧埌搴撳瓨淇℃伅 - 搴撳瓨鏁伴噺: {stockDetail.StockQuantity}, 鍑哄簱鏁伴噺: {stockDetail.OutboundQuantity}");
+
+            // 楠岃瘉鎷嗗寘鏁伴噺涓嶈兘澶т簬搴撳瓨鏁伴噺
+            if (stockDetail.StockQuantity < splitQuantity)
+            {
+                _logger.LogWarning($"鎷嗗寘鏁伴噺澶т簬搴撳瓨鏁伴噺 - 鎷嗗寘鏁伴噺: {splitQuantity}, 搴撳瓨鏁伴噺: {stockDetail.StockQuantity}");
+                return ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error($"鎷嗗寘鏁伴噺涓嶈兘澶т簬搴撳瓨鏁伴噺锛屽綋鍓嶅簱瀛橈細{stockDetail.StockQuantity}");
+            }
+
+            // 楠岃瘉鎷嗗寘鏁伴噺涓嶈兘澶т簬閿佸畾淇℃伅鐨勫垎閰嶆暟閲�
+            if (lockInfo.AssignQuantity < splitQuantity)
+            {
+                _logger.LogWarning($"鎷嗗寘鏁伴噺澶т簬鍒嗛厤鏁伴噺 - 鎷嗗寘鏁伴噺: {splitQuantity}, 鍒嗛厤鏁伴噺: {lockInfo.AssignQuantity}");
+                return ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error($"鎷嗗寘鏁伴噺涓嶈兘澶т簬鍒嗛厤鏁伴噺锛屽綋鍓嶅垎閰嶆暟閲忥細{lockInfo.AssignQuantity}");
+            }
+
+            // 楠岃瘉鎷嗗寘鏁伴噺涓嶈兘澶т簬閿佸畾淇℃伅鐨勬湭鎷i�夋暟閲�
+            decimal remainingToPick = lockInfo.AssignQuantity - lockInfo.PickedQty;
+            if (remainingToPick < splitQuantity)
+            {
+                _logger.LogWarning($"鎷嗗寘鏁伴噺澶т簬鏈嫞閫夋暟閲� - 鎷嗗寘鏁伴噺: {splitQuantity}, 鏈嫞閫夋暟閲�: {remainingToPick}");
+                return ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error($"鎷嗗寘鏁伴噺涓嶈兘澶т簬鏈嫞閫夋暟閲忥紝褰撳墠鏈嫞閫夛細{remainingToPick}");
+            }
+
+            // 楠岃瘉鎷嗗寘鍚庡師閿佸畾淇℃伅鐨勫垎閰嶆暟閲忎笉浼氫负璐熸暟
+            if (lockInfo.AssignQuantity - splitQuantity < 0)
+            {
+                _logger.LogWarning($"鎷嗗寘鍚庡垎閰嶆暟閲忎负璐熸暟 - 褰撳墠鍒嗛厤鏁伴噺: {lockInfo.AssignQuantity}, 鎷嗗寘鏁伴噺: {splitQuantity}");
+                return ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error($"鎷嗗寘鍚庡垎閰嶆暟閲忎笉鑳戒负璐熸暟");
+            }
+
+            // 楠岃瘉璁㈠崟鏄庣粏鐨勫垎閰嶆暟閲忔槸鍚﹁冻澶�
+            // 娉ㄦ剰锛氭墜鍔ㄦ媶鍖呬笉浼氭敼鍙樿鍗曟槑缁嗙殑鍒嗛厤鏁伴噺锛屽洜涓烘�诲垎閰嶆暟閲忎笉鍙�
+            // 鍙槸浠庝竴涓攣瀹氫俊鎭浆绉诲埌鍙︿竴涓攣瀹氫俊鎭�
+            decimal totalLockAssignQuantity = await GetTotalLockAssignQuantity(orderDetail.Id);
+            if (orderDetail.AllocatedQuantity != totalLockAssignQuantity)
+            {
+                _logger.LogWarning($"璁㈠崟鏄庣粏鍒嗛厤鏁伴噺涓庨攣瀹氫俊鎭笉涓�鑷� - 璁㈠崟鏄庣粏鍒嗛厤鏁伴噺: {orderDetail.AllocatedQuantity}, 閿佸畾淇℃伅鎬诲垎閰嶆暟閲�: {totalLockAssignQuantity}");
+            }
+
+            _logger.LogInformation($"鎷嗗寘楠岃瘉閫氳繃 - 鍘熸潯鐮�: {originalBarcode}, 鎷嗗寘鏁伴噺: {splitQuantity}");
+
+            return ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Success((lockInfo, stockDetail));
+        }
+
+        /// <summary>
+        /// 鑾峰彇璁㈠崟鏄庣粏鐨勬墍鏈夐攣瀹氫俊鎭殑鎬诲垎閰嶆暟閲�
+        /// </summary>
+        private async Task<decimal> GetTotalLockAssignQuantity(long orderDetailId)
+        {
+            var lockInfos = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                .Where(x => x.OrderDetailId == orderDetailId)
+                .ToListAsync();
+
+            return lockInfos.Sum(x => x.AssignQuantity);
+        }
+
+
+
+        /// <summary>
+        /// 鎵ц鎵嬪姩鎷嗗寘閫昏緫 
+        /// </summary>
+        private async Task<List<SplitResult>> ExecuteManualSplitLogic(Dt_OutStockLockInfo lockInfo, Dt_StockInfoDetail stockDetail,
+            decimal splitQuantity, string palletCode)
+        {
+            _logger.LogInformation($"寮�濮嬫墽琛屾墜鍔ㄦ媶鍖呴�昏緫 - 鍘熸潯鐮�: {stockDetail.Barcode}, 鎷嗗寘鏁伴噺: {splitQuantity}");
+
+            try
+            {
+                // 楠岃瘉搴撳瓨鏁伴噺鏄惁瓒冲
+                decimal availableStock = stockDetail.StockQuantity;
+                if (availableStock < splitQuantity)
+                {
+                    throw new InvalidOperationException($"搴撳瓨涓嶈冻锛屽綋鍓嶅簱瀛�: {availableStock}, 闇�瑕佹媶鍖�: {splitQuantity}");
+                }
+
+                // 楠岃瘉鎷嗗寘鏁伴噺涓嶈兘绛変簬鎴栧ぇ浜庡師閿佸畾淇℃伅鍒嗛厤鏁伴噺
+                if (splitQuantity >= lockInfo.AssignQuantity)
+                {
+                    throw new InvalidOperationException($"鎷嗗寘鏁伴噺涓嶈兘绛変簬鎴栧ぇ浜庡師閿佸畾淇℃伅鍒嗛厤鏁伴噺锛屾媶鍖呮暟閲�: {splitQuantity}, 鍘熷垎閰嶆暟閲�: {lockInfo.AssignQuantity}");
+                }
+
+                // 璁$畻鍓╀綑鏁伴噺
+                decimal remainQty = lockInfo.AssignQuantity - splitQuantity;
+
+                // 楠岃瘉鍓╀綑鏁伴噺鏄惁鍚堢悊
+                if (remainQty <= 0)
+                {
+                    throw new InvalidOperationException($"鎷嗗寘鍚庡墿浣欐暟閲忓繀椤诲ぇ浜�0锛屽綋鍓嶅墿浣�: {remainQty}");
+                }
+
+                _logger.LogInformation($"鎷嗗寘璁$畻 - 鍘熷垎閰嶆暟閲�: {lockInfo.AssignQuantity}, 鎷嗗寘鏁伴噺: {splitQuantity}, 鍓╀綑鏁伴噺: {remainQty}");
+                _logger.LogInformation($"鍘熷簱瀛樹俊鎭� - 搴撳瓨鏁伴噺: {stockDetail.StockQuantity}, 鍑哄簱鏁伴噺: {stockDetail.OutboundQuantity}");
+
+                // 鐢熸垚鏂版潯鐮�
+                string newBarcode = await GenerateNewBarcode();
+                _logger.LogInformation($"鐢熸垚鏂版潯鐮�: {newBarcode}");
+
+                // 璁板綍鎷嗗寘鍓嶇殑鍏抽敭鏁版嵁
+                decimal originalLockAssignQty = lockInfo.AssignQuantity;
+                decimal originalLockOrderQty = lockInfo.OrderQuantity;
+                decimal originalStockQty = stockDetail.StockQuantity;
+                decimal originalOutboundQty = stockDetail.OutboundQuantity;
+
+                // 淇锛氳绠楁柊搴撳瓨鏄庣粏鐨勬纭暟閲�
+                // 鏂版潯鐮佸簲璇ュ彧鏈夋媶鍖呮暟閲忥紝鑰屼笉鏄�2鍊�
+                decimal newStockQuantity = splitQuantity;
+                decimal originalRemainingStockQuantity = originalStockQty - splitQuantity;
+
+                _logger.LogInformation($"鏁伴噺鍒嗛厤 - 鏂版潯鐮佹暟閲�: {newStockQuantity}, 鍘熸潯鐮佸墿浣欐暟閲�: {originalRemainingStockQuantity}");
+
+                // 鍒涘缓鏂板簱瀛樻槑缁� - 淇鏁伴噺闂
+                var newStockDetail = new Dt_StockInfoDetail
+                {
+                    StockId = stockDetail.StockId,
+                    MaterielCode = stockDetail.MaterielCode,
+                    OrderNo = stockDetail.OrderNo,
+                    BatchNo = stockDetail.BatchNo,
+                    StockQuantity = newStockQuantity,   
+                    OutboundQuantity = 0,   
+                    Barcode = newBarcode,
+                    Status = (int)StockStatusEmun.鍑哄簱閿佸畾,
+                    SupplyCode = stockDetail.SupplyCode,
+                    Unit = stockDetail.Unit,
+                    BarcodeQty = stockDetail.BarcodeQty,
+                    BarcodeUnit = stockDetail.BarcodeUnit,
+                    BusinessType = stockDetail.BusinessType,
+                    InboundOrderRowNo = stockDetail.InboundOrderRowNo,
+                    FactoryArea = stockDetail.FactoryArea,
+                    WarehouseCode = stockDetail.WarehouseCode,
+                };
+
+                await _stockInfoDetailService.Db.Insertable(newStockDetail).ExecuteCommandAsync();
+                _logger.LogInformation($"鍒涘缓鏂板簱瀛樻槑缁嗘垚鍔� - 鏉$爜: {newBarcode}, 搴撳瓨鏁伴噺: {newStockQuantity}");
+
+                // 鏇存柊鍘熷簱瀛樻槑缁� 
+                stockDetail.StockQuantity = originalRemainingStockQuantity;
+
+                // 纭繚涓嶄細涓鸿礋鏁�
+                if (stockDetail.StockQuantity < 0)
+                {
+                    _logger.LogWarning($"鍘熷簱瀛樻暟閲忓嚭鐜拌礋鏁帮紝閲嶇疆涓�0");
+                    stockDetail.StockQuantity = 0;
+                }             
+
+                await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+                _logger.LogInformation($"鏇存柊鍘熷簱瀛樻槑缁� - 鏉$爜: {stockDetail.Barcode}, " +
+                                     $"搴撳瓨鏁伴噺: {originalStockQty} -> {stockDetail.StockQuantity}, " +
+                                     $"鍑哄簱鏁伴噺: {originalOutboundQty} -> {stockDetail.OutboundQuantity}");
+
+                // 鍒涘缓鏂伴攣瀹氫俊鎭�
+                var newLockInfo = new Dt_OutStockLockInfo
+                {
+                    OrderNo = lockInfo.OrderNo,
+                    OrderDetailId = lockInfo.OrderDetailId,
+                    OutboundBatchNo = lockInfo.OutboundBatchNo,
+                    MaterielCode = lockInfo.MaterielCode,
+                    MaterielName = lockInfo.MaterielName,
+                    StockId = lockInfo.StockId,
+                    OrderQuantity = splitQuantity,
+                    AssignQuantity = splitQuantity,
+                    PickedQty = 0,
+                    LocationCode = lockInfo.LocationCode,
+                    PalletCode = lockInfo.PalletCode,
+                    TaskNum = lockInfo.TaskNum,
+                    Status = (int)OutLockStockStatusEnum.鍑哄簱涓�,
+                    Unit = lockInfo.Unit,
+                    SupplyCode = lockInfo.SupplyCode,
+                    OrderType = lockInfo.OrderType,
+                    CurrentBarcode = newBarcode,
+                    IsSplitted = 1,
+                    ParentLockId = lockInfo.Id,
+                    Operator = App.User.UserName,
+                    FactoryArea = lockInfo.FactoryArea,
+                    lineNo = lockInfo.lineNo,
+                    WarehouseCode = lockInfo.WarehouseCode,
+                    BarcodeQty = lockInfo.BarcodeQty,
+                    BarcodeUnit = lockInfo.BarcodeUnit,
+                };
+
+                await _outStockLockInfoService.Db.Insertable(newLockInfo).ExecuteCommandAsync();
+                _logger.LogInformation($"鍒涘缓鏂伴攣瀹氫俊鎭垚鍔� - 鏉$爜: {newBarcode}, 鍒嗛厤鏁伴噺: {splitQuantity}");
+
+                // 鏇存柊鍘熼攣瀹氫俊鎭�
+                lockInfo.AssignQuantity = remainQty;
+                lockInfo.OrderQuantity = remainQty;
+
+                await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
+                _logger.LogInformation($"鏇存柊鍘熼攣瀹氫俊鎭� - 鍒嗛厤鏁伴噺: {originalLockAssignQty} -> {lockInfo.AssignQuantity}, " +
+                                     $"璁㈠崟鏁伴噺: {originalLockOrderQty} -> {lockInfo.OrderQuantity}");
+
+                // 楠岃瘉鎷嗗寘鍚庢暟鎹竴鑷存��
+                await ValidateDataConsistencyAfterSplit(lockInfo.OrderDetailId, originalLockAssignQty, originalLockOrderQty);
+
+                // 璁板綍鎷嗗寘鍘嗗彶
+                await RecordSplitHistory(lockInfo, stockDetail, splitQuantity, newBarcode, false, originalStockQty);
+
+                // 鍒涘缓鎷嗗寘缁撴灉鍒楄〃
+                var splitResults = CreateSplitResults(lockInfo, splitQuantity, remainQty, newBarcode, stockDetail.Barcode);
+
+                _logger.LogInformation($"鎵嬪姩鎷嗗寘閫昏緫鎵ц瀹屾垚 - 鍘熸潯鐮�: {stockDetail.Barcode}, 鏂版潯鐮�: {newBarcode}, 鎷嗗寘鏁伴噺: {splitQuantity}");
+
+                return splitResults;
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"鎵嬪姩鎷嗗寘閫昏緫鎵ц澶辫触 - 鍘熸潯鐮�: {stockDetail.Barcode}, 鎷嗗寘鏁伴噺: {splitQuantity}, Error: {ex.Message}");
+                throw;
+            }
+        }
+
+      /// <summary>
+        /// 楠岃瘉鎷嗗寘鍚庢暟鎹竴鑷存��
+        /// </summary>
+        private async Task ValidateDataConsistencyAfterSplit(long orderDetailId, decimal expectedAllocatedQty, decimal expectedLockQty)
+        {
+            // 閲嶆柊鑾峰彇璁㈠崟鏄庣粏鏁版嵁
+            var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
+                .FirstAsync(x => x.Id == orderDetailId);
+
+            if (orderDetail == null)
+                return;
+
+            // 璁$畻鎵�鏈夐攣瀹氫俊鎭殑鎬诲垎閰嶆暟閲�
+            var allLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                .Where(x => x.OrderDetailId == orderDetailId)
+                .ToListAsync();
+
+            decimal totalLockAssignQty = allLocks.Sum(x => x.AssignQuantity);
+
+            _logger.LogInformation($"鏁版嵁涓�鑷存�ч獙璇� - 璁㈠崟鏄庣粏鍒嗛厤鏁伴噺: {orderDetail.AllocatedQuantity}, 閿佸畾淇℃伅鎬诲垎閰嶆暟閲�: {totalLockAssignQty}");
+
+            // 濡傛灉鏁版嵁涓嶄竴鑷达紝璁板綍璀﹀憡
+            if (Math.Abs(orderDetail.AllocatedQuantity - totalLockAssignQty) > 0.01m)
+            {
+                _logger.LogWarning($"鏁版嵁涓嶄竴鑷� - 璁㈠崟鏄庣粏鍒嗛厤鏁伴噺: {orderDetail.AllocatedQuantity}, 閿佸畾淇℃伅鎬诲垎閰嶆暟閲�: {totalLockAssignQty}");
+            }
+
+            // 楠岃瘉鍒嗛厤鏁伴噺娌℃湁寮傚父鍙樺寲
+            if (Math.Abs(orderDetail.AllocatedQuantity - expectedAllocatedQty) > 0.01m)
+            {
+                _logger.LogWarning($"鍒嗛厤鏁伴噺寮傚父鍙樺寲 - 鏈熸湜: {expectedAllocatedQty}, 瀹為檯: {orderDetail.AllocatedQuantity}");
+            }
+
+            if (Math.Abs(orderDetail.LockQuantity - expectedLockQty) > 0.01m)
+            {
+                _logger.LogWarning($"閿佸畾鏁伴噺寮傚父鍙樺寲 - 鏈熸湜: {expectedLockQty}, 瀹為檯: {orderDetail.LockQuantity}");
+            }
+        }
+        #endregion
 
         #region 鍙栨秷鎷嗗寘 
 
@@ -545,18 +1145,18 @@
             {
                 _unitOfWorkManage.BeginTran();
 
-                // 1. 鏌ユ壘鎷嗗寘璁板綍骞堕獙璇�
+                // 鏌ユ壘鎷嗗寘璁板綍骞堕獙璇�
                 var validationResult = await ValidateCancelSplitRequest(orderNo, palletCode, newBarcode);
                 if (!validationResult.IsValid)
                     return WebResponseContent.Instance.Error(validationResult.ErrorMessage);
 
                 var (splitRecord, newLockInfo, newStockDetail) = validationResult.Data;
 
-                // 2. 鏌ユ壘鍘熷閿佸畾淇℃伅
+                // 鏌ユ壘鍘熷閿佸畾淇℃伅
                 var originalLockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                     .FirstAsync(x => x.Id == splitRecord.OutStockLockInfoId);
 
-                // 3. 妫�鏌ヨ鏉$爜鏄惁琚啀娆℃媶鍖�
+                //  妫�鏌ヨ鏉$爜鏄惁琚啀娆℃媶鍖�
                 var childSplitRecords = await _splitPackageService.Db.Queryable<Dt_SplitPackageRecord>()
                     .Where(x => x.OriginalBarcode == newBarcode && !x.IsReverted)
                     .ToListAsync();
@@ -566,7 +1166,7 @@
                     return WebResponseContent.Instance.Error("璇ユ潯鐮佸凡琚啀娆℃媶鍖咃紝璇峰厛鍙栨秷鍚庣画鐨勬媶鍖呮搷浣�");
                 }
 
-                // 4. 鎵ц鍙栨秷鎷嗗寘閫昏緫
+                //  鎵ц鍙栨秷鎷嗗寘閫昏緫
                 await ExecuteCancelSplitLogic(splitRecord, originalLockInfo, newLockInfo, newStockDetail);
 
                 _unitOfWorkManage.CommitTran();
@@ -588,60 +1188,252 @@
             Dt_OutStockLockInfo originalLockInfo, Dt_OutStockLockInfo newLockInfo,
             Dt_StockInfoDetail newStockDetail)
         {
-            // 1. 鎭㈠鍘熼攣瀹氫俊鎭�
-            // 娉ㄦ剰锛氳繖閲岄渶瑕佺疮鍔狅紝鑰屼笉鏄畝鍗曠殑璧嬪�硷紝鍥犱负鍙兘鏈夊娆℃媶鍖�
+            _logger.LogInformation($"寮�濮嬫墽琛屽彇娑堟媶鍖呴�昏緫 - 鍘熸潯鐮�: {splitRecord.OriginalBarcode}, 鏂版潯鐮�: {splitRecord.NewBarcode}, 鎷嗗寘鏁伴噺: {splitRecord.SplitQty}");
+
+            try
+            {
+                // 鏍规嵁鎷嗗寘绫诲瀷璋冪敤涓嶅悓鐨勫鐞嗘柟娉�
+                if (splitRecord.IsAutoSplit)
+                {
+                    await HandleAutoSplitCancel(splitRecord, originalLockInfo, newLockInfo, newStockDetail);
+                }
+                else
+                {
+                    await HandleManualSplitCancel(splitRecord, originalLockInfo, newLockInfo, newStockDetail);
+                }
+
+                // 楠岃瘉鍙栨秷鎷嗗寘鍚庢暟鎹竴鑷存��
+                await ValidateDataConsistencyAfterCancelSplit(originalLockInfo.OrderDetailId,
+                    originalLockInfo.AssignQuantity, originalLockInfo.OrderQuantity,
+                    splitRecord.IsAutoSplit, splitRecord.SplitQty);
+
+                // 妫�鏌ュ苟鏇存柊鎵规鍜岃鍗曠姸鎬�
+                await CheckAndUpdateBatchStatus(originalLockInfo.BatchNo);
+                await CheckAndUpdateOrderStatus(originalLockInfo.OrderNo);
+
+                _logger.LogInformation($"鍙栨秷鎷嗗寘閫昏緫鎵ц瀹屾垚");
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"鍙栨秷鎷嗗寘閫昏緫鎵ц澶辫触: {ex.Message}");
+                throw;
+            }
+        }
+
+        /// <summary>
+        /// 澶勭悊鑷姩鎷嗗寘鍙栨秷
+        /// </summary>
+        private async Task HandleAutoSplitCancel(Dt_SplitPackageRecord splitRecord,
+            Dt_OutStockLockInfo originalLockInfo, Dt_OutStockLockInfo newLockInfo,
+            Dt_StockInfoDetail newStockDetail)
+        {
+            _logger.LogInformation($"澶勭悊鑷姩鎷嗗寘鍙栨秷 - 鍘熸潯鐮�: {splitRecord.OriginalBarcode}, 鏂版潯鐮�: {splitRecord.NewBarcode}");
+
+            // 鑾峰彇璁㈠崟鏄庣粏
+            var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
+                .FirstAsync(x => x.Id == originalLockInfo.OrderDetailId);
+
+            if (orderDetail == null)
+                throw new InvalidOperationException("鏈壘鍒拌鍗曟槑缁�");
+
+            //  鎭㈠璁㈠崟鏄庣粏鐨勫垎閰嶆暟閲�
+            decimal originalAllocatedQty = orderDetail.AllocatedQuantity;
+            decimal originalLockQty = orderDetail.LockQuantity;
+
+            orderDetail.AllocatedQuantity -= splitRecord.SplitQty;
+            orderDetail.LockQuantity -= splitRecord.SplitQty;
+
+            // 杈圭晫妫�鏌�
+            if (orderDetail.AllocatedQuantity < 0) orderDetail.AllocatedQuantity = 0;
+            if (orderDetail.LockQuantity < 0) orderDetail.LockQuantity = 0;
+
+            await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
+            _logger.LogInformation($"鑷姩鎷嗗寘鍙栨秷鎭㈠璁㈠崟鏄庣粏 - 鍒嗛厤鏁伴噺: {originalAllocatedQty} -> {orderDetail.AllocatedQuantity}");
+
+            //  鎭㈠鍘熷簱瀛�
+            var originalStock = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                .FirstAsync(x => x.Barcode == splitRecord.OriginalBarcode && x.StockId == splitRecord.StockId);
+
+            if (originalStock != null)
+            {
+                decimal originalStockQty = originalStock.StockQuantity;
+                originalStock.StockQuantity += splitRecord.SplitQty;
+
+                // 濡傛灉鍘熷簱瀛樼姸鎬佹槸鍑哄簱瀹屾垚锛屾仮澶嶄负鍑哄簱閿佸畾
+                if (originalStock.Status == (int)StockStatusEmun.鍑哄簱瀹屾垚)
+                {
+                    originalStock.Status = (int)StockStatusEmun.鍑哄簱閿佸畾;
+                }
+
+                await _stockInfoDetailService.Db.Updateable(originalStock).ExecuteCommandAsync();
+                _logger.LogInformation($"鑷姩鎷嗗寘鍙栨秷鎭㈠鍘熷簱瀛� - 鏉$爜: {originalStock.Barcode}, 鏁伴噺: {originalStockQty} -> {originalStock.StockQuantity}");
+            }
+
+            // 鍒犻櫎鏂伴攣瀹氫俊鎭拰搴撳瓨鏄庣粏
+            await DeleteNewSplitRecords(newLockInfo, newStockDetail);
+        }
+
+        /// <summary>
+        /// 澶勭悊鎵嬪姩鎷嗗寘鍙栨秷
+        /// </summary>
+        private async Task HandleManualSplitCancel(Dt_SplitPackageRecord splitRecord,
+            Dt_OutStockLockInfo originalLockInfo, Dt_OutStockLockInfo newLockInfo,
+            Dt_StockInfoDetail newStockDetail)
+        {
+            _logger.LogInformation($"澶勭悊鎵嬪姩鎷嗗寘鍙栨秷 - 鍘熸潯鐮�: {splitRecord.OriginalBarcode}, 鏂版潯鐮�: {splitRecord.NewBarcode}");
+
+            //  鎭㈠鍘熼攣瀹氫俊鎭殑鍒嗛厤鏁伴噺
+            decimal originalAssignQty = originalLockInfo.AssignQuantity;
+            decimal originalOrderQty = originalLockInfo.OrderQuantity;
+
             originalLockInfo.AssignQuantity += splitRecord.SplitQty;
             originalLockInfo.OrderQuantity += splitRecord.SplitQty;
 
-            // 濡傛灉鍘熼攣瀹氫俊鎭殑鐘舵�佹槸鎷i�夊畬鎴愶紝闇�瑕侀噸鏂拌缃负鍑哄簱涓�
+            // 鎭㈠鐘舵��
             if (originalLockInfo.Status == (int)OutLockStockStatusEnum.鎷i�夊畬鎴�)
             {
                 originalLockInfo.Status = (int)OutLockStockStatusEnum.鍑哄簱涓�;
             }
 
             await _outStockLockInfoService.Db.Updateable(originalLockInfo).ExecuteCommandAsync();
+            _logger.LogInformation($"鎵嬪姩鎷嗗寘鍙栨秷鎭㈠鍘熼攣瀹氫俊鎭� - 鍒嗛厤鏁伴噺: {originalAssignQty} -> {originalLockInfo.AssignQuantity}");
 
             // 鎭㈠鍘熷簱瀛樻槑缁�
             var originalStock = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
                 .FirstAsync(x => x.Barcode == splitRecord.OriginalBarcode && x.StockId == splitRecord.StockId);
 
-            originalStock.StockQuantity += splitRecord.SplitQty;
-
-            // 濡傛灉鍘熷簱瀛樼姸鎬佹槸鍑哄簱瀹屾垚锛岄渶瑕侀噸鏂拌缃负鍑哄簱閿佸畾
-            if (originalStock.Status == (int)StockStatusEmun.鍑哄簱瀹屾垚)
+            if (originalStock != null)
             {
-                originalStock.Status = (int)StockStatusEmun.鍑哄簱閿佸畾;
+                decimal originalStockQty = originalStock.StockQuantity;
+                originalStock.StockQuantity += splitRecord.SplitQty;
+
+                // 鎭㈠搴撳瓨鐘舵��
+                if (originalStock.Status == (int)StockStatusEmun.鍑哄簱瀹屾垚)
+                {
+                    originalStock.Status = (int)StockStatusEmun.鍑哄簱閿佸畾;
+                }
+
+                await _stockInfoDetailService.Db.Updateable(originalStock).ExecuteCommandAsync();
+                _logger.LogInformation($"鎵嬪姩鎷嗗寘鍙栨秷鎭㈠鍘熷簱瀛� - 鏉$爜: {originalStock.Barcode}, 鏁伴噺: {originalStockQty} -> {originalStock.StockQuantity}");
             }
 
-            await _stockInfoDetailService.Db.Updateable(originalStock).ExecuteCommandAsync();
-
-            // 鍒犻櫎鏂伴攣瀹氫俊鎭�
-            await _outStockLockInfoService.Db.Deleteable<Dt_OutStockLockInfo>()
-                .Where(x => x.Id == newLockInfo.Id)
-                .ExecuteCommandAsync();
-
-            // 鍒犻櫎鏂板簱瀛樻槑缁�
-            await _stockInfoDetailService.Db.Deleteable<Dt_StockInfoDetail>()
-                .Where(x => x.Barcode == newLockInfo.CurrentBarcode)
-                .ExecuteCommandAsync();
-
-            //鏍囪鎷嗗寘璁板綍涓哄凡鎾ら攢
-            splitRecord.IsReverted = true;
-            splitRecord.RevertTime = DateTime.Now;
-            splitRecord.RevertOperator = App.User.UserName;
-            await _splitPackageService.Db.Updateable(splitRecord).ExecuteCommandAsync();
-
-            // 妫�鏌ュ苟鏇存柊鎵规鍜岃鍗曠姸鎬�
-            await CheckAndUpdateBatchStatus(originalLockInfo.BatchNo);
-            await CheckAndUpdateOrderStatus(originalLockInfo.OrderNo);
+            // 鍒犻櫎鏂伴攣瀹氫俊鎭拰搴撳瓨鏄庣粏
+            await DeleteNewSplitRecords(newLockInfo, newStockDetail);
         }
 
+        /// <summary>
+        /// 鍒犻櫎鏂版媶鍖呰褰曠浉鍏崇殑鏁版嵁
+        /// </summary>
+        private async Task DeleteNewSplitRecords(Dt_OutStockLockInfo newLockInfo, Dt_StockInfoDetail newStockDetail)
+        {
+            // 鍒犻櫎鏂伴攣瀹氫俊鎭�
+            if (newLockInfo != null)
+            {
+                _logger.LogInformation($"鍒犻櫎鏂伴攣瀹氫俊鎭� - 鏉$爜: {newLockInfo.CurrentBarcode}, 鍒嗛厤鏁伴噺: {newLockInfo.AssignQuantity}");
+                await _outStockLockInfoService.Db.Deleteable<Dt_OutStockLockInfo>()
+                    .Where(x => x.Id == newLockInfo.Id)
+                    .ExecuteCommandAsync();
+            }
+
+            // 鍒犻櫎鏂板簱瀛樻槑缁�
+            if (newStockDetail != null)
+            {
+                _logger.LogInformation($"鍒犻櫎鏂板簱瀛樻槑缁� - 鏉$爜: {newStockDetail.Barcode}, 搴撳瓨鏁伴噺: {newStockDetail.StockQuantity}");
+                await _stockInfoDetailService.Db.Deleteable<Dt_StockInfoDetail>()
+                    .Where(x => x.Barcode == newStockDetail.Barcode)
+                    .ExecuteCommandAsync();
+            }
+        }
+
+        /// <summary>
+        /// 楠岃瘉鍙栨秷鎷嗗寘鍚庢暟鎹竴鑷存�� - 鏈�鏂扮増鏈�
+        /// </summary>
+        private async Task ValidateDataConsistencyAfterCancelSplit(long orderDetailId, decimal originalAllocatedQty, decimal originalLockQty, bool isAutoSplit, decimal splitQuantity)
+        {
+            // 閲嶆柊鑾峰彇璁㈠崟鏄庣粏鏁版嵁
+            var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
+                .FirstAsync(x => x.Id == orderDetailId);
+
+            if (orderDetail == null)
+                return;
+
+            // 璁$畻鎵�鏈夐攣瀹氫俊鎭殑鎬诲垎閰嶆暟閲�
+            var allLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                .Where(x => x.OrderDetailId == orderDetailId)
+                .ToListAsync();
+
+            decimal totalLockAssignQty = allLocks.Sum(x => x.AssignQuantity);
+
+            _logger.LogInformation($"鍙栨秷鎷嗗寘鍚庢暟鎹竴鑷存�ч獙璇� - 璁㈠崟鏄庣粏鍒嗛厤鏁伴噺: {orderDetail.AllocatedQuantity}, 閿佸畾淇℃伅鎬诲垎閰嶆暟閲�: {totalLockAssignQty}");
+
+            // 鏍规嵁鎷嗗寘绫诲瀷璁$畻鏈熸湜鍊�
+            decimal expectedAllocatedQty;
+            decimal expectedLockQty;
+
+            if (isAutoSplit)
+            {
+                // 鑷姩鎷嗗寘鍙栨秷锛氬垎閰嶆暟閲忓簲璇ュ噺灏戞媶鍖呮暟閲�
+                expectedAllocatedQty = originalAllocatedQty - splitQuantity;
+                expectedLockQty = originalLockQty - splitQuantity;
+
+                _logger.LogInformation($"鍙栨秷鑷姩鎷嗗寘鏈熸湜鍊� - 鍒嗛厤鏁伴噺: {expectedAllocatedQty}, 閿佸畾鏁伴噺: {expectedLockQty}");
+            }
+            else
+            {
+                // 鎵嬪姩鎷嗗寘鍙栨秷锛氬垎閰嶆暟閲忓簲璇ヤ繚鎸佷笉鍙�
+                expectedAllocatedQty = originalAllocatedQty;
+                expectedLockQty = originalLockQty;
+
+                _logger.LogInformation($"鍙栨秷鎵嬪姩鎷嗗寘鏈熸湜鍊� - 鍒嗛厤鏁伴噺: {expectedAllocatedQty}, 閿佸畾鏁伴噺: {expectedLockQty}");
+            }
+
+            // 杈圭晫妫�鏌ワ細纭繚鏈熸湜鍊间笉涓鸿礋鏁�
+            if (expectedAllocatedQty < 0)
+            {
+                _logger.LogWarning($"鏈熸湜鍒嗛厤鏁伴噺涓鸿礋鏁帮紝閲嶇疆涓�0銆傝绠楀��: {expectedAllocatedQty}");
+                expectedAllocatedQty = 0;
+            }
+
+            if (expectedLockQty < 0)
+            {
+                _logger.LogWarning($"鏈熸湜閿佸畾鏁伴噺涓鸿礋鏁帮紝閲嶇疆涓�0銆傝绠楀��: {expectedLockQty}");
+                expectedLockQty = 0;
+            }
+
+            // 楠岃瘉鍒嗛厤鏁伴噺
+            if (Math.Abs(orderDetail.AllocatedQuantity - expectedAllocatedQty) > 0.01m)
+            {
+                _logger.LogWarning($"鍙栨秷鎷嗗寘鍚庡垎閰嶆暟閲忓紓甯� - 鏈熸湜: {expectedAllocatedQty}, 瀹為檯: {orderDetail.AllocatedQuantity}");
+            }
+
+            // 楠岃瘉閿佸畾鏁伴噺
+            if (Math.Abs(orderDetail.LockQuantity - expectedLockQty) > 0.01m)
+            {
+                _logger.LogWarning($"鍙栨秷鎷嗗寘鍚庨攣瀹氭暟閲忓紓甯� - 鏈熸湜: {expectedLockQty}, 瀹為檯: {orderDetail.LockQuantity}");
+            }
+
+            // 楠岃瘉璁㈠崟鏄庣粏鍒嗛厤鏁伴噺涓庨攣瀹氫俊鎭�诲垎閰嶆暟閲忕殑涓�鑷存��
+            if (Math.Abs(orderDetail.AllocatedQuantity - totalLockAssignQty) > 0.01m)
+            {
+                _logger.LogWarning($"鍙栨秷鎷嗗寘鍚庢暟鎹笉涓�鑷� - 璁㈠崟鏄庣粏鍒嗛厤鏁伴噺: {orderDetail.AllocatedQuantity}, 閿佸畾淇℃伅鎬诲垎閰嶆暟閲�: {totalLockAssignQty}");
+            }
+
+            // 璁板綍璇︾粏鐨勪竴鑷存�ф姤鍛�
+            _logger.LogInformation($"鍙栨秷鎷嗗寘鏁版嵁涓�鑷存�ф姤鍛� - " +
+                                  $"璁㈠崟鏄庣粏鍒嗛厤鏁伴噺: {orderDetail.AllocatedQuantity}, " +
+                                  $"璁㈠崟鏄庣粏閿佸畾鏁伴噺: {orderDetail.LockQuantity}, " +
+                                  $"閿佸畾淇℃伅鎬诲垎閰嶆暟閲�: {totalLockAssignQty}, " +
+                                  $"鎷嗗寘绫诲瀷: {(isAutoSplit ? "鑷姩" : "鎵嬪姩")}, " +
+                                  $"鎷嗗寘鏁伴噺: {splitQuantity}");
+        }
         /// <summary>
         /// 楠岃瘉鍙栨秷鎷嗗寘璇锋眰 
         /// </summary>
         private async Task<ValidationResult<(Dt_SplitPackageRecord, Dt_OutStockLockInfo, Dt_StockInfoDetail)>> ValidateCancelSplitRequest(
             string orderNo, string palletCode, string newBarcode)
         {
+            _logger.LogInformation($"寮�濮嬮獙璇佸彇娑堟媶鍖呰姹� - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}, 鏉$爜: {newBarcode}");
+
             // 鏌ユ壘鎷嗗寘璁板綍
             var splitRecord = await _splitPackageService.Db.Queryable<Dt_SplitPackageRecord>()
                 .Where(x => x.NewBarcode == newBarcode &&
@@ -651,6 +1443,8 @@
 
             if (splitRecord == null)
                 return ValidationResult<(Dt_SplitPackageRecord, Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error("鏈壘鍒版媶鍖呰褰�");
+
+            _logger.LogInformation($"鎵惧埌鎷嗗寘璁板綍 - 鍘熸潯鐮�: {splitRecord.OriginalBarcode}, 鏂版潯鐮�: {splitRecord.NewBarcode}, 鎷嗗寘鏁伴噺: {splitRecord.SplitQty}");
 
             // 鏌ユ壘鏂伴攣瀹氫俊鎭�
             var newLockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
@@ -662,13 +1456,35 @@
             if (newLockInfo == null)
                 return ValidationResult<(Dt_SplitPackageRecord, Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error("鏈壘鍒版柊閿佸畾淇℃伅");
 
-            // 妫�鏌ユ柊鏉$爜鏄惁宸茶鍒嗘嫞
-            var pickingRecord = await Db.Queryable<Dt_PickingRecord>()
-                .Where(x => x.Barcode == newBarcode && !x.IsCancelled)
-                .FirstAsync();
+            _logger.LogInformation($"鎵惧埌鏂伴攣瀹氫俊鎭� - 鐘舵��: {newLockInfo.Status}, 宸叉嫞閫�: {newLockInfo.PickedQty}, 鍒嗛厤鏁伴噺: {newLockInfo.AssignQuantity}");
 
-            if (pickingRecord != null)
-                return ValidationResult<(Dt_SplitPackageRecord, Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error("璇ユ潯鐮佸凡琚垎鎷o紝鏃犳硶鍙栨秷鎷嗗寘");
+            // 妫�鏌ユ柊鏉$爜鏄惁宸茶鍒嗘嫞
+            var newBarcodePickingRecords = await Db.Queryable<Dt_PickingRecord>()
+                .Where(x => x.Barcode == newBarcode && x.OrderNo == orderNo && !x.IsCancelled)
+                .ToListAsync();
+
+            if (newBarcodePickingRecords.Any())
+            {
+                var totalPickedQty = newBarcodePickingRecords.Sum(x => x.PickQuantity);
+                _logger.LogWarning($"鏂版潯鐮� {newBarcode} 宸茶鍒嗘嫞锛屾�绘嫞閫夋暟閲�: {totalPickedQty}");
+                return ValidationResult<(Dt_SplitPackageRecord, Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error(
+                    $"鏂版潯鐮佸凡琚垎鎷o紙宸叉嫞閫夋暟閲忥細{totalPickedQty}锛夛紝璇峰厛鍙栨秷鍒嗘嫞锛岀劧鍚庡啀鍙栨秷鎷嗗寘");
+            }
+
+            // 妫�鏌ュ師鏉$爜鏄惁宸茶鍒嗘嫞
+            var originalBarcodePickingRecords = await Db.Queryable<Dt_PickingRecord>()
+                .Where(x => x.Barcode == splitRecord.OriginalBarcode && x.OrderNo == orderNo && !x.IsCancelled)
+                .ToListAsync();
+
+            if (originalBarcodePickingRecords.Any())
+            {
+                var totalPickedQty = originalBarcodePickingRecords.Sum(x => x.PickQuantity);
+                _logger.LogWarning($"鍘熸潯鐮� {splitRecord.OriginalBarcode} 宸茶鍒嗘嫞锛屾�绘嫞閫夋暟閲�: {totalPickedQty}");
+                return ValidationResult<(Dt_SplitPackageRecord, Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error(
+                    $"鍘熸潯鐮佸凡琚垎鎷o紙宸叉嫞閫夋暟閲忥細{totalPickedQty}锛夛紝璇峰厛鍙栨秷鍒嗘嫞锛岀劧鍚庡啀鍙栨秷鎷嗗寘");
+            }
+
+            _logger.LogInformation($"鏂版棫鏉$爜鍧囨湭琚垎鎷o紝鍙互鍙栨秷鎷嗗寘");
 
             // 妫�鏌ユ柊鏉$爜鏄惁琚啀娆℃媶鍖�
             var childSplitRecords = await _splitPackageService.Db.Queryable<Dt_SplitPackageRecord>()
@@ -678,12 +1494,18 @@
             if (childSplitRecords.Any())
             {
                 var childBarcodes = string.Join(", ", childSplitRecords.Select(x => x.NewBarcode));
+                _logger.LogWarning($"鏉$爜 {newBarcode} 宸茶鍐嶆鎷嗗寘锛岀敓鎴愮殑鏂版潯鐮�: {childBarcodes}");
                 return ValidationResult<(Dt_SplitPackageRecord, Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error(
                     $"璇ユ潯鐮佸凡琚啀娆℃媶鍖咃紝鐢熸垚鐨勬柊鏉$爜锛歿childBarcodes}锛岃鍏堝彇娑堝悗缁媶鍖�");
             }
 
             var newStockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
                 .FirstAsync(x => x.Barcode == newBarcode);
+
+            if (newStockDetail == null)
+                return ValidationResult<(Dt_SplitPackageRecord, Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error("鏈壘鍒版柊搴撳瓨鏄庣粏");
+
+            _logger.LogInformation($"鍙栨秷鎷嗗寘楠岃瘉閫氳繃 - 鏉$爜: {newBarcode}");
 
             return ValidationResult<(Dt_SplitPackageRecord, Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Success((splitRecord, newLockInfo, newStockDetail));
         }
@@ -701,17 +1523,34 @@
             {
                 _unitOfWorkManage.BeginTran();
 
-                // 1. 鏌ユ壘鎵�鏈夌浉鍏崇殑鎷嗗寘璁板綍锛堝舰鎴愭媶鍖呴摼锛�
+                // 鏌ユ壘鎵�鏈夌浉鍏崇殑鎷嗗寘璁板綍锛堝舰鎴愭媶鍖呴摼锛�
                 var splitChain = await GetSplitPackageChain(orderNo, startBarcode);
 
                 if (!splitChain.Any())
                     return WebResponseContent.Instance.Error("鏈壘鍒版媶鍖呰褰�");
 
-                // 2. 鎸夋媶鍖呴『搴忓�掑簭鍙栨秷锛堜粠鏈�鏂扮殑寮�濮嬪彇娑堬級
+                _logger.LogInformation($"鎵惧埌鎷嗗寘閾撅紝鍏� {splitChain.Count} 鏉¤褰�");
+
+                // 鏀堕泦鎷嗗寘閾句腑娑夊強鐨勬墍鏈夋潯鐮侊紙鍖呮嫭鍘熸潯鐮佸拰鏂版潯鐮侊級
+                var allBarcodesInChain = new List<string> { startBarcode };
+                allBarcodesInChain.AddRange(splitChain.Select(x => x.NewBarcode));
+
+                // 妫�鏌ユ媶鍖呴摼涓槸鍚︽湁宸茶鍒嗘嫞鐨勬潯鐮�
+                var pickedBarcodesInfo = await GetPickedBarcodesInfo(orderNo, allBarcodesInChain);
+
+                if (pickedBarcodesInfo.Any())
+                {
+                    var pickedBarcodes = string.Join(", ", pickedBarcodesInfo.Select(x => $"{x.Barcode}(宸叉嫞閫墈x.PickedQty})"));
+                    return WebResponseContent.Instance.Error(
+                        $"浠ヤ笅鏉$爜宸茶鍒嗘嫞锛岃鍏堝彇娑堝垎鎷o細{pickedBarcodes}");
+                }
+
+                // 鎸夋媶鍖呴『搴忓�掑簭鍙栨秷锛堜粠鏈�鏂扮殑寮�濮嬪彇娑堬級
                 var reversedChain = splitChain.OrderByDescending(x => x.SplitTime).ToList();
 
                 foreach (var splitRecord in reversedChain)
                 {
+                    _logger.LogInformation($"鍙栨秷鎷嗗寘璁板綍 - 鍘熸潯鐮�: {splitRecord.OriginalBarcode}, 鏂版潯鐮�: {splitRecord.NewBarcode}");
                     await CancelSingleSplitPackage(splitRecord, palletCode);
                 }
 
@@ -727,6 +1566,34 @@
             }
         }
 
+        
+        /// <summary>
+        /// 鑾峰彇宸茶鍒嗘嫞鐨勬潯鐮佷俊鎭�
+        /// </summary>
+        private async Task<List<PickedBarcodeInfo>> GetPickedBarcodesInfo(string orderNo, List<string> barcodes)
+        {
+            var pickedBarcodes = new List<PickedBarcodeInfo>();
+
+            foreach (var barcode in barcodes)
+            {
+                var pickingRecords = await Db.Queryable<Dt_PickingRecord>()
+                    .Where(x => x.Barcode == barcode && x.OrderNo == orderNo && !x.IsCancelled)
+                    .ToListAsync();
+
+                if (pickingRecords.Any())
+                {
+                    var totalPickedQty = pickingRecords.Sum(x => x.PickQuantity);
+                    pickedBarcodes.Add(new PickedBarcodeInfo
+                    {
+                        Barcode = barcode,
+                        PickedQty = totalPickedQty,
+                        PickRecordCount = pickingRecords.Count
+                    });
+                }
+            }
+
+            return pickedBarcodes;
+        }
         /// <summary>
         /// 鑾峰彇鎷嗗寘閾� - 鏌ユ壘鏌愪釜鏉$爜鐨勬墍鏈夋媶鍖呰褰曪紙鍖呮嫭鍚庣画鎷嗗寘锛�
         /// </summary>
@@ -771,6 +1638,27 @@
         /// </summary>
         private async Task CancelSingleSplitPackage(Dt_SplitPackageRecord splitRecord, string palletCode)
         {
+            _logger.LogInformation($"寮�濮嬪彇娑堝崟涓媶鍖呰褰� - 鍘熸潯鐮�: {splitRecord.OriginalBarcode}, 鏂版潯鐮�: {splitRecord.NewBarcode}");
+
+            // 鍐嶆楠岃瘉鍒嗘嫞鐘舵�侊紙闃叉骞跺彂鎿嶄綔锛�
+            var newBarcodePickingRecords = await Db.Queryable<Dt_PickingRecord>()
+                .Where(x => x.Barcode == splitRecord.NewBarcode && !x.IsCancelled)
+                .ToListAsync();
+
+            if (newBarcodePickingRecords.Any())
+            {
+                throw new InvalidOperationException($"鏂版潯鐮� {splitRecord.NewBarcode} 鍦ㄩ獙璇佸悗琚垎鎷o紝鏃犳硶鍙栨秷鎷嗗寘");
+            }
+
+            var originalBarcodePickingRecords = await Db.Queryable<Dt_PickingRecord>()
+                .Where(x => x.Barcode == splitRecord.OriginalBarcode && !x.IsCancelled)
+                .ToListAsync();
+
+            if (originalBarcodePickingRecords.Any())
+            {
+                throw new InvalidOperationException($"鍘熸潯鐮� {splitRecord.OriginalBarcode} 鍦ㄩ獙璇佸悗琚垎鎷o紝鏃犳硶鍙栨秷鎷嗗寘");
+            }
+
             // 鏌ユ壘鐩稿叧鏁版嵁
             var newLockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                 .Where(x => x.CurrentBarcode == splitRecord.NewBarcode &&
@@ -785,6 +1673,8 @@
 
             // 鎵ц鍙栨秷閫昏緫
             await ExecuteCancelSplitLogic(splitRecord, originalLockInfo, newLockInfo, newStockDetail);
+
+            _logger.LogInformation($"鍙栨秷鍗曚釜鎷嗗寘璁板綍瀹屾垚 - 鍘熸潯鐮�: {splitRecord.OriginalBarcode}, 鏂版潯鐮�: {splitRecord.NewBarcode}");
         }
         #endregion
 
@@ -810,7 +1700,8 @@
                         NewBarcode = x.NewBarcode,
                         SplitQuantity = x.SplitQty,
                         Operator = x.Operator,
-                        IsReverted = x.IsReverted
+                        IsReverted = x.IsReverted,
+                        IsAutoSplit = x.IsAutoSplit
                     }).ToList()
                 };
 
@@ -899,68 +1790,1259 @@
 
         #endregion
 
-
-
-
-        #region 鍒嗘壒鍥炲簱
-
+        #region 缁熶竴鍥炲簱閫昏緫
+             
         /// <summary>
-        /// 鍒嗘壒鍥炲簱 - 閲婃斁鏈嫞閫夌殑搴撳瓨
+        /// 缁熶竴鍥炲簱鏂规硶
         /// </summary>
-        public async Task<WebResponseContent> BatchReturnStock(string orderNo, string palletCode)
+        public async Task<WebResponseContent> ExecutePalletReturn(string orderNo, string palletCode, string returnReason = "鍒嗘壒鍥炲簱")
         {
+            ReturnTaskInfo returnTaskInfo = null;
             try
             {
+                _logger.LogInformation($"銆愬寮哄洖搴撳紑濮嬨�戣鍗�: {orderNo}, 鎵樼洏: {palletCode}");
+
                 _unitOfWorkManage.BeginTran();
 
-                // 鏌ユ壘鎵樼洏涓婃湭瀹屾垚鐨勯攣瀹氳褰曪紙鍙鐞嗗嚭搴撲腑鐨勮褰曪級
-                var unfinishedLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                    .Where(x => x.OrderNo == orderNo &&
-                               x.PalletCode == palletCode &&
-                               x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�)
-                    .ToListAsync();
+                //  鍩虹楠岃瘉
+                if (string.IsNullOrEmpty(orderNo) || string.IsNullOrEmpty(palletCode))
+                    return WebResponseContent.Instance.Error("璁㈠崟鍙峰拰鎵樼洏鐮佷笉鑳戒负绌�");
 
-                if (!unfinishedLocks.Any())
-                    return WebResponseContent.Instance.Error("璇ユ墭鐩樻病鏈夋湭瀹屾垚鐨勯攣瀹氳褰�");
+                // 鑾峰彇搴撳瓨淇℃伅
+                var stockInfo = await _stockInfoService.Db.Queryable<Dt_StockInfo>().FirstAsync(x => x.PalletCode == palletCode);
 
-                // 鎸夊嚭搴撴壒娆″垎缁勫鐞�
-                var batchGroups = unfinishedLocks.GroupBy(x => x.OutboundBatchNo); // 浣跨敤 OutboundBatchNo
+                if (stockInfo == null)
+                    return WebResponseContent.Instance.Error($"鏈壘鍒版墭鐩� {palletCode} 瀵瑰簲鐨勫簱瀛樹俊鎭�");
 
-                foreach (var batchGroup in batchGroups)
+                int stockId = stockInfo.Id;
+
+                //  鎵ц鍥炲簱鍓嶆暟鎹獙璇�
+                var validationResult = await ValidateDataBeforeReturn(orderNo, palletCode, stockId);
+                if (!validationResult.IsValid)
                 {
-                    var outboundBatchNo = batchGroup.Key;
-                    var batchLocks = batchGroup.ToList();
-
-                    // 閲婃斁搴撳瓨鍜岄攣瀹氳褰�
-                    foreach (var lockInfo in batchLocks)
-                    {
-                        await ReleaseLockAndStock(lockInfo);
-                    }
-
-                    // 鏇存柊鎵规鐘舵��
-                    await UpdateBatchStatusForReturn(outboundBatchNo, batchLocks);
-
-                    // 鏇存柊璁㈠崟鏄庣粏鐨勫凡鍒嗛厤鏁伴噺
-                    await UpdateOrderDetailAfterReturn(batchLocks);
+                    _logger.LogWarning($"鍥炲簱鍓嶆暟鎹獙璇佸け璐�: {validationResult.ErrorMessage}");                 
                 }
 
+                // 鍒嗘瀽鎵樼洏鐘舵��
+                var statusAnalysis = await AnalyzePalletStatusForReturn(orderNo, palletCode, stockInfo.Id);
+
+                if (!statusAnalysis.HasItemsToReturn)
+                {
+                    try
+                    {
+                        _logger.LogInformation($"銆愭棤鍥炲簱鐗╁搧銆戝鐞嗙┖鎵樼洏");
+                        var result = await HandleEmptyPalletReturn(orderNo, palletCode, stockInfo);
+                        _unitOfWorkManage.CommitTran();
+
+                        // 鍦ㄤ簨鍔℃彁浜ゅ悗澶勭悊ESS鍛戒护
+                        if (result.Status && result.Data is ReturnTaskInfo taskInfo)
+                        {
+                            await ProcessESSAfterTransaction(palletCode, taskInfo);
+                        }
+                        return result;
+                    }
+                    catch (Exception ex)
+                    {
+                        _unitOfWorkManage.RollbackTran();
+                        _logger.LogError($"绌虹鍥炲簱ExecutePalletReturn澶辫触: {ex.Message}");
+                        return WebResponseContent.Instance.Error($"绌虹鍥炲簱ExecutePalletReturn澶辫触锛歿ex.Message}");
+                    }
+                }
+
+                _logger.LogInformation($"銆愬紑濮嬪洖搴撱�戞�诲洖搴撴暟閲�: {statusAnalysis.TotalReturnQty}, 鏉$爜鏁�: {statusAnalysis.AllBarcodes.Count}");
+
+                //  鎵ц鍥炲簱鎿嶄綔
+                try
+                {
+                    await ExecuteEnhancedReturnOperations(statusAnalysis);
+                }
+                catch (Exception ex)
+                {
+                    _logger.LogError($"涓诲洖搴撴柟娉曞け璐�: {ex.Message}");
+                    // 灏濊瘯绠�鍖栨柟娉�
+                    await ExecuteSimpleReturnDataOperations(statusAnalysis);
+                }
+
+                //  鏇存柊璁㈠崟鐘舵��
+                await UpdateOrderStatusAfterReturn(orderNo);
+                            
+                //  鍒涘缓鍥炲簱浠诲姟
+                try
+                {
+                    // 鍒涘缓鍥炲簱浠诲姟锛屼絾涓嶅彂閫丒SS鍛戒护
+                    returnTaskInfo = await CreateReturnTaskWithoutESS(orderNo, palletCode, stockInfo);
+
+                }
+                catch (Exception taskEx)
+                {
+                    _logger.LogError($"鍥炲簱浠诲姟CreateReturnTaskWithoutESS鍒涘缓澶辫触: {taskEx.Message}");
+                    // 浠诲姟鍒涘缓澶辫触涓嶅奖鍝嶆暟鎹洖搴�
+                }
                 _unitOfWorkManage.CommitTran();
 
-                return WebResponseContent.Instance.OK("鍒嗘壒鍥炲簱鎴愬姛");
+                // 鍦ㄤ簨鍔℃彁浜ゅ悗澶勭悊ESS鍛戒护
+                if (returnTaskInfo != null && returnTaskInfo.ShouldSendESS)
+                {
+                    await ProcessESSAfterTransaction(palletCode, returnTaskInfo);
+                }
+                //  鍥炲簱鍚庨獙璇�
+                await ValidateDataAfterReturn(orderNo, palletCode, stockId);
+
+                return WebResponseContent.Instance.OK($"鍥炲簱鎴愬姛锛屽洖搴撴暟閲忥細{statusAnalysis.TotalReturnQty}", new
+                {
+                    ReturnQuantity = statusAnalysis.TotalReturnQty,
+                    ReturnBarcodes = statusAnalysis.AllBarcodes,
+                    Reason = returnReason,
+                    PalletCode = palletCode,
+                    OrderNo = orderNo
+                });
             }
             catch (Exception ex)
             {
                 _unitOfWorkManage.RollbackTran();
-                _logger.LogError($"鍒嗘壒鍥炲簱澶辫触 - OrderNo: {orderNo}, PalletCode: {palletCode}, Error: {ex.Message}");
-                return WebResponseContent.Instance.Error($"鍒嗘壒鍥炲簱澶辫触锛歿ex.Message}");
+                _logger.LogError($"ExecutePalletReturn 鍥炲簱澶辫触: {ex.Message}");
+                return WebResponseContent.Instance.Error($"ExecutePalletReturn 鍥炲簱澶辫触锛歿ex.Message}");
             }
         }
+
+        /// <summary>
+        /// 浜嬪姟鎻愪氦鍚庡鐞咵SS鍛戒护 - 鐙珛鏂规硶锛岄伩鍏嶄簨鍔¢攣
+        /// </summary>
+        private async Task ProcessESSAfterTransaction(string palletCode, ReturnTaskInfo taskInfo)
+        {
+            try
+            {
+                _logger.LogInformation($"寮�濮嬪鐞咵SS鍛戒护 - 鎵樼洏: {palletCode}");
+
+                if (taskInfo == null || !taskInfo.ShouldSendESS || taskInfo.ReturnTask == null)
+                {
+                    _logger.LogWarning($"鏃犻渶鍙戦�丒SS鍛戒护鎴栦换鍔′俊鎭笉瀹屾暣");
+                    return;
+                }
+
+                // 鍙戦�丒SS鍛戒护
+                await SendESSCommands(palletCode, taskInfo.OriginalTaskTargetAddress, taskInfo.ReturnTask);
+
+                _logger.LogInformation($"ESS鍛戒护澶勭悊瀹屾垚 - 鎵樼洏: {palletCode}, 浠诲姟鍙�: {taskInfo.ReturnTask.TaskNum}");
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"澶勭悊ESS鍛戒护澶辫触 - 鎵樼洏: {palletCode}, Error: {ex.Message}");
+                // 杩欓噷涓嶆姏鍑哄紓甯革紝鍥犱负鏁版嵁鍥炲簱宸茬粡鎴愬姛锛孍SS鍛戒护鍙戦�佸け璐ュ彲浠ョ◢鍚庨噸璇�
+            }
+        }
+        /// <summary>
+        /// 鍒涘缓鍥炲簱浠诲姟锛堜笉鍙戦�丒SS鍛戒护锛�- 鐢ㄤ簬浜嬪姟鍐呭鐞�
+        /// </summary>
+        private async Task<ReturnTaskInfo> CreateReturnTaskWithoutESS(string orderNo, string palletCode, Dt_StockInfo stockInfo)
+        {
+            try
+            {
+                // 鑾峰彇褰撳墠浠诲姟淇℃伅
+                var currentTask = await _taskRepository.Db.Queryable<Dt_Task>()
+                    .Where(x => x.OrderNo == orderNo && x.PalletCode == palletCode)
+                    .FirstAsync();
+
+                if (currentTask == null)
+                {
+                    _logger.LogWarning($"鏈壘鍒板綋鍓嶄换鍔� - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}");
+                    return null;
+                }
+
+                // 鍒嗛厤鏂拌揣浣�
+                var newLocation = _locationInfoService.AssignLocation(stockInfo.LocationType);
+
+                var returnTask = new Dt_Task()
+                {
+                    CurrentAddress = stations[currentTask.TargetAddress],
+                    Grade = 0,
+                    PalletCode = palletCode,
+                    NextAddress = "",
+                    OrderNo = orderNo,
+                    Roadway = newLocation.RoadwayNo,
+                    SourceAddress = stations[currentTask.TargetAddress],
+                    TargetAddress = newLocation.LocationCode,
+                    TaskStatus = TaskStatusEnum.New.ObjToInt(),
+                    TaskType = TaskTypeEnum.InPick.ObjToInt(),
+                    PalletType = stockInfo.PalletType,
+                    WarehouseId = currentTask.WarehouseId
+                };
+
+                try
+                {
+                    await _taskRepository.Db.Insertable(returnTask).ExecuteCommandAsync();
+
+                    _logger.LogInformation($"鍒涘缓鍥炲簱浠诲姟鎴愬姛: {returnTask.TaskNum}, 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}");
+
+                    // 鍒犻櫎鍘熷鍑哄簱浠诲姟
+                    _logger.LogInformation($"寮�濮嬪垹闄ゅ巻鍙蹭换鍔�: {orderNo}, {currentTask.TaskNum}");
+                    var result = _task_HtyService.DeleteAndMoveIntoHty(currentTask, OperateTypeEnum.浜哄伐鍒犻櫎);
+                    await _taskRepository.Db.Deleteable(currentTask).ExecuteCommandAsync();
+
+                    if (!result)
+                    {
+                        await _taskRepository.Db.Deleteable(currentTask).ExecuteCommandAsync();
+                    }
+                    _logger.LogInformation($"鍒犻櫎鍘嗗彶浠诲姟瀹屾垚: {currentTask.TaskNum}, 褰卞搷琛屾暟: {result}");
+
+                    // 杩斿洖浠诲姟淇℃伅锛屼絾涓嶅彂閫丒SS鍛戒护
+                    return new ReturnTaskInfo
+                    {
+                        ShouldSendESS = true,
+                        PalletCode = palletCode,
+                        OriginalTaskTargetAddress = currentTask.TargetAddress,
+                        ReturnTask = returnTask
+                    };
+                }
+                catch (Exception ex)
+                {
+                    _logger.LogError($"鍒涘缓鍥炲簱浠诲姟澶辫触 - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}, Error: {ex.Message}");
+                    throw new Exception($"鍒涘缓鍥炲簱浠诲姟澶辫触 - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}", ex);
+                }
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"鍒涘缓鍥炲簱浠诲姟澶辫触 - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}, Error: {ex.Message}");
+                return null;
+            }
+        }
+        /// <summary>
+        /// 澧炲己鐨勫洖搴撳墠鏁版嵁楠岃瘉
+        /// </summary>
+        private async Task<ValidationResult<bool>> ValidateDataBeforeReturn(string orderNo, string palletCode, int stockId)
+        {
+            var errors = new List<string>();
+
+            try
+            {
+                //  楠岃瘉搴撳瓨鏁版嵁
+                var stockDetails = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                    .Where(x => x.StockId == stockId)
+                    .ToListAsync();
+
+                // 妫�鏌ュ簱瀛樻暟閲忔槸鍚︿负璐熸暟
+                var negativeStocks = stockDetails.Where(x => x.StockQuantity < 0).ToList();
+                if (negativeStocks.Any())
+                {
+                    errors.Add($"鍙戠幇璐熸暟搴撳瓨: {string.Join(", ", negativeStocks.Select(x => $"{x.Barcode}:{x.StockQuantity}"))}");
+                }
+
+                //  楠岃瘉閿佸畾璁板綍
+                var lockInfos = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                    .Where(x => x.OrderNo == orderNo && x.PalletCode == palletCode)
+                    .ToListAsync();
+
+                // 妫�鏌ュ凡鎷i�夋暟閲忔槸鍚﹀ぇ浜庡垎閰嶆暟閲�
+                var invalidLocks = lockInfos.Where(x => x.PickedQty > x.AssignQuantity).ToList();
+                if (invalidLocks.Any())
+                {
+                    errors.Add($"鍙戠幇宸叉嫞閫夋暟閲忓ぇ浜庡垎閰嶆暟閲忕殑閿佸畾璁板綍");
+                }
+
+                //  楠岃瘉鎷嗗寘璁板綍
+                var splitRecords = await _splitPackageService.Db.Queryable<Dt_SplitPackageRecord>()
+                    .Where(x => x.OrderNo == orderNo && x.PalletCode == palletCode)
+                    .ToListAsync();
+
+                // 妫�鏌ュ惊鐜媶鍖�
+                var barcodeMap = new Dictionary<string, string>();
+                foreach (var record in splitRecords.Where(x => !x.IsReverted))
+                {
+                    if (!barcodeMap.ContainsKey(record.OriginalBarcode))
+                        barcodeMap[record.OriginalBarcode] = record.NewBarcode;
+                }
+
+                // 妫�鏌ュ惊鐜紩鐢�
+                foreach (var record in splitRecords)
+                {
+                    var current = record.OriginalBarcode;
+                    var visited = new HashSet<string>();
+
+                    while (barcodeMap.ContainsKey(current))
+                    {
+                        if (visited.Contains(current))
+                        {
+                            errors.Add($"鍙戠幇寰幆鎷嗗寘寮曠敤: {record.OriginalBarcode}");
+                            break;
+                        }
+                        visited.Add(current);
+                        current = barcodeMap[current];
+                    }
+                }
+
+                if (errors.Any())
+                {
+                    return ValidationResult<bool>.Error($"鍥炲簱鍓嶆暟鎹獙璇佸彂鐜伴棶棰�: {string.Join("; ", errors)}");
+                }
+
+                return ValidationResult<bool>.Success(true);
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"鏁版嵁楠岃瘉澶辫触: {ex.Message}");
+                return ValidationResult<bool>.Error($"鏁版嵁楠岃瘉寮傚父: {ex.Message}");
+            }
+        }
+
+        // <summary>
+        /// 鎵ц澧炲己鐨勫洖搴撴搷浣� - 淇鐗堬紙閬垮厤閲嶅澶勭悊锛�
+        /// </summary>
+        private async Task ExecuteEnhancedReturnOperations(PalletStatusAnalysis statusAnalysis)
+        {
+            _logger.LogInformation($"銆愬紑濮嬫墽琛屽洖搴撴搷浣溿�戣鍗�: {statusAnalysis.OrderNo}, 鎵樼洏: {statusAnalysis.PalletCode}");
+
+            // 浣跨敤鏈湴宸插鐞嗛泦鍚堬紝閬垮厤閲嶅
+            var locallyProcessedBarcodes = new HashSet<string>();
+            decimal totalProcessedQty = 0;
+
+            // 澶勭悊宸插垎閰嶇殑閿佸畾璁板綍
+            if (statusAnalysis.HasRemainingLocks)
+            {
+                _logger.LogInformation($"澶勭悊宸插垎閰嶉攣瀹氳褰� - {statusAnalysis.RemainingLocks.Count} 鏉�");
+                foreach (var lockInfo in statusAnalysis.RemainingLocks)
+                {
+                    if (string.IsNullOrEmpty(lockInfo.CurrentBarcode) ||
+                        locallyProcessedBarcodes.Contains(lockInfo.CurrentBarcode))
+                    {
+                        _logger.LogInformation($"璺宠繃宸插鐞嗘潯鐮佺殑閿佸畾璁板綍: {lockInfo.CurrentBarcode}");
+                        continue;
+                    }
+
+                    decimal returnQty = lockInfo.AssignQuantity - lockInfo.PickedQty;
+                    if (returnQty > 0)
+                    {
+                        // 銆愪慨澶嶃�戜紶閫� isUnallocated = false
+                        await ProcessSingleBarcodeReturn(lockInfo.CurrentBarcode, statusAnalysis.StockId, returnQty, false);
+                        locallyProcessedBarcodes.Add(lockInfo.CurrentBarcode);
+                        totalProcessedQty += returnQty;
+                        _logger.LogInformation($"宸插鐞嗛攣瀹氳褰� - 鏉$爜: {lockInfo.CurrentBarcode}, 鏁伴噺: {returnQty}");
+                    }
+                }
+            }
+
+            //  澶勭悊鏈垎閰嶇殑閿佸畾璁板綍
+            if (statusAnalysis.HasUnallocatedLocks)
+            {
+                _logger.LogInformation($"澶勭悊鏈垎閰嶉攣瀹氳褰� - {statusAnalysis.UnallocatedLocks.Count} 鏉�");
+                foreach (var lockInfo in statusAnalysis.UnallocatedLocks)
+                {
+                    if (string.IsNullOrEmpty(lockInfo.CurrentBarcode) ||
+                        locallyProcessedBarcodes.Contains(lockInfo.CurrentBarcode))
+                    {
+                        _logger.LogInformation($"璺宠繃宸插鐞嗘潯鐮佺殑鏈垎閰嶉攣瀹�: {lockInfo.CurrentBarcode}");
+                        continue;
+                    }
+
+                    decimal returnQty = lockInfo.AssignQuantity - lockInfo.PickedQty;
+                    if (returnQty > 0)
+                    {
+                        // 銆愪慨澶嶃�戜娇鐢ㄤ笓闂ㄧ殑鏈垎閰嶉攣瀹氬鐞嗘柟娉�
+                        await ProcessUnallocatedLockReturn(lockInfo, returnQty);
+                        locallyProcessedBarcodes.Add(lockInfo.CurrentBarcode);
+                        totalProcessedQty += returnQty;
+                        _logger.LogInformation($"宸插鐞嗘湭鍒嗛厤閿佸畾 - 鏉$爜: {lockInfo.CurrentBarcode}, 鏁伴噺: {returnQty}");
+                    }
+                }
+            }
+
+            // 澶勭悊鏈垎閰嶇殑搴撳瓨璐х墿
+            if (statusAnalysis.HasPalletStockGoods)
+            {
+                _logger.LogInformation($"澶勭悊鏈垎閰嶅簱瀛樿揣鐗� - {statusAnalysis.PalletStockGoods.Count} 涓�");
+                foreach (var stockDetail in statusAnalysis.PalletStockGoods)
+                {
+                    if (string.IsNullOrEmpty(stockDetail.Barcode) ||
+                        locallyProcessedBarcodes.Contains(stockDetail.Barcode))
+                    {
+                        _logger.LogInformation($"璺宠繃宸插鐞嗘潯鐮佺殑搴撳瓨: {stockDetail.Barcode}");
+                        continue;
+                    }
+
+                    decimal returnQty = stockDetail.StockQuantity;
+                    if (returnQty > 0)
+                    {
+                        await ProcessUnallocatedStockReturn(stockDetail);
+                        locallyProcessedBarcodes.Add(stockDetail.Barcode);
+                        totalProcessedQty += returnQty;
+                        _logger.LogInformation($"宸插鐞嗘湭鍒嗛厤搴撳瓨 - 鏉$爜: {stockDetail.Barcode}, 鏁伴噺: {returnQty}");
+                    }
+                }
+            }
+
+            // 澶勭悊鎷嗗寘璁板綍 - 鍙鐞嗘湭琚叾浠栭�昏緫瑕嗙洊鐨勬潯鐮�
+            if (statusAnalysis.HasSplitRecords && statusAnalysis.SplitReturnQty > 0)
+            {
+                _logger.LogInformation($"澶勭悊鎷嗗寘璁板綍鐩稿叧搴撳瓨 - 鏂板鏁伴噺: {statusAnalysis.SplitReturnQty}");
+
+                // 鍙鐞嗗湪SplitRecords涓絾涓嶅湪宸插鐞嗛泦鍚堜腑鐨勬潯鐮�
+                var splitBarcodes = statusAnalysis.SplitRecords
+                    .SelectMany(r => new[] { r.OriginalBarcode, r.NewBarcode })
+                    .Where(b => !string.IsNullOrEmpty(b))
+                    .Distinct()
+                    .ToList();
+
+                foreach (var barcode in splitBarcodes)
+                {
+                    if (locallyProcessedBarcodes.Contains(barcode))
+                    {
+                        _logger.LogInformation($"璺宠繃宸插鐞嗙殑鎷嗗寘鏉$爜: {barcode}");
+                        continue;
+                    }
+
+                    var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                        .FirstAsync(x => x.Barcode == barcode && x.StockId == statusAnalysis.StockId);
+
+                    if (stockDetail != null && stockDetail.StockQuantity > 0)
+                    {
+                        decimal returnQty = stockDetail.StockQuantity;
+                        await ProcessSingleBarcodeReturn(barcode, statusAnalysis.StockId, returnQty);
+                        locallyProcessedBarcodes.Add(barcode);
+                        totalProcessedQty += returnQty;
+                        _logger.LogInformation($"澶勭悊鎷嗗寘鏉$爜 - {barcode}, 鏁伴噺: {returnQty}");
+                    }
+                }
+            }
+
+            _logger.LogInformation($"銆愬洖搴撴搷浣滃畬鎴愩�戞�诲鐞嗘暟閲�: {totalProcessedQty}, 澶勭悊鏉$爜鏁�: {locallyProcessedBarcodes.Count}");
+
+            // 楠岃瘉澶勭悊鏁伴噺涓庨鏈熶竴鑷�
+            if (Math.Abs(totalProcessedQty - statusAnalysis.TotalReturnQty) > 0.01m)
+            {
+                _logger.LogWarning($"澶勭悊鏁伴噺({totalProcessedQty})涓庨鏈�({statusAnalysis.TotalReturnQty})涓嶄竴鑷达紝浣嗙户缁墽琛�");
+            }
+        }
+
+
+        /// <summary>
+        /// 澶勭悊鍗曚釜鏉$爜鍥炲簱锛堥�氱敤鏂规硶锛�- 鍖哄垎宸插垎閰嶅拰鏈垎閰�
+        /// </summary>
+        private async Task ProcessSingleBarcodeReturn(string barcode, int stockId, decimal returnQty, bool isUnallocated = false)
+        {
+            try
+            {
+                _logger.LogInformation($"澶勭悊鍗曚釜鏉$爜鍥炲簱 - {barcode}, 鏁伴噺: {returnQty}, 鏄惁鏈垎閰�: {isUnallocated}");
+
+                var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                    .FirstAsync(x => x.Barcode == barcode && x.StockId == stockId);
+
+                if (stockDetail == null)
+                {
+                    _logger.LogWarning($"鏈壘鍒板簱瀛樻槑缁�: {barcode}");
+                    return;
+                }
+
+                decimal originalStockQty = stockDetail.StockQuantity;
+                decimal originalOutboundQty = stockDetail.OutboundQuantity;
+                int originalStatus = stockDetail.Status;
+
+                _logger.LogInformation($"鍥炲簱鍓嶇姸鎬� - 搴撳瓨: {originalStockQty}, 鍑哄簱: {originalOutboundQty}, 鐘舵��: {GetStockStatusName(originalStatus)}");
+
+                // 鏍规嵁鏄惁鏈垎閰嶅喅瀹氬鐞嗛�昏緫
+                if (isUnallocated)
+                {
+                    // 鏈垎閰嶉攣瀹氾細鍙仮澶嶇姸鎬侊紝涓嶆敼鍙樺簱瀛樻暟閲�
+                    // 鍑哄簱鏁伴噺搴斾负0
+                    if (stockDetail.OutboundQuantity > 0)
+                    {
+                        _logger.LogWarning($"鏈垎閰嶉攣瀹氱殑搴撳瓨鍑哄簱鏁伴噺涓嶄负0锛岄噸缃负0 - 鏉$爜: {stockDetail.Barcode}, 褰撳墠鍑哄簱: {stockDetail.OutboundQuantity}");
+                        stockDetail.OutboundQuantity = 0;
+                    }
+
+                    // 搴撳瓨鏁伴噺淇濇寔涓嶅彉
+                    _logger.LogInformation($"鏈垎閰嶉攣瀹氬洖搴� - 搴撳瓨鏁伴噺淇濇寔涓嶅彉: {stockDetail.StockQuantity}");
+                }
+                else
+                {
+                    // 宸插垎閰嶉攣瀹氾細鎭㈠搴撳瓨鏁伴噺
+                    stockDetail.StockQuantity += returnQty;
+
+                    // 鍑忓皯鍑哄簱鏁伴噺锛堝鏋滃嚭搴撴暟閲忓ぇ浜�0锛�
+                    if (stockDetail.OutboundQuantity >= returnQty)
+                    {
+                        stockDetail.OutboundQuantity -= returnQty;
+                    }
+                    else
+                    {
+                        // 濡傛灉鍑哄簱鏁伴噺灏忎簬鍥炲簱鏁伴噺锛岃鏄庢暟鎹紓甯革紝鍑哄簱鏁伴噺娓呴浂
+                        _logger.LogWarning($"鍑哄簱鏁伴噺({stockDetail.OutboundQuantity})灏忎簬鍥炲簱鏁伴噺({returnQty})锛屾竻闆�");
+                        stockDetail.OutboundQuantity = 0;
+                    }
+
+                    _logger.LogInformation($"宸插垎閰嶉攣瀹氬洖搴� - 搴撳瓨鏁伴噺澧炲姞: {originalStockQty} -> {stockDetail.StockQuantity}");
+                }
+
+                // 鏇存柊鐘舵��
+                stockDetail.Status = (int)StockStatusEmun.鍏ュ簱瀹屾垚;
+
+                await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+
+                _logger.LogInformation($"鏉$爜鍥炲簱瀹屾垚 - {barcode}: 搴撳瓨 {originalStockQty}->{stockDetail.StockQuantity}, 鍑哄簱 {originalOutboundQty}->{stockDetail.OutboundQuantity}");
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"澶勭悊鏉$爜鍥炲簱澶辫触 - {barcode}: {ex.Message}");
+                throw;
+            }
+        }
+        /// <summary>
+        /// 澶勭悊鏈垎閰嶉攣瀹氳褰曞洖搴� - 淇鐗堟湰
+        /// 鏈垎閰嶉攣瀹氳褰曪細鍙仮澶嶇姸鎬侊紝涓嶅鍔犲簱瀛樻暟閲�
+        /// </summary>
+        private async Task ProcessUnallocatedLockReturn(Dt_OutStockLockInfo lockInfo, decimal returnQty)
+        {
+            _logger.LogInformation($"澶勭悊鏈垎閰嶉攣瀹氬洖搴� - 閿佸畾ID: {lockInfo.Id}, 鏉$爜: {lockInfo.CurrentBarcode}, 鏁伴噺: {returnQty}");
+
+            try
+            {
+                // 楠岃瘉閿佸畾璁板綍鐘舵��
+                if (lockInfo.Status != (int)OutLockStockStatusEnum.鍑哄簱涓� &&
+                    lockInfo.Status != (int)OutLockStockStatusEnum.鍥炲簱涓�)
+                {
+                    _logger.LogWarning($"閿佸畾璁板綍鐘舵�佷笉鏄嚭搴撲腑鎴栧洖搴撲腑锛岃烦杩囧鐞� - 鐘舵��: {lockInfo.Status}");
+                    return;
+                }
+
+                // 鑾峰彇搴撳瓨鏄庣粏
+                var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                    .FirstAsync(x => x.Barcode == lockInfo.CurrentBarcode && x.StockId == lockInfo.StockId);
+
+                if (stockDetail == null)
+                {
+                    _logger.LogError($"鏈壘鍒板簱瀛樻槑缁� - 鏉$爜: {lockInfo.CurrentBarcode}, StockId: {lockInfo.StockId}");
+                    throw new InvalidOperationException($"搴撳瓨鏄庣粏涓嶅瓨鍦�: {lockInfo.CurrentBarcode}");
+                }
+
+                // 璁板綍鍘熷鐘舵��
+                decimal originalStockQty = stockDetail.StockQuantity;
+                decimal originalOutboundQty = stockDetail.OutboundQuantity;
+                int originalStatus = stockDetail.Status;
+
+                _logger.LogInformation($"鏈垎閰嶉攣瀹氬洖搴撳墠鐘舵��:");
+                _logger.LogInformation($"  搴撳瓨 - 鏉$爜: {stockDetail.Barcode}, 鏁伴噺: {originalStockQty}, 鍑哄簱: {originalOutboundQty}, 鐘舵��: {GetStockStatusName(originalStatus)}");
+
+                // 瀵逛簬鏈垎閰嶉攣瀹氳褰曪紝搴撳瓨鏁伴噺涓嶅簲鏀瑰彉锛�
+                // 鍥犱负搴撳瓨鏈潵灏卞瓨鍦紝鍙槸鐘舵�佽閿佸畾
+                // stockDetail.StockQuantity 淇濇寔涓嶅彉
+
+                // 鍑哄簱鏁伴噺搴斾负0锛堟湭鍒嗛厤閿佸畾涓嶅簲璇ユ湁鍑哄簱锛�
+                if (stockDetail.OutboundQuantity > 0)
+                {
+                    _logger.LogWarning($"鏈垎閰嶉攣瀹氱殑搴撳瓨鍑哄簱鏁伴噺涓嶄负0锛岄噸缃负0 - 鏉$爜: {stockDetail.Barcode}, 褰撳墠鍑哄簱: {stockDetail.OutboundQuantity}");
+                    stockDetail.OutboundQuantity = 0;
+                }
+
+                // 鏇存柊搴撳瓨鐘舵�佷负鍏ュ簱瀹屾垚锛堟仮澶嶄负鍙敤鐘舵�侊級
+                stockDetail.Status = (int)StockStatusEmun.鍏ュ簱瀹屾垚;
+
+                await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+
+                _logger.LogInformation($"鏇存柊鏈垎閰嶅簱瀛樼姸鎬� - 鏉$爜: {stockDetail.Barcode}");
+                _logger.LogInformation($"  搴撳瓨鏁伴噺: {originalStockQty} -> {stockDetail.StockQuantity} (淇濇寔涓嶅彉)");
+                _logger.LogInformation($"  鍑哄簱鏁伴噺: {originalOutboundQty} -> {stockDetail.OutboundQuantity}");
+                _logger.LogInformation($"  鐘舵��: {GetStockStatusName(originalStatus)} -> {GetStockStatusName(stockDetail.Status)}");
+
+                // 鏇存柊閿佸畾璁板綍鐘舵�佷负宸插洖搴�
+                lockInfo.Status = (int)OutLockStockStatusEnum.宸插洖搴�;
+                lockInfo.Operator = App.User.UserName;
+
+                await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
+
+                _logger.LogInformation($"鏇存柊鏈垎閰嶉攣瀹氱姸鎬� - 閿佸畾ID: {lockInfo.Id}, 鐘舵��: 鍑哄簱涓� -> 宸插洖搴�");
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"澶勭悊鏈垎閰嶉攣瀹氬洖搴撳け璐� - 閿佸畾ID: {lockInfo.Id}, Error: {ex.Message}");
+                throw new InvalidOperationException($"澶勭悊鏈垎閰嶉攣瀹氬洖搴撳け璐�: {ex.Message}", ex);
+            }
+        }
+
+        /// <summary>
+        /// 澶勭悊鏈垎閰嶅簱瀛樺洖搴�
+        /// </summary>
+        private async Task ProcessUnallocatedStockReturn(Dt_StockInfoDetail stockDetail)
+        {
+            _logger.LogInformation($"澶勭悊鏈垎閰嶅簱瀛樺洖搴� - 鏉$爜: {stockDetail.Barcode}, 鏁伴噺: {stockDetail.StockQuantity}");
+
+            // 鐩存帴鏇存柊搴撳瓨鐘舵��
+            stockDetail.Status = (int)StockStatusEmun.鍏ュ簱瀹屾垚;
+            await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+        }
+
+
+        /// <summary>
+        /// 鍥炲簱鍚庢暟鎹獙璇� - 澧炲己鐗�
+        /// </summary>
+        private async Task ValidateDataAfterReturn(string orderNo, string palletCode, int stockId)
+        {
+            try
+            {
+                _logger.LogInformation($"寮�濮嬪洖搴撳悗鏁版嵁楠岃瘉");
+
+                //  楠岃瘉搴撳瓨鐘舵�佸拰鏁伴噺
+                var stockDetails = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                    .Where(x => x.StockId == stockId)
+                    .ToListAsync();
+
+                decimal totalStock = stockDetails.Sum(x => x.StockQuantity);
+
+                // 楠岃瘉搴撳瓨鏁伴噺鏄惁鍚堢悊
+                var unreasonableStocks = stockDetails.Where(x => x.StockQuantity < 0).ToList();
+                if (unreasonableStocks.Any())
+                {
+                    _logger.LogError($"鍙戠幇璐熸暟搴撳瓨鏁伴噺锛佹潯鐮�: {string.Join(", ", unreasonableStocks.Select(x => x.Barcode))}");
+                }
+
+                //  楠岃瘉閿佸畾璁板綍鐘舵��
+                var lockInfos = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                    .Where(x => x.OrderNo == orderNo && x.PalletCode == palletCode)
+                    .ToListAsync();
+
+                var notReturnedLocks = lockInfos.Where(x =>
+                    x.Status != (int)OutLockStockStatusEnum.宸插洖搴� &&
+                    x.Status != (int)OutLockStockStatusEnum.宸插彇璧� &&
+                    x.Status != (int)OutLockStockStatusEnum.鎷i�夊畬鎴�).ToList();
+
+                if (notReturnedLocks.Any())
+                {
+                    _logger.LogWarning($"鍥炲簱鍚庝粛鏈夋湭鍥炲簱鐘舵�佺殑閿佸畾璁板綍: {notReturnedLocks.Count}鏉�");
+                    foreach (var lockInfo in notReturnedLocks)
+                    {
+                        _logger.LogWarning($"鏈洖搴撻攣瀹� - ID: {lockInfo.Id}, 鐘舵��: {GetLockStatusName(lockInfo.Status)}, 鏉$爜: {lockInfo.CurrentBarcode}");
+                    }
+                }
+
+                // 鏁版嵁涓�鑷存�ч獙璇�
+                decimal totalExpectedReturnQty = lockInfos
+                    .Where(x => x.Status == (int)OutLockStockStatusEnum.宸插洖搴�)
+                    .Sum(x => x.AssignQuantity - x.PickedQty);
+
+                _logger.LogInformation($"鍥炲簱楠岃瘉姹囨��:");
+                _logger.LogInformation($"  鍥炲簱鍚庡簱瀛樻�婚噺: {totalStock}");
+                _logger.LogInformation($"  宸插洖搴撻攣瀹氳褰曟暟閲�: {lockInfos.Count(x => x.Status == (int)OutLockStockStatusEnum.宸插洖搴�)}");
+                _logger.LogInformation($"  鎬诲洖搴撴暟閲忥紙閿佸畾璁板綍璁$畻锛�: {totalExpectedReturnQty}");
+
+                // 楠岃瘉搴撳瓨鏁伴噺涓庨攣瀹氳褰曠殑涓�鑷存��
+                foreach (var lockInfo in lockInfos.Where(x => !string.IsNullOrEmpty(x.CurrentBarcode)))
+                {
+                    var stock = stockDetails.FirstOrDefault(x => x.Barcode == lockInfo.CurrentBarcode);
+                    if (stock != null)
+                    {
+                        // 濡傛灉閿佸畾璁板綍鏄凡鍥炲簱鐘舵�侊紝瀵瑰簲鐨勫簱瀛樺簲璇ユ槸鍏ュ簱瀹屾垚鐘舵��
+                        if (lockInfo.Status == (int)OutLockStockStatusEnum.宸插洖搴� &&
+                            stock.Status != (int)StockStatusEmun.鍏ュ簱瀹屾垚)
+                        {
+                            _logger.LogWarning($"閿佸畾璁板綍宸插洖搴撲絾搴撳瓨鐘舵�佷笉姝g‘ - 鏉$爜: {lockInfo.CurrentBarcode}, 搴撳瓨鐘舵��: {GetStockStatusName(stock.Status)}");
+                        }
+                    }
+                }
+
+                _logger.LogInformation($"鍥炲簱鍚庢暟鎹獙璇佸畬鎴�");
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"鍥炲簱鍚庨獙璇佸け璐�: {ex.Message}");
+            }
+        }
+
+    
+        private string GetLockStatusName(int status)
+        {
+            return status switch
+            {
+                1 => "鍑哄簱涓�",
+                2 => "鎷i�夊畬鎴�",
+                3 => "宸插洖搴�",
+                4 => "宸插彇璧�",
+                _ => $"鏈煡({status})"
+            };
+        }
+
+        /// <summary>
+        /// 绠�鍖栧洖搴撴暟鎹搷浣滐紙褰撲富鏂规硶澶辫触鏃朵娇鐢級
+        /// </summary>
+        private async Task ExecuteSimpleReturnDataOperations(PalletStatusAnalysis statusAnalysis)
+        {
+            _logger.LogInformation($"銆愮畝鍖栧洖搴撱�戝紑濮嬫墽琛岀畝鍖栧洖搴撴搷浣�");
+
+            try
+            {
+                // 鑾峰彇璇ユ墭鐩樼殑鎵�鏈夋潯鐮侊紙鍖呮嫭鎵�鏈夌姸鎬佺殑搴撳瓨锛�
+                var allStockDetails = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                    .Where(x => x.StockId == statusAnalysis.StockId)
+                    .ToListAsync();
+
+                _logger.LogInformation($"鎵惧埌 {allStockDetails.Count} 涓簱瀛樻槑缁嗚褰�");
+
+                foreach (var stockDetail in allStockDetails)
+                {
+                    // 璁板綍鍘熷鐘舵��
+                    int originalStatus = stockDetail.Status;
+                    decimal originalStockQty = stockDetail.StockQuantity;
+
+                    // 灏嗘墍鏈夊嚭搴撶浉鍏崇殑鐘舵�佹仮澶嶄负鍏ュ簱瀹屾垚
+                    if (stockDetail.Status == (int)StockStatusEmun.鍑哄簱閿佸畾 ||
+                        //stockDetail.Status == (int)StockStatusEmun.鍑哄簱涓� ||
+                        stockDetail.Status == (int)StockStatusEmun.鍑哄簱瀹屾垚)
+                    {
+                        // 濡傛灉鏄嚭搴撳畬鎴愮姸鎬佷笖搴撳瓨涓�0锛屽彲鑳介渶瑕佺壒娈婂鐞�
+                        if (stockDetail.Status == (int)StockStatusEmun.鍑哄簱瀹屾垚 && stockDetail.StockQuantity == 0)
+                        {
+                            _logger.LogInformation($"璺宠繃宸插嚭搴撳畬鎴愮殑闆跺簱瀛樻潯鐮�: {stockDetail.Barcode}");
+                            continue;
+                        }
+
+                        stockDetail.Status = (int)StockStatusEmun.鍏ュ簱瀹屾垚;
+
+                        // 濡傛灉鏄嚭搴撻攣瀹氱姸鎬佷絾搴撳瓨涓�0锛岄噸缃簱瀛樹负1锛堥伩鍏嶉浂搴撳瓨闂锛�
+                        if (stockDetail.Status == (int)StockStatusEmun.鍑哄簱閿佸畾 && stockDetail.StockQuantity == 0)
+                        {
+                            // 鏌ユ壘鏄惁鏈夊搴旂殑閿佸畾璁板綍鏉ョ‘瀹氬簲璇ユ仮澶嶇殑鏁伴噺
+                            var lockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                                .Where(x => x.CurrentBarcode == stockDetail.Barcode &&
+                                           x.StockId == stockDetail.StockId)
+                                .FirstAsync();
+
+                            if (lockInfo != null)
+                            {
+                                stockDetail.StockQuantity = lockInfo.AssignQuantity - lockInfo.PickedQty;
+                                _logger.LogInformation($"鎭㈠闆跺簱瀛樻潯鐮佺殑鏁伴噺 - 鏉$爜: {stockDetail.Barcode}, 鏁伴噺: {stockDetail.StockQuantity}");
+                            }
+                        }
+
+                        await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+                        _logger.LogInformation($"绠�鍖栧洖搴� - 鏉$爜: {stockDetail.Barcode}, 鐘舵��: {GetStockStatusName(originalStatus)} -> 鍏ュ簱瀹屾垚, 鏁伴噺: {originalStockQty} -> {stockDetail.StockQuantity}");
+                    }
+                }
+
+                // 鏇存柊鎵�鏈夐攣瀹氳褰曚负宸插洖搴�
+                var allLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                    .Where(x => x.OrderNo == statusAnalysis.OrderNo &&
+                               x.PalletCode == statusAnalysis.PalletCode &&
+                               (x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓� ||
+                                x.Status == (int)OutLockStockStatusEnum.鎷i�夊畬鎴�))
+                    .ToListAsync();
+
+                foreach (var lockInfo in allLocks)
+                {
+                    lockInfo.Status = (int)OutLockStockStatusEnum.宸插洖搴�;
+                    lockInfo.Operator = App.User.UserName;
+
+                    await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
+                    _logger.LogInformation($"绠�鍖栧洖搴� - 閿佸畾璁板綍: {lockInfo.Id}, 鐘舵��: 宸插洖搴�");
+                }
+
+                _logger.LogInformation($"銆愮畝鍖栧洖搴撱�戝畬鎴� - 澶勭悊 {allStockDetails.Count} 涓潯鐮�, {allLocks.Count} 鏉¢攣瀹氳褰�");
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"绠�鍖栧洖搴撳け璐�: {ex.Message}");
+                throw;
+            }
+        }
+
+        /// <summary>
+        /// 鑾峰彇搴撳瓨鐘舵�佸悕绉�
+        /// </summary>
+        private string GetStockStatusName(int status)
+        {
+            return status switch
+            {
+                1 => "鍏ュ簱纭",
+                2 => "鍏ュ簱瀹屾垚",
+                3 => "鍑哄簱閿佸畾",
+                4 => "鍑哄簱涓�",
+                5 => "鍑哄簱瀹屾垚",
+                6 => "宸叉竻鐞�",
+                _ => $"鏈煡({status})"
+            };
+        }
+
+
+        /// <summary>
+        /// 鍒涘缓鍥炲簱浠诲姟
+        /// </summary>
+        private async Task CreateReturnTask(string orderNo, string palletCode, Dt_StockInfo stockInfo)
+        {
+            // 鑾峰彇褰撳墠浠诲姟淇℃伅
+            var currentTask = await _taskRepository.Db.Queryable<Dt_Task>()
+                .Where(x => x.OrderNo == orderNo && x.PalletCode == palletCode)
+                .FirstAsync();
+
+            if (currentTask != null)
+            {
+                // 鍒嗛厤鏂拌揣浣�
+                var newLocation = _locationInfoService.AssignLocation(stockInfo.LocationType);
+
+                var returnTask = new Dt_Task()
+                {
+                    CurrentAddress = stations[currentTask.TargetAddress],
+                    Grade = 0,
+                    PalletCode = palletCode,
+                    NextAddress = "",
+                    OrderNo = orderNo,
+                    Roadway = newLocation.RoadwayNo,
+                    SourceAddress = stations[currentTask.TargetAddress],
+                    TargetAddress = newLocation.LocationCode,
+                    TaskStatus = TaskStatusEnum.New.ObjToInt(),
+                    TaskType = TaskTypeEnum.InPick.ObjToInt(),
+                    PalletType = stockInfo.PalletType,
+                    WarehouseId = currentTask.WarehouseId
+                };
+                var targetAddress = currentTask.TargetAddress;
+
+                try
+                {
+                    await _taskRepository.Db.Insertable(returnTask).ExecuteCommandAsync();
+
+                    _logger.LogInformation($"CreateReturnTaskAndHandleESS  鍒嗘壒鍒犻櫎鍘嗗彶浠诲姟: {orderNo} 锛� {currentTask.TaskNum}");
+                    // 鍒犻櫎鍘熷鍑哄簱浠诲姟
+                    //_taskRepository.DeleteAndMoveIntoHty(originalTask, OperateTypeEnum.鑷姩瀹屾垚);
+                    var result = _task_HtyService.DeleteAndMoveIntoHty(currentTask, OperateTypeEnum.浜哄伐鍒犻櫎);
+                    await _taskRepository.Db.Deleteable(currentTask).ExecuteCommandAsync();
+
+                    if (!result)
+                    {
+                        await _taskRepository.Db.Deleteable(currentTask).ExecuteCommandAsync();
+                    }
+                    _logger.LogInformation($"CreateReturnTaskAndHandleESS  鍒嗘壒鍒犻櫎鍘嗗彶浠诲姟: {orderNo} 锛� {currentTask.TaskNum},褰卞搷琛�  {result}");
+
+                }
+                catch (Exception ex)
+                {
+                    _logger.LogInformation($"鍒涘缓鍥炲簱浠诲姟澶辫触 - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}");
+                    throw new Exception($"鍒涘缓鍥炲簱浠诲姟澶辫触 - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}");
+
+                }
+                // 鍙戦�丒SS鍛戒护
+                await SendESSCommands(palletCode, targetAddress, returnTask);
+
+                _logger.LogInformation($"鍒涘缓鍥炲簱浠诲姟鎴愬姛 - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}");
+            }
+        }
+
+        /// <summary>
+        /// 鏇存柊鍥炲簱鍚庣殑璁㈠崟鐘舵��
+        /// </summary>
+        private async Task UpdateOrderStatusAfterReturn(string orderNo)
+        {
+            // 妫�鏌ヨ鍗曟槸鍚﹁繕鏈夋湭瀹屾垚鐨勯攣瀹氳褰�
+            var activeLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                .Where(x => x.OrderNo == orderNo &&
+                           (x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓� ||
+                            x.Status == (int)OutLockStockStatusEnum.鍥炲簱涓�))
+                .ToListAsync();
+
+            if (!activeLocks.Any())
+            {
+                // 鎵�鏈夐攣瀹氳褰曢兘宸插畬鎴愭垨宸插洖搴擄紝鏇存柊璁㈠崟鐘舵��
+                await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
+                    .SetColumns(x => new Dt_OutboundOrder
+                    {
+                        OrderStatus = (int)OutOrderStatusEnum.鍑哄簱瀹屾垚,
+                    })
+                    .Where(x => x.OrderNo == orderNo)
+                    .ExecuteCommandAsync();
+
+                _logger.LogInformation($"鏇存柊璁㈠崟鐘舵�佷负鍑哄簱瀹屾垚 - 璁㈠崟: {orderNo}");
+            }
+        }
+
+        /// <summary>
+        /// 澶勭悊绌烘墭鐩樺洖搴�
+        /// </summary>
+        private async Task<WebResponseContent> HandleEmptyPalletReturn(string orderNo, string palletCode, Dt_StockInfo stockInfo)
+        {
+            _logger.LogInformation($"澶勭悊绌烘墭鐩樺洖搴� - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}");
+
+            try
+            {
+                // 娓呯悊闆跺簱瀛樻暟鎹�
+                await CleanupZeroStockData(stockInfo.Id);
+
+                // 鑾峰彇褰撳墠浠诲姟
+                var currentTask = await GetCurrentTask(orderNo, palletCode);
+                if (currentTask == null)
+                {
+                    return WebResponseContent.Instance.Error("鏈壘鍒板綋鍓嶄换鍔�");
+                }
+                // 鍒涘缓绌烘墭鐩樺簱瀛樿褰�
+                var emptyStockInfo = new Dt_StockInfo()
+                {
+                    PalletType = PalletTypeEnum.Empty.ObjToInt(),
+                    StockStatus = StockStatusEmun.缁勭洏鏆傚瓨.ObjToInt(),
+                    PalletCode = palletCode,
+                    LocationType = stockInfo.LocationType
+                };
+                emptyStockInfo.Details = new List<Dt_StockInfoDetail>();
+                _stockInfoService.AddMaterielGroup(emptyStockInfo);
+
+                // 鍒涘缓鍥炲簱浠诲姟锛堜笉鍙戦�丒SS鍛戒护锛�
+                var returnTaskInfo = await CreateEmptyPalletReturnTask(orderNo, palletCode, emptyStockInfo, currentTask);
+
+                return WebResponseContent.Instance.OK("绌烘墭鐩樺洖搴撴垚鍔�", returnTaskInfo);
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"绌烘墭鐩樺洖搴撳け璐� HandleEmptyPalletReturn: {ex.Message}");
+                return WebResponseContent.Instance.Error($"绌烘墭鐩樺洖搴撳け璐� HandleEmptyPalletReturn: {ex.Message}");
+            }
+        }
+
+        private async Task<Dt_Task> GetCurrentTask(string orderNo, string palletCode)
+        {
+            // 鍏堝皾璇曢�氳繃璁㈠崟鍙峰拰鎵樼洏鍙锋煡鎵句换鍔�
+            var task = await _taskRepository.Db.Queryable<Dt_Task>()
+                .Where(x => x.OrderNo == orderNo && x.PalletCode == palletCode)
+                .FirstAsync();
+
+            if (task == null)
+            {
+                // 濡傛灉鎵句笉鍒帮紝鍐嶉�氳繃鎵樼洏鍙锋煡鎵�
+                task = await _taskRepository.Db.Queryable<Dt_Task>()
+                    .Where(x => x.PalletCode == palletCode)
+                    .FirstAsync();
+            }
+
+            return task;
+        }
+
+        // <summary>
+        /// 鍒涘缓绌烘墭鐩樺洖搴撲换鍔★紙涓嶅彂閫丒SS鍛戒护锛�
+        /// </summary>
+        private async Task<ReturnTaskInfo> CreateEmptyPalletReturnTask(string orderNo, string palletCode, Dt_StockInfo emptyStockInfo, Dt_Task currentTask)
+        {
+            try
+            {
+                // 鍒嗛厤鏂拌揣浣�
+                var newLocation = _locationInfoService.AssignLocation(emptyStockInfo.LocationType);
+
+                var returnTask = new Dt_Task()
+                {
+                    CurrentAddress = stations[currentTask.TargetAddress],
+                    Grade = 0,
+                    PalletCode = palletCode,
+                    NextAddress = "",
+                    OrderNo = orderNo,
+                    Roadway = newLocation.RoadwayNo,
+                    SourceAddress = stations[currentTask.TargetAddress],
+                    TargetAddress = newLocation.LocationCode,
+                    TaskStatus = TaskStatusEnum.New.ObjToInt(),
+                    TaskType = TaskTypeEnum.InEmpty.ObjToInt(),
+                    PalletType = PalletTypeEnum.Empty.ObjToInt(),
+                    WarehouseId = currentTask.WarehouseId
+                };
+
+                await _taskRepository.Db.Insertable(returnTask).ExecuteCommandAsync();
+
+                _logger.LogInformation($"鍒涘缓绌烘墭鐩樺洖搴撲换鍔℃垚鍔�: {returnTask.TaskNum}");
+
+                // 鍒犻櫎鍘熷鍑哄簱浠诲姟
+                var result = _task_HtyService.DeleteAndMoveIntoHty(currentTask, OperateTypeEnum.浜哄伐鍒犻櫎);
+                await _taskRepository.Db.Deleteable(currentTask).ExecuteCommandAsync();
+
+                if (!result)
+                {
+                    await _taskRepository.Db.Deleteable(currentTask).ExecuteCommandAsync();
+                }
+
+                // 杩斿洖浠诲姟淇℃伅
+                return new ReturnTaskInfo
+                {
+                    ShouldSendESS = true,
+                    PalletCode = palletCode,
+                    OriginalTaskTargetAddress = currentTask.TargetAddress,
+                    ReturnTask = returnTask
+                };
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"鍒涘缓绌烘墭鐩樺洖搴撲换鍔″け璐�: {ex.Message}");
+                throw;
+            }
+        }
+
+        /// <summary>
+        /// 鍒嗘瀽鎵樼洏鐘舵�佺敤浜庡洖搴� - 淇鐗堬紙瑙e喅鎷嗗寘璁板綍閲嶅璁$畻闂锛�
+        /// </summary>
+        private async Task<PalletStatusAnalysis> AnalyzePalletStatusForReturn(string orderNo, string palletCode, int stockId)
+        {
+            var result = new PalletStatusAnalysis
+            {
+                OrderNo = orderNo,
+                PalletCode = palletCode,
+                StockId = stockId,
+                AllBarcodes = new List<string>(),
+                ProcessedBarcodes = new HashSet<string>()
+            };
+
+            _logger.LogInformation($"銆愬洖搴撳垎鏋愩�戝紑濮嬪垎鏋愭墭鐩樼姸鎬� - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}, StockId: {stockId}");
+
+            try
+            {
+                //  棣栧厛鑾峰彇鎵樼洏涓婃墍鏈夌殑搴撳瓨鏄庣粏锛堝熀纭�鏁版嵁锛�
+                var allStockDetails = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                    .Where(x => x.StockId == stockId && x.StockQuantity > 0)
+                    .ToListAsync();
+
+                _logger.LogInformation($"鎵惧埌 {allStockDetails.Count} 涓湁搴撳瓨鐨勬槑缁嗚褰�");
+
+                //  鍒嗘瀽鎵�鏈夐攣瀹氳褰曪紙宸插垎閰嶅拰鏈垎閰嶏級
+                var allLockInfos = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                    .Where(x => x.OrderNo == orderNo && x.PalletCode == palletCode)
+                    .ToListAsync();
+
+                // 鍖哄垎宸插垎閰嶅拰鏈垎閰嶉攣瀹氳褰�
+                var allocatedLocks = allLockInfos
+                    .Where(x => x.IsUnallocated != 1 && x.OrderDetailId > 0 &&
+                               x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�)
+                    .ToList();
+
+                var unallocatedLocks = allLockInfos
+                    .Where(x => (x.IsUnallocated == 1 || x.OrderDetailId == 0) &&
+                               x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�)
+                    .ToList();
+
+                // 澶勭悊宸插垎閰嶉攣瀹氳褰�
+                if (allocatedLocks.Any())
+                {
+                    result.HasRemainingLocks = true;
+                    result.RemainingLocks = allocatedLocks;
+
+                    // 瀵逛簬宸插垎閰嶉攣瀹氳褰曪紝鍥炲簱鏁伴噺鏄湭鎷i�夌殑閮ㄥ垎
+                    result.RemainingLocksReturnQty = allocatedLocks.Sum(x =>
+                    {
+                        var returnQty = x.AssignQuantity - x.PickedQty;
+                        return returnQty > 0 ? returnQty : 0;
+                    });
+
+                    foreach (var lockInfo in allocatedLocks)
+                    {
+                        if (!string.IsNullOrEmpty(lockInfo.CurrentBarcode))
+                        {
+                            result.AllBarcodes.Add(lockInfo.CurrentBarcode);
+                            result.ProcessedBarcodes.Add(lockInfo.CurrentBarcode);
+                        }
+                    }
+                    _logger.LogInformation($"鍙戠幇 {allocatedLocks.Count} 鏉″凡鍒嗛厤閿佸畾璁板綍锛屽洖搴撴暟閲�: {result.RemainingLocksReturnQty}");
+                }
+
+                // 澶勭悊鏈垎閰嶉攣瀹氳褰曪紙鑷姩鎷嗗寘浜х敓鐨勶級
+                if (unallocatedLocks.Any())
+                {
+                    result.HasUnallocatedLocks = true;
+                    result.UnallocatedLocks = unallocatedLocks;
+
+                    // 瀵逛簬鏈垎閰嶉攣瀹氳褰曪紝鍥炲簱鏁伴噺鏄畠鐨勫垎閰嶆暟閲忥紙鍥犱负鏈嫞閫夎繃锛�
+                    // 浣嗗疄闄呬笂锛屽簱瀛樻湰鏉ュ氨瀛樺湪锛屽彧鏄姸鎬侀渶瑕佹仮澶�
+                    result.UnallocatedLocksReturnQty = unallocatedLocks.Sum(x => x.AssignQuantity);
+
+                    foreach (var lockInfo in unallocatedLocks)
+                    {
+                        if (!string.IsNullOrEmpty(lockInfo.CurrentBarcode) &&
+                            !result.ProcessedBarcodes.Contains(lockInfo.CurrentBarcode))
+                        {
+                            result.AllBarcodes.Add(lockInfo.CurrentBarcode);
+                            result.ProcessedBarcodes.Add(lockInfo.CurrentBarcode);
+                        }
+                    }
+                    _logger.LogInformation($"鍙戠幇 {unallocatedLocks.Count} 鏉℃湭鍒嗛厤閿佸畾璁板綍锛屽洖搴撴暟閲忥紙鐘舵�佹仮澶嶏級: {result.UnallocatedLocksReturnQty}");
+                }
+
+                // 閲嶆柊璁$畻鎬诲洖搴撴暟閲�
+                // 瀵逛簬宸插垎閰嶉攣瀹氾細鍥炲簱鏁伴噺 = 鏈嫞閫夋暟閲�
+                // 瀵逛簬鏈垎閰嶉攣瀹氾細娌℃湁瀹為檯鐨勫簱瀛樻暟閲忓彉鍖栵紝鍙槸鐘舵�佹仮澶�
+                result.TotalReturnQty = result.RemainingLocksReturnQty; // 鍙绠楀凡鍒嗛厤閿佸畾鐨勫洖搴撴暟閲�
+
+                // 璁板綍搴撳瓨鏁伴噺锛堢敤浜庨獙璇侊級
+                decimal totalStockOnPallet = allStockDetails.Sum(x => x.StockQuantity);
+
+                _logger.LogInformation($"鍥炲簱鍒嗘瀽瀹屾垚:");
+                _logger.LogInformation($"  鎵樼洏鎬诲簱瀛�: {totalStockOnPallet}");
+                _logger.LogInformation($"  宸插垎閰嶉攣瀹氬洖搴撴暟閲�: {result.RemainingLocksReturnQty}");
+                _logger.LogInformation($"  鏈垎閰嶉攣瀹氱姸鎬佹仮澶嶆暟閲�: {result.UnallocatedLocksReturnQty}");
+                _logger.LogInformation($"  瀹為檯鐗╃悊鍥炲簱鏁伴噺: {result.TotalReturnQty}");
+
+                result.HasItemsToReturn = result.TotalReturnQty > 0 || result.UnallocatedLocksReturnQty > 0;
+                result.IsEmptyPallet = !result.HasItemsToReturn;
+
+                return result;
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"鍥炲簱鍒嗘瀽澶辫触 - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}, Error: {ex.Message}");
+                throw;
+            }
+        }       
+     
+        /// <summary>
+        /// 鍒嗘壒鍥炲簱 - 璋冪敤缁熶竴鍥炲簱鏂规硶
+        /// </summary>
+        public async Task<WebResponseContent> BatchReturnStock(string orderNo, string palletCode)
+        {
+            return await ExecutePalletReturn(orderNo, palletCode, "鍒嗘壒鍥炲簱");
+        }
+
+      
+
+        /// <summary>
+        /// 鍙栬蛋绌虹 -姝g‘澶勭悊鏈垎閰嶉攣瀹氳褰�
+        /// </summary>
+        public async Task<WebResponseContent> RemoveEmptyPallet(string orderNo, string palletCode)
+        {
+            try
+            {
+                _logger.LogInformation($"銆愬彇璧扮┖绠卞紑濮嬨�戣鍗�: {orderNo}, 鎵樼洏: {palletCode}");
+
+                _unitOfWorkManage.BeginTran();
+
+                //  鍏堝皾璇曟墽琛屽洖搴撴搷浣滐紝纭繚鎵�鏈夌墿鍝侀兘鍥炲簱
+                _logger.LogInformation($"姝ラ1: 鍏堟墽琛屽洖搴撴搷浣�");
+                var returnResult = await ExecutePalletReturn(orderNo, palletCode, "鍙栬蛋绌虹鍓嶅洖搴�");
+
+                // 鍗充娇鍥炲簱澶辫触锛岀户缁獙璇佺┖绠辨潯浠讹紙鍙兘鏄湡鐨勭┖鎵樼洏锛�
+                if (!returnResult.Status)
+                {
+                    _logger.LogWarning($"鍥炲簱鎿嶄綔鍙兘澶辫触鎴栨棤鐗╁搧: {returnResult.Message}");
+                }
+
+                // 楠岃瘉绌虹鍙栬蛋鏉′欢锛堝繀椤诲叏閮ㄥ畬鎴愭嫞閫夋垨宸插洖搴擄級
+                _logger.LogInformation($"姝ラ2: 楠岃瘉绌虹鍙栬蛋鏉′欢");
+
+                // 鑾峰彇鎵樼洏鐨勬墍鏈夐攣瀹氳褰曪紙鍖呮嫭宸插洖搴撳拰宸插彇璧扮殑锛�
+                var allLockInfos = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                    .Where(x => x.OrderNo == orderNo && x.PalletCode == palletCode)
+                    .ToListAsync();
+
+                if (!allLockInfos.Any())
+                {
+                    _unitOfWorkManage.RollbackTran();
+                    return WebResponseContent.Instance.Error("璇ユ墭鐩樻病鏈夐攣瀹氳褰�");
+                }
+
+                // 妫�鏌ユ槸鍚︽湁鏈畬鎴愮殑閿佸畾璁板綍
+                var unfinishedLocks = allLockInfos.Where(x =>
+                    x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓� ||
+                    x.Status == (int)OutLockStockStatusEnum.鍥炲簱涓�).ToList();
+
+                if (unfinishedLocks.Any())
+                {
+                    var unfinishedCount = unfinishedLocks.Count;
+                    // 鍖哄垎宸插垎閰嶅拰鏈垎閰�
+                    var allocatedUnfinished = unfinishedLocks.Where(x => x.IsUnallocated != 1).ToList();
+                    var unallocatedUnfinished = unfinishedLocks.Where(x => x.IsUnallocated == 1).ToList();
+
+                    string errorMsg = $"鎵樼洏杩樻湁{unfinishedCount}鏉℃湭瀹屾垚璁板綍";
+                    if (allocatedUnfinished.Any()) errorMsg += $"锛屽叾涓凡鍒嗛厤{allocatedUnfinished.Count}鏉�";
+                    if (unallocatedUnfinished.Any()) errorMsg += $"锛屾湭鍒嗛厤{unallocatedUnfinished.Count}鏉�";
+
+                    errorMsg += "锛屼笉鑳藉彇璧扮┖绠�";
+
+                    _unitOfWorkManage.RollbackTran();
+                    return WebResponseContent.Instance.Error(errorMsg);
+                }
+
+                // 鑾峰彇宸插畬鎴愮殑閿佸畾璁板綍锛堢姸鎬佷负鎷i�夊畬鎴愭垨宸插彇璧帮級
+                var completedLocks = allLockInfos.Where(x =>
+                    x.Status == (int)OutLockStockStatusEnum.鎷i�夊畬鎴� ||
+                    x.Status == (int)OutLockStockStatusEnum.宸插彇璧�).ToList();
+
+                if (!completedLocks.Any())
+                {
+                    // 妫�鏌ユ槸鍚﹂兘鏄凡鍥炲簱鐘舵��
+                    var returnedLocks = allLockInfos.Where(x => x.Status == (int)OutLockStockStatusEnum.宸插洖搴�).ToList();
+                    if (returnedLocks.Any())
+                    {
+                        _logger.LogInformation($"鎵�鏈夐攣瀹氳褰曢兘宸插洖搴擄紝鍙互鍙栬蛋绌虹");
+                        completedLocks = returnedLocks;
+                    }
+                    else
+                    {
+                        _unitOfWorkManage.RollbackTran();
+                        return WebResponseContent.Instance.Error("璇ユ墭鐩樻病鏈夊凡瀹屾垚鎷i�夋垨宸插洖搴撶殑璁板綍");
+                    }
+                }
+
+                _logger.LogInformation($"楠岃瘉閫氳繃锛屾壘鍒� {completedLocks.Count} 鏉″凡瀹屾垚璁板綍");
+
+                //  娓呯悊宸插畬鎴愮殑閿佸畾璁板綍锛堟爣璁颁负宸插彇璧帮級
+                _logger.LogInformation($"姝ラ3: 娓呯悊閿佸畾璁板綍");
+                foreach (var lockInfo in completedLocks)
+                {
+                    // 鍙鐞嗙姸鎬佷笉鏄凡鍙栬蛋鐨勮褰�
+                    if (lockInfo.Status != (int)OutLockStockStatusEnum.宸插彇璧�)
+                    {
+                        lockInfo.Status = (int)OutLockStockStatusEnum.宸插彇璧�;
+                        lockInfo.Operator = App.User.UserName;
+                        await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
+                        _logger.LogInformation($"閿佸畾璁板綍鏍囪涓哄凡鍙栬蛋 - ID: {lockInfo.Id}");
+                    }
+                }
+
+                // 娓呯悊瀵瑰簲鐨勫簱瀛樿褰曠姸鎬�
+                _logger.LogInformation($"姝ラ4: 娓呯悊搴撳瓨璁板綍");
+                foreach (var lockInfo in completedLocks)
+                {
+                    await CleanupStockInfo(lockInfo);
+                }
+
+                // 鏇存柊鐩稿叧璁㈠崟鐘舵��
+                _logger.LogInformation($"姝ラ5: 鏇存柊璁㈠崟鐘舵��");
+                await UpdateOrderStatusAfterPalletRemoval(orderNo);
+
+                // 璁板綍鎿嶄綔鍘嗗彶
+                //_logger.LogInformation($"姝ラ6: 璁板綍鎿嶄綔鍘嗗彶");
+                //await RecordEmptyPalletRemoval(orderNo, palletCode, completedLocks);
+
+                _unitOfWorkManage.CommitTran();
+
+                _logger.LogInformation($"銆愬彇璧扮┖绠辨垚鍔熴�戣鍗�: {orderNo}, 鎵樼洏: {palletCode}");
+
+                return WebResponseContent.Instance.OK("鍙栬蛋绌虹鎴愬姛");
+            }
+            catch (Exception ex)
+            {
+                _unitOfWorkManage.RollbackTran();
+                _logger.LogError($"鍙栬蛋绌虹澶辫触 - OrderNo: {orderNo}, PalletCode: {palletCode}, Error: {ex.Message}");
+                return WebResponseContent.Instance.Error($"鍙栬蛋绌虹澶辫触锛歿ex.Message}");
+            }
+        }
+ 
+        #endregion
+
+       #region 杈呭姪鏂规硶
+            
+        private async Task CleanupZeroStockData(int stockId)
+        {
+            try
+            {
+                // 鍒犻櫎搴撳瓨鏁伴噺涓�0鐨勬槑缁嗚褰�
+                var deleteDetailCount = await _stockInfoDetailService.Db.Deleteable<Dt_StockInfoDetail>()
+            .Where(x => x.StockId == stockId && x.StockQuantity == 0)
+            .ExecuteCommandAsync();
+
+                await _stockInfoService.Db.Deleteable<Dt_StockInfo>()
+                   .Where(x => x.Id == stockId).ExecuteCommandAsync();
+
+                _logger.LogInformation($"娓呯悊闆跺簱瀛樻槑缁嗚褰� - StockId: {stockId}, 鍒犻櫎璁板綍鏁�: {deleteDetailCount}");
+
+
+
+            }
+            catch (Exception ex)
+            {
+                _logger.LogWarning($"娓呯悊闆跺簱瀛樻暟鎹け璐� - StockId: {stockId}, Error: {ex.Message}");
+                
+            }
+        }
+   
         #endregion
 
         #region 楠岃瘉鏂规硶
         private async Task<ValidationResult<(Dt_OutStockLockInfo, Dt_OutboundOrderDetail, Dt_StockInfoDetail, Dt_OutboundBatch)>> ValidatePickingRequest(
        string orderNo, string palletCode, string barcode)
         {
+            _logger.LogInformation($"寮�濮嬮獙璇佸垎鎷h姹� - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}, 鏉$爜: {barcode}");
+
             // 鏌ユ壘閿佸畾淇℃伅
             var lockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                 .Where(x => x.OrderNo == orderNo &&
@@ -972,6 +3054,13 @@
             if (lockInfo == null)
                 return ValidationResult<(Dt_OutStockLockInfo, Dt_OutboundOrderDetail, Dt_StockInfoDetail, Dt_OutboundBatch)>.Error("鏈壘鍒版湁鏁堢殑閿佸畾淇℃伅");
 
+            if (lockInfo.IsUnallocated == 1 || lockInfo.OrderDetailId == 0)
+            {
+                return ValidationResult<(Dt_OutStockLockInfo, Dt_OutboundOrderDetail, Dt_StockInfoDetail, Dt_OutboundBatch)>.Error("璇ユ潯鐮佹槸鏈垎閰嶉攣瀹氳褰曪紝涓嶈兘鐩存帴鍒嗘嫞");
+            }
+
+            _logger.LogInformation($"鎵惧埌閿佸畾淇℃伅 - 鍒嗛厤鏁伴噺: {lockInfo.AssignQuantity}, 宸叉嫞閫�: {lockInfo.PickedQty}");
+
             // 妫�鏌ユ槸鍚﹀凡缁忓垎鎷e畬鎴�
             if (lockInfo.PickedQty >= lockInfo.AssignQuantity)
                 return ValidationResult<(Dt_OutStockLockInfo, Dt_OutboundOrderDetail, Dt_StockInfoDetail, Dt_OutboundBatch)>.Error("璇ユ潯鐮佸凡鍒嗘嫞瀹屾垚");
@@ -980,70 +3069,280 @@
             var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
                 .FirstAsync(x => x.Id == lockInfo.OrderDetailId);
 
+            if (orderDetail == null)
+                return ValidationResult<(Dt_OutStockLockInfo, Dt_OutboundOrderDetail, Dt_StockInfoDetail, Dt_OutboundBatch)>.Error("鏈壘鍒拌鍗曟槑缁�");
+
+            _logger.LogInformation($"鎵惧埌璁㈠崟鏄庣粏 - 宸插垎閰嶆暟閲�: {orderDetail.AllocatedQuantity}, 閿佸畾鏁伴噺: {orderDetail.LockQuantity}");
+
+            // 妫�鏌ヨ鍗曟槑缁嗙殑宸插垎閰嶆暟閲忔槸鍚﹁冻澶�
+            decimal remainingToPick = lockInfo.AssignQuantity - lockInfo.PickedQty;
+
+            // 杩欓噷搴旇妫�鏌ラ攣瀹氫俊鎭殑鍒嗛厤鏁伴噺锛岃�屼笉鏄鍗曟槑缁嗙殑鍒嗛厤鏁伴噺
+            // 鍥犱负鎷嗗寘鍚庯紝閿佸畾淇℃伅鐨勫垎閰嶆暟閲忓彲鑳藉皬浜庤鍗曟槑缁嗙殑鍒嗛厤鏁伴噺
+            if (lockInfo.AssignQuantity < remainingToPick)
+            {
+                _logger.LogWarning($"閿佸畾淇℃伅鍒嗛厤鏁伴噺涓嶈冻 - 闇�瑕佹嫞閫�: {remainingToPick}, 閿佸畾淇℃伅鍒嗛厤鏁伴噺: {lockInfo.AssignQuantity}");
+                return ValidationResult<(Dt_OutStockLockInfo, Dt_OutboundOrderDetail, Dt_StockInfoDetail, Dt_OutboundBatch)>.Error(
+                    $"閿佸畾淇℃伅鍒嗛厤鏁伴噺涓嶈冻锛岄渶瑕佹嫞閫夛細{remainingToPick}锛岄攣瀹氫俊鎭垎閰嶆暟閲忥細{lockInfo.AssignQuantity}");
+            }
+
+            // 妫�鏌ラ攣瀹氭暟閲忔槸鍚﹁冻澶�
+            if (orderDetail.LockQuantity < remainingToPick)
+            {
+                _logger.LogWarning($"璁㈠崟鏄庣粏閿佸畾鏁伴噺涓嶈冻 - 闇�瑕佹嫞閫�: {remainingToPick}, 鍙敤閿佸畾鏁伴噺: {orderDetail.LockQuantity}");
+                return ValidationResult<(Dt_OutStockLockInfo, Dt_OutboundOrderDetail, Dt_StockInfoDetail, Dt_OutboundBatch)>.Error(
+                    $"璁㈠崟鏄庣粏閿佸畾鏁伴噺涓嶈冻锛岄渶瑕佹嫞閫夛細{remainingToPick}锛屽彲鐢ㄩ攣瀹氭暟閲忥細{orderDetail.LockQuantity}");
+            }
+
+            // 妫�鏌ヨ鍗曟槑缁嗗垎閰嶆暟閲忔槸鍚︿负璐熸暟
+            if (orderDetail.AllocatedQuantity < 0)
+            {
+                _logger.LogError($"璁㈠崟鏄庣粏鍒嗛厤鏁伴噺涓鸿礋鏁� - 褰撳墠鍊�: {orderDetail.AllocatedQuantity}");
+                return ValidationResult<(Dt_OutStockLockInfo, Dt_OutboundOrderDetail, Dt_StockInfoDetail, Dt_OutboundBatch)>.Error(
+                    $"璁㈠崟鏄庣粏鍒嗛厤鏁伴噺寮傚父锛堣礋鏁帮級锛岃鑱旂郴绠$悊鍛樺鐞�");
+            }
+
             var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
                 .FirstAsync(x => x.Barcode == barcode && x.StockId == lockInfo.StockId);
 
+            if (stockDetail == null)
+                return ValidationResult<(Dt_OutStockLockInfo, Dt_OutboundOrderDetail, Dt_StockInfoDetail, Dt_OutboundBatch)>.Error("鏈壘鍒板搴旂殑搴撳瓨淇℃伅");
+
             // 楠岃瘉搴撳瓨鏁伴噺
-            if (stockDetail.StockQuantity < lockInfo.AssignQuantity)
+            if (stockDetail.StockQuantity < remainingToPick)
                 return ValidationResult<(Dt_OutStockLockInfo, Dt_OutboundOrderDetail, Dt_StockInfoDetail, Dt_OutboundBatch)>.Error(
-                    $"搴撳瓨鏁伴噺涓嶈冻锛岄渶瑕侊細{lockInfo.AssignQuantity}锛屽疄闄咃細{stockDetail.StockQuantity}");
+                    $"搴撳瓨鏁伴噺涓嶈冻锛岄渶瑕佹嫞閫夛細{remainingToPick}锛屽疄闄呭簱瀛橈細{stockDetail.StockQuantity}");
+
+            // 楠岃瘉搴撳瓨鐘舵��
+            //if (stockDetail.Status != (int)StockStatusEmun.鍑哄簱閿佸畾)
+            //{
+            //    return ValidationResult<(Dt_OutStockLockInfo, Dt_OutboundOrderDetail, Dt_StockInfoDetail, Dt_OutboundBatch)>.Error(
+            //        $"搴撳瓨鐘舵�佸紓甯革紝褰撳墠鐘舵�侊細{stockDetail.Status}锛屾湡鏈涚姸鎬侊細鍑哄簱閿佸畾");
+            //}
 
             // 浣跨敤 OutboundBatchNo 鏌ユ壘鎵规
             var batch = await _outboundBatchRepository.Db.Queryable<Dt_OutboundBatch>()
-                .FirstAsync(x => x.BatchNo == lockInfo.OutboundBatchNo); // 淇涓� OutboundBatchNo
+                .FirstAsync(x => x.BatchNo == lockInfo.OutboundBatchNo);
+
+            _logger.LogInformation($"鍒嗘嫞楠岃瘉閫氳繃 - 鏉$爜: {barcode}, 鍓╀綑闇�鎷i��: {remainingToPick}, 鍙敤搴撳瓨: {stockDetail.StockQuantity}");
 
             return ValidationResult<(Dt_OutStockLockInfo, Dt_OutboundOrderDetail, Dt_StockInfoDetail, Dt_OutboundBatch)>.Success((lockInfo, orderDetail, stockDetail, batch));
         }
-        private async Task<ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>> ValidateSplitRequest(
-            string orderNo, string palletCode, string originalBarcode, decimal splitQuantity)
+
+
+        /// <summary>
+        /// 妫�鏌ュ苟鎵ц鑷姩鎷嗗寘锛堝鏋滈渶瑕侊級
+        /// </summary>
+        private async Task<List<SplitResult>> CheckAndAutoSplitIfNeeded(Dt_OutStockLockInfo lockInfo, Dt_StockInfoDetail stockDetail, string palletCode)
         {
-            var lockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                .Where(x => x.OrderNo == orderNo &&
-                           x.PalletCode == palletCode &&
-                           x.CurrentBarcode == originalBarcode &&
-                           x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�)
-                .FirstAsync();
+            if (lockInfo.IsUnallocated == 1 || lockInfo.OrderDetailId == 0)
+            {
+                _logger.LogInformation($"璺宠繃鏈垎閰嶉攣瀹氳褰曠殑鑷姩鎷嗗寘妫�鏌� - 閿佸畾ID: {lockInfo.Id}");
+                return null;
+            }
 
-            if (lockInfo == null)
-                return ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error("鏈壘鍒版湁鏁堢殑閿佸畾淇℃伅");
+            // 妫�鏌ユ槸鍚﹂渶瑕佽嚜鍔ㄦ媶鍖呯殑鏉′欢锛�
+            // 1. 搴撳瓨鏁伴噺澶т簬鍒嗛厤鏁伴噺
+            // 2. 閿佸畾淇℃伅鐘舵�佷负鍑哄簱涓�
+            // 3. 鏈嫞閫夋暟閲忕瓑浜庡垎閰嶆暟閲忥紙琛ㄧず杩樻湭寮�濮嬫嫞閫夛級
+            bool needAutoSplit = stockDetail.StockQuantity > lockInfo.AssignQuantity &&
+                                lockInfo.Status == (int)OutLockStockStatusEnum.鍑哄簱涓� &&
+                                lockInfo.PickedQty == 0;
 
-            var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
-                .FirstAsync(x => x.Barcode == originalBarcode && x.StockId == lockInfo.StockId);
+            if (!needAutoSplit)
+                return null;
 
-            if (stockDetail.StockQuantity < splitQuantity)
-                return ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error("鎷嗗寘鏁伴噺涓嶈兘澶т簬搴撳瓨鏁伴噺");
+            // 璁$畻鎷嗗寘鏁伴噺 = 搴撳瓨鏁伴噺 - 鍒嗛厤鏁伴噺
+            decimal splitQuantity = stockDetail.StockQuantity - lockInfo.AssignQuantity;
 
-            if (lockInfo.AssignQuantity - lockInfo.PickedQty < splitQuantity)
-                return ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error("鎷嗗寘鏁伴噺涓嶈兘澶т簬鏈嫞閫夋暟閲�");
+            _logger.LogInformation($"闇�瑕佽嚜鍔ㄦ媶鍖� - 搴撳瓨: {stockDetail.StockQuantity}, 鍒嗛厤: {lockInfo.AssignQuantity}, 鎷嗗寘鏁伴噺: {splitQuantity}");
 
-            return ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Success((lockInfo, stockDetail));
+            // 鎵ц鑷姩鎷嗗寘
+            var splitResult = await ExecuteAutoSplitLogic(lockInfo, stockDetail, splitQuantity,  palletCode);
+
+            return splitResult;
         }
- 
+
+        /// <summary>
+        /// 鎵ц鑷姩鎷嗗寘閫昏緫 - 瀹屽叏淇鐗�
+        /// 鍘熷垯锛氬彧鍒嗙鐗╃悊搴撳瓨锛屼笉鏀瑰彉鍘熻鍗曠殑浠讳綍鍒嗛厤鍜屽嚭搴撴暟閲�
+        /// </summary>
+        private async Task<List<SplitResult>> ExecuteAutoSplitLogic(Dt_OutStockLockInfo lockInfo, Dt_StockInfoDetail stockDetail,
+            decimal splitQuantity,string palletCode)
+        {
+            _logger.LogInformation($"寮�濮嬫墽琛岃嚜鍔ㄦ媶鍖呴�昏緫 - 鍘熸潯鐮�: {stockDetail.Barcode}, 鎷嗗寘鏁伴噺: {splitQuantity}");
+
+            try
+            {
+                //  楠岃瘉鎷嗗寘鏁伴噺鍚堢悊鎬�
+                if (splitQuantity <= 0)
+                    throw new InvalidOperationException($"鎷嗗寘鏁伴噺蹇呴』澶т簬0锛屽綋鍓嶅��: {splitQuantity}");
+
+                if (stockDetail.StockQuantity < lockInfo.AssignQuantity + splitQuantity)
+                    throw new InvalidOperationException($"搴撳瓨鏁伴噺涓嶈冻浠ヨ繘琛岃嚜鍔ㄦ媶鍖咃紝搴撳瓨: {stockDetail.StockQuantity}, 闇�瑕�: {lockInfo.AssignQuantity + splitQuantity}");
+
+                //  鐢熸垚鏂版潯鐮�
+                string newBarcode = await GenerateNewBarcode();
+                _logger.LogInformation($"鐢熸垚鏂版潯鐮�: {newBarcode}");
+
+                // 銆愭牳蹇冧慨姝c�戞洿鏂板師搴撳瓨鏄庣粏锛氬彧鍑忓皯鐗╃悊搴撳瓨锛屼笉褰卞搷鍑哄簱鏁伴噺
+                decimal originalStockQty = stockDetail.StockQuantity;
+                stockDetail.StockQuantity -= splitQuantity; // 浠呭簱瀛樺噺灏�
+                                                            // stockDetail.OutboundQuantity 淇濇寔涓嶅彉锛�
+
+                await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+                _logger.LogInformation($"鏇存柊鍘熷簱瀛樻槑缁嗭細鏉$爜 {stockDetail.Barcode} 搴撳瓨 {originalStockQty} -> {stockDetail.StockQuantity}锛屽嚭搴撴暟閲忎笉鍙�({stockDetail.OutboundQuantity})");
+
+                //  鍒涘缓鏂板簱瀛樻槑缁嗭紙澶氫綑閮ㄥ垎锛�- 鍑哄簱鏁伴噺涓�0
+                var newStockDetail = new Dt_StockInfoDetail
+                {
+                    StockId = stockDetail.StockId,
+                    MaterielCode = stockDetail.MaterielCode,
+                    OrderNo = stockDetail.OrderNo,
+                    BatchNo = stockDetail.BatchNo,
+                    StockQuantity = splitQuantity, // 鏂板簱瀛樻暟閲�
+                    OutboundQuantity = 0, // 鍒濆鍑哄簱鏁伴噺涓�0
+                    Barcode = newBarcode,
+                    Status = (int)StockStatusEmun.鍑哄簱閿佸畾, // 浠嶄负閿佸畾鐘舵�侊紝浣嗘湭缁戝畾璁㈠崟
+                    SupplyCode = stockDetail.SupplyCode,
+                    Unit = stockDetail.Unit,
+                    BarcodeQty = stockDetail.BarcodeQty,
+                    BarcodeUnit = stockDetail.BarcodeUnit,
+                    BusinessType = stockDetail.BusinessType,
+                    InboundOrderRowNo = stockDetail.InboundOrderRowNo,
+                    FactoryArea=stockDetail.FactoryArea,
+                    WarehouseCode = stockDetail.WarehouseCode,  
+                };
+
+                await _stockInfoDetailService.Db.Insertable(newStockDetail).ExecuteCommandAsync();
+                _logger.LogInformation($"鍒涘缓鏂板簱瀛樻槑缁嗭細鏉$爜 {newBarcode}锛屽簱瀛� {splitQuantity}锛屽嚭搴� 0");
+
+                //  鍒涘缓鏂伴攣瀹氫俊鎭� - 鏍囪涓烘湭鍒嗛厤
+                var newLockInfo = new Dt_OutStockLockInfo
+                {
+                    OrderNo = lockInfo.OrderNo,
+                    OrderDetailId = 0, // 涓嶇粦瀹氬埌鍏蜂綋璁㈠崟鏄庣粏锛岃〃绀烘湭鍒嗛厤
+                    OutboundBatchNo = lockInfo.OutboundBatchNo,
+                    MaterielCode = lockInfo.MaterielCode,
+                    MaterielName = lockInfo.MaterielName,
+                    StockId = lockInfo.StockId,
+                    OrderQuantity = splitQuantity,
+                    AssignQuantity = splitQuantity,
+                    PickedQty = 0,
+                    LocationCode = lockInfo.LocationCode,
+                    PalletCode = lockInfo.PalletCode,
+                    TaskNum = lockInfo.TaskNum,
+                    Status = (int)OutLockStockStatusEnum.鍑哄簱涓�,
+                    Unit = lockInfo.Unit,
+                    SupplyCode = lockInfo.SupplyCode,
+                    OrderType = lockInfo.OrderType,
+                    CurrentBarcode = newBarcode,
+                    IsSplitted = 1,
+                    ParentLockId = lockInfo.Id,
+                    Operator = App.User.UserName,
+                    FactoryArea = lockInfo.FactoryArea,
+                    lineNo = lockInfo.lineNo,
+                    WarehouseCode = lockInfo.WarehouseCode,
+                    BarcodeQty = lockInfo.BarcodeQty,
+                    BarcodeUnit = lockInfo.BarcodeUnit,
+                    IsUnallocated = 1 // 鏄庣‘鏍囪涓�"鏈垎閰�"鐨勯攣瀹氳褰�
+                };
+
+                await _outStockLockInfoService.Db.Insertable(newLockInfo).ExecuteCommandAsync();
+                _logger.LogInformation($"鍒涘缓鏈垎閰嶉攣瀹氳褰曪細ID {newLockInfo.Id}锛屾潯鐮� {newBarcode}锛屾暟閲� {splitQuantity}");
+
+                //鍘熼攣瀹氳褰曞拰鍘熻鍗曟槑缁嗘暟鎹畬鍏ㄤ繚鎸佷笉鍙橈紒
+                // - 涓嶄慨鏀� lockInfo 鐨勪换浣曞瓧娈�
+                // - 涓嶄慨鏀瑰叧鑱旂殑 Dt_OutboundOrderDetail 鐨� AllocatedQuantity 鍜� LockQuantity
+
+                // 璁板綍鎷嗗寘鍘嗗彶
+                await RecordSplitHistory(lockInfo, stockDetail, splitQuantity, newBarcode, true, originalStockQty);
+
+                // 鍒涘缓鎷嗗寘缁撴灉鍒楄〃
+                var splitResults = CreateSplitResults(lockInfo, splitQuantity, stockDetail.StockQuantity, newBarcode, stockDetail.Barcode);
+
+                _logger.LogInformation($"鑷姩鎷嗗寘閫昏緫鎵ц瀹屾垚 - 鍒涘缓浜嗘湭鍒嗛厤鐨勫簱瀛樺拰閿佸畾璁板綍");
+
+                return splitResults;
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"鑷姩鎷嗗寘閫昏緫鎵ц澶辫触 - 鍘熸潯鐮�: {stockDetail.Barcode}, Error: {ex.Message}");
+                throw;
+            }
+        }
+
         #endregion
 
         #region 鏍稿績閫昏緫鏂规硶
 
+        /// <summary>
+        /// 鎵ц鍒嗘嫞閫昏緫 - 瀹屽叏淇鐗�
+        /// 纭繚OutboundQuantity鍑嗙‘绱姞锛屼笉鍖呭惈鎷嗗寘鏁伴噺
+        /// </summary>
         private async Task<PickingResult> ExecutePickingLogic(
             Dt_OutStockLockInfo lockInfo, Dt_OutboundOrderDetail orderDetail,
             Dt_StockInfoDetail stockDetail, decimal actualPickedQty)
         {
-            // 鏇存柊閿佸畾淇℃伅
-            lockInfo.PickedQty += actualPickedQty;
-            if (lockInfo.PickedQty >= lockInfo.AssignQuantity)
+            _logger.LogInformation($"寮�濮嬫墽琛屽垎鎷i�昏緫 - 鏉$爜: {stockDetail.Barcode}, 鍒嗛厤鏁伴噺: {lockInfo.AssignQuantity}, 瀹為檯鎷i��: {actualPickedQty}");
+
+            // 鍐嶆楠岃瘉搴撳瓨鏁伴噺
+            if (stockDetail.StockQuantity < actualPickedQty)
             {
-                lockInfo.Status = (int)OutLockStockStatusEnum.鎷i�夊畬鎴�;
+                throw new InvalidOperationException($"搴撳瓨鏁伴噺涓嶈冻锛岄渶瑕佹嫞閫� {actualPickedQty}锛屽疄闄呭簱瀛� {stockDetail.StockQuantity}");
             }
-            await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
 
-            // 鏇存柊搴撳瓨
+            // 璁板綍鎷i�夊墠鐨勫��
+            decimal originalStockQty = stockDetail.StockQuantity;
+            decimal originalOutboundQty = stockDetail.OutboundQuantity;
+            int originalStatus = stockDetail.Status;
+
+            // 纭繚OutboundQuantity鍙鍔犳湰娆℃嫞閫夋暟閲忥紝涓嶅寘鍚叾浠�
             stockDetail.StockQuantity -= actualPickedQty;
-            stockDetail.OutboundQuantity += actualPickedQty;
+            stockDetail.OutboundQuantity += actualPickedQty;  // 鍙鍔犳湰娆℃嫞閫夋暟閲�
 
+            _logger.LogInformation($"鏇存柊搴撳瓨淇℃伅 - 鏉$爜: {stockDetail.Barcode}");
+            _logger.LogInformation($"  搴撳瓨鏁伴噺: {originalStockQty} -> {stockDetail.StockQuantity}");
+            _logger.LogInformation($"  鍑哄簱鏁伴噺: {originalOutboundQty} -> {stockDetail.OutboundQuantity}");
+
+            // 鏇存柊搴撳瓨鐘舵��
             if (stockDetail.StockQuantity <= 0)
             {
                 stockDetail.Status = (int)StockStatusEmun.鍑哄簱瀹屾垚;
+                _logger.LogInformation($"搴撳瓨鐘舵�佹洿鏂颁负鍑哄簱瀹屾垚");
             }
+            else
+            {
+                stockDetail.Status = (int)StockStatusEmun.鍑哄簱閿佸畾;
+                _logger.LogInformation($"搴撳瓨鐘舵�佷繚鎸佷负鍑哄簱閿佸畾");
+            }
+
             await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+
+            // 鏇存柊閿佸畾淇℃伅
+            decimal originalPickedQty = lockInfo.PickedQty;
+            lockInfo.PickedQty += actualPickedQty;
+            _logger.LogInformation($"鏇存柊閿佸畾淇℃伅 - 宸叉嫞閫夋暟閲忎粠 {originalPickedQty} 澧炲姞鍒� {lockInfo.PickedQty}");
+
+            // 鍒ゆ柇鎷i�夊畬鎴愮姸鎬�
+            if (Math.Abs(lockInfo.PickedQty - lockInfo.AssignQuantity) < 0.001m)
+            {
+                lockInfo.Status = (int)OutLockStockStatusEnum.鎷i�夊畬鎴�;
+                _logger.LogInformation($"閿佸畾淇℃伅鐘舵�佹洿鏂颁负鎷i�夊畬鎴�");
+            }
+            else if (lockInfo.PickedQty > 0)
+            {
+                lockInfo.Status = (int)OutLockStockStatusEnum.鍑哄簱涓�;
+                _logger.LogInformation($"閿佸畾淇℃伅鐘舵�佷繚鎸佷负鍑哄簱涓紙閮ㄥ垎鎷i�夛級");
+            }
+
+            lockInfo.Operator = App.User.UserName;
+            await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
+
+            // 楠岃瘉鎷i�夊悗鐨勬暟鎹竴鑷存��
+            await ValidatePickingDataConsistency(lockInfo, stockDetail, actualPickedQty);
+
+            _logger.LogInformation($"鍒嗘嫞閫昏緫鎵ц瀹屾垚 - 鏉$爜: {stockDetail.Barcode}");
 
             return new PickingResult
             {
@@ -1052,40 +3351,118 @@
             };
         }
 
+        /// <summary>
+        /// 楠岃瘉鎷i�夊悗鏁版嵁涓�鑷存��
+        /// </summary>
+        private async Task ValidatePickingDataConsistency(Dt_OutStockLockInfo lockInfo, Dt_StockInfoDetail stockDetail, decimal pickedQty)
+        {
+            _logger.LogInformation($"楠岃瘉鎷i�夋暟鎹竴鑷存�� - 鏉$爜: {stockDetail.Barcode}");
+
+            //  楠岃瘉搴撳瓨鏄庣粏鐨凮utboundQuantity澧炲姞閲忕瓑浜庢嫞閫夋暟閲�
+            var refreshedStockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                .FirstAsync(x => x.Id == stockDetail.Id);
+
+            decimal outboundIncrease = refreshedStockDetail.OutboundQuantity - stockDetail.OutboundQuantity;
+
+            if (Math.Abs(outboundIncrease - pickedQty) > 0.01m)
+            {
+                _logger.LogError($"鎷i�夋暟鎹笉涓�鑷达細鍑哄簱鏁伴噺澧炲姞 {outboundIncrease}锛屼絾鎷i�夋暟閲忔槸 {pickedQty}");
+                // 纭繚OutboundQuantity姝g‘
+                refreshedStockDetail.OutboundQuantity = stockDetail.OutboundQuantity + pickedQty;
+                await _stockInfoDetailService.Db.Updateable(refreshedStockDetail).ExecuteCommandAsync();
+                _logger.LogWarning($"宸蹭慨澶嶅嚭搴撴暟閲忥細{stockDetail.OutboundQuantity} -> {refreshedStockDetail.OutboundQuantity}");
+            }
+
+            // 楠岃瘉閿佸畾璁板綍鐨勫凡鎷i�夋暟閲�
+            var refreshedLockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                .FirstAsync(x => x.Id == lockInfo.Id);
+
+            if (Math.Abs(refreshedLockInfo.PickedQty - (lockInfo.PickedQty - pickedQty) - pickedQty) > 0.01m)
+            {
+                _logger.LogError($"閿佸畾璁板綍宸叉嫞閫夋暟閲忎笉涓�鑷�");
+            }
+
+            _logger.LogInformation($"鎷i�夋暟鎹竴鑷存�ч獙璇侀�氳繃");
+        }
+
         private async Task<RevertPickingResult> RevertPickingData(Dt_PickingRecord pickingRecord)
         {
+            _logger.LogInformation($"寮�濮嬫仮澶嶆嫞閫夋暟鎹� - 鎷i�夎褰旾D: {pickingRecord.Id}, 鏉$爜: {pickingRecord.Barcode}, 鎷i�夋暟閲�: {pickingRecord.PickQuantity}");
+
             // 鎭㈠閿佸畾淇℃伅
             var lockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                 .FirstAsync(x => x.Id == pickingRecord.OutStockLockId);
 
+            if (lockInfo == null)
+            {
+                throw new InvalidOperationException($"鏈壘鍒板搴旂殑閿佸畾淇℃伅锛孖D: {pickingRecord.OutStockLockId}");
+            }
+
+            decimal originalPickedQty = lockInfo.PickedQty;
+            decimal originalAssignQty = lockInfo.AssignQuantity; // 璁板綍鍘熷鍒嗛厤鏁伴噺
+
+            // 鍙仮澶嶅凡鎷i�夋暟閲忥紝涓嶄慨鏀瑰垎閰嶆暟閲�
             lockInfo.PickedQty -= pickingRecord.PickQuantity;
 
-            // 鏍规嵁鎷i�夋暟閲忓垽鏂姸鎬�
+            // 纭繚宸叉嫞閫夋暟閲忎笉浼氫负璐熸暟
+            if (lockInfo.PickedQty < 0)
+            {
+                _logger.LogWarning($"宸叉嫞閫夋暟閲忓嚭鐜拌礋鏁帮紝閲嶇疆涓�0銆傚師鍊�: {lockInfo.PickedQty + pickingRecord.PickQuantity}, 鎭㈠鏁伴噺: {pickingRecord.PickQuantity}");
+                lockInfo.PickedQty = 0;
+            }
+
+            _logger.LogInformation($"鎭㈠閿佸畾淇℃伅 - 宸叉嫞閫夋暟閲忎粠 {originalPickedQty} 鍑忓皯鍒� {lockInfo.PickedQty}");
+            _logger.LogInformation($"閿佸畾淇℃伅鍒嗛厤鏁伴噺淇濇寔涓嶅彉: {originalAssignQty}");
+
+            // 鎭㈠閿佸畾鐘舵��
             if (lockInfo.PickedQty <= 0)
             {
                 lockInfo.Status = (int)OutLockStockStatusEnum.鍑哄簱涓�;
+                _logger.LogInformation($"閿佸畾淇℃伅鐘舵�佹仮澶嶄负鍑哄簱涓�");
             }
             else if (lockInfo.PickedQty < lockInfo.AssignQuantity)
             {
-                lockInfo.Status = (int)OutLockStockStatusEnum.鍑哄簱涓�;
+                lockInfo.Status = (int)OutLockStockStatusEnum.鍑哄簱涓�; // 閮ㄥ垎鎷i�夌姸鎬�
+                _logger.LogInformation($"閿佸畾淇℃伅鐘舵�佹仮澶嶄负鍑哄簱涓紙閮ㄥ垎鎷i�夛級");
             }
 
             await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
 
-            // 鎭㈠搴撳瓨
+            // 鎭㈠搴撳瓨淇℃伅
             var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
                 .FirstAsync(x => x.Barcode == pickingRecord.Barcode);
 
+            if (stockDetail == null)
+            {
+                throw new InvalidOperationException($"鏈壘鍒板搴旂殑搴撳瓨淇℃伅锛屾潯鐮�: {pickingRecord.Barcode}");
+            }
+
+            decimal originalStockQty = stockDetail.StockQuantity;
+            decimal originalOutboundQty = stockDetail.OutboundQuantity;
+
             stockDetail.StockQuantity += pickingRecord.PickQuantity;
             stockDetail.OutboundQuantity -= pickingRecord.PickQuantity;
+
+            // 纭繚鍑哄簱鏁伴噺涓嶄細涓鸿礋鏁�
+            if (stockDetail.OutboundQuantity < 0)
+            {
+                _logger.LogWarning($"鍑哄簱鏁伴噺鍑虹幇璐熸暟锛岄噸缃负0銆傚師鍊�: {stockDetail.OutboundQuantity + pickingRecord.PickQuantity}, 鎭㈠鏁伴噺: {pickingRecord.PickQuantity}");
+                stockDetail.OutboundQuantity = 0;
+            }
+
+            _logger.LogInformation($"鎭㈠搴撳瓨淇℃伅 - 搴撳瓨鏁伴噺浠� {originalStockQty} 澧炲姞鍒� {stockDetail.StockQuantity}");
+            _logger.LogInformation($"鎭㈠搴撳瓨淇℃伅 - 鍑哄簱鏁伴噺浠� {originalOutboundQty} 鍑忓皯鍒� {stockDetail.OutboundQuantity}");
 
             // 鎭㈠搴撳瓨鐘舵��
             if (stockDetail.StockQuantity > 0)
             {
                 stockDetail.Status = (int)StockStatusEmun.鍑哄簱閿佸畾;
+                _logger.LogInformation($"搴撳瓨鐘舵�佹仮澶嶄负鍑哄簱閿佸畾");
             }
 
             await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+
+            _logger.LogInformation($"鎭㈠鎷i�夋暟鎹畬鎴� - 鏉$爜: {pickingRecord.Barcode}");
 
             return new RevertPickingResult
             {
@@ -1093,244 +3470,232 @@
                 StockDetail = stockDetail
             };
         }
-        private async Task<SplitResultDto> ExecuteSplitLogic(Dt_OutStockLockInfo lockInfo, Dt_StockInfoDetail stockDetail,
-     decimal splitQuantity, string palletCode)
-        {
-            // 鐢熸垚鏂版潯鐮�
-            string newBarcode = await GenerateNewBarcode();
-
-            // 鍒涘缓鏂板簱瀛樻槑缁�
-            var newStockDetail = new Dt_StockInfoDetail
-            {
-                StockId = stockDetail.StockId,
-                MaterielCode = stockDetail.MaterielCode,
-                OrderNo = stockDetail.OrderNo,
-                BatchNo = stockDetail.BatchNo, // 鐗╂枡鎵规
-                StockQuantity = splitQuantity,
-                OutboundQuantity = 0,
-                Barcode = newBarcode,
-                Status = (int)StockStatusEmun.鍑哄簱閿佸畾,
-                SupplyCode = stockDetail.SupplyCode,
-                Unit = stockDetail.Unit,
-                BarcodeQty = stockDetail.BarcodeQty,
-                BarcodeUnit = stockDetail.BarcodeUnit,
-                BusinessType = stockDetail.BusinessType,
-                InboundOrderRowNo = stockDetail.InboundOrderRowNo,
-            };
-            await _stockInfoDetailService.Db.Insertable(newStockDetail).ExecuteCommandAsync();
-
-            // 鏇存柊鍘熷簱瀛樻槑缁�
-            stockDetail.StockQuantity -= splitQuantity;
-            await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
-
-            // 鍒涘缓鏂伴攣瀹氫俊鎭� - 浣跨敤姝g‘鐨� OutboundBatchNo
-            var newLockInfo = new Dt_OutStockLockInfo
-            {
-                OrderNo = lockInfo.OrderNo,
-                OrderDetailId = lockInfo.OrderDetailId,
-                OutboundBatchNo = lockInfo.OutboundBatchNo, // 浣跨敤 OutboundBatchNo
-                MaterielCode = lockInfo.MaterielCode,
-                MaterielName = lockInfo.MaterielName,
-                StockId = lockInfo.StockId,
-                OrderQuantity = splitQuantity,
-                AssignQuantity = splitQuantity,
-                PickedQty = 0,
-                LocationCode = lockInfo.LocationCode,
-                PalletCode = lockInfo.PalletCode,
-                TaskNum = lockInfo.TaskNum,
-                Status = (int)OutLockStockStatusEnum.鍑哄簱涓�,
-                Unit = lockInfo.Unit,
-                SupplyCode = lockInfo.SupplyCode,
-                OrderType = lockInfo.OrderType,
-                CurrentBarcode = newBarcode,
-                IsSplitted = 1,
-                ParentLockId = lockInfo.Id,
-                Operator = App.User.UserName,
-                FactoryArea = lockInfo.FactoryArea,
-                lineNo = lockInfo.lineNo,
-                WarehouseCode = lockInfo.WarehouseCode,
-                BarcodeQty = lockInfo.BarcodeQty,
-                BarcodeUnit = lockInfo.BarcodeUnit,
-            };
-
-            await _outStockLockInfoService.Db.Insertable(newLockInfo).ExecuteCommandAsync();
-
-            // 鏇存柊鍘熼攣瀹氫俊鎭�
-            lockInfo.AssignQuantity -= splitQuantity;
-            lockInfo.OrderQuantity -= splitQuantity;
-            await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
-
-            // 璁板綍鎷嗗寘鍘嗗彶
-            await RecordSplitHistory(lockInfo, stockDetail, splitQuantity, newBarcode);
-
-            return new SplitResultDto { NewBarcode = newBarcode };
-        }
-        private async Task ExecuteCancelSplitLogic(Dt_SplitPackageRecord splitRecord, Dt_OutStockLockInfo newLockInfo, Dt_StockInfoDetail newStockDetail)
-        {
-            // 鎭㈠鍘熷簱瀛�
-            var originalStock = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
-                .FirstAsync(x => x.Barcode == splitRecord.OriginalBarcode && x.StockId == splitRecord.StockId);
-
-            originalStock.StockQuantity += splitRecord.SplitQty;
-            await _stockInfoDetailService.Db.Updateable(originalStock).ExecuteCommandAsync();
-
-            // 鎭㈠鍘熼攣瀹氫俊鎭�
-            var originalLockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                .FirstAsync(x => x.Id == splitRecord.OutStockLockInfoId);
-
-            originalLockInfo.AssignQuantity += splitRecord.SplitQty;
-            originalLockInfo.OrderQuantity += splitRecord.SplitQty;
-            await _outStockLockInfoService.Db.Updateable(originalLockInfo).ExecuteCommandAsync();
-
-            // 鍒犻櫎鏂板簱瀛樻槑缁�
-            await _stockInfoDetailService.Db.Deleteable<Dt_StockInfoDetail>()
-                .Where(x => x.Barcode == newLockInfo.CurrentBarcode)
-                .ExecuteCommandAsync();
-
-            // 鍒犻櫎鏂伴攣瀹氫俊鎭�
-            await _outStockLockInfoService.Db.Deleteable<Dt_OutStockLockInfo>()
-                .Where(x => x.Id == newLockInfo.Id)
-                .ExecuteCommandAsync();
-
-            // 鏍囪鎷嗗寘璁板綍涓哄凡鎾ら攢
-            splitRecord.IsReverted = true;
-            splitRecord.RevertTime = DateTime.Now;
-            splitRecord.RevertOperator = App.User.UserName;
-            await _splitPackageService.Db.Updateable(splitRecord).ExecuteCommandAsync();
-        }
 
         #endregion
 
         #region 鏁版嵁鏇存柊鏂规硶
 
+        /// <summary>
+        /// 鏇存柊鎵规鍜岃鍗曟暟鎹� - 淇鐗�
+        /// 纭繚鍙洿鏂板疄闄呯殑鎷i�夋暟閲�
+        /// </summary>
         private async Task UpdateBatchAndOrderData(Dt_OutboundBatch batch, Dt_OutboundOrderDetail orderDetail, decimal pickedQty, string orderNo)
         {
-            // 鏇存柊鎵规瀹屾垚鏁伴噺
-            batch.CompletedQuantity += pickedQty;
-            if (batch.CompletedQuantity >= batch.BatchQuantity)
+            _logger.LogInformation($"寮�濮嬫洿鏂版壒娆″拰璁㈠崟鏁版嵁 - 鎷i�夋暟閲�: {pickedQty}");
+
+            // 閲嶆柊鑾峰彇鏈�鏂版暟鎹紙闃叉骞跺彂闂锛�
+            var latestOrderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
+                .FirstAsync(x => x.Id == orderDetail.Id);
+
+            if (latestOrderDetail == null)
+                throw new InvalidOperationException("鏈壘鍒拌鍗曟槑缁�");
+
+            orderDetail = latestOrderDetail;
+
+            // 楠岃瘉鎷i�夋暟閲忓悎鐞嗘��
+            if (pickedQty <= 0)
             {
-                batch.BatchStatus = (int)BatchStatusEnum.宸插畬鎴�;
+                _logger.LogWarning($"鎷i�夋暟閲忔棤鏁�: {pickedQty}");
+                return;
             }
-            await _outboundBatchRepository.Db.Updateable(batch).ExecuteCommandAsync();
+
+            // 璁板綍鍘熷鍊�
+            decimal originalOverOutQty = orderDetail.OverOutQuantity;
+            decimal originalAllocatedQty = orderDetail.AllocatedQuantity;
+            decimal originalLockQty = orderDetail.LockQuantity;
 
             // 鏇存柊璁㈠崟鏄庣粏
-            orderDetail.OverOutQuantity += pickedQty;
-            orderDetail.AllocatedQuantity -= pickedQty;
+            orderDetail.OverOutQuantity += pickedQty;  // 宸插嚭搴撴暟閲忓鍔�
+            orderDetail.AllocatedQuantity -= pickedQty;  // 宸插垎閰嶆暟閲忓噺灏�
+            orderDetail.LockQuantity -= pickedQty;  // 閿佸畾鏁伴噺鍑忓皯
+
+            // 纭繚鏁伴噺涓嶄細涓鸿礋鏁�
+            if (orderDetail.AllocatedQuantity < 0)
+            {
+                _logger.LogWarning($"鍒嗛厤鏁伴噺鍑虹幇璐熸暟锛岄噸缃负0銆傚師鍊�: {orderDetail.AllocatedQuantity + pickedQty}");
+                orderDetail.AllocatedQuantity = 0;
+            }
+
+            if (orderDetail.LockQuantity < 0)
+            {
+                _logger.LogWarning($"閿佸畾鏁伴噺鍑虹幇璐熸暟锛岄噸缃负0銆傚師鍊�: {orderDetail.LockQuantity + pickedQty}");
+                orderDetail.LockQuantity = 0;
+            }
+
+            // 鏇存柊鎵规鍒嗛厤鐘舵��
+            await UpdateBatchAllocateStatus(orderDetail);
+
             await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
+
+            _logger.LogInformation($"鏇存柊璁㈠崟鏄庣粏鎴愬姛");
+            _logger.LogInformation($"  宸插嚭搴撴暟閲�: {originalOverOutQty} -> {orderDetail.OverOutQuantity}");
+            _logger.LogInformation($"  宸插垎閰嶆暟閲�: {originalAllocatedQty} -> {orderDetail.AllocatedQuantity}");
+            _logger.LogInformation($"  閿佸畾鏁伴噺: {originalLockQty} -> {orderDetail.LockQuantity}");
+
+            // 鏇存柊鎵规瀹屾垚鏁伴噺
+            if (batch != null)
+            {
+                decimal originalBatchCompletedQty = batch.CompletedQuantity;
+                batch.CompletedQuantity += pickedQty;
+
+                _logger.LogInformation($"鏇存柊鎵规瀹屾垚鏁伴噺 - 浠� {originalBatchCompletedQty} 澧炲姞鍒� {batch.CompletedQuantity}");
+
+                // 鏇存柊鎵规鐘舵��
+                if (batch.CompletedQuantity >= batch.BatchQuantity)
+                {
+                    batch.BatchStatus = (int)BatchStatusEnum.宸插畬鎴�;
+                    _logger.LogInformation($"鎵规鐘舵�佹洿鏂颁负宸插畬鎴�");
+                }
+                else if (batch.CompletedQuantity > 0)
+                {
+                    batch.BatchStatus = (int)BatchStatusEnum.鎵ц涓�;
+                    _logger.LogInformation($"鎵规鐘舵�佹洿鏂颁负鎵ц涓�");
+                }
+
+                await _outboundBatchRepository.Db.Updateable(batch).ExecuteCommandAsync();
+            }
 
             // 妫�鏌ヨ鍗曠姸鎬�
             await CheckAndUpdateOrderStatus(orderNo);
+
+            _logger.LogInformation($"鎵规鍜岃鍗曟暟鎹洿鏂板畬鎴�");
         }
 
         private async Task RevertBatchAndOrderData(Dt_PickingRecord pickingRecord, RevertPickingResult revertResult)
         {
-            // 鎭㈠鎵规瀹屾垚鏁伴噺
+            _logger.LogInformation($"寮�濮嬫仮澶嶆壒娆″拰璁㈠崟鏁版嵁");
+
+            //   鎭㈠鎵规瀹屾垚鏁伴噺
             var batch = await _outboundBatchRepository.Db.Queryable<Dt_OutboundBatch>()
-                .FirstAsync(x => x.BatchNo == revertResult.LockInfo.OutboundBatchNo); // 浣跨敤 OutboundBatchNo
+                .FirstAsync(x => x.BatchNo == revertResult.LockInfo.OutboundBatchNo);
 
             if (batch != null)
             {
+                decimal originalCompletedQty = batch.CompletedQuantity;
                 batch.CompletedQuantity -= pickingRecord.PickQuantity;
+                if (batch.CompletedQuantity < 0)
+                {
+                    batch.CompletedQuantity = 0;
+                    _logger.LogWarning($"鎵规瀹屾垚鏁伴噺鍑虹幇璐熸暟锛岄噸缃负0");
+                }
+                _logger.LogInformation($"鎭㈠鎵规瀹屾垚鏁伴噺 - 浠� {originalCompletedQty} 鍑忓皯鍒� {batch.CompletedQuantity}");
 
                 // 閲嶆柊璁$畻鎵规鐘舵��
                 if (batch.CompletedQuantity <= 0)
                 {
                     batch.BatchStatus = (int)BatchStatusEnum.鍒嗛厤涓�;
+                    _logger.LogInformation($"鎵规鐘舵�佹仮澶嶄负鍒嗛厤涓�");
                 }
                 else if (batch.CompletedQuantity < batch.BatchQuantity)
                 {
                     batch.BatchStatus = (int)BatchStatusEnum.鎵ц涓�;
+                    _logger.LogInformation($"鎵规鐘舵�佹仮澶嶄负鎵ц涓�");
                 }
 
                 await _outboundBatchRepository.Db.Updateable(batch).ExecuteCommandAsync();
             }
 
-            // 鎭㈠璁㈠崟鏄庣粏
+            //   鎭㈠璁㈠崟鏄庣粏
             var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
                 .FirstAsync(x => x.Id == pickingRecord.OrderDetailId);
 
-            orderDetail.OverOutQuantity -= pickingRecord.PickQuantity;
-            orderDetail.AllocatedQuantity += pickingRecord.PickQuantity;
-            await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
+            if (orderDetail != null)
+            {
+                decimal originalOverOutQty = orderDetail.OverOutQuantity;
+                decimal originalAllocatedQty = orderDetail.AllocatedQuantity;
+                decimal originalLockQty = orderDetail.LockQuantity;
+
+                // 鍙仮澶嶇浉鍏虫暟閲忥紝鍒嗛厤鏁伴噺淇濇寔涓嶅彉
+                orderDetail.OverOutQuantity -= pickingRecord.PickQuantity;
+                orderDetail.AllocatedQuantity += pickingRecord.PickQuantity;
+                orderDetail.LockQuantity += pickingRecord.PickQuantity;
+                if (orderDetail.OverOutQuantity < 0) orderDetail.OverOutQuantity = 0;
+                if (orderDetail.AllocatedQuantity < 0) orderDetail.AllocatedQuantity = 0;
+                if (orderDetail.LockQuantity < 0) orderDetail.LockQuantity = 0;
+
+                _logger.LogInformation($"鎭㈠璁㈠崟鏄庣粏 - 宸插嚭搴撴暟閲忎粠 {originalOverOutQty} 鍑忓皯鍒� {orderDetail.OverOutQuantity}");
+                _logger.LogInformation($"璁㈠崟鏄庣粏鍒嗛厤鏁伴噺淇濇寔涓嶅彉: {originalAllocatedQty}");
+                _logger.LogInformation($"璁㈠崟鏄庣粏閿佸畾鏁伴噺淇濇寔涓嶅彉: {originalLockQty}");
+
+                await UpdateBatchAllocateStatus(orderDetail);
+                await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
+            }
 
             // 閲嶆柊妫�鏌ヨ鍗曠姸鎬�
             await CheckAndUpdateOrderStatus(pickingRecord.OrderNo);
-        }
-        private async Task ReleaseLockAndStock(Dt_OutStockLockInfo lockInfo)
-        {
-            // 鎭㈠搴撳瓨鐘舵�� - 鍥炲簱鍚庡簱瀛樺彉涓哄彲鐢ㄧ姸鎬�
-            var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
-                .FirstAsync(x => x.Barcode == lockInfo.CurrentBarcode && x.StockId == lockInfo.StockId);
 
-            if (stockDetail != null)
+            _logger.LogInformation($"鎭㈠鎵规鍜岃鍗曟暟鎹畬鎴�");
+        }
+
+        private async Task UpdateBatchAllocateStatus(Dt_OutboundOrderDetail orderDetail)
+        {
+            if (orderDetail.AllocatedQuantity >= orderDetail.NeedOutQuantity)
             {
-                // 鍥炲簱鍚庡簱瀛樼姸鎬佹仮澶嶄负鍏ュ簱瀹屾垚锛堝彲鐢ㄧ姸鎬侊級
-                stockDetail.Status = (int)StockStatusEmun.鍏ュ簱瀹屾垚;
-                await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+                orderDetail.BatchAllocateStatus = OrderDetailStatusEnum.AssignOver.ObjToInt();
             }
-
-            // 鏇存柊閿佸畾璁板綍鐘舵�佷负宸插洖搴�
-            lockInfo.Status = (int)OutLockStockStatusEnum.宸插洖搴�;
-            lockInfo.Operator = App.User.UserName;
-            await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
-        }
-
-        /// <summary>
-        /// 鏇存柊鎵规鐘舵�侊紙鍥炲簱锛� 
-        /// </summary>
-        private async Task UpdateBatchStatusForReturn(string outboundBatchNo, List<Dt_OutStockLockInfo> returnedLocks)
-        {
-            var batch = await _outboundBatchRepository.Db.Queryable<Dt_OutboundBatch>()
-                .FirstAsync(x => x.BatchNo == outboundBatchNo);
-
-            if (batch != null)
+            else if (orderDetail.AllocatedQuantity > 0)
             {
-                // 璁$畻鍥炲簱鏁伴噺锛堟湭鎷i�夌殑閮ㄥ垎锛�
-                var returnedQty = returnedLocks.Sum(x => x.AssignQuantity - x.PickedQty);
-                batch.CompletedQuantity -= returnedQty;
-
-                // 鏇存柊鎵规鐘舵��
-                if (batch.CompletedQuantity <= 0)
-                {
-                    batch.BatchStatus = (int)BatchStatusEnum.宸插洖搴�;
-                }
-                else if (batch.CompletedQuantity < batch.BatchQuantity)
-                {
-                    batch.BatchStatus = (int)BatchStatusEnum.鎵ц涓�;
-                }
-                else
-                {
-                    batch.BatchStatus = (int)BatchStatusEnum.宸插畬鎴�;
-                }
-
-                batch.Operator = App.User.UserName;
-                await _outboundBatchRepository.Db.Updateable(batch).ExecuteCommandAsync();
+                orderDetail.BatchAllocateStatus = OrderDetailStatusEnum.AssignOverPartial.ObjToInt();
+            }
+            else
+            {
+                orderDetail.BatchAllocateStatus = OrderDetailStatusEnum.New.ObjToInt();
             }
         }
-
-        /// <summary>
-        /// 鏇存柊璁㈠崟鏄庣粏锛堝洖搴撳悗锛� 
-        /// </summary>
-        private async Task UpdateOrderDetailAfterReturn(List<Dt_OutStockLockInfo> returnedLocks)
-        {
-            var orderDetailGroups = returnedLocks.GroupBy(x => x.OrderDetailId);
-
-            foreach (var group in orderDetailGroups)
-            {
-                var orderDetailId = group.Key;
-                var returnedQty = group.Sum(x => x.AssignQuantity - x.PickedQty);
-
-                var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
-                    .FirstAsync(x => x.Id == orderDetailId);
-
-                if (orderDetail != null)
-                {
-                    orderDetail.AllocatedQuantity -= returnedQty;
-                    await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
-                }
-            }
-        }
+      
         #endregion
+                
+        /// <summary>
+        /// 缁橢SS涓嬩换鍔�
+        /// </summary>
+        /// <param name="palletCode"></param>
+        /// <param name="targetAddress"></param>
+        /// <param name="returnTask"></param>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
+        private async Task SendESSCommands(string palletCode, string targetAddress, Dt_Task returnTask)
+        {
+            try
+            {
+                // 鍙戦�佹祦鍔ㄤ俊鍙�
+                var moveResult = await _eSSApiService.MoveContainerAsync(new WIDESEA_DTO.Basic.MoveContainerRequest
+                {
+                    slotCode = movestations[targetAddress],
+                    containerCode = palletCode
+                });
+
+              
+                var essTask = new TaskModel()
+                {
+                    taskType = "putaway",
+                    taskGroupCode = "",
+                    groupPriority = 0,
+                    tasks = new List<TasksType>{  new() {
+                            taskCode = returnTask.TaskNum.ToString(),
+                            taskPriority = 0,
+                            taskDescribe = new TaskDescribeType
+                            {
+                                containerCode = palletCode,
+                                containerType = "CT_KUBOT_STANDARD",
+                                fromLocationCode = stations.GetValueOrDefault(targetAddress) ?? "",
+                                toStationCode = "",
+                                toLocationCode = returnTask.TargetAddress,
+                                deadline = 0,
+                                storageTag = ""
+                            }
+                        } }
+                };
+
+                var resultTask = await _eSSApiService.CreateTaskAsync(essTask);
+                _logger.LogInformation($"ReturnRemaining 鍒涘缓浠诲姟鎴愬姛: {resultTask}");
+             
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"ReturnRemaining ESS鍛戒护鍙戦�佸け璐�: {ex.Message}");
+                throw new Exception($"ESS绯荤粺閫氫俊澶辫触: {ex.Message}");
+            }
+        }
 
         #region 杈呭姪鏂规硶
 
@@ -1340,19 +3705,33 @@
             return "WSLOT" + DateTime.Now.ToString("yyyyMMdd") + seq.ToString().PadLeft(5, '0');
         }
 
-        private async Task RecordSplitHistory(Dt_OutStockLockInfo lockInfo, Dt_StockInfoDetail stockDetail, decimal splitQty, string newBarcode)
+        private async Task RecordSplitHistory(Dt_OutStockLockInfo lockInfo, Dt_StockInfoDetail stockDetail, decimal splitQty, string newBarcode, bool isAutoSplit, decimal? originalStockQuantity = null)
         {
             var splitHistory = new Dt_SplitPackageRecord
             {
-                OrderNo = lockInfo.OrderNo,
+                FactoryArea = lockInfo.FactoryArea,
+                TaskNum = lockInfo.TaskNum,
                 OutStockLockInfoId = lockInfo.Id,
                 StockId = stockDetail.StockId,
                 Operator = App.User.UserName,
+                IsReverted = false,
                 OriginalBarcode = stockDetail.Barcode,
                 NewBarcode = newBarcode,
                 SplitQty = splitQty,
+               // RemainQuantity = remainQty,
+                MaterielCode = lockInfo.MaterielCode,
                 SplitTime = DateTime.Now,
-                Status = (int)SplitPackageStatusEnum.宸叉媶鍖�
+                OrderNo = lockInfo.OrderNo,
+                PalletCode = lockInfo.PalletCode,
+             
+
+              
+                Status = (int)SplitPackageStatusEnum.宸叉媶鍖�,
+                IsAutoSplit = isAutoSplit,
+                // SplitType = isAutoSplit ? "鑷姩鎷嗗寘" : "鎵嬪姩鎷嗗寘"
+                OriginalStockQuantity = originalStockQuantity ?? stockDetail.StockQuantity,
+                //RemainingStockQuantity = stockDetail.StockQuantity - splitQty
+               
             };
 
             await _splitPackageService.Db.Insertable(splitHistory).ExecuteCommandAsync();
@@ -1414,9 +3793,41 @@
             };
         }
         #endregion
- 
 
         #region DTO绫�
+
+        /// <summary>
+        /// 鍥炲簱浠诲姟淇℃伅绫�
+        /// </summary>
+        public class ReturnTaskInfo
+        {
+            /// <summary>
+            /// 鏄惁闇�瑕佸彂閫丒SS鍛戒护
+            /// </summary>
+            public bool ShouldSendESS { get; set; }
+
+            /// <summary>
+            /// 鎵樼洏鐮�
+            /// </summary>
+            public string PalletCode { get; set; }
+
+            /// <summary>
+            /// 鍘熷浠诲姟鐨勭洰鏍囧湴鍧�
+            /// </summary>
+            public string OriginalTaskTargetAddress { get; set; }
+
+            /// <summary>
+            /// 鍥炲簱浠诲姟
+            /// </summary>
+            public Dt_Task ReturnTask { get; set; }
+        }
+        public class PickedBarcodeInfo
+        {
+            public string Barcode { get; set; }
+            public decimal PickedQty { get; set; }
+            public int PickRecordCount { get; set; }
+        }
+
 
         public class PickingResult
         {
@@ -1430,11 +3841,6 @@
             public Dt_StockInfoDetail StockDetail { get; set; }
         }
 
-        public class SplitResultDto
-        {
-            public string NewBarcode { get; set; }
-        }
-
         public class ValidationResult<T>
         {
             public bool IsValid { get; set; }
@@ -1446,12 +3852,5 @@
         }
 
         #endregion
-    }
-
-
-    // 鏀寔绫�
-    public class SplitResultDto
-    {
-        public string NewBarcode { get; set; }
     }
 }

--
Gitblit v1.9.3