From b6a40a2d8fdcffb3accfc7e424c0726a87a59ddf Mon Sep 17 00:00:00 2001
From: heshaofeng <heshaofeng@hnkhzn.com>
Date: 星期五, 05 十二月 2025 21:20:59 +0800
Subject: [PATCH] 提交

---
 项目代码/WMS无仓储版/WIDESEA_WMSServer/WIDESEA_OutboundService/OutboundBatchPickingService.cs | 3062 +++++++++++++++++++++++++++++++++++++++++++++++++++-------
 1 files changed, 2,672 insertions(+), 390 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..c0e37a5 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"
@@ -1,5 +1,6 @@
 锘縰sing Microsoft.Extensions.Logging;
 using SqlSugar;
+using SqlSugar.Extensions;
 using System;
 using System.Collections.Generic;
 using System.Linq;
@@ -9,14 +10,18 @@
 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_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,166 +247,6 @@
 
         #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>
@@ -411,32 +258,60 @@
             {
                 _unitOfWorkManage.BeginTran();
 
-                // 1. 楠岃瘉鍒嗘嫞璇锋眰
+                // 楠岃瘉鍒嗘嫞璇锋眰
                 var validationResult = await ValidatePickingRequest(orderNo, palletCode, barcode);
                 if (!validationResult.IsValid)
                     return WebResponseContent.Instance.Error(validationResult.ErrorMessage);
 
                 var (lockInfo, orderDetail, stockDetail, batch) = validationResult.Data;
 
-                // 浣跨敤閿佸畾淇℃伅鐨勫垎閰嶆暟閲忎綔涓哄疄闄呭垎鎷f暟閲�
-                var actualPickedQty = lockInfo.AssignQuantity;
+                // 妫�鏌ユ槸鍚﹂渶瑕佽嚜鍔ㄦ媶鍖�
+                var autoSplitResult = await CheckAndAutoSplitIfNeeded(lockInfo, stockDetail, palletCode);
+                if (autoSplitResult != null)
+                {
+                    // 濡傛灉鎵ц浜嗚嚜鍔ㄦ媶鍖咃紝閲嶆柊鑾峰彇鏈�鏂扮殑閿佸畾淇℃伅鍜屽簱瀛樹俊鎭�
+                    var refreshedValidation = await ValidatePickingRequest(orderNo, palletCode, barcode);
+                    if (!refreshedValidation.IsValid)
+                    {
+                        _unitOfWorkManage.RollbackTran();
+                        return WebResponseContent.Instance.Error(refreshedValidation.ErrorMessage);
+                    }
 
-                // 2. 鎵ц鍒嗘嫞閫昏緫
-                var pickingResult = await ExecutePickingLogic(lockInfo, orderDetail, stockDetail, actualPickedQty);
+                    (lockInfo, orderDetail, stockDetail, batch) = refreshedValidation.Data;
 
-                // 3. 鏇存柊鎵规鍜岃鍗曟暟鎹�
-                await UpdateBatchAndOrderData(batch, orderDetail, actualPickedQty, orderNo);
 
-                // 4. 璁板綍鎷i�夊巻鍙�
-                await RecordPickingHistory(pickingResult, orderNo, palletCode);
+                    var actualPickedQty = lockInfo.AssignQuantity;
+                    var pickingResult = await ExecutePickingLogic(lockInfo, orderDetail, stockDetail, actualPickedQty);
+
+                    // 鏇存柊鎵规鍜岃鍗曟暟鎹�
+                    await UpdateBatchAndOrderData(batch, orderDetail, actualPickedQty, orderNo);
+
+                    // 璁板綍鎷i�夊巻鍙�
+                    await RecordPickingHistory(pickingResult, orderNo, palletCode);
+
+                    _unitOfWorkManage.CommitTran();
+
+                    return WebResponseContent.Instance.OK("鑷姩鎷嗗寘骞跺垎鎷f垚鍔�", autoSplitResult);
+                }
+
+                // 姝e父鍒嗘嫞娴佺▼锛堜笉闇�瑕佽嚜鍔ㄦ媶鍖咃級
+                var normalPickedQty = lockInfo.AssignQuantity;
+                var normalPickingResult = await ExecutePickingLogic(lockInfo, orderDetail, stockDetail, normalPickedQty);
+
+                // 鏇存柊鎵规鍜岃鍗曟暟鎹�
+                await UpdateBatchAndOrderData(batch, orderDetail, normalPickedQty, orderNo);
+
+                // 璁板綍鎷i�夊巻鍙�
+                await RecordPickingHistory(normalPickingResult, orderNo, palletCode);
 
                 _unitOfWorkManage.CommitTran();
 
                 return WebResponseContent.Instance.OK("鍒嗘嫞鎴愬姛", new
                 {
-                    PickedQuantity = actualPickedQty,
+                    PickedQuantity = normalPickedQty,
                     Barcode = barcode,
-                    MaterialCode = lockInfo.MaterielCode
+                    MaterialCode = lockInfo.MaterielCode,
+                    AutoSplitted = false
                 });
             }
             catch (Exception ex)
@@ -492,7 +367,179 @@
         }
         #endregion
 
-        #region 鎵嬪姩鎷嗗寘
+
+        #region 鍙栬蛋绌虹閫昏緫
+
+
+
+        /// <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 stockInfo = await _stockInfoService.Db.Queryable<Dt_StockInfo>()
+                .FirstAsync(x => x.PalletCode == palletCode);
+
+            if (stockInfo != null)
+            {
+                var remainingStock = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                    .Where(x => x.StockId == stockInfo.Id &&
+                               x.Status == (int)StockStatusEmun.鍑哄簱閿佸畾 &&
+                               x.StockQuantity > 0)
+                    .ToListAsync();
+
+                if (remainingStock.Any())
+                {
+                    var remainingQty = remainingStock.Sum(x => x.StockQuantity);
+                    return ValidationResult<List<Dt_OutStockLockInfo>>.Error(
+                        $"鎵樼洏涓婅繕鏈夊簱瀛樿揣鐗╋紝鏁伴噺{remainingQty}锛屼笉鑳藉彇璧扮┖绠�");
+                }
+            }
+
+            // 鑾峰彇宸插畬鎴愮殑閿佸畾璁板綍
+            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
+
+        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 +550,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 +572,247 @@
             }
         }
 
+        /// <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}");
+
+            // 楠岃瘉鎷嗗寘鏁伴噺
+            if (lockInfo.AssignQuantity < splitQuantity)
+            {
+                throw new InvalidOperationException($"鎷嗗寘鏁伴噺瓒呰繃閿佸畾淇℃伅鍒嗛厤鏁伴噺锛屾媶鍖呮暟閲�: {splitQuantity}, 鍒嗛厤鏁伴噺: {lockInfo.AssignQuantity}");
+            }
+
+            // 鐢熸垚鏂版潯鐮�
+            string newBarcode = await GenerateNewBarcode();
+
+            // 璁$畻鍓╀綑鏁伴噺
+            decimal remainQty = lockInfo.AssignQuantity - splitQuantity;
+
+            // 鍒涘缓鏂板簱瀛樻槑缁�
+            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;
+            if (stockDetail.StockQuantity < 0) stockDetail.StockQuantity = 0;
+            await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+
+            // 鍒涘缓鏂伴攣瀹氫俊鎭�
+            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();
+
+            // 鏇存柊鍘熼攣瀹氫俊鎭�
+            lockInfo.AssignQuantity = remainQty;
+            lockInfo.OrderQuantity = remainQty;
+            await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
+
+            // 閲嶈锛氭墜鍔ㄦ媶鍖呬笉鏀瑰彉璁㈠崟鏄庣粏鐨勬�诲垎閰嶆暟閲�
+            // 鍥犱负鍒嗛厤鏁伴噺鍙槸浠庝竴涓攣瀹氫俊鎭浆绉诲埌鍙︿竴涓攣瀹氫俊鎭�
+            _logger.LogInformation($"鎵嬪姩鎷嗗寘 - 璁㈠崟鏄庣粏鎬诲垎閰嶆暟閲忎繚鎸佷笉鍙�");
+
+            // 璁板綍鎷嗗寘鍘嗗彶
+            await RecordSplitHistory(lockInfo, stockDetail, splitQuantity, newBarcode, false);
+
+            // 鍒涘缓鎷嗗寘缁撴灉鍒楄〃
+            var splitResults = CreateSplitResults(lockInfo, splitQuantity, remainQty, newBarcode, stockDetail.Barcode);
+
+            _logger.LogInformation($"鎵嬪姩鎷嗗寘閫昏緫鎵ц瀹屾垚");
+
+            return splitResults;
+        }
+        /// <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 鍙栨秷鎷嗗寘 
 
@@ -588,15 +868,45 @@
             Dt_OutStockLockInfo originalLockInfo, Dt_OutStockLockInfo newLockInfo,
             Dt_StockInfoDetail newStockDetail)
         {
-            // 1. 鎭㈠鍘熼攣瀹氫俊鎭�
-            // 娉ㄦ剰锛氳繖閲岄渶瑕佺疮鍔狅紝鑰屼笉鏄畝鍗曠殑璧嬪�硷紝鍥犱负鍙兘鏈夊娆℃媶鍖�
-            originalLockInfo.AssignQuantity += splitRecord.SplitQty;
-            originalLockInfo.OrderQuantity += splitRecord.SplitQty;
+            _logger.LogInformation($"寮�濮嬫墽琛屽彇娑堟媶鍖呴�昏緫 - 鍘熸潯鐮�: {splitRecord.OriginalBarcode}, 鏂版潯鐮�: {splitRecord.NewBarcode}, 鎷嗗寘鏁伴噺: {splitRecord.SplitQty}");
+
+            // 鑾峰彇璁㈠崟鏄庣粏
+            var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
+                .FirstAsync(x => x.Id == originalLockInfo.OrderDetailId);
+
+            if (orderDetail == null)
+                throw new InvalidOperationException("鏈壘鍒拌鍗曟槑缁�");
+
+            // 璁板綍鍙栨秷鎷嗗寘鍓嶇殑鍏抽敭鏁版嵁
+            decimal originalOrderDetailAllocatedQty = orderDetail.AllocatedQuantity;
+            decimal originalOrderDetailLockQty = orderDetail.LockQuantity;
+
+            _logger.LogInformation($"鍙栨秷鎷嗗寘鍓嶆暟鎹� - 璁㈠崟鏄庣粏鍒嗛厤鏁伴噺: {originalOrderDetailAllocatedQty}, 閿佸畾鏁伴噺: {originalOrderDetailLockQty}");
+
+            // 鎭㈠鍘熼攣瀹氫俊鎭�
+            decimal originalAssignQtyBefore = originalLockInfo.AssignQuantity;
+            decimal originalOrderQtyBefore = originalLockInfo.OrderQuantity;
+
+            // 鏍规嵁鎷嗗寘绫诲瀷鍐冲畾濡備綍鎭㈠
+            if (splitRecord.IsAutoSplit)
+            {
+                // 鑷姩鎷嗗寘锛氬師閿佸畾淇℃伅淇濇寔涓嶅彉锛屽彧闇�瑕佸垹闄ゆ柊閿佸畾淇℃伅
+                _logger.LogInformation($"鍙栨秷鑷姩鎷嗗寘 - 鍘熼攣瀹氫俊鎭繚鎸佷笉鍙�");
+            }
+            else
+            {
+                // 鎵嬪姩鎷嗗寘锛氭仮澶嶅師閿佸畾淇℃伅鐨勫垎閰嶆暟閲�
+                originalLockInfo.AssignQuantity += splitRecord.SplitQty;
+                originalLockInfo.OrderQuantity += splitRecord.SplitQty;
+
+                _logger.LogInformation($"鍙栨秷鎵嬪姩鎷嗗寘 - 鎭㈠鍘熼攣瀹氫俊鎭垎閰嶆暟閲忎粠 {originalAssignQtyBefore} 澧炲姞鍒� {originalLockInfo.AssignQuantity}");
+            }
 
             // 濡傛灉鍘熼攣瀹氫俊鎭殑鐘舵�佹槸鎷i�夊畬鎴愶紝闇�瑕侀噸鏂拌缃负鍑哄簱涓�
             if (originalLockInfo.Status == (int)OutLockStockStatusEnum.鎷i�夊畬鎴�)
             {
                 originalLockInfo.Status = (int)OutLockStockStatusEnum.鍑哄簱涓�;
+                _logger.LogInformation($"鍘熼攣瀹氫俊鎭姸鎬佷粠鎷i�夊畬鎴愭仮澶嶄负鍑哄簱涓�");
             }
 
             await _outStockLockInfoService.Db.Updateable(originalLockInfo).ExecuteCommandAsync();
@@ -605,43 +915,176 @@
             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.鍑哄簱閿佸畾;
+                if (splitRecord.IsAutoSplit)
+                {
+                    // 鑷姩鎷嗗寘锛氬師搴撳瓨鏄庣粏淇濇寔涓嶅彉
+                    _logger.LogInformation($"鍙栨秷鑷姩鎷嗗寘 - 鍘熷簱瀛樻槑缁嗕繚鎸佷笉鍙�");
+                }
+                else
+                {
+                    // 鎵嬪姩鎷嗗寘锛氭仮澶嶅師搴撳瓨鏁伴噺
+                    decimal originalStockQtyBefore = originalStock.StockQuantity;
+                    originalStock.StockQuantity += splitRecord.SplitQty;
+
+                    _logger.LogInformation($"鍙栨秷鎵嬪姩鎷嗗寘 - 鎭㈠鍘熷簱瀛樻槑缁嗘暟閲忎粠 {originalStockQtyBefore} 澧炲姞鍒� {originalStock.StockQuantity}");
+
+                    // 濡傛灉鍘熷簱瀛樼姸鎬佹槸鍑哄簱瀹屾垚锛岄渶瑕侀噸鏂拌缃负鍑哄簱閿佸畾
+                    if (originalStock.Status == (int)StockStatusEmun.鍑哄簱瀹屾垚)
+                    {
+                        originalStock.Status = (int)StockStatusEmun.鍑哄簱閿佸畾;
+                        _logger.LogInformation($"鍘熷簱瀛樼姸鎬佷粠鍑哄簱瀹屾垚鎭㈠涓哄嚭搴撻攣瀹�");
+                    }
+
+                    await _stockInfoDetailService.Db.Updateable(originalStock).ExecuteCommandAsync();
+                }
             }
 
-            await _stockInfoDetailService.Db.Updateable(originalStock).ExecuteCommandAsync();
-
             // 鍒犻櫎鏂伴攣瀹氫俊鎭�
+            _logger.LogInformation($"鍒犻櫎鏂伴攣瀹氫俊鎭� - 鏉$爜: {newLockInfo.CurrentBarcode}, 鍒嗛厤鏁伴噺: {newLockInfo.AssignQuantity}");
             await _outStockLockInfoService.Db.Deleteable<Dt_OutStockLockInfo>()
                 .Where(x => x.Id == newLockInfo.Id)
                 .ExecuteCommandAsync();
 
             // 鍒犻櫎鏂板簱瀛樻槑缁�
+            _logger.LogInformation($"鍒犻櫎鏂板簱瀛樻槑缁� - 鏉$爜: {newStockDetail.Barcode}, 搴撳瓨鏁伴噺: {newStockDetail.StockQuantity}");
             await _stockInfoDetailService.Db.Deleteable<Dt_StockInfoDetail>()
                 .Where(x => x.Barcode == newLockInfo.CurrentBarcode)
                 .ExecuteCommandAsync();
 
-            //鏍囪鎷嗗寘璁板綍涓哄凡鎾ら攢
+            // 濡傛灉鏄嚜鍔ㄦ媶鍖咃紝闇�瑕佸噺灏戣鍗曟槑缁嗙殑鍒嗛厤鏁伴噺鍜岄攣瀹氭暟閲�
+            if (splitRecord.IsAutoSplit)
+            {
+                decimal originalAllocatedBefore = orderDetail.AllocatedQuantity;
+                decimal originalLockBefore = orderDetail.LockQuantity;
+
+                orderDetail.AllocatedQuantity -= splitRecord.SplitQty;
+                orderDetail.LockQuantity -= splitRecord.SplitQty;
+
+                // 杈圭晫妫�鏌ワ細纭繚鏁伴噺涓嶄細涓鸿礋鏁�
+                if (orderDetail.AllocatedQuantity < 0)
+                {
+                    _logger.LogWarning($"鍒嗛厤鏁伴噺鍑虹幇璐熸暟锛岄噸缃负0銆傚師鍊�: {orderDetail.AllocatedQuantity + splitRecord.SplitQty}, 鍑忓皯: {splitRecord.SplitQty}");
+                    orderDetail.AllocatedQuantity = 0;
+                }
+                if (orderDetail.LockQuantity < 0)
+                {
+                    _logger.LogWarning($"閿佸畾鏁伴噺鍑虹幇璐熸暟锛岄噸缃负0銆傚師鍊�: {orderDetail.LockQuantity + splitRecord.SplitQty}, 鍑忓皯: {splitRecord.SplitQty}");
+                    orderDetail.LockQuantity = 0;
+                }
+
+                await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
+
+                _logger.LogInformation($"鍙栨秷鑷姩鎷嗗寘鍑忓皯璁㈠崟鏄庣粏鏁伴噺 - 鍒嗛厤鏁伴噺浠� {originalAllocatedBefore} 鍑忓皯鍒� {orderDetail.AllocatedQuantity}");
+                _logger.LogInformation($"鍙栨秷鑷姩鎷嗗寘鍑忓皯璁㈠崟鏄庣粏鏁伴噺 - 閿佸畾鏁伴噺浠� {originalLockBefore} 鍑忓皯鍒� {orderDetail.LockQuantity}");
+            }
+
+            // 鏍囪鎷嗗寘璁板綍涓哄凡鎾ら攢
             splitRecord.IsReverted = true;
             splitRecord.RevertTime = DateTime.Now;
             splitRecord.RevertOperator = App.User.UserName;
             await _splitPackageService.Db.Updateable(splitRecord).ExecuteCommandAsync();
+            _logger.LogInformation($"鏍囪鎷嗗寘璁板綍涓哄凡鎾ら攢");
+
+            // 楠岃瘉鍙栨秷鎷嗗寘鍚庢暟鎹竴鑷存��
+            await ValidateDataConsistencyAfterCancelSplit(orderDetail.Id, originalOrderDetailAllocatedQty, originalOrderDetailLockQty, splitRecord.IsAutoSplit, splitRecord.SplitQty);
 
             // 妫�鏌ュ苟鏇存柊鎵规鍜岃鍗曠姸鎬�
             await CheckAndUpdateBatchStatus(originalLockInfo.BatchNo);
             await CheckAndUpdateOrderStatus(originalLockInfo.OrderNo);
-        }
 
+            _logger.LogInformation($"鍙栨秷鎷嗗寘閫昏緫鎵ц瀹屾垚");
+        }
+        /// <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 +1094,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 +1107,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 +1145,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));
         }
@@ -707,11 +1180,28 @@
                 if (!splitChain.Any())
                     return WebResponseContent.Instance.Error("鏈壘鍒版媶鍖呰褰�");
 
-                // 2. 鎸夋媶鍖呴『搴忓�掑簭鍙栨秷锛堜粠鏈�鏂扮殑寮�濮嬪彇娑堬級
+                _logger.LogInformation($"鎵惧埌鎷嗗寘閾撅紝鍏� {splitChain.Count} 鏉¤褰�");
+
+                // 2. 鏀堕泦鎷嗗寘閾句腑娑夊強鐨勬墍鏈夋潯鐮侊紙鍖呮嫭鍘熸潯鐮佸拰鏂版潯鐮侊級
+                var allBarcodesInChain = new List<string> { startBarcode };
+                allBarcodesInChain.AddRange(splitChain.Select(x => x.NewBarcode));
+
+                // 3. 妫�鏌ユ媶鍖呴摼涓槸鍚︽湁宸茶鍒嗘嫞鐨勬潯鐮�
+                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}");
+                }
+
+                // 4. 鎸夋媶鍖呴『搴忓�掑簭鍙栨秷锛堜粠鏈�鏂扮殑寮�濮嬪彇娑堬級
                 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 +1217,133 @@
             }
         }
 
+        /// <summary>
+        /// 鑾峰彇鏉$爜鐨勬媶鍖呭拰鎷i�夌姸鎬�
+        /// </summary>
+        public async Task<WebResponseContent> GetBarcodeSplitAndPickStatus(string orderNo, string barcode)
+        {
+            try
+            {
+                // 1. 鑾峰彇鎷嗗寘淇℃伅
+                var splitChain = await GetSplitPackageChain(orderNo, barcode);
+                var isOriginalBarcode = !splitChain.Any(x => x.NewBarcode == barcode);
+
+                // 2. 鑾峰彇鎷i�変俊鎭�
+                var pickingRecords = await Db.Queryable<Dt_PickingRecord>()
+                    .Where(x => x.Barcode == barcode && x.OrderNo == orderNo && !x.IsCancelled)
+                    .ToListAsync();
+
+                var totalPickedQty = pickingRecords.Sum(x => x.PickQuantity);
+
+                // 3. 鑾峰彇閿佸畾淇℃伅
+                var lockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                    .Where(x => x.CurrentBarcode == barcode && x.OrderNo == orderNo)
+                    .FirstAsync();
+
+                // 4. 鑾峰彇搴撳瓨淇℃伅
+                var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                    .Where(x => x.Barcode == barcode)
+                    .FirstAsync();
+
+                var statusInfo = new BarcodeStatusInfoDto
+                {
+                    Barcode = barcode,
+                    OrderNo = orderNo,
+                    IsOriginalBarcode = isOriginalBarcode,
+                    SplitChainCount = splitChain.Count,
+                    HasBeenPicked = pickingRecords.Any(),
+                    TotalPickedQuantity = totalPickedQty,
+                    PickRecordCount = pickingRecords.Count,
+                    LockInfoStatus = lockInfo?.Status ?? 0,
+                    LockInfoPickedQty = lockInfo?.PickedQty ?? 0,
+                    LockInfoAssignQty = lockInfo?.AssignQuantity ?? 0,
+                    StockQuantity = stockDetail?.StockQuantity ?? 0,
+                    StockStatus = stockDetail?.Status ?? 0,
+                    CanCancelSplit = !pickingRecords.Any(), // 鏈鍒嗘嫞鎵嶈兘鍙栨秷鎷嗗寘
+                    NeedCancelPickFirst = pickingRecords.Any() // 闇�瑕佸厛鍙栨秷鍒嗘嫞
+                };
+
+                // 5. 鑾峰彇鎿嶄綔寤鸿
+                statusInfo.OperationSuggestions = GetOperationSuggestions(statusInfo);
+
+                return WebResponseContent.Instance.OK("鑾峰彇鐘舵�佹垚鍔�", statusInfo);
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"鑾峰彇鏉$爜鐘舵�佸け璐� - OrderNo: {orderNo}, Barcode: {barcode}, Error: {ex.Message}");
+                return WebResponseContent.Instance.Error("鑾峰彇鏉$爜鐘舵�佸け璐�");
+            }
+        }
+        /// <summary>
+        /// 鑾峰彇鎿嶄綔寤鸿
+        /// </summary>
+        private List<string> GetOperationSuggestions(BarcodeStatusInfoDto statusInfo)
+        {
+            var suggestions = new List<string>();
+
+            if (statusInfo.HasBeenPicked)
+            {
+                suggestions.Add($"璇ユ潯鐮佸凡琚垎鎷o紙鏁伴噺锛歿statusInfo.TotalPickedQuantity}锛夛紝濡傞渶鍙栨秷鎷嗗寘锛岃鍏堝彇娑堝垎鎷�");
+
+                if (statusInfo.IsOriginalBarcode)
+                {
+                    suggestions.Add("杩欐槸鍘熸潯鐮侊紝鍙栨秷鍒嗘嫞鍚庡皢鎭㈠涓哄彲鍒嗘嫞鐘舵��");
+                }
+                else
+                {
+                    suggestions.Add("杩欐槸鎷嗗寘鐢熸垚鐨勬柊鏉$爜锛屽彇娑堝垎鎷e悗鎵嶈兘鍙栨秷鎷嗗寘");
+                }
+            }
+            else
+            {
+                if (statusInfo.IsOriginalBarcode && statusInfo.SplitChainCount > 0)
+                {
+                    suggestions.Add("杩欐槸鍘熸潯鐮侊紝鍙互鍙栨秷鎷嗗寘閾�");
+                }
+                else if (!statusInfo.IsOriginalBarcode)
+                {
+                    suggestions.Add("杩欐槸鎷嗗寘鐢熸垚鐨勬柊鏉$爜锛屽彲浠ュ崟鐙彇娑堟媶鍖�");
+                }
+            }
+
+            if (statusInfo.LockInfoStatus == (int)OutLockStockStatusEnum.鎷i�夊畬鎴�)
+            {
+                suggestions.Add("閿佸畾鐘舵�侊細鎷i�夊畬鎴�");
+            }
+            else if (statusInfo.LockInfoStatus == (int)OutLockStockStatusEnum.鍑哄簱涓�)
+            {
+                suggestions.Add("閿佸畾鐘舵�侊細鍑哄簱涓�");
+            }
+
+            return suggestions;
+        }
+        /// <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 +1388,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 +1423,8 @@
 
             // 鎵ц鍙栨秷閫昏緫
             await ExecuteCancelSplitLogic(splitRecord, originalLockInfo, newLockInfo, newStockDetail);
+
+            _logger.LogInformation($"鍙栨秷鍗曚釜鎷嗗寘璁板綍瀹屾垚 - 鍘熸潯鐮�: {splitRecord.OriginalBarcode}, 鏂版潯鐮�: {splitRecord.NewBarcode}");
         }
         #endregion
 
@@ -810,7 +1450,8 @@
                         NewBarcode = x.NewBarcode,
                         SplitQuantity = x.SplitQty,
                         Operator = x.Operator,
-                        IsReverted = x.IsReverted
+                        IsReverted = x.IsReverted,
+                        IsAutoSplit = x.IsAutoSplit
                     }).ToList()
                 };
 
@@ -899,68 +1540,1306 @@
 
         #endregion
 
+        #region 缁熶竴鍥炲簱閫昏緫
+        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;
+        }
+        private async Task<PalletStatusAnalysis> AnalyzePalletStatus(string orderNo, string palletCode, int stockId)
+        {
+            var result = new PalletStatusAnalysis
+            {
+                OrderNo = orderNo,
+                PalletCode = palletCode,
+                StockId = stockId
+            };
 
-        #region 鍒嗘壒鍥炲簱
+            // 鍒嗘瀽鏈垎鎷g殑鍑哄簱閿佸畾璁板綍
+            var remainingLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                .Where(it => it.OrderNo == orderNo &&
+                           it.PalletCode == palletCode &&
+                           it.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�)
+                .ToListAsync();
+
+            if (remainingLocks.Any())
+            {
+                result.HasRemainingLocks = true;
+                result.RemainingLocks = remainingLocks;
+                result.RemainingLocksReturnQty = remainingLocks.Sum(x => x.AssignQuantity - x.PickedQty);
+                _logger.LogInformation($"鍙戠幇{remainingLocks.Count}鏉℃湭鍒嗘嫞閿佸畾璁板綍锛屾�绘暟閲�: {result.RemainingLocksReturnQty}");
+            }
+
+            // 鍒嗘瀽鎵樼洏涓婄殑搴撳瓨璐х墿
+            var palletStockGoods = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                .Where(it => it.StockId == stockId &&
+                     (it.Status == StockStatusEmun.鍏ュ簱纭.ObjToInt() ||
+                      it.Status == StockStatusEmun.鍏ュ簱瀹屾垚.ObjToInt() ||
+                      it.Status == StockStatusEmun.鍑哄簱閿佸畾.ObjToInt()))
+                .Where(it => it.StockQuantity > 0)
+                .ToListAsync();
+
+            if (palletStockGoods.Any())
+            {
+                result.HasPalletStockGoods = true;
+                result.PalletStockGoods = palletStockGoods;
+                result.PalletStockReturnQty = palletStockGoods.Sum(x => x.StockQuantity);
+                _logger.LogInformation($"鍙戠幇{palletStockGoods.Count}涓簱瀛樿揣鐗╋紝鎬绘暟閲�: {result.PalletStockReturnQty}");
+
+                // 璁板綍璇︾粏鐘舵�佸垎甯�
+                var statusGroups = palletStockGoods.GroupBy(x => x.Status);
+                foreach (var group in statusGroups)
+                {
+                    _logger.LogInformation($"搴撳瓨鐘舵�亄group.Key}: {group.Count()}涓揣鐗╋紝鏁伴噺: {group.Sum(x => x.StockQuantity)}");
+                }
+            }
+
+            //鍒嗘瀽鎷嗗寘璁板綍
+            var splitRecords = await _splitPackageService.Db.Queryable<Dt_SplitPackageRecord>()
+                .Where(it => it.OrderNo == orderNo &&
+                           it.PalletCode == palletCode &&
+                           !it.IsReverted && it.Status != (int)SplitPackageStatusEnum.宸叉嫞閫� &&
+                           it.Status != (int)SplitPackageStatusEnum.宸插洖搴�)
+                .ToListAsync();
+
+            if (splitRecords.Any())
+            {
+                result.HasSplitRecords = true;
+                result.SplitRecords = splitRecords;
+                result.SplitReturnQty = await CalculateSplitReturnQuantity(splitRecords, stockId);
+
+                _logger.LogInformation($"鍙戠幇{splitRecords.Count}鏉℃湭鎷i�夋媶鍖呰褰曪紝鎬绘暟閲�: {result.SplitReturnQty}");
+            }
+
+            // 4. 璁$畻鎬诲洖搴撴暟閲忓拰绌烘墭鐩樼姸鎬�
+            result.TotalReturnQty = result.RemainingLocksReturnQty + result.PalletStockReturnQty + result.SplitReturnQty;
+            result.HasItemsToReturn = result.TotalReturnQty > 0;
+            result.IsEmptyPallet = !result.HasItemsToReturn;
+
+            // 5. 妫�鏌ユ槸鍚︽湁杩涜涓殑浠诲姟
+            result.HasActiveTasks = await _taskRepository.Db.Queryable<Dt_Task>()
+                .Where(x => x.OrderNo == orderNo && x.TaskType == TaskTypeEnum.InPick.ObjToInt() &&
+                           x.PalletCode == palletCode &&
+                           x.TaskStatus == (int)TaskStatusEnum.New)
+                .AnyAsync();
+
+            _logger.LogInformation($"鎵樼洏鐘舵�佸垎鏋愬畬鎴� - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}, " +
+                                  $"鎬诲洖搴撴暟閲�: {result.TotalReturnQty}, 鏄惁绌烘墭鐩�: {result.IsEmptyPallet}, " +
+                                  $"鏈夎繘琛屼腑浠诲姟: {result.HasActiveTasks}");
+
+            return result;
+        }
+        private async Task<decimal> CalculateSplitReturnQuantity(List<Dt_SplitPackageRecord> splitRecords, int stockId)
+        {
+            decimal totalQty = 0;
+            var processedBarcodes = new HashSet<string>();
+
+            foreach (var splitRecord in splitRecords)
+            {
+                if (splitRecord.Status != (int)SplitPackageStatusEnum.宸叉挙閿�)
+                    continue;
+                // 妫�鏌ュ師鏉$爜
+                if (!processedBarcodes.Contains(splitRecord.OriginalBarcode))
+                {
+                    var originalStock = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                        .Where(it => it.Barcode == splitRecord.OriginalBarcode && it.StockId == stockId &&
+                           it.Status != StockStatusEmun.鍑哄簱瀹屾垚.ObjToInt())
+                        .FirstAsync();
+
+                    if (originalStock != null && originalStock.StockQuantity > 0)
+                    {
+                        totalQty += originalStock.StockQuantity;
+                        processedBarcodes.Add(splitRecord.OriginalBarcode);
+                    }
+                }
+
+                // 妫�鏌ユ柊鏉$爜
+                if (!processedBarcodes.Contains(splitRecord.NewBarcode))
+                {
+                    var newStock = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                        .Where(it => it.Barcode == splitRecord.NewBarcode && it.StockId == stockId && it.Status != StockStatusEmun.鍑哄簱瀹屾垚.ObjToInt())
+                        .FirstAsync();
+
+                    if (newStock != null && newStock.StockQuantity > 0)
+                    {
+                        totalQty += newStock.StockQuantity;
+                        processedBarcodes.Add(splitRecord.NewBarcode);
+                    }
+                }
+            }
+
+            return totalQty;
+        }
 
         /// <summary>
-        /// 鍒嗘壒鍥炲簱 - 閲婃斁鏈嫞閫夌殑搴撳瓨
+        /// 缁熶竴鍥炲簱鏂规硶 - 澶勭悊鎵樼洏涓婃墍鏈夊墿浣欒揣鐗�
         /// </summary>
-        public async Task<WebResponseContent> BatchReturnStock(string orderNo, string palletCode)
+        public async Task<WebResponseContent> ExecutePalletReturn(string orderNo, string palletCode, string returnReason = "鍒嗘壒鍥炲簱")
         {
             try
             {
                 _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);
+                if (stockInfo == null)
+                    return WebResponseContent.Instance.Error($"鏈壘鍒版墭鐩� {palletCode} 瀵瑰簲鐨勫簱瀛樹俊鎭�");
 
-                // 鎸夊嚭搴撴壒娆″垎缁勫鐞�
-                var batchGroups = unfinishedLocks.GroupBy(x => x.OutboundBatchNo); // 浣跨敤 OutboundBatchNo
+                // 鍒嗘瀽鎵樼洏鐘舵��
+                var statusAnalysis = await AnalyzePalletStatusForReturn(orderNo, palletCode, stockInfo.Id);
 
-                foreach (var batchGroup in batchGroups)
-                {
-                    var outboundBatchNo = batchGroup.Key;
-                    var batchLocks = batchGroup.ToList();
+                if (!statusAnalysis.HasItemsToReturn)
+                    return await HandleEmptyPalletReturn(orderNo, palletCode, stockInfo);
 
-                    // 閲婃斁搴撳瓨鍜岄攣瀹氳褰�
-                    foreach (var lockInfo in batchLocks)
-                    {
-                        await ReleaseLockAndStock(lockInfo);
-                    }
+                _logger.LogInformation($"寮�濮嬪洖搴撴搷浣� - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}, 鍥炲簱鏁伴噺: {statusAnalysis.TotalReturnQty}");
 
-                    // 鏇存柊鎵规鐘舵��
-                    await UpdateBatchStatusForReturn(outboundBatchNo, batchLocks);
+                // 鎵ц鍥炲簱鏁版嵁鎿嶄綔
+                await ExecuteReturnDataOperations(statusAnalysis);
 
-                    // 鏇存柊璁㈠崟鏄庣粏鐨勫凡鍒嗛厤鏁伴噺
-                    await UpdateOrderDetailAfterReturn(batchLocks);
-                }
+                // 鏇存柊璁㈠崟鐘舵��
+                await UpdateOrderStatusAfterReturn(orderNo);
 
                 _unitOfWorkManage.CommitTran();
 
-                return WebResponseContent.Instance.OK("鍒嗘壒鍥炲簱鎴愬姛");
+                // 鍒涘缓鍥炲簱浠诲姟锛圓GV锛�
+                await CreateReturnTask(orderNo, palletCode, stockInfo);
+
+                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($"鍥炲簱鎿嶄綔澶辫触 - OrderNo: {orderNo}, PalletCode: {palletCode}, Error: {ex.Message}");
+                return WebResponseContent.Instance.Error($"鍥炲簱鎿嶄綔澶辫触: {ex.Message}");
+            }
+        }
+        /// <summary>
+        /// 鎵ц鍥炲簱鏁版嵁鎿嶄綔
+        /// 纭繚涓嶄細灏嗙敓鎴愮殑鏉$爜鏁伴噺閿欒缁戝畾鍒伴攣瀹氭暟閲�
+        /// </summary>
+        private async Task ExecuteReturnDataOperations(PalletStatusAnalysis statusAnalysis)
+        {
+            _logger.LogInformation($"寮�濮嬫墽琛屽洖搴撴暟鎹搷浣� - 璁㈠崟: {statusAnalysis.OrderNo}, 鎵樼洏: {statusAnalysis.PalletCode}");
+
+            try
+            {
+                // 1. 澶勭悊宸插垎閰嶇殑鏈垎鎷i攣瀹氳褰�
+                if (statusAnalysis.HasRemainingLocks)
+                {
+                    _logger.LogInformation($"澶勭悊 {statusAnalysis.RemainingLocks.Count} 鏉″凡鍒嗛厤鏈垎鎷i攣瀹氳褰�");
+                    await HandleAllocatedLocksReturn(statusAnalysis.RemainingLocks);
+                }
+
+                // 2. 澶勭悊鏈垎閰嶇殑閿佸畾璁板綍锛堝鑷姩鎷嗗寘浜х敓鐨勶級
+                if (statusAnalysis.HasUnallocatedLocks)
+                {
+                    _logger.LogInformation($"澶勭悊 {statusAnalysis.UnallocatedLocks.Count} 鏉℃湭鍒嗛厤閿佸畾璁板綍");
+                    await HandleUnallocatedLocksReturn(statusAnalysis.UnallocatedLocks);
+                }
+
+                // 3. 澶勭悊鏈垎閰嶇殑搴撳瓨璐х墿
+                if (statusAnalysis.HasPalletStockGoods)
+                {
+                    _logger.LogInformation($"澶勭悊 {statusAnalysis.PalletStockGoods.Count} 涓湭鍒嗛厤搴撳瓨璐х墿");
+                    await HandleUnallocatedStockReturn(statusAnalysis.PalletStockGoods);
+                }
+
+                _logger.LogInformation($"鍥炲簱鏁版嵁鎿嶄綔瀹屾垚 - 鎬诲洖搴撴暟閲�: {statusAnalysis.TotalReturnQty}");
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"鍥炲簱鏁版嵁鎿嶄綔澶辫触 - 璁㈠崟: {statusAnalysis.OrderNo}, 鎵樼洏: {statusAnalysis.PalletCode}, Error: {ex.Message}");
+                throw;
+            }
+        }
+        // <summary>
+        /// 澶勭悊鏈垎閰嶇殑閿佸畾璁板綍鍥炲簱
+        /// 涓嶉渶瑕佸噺灏戣鍗曟槑缁嗙殑鍒嗛厤鏁伴噺
+        /// </summary>
+        private async Task HandleUnallocatedLocksReturn(List<Dt_OutStockLockInfo> unallocatedLocks)
+        {
+            _logger.LogInformation($"寮�濮嬪鐞嗘湭鍒嗛厤閿佸畾璁板綍鍥炲簱 - 鍏� {unallocatedLocks.Count} 鏉¤褰�");
+
+            foreach (var lockInfo in unallocatedLocks)
+            {
+                // 璁$畻鍥炲簱鏁伴噺锛堟湭鎷i�夌殑閮ㄥ垎锛�
+                decimal returnQty = lockInfo.AssignQuantity - lockInfo.PickedQty;
+
+                if (returnQty <= 0)
+                {
+                    _logger.LogInformation($"璺宠繃鏈垎閰嶉攣瀹氳褰� - 閿佸畾ID: {lockInfo.Id}, 宸叉嫞閫夊畬鎴愭垨鏃犻渶鍥炲簱");
+                    continue;
+                }
+
+                _logger.LogInformation($"澶勭悊鏈垎閰嶉攣瀹氳褰曞洖搴� - 閿佸畾ID: {lockInfo.Id}, 鏉$爜: {lockInfo.CurrentBarcode}, 鍥炲簱鏁伴噺: {returnQty}");
+
+                // 鎭㈠搴撳瓨鐘舵��
+                await RestoreStockForLockInfo(lockInfo, returnQty);
+
+                // 鏇存柊閿佸畾璁板綍鐘舵�佷负宸插洖搴�
+                lockInfo.Status = (int)OutLockStockStatusEnum.宸插洖搴�;
+                lockInfo.Operator = App.User.UserName;
+
+                await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
+
+                _logger.LogInformation($"鏇存柊鏈垎閰嶉攣瀹氱姸鎬� - 閿佸畾ID: {lockInfo.Id}, 鐘舵��: 鍑哄簱涓� -> 宸插洖搴�");
+
+                // 閲嶈锛氭湭鍒嗛厤閿佸畾璁板綍涓嶉渶瑕佸噺灏戣鍗曟槑缁嗙殑鍒嗛厤鏁伴噺
+                _logger.LogInformation($"鏈垎閰嶉攣瀹氳褰曞洖搴撳畬鎴� - 閿佸畾ID: {lockInfo.Id}, 鍥炲簱鏁伴噺: {returnQty}, 鏃犻渶鏇存柊璁㈠崟鏄庣粏");
+            }
+
+            _logger.LogInformation($"鏈垎閰嶉攣瀹氳褰曞洖搴撳鐞嗗畬鎴� - 鍏卞鐞� {unallocatedLocks.Count} 鏉¤褰�");
+        }
+        private async Task HandleAllocatedLocksReturn(List<Dt_OutStockLockInfo> allocatedLocks)
+        {
+            _logger.LogInformation($"寮�濮嬪鐞嗗凡鍒嗛厤閿佸畾璁板綍鍥炲簱 - 鍏� {allocatedLocks.Count} 鏉¤褰�");
+
+            // 鎸夎鍗曟槑缁嗗垎缁勫鐞�
+            var orderDetailGroups = allocatedLocks.GroupBy(x => x.OrderDetailId);
+
+            foreach (var group in orderDetailGroups)
+            {
+                var orderDetailId = group.Key;
+                var groupLocks = group.ToList();
+
+                _logger.LogInformation($"澶勭悊璁㈠崟鏄庣粏 {orderDetailId} 鐨� {groupLocks.Count} 鏉¢攣瀹氳褰�");
+
+                // 鑾峰彇璁㈠崟鏄庣粏
+                var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
+                    .FirstAsync(x => x.Id == orderDetailId);
+
+                if (orderDetail == null)
+                {
+                    _logger.LogWarning($"鏈壘鍒拌鍗曟槑缁� - OrderDetailId: {orderDetailId}");
+                    continue;
+                }
+
+                decimal totalReturnQtyForDetail = 0;
+
+                foreach (var lockInfo in groupLocks)
+                {
+                    // 璁$畻鍥炲簱鏁伴噺锛堟湭鎷i�夌殑閮ㄥ垎锛�
+                    decimal returnQty = lockInfo.AssignQuantity - lockInfo.PickedQty;
+
+                    if (returnQty <= 0)
+                    {
+                        _logger.LogInformation($"璺宠繃閿佸畾璁板綍 - 閿佸畾ID: {lockInfo.Id}, 宸叉嫞閫夊畬鎴愭垨鏃犻渶鍥炲簱");
+                        continue;
+                    }
+
+                    _logger.LogInformation($"澶勭悊宸插垎閰嶉攣瀹氳褰曞洖搴� - 閿佸畾ID: {lockInfo.Id}, 鏉$爜: {lockInfo.CurrentBarcode}, 鍥炲簱鏁伴噺: {returnQty}");
+
+                    // 鎭㈠搴撳瓨鐘舵��
+                    await RestoreStockForLockInfo(lockInfo, returnQty);
+
+                    // 鏇存柊閿佸畾璁板綍鐘舵�佷负宸插洖搴�
+                    lockInfo.Status = (int)OutLockStockStatusEnum.宸插洖搴�;
+                    lockInfo.Operator = App.User.UserName;
+
+                    await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
+
+                    _logger.LogInformation($"鏇存柊宸插垎閰嶉攣瀹氱姸鎬� - 閿佸畾ID: {lockInfo.Id}, 鐘舵��: 鍑哄簱涓� -> 宸插洖搴�");
+
+                    totalReturnQtyForDetail += returnQty;
+                }
+
+                // 鍑忓皯璁㈠崟鏄庣粏鐨勫垎閰嶆暟閲�
+                if (totalReturnQtyForDetail > 0)
+                {
+                    await ReduceOrderDetailAllocation(orderDetail, totalReturnQtyForDetail);
+                }
+            }
+
+            _logger.LogInformation($"宸插垎閰嶉攣瀹氳褰曞洖搴撳鐞嗗畬鎴� - 鍏卞鐞� {allocatedLocks.Count} 鏉¤褰�");
+        }
+        /// <summary>
+        /// 鎭㈠閿佸畾璁板綍瀵瑰簲鐨勫簱瀛�
+        /// </summary>
+        private async Task RestoreStockForLockInfo(Dt_OutStockLockInfo lockInfo, decimal returnQty)
+        {
+            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;
+
+                // 鎭㈠搴撳瓨鏁伴噺锛氬嚭搴撴暟閲忓噺灏戯紝搴撳瓨鏁伴噺澧炲姞
+                stockDetail.OutboundQuantity -= returnQty;
+                stockDetail.StockQuantity += returnQty;
+
+                // 纭繚鏁伴噺涓嶄細涓鸿礋鏁�
+                if (stockDetail.OutboundQuantity < 0)
+                {
+                    _logger.LogWarning($"鍑哄簱鏁伴噺鍑虹幇璐熸暟锛岄噸缃负0銆傚師鍊�: {stockDetail.OutboundQuantity + returnQty}");
+                    stockDetail.OutboundQuantity = 0;
+                }
+
+                // 鎭㈠搴撳瓨鐘舵�佷负鍙敤鐘舵��
+                if (stockDetail.Status == (int)StockStatusEmun.鍑哄簱閿佸畾)
+                {
+                    stockDetail.Status = (int)StockStatusEmun.鍏ュ簱瀹屾垚;
+                    _logger.LogInformation($"搴撳瓨鐘舵�佹洿鏂颁负鍏ュ簱瀹屾垚 - 鏉$爜: {stockDetail.Barcode}");
+                }
+
+                await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+
+                _logger.LogInformation($"鎭㈠搴撳瓨鐘舵�� - 鏉$爜: {stockDetail.Barcode}, " +
+                                     $"搴撳瓨鏁伴噺: {originalStockQty} -> {stockDetail.StockQuantity}, " +
+                                     $"鍑哄簱鏁伴噺: {originalOutboundQty} -> {stockDetail.OutboundQuantity}");
+            }
+            else
+            {
+                _logger.LogWarning($"鏈壘鍒板搴旂殑搴撳瓨淇℃伅 - 鏉$爜: {lockInfo.CurrentBarcode}, StockId: {lockInfo.StockId}");
+            }
+        }
+        /// <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 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);
+
+                // 鍒涘缓绌烘墭鐩樺洖搴撲换鍔�
+                await CreateReturnTask(orderNo, palletCode, emptyStockInfo);
+
+                return WebResponseContent.Instance.OK("绌烘墭鐩樺洖搴撴垚鍔�");
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"绌烘墭鐩樺洖搴撳け璐�: {ex.Message}");
+                return WebResponseContent.Instance.Error($"绌烘墭鐩樺洖搴撳け璐�: {ex.Message}");
+            }
+        }
+        /// <summary>
+        /// 鍒嗘瀽鎵樼洏鐘舵�佺敤浜庡洖搴�
+        /// 纭繚涓嶄細閿欒璇嗗埆闇�瑕佸洖搴撶殑鐗╁搧
+        /// </summary>
+        private async Task<PalletStatusAnalysis> AnalyzePalletStatusForReturn(string orderNo, string palletCode, int stockId)
+        {
+            var result = new PalletStatusAnalysis
+            {
+                OrderNo = orderNo,
+                PalletCode = palletCode,
+                StockId = stockId
+            };
+
+            // 1. 鍒嗘瀽鏈垎鎷g殑閿佸畾璁板綍锛堢姸鎬佷负鍑哄簱涓級
+            var unfinishedLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                .Where(x => x.OrderNo == orderNo &&
+                           x.PalletCode == palletCode &&
+                           x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�)
+                .ToListAsync();
+
+            if (unfinishedLocks.Any())
+            {
+                //  鍖哄垎宸插垎閰嶅拰鏈垎閰嶇殑閿佸畾璁板綍
+                var allocatedLocks = unfinishedLocks.Where(x => x.IsUnallocated != 1 && x.OrderDetailId > 0).ToList();
+                var unallocatedLocks = unfinishedLocks.Where(x => x.IsUnallocated == 1 || x.OrderDetailId == 0).ToList();
+
+                // 澶勭悊宸插垎閰嶇殑閿佸畾璁板綍
+                if (allocatedLocks.Any())
+                {
+                    result.HasRemainingLocks = true;
+                    result.RemainingLocks = allocatedLocks;
+                    result.RemainingLocksReturnQty = allocatedLocks.Sum(x => x.AssignQuantity - x.PickedQty);
+
+                    foreach (var lockInfo in allocatedLocks)
+                    {
+                        if (!string.IsNullOrEmpty(lockInfo.CurrentBarcode))
+                        {
+                            result.AllBarcodes.Add(lockInfo.CurrentBarcode);
+                        }
+                    }
+
+                    _logger.LogInformation($"鍙戠幇{allocatedLocks.Count}鏉″凡鍒嗛厤鏈垎鎷i攣瀹氳褰曪紝鎬绘暟閲�: {result.RemainingLocksReturnQty}");
+                }
+
+                // 澶勭悊鏈垎閰嶇殑閿佸畾璁板綍锛堝鑷姩鎷嗗寘浜х敓鐨勶級
+                if (unallocatedLocks.Any())
+                {
+                    result.HasUnallocatedLocks = true;
+                    result.UnallocatedLocks = unallocatedLocks;
+                    result.UnallocatedLocksReturnQty = unallocatedLocks.Sum(x => x.AssignQuantity - x.PickedQty);
+
+                    foreach (var lockInfo in unallocatedLocks)
+                    {
+                        if (!string.IsNullOrEmpty(lockInfo.CurrentBarcode))
+                        {
+                            result.AllBarcodes.Add(lockInfo.CurrentBarcode);
+                        }
+                    }
+
+                    _logger.LogInformation($"鍙戠幇{unallocatedLocks.Count}鏉℃湭鍒嗛厤閿佸畾璁板綍锛屾�绘暟閲�: {result.UnallocatedLocksReturnQty}");
+                }
+            }
+
+            // 2. 鍒嗘瀽鎵樼洏涓婄殑鍓╀綑搴撳瓨璐х墿锛堢姸鎬佷负鍑哄簱閿佸畾浣嗘湭鍒嗛厤锛�
+            var palletStockGoods = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                .Where(x => x.StockId == stockId &&
+                           x.Status == (int)StockStatusEmun.鍑哄簱閿佸畾 &&
+                           x.StockQuantity > 0)
+                .ToListAsync();
+
+            // 杩囨护鎺夊凡缁忚閿佸畾璁板綍鍗犵敤鐨勫簱瀛�
+            var lockedBarcodes = unfinishedLocks.Select(x => x.CurrentBarcode).ToList();
+            var unlockedStockGoods = palletStockGoods.Where(x => !lockedBarcodes.Contains(x.Barcode)).ToList();
+
+            // 杩涗竴姝ヨ繃婊わ細妫�鏌ヨ繖浜涘簱瀛樻槸鍚︽湁鍏宠仈鐨勯攣瀹氳褰�
+            var trulyUnallocatedGoods = new List<Dt_StockInfoDetail>();
+            foreach (var stock in unlockedStockGoods)
+            {
+                var hasLock = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                    .Where(x => x.CurrentBarcode == stock.Barcode &&
+                               x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�)
+                    .AnyAsync();
+
+                if (!hasLock)
+                {
+                    trulyUnallocatedGoods.Add(stock);
+                }
+            }
+
+            if (trulyUnallocatedGoods.Any())
+            {
+                result.HasPalletStockGoods = true;
+                result.PalletStockGoods = trulyUnallocatedGoods;
+                result.PalletStockReturnQty = trulyUnallocatedGoods.Sum(x => x.StockQuantity);
+
+                foreach (var stock in trulyUnallocatedGoods)
+                {
+                    result.AllBarcodes.Add(stock.Barcode);
+                }
+
+                _logger.LogInformation($"鍙戠幇{trulyUnallocatedGoods.Count}涓湡姝f湭鍒嗛厤搴撳瓨璐х墿锛屾�绘暟閲�: {result.PalletStockReturnQty}");
+            }
+
+            // 3. 璁$畻鎬诲洖搴撴暟閲�
+            result.TotalReturnQty = result.RemainingLocksReturnQty + result.UnallocatedLocksReturnQty + result.PalletStockReturnQty;
+            result.HasItemsToReturn = result.TotalReturnQty > 0;
+            result.IsEmptyPallet = !result.HasItemsToReturn;
+
+            _logger.LogInformation($"鎵樼洏鐘舵�佸垎鏋愬畬鎴� - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}, 鎬诲洖搴撴暟閲�: {result.TotalReturnQty}");
+
+            return result;
+        }
+        /// <summary>
+        /// 澶勭悊鏈垎鎷g殑閿佸畾璁板綍鍥炲簱
+        /// 纭繚涓嶄細閿欒缁戝畾鏉$爜鏁伴噺鍒伴攣瀹氭暟閲�
+        /// </summary>
+        private async Task HandleRemainingLocksReturn(List<Dt_OutStockLockInfo> remainingLocks)
+        {
+            _logger.LogInformation($"寮�濮嬪鐞嗘湭鍒嗘嫞閿佸畾璁板綍鍥炲簱 - 鍏� {remainingLocks.Count} 鏉¤褰�");
+
+            // 鎸夎鍗曟槑缁嗗垎缁勫鐞嗭紝纭繚璁㈠崟鏄庣粏鏁版嵁鐨勪竴鑷存��
+            var orderDetailGroups = remainingLocks.GroupBy(x => x.OrderDetailId);
+
+            foreach (var group in orderDetailGroups)
+            {
+                var orderDetailId = group.Key;
+                var groupLocks = group.ToList();
+
+                _logger.LogInformation($"澶勭悊璁㈠崟鏄庣粏 {orderDetailId} 鐨� {groupLocks.Count} 鏉¢攣瀹氳褰�");
+
+                // 鑾峰彇璁㈠崟鏄庣粏
+                var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
+                    .FirstAsync(x => x.Id == orderDetailId);
+
+                if (orderDetail == null)
+                {
+                    _logger.LogWarning($"鏈壘鍒拌鍗曟槑缁� - OrderDetailId: {orderDetailId}");
+                    continue;
+                }
+
+                decimal totalReturnQtyForDetail = 0;
+
+                foreach (var lockInfo in groupLocks)
+                {
+                    // 鍙鐞嗙姸鎬佷负鍑哄簱涓殑閿佸畾璁板綍
+                    if (lockInfo.Status != (int)OutLockStockStatusEnum.鍑哄簱涓�)
+                    {
+                        _logger.LogInformation($"璺宠繃闈炲嚭搴撲腑鐘舵�佺殑閿佸畾璁板綍 - 閿佸畾ID: {lockInfo.Id}, 鐘舵��: {lockInfo.Status}");
+                        continue;
+                    }
+
+                    // 璁$畻鍥炲簱鏁伴噺锛堟湭鎷i�夌殑閮ㄥ垎锛�
+                    decimal returnQty = lockInfo.AssignQuantity - lockInfo.PickedQty;
+
+                    if (returnQty <= 0)
+                    {
+                        _logger.LogInformation($"璺宠繃閿佸畾璁板綍 - 閿佸畾ID: {lockInfo.Id}, 宸叉嫞閫夊畬鎴愭垨鏃犻渶鍥炲簱");
+                        continue;
+                    }
+
+                    _logger.LogInformation($"澶勭悊閿佸畾璁板綍鍥炲簱 - 閿佸畾ID: {lockInfo.Id}, 鏉$爜: {lockInfo.CurrentBarcode}, 鍥炲簱鏁伴噺: {returnQty}");
+
+                    // 鎭㈠搴撳瓨鐘舵��
+                    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;
+
+                        // 鍙仮澶嶅疄闄呯殑搴撳瓨鏁伴噺锛屼笉鍒涘缓鏂扮殑鏉$爜鎴栫粦瀹�
+                        // 鎭㈠搴撳瓨鏁伴噺锛氬嚭搴撴暟閲忓噺灏戯紝搴撳瓨鏁伴噺澧炲姞
+                        stockDetail.OutboundQuantity -= returnQty;
+                        stockDetail.StockQuantity += returnQty;
+
+                        // 纭繚鏁伴噺涓嶄細涓鸿礋鏁�
+                        if (stockDetail.OutboundQuantity < 0)
+                        {
+                            _logger.LogWarning($"鍑哄簱鏁伴噺鍑虹幇璐熸暟锛岄噸缃负0銆傚師鍊�: {stockDetail.OutboundQuantity + returnQty}");
+                            stockDetail.OutboundQuantity = 0;
+                        }
+
+                        // 鎭㈠搴撳瓨鐘舵�佷负鍙敤鐘舵��
+                        if (stockDetail.Status == (int)StockStatusEmun.鍑哄簱閿佸畾)
+                        {
+                            stockDetail.Status = (int)StockStatusEmun.鍏ュ簱瀹屾垚;
+                            _logger.LogInformation($"搴撳瓨鐘舵�佹洿鏂颁负鍏ュ簱瀹屾垚 - 鏉$爜: {stockDetail.Barcode}");
+                        }
+
+                        await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+
+                        _logger.LogInformation($"鎭㈠搴撳瓨鐘舵�� - 鏉$爜: {stockDetail.Barcode}, " +
+                                             $"搴撳瓨鏁伴噺: {originalStockQty} -> {stockDetail.StockQuantity}, " +
+                                             $"鍑哄簱鏁伴噺: {originalOutboundQty} -> {stockDetail.OutboundQuantity}");
+                    }
+                    else
+                    {
+                        _logger.LogWarning($"鏈壘鍒板搴旂殑搴撳瓨淇℃伅 - 鏉$爜: {lockInfo.CurrentBarcode}, StockId: {lockInfo.StockId}");
+                        // 閲嶈锛氬鏋滄壘涓嶅埌搴撳瓨淇℃伅锛岃烦杩囨閿佸畾璁板綍锛岄伩鍏嶆暟鎹笉涓�鑷�
+                        continue;
+                    }
+
+                    // 鏇存柊閿佸畾璁板綍鐘舵�佷负宸插洖搴擄紝浣嗕笉淇敼鍒嗛厤鏁伴噺
+                    // 鍒嗛厤鏁伴噺鍦ㄨ鍗曟槑缁嗗眰闈㈢粺涓�澶勭悊
+                    var originalStatus = lockInfo.Status;
+                    lockInfo.Status = (int)OutLockStockStatusEnum.宸插洖搴�;
+                    lockInfo.Operator = App.User.UserName;
+
+                    await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
+
+                    _logger.LogInformation($"鏇存柊閿佸畾鐘舵�� - 閿佸畾ID: {lockInfo.Id}, 鐘舵��: {originalStatus} -> {lockInfo.Status}");
+
+                    totalReturnQtyForDetail += returnQty;
+
+                    _logger.LogInformation($"閿佸畾璁板綍鍥炲簱瀹屾垚 - 閿佸畾ID: {lockInfo.Id}, 鍥炲簱鏁伴噺: {returnQty}");
+                }
+
+                // 鍑忓皯璁㈠崟鏄庣粏鐨勫垎閰嶆暟閲�
+                if (totalReturnQtyForDetail > 0)
+                {
+                    await ReduceOrderDetailAllocation(orderDetail, totalReturnQtyForDetail);
+                }
+            }
+
+            _logger.LogInformation($"鏈垎鎷i攣瀹氳褰曞洖搴撳鐞嗗畬鎴� - 鍏卞鐞� {remainingLocks.Count} 鏉¤褰�");
+        }
+        /// <summary>
+        /// 澶勭悊鏈垎閰嶇殑搴撳瓨璐х墿鍥炲簱
+        /// 纭繚涓嶄細鍒涘缓鏂扮殑閿佸畾璁板綍
+        /// </summary>
+        private async Task HandleUnallocatedStockReturn(List<Dt_StockInfoDetail> stockGoods)
+        {
+            _logger.LogInformation($"寮�濮嬪鐞嗘湭鍒嗛厤搴撳瓨鍥炲簱 - 鍏� {stockGoods.Count} 涓揣鐗�");
+
+            foreach (var stockDetail in stockGoods)
+            {
+                if (stockDetail.StockQuantity <= 0)
+                {
+                    _logger.LogInformation($"璺宠繃闆跺簱瀛樿揣鐗� - 鏉$爜: {stockDetail.Barcode}");
+                    continue;
+                }
+
+                _logger.LogInformation($"澶勭悊鏈垎閰嶅簱瀛樺洖搴� - 鏉$爜: {stockDetail.Barcode}, 鏁伴噺: {stockDetail.StockQuantity}");
+
+                // 妫�鏌ユ槸鍚﹀凡缁忔湁瀵瑰簲鐨勯攣瀹氳褰�
+                var existingLock = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                    .Where(x => x.CurrentBarcode == stockDetail.Barcode &&
+                               x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�)
+                    .FirstAsync();
+
+                if (existingLock != null)
+                {
+                    _logger.LogWarning($"搴撳瓨鏉$爜 {stockDetail.Barcode} 宸叉湁閿佸畾璁板綍锛岃烦杩囩洿鎺ュ洖搴撳鐞�");
+                    continue;
+                }
+
+                // 璁板綍鎭㈠鍓嶇殑鐘舵��
+                var originalStatus = stockDetail.Status;
+
+                // 鐩存帴鎭㈠搴撳瓨鐘舵�佷负鍙敤鐘舵�侊紝涓嶅垱寤轰换浣曢攣瀹氳褰�
+                stockDetail.Status = (int)StockStatusEmun.鍏ュ簱瀹屾垚;
+
+                await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+
+                _logger.LogInformation($"鏈垎閰嶅簱瀛樺洖搴撳畬鎴� - 鏉$爜: {stockDetail.Barcode}, 鐘舵��: {originalStatus} -> {stockDetail.Status}");
+            }
+
+            _logger.LogInformation($"鏈垎閰嶅簱瀛樺洖搴撳鐞嗗畬鎴� - 鍏卞鐞� {stockGoods.Count} 涓揣鐗�");
+        }
+        /// <summary>
+        /// 鍑忓皯璁㈠崟鏄庣粏鐨勫垎閰嶆暟閲�
+        /// 纭繚鍒嗛厤鏁伴噺鐨勫噺灏戞槸鍑嗙‘鐨�
+        /// </summary>
+        private async Task ReduceOrderDetailAllocation(Dt_OutboundOrderDetail orderDetail, decimal reduceQty)
+        {
+            if (orderDetail == null)
+                return;
+
+            decimal originalAllocated = orderDetail.AllocatedQuantity;
+            decimal originalLock = orderDetail.LockQuantity;
+
+            // 楠岃瘉鍑忓皯鏁伴噺涓嶄細瀵艰嚧璐熸暟
+            if (orderDetail.AllocatedQuantity < reduceQty)
+            {
+                _logger.LogWarning($"鍒嗛厤鏁伴噺涓嶈冻锛岃皟鏁村噺灏戞暟閲� - 鍘熻鍒掑噺灏�: {reduceQty}, 瀹為檯鍙敤: {orderDetail.AllocatedQuantity}");
+                reduceQty = orderDetail.AllocatedQuantity;
+            }
+
+            // 鍑忓皯鍒嗛厤鏁伴噺鍜岄攣瀹氭暟閲�
+            orderDetail.AllocatedQuantity -= reduceQty;
+            orderDetail.LockQuantity -= reduceQty;
+
+            // 纭繚鏁伴噺涓嶄細涓鸿礋鏁�
+            if (orderDetail.AllocatedQuantity < 0)
+            {
+                _logger.LogWarning($"鍒嗛厤鏁伴噺鍑虹幇璐熸暟锛岄噸缃负0銆傚師鍊�: {orderDetail.AllocatedQuantity + reduceQty}, 鍑忓皯: {reduceQty}");
+                orderDetail.AllocatedQuantity = 0;
+            }
+
+            if (orderDetail.LockQuantity < 0)
+            {
+                _logger.LogWarning($"閿佸畾鏁伴噺鍑虹幇璐熸暟锛岄噸缃负0銆傚師鍊�: {orderDetail.LockQuantity + reduceQty}, 鍑忓皯: {reduceQty}");
+                orderDetail.LockQuantity = 0;
+            }
+
+            // 鏇存柊鎵规鍒嗛厤鐘舵��
+            await UpdateBatchAllocateStatus(orderDetail);
+
+            await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
+
+            _logger.LogInformation($"鍑忓皯璁㈠崟鏄庣粏鍒嗛厤 - OrderDetailId: {orderDetail.Id}, " +
+                                 $"鍒嗛厤鏁伴噺: {originalAllocated} -> {orderDetail.AllocatedQuantity}, " +
+                                 $"閿佸畾鏁伴噺: {originalLock} -> {orderDetail.LockQuantity}, " +
+                                 $"鍑忓皯鏁伴噺: {reduceQty}");
+
+            // 楠岃瘉鏁版嵁涓�鑷存��
+            await ValidateOrderDetailConsistency(orderDetail.Id);
+        }
+        /// <summary>
+        /// 楠岃瘉璁㈠崟鏄庣粏鏁版嵁涓�鑷存��
+        /// </summary>
+        private async Task ValidateOrderDetailConsistency(long orderDetailId)
+        {
+            var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
+                .FirstAsync(x => x.Id == orderDetailId);
+
+            if (orderDetail == null)
+                return;
+
+            // 璁$畻鎵�鏈夌浉鍏抽攣瀹氳褰曠殑鎬诲垎閰嶆暟閲�
+            var relatedLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                .Where(x => x.OrderDetailId == orderDetailId &&
+                           x.Status != (int)OutLockStockStatusEnum.宸插洖搴�)
+                .ToListAsync();
+
+            decimal totalLockAssignQty = relatedLocks.Sum(x => x.AssignQuantity);
+
+            // 楠岃瘉璁㈠崟鏄庣粏鍒嗛厤鏁伴噺涓庨攣瀹氳褰曟�诲垎閰嶆暟閲忕殑涓�鑷存��
+            if (Math.Abs(orderDetail.AllocatedQuantity - totalLockAssignQty) > 0.01m)
+            {
+                _logger.LogWarning($"鏁版嵁涓嶄竴鑷磋鍛� - OrderDetailId: {orderDetailId}, " +
+                                  $"璁㈠崟鏄庣粏鍒嗛厤鏁伴噺: {orderDetail.AllocatedQuantity}, " +
+                                  $"閿佸畾璁板綍鎬诲垎閰嶆暟閲�: {totalLockAssignQty}");
+            }
+            else
+            {
+                _logger.LogInformation($"鏁版嵁涓�鑷存�ч獙璇侀�氳繃 - OrderDetailId: {orderDetailId}");
+            }
+        }
+        /// <summary>
+        /// 鍒嗘壒鍥炲簱 - 璋冪敤缁熶竴鍥炲簱鏂规硶
+        /// </summary>
+        public async Task<WebResponseContent> BatchReturnStock(string orderNo, string palletCode)
+        {
+            return await ExecutePalletReturn(orderNo, palletCode, "鍒嗘壒鍥炲簱");
+        }
+
+        /// <summary>
+        /// 鍓╀綑鍥炲簱 - 璋冪敤缁熶竴鍥炲簱鏂规硶
+        /// </summary>
+        public async Task<WebResponseContent> ReturnRemaining(string orderNo, string palletCode, string reason)
+        {
+            return await ExecutePalletReturn(orderNo, palletCode, reason);
+        }
+
+        /// <summary>
+        /// 鍙栬蛋绌虹 - 鍏堟墽琛屽洖搴撳啀娓呯悊 - 澧炲己鐗堟湰
+        /// </summary>
+        public async Task<WebResponseContent> RemoveEmptyPallet(string orderNo, string palletCode)
+        {
+            try
+            {
+                _unitOfWorkManage.BeginTran();
+
+                _logger.LogInformation($"寮�濮嬪彇璧扮┖绠� - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}");
+
+                // 1. 楠岃瘉绌虹鍙栬蛋鏉′欢锛堝繀椤诲叏閮ㄥ畬鎴愭嫞閫夛級
+                var validationResult = await ValidateEmptyPalletRemoval(orderNo, palletCode);
+                if (!validationResult.IsValid)
+                {
+                    _unitOfWorkManage.RollbackTran();
+                    return WebResponseContent.Instance.Error(validationResult.ErrorMessage);
+                }
+
+                var completedLocks = validationResult.Data;
+
+                // 2. 娓呯悊宸插畬鎴愮殑閿佸畾璁板綍锛堟爣璁颁负宸插彇璧帮級
+                await CleanupCompletedLocks(completedLocks);
+
+                // 3. 娓呯悊瀵瑰簲鐨勫簱瀛樿褰曠姸鎬�
+                foreach (var lockInfo in completedLocks)
+                {
+                    await CleanupStockInfo(lockInfo);
+                }
+
+                // 4. 鏇存柊鐩稿叧璁㈠崟鐘舵��
+                await UpdateOrderStatusAfterPalletRemoval(orderNo);
+
+                // 5. 璁板綍鎿嶄綔鍘嗗彶
+                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}");
+            }
+        }
+        /// <summary>
+        /// 鏀堕泦闇�瑕佸洖搴撶殑鏉$爜
+        /// </summary>
+        private async Task<List<string>> CollectReturnBarcodes(PalletStatusAnalysis status)
+        {
+            var returnBarcodes = new HashSet<string>();
+
+            try
+            {
+                _logger.LogInformation($"寮�濮嬫敹闆嗗洖搴撴潯鐮� - 璁㈠崟: {status.OrderNo}, 鎵樼洏: {status.PalletCode}");
+
+                // 1. 鏀堕泦鏈垎鎷i攣瀹氳褰曠殑鏉$爜
+                if (status.HasRemainingLocks)
+                {
+                    foreach (var lockInfo in status.RemainingLocks)
+                    {
+                        if (!string.IsNullOrEmpty(lockInfo.CurrentBarcode))
+                        {
+                            returnBarcodes.Add(lockInfo.CurrentBarcode);
+                            _logger.LogInformation($"娣诲姞閿佸畾璁板綍鏉$爜: {lockInfo.CurrentBarcode}");
+                        }
+                    }
+                }
+
+                // 2. 鏀堕泦鎵樼洏涓婂簱瀛樿揣鐗╃殑鏉$爜
+                if (status.HasPalletStockGoods)
+                {
+                    foreach (var stockDetail in status.PalletStockGoods)
+                    {
+                        if (!string.IsNullOrEmpty(stockDetail.Barcode) && stockDetail.StockQuantity > 0)
+                        {
+                            returnBarcodes.Add(stockDetail.Barcode);
+                            _logger.LogInformation($"娣诲姞搴撳瓨璐х墿鏉$爜: {stockDetail.Barcode}, 鏁伴噺: {stockDetail.StockQuantity}");
+                        }
+                    }
+                }
+
+                // 3. 鏀堕泦鎷嗗寘璁板綍鐩稿叧鐨勬潯鐮�
+                if (status.HasSplitRecords)
+                {
+                    foreach (var splitRecord in status.SplitRecords)
+                    {
+                        // 娣诲姞鍘熸潯鐮�
+                        if (!string.IsNullOrEmpty(splitRecord.OriginalBarcode))
+                        {
+                            var originalStock = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                                .FirstAsync(x => x.Barcode == splitRecord.OriginalBarcode && x.StockId == status.StockId);
+
+                            if (originalStock != null && originalStock.StockQuantity > 0)
+                            {
+                                returnBarcodes.Add(splitRecord.OriginalBarcode);
+                                _logger.LogInformation($"娣诲姞鎷嗗寘鍘熸潯鐮�: {splitRecord.OriginalBarcode}, 鏁伴噺: {originalStock.StockQuantity}");
+                            }
+                        }
+
+                        // 娣诲姞鏂版潯鐮�
+                        if (!string.IsNullOrEmpty(splitRecord.NewBarcode))
+                        {
+                            var newStock = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                                .FirstAsync(x => x.Barcode == splitRecord.NewBarcode && x.StockId == status.StockId);
+
+                            if (newStock != null && newStock.StockQuantity > 0)
+                            {
+                                returnBarcodes.Add(splitRecord.NewBarcode);
+                                _logger.LogInformation($"娣诲姞鎷嗗寘鏂版潯鐮�: {splitRecord.NewBarcode}, 鏁伴噺: {newStock.StockQuantity}");
+                            }
+                        }
+                    }
+                }
+
+                _logger.LogInformation($"鍥炲簱鏉$爜鏀堕泦瀹屾垚 - 鍏� {returnBarcodes.Count} 涓潯鐮�: {string.Join(", ", returnBarcodes)}");
+
+                return returnBarcodes.ToList();
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"鏀堕泦鍥炲簱鏉$爜澶辫触 - Error: {ex.Message}");
+                return returnBarcodes.ToList();
             }
         }
         #endregion
+
+        #region 鍥炲簱鎿嶄綔鏍稿績鏂规硶
+
+        /// <summary>
+        /// 鎵ц鍥炲簱鎿嶄綔 - 澧炲己鐗堟湰
+        /// </summary>
+        private async Task ExecuteReturnOperations(string orderNo, string palletCode, Dt_StockInfo stockInfo,
+            Dt_Task task, PalletStatusAnalysis statusAnalysis)
+        {
+            _logger.LogInformation($"寮�濮嬫墽琛屽洖搴撴搷浣� - 璁㈠崟: {orderNo}, 鎵樼洏: {palletCode}");
+
+            //  澶勭悊鏈垎鎷g殑閿佸畾璁板綍
+            if (statusAnalysis.HasRemainingLocks)
+            {
+                _logger.LogInformation($"澶勭悊 {statusAnalysis.RemainingLocks.Count} 鏉℃湭鍒嗘嫞閿佸畾璁板綍");
+                await HandleRemainingLocksReturn(statusAnalysis.RemainingLocks);
+            }
+
+            //澶勭悊鎵樼洏涓婄殑搴撳瓨璐х墿
+            if (statusAnalysis.HasPalletStockGoods)
+            {
+                _logger.LogInformation($"澶勭悊 {statusAnalysis.PalletStockGoods.Count} 涓簱瀛樿揣鐗�");
+                await HandlePalletStockGoodsReturn(statusAnalysis.PalletStockGoods, stockInfo.Id);
+            }
+
+            //澶勭悊鎷嗗寘璁板綍
+            if (statusAnalysis.HasSplitRecords)
+            {
+                _logger.LogInformation($"澶勭悊 {statusAnalysis.SplitRecords.Count} 鏉℃媶鍖呰褰�");
+                await HandleSplitRecordsReturn(statusAnalysis.SplitRecords, stockInfo.Id);
+            }
+
+            _logger.LogInformation($"鍥炲簱鎿嶄綔瀹屾垚 - 鎬诲洖搴撴暟閲�: {statusAnalysis.TotalReturnQty}");
+        }
+
+        /// <summary>
+        /// 澶勭悊鏈垎鎷g殑閿佸畾璁板綍鍥炲簱
+        /// </summary>
+
+
+        /// <summary>
+        /// 澶勭悊鎵樼洏涓婄殑搴撳瓨璐х墿鍥炲簱
+        /// </summary>
+        private async Task HandlePalletStockGoodsReturn(List<Dt_StockInfoDetail> palletStockGoods, int stockId)
+        {
+            foreach (var stockDetail in palletStockGoods)
+            {
+                // 鍙鐞嗗嚭搴撻攣瀹氱姸鎬佺殑搴撳瓨
+                if (stockDetail.Status == (int)StockStatusEmun.鍑哄簱閿佸畾 && stockDetail.StockQuantity > 0)
+                {
+                    // 鎭㈠搴撳瓨鐘舵�佷负鍙敤鐘舵��
+                    stockDetail.Status = (int)StockStatusEmun.鍏ュ簱瀹屾垚;
+                    await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+
+                    _logger.LogInformation($"鎭㈠搴撳瓨璐х墿 - 鏉$爜: {stockDetail.Barcode}, 鏁伴噺: {stockDetail.StockQuantity}");
+                }
+            }
+        }
+
+        /// <summary>
+        /// 澶勭悊鎷嗗寘璁板綍鍥炲簱
+        /// </summary>
+        private async Task HandleSplitRecordsReturn(List<Dt_SplitPackageRecord> splitRecords, int stockId)
+        {
+            foreach (var splitRecord in splitRecords)
+            {
+                // 澶勭悊鏂版潯鐮�
+                var newLockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                    .Where(x => x.CurrentBarcode == splitRecord.NewBarcode &&
+                               x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�)
+                    .FirstAsync();
+
+                if (newLockInfo != null)
+                {
+                    await HandleSingleLockReturn(newLockInfo);
+                }
+
+                // 澶勭悊鍘熸潯鐮�
+                var originalLockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                    .Where(x => x.CurrentBarcode == splitRecord.OriginalBarcode &&
+                               x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�)
+                    .FirstAsync();
+
+                if (originalLockInfo != null)
+                {
+                    await HandleSingleLockReturn(originalLockInfo);
+                }
+
+                // 鏇存柊鎷嗗寘璁板綍鐘舵�佷负宸插洖搴�
+                splitRecord.Status = (int)SplitPackageStatusEnum.宸插洖搴�;
+                await _splitPackageService.Db.Updateable(splitRecord).ExecuteCommandAsync();
+            }
+        }
+
+        private async Task HandleSingleLockReturn(Dt_OutStockLockInfo lockInfo)
+        {
+            decimal returnQty = lockInfo.AssignQuantity - lockInfo.PickedQty;
+
+            if (returnQty <= 0)
+            {
+                _logger.LogInformation($"璺宠繃閿佸畾璁板綍 - 閿佸畾ID: {lockInfo.Id}, 宸叉嫞閫夊畬鎴愭垨鏃犻渶鍥炲簱");
+                return;
+            }
+
+            _logger.LogInformation($"澶勭悊鎷嗗寘鐩稿叧閿佸畾璁板綍 - 閿佸畾ID: {lockInfo.Id}, 鏉$爜: {lockInfo.CurrentBarcode}, 鍥炲簱鏁伴噺: {returnQty}");
+
+            // 鎭㈠搴撳瓨
+            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;
+
+                stockDetail.StockQuantity += returnQty;
+                stockDetail.OutboundQuantity -= returnQty;
+
+                if (stockDetail.OutboundQuantity < 0)
+                {
+                    stockDetail.OutboundQuantity = 0;
+                }
+
+                stockDetail.Status = (int)StockStatusEmun.鍏ュ簱瀹屾垚;
+                await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
+
+                _logger.LogInformation($"鎭㈠鎷嗗寘鐩稿叧搴撳瓨 - 鏉$爜: {stockDetail.Barcode}, " +
+                                     $"搴撳瓨鏁伴噺: {originalStockQty} -> {stockDetail.StockQuantity}");
+            }
+
+            // 鏇存柊閿佸畾鐘舵��
+            lockInfo.Status = (int)OutLockStockStatusEnum.宸插洖搴�;
+            lockInfo.Operator = App.User.UserName;
+            await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
+
+            // 鍑忓皯璁㈠崟鏄庣粏鐨勫垎閰嶆暟閲�
+            if (lockInfo.OrderDetailId > 0)
+            {
+                var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
+                    .FirstAsync(x => x.Id == lockInfo.OrderDetailId);
+
+                if (orderDetail != null)
+                {
+                    await ReduceOrderDetailAllocation(orderDetail, returnQty);
+                }
+            }
+
+            _logger.LogInformation($"鎷嗗寘鐩稿叧閿佸畾璁板綍鍥炲簱瀹屾垚 - 閿佸畾ID: {lockInfo.Id}, 鍥炲簱鏁伴噺: {returnQty}");
+        }
+        /// <summary>
+        /// 閲婃斁鎵�鏈夐攣瀹氫互渚块噸鏂板垎閰�
+        /// </summary>
+        private async Task ReleaseAllLocksForReallocation(string orderNo, string palletCode, PalletStatusAnalysis statusAnalysis)
+        {
+            // 鏇存柊璁㈠崟鏄庣粏鐨勫凡鍒嗛厤鏁伴噺
+            if (statusAnalysis.HasRemainingLocks)
+            {
+                var orderDetailGroups = statusAnalysis.RemainingLocks.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;
+                        orderDetail.LockQuantity = orderDetail.AllocatedQuantity;
+
+                        await UpdateBatchAllocateStatus(orderDetail);
+                        await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
+
+                        _logger.LogInformation($"鏇存柊璁㈠崟鏄庣粏 - OrderDetailId: {orderDetailId}, 鍑忓皯鍒嗛厤鏁伴噺: {returnedQty}");
+                    }
+                }
+            }
+        }
+
+        #endregion
+
+        #region 杈呭姪鏂规硶
+
+        /// <summary>
+        /// 澶勭悊娌℃湁鍥炲簱鐗╁搧鐨勬儏鍐�
+        /// </summary>
+        private async Task<WebResponseContent> HandleNoReturnItems(string orderNo, string palletCode, Dt_Task originalTask, int stockId)
+        {
+            _logger.LogInformation($"鎵樼洏 {palletCode} 娌℃湁闇�瑕佸洖搴撶殑鐗╁搧");
+
+            // 妫�鏌ユ槸鍚︽槸绌烘墭鐩�
+            var statusAnalysis = await AnalyzePalletStatus(orderNo, palletCode, stockId);
+            if (statusAnalysis.IsEmptyPallet)
+            {
+                try
+                {
+                    var locationtype = 0;
+                    var stockInfo = await _stockInfoService.Db.Queryable<Dt_StockInfo>()
+                            .Where(x => x.PalletCode == palletCode)
+                            .FirstAsync();
+
+                    if (stockInfo == null)
+                    {
+                        var firstLocation = await _locationInfoService.Db.Queryable<Dt_LocationInfo>().FirstAsync(x => x.LocationCode == originalTask.SourceAddress);
+                        locationtype = firstLocation?.LocationType ?? 1;
+                    }
+                    else
+                    {
+                        locationtype = stockInfo.LocationType;
+                        _stockInfoService.DeleteData(stockInfo);
+                    }
+
+                    var targetAddress = originalTask.TargetAddress;
+
+                    await CleanupZeroStockData(stockId);
+
+
+                    var emptystockInfo = new Dt_StockInfo() { PalletType = PalletTypeEnum.Empty.ObjToInt(), StockStatus = StockStatusEmun.缁勭洏鏆傚瓨.ObjToInt(), PalletCode = palletCode, LocationType = locationtype };
+                    emptystockInfo.Details = new List<Dt_StockInfoDetail>();
+                    _stockInfoService.AddMaterielGroup(emptystockInfo);
+                    //绌烘墭鐩樺浣曞鐞�  杩樻湁涓�涓嚭搴撲换鍔¤澶勭悊銆�
+                    originalTask.PalletType = PalletTypeEnum.Empty.ObjToInt();
+
+                    await CreateReturnTaskAndHandleESS(orderNo, palletCode, originalTask, TaskTypeEnum.InEmpty, PalletTypeEnum.Empty.ObjToInt());
+
+                }
+                catch (Exception ex)
+                {
+                    _logger.LogError($" HandleNoReturnItems  澶辫触: {ex.Message}");
+                    return WebResponseContent.Instance.Error($" 鍥炲簱绌烘墭鐩樺け璐ワ紒");
+                }
+                return WebResponseContent.Instance.OK("绌烘墭鐩樺洖搴撲换鍔″垱寤烘垚鍔�");
+            }
+            else
+            {
+                return WebResponseContent.Instance.Error("鎵樼洏鐘舵�佸紓甯革細鏈夌墿鍝佷絾鏃犳硶璁$畻鍥炲簱鏁伴噺");
+            }
+        }
+        private async Task CleanupZeroStockData(int stockId)
+        {
+            try
+            {
+                // 1. 鍒犻櫎搴撳瓨鏁伴噺涓�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}");
+                // 娉ㄦ剰锛氭竻鐞嗗け璐ヤ笉搴旇褰卞搷涓绘祦绋�
+            }
+        }
+        /// <summary>
+        /// 鏇存柊璁㈠崟鐘舵�侊紙鍥炲簱鍚庯級
+        /// </summary>
+        private async Task UpdateOrderStatusForReturn(string orderNo)
+        {
+            // 妫�鏌ヨ鍗曟槸鍚︽墍鏈夋墭鐩橀兘宸插畬鎴愭垨宸插洖搴�
+            var allLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                .Where(x => x.OrderNo == orderNo)
+                .ToListAsync();
+
+            var activeLocks = allLocks.Where(x =>
+                x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓� ||
+                x.Status == (int)OutLockStockStatusEnum.鍥炲簱涓�).ToList();
+
+            // 濡傛灉娌℃湁娲昏穬鐨勯攣瀹氳褰曪紝鏇存柊璁㈠崟鐘舵��
+            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}");
+            }
+        }
+
+        #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 +2851,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,132 +2866,130 @@
             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;
+            }
+            // 妫�鏌ユ槸鍚﹂渶瑕佽嚜鍔ㄦ媶鍖呯殑鏉′欢锛�
+            // 1. 搴撳瓨鏁伴噺澶т簬鍒嗛厤鏁伴噺
+            // 2. 閿佸畾淇℃伅鐘舵�佷负鍑哄簱涓�
+            // 3. 鏈嫞閫夋暟閲忕瓑浜庡垎閰嶆暟閲忥紙琛ㄧず杩樻湭寮�濮嬫嫞閫夛級
+            bool needAutoSplit = stockDetail.StockQuantity > lockInfo.AssignQuantity &&
+                                lockInfo.Status == (int)OutLockStockStatusEnum.鍑哄簱涓� &&
+                                lockInfo.PickedQty == 0;
 
-            if (lockInfo == null)
-                return ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error("鏈壘鍒版湁鏁堢殑閿佸畾淇℃伅");
+            if (!needAutoSplit)
+                return null;
 
-            var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
-                .FirstAsync(x => x.Barcode == originalBarcode && x.StockId == lockInfo.StockId);
+            // 璁$畻鎷嗗寘鏁伴噺 = 搴撳瓨鏁伴噺 - 鍒嗛厤鏁伴噺
+            decimal splitQuantity = stockDetail.StockQuantity - lockInfo.AssignQuantity;
 
-            if (stockDetail.StockQuantity < splitQuantity)
-                return ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error("鎷嗗寘鏁伴噺涓嶈兘澶т簬搴撳瓨鏁伴噺");
+            // 鎵ц鑷姩鎷嗗寘
+            var splitResult = await ExecuteAutoSplitLogic(lockInfo, stockDetail, splitQuantity, palletCode);
 
-            if (lockInfo.AssignQuantity - lockInfo.PickedQty < splitQuantity)
-                return ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Error("鎷嗗寘鏁伴噺涓嶈兘澶т簬鏈嫞閫夋暟閲�");
-
-            return ValidationResult<(Dt_OutStockLockInfo, Dt_StockInfoDetail)>.Success((lockInfo, stockDetail));
+            return splitResult;
         }
- 
-        #endregion
-
-        #region 鏍稿績閫昏緫鏂规硶
-
-        private async Task<PickingResult> ExecutePickingLogic(
-            Dt_OutStockLockInfo lockInfo, Dt_OutboundOrderDetail orderDetail,
-            Dt_StockInfoDetail stockDetail, decimal actualPickedQty)
-        {
-            // 鏇存柊閿佸畾淇℃伅
-            lockInfo.PickedQty += actualPickedQty;
-            if (lockInfo.PickedQty >= lockInfo.AssignQuantity)
-            {
-                lockInfo.Status = (int)OutLockStockStatusEnum.鎷i�夊畬鎴�;
-            }
-            await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
-
-            // 鏇存柊搴撳瓨
-            stockDetail.StockQuantity -= actualPickedQty;
-            stockDetail.OutboundQuantity += actualPickedQty;
-
-            if (stockDetail.StockQuantity <= 0)
-            {
-                stockDetail.Status = (int)StockStatusEmun.鍑哄簱瀹屾垚;
-            }
-            await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
-
-            return new PickingResult
-            {
-                FinalLockInfo = lockInfo,
-                ActualPickedQty = actualPickedQty
-            };
-        }
-
-        private async Task<RevertPickingResult> RevertPickingData(Dt_PickingRecord pickingRecord)
-        {
-            // 鎭㈠閿佸畾淇℃伅
-            var lockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                .FirstAsync(x => x.Id == pickingRecord.OutStockLockId);
-
-            lockInfo.PickedQty -= pickingRecord.PickQuantity;
-
-            // 鏍规嵁鎷i�夋暟閲忓垽鏂姸鎬�
-            if (lockInfo.PickedQty <= 0)
-            {
-                lockInfo.Status = (int)OutLockStockStatusEnum.鍑哄簱涓�;
-            }
-            else if (lockInfo.PickedQty < lockInfo.AssignQuantity)
-            {
-                lockInfo.Status = (int)OutLockStockStatusEnum.鍑哄簱涓�;
-            }
-
-            await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
-
-            // 鎭㈠搴撳瓨
-            var stockDetail = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
-                .FirstAsync(x => x.Barcode == pickingRecord.Barcode);
-
-            stockDetail.StockQuantity += pickingRecord.PickQuantity;
-            stockDetail.OutboundQuantity -= pickingRecord.PickQuantity;
-
-            // 鎭㈠搴撳瓨鐘舵��
-            if (stockDetail.StockQuantity > 0)
-            {
-                stockDetail.Status = (int)StockStatusEmun.鍑哄簱閿佸畾;
-            }
-
-            await _stockInfoDetailService.Db.Updateable(stockDetail).ExecuteCommandAsync();
-
-            return new RevertPickingResult
-            {
-                LockInfo = lockInfo,
-                StockDetail = stockDetail
-            };
-        }
-        private async Task<SplitResultDto> ExecuteSplitLogic(Dt_OutStockLockInfo lockInfo, Dt_StockInfoDetail stockDetail,
+        /// <summary>
+        /// 鎵ц鑷姩鎷嗗寘閫昏緫
+        /// 纭繚鑷姩鎷嗗寘涓嶄細褰卞搷鍥炲簱閫昏緫
+        /// </summary>
+        private async Task<List<SplitResult>> ExecuteAutoSplitLogic(Dt_OutStockLockInfo lockInfo, Dt_StockInfoDetail stockDetail,
      decimal splitQuantity, string palletCode)
         {
+            _logger.LogInformation($"寮�濮嬫墽琛岃嚜鍔ㄦ媶鍖呴�昏緫 - 鍘熸潯鐮�: {stockDetail.Barcode}, 鎷嗗寘鏁伴噺: {splitQuantity}");
+
+            // 楠岃瘉鎷嗗寘鏁伴噺鍚堢悊鎬�
+            if (splitQuantity <= 0)
+            {
+                throw new InvalidOperationException($"鎷嗗寘鏁伴噺蹇呴』澶т簬0锛屽綋鍓嶅��: {splitQuantity}");
+            }
+
+            if (stockDetail.StockQuantity < lockInfo.AssignQuantity + splitQuantity)
+            {
+                throw new InvalidOperationException($"搴撳瓨鏁伴噺涓嶈冻浠ヨ繘琛岃嚜鍔ㄦ媶鍖�");
+            }
+
             // 鐢熸垚鏂版潯鐮�
             string newBarcode = await GenerateNewBarcode();
 
-            // 鍒涘缓鏂板簱瀛樻槑缁�
+            // 璁板綍鎷嗗寘鍓嶇殑鍒嗛厤鏁伴噺
+            decimal originalAssignQty = lockInfo.AssignQuantity;
+            decimal remainQty = originalAssignQty; // 鍘熼攣瀹氫俊鎭垎閰嶆暟閲忎繚鎸佷笉鍙�
+
+            // 鍒涘缓鏂板簱瀛樻槑缁嗭紙澶氫綑閮ㄥ垎锛�
             var newStockDetail = new Dt_StockInfoDetail
             {
                 StockId = stockDetail.StockId,
                 MaterielCode = stockDetail.MaterielCode,
                 OrderNo = stockDetail.OrderNo,
-                BatchNo = stockDetail.BatchNo, // 鐗╂枡鎵规
+                BatchNo = stockDetail.BatchNo,
                 StockQuantity = splitQuantity,
                 OutboundQuantity = 0,
                 Barcode = newBarcode,
@@ -1118,17 +3002,14 @@
                 InboundOrderRowNo = stockDetail.InboundOrderRowNo,
             };
             await _stockInfoDetailService.Db.Insertable(newStockDetail).ExecuteCommandAsync();
+            _logger.LogInformation($"鍒涘缓鏂板簱瀛樻槑缁� - 鏉$爜: {newBarcode}, 搴撳瓨鏁伴噺: {splitQuantity}");
 
-            // 鏇存柊鍘熷簱瀛樻槑缁�
-            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
+                OrderDetailId = 0, // 閲嶈锛氫笉缁戝畾鍒板叿浣撹鍗曟槑缁�
+                OutboundBatchNo = lockInfo.OutboundBatchNo,
                 MaterielCode = lockInfo.MaterielCode,
                 MaterielName = lockInfo.MaterielName,
                 StockId = lockInfo.StockId,
@@ -1151,52 +3032,223 @@
                 WarehouseCode = lockInfo.WarehouseCode,
                 BarcodeQty = lockInfo.BarcodeQty,
                 BarcodeUnit = lockInfo.BarcodeUnit,
+                IsUnallocated = 1 // 鏍囪涓烘湭鍒嗛厤
             };
 
             await _outStockLockInfoService.Db.Insertable(newLockInfo).ExecuteCommandAsync();
+            _logger.LogInformation($"鍒涘缓鏂伴攣瀹氫俊鎭� - 鏉$爜: {newBarcode}, 鍒嗛厤鏁伴噺: {splitQuantity}, 鏍囪涓烘湭鍒嗛厤");
 
-            // 鏇存柊鍘熼攣瀹氫俊鎭�
-            lockInfo.AssignQuantity -= splitQuantity;
-            lockInfo.OrderQuantity -= splitQuantity;
-            await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
+            // 鑷姩鎷嗗寘涓嶆敼鍙樿鍗曟槑缁嗙殑鍒嗛厤鏁伴噺
+            _logger.LogInformation($"鑷姩鎷嗗寘 - 璁㈠崟鏄庣粏鍒嗛厤鏁伴噺淇濇寔涓嶅彉");
 
             // 璁板綍鎷嗗寘鍘嗗彶
-            await RecordSplitHistory(lockInfo, stockDetail, splitQuantity, newBarcode);
+            await RecordSplitHistory(lockInfo, stockDetail, splitQuantity, newBarcode, true, stockDetail.StockQuantity);
 
-            return new SplitResultDto { NewBarcode = newBarcode };
+            // 鍒涘缓鎷嗗寘缁撴灉鍒楄〃
+            var splitResults = CreateSplitResults(lockInfo, splitQuantity, remainQty, newBarcode, stockDetail.Barcode);
+
+            _logger.LogInformation($"鑷姩鎷嗗寘閫昏緫鎵ц瀹屾垚");
+
+            return splitResults;
         }
-        private async Task ExecuteCancelSplitLogic(Dt_SplitPackageRecord splitRecord, Dt_OutStockLockInfo newLockInfo, Dt_StockInfoDetail newStockDetail)
+
+        /// <summary>
+        /// 楠岃瘉鑷姩鎷嗗寘鍚庢暟鎹竴鑷存��
+        /// </summary>
+        private async Task ValidateDataConsistencyAfterAutoSplit(long orderDetailId, decimal originalAllocatedQty, decimal originalLockQty, decimal splitQuantity)
         {
-            // 鎭㈠鍘熷簱瀛�
-            var originalStock = await _stockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
-                .FirstAsync(x => x.Barcode == splitRecord.OriginalBarcode && x.StockId == splitRecord.StockId);
+            // 閲嶆柊鑾峰彇璁㈠崟鏄庣粏鏁版嵁
+            var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
+                .FirstAsync(x => x.Id == orderDetailId);
 
-            originalStock.StockQuantity += splitRecord.SplitQty;
-            await _stockInfoDetailService.Db.Updateable(originalStock).ExecuteCommandAsync();
+            if (orderDetail == null)
+                return;
 
-            // 鎭㈠鍘熼攣瀹氫俊鎭�
-            var originalLockInfo = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                .FirstAsync(x => x.Id == splitRecord.OutStockLockInfoId);
+            // 璁$畻鎵�鏈夐攣瀹氫俊鎭殑鎬诲垎閰嶆暟閲�
+            var allLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                .Where(x => x.OrderDetailId == orderDetailId)
+                .ToListAsync();
 
-            originalLockInfo.AssignQuantity += splitRecord.SplitQty;
-            originalLockInfo.OrderQuantity += splitRecord.SplitQty;
-            await _outStockLockInfoService.Db.Updateable(originalLockInfo).ExecuteCommandAsync();
+            decimal totalLockAssignQty = allLocks.Sum(x => x.AssignQuantity);
 
-            // 鍒犻櫎鏂板簱瀛樻槑缁�
-            await _stockInfoDetailService.Db.Deleteable<Dt_StockInfoDetail>()
-                .Where(x => x.Barcode == newLockInfo.CurrentBarcode)
-                .ExecuteCommandAsync();
+            _logger.LogInformation($"鑷姩鎷嗗寘鍚庢暟鎹竴鑷存�ч獙璇� - 璁㈠崟鏄庣粏鍒嗛厤鏁伴噺: {orderDetail.AllocatedQuantity}, 閿佸畾淇℃伅鎬诲垎閰嶆暟閲�: {totalLockAssignQty}");
 
-            // 鍒犻櫎鏂伴攣瀹氫俊鎭�
-            await _outStockLockInfoService.Db.Deleteable<Dt_OutStockLockInfo>()
-                .Where(x => x.Id == newLockInfo.Id)
-                .ExecuteCommandAsync();
+            // 楠岃瘉鑷姩鎷嗗寘鍚庣殑鏁版嵁涓�鑷存��
+            decimal expectedAllocatedQty = originalAllocatedQty + splitQuantity;
+            decimal expectedLockQty = originalLockQty + splitQuantity;
 
-            // 鏍囪鎷嗗寘璁板綍涓哄凡鎾ら攢
-            splitRecord.IsReverted = true;
-            splitRecord.RevertTime = DateTime.Now;
-            splitRecord.RevertOperator = App.User.UserName;
-            await _splitPackageService.Db.Updateable(splitRecord).ExecuteCommandAsync();
+            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}");
+            }
+        }
+        #endregion
+
+        #region 鏍稿績閫昏緫鏂规硶
+
+        private async Task<PickingResult> ExecutePickingLogic(
+            Dt_OutStockLockInfo lockInfo, Dt_OutboundOrderDetail orderDetail,
+            Dt_StockInfoDetail stockDetail, decimal actualPickedQty)
+        {
+            _logger.LogInformation($"寮�濮嬫墽琛屽垎鎷i�昏緫 - 鏉$爜: {stockDetail.Barcode}, 鍒嗛厤鏁伴噺: {lockInfo.AssignQuantity}, 瀹為檯鎷i��: {actualPickedQty}");
+
+            // 鍐嶆楠岃瘉璁㈠崟鏄庣粏鐨勫垎閰嶆暟閲忥紙闃叉骞跺彂鎿嶄綔锛�
+            if (orderDetail.AllocatedQuantity < actualPickedQty)
+            {
+                throw new InvalidOperationException($"璁㈠崟鏄庣粏鍒嗛厤鏁伴噺涓嶈冻锛岄渶瑕佹嫞閫� {actualPickedQty}锛屽彲鐢ㄥ垎閰嶆暟閲� {orderDetail.AllocatedQuantity}");
+            }
+
+            if (orderDetail.LockQuantity < actualPickedQty)
+            {
+                throw new InvalidOperationException($"璁㈠崟鏄庣粏閿佸畾鏁伴噺涓嶈冻锛岄渶瑕佹嫞閫� {actualPickedQty}锛屽彲鐢ㄩ攣瀹氭暟閲� {orderDetail.LockQuantity}");
+            }
+
+            // 鏇存柊閿佸畾淇℃伅
+            lockInfo.PickedQty += actualPickedQty;
+            _logger.LogInformation($"鏇存柊閿佸畾淇℃伅 - 宸叉嫞閫夋暟閲忎粠 {lockInfo.PickedQty - actualPickedQty} 澧炲姞鍒� {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();
+
+            // 鏇存柊搴撳瓨淇℃伅
+            decimal originalStockQty = stockDetail.StockQuantity;
+            decimal originalOutboundQty = stockDetail.OutboundQuantity;
+
+            stockDetail.StockQuantity -= actualPickedQty;
+            stockDetail.OutboundQuantity += actualPickedQty;
+
+            _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();
+
+            _logger.LogInformation($"鍒嗘嫞閫昏緫鎵ц瀹屾垚 - 鏉$爜: {stockDetail.Barcode}");
+
+            return new PickingResult
+            {
+                FinalLockInfo = lockInfo,
+                ActualPickedQty = actualPickedQty
+            };
+        }
+
+        private async Task<RevertPickingResult> RevertPickingData(Dt_PickingRecord pickingRecord)
+        {
+            _logger.LogInformation($"寮�濮嬫仮澶嶆嫞閫夋暟鎹� - 鎷i�夎褰旾D: {pickingRecord.Id}, 鏉$爜: {pickingRecord.Barcode}, 鎷i�夋暟閲�: {pickingRecord.PickQuantity}");
+
+            // 1. 鎭㈠閿佸畾淇℃伅
+            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;
+
+            // 纭繚宸叉嫞閫夋暟閲忎笉浼氫负璐熸暟
+            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.鍑哄簱涓�; // 閮ㄥ垎鎷i�夌姸鎬�
+                _logger.LogInformation($"閿佸畾淇℃伅鐘舵�佹仮澶嶄负鍑哄簱涓紙閮ㄥ垎鎷i�夛級");
+            }
+
+            await _outStockLockInfoService.Db.Updateable(lockInfo).ExecuteCommandAsync();
+
+            // 2. 鎭㈠搴撳瓨淇℃伅
+            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
+            {
+                LockInfo = lockInfo,
+                StockDetail = stockDetail
+            };
         }
 
         #endregion
@@ -1205,56 +3257,144 @@
 
         private async Task UpdateBatchAndOrderData(Dt_OutboundBatch batch, Dt_OutboundOrderDetail orderDetail, decimal pickedQty, string orderNo)
         {
-            // 鏇存柊鎵规瀹屾垚鏁伴噺
+            _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;
+            // 楠岃瘉鍒嗛厤鏁伴噺涓嶄細鍙樻垚璐熸暟
+            if (orderDetail.AllocatedQuantity < pickedQty)
+            {
+                decimal actualPickedQty = orderDetail.AllocatedQuantity;
+                _logger.LogWarning($"鍒嗛厤鏁伴噺涓嶈冻锛岃皟鏁存嫞閫夋暟閲� - 鍘熼渶瑕�: {pickedQty}, 瀹為檯鍙敤: {actualPickedQty}");
+                pickedQty = actualPickedQty;
+            }
+
+            if (orderDetail.LockQuantity < pickedQty)
+            {
+                decimal actualPickedQty = orderDetail.LockQuantity;
+                _logger.LogWarning($"閿佸畾鏁伴噺涓嶈冻锛岃皟鏁存嫞閫夋暟閲� - 鍘熼渶瑕�: {pickedQty}, 瀹為檯鍙敤: {actualPickedQty}");
+                pickedQty = actualPickedQty;
+            }
+
+            // 1. 鏇存柊鎵规瀹屾垚鏁伴噺
+            decimal originalBatchCompletedQty = batch.CompletedQuantity;
             batch.CompletedQuantity += pickedQty;
+
+            _logger.LogInformation($"鏇存柊鎵规瀹屾垚鏁伴噺 - 浠� {originalBatchCompletedQty} 澧炲姞鍒� {batch.CompletedQuantity}");
+
             if (batch.CompletedQuantity >= batch.BatchQuantity)
             {
                 batch.BatchStatus = (int)BatchStatusEnum.宸插畬鎴�;
+                _logger.LogInformation($"鎵规鐘舵�佹洿鏂颁负宸插畬鎴�");
             }
             await _outboundBatchRepository.Db.Updateable(batch).ExecuteCommandAsync();
 
             // 鏇存柊璁㈠崟鏄庣粏
+            decimal originalOverOutQty = orderDetail.OverOutQuantity;
+            decimal originalAllocatedQty = orderDetail.AllocatedQuantity;
+            decimal originalLockQty = orderDetail.LockQuantity;
+
             orderDetail.OverOutQuantity += pickedQty;
             orderDetail.AllocatedQuantity -= pickedQty;
+            // LockQuantity 鍚屾鍑忓皯
+            orderDetail.LockQuantity = orderDetail.AllocatedQuantity;
+            if (orderDetail.AllocatedQuantity < 0) orderDetail.AllocatedQuantity = 0;
+            if (orderDetail.LockQuantity < 0) orderDetail.LockQuantity = 0;
+            _logger.LogInformation($"鏇存柊璁㈠崟鏄庣粏 - 宸插嚭搴撴暟閲忎粠 {originalOverOutQty} 澧炲姞鍒� {orderDetail.OverOutQuantity}");
+            _logger.LogInformation($"鏇存柊璁㈠崟鏄庣粏 - 宸插垎閰嶆暟閲忎粠 {originalAllocatedQty} 鍑忓皯鍒� {orderDetail.AllocatedQuantity}");
+            _logger.LogInformation($"鏇存柊璁㈠崟鏄庣粏 - 閿佸畾鏁伴噺浠� {originalLockQty} 鍑忓皯鍒� {orderDetail.LockQuantity}");
+
             await _outboundOrderDetailService.Db.Updateable(orderDetail).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();
+            }
+
+            // 3. 閲嶆柊妫�鏌ヨ鍗曠姸鎬�
             await CheckAndUpdateOrderStatus(pickingRecord.OrderNo);
+
+            _logger.LogInformation($"鎭㈠鎵规鍜岃鍗曟暟鎹畬鎴�");
+        }
+
+        private async Task UpdateBatchAllocateStatus(Dt_OutboundOrderDetail orderDetail)
+        {
+            if (orderDetail.AllocatedQuantity >= orderDetail.NeedOutQuantity)
+            {
+                orderDetail.BatchAllocateStatus = OrderDetailStatusEnum.AssignOver.ObjToInt();
+            }
+            else if (orderDetail.AllocatedQuantity > 0)
+            {
+                orderDetail.BatchAllocateStatus = OrderDetailStatusEnum.AssignOverPartial.ObjToInt();
+            }
+            else
+            {
+                orderDetail.BatchAllocateStatus = OrderDetailStatusEnum.New.ObjToInt();
+            }
         }
         private async Task ReleaseLockAndStock(Dt_OutStockLockInfo lockInfo)
         {
@@ -1326,11 +3466,120 @@
                 if (orderDetail != null)
                 {
                     orderDetail.AllocatedQuantity -= returnedQty;
+                    // LockQuantity 鍚屾鍑忓皯锛屼繚鎸佷笌宸插垎閰嶆暟閲忎竴鑷�
+                    orderDetail.LockQuantity = orderDetail.AllocatedQuantity;
+
+                    await UpdateBatchAllocateStatus(orderDetail);
+
                     await _outboundOrderDetailService.Db.Updateable(orderDetail).ExecuteCommandAsync();
                 }
             }
         }
         #endregion
+
+        private async Task CreateReturnTaskAndHandleESS(string orderNo, string palletCode, Dt_Task originalTask, TaskTypeEnum taskTypeEnum, int palletType)
+        {
+            var firstLocation = await _locationInfoService.Db.Queryable<Dt_LocationInfo>()
+                .FirstAsync(x => x.LocationCode == originalTask.SourceAddress);
+
+            // 鍒嗛厤鏂拌揣浣�
+            var newLocation = _locationInfoService.AssignLocation(firstLocation.LocationType);
+
+            Dt_Task returnTask = new()
+            {
+                CurrentAddress = stations[originalTask.TargetAddress],
+                Grade = 0,
+                PalletCode = palletCode,
+                NextAddress = "",
+                // OrderNo = originalTask.OrderNo,
+                OrderNo = orderNo,
+                Roadway = newLocation.RoadwayNo,
+                SourceAddress = stations[originalTask.TargetAddress],
+                TargetAddress = newLocation.LocationCode,
+                TaskStatus = TaskStatusEnum.New.ObjToInt(),
+                TaskType = taskTypeEnum.ObjToInt(),
+                PalletType = palletType,
+                WarehouseId = originalTask.WarehouseId
+
+            };
+            // 淇濆瓨鍥炲簱浠诲姟
+            var insertcount = await _taskRepository.Db.Insertable(returnTask).ExecuteCommandAsync();
+            if (insertcount <= 0)
+            {
+                throw new Exception("鍒涘缓浠诲姟澶辫触锛�");
+            }
+            var targetAddress = originalTask.TargetAddress;
+
+            _logger.LogInformation($"CreateReturnTaskAndHandleESS  鍒嗘壒鍒犻櫎鍘嗗彶浠诲姟: {orderNo} 锛� {originalTask.TaskNum}");
+            // 鍒犻櫎鍘熷鍑哄簱浠诲姟
+            //_taskRepository.DeleteAndMoveIntoHty(originalTask, OperateTypeEnum.鑷姩瀹屾垚);
+           var result= _task_HtyService.DeleteAndMoveIntoHty(originalTask, OperateTypeEnum.浜哄伐鍒犻櫎);
+            await _taskRepository.Db.Deleteable(originalTask).ExecuteCommandAsync();
+
+            if (!result)
+            {
+                await _taskRepository.Db.Deleteable(originalTask).ExecuteCommandAsync();
+            }
+            _logger.LogInformation($"CreateReturnTaskAndHandleESS  鍒嗘壒鍒犻櫎鍘嗗彶浠诲姟: {orderNo} 锛� {originalTask.TaskNum},褰卞搷琛�  {result}");
+
+
+            // 缁� ESS 鍙戦�佹祦鍔ㄤ俊鍙峰拰鍒涘缓浠诲姟
+            await SendESSCommands(palletCode, targetAddress, returnTask);
+        }
+        /// <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
+            {
+                // 1. 鍙戦�佹祦鍔ㄤ俊鍙�
+                var moveResult = await _eSSApiService.MoveContainerAsync(new WIDESEA_DTO.Basic.MoveContainerRequest
+                {
+                    slotCode = movestations[targetAddress],
+                    containerCode = palletCode
+                });
+
+                //if (moveResult)
+                //{
+                // 2. 鍒涘缓鍥炲簱浠诲姟
+                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,7 +3589,7 @@
             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
             {
@@ -1352,7 +3601,12 @@
                 NewBarcode = newBarcode,
                 SplitQty = splitQty,
                 SplitTime = DateTime.Now,
-                Status = (int)SplitPackageStatusEnum.宸叉媶鍖�
+                Status = (int)SplitPackageStatusEnum.宸叉媶鍖�,
+                IsAutoSplit = isAutoSplit,
+                // SplitType = isAutoSplit ? "鑷姩鎷嗗寘" : "鎵嬪姩鎷嗗寘"
+                OriginalStockQuantity = originalStockQuantity ?? stockDetail.StockQuantity,
+                //RemainingStockQuantity = stockDetail.StockQuantity - splitQty
+                TaskNum = lockInfo.TaskNum
             };
 
             await _splitPackageService.Db.Insertable(splitHistory).ExecuteCommandAsync();
@@ -1414,9 +3668,44 @@
             };
         }
         #endregion
- 
+
 
         #region DTO绫�
+        /// <summary>
+        /// 鏉$爜鐘舵�佷俊鎭疍TO
+        /// </summary>
+        public class BarcodeStatusInfoDto
+        {
+            public string Barcode { get; set; }
+            public string OrderNo { get; set; }
+            public bool IsOriginalBarcode { get; set; }
+            public int SplitChainCount { get; set; }
+            public bool HasBeenPicked { get; set; }
+            public decimal TotalPickedQuantity { get; set; }
+            public int PickRecordCount { get; set; }
+            public int LockInfoStatus { get; set; }
+            public decimal LockInfoPickedQty { get; set; }
+            public decimal LockInfoAssignQty { get; set; }
+            public decimal StockQuantity { get; set; }
+            public int StockStatus { get; set; }
+            public bool CanCancelSplit { get; set; }
+            public bool NeedCancelPickFirst { get; set; }
+            public List<string> OperationSuggestions { get; set; } = new List<string>();
+        }
+        public class PickedBarcodeInfo
+        {
+            public string Barcode { get; set; }
+            public decimal PickedQty { get; set; }
+            public int PickRecordCount { get; set; }
+        }
+        /// <summary>
+        /// 鑷姩鎷嗗寘缁撴灉
+        /// </summary>
+        public class AutoSplitResult
+        {
+            public string NewBarcode { get; set; }
+            public decimal SplitQuantity { get; set; }
+        }
 
         public class PickingResult
         {
@@ -1446,12 +3735,5 @@
         }
 
         #endregion
-    }
-
-
-    // 鏀寔绫�
-    public class SplitResultDto
-    {
-        public string NewBarcode { get; set; }
     }
 }

--
Gitblit v1.9.3