From 48710581fbbdd40eb3a743d91fa04e81531ba2ab Mon Sep 17 00:00:00 2001
From: heshaofeng <heshaofeng@hnkhzn.com>
Date: 星期五, 05 十二月 2025 08:39:42 +0800
Subject: [PATCH] Merge branch 'master' of http://115.159.85.185:8098/r/ZhongRui/ALDbanyunxiangmu

---
 项目代码/WMS无仓储版/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService.cs |  777 ++++++++++++++++++++++++++++++++++++++++++++++-------------
 1 files changed, 604 insertions(+), 173 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_TaskInfoService/TaskService.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_TaskInfoService/TaskService.cs"
index 3bea184..c72a941 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_TaskInfoService/TaskService.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_TaskInfoService/TaskService.cs"
@@ -18,6 +18,7 @@
 using AutoMapper;
 using Dm.filter;
 using MailKit.Search;
+using Microsoft.AspNetCore.Mvc;
 using Microsoft.Extensions.Logging;
 using Newtonsoft.Json;
 using Org.BouncyCastle.Asn1.Ocsp;
@@ -27,6 +28,8 @@
 using System.Reflection.Emit;
 using System.Threading.Tasks;
 using System.Xml.Linq;
+using WIDESEA_BasicService;
+using WIDESEA_Common.AllocateEnum;
 using WIDESEA_Common.CommonEnum;
 using WIDESEA_Common.LocationEnum;
 using WIDESEA_Common.OrderEnum;
@@ -51,6 +54,7 @@
 using WIDESEA_IStockService;
 using WIDESEA_ITaskInfoService;
 using WIDESEA_Model.Models;
+using WIDESEA_Model.Models.Check;
 using WIDESEA_Model.Models.Outbound;
 
 namespace WIDESEA_TaskInfoService
@@ -66,16 +70,21 @@
         private readonly IInboundOrderService _inboundOrderService;
         private readonly IInboundOrderDetailService _inboundOrderDetailService;
 
+        private readonly IRepository<Dt_AllocateOrderDetail> _allocateOrderDetailRepository;
+        private readonly IRepository<Dt_AllocateOrder> _allocateOrderRepository;
+        private readonly IRepository<Dt_ReCheckOrder> _reCheckOrderRepository;
         private readonly IRepository<Dt_OutboundBatch> _OutboundBatchRepository;
         private readonly IOutboundOrderService _outboundOrderService;
         private readonly IOutboundOrderDetailService _outboundOrderDetailService;
         private readonly IOutStockLockInfoService _outStockLockInfoService;
         private readonly ILocationStatusChangeRecordService _locationStatusChangeRecordService;
+        private readonly IMaterialUnitService _materialUnitService;
         private readonly IESSApiService _eSSApiService;
         private readonly IStockService _stockService;
         private readonly IRecordService _recordService;
         private readonly IAllocateService _allocateService;
         private readonly IInvokeMESService _invokeMESService;
+        private readonly ITask_HtyService _task_HtyService;
         public IRepository<Dt_Task> Repository => BaseDal;
 
         private Dictionary<string, SqlSugar.OrderByType> _taskOrderBy = new()
@@ -95,7 +104,7 @@
 
         public List<int> TaskOutboundTypes => typeof(TaskTypeEnum).GetEnumIndexList();
 
-        public TaskService(IRepository<Dt_Task> BaseDal, IMapper mapper, IUnitOfWorkManage unitOfWorkManage, IRepository<Dt_StockInfo> stockRepository, ILocationInfoService locationInfoService, IInboundOrderService inboundOrderService, ILocationStatusChangeRecordService locationStatusChangeRecordService, IESSApiService eSSApiService, ILogger<TaskService> logger, IStockService stockService, IRecordService recordService, IInboundOrderDetailService inboundOrderDetailService, IOutboundOrderService outboundOrderService, IOutboundOrderDetailService outboundOrderDetailService, IInvokeMESService invokeMESService, IOutStockLockInfoService outStockLockInfoService, IAllocateService allocateService, IRepository<Dt_OutboundBatch> outboundBatchRepository) : base(BaseDal)
+        public TaskService(IRepository<Dt_Task> BaseDal, IMapper mapper, IUnitOfWorkManage unitOfWorkManage, IRepository<Dt_StockInfo> stockRepository, ILocationInfoService locationInfoService, IInboundOrderService inboundOrderService, ILocationStatusChangeRecordService locationStatusChangeRecordService, IESSApiService eSSApiService, ILogger<TaskService> logger, IStockService stockService, IRecordService recordService, IInboundOrderDetailService inboundOrderDetailService, IOutboundOrderService outboundOrderService, IOutboundOrderDetailService outboundOrderDetailService, IInvokeMESService invokeMESService, IOutStockLockInfoService outStockLockInfoService, IAllocateService allocateService, IRepository<Dt_OutboundBatch> outboundBatchRepository, IRepository<Dt_ReCheckOrder> reCheckOrderRepository, IRepository<Dt_AllocateOrderDetail> allocateOrderDetailRepository, IRepository<Dt_AllocateOrder> allocateOrderRepository, IMaterialUnitService materialUnitService, ITask_HtyService task_HtyService) : base(BaseDal)
         {
             _mapper = mapper;
             _unitOfWorkManage = unitOfWorkManage;
@@ -114,8 +123,25 @@
             _outStockLockInfoService = outStockLockInfoService;
             _allocateService = allocateService;
             _OutboundBatchRepository = outboundBatchRepository;
+            _reCheckOrderRepository = reCheckOrderRepository;
+            _allocateOrderDetailRepository = allocateOrderDetailRepository;
+            _allocateOrderRepository = allocateOrderRepository;
+            _materialUnitService = materialUnitService;
+            _task_HtyService = task_HtyService;
         }
 
+        public async Task TaskStatusChange(string taskNum,TaskStatusEnum taskStatusEnum)
+        {
+            if (int.TryParse(taskNum, out var newTaskNum))
+            {
+                await Db.Updateable<Dt_Task>().SetColumns(it => new Dt_Task {
+                        TaskStatus = taskStatusEnum.ObjToInt()
+                    })
+                    .Where(it => it.TaskNum == newTaskNum)
+                    .ExecuteCommandAsync();
+            }
+              
+        }
 
         /// <summary>
         /// 
@@ -264,8 +290,12 @@
 
             task.TaskStatus = TaskStatusEnum.Finish.ObjToInt();
 
-            BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
-
+            //  BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
+            var result = _task_HtyService.DeleteAndMoveIntoHty(task, OperateTypeEnum.浜哄伐鍒犻櫎);
+            if (!result)
+            {
+                await Db.Deleteable(task).ExecuteCommandAsync();
+            }
             _locationStatusChangeRecordService.AddLocationStatusChangeRecord(locationInfo, beforeStatus, StockChangeType.Inbound.ObjToInt(), "", task.TaskNum);
 
             _recordService.StockQuantityChangeRecordService.AddStockChangeRecord(stockInfo, stockInfo.Details, beforeQuantity, stockInfo.Details.Sum(x => x.StockQuantity) + beforeQuantity, WIDESEA_Common.StockEnum.StockChangeType.MaterielGroup);
@@ -282,7 +312,7 @@
                             {
                                 ReqCode = Guid.NewGuid().ToString(),
                                 ReqTime = DateTime.Now.ToString(),
-                                BusinessType = "2",
+                                BusinessType = BusinessTypeEnum.澶栭儴浠撳簱璋冩櫤浠�.ObjToInt().ToString(),
                                 FactoryArea = inboundOrder.FactoryArea,
                                 OperationType = 1,
                                 Operator = inboundOrder.Operator,
@@ -293,7 +323,7 @@
 
                             };
 
-                            var groupedData = inboundOrder.Details.GroupBy(item => new { item.MaterielCode, item.SupplyCode, item.BatchNo, item.lineNo, item.BarcodeUnit, item.WarehouseCode })
+                            var groupedData = inboundOrder.Details.GroupBy(item => new { item.MaterielCode, item.lineNo, item.BarcodeUnit, item.WarehouseCode })
                                .Select(group => new AllocateDtoDetail
                                {
                                    MaterialCode = group.Key.MaterielCode,
@@ -308,13 +338,13 @@
                                        Qty = row.BarcodeQty,
                                        BatchNo = row.BatchNo,
                                        SupplyCode = row.SupplyCode,
-                                       Unit = row.Unit
+                                       Unit = row.BarcodeUnit
                                    }).ToList()
                                }).ToList();
                             allocatefeedmodel.Details = groupedData;
 
-                            var result = await _invokeMESService.FeedbackAllocate(allocatefeedmodel);
-                            if (result != null && result.code == 200)
+                            var feedbackresult = await _invokeMESService.FeedbackAllocate(allocatefeedmodel);
+                            if (feedbackresult != null && feedbackresult.code == 200)
                             {
                                 _inboundOrderService.Db.Updateable<Dt_InboundOrder>().SetColumns(it => new Dt_InboundOrder { ReturnToMESStatus = 1 })
                                 .Where(it => it.Id == inboundOrder.Id).ExecuteCommand();
@@ -325,6 +355,59 @@
                     }
                     else if (inboundOrder.OrderType == InOrderTypeEnum.ReCheck.ObjToInt()) //閲嶆鍏ュ簱
                     {
+                        //涓嶉渶瑕佸洖浼犮�傚崰涓�涓綅缃��
+                    }
+                    else if (inboundOrder.OrderType == InOrderTypeEnum.InternalAllocat.ObjToInt()) //鏅轰粨璋冩櫤浠�
+                    {
+                        _logger.LogInformation($"InboundTaskCompleted 鍥炲啓MES  : {inboundOrder.InboundOrderNo}  ,ordertype: {InOrderTypeEnum.InternalAllocat.ObjToInt()} ");
+                        // BusinessTypeEnum.鏅轰粨璋冩櫤浠�
+                        if (inboundOrder != null && inboundOrder.OrderStatus == InOrderStatusEnum.鍏ュ簱瀹屾垚.ObjToInt())
+                        {
+                            var allocate = _allocateService.Repository.QueryData(x => x.OrderNo == inboundOrder.InboundOrderNo).First();
+                            var allocatefeedmodel = new AllocateDto
+                            {
+                                ReqCode = Guid.NewGuid().ToString(),
+                                ReqTime = DateTime.Now.ToString(),
+                                BusinessType = BusinessTypeEnum.鏅轰粨璋冩櫤浠�.ObjToInt().ToString(),
+                                FactoryArea = inboundOrder.FactoryArea,
+                                OperationType = 1,
+                                Operator = inboundOrder.Operator,
+                                OrderNo = inboundOrder.UpperOrderNo,
+                                fromWarehouse = allocate?.FromWarehouse ?? "",
+                                toWarehouse = allocate?.ToWarehouse ?? "",
+                                Details = new List<AllocateDtoDetail>()
+
+                            };
+
+                            var groupedData = inboundOrder.Details.GroupBy(item => new { item.MaterielCode, item.lineNo, item.BarcodeUnit, item.WarehouseCode })
+                               .Select(group => new AllocateDtoDetail
+                               {
+                                   MaterialCode = group.Key.MaterielCode,
+                                   LineNo = group.Key.lineNo,
+                                   WarehouseCode = group.Key.WarehouseCode,
+                                   Qty = group.Sum(x => x.BarcodeQty),
+                                   // warehouseCode= "1072",
+                                   Unit = group.Key.BarcodeUnit,
+                                   Barcodes = group.Select(row => new BarcodeInfo
+                                   {
+                                       Barcode = row.Barcode,
+                                       Qty = row.BarcodeQty,
+                                       BatchNo = row.BatchNo,
+                                       SupplyCode = row.SupplyCode,
+                                       Unit = row.BarcodeUnit
+                                   }).ToList()
+                               }).ToList();
+                            allocatefeedmodel.Details = groupedData;
+
+                            var feedbackresult = await _invokeMESService.FeedbackAllocate(allocatefeedmodel);
+                            if (feedbackresult != null && feedbackresult.code == 200)
+                            {
+                                _inboundOrderService.Db.Updateable<Dt_InboundOrder>().SetColumns(it => new Dt_InboundOrder { ReturnToMESStatus = 1 })
+                                .Where(it => it.Id == inboundOrder.Id).ExecuteCommand();
+                                _inboundOrderDetailService.Db.Updateable<Dt_InboundOrderDetail>().SetColumns(it => new Dt_InboundOrderDetail { ReturnToMESStatus = 1 })
+                                .Where(it => it.OrderId == inboundOrder.Id).ExecuteCommand();
+                            }
+                        }
 
                     }
                     else
@@ -364,8 +447,8 @@
                                }).ToList();
                             feedmodel.details = groupedData;
 
-                            var result = await _invokeMESService.FeedbackInbound(feedmodel);
-                            if (result != null && result.code == 200)
+                            var feedbackresult = await _invokeMESService.FeedbackInbound(feedmodel);
+                            if (feedbackresult != null && feedbackresult.code == 200)
                             {
                                 _inboundOrderService.Db.Updateable<Dt_InboundOrder>().SetColumns(it => new Dt_InboundOrder { ReturnToMESStatus = 1 })
                                 .Where(it => it.Id == inboundOrder.Id).ExecuteCommand();
@@ -390,7 +473,7 @@
         {
             _logger.LogInformation($"TaskService  OutAllocateTaskCompleted: {task.TaskNum}");
 
-           return  await OutboundTaskCompleted(task);          
+            return await OutboundTaskCompleted(task);
         }
         public async Task<WebResponseContent> OutboundTaskCompleted(Dt_Task task)
         {
@@ -471,8 +554,12 @@
                 var outboundOrder = _outboundOrderService.Db.Queryable<Dt_OutboundOrder>().First(x => x.OrderNo == task.OrderNo);
 
                 task.TaskStatus = TaskStatusEnum.Finish.ObjToInt();
-                BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? WIDESEA_Core.Enums.OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
-
+                // BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? WIDESEA_Core.Enums.OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
+                var result = _task_HtyService.DeleteAndMoveIntoHty(task, OperateTypeEnum.浜哄伐鍒犻櫎);
+                if (!result)
+                {
+                    await Db.Deleteable(task).ExecuteCommandAsync();
+                }
                 _locationStatusChangeRecordService.AddLocationStatusChangeRecord(locationInfo, beforelocationStatus, StockChangeType.Inbound.ObjToInt(), "", task.TaskNum);
 
 
@@ -493,60 +580,84 @@
             }
         }
 
+
         public async Task<WebResponseContent> InPickTaskCompleted(Dt_Task task)
         {
-            _logger.LogInformation($"TaskService  InPickTaskCompleted: {task.TaskNum}");
+            _logger.LogInformation($"TaskService InPickTaskCompleted: {task.TaskNum}");
+
             try
             {
-                //鏌ュ簱瀛�
-                Dt_StockInfo stockInfo = await _stockRepository.Db.Queryable<Dt_StockInfo>().Includes(x => x.Details).Where(x => x.PalletCode == task.PalletCode).FirstAsync();
+                _unitOfWorkManage.BeginTran(); // 娣诲姞浜嬪姟绠$悊
+
+                // 鏌ュ簱瀛�
+                Dt_StockInfo stockInfo = await _stockRepository.Db.Queryable<Dt_StockInfo>()
+                    .Includes(x => x.Details)
+                    .Where(x => x.PalletCode == task.PalletCode)
+                    .FirstAsync();
+
                 if (stockInfo == null)
                 {
-                    _logger.LogInformation($"TaskService  InPickTaskCompleted: 鏈壘鍒版墭鐩樺搴旂殑缁勭洏淇℃伅.{task.TaskNum}");
+                    _logger.LogInformation($"TaskService InPickTaskCompleted: 鏈壘鍒版墭鐩樺搴旂殑缁勭洏淇℃伅.{task.TaskNum}");
                     return WebResponseContent.Instance.Error($"鏈壘鍒版墭鐩樺搴旂殑缁勭洏淇℃伅");
                 }
+
                 if (stockInfo.Details.Count == 0 && stockInfo.PalletType != PalletTypeEnum.Empty.ObjToInt())
                 {
-                    _logger.LogInformation($"TaskService  InPickTaskCompleted: 鏈壘鍒拌鎵樼洏搴撳瓨鏄庣粏淇℃伅.{task.TaskNum}");
+                    _logger.LogInformation($"TaskService InPickTaskCompleted: 鏈壘鍒拌鎵樼洏搴撳瓨鏄庣粏淇℃伅.{task.TaskNum}");
                     return WebResponseContent.Instance.Error($"鏈壘鍒拌鎵樼洏搴撳瓨鏄庣粏淇℃伅");
                 }
-                //鏌ヨ揣浣�
+
+                // 鏌ヨ揣浣�
                 Dt_LocationInfo locationInfo = _locationInfoService.Repository.QueryFirst(x => x.LocationCode == task.TargetAddress);
                 if (locationInfo == null)
                 {
-                    _logger.LogInformation($"TaskService  InPickTaskCompleted:  鏈壘鍒板搴旂殑缁堢偣璐т綅淇℃伅 {task.TaskNum}.");
+                    _logger.LogInformation($"TaskService InPickTaskCompleted: 鏈壘鍒板搴旂殑缁堢偣璐т綅淇℃伅 {task.TaskNum}.");
                     return WebResponseContent.Instance.Error($"鏈壘鍒板搴旂殑缁堢偣璐т綅淇℃伅");
                 }
 
                 var beforelocationStatus = locationInfo.LocationStatus;
+
                 // 鑾峰彇鎵�鏈夊洖搴撲腑鐨勫嚭搴撻攣瀹氳褰�
                 var returnLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                    .Where(it => it.OrderNo == task.OrderNo && it.PalletCode == task.PalletCode && it.Status == (int)OutLockStockStatusEnum.鍥炲簱涓�)
+                    .Where(it => it.OrderNo == task.OrderNo &&
+                               it.PalletCode == task.PalletCode &&
+                               it.Status == (int)OutLockStockStatusEnum.鍥炲簱涓�)
                     .ToListAsync();
+
                 // 鏇存柊鍑哄簱閿佸畾璁板綍鐘舵�佷负鍥炲簱瀹屾垚
                 foreach (var lockInfo in returnLocks)
                 {
                     lockInfo.Status = (int)OutLockStockStatusEnum.宸插洖搴�;
+                    lockInfo.Operator = App.User.UserName;
                 }
-                _outStockLockInfoService.Db.Updateable(returnLocks).ExecuteCommand();
 
+                if (returnLocks.Any())
+                {
+                    await _outStockLockInfoService.Db.Updateable(returnLocks).ExecuteCommandAsync();
+                    _logger.LogInformation($"鏇存柊{returnLocks.Count}鏉¢攣瀹氳褰曚负宸插洖搴撶姸鎬�");
+                }
+
+                // 鏇存柊搴撳瓨淇℃伅
                 stockInfo.LocationCode = task.TargetAddress;
                 stockInfo.StockStatus = StockStatusEmun.鍏ュ簱瀹屾垚.ObjToInt();
+
+                // 鏇存柊搴撳瓨鏄庣粏鐘舵��
                 if (stockInfo.Details != null && stockInfo.Details.Any())
                 {
-                    stockInfo.Details.ForEach(x =>
+                    foreach (var detail in stockInfo.Details)
                     {
-                        x.Status = StockStatusEmun.鍏ュ簱瀹屾垚.ObjToInt();
-                    });
+                        detail.Status = StockStatusEmun.鍏ュ簱瀹屾垚.ObjToInt();
+                        detail.OutboundQuantity = 0; // 鍏ュ簱瀹屾垚鏃跺嚭搴撴暟閲忔竻闆�
+                    }
                     _stockService.StockInfoDetailService.Repository.UpdateData(stockInfo.Details);
                 }
 
                 _stockService.StockInfoService.Repository.UpdateData(stockInfo);
-
-                await ProcessStockDetailsForReturn(task, stockInfo.Id);
-
+                // 鍒犻櫎闆跺簱瀛樻暟鎹�
                 await DeleteZeroQuantityStockDetails(stockInfo.Id);
 
+                await UpdateAffectedOrderDetails(task.OrderNo, returnLocks);
+                // 鏇存柊璐т綅鐘舵��
                 if (stockInfo.PalletType == PalletTypeEnum.Empty.ObjToInt())
                 {
                     locationInfo.LocationStatus = LocationStatusEnum.Pallet.ObjToInt();
@@ -555,30 +666,346 @@
                 {
                     locationInfo.LocationStatus = LocationStatusEnum.InStock.ObjToInt();
                 }
+
                 _locationInfoService.Repository.UpdateData(locationInfo);
-                var outboundOrder = _outboundOrderService.Db.Queryable<Dt_OutboundOrder>().First(x => x.OrderNo == task.OrderNo);
+
                 task.TaskStatus = TaskStatusEnum.Finish.ObjToInt();
 
-                BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
-                BaseDal.DeleteData(task);
-                _locationStatusChangeRecordService.AddLocationStatusChangeRecord(locationInfo, beforelocationStatus, StockChangeType.Inbound.ObjToInt(), "", task.TaskNum);
-
-                if (outboundOrder != null)
+                // 鍒犻櫎浠诲姟璁板綍
+                //BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
+                //BaseDal.DeleteData(task);
+                var result = _task_HtyService.DeleteAndMoveIntoHty(task, OperateTypeEnum.浜哄伐鍒犻櫎);
+                if (!result)
                 {
-                    await HandleOutboundOrderToMESCompletion(outboundOrder, outboundOrder.OrderNo);
+                    await Db.Deleteable(task).ExecuteCommandAsync();
                 }
-                else
+                // 璁板綍璐т綅鐘舵�佸彉鏇�
+                _locationStatusChangeRecordService.AddLocationStatusChangeRecord(
+                    locationInfo,
+                    beforelocationStatus,
+                    StockChangeType.Inbound.ObjToInt(),
+                    "",
+                    task.TaskNum
+                );
+                await RecalculateOrderStatus(task.OrderNo);
+
+                _unitOfWorkManage.CommitTran(); // 鎻愪氦浜嬪姟
+                _logger.LogInformation($"鎵樼洏鍥炲簱瀹屾垚澶勭悊鎴愬姛 - 浠诲姟鍙�: {task.TaskNum}, 鎵樼洏: {task.PalletCode}, 璁㈠崟: {task.OrderNo}");
+                _ = Task.Run(async () =>
                 {
-                    _logger.LogInformation($"TaskService  InPickTaskCompleted: {task.TaskNum} ,鏈壘鍒板嚭搴撳崟銆�  ");
+                    try
+                    {
+                        var outboundOrder = await _outboundOrderService.Db.Queryable<Dt_OutboundOrder>()
+                            .FirstAsync(x => x.OrderNo == task.OrderNo);
+
+                        if (outboundOrder != null)
+                        {
+                            // 妫�鏌ヨ鍗曟槸鍚﹀凡瀹屾垚锛屽彧鏈夊畬鎴愭椂鎵嶅悜MES鍙嶉
+                            if (outboundOrder.OrderStatus == (int)OutOrderStatusEnum.鍑哄簱瀹屾垚)
+                            {
+                                await HandleOutboundOrderToMESCompletion(outboundOrder, outboundOrder.OrderNo);
+                            }
+                            else
+                            {
+                                _logger.LogInformation($"璁㈠崟{task.OrderNo}鐘舵�佷负{outboundOrder.OrderStatus}锛屾殏涓嶅悜MES鍙嶉");
+                            }
+                        }
+                    }
+                    catch (Exception ex)
+                    {
+                        _logger.LogError($"寮傛MES鍙嶉澶勭悊澶辫触 - OrderNo: {task.OrderNo}, Error: {ex.Message}");
+                    }
+                });
+            }
+            catch (Exception ex)
+            {
+                _unitOfWorkManage.RollbackTran(); // 鍥炴粴浜嬪姟
+                _logger.LogError($"TaskService InPickTaskCompleted澶辫触 - TaskNum: {task.TaskNum}, Error: {ex.Message}");
+                return WebResponseContent.Instance.Error($"鍥炲簱浠诲姟瀹屾垚澶勭悊澶辫触: {ex.Message}");
+            }
+
+            return WebResponseContent.Instance.OK();
+        }
+        // <summary>
+        /// 鏇存柊鍙楀奖鍝嶇殑璁㈠崟鏄庣粏閿佸畾鏁伴噺
+        /// </summary>
+        private async Task UpdateAffectedOrderDetails(string orderNo, List<Dt_OutStockLockInfo> returnLocks)
+        {
+            try
+            {
+                // 鑾峰彇鍙楀奖鍝嶇殑璁㈠崟鏄庣粏ID锛堝幓閲嶏級
+                var affectedDetailIds = returnLocks
+                    .Select(x => x.OrderDetailId)
+                    .Distinct()
+                    .ToList();
+
+                if (!affectedDetailIds.Any())
+                {
+                    _logger.LogInformation($"娌℃湁鍙楀奖鍝嶇殑璁㈠崟鏄庣粏 - OrderNo: {orderNo}");
+                    return;
+                }
+
+                _logger.LogInformation($"鏇存柊{affectedDetailIds.Count}涓彈褰卞搷鐨勮鍗曟槑缁� - OrderNo: {orderNo}");
+
+                foreach (var detailId in affectedDetailIds)
+                {
+                    // 閲嶆柊璁$畻璇ヨ鍗曟槑缁嗙殑閿佸畾鏁伴噺
+                    decimal currentLockQty = await CalculateOrderDetailLockQuantity(detailId);
+
+                    // 妫�鏌ユ暟鎹竴鑷存��
+                    if (currentLockQty < 0)
+                    {
+                        _logger.LogWarning($"閿佸畾鏁伴噺璁$畻涓鸿礋鍊� - OrderDetailId: {detailId}, 褰撳墠鍊�: {currentLockQty}锛岄噸缃负0");
+                        currentLockQty = 0;
+                    }
+
+                    // 鑾峰彇璁㈠崟鏄庣粏
+                    var orderDetail = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
+                        .FirstAsync(x => x.Id == detailId);
+
+                    if (orderDetail == null)
+                    {
+                        _logger.LogWarning($"鏈壘鍒拌鍗曟槑缁� - OrderDetailId: {detailId}");
+                        continue;
+                    }
+
+                    // 鏇存柊閿佸畾鏁伴噺
+                    if (orderDetail.LockQuantity != currentLockQty)
+                    {
+                        await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
+                            .SetColumns(it => new Dt_OutboundOrderDetail
+                            {
+                                LockQuantity = currentLockQty,
+                            })
+                            .Where(it => it.Id == detailId)
+                            .ExecuteCommandAsync();
+
+                        _logger.LogInformation($"鏇存柊璁㈠崟鏄庣粏閿佸畾鏁伴噺 - OrderDetailId: {detailId}, " +
+                                              $"鏃у��: {orderDetail.LockQuantity}, 鏂板��: {currentLockQty}");
+                    }
+
+                    // 鏇存柊璁㈠崟鏄庣粏鐘舵��
+                    await UpdateOrderDetailStatus(orderDetail);
                 }
             }
             catch (Exception ex)
             {
-                _logger.LogInformation($"TaskService  InPickTaskCompleted: {task.TaskNum} , {ex.Message}");
+                _logger.LogError($"UpdateAffectedOrderDetails澶辫触 - OrderNo: {orderNo}, Error: {ex.Message}");
+                throw;
             }
-            return await Task.FromResult(WebResponseContent.Instance.OK());
         }
 
+        /// <summary>
+        /// 閲嶆柊璁$畻璁㈠崟鏄庣粏閿佸畾鏁伴噺
+        /// </summary>
+        private async Task<decimal> CalculateOrderDetailLockQuantity(int orderDetailId)
+        {
+            try
+            {
+                // 鏌ユ壘璇ヨ鍗曟槑缁嗕笅鎵�鏈夌姸鎬佷负"鍑哄簱涓�"鐨勯攣瀹氳褰�
+                var activeLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                    .Where(x => x.OrderDetailId == orderDetailId &&
+                               x.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�)
+                    .ToListAsync();
+
+                // 杩囨护鎷嗗寘璁板綍
+                var filteredLocks = new List<Dt_OutStockLockInfo>();
+
+                foreach (var lockInfo in activeLocks)
+                {
+                    // 濡傛灉鏄媶鍖呰褰曪紝闇�瑕佺壒娈婂鐞�
+                    if (lockInfo.IsSplitted == 1 && lockInfo.ParentLockId.HasValue)
+                    {
+                        // 鏌ユ壘鐖堕攣瀹氳褰�
+                        var parentLock = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                            .Where(x => x.Id == lockInfo.ParentLockId.Value)
+                            .FirstAsync();
+
+                        // 濡傛灉鐖惰褰曞瓨鍦ㄤ笖鐘舵�佷篃鏄嚭搴撲腑锛屽垯鍙绠楃埗璁板綍
+                        if (parentLock != null && parentLock.Status == (int)OutLockStockStatusEnum.鍑哄簱涓�)
+                        {
+                            // 鐖惰褰曞凡缁忓湪鍒楄〃涓紝璺宠繃褰撳墠鎷嗗寘璁板綍
+                            continue;
+                        }
+                    }
+
+                    filteredLocks.Add(lockInfo);
+                }
+
+                decimal totalLockQty = filteredLocks.Sum(x => x.AssignQuantity - x.PickedQty);
+
+                _logger.LogDebug($"璁$畻閿佸畾鏁伴噺 - OrderDetailId: {orderDetailId}, " +
+                               $"鎵惧埌{filteredLocks.Count}涓湁鏁堥攣瀹氳褰�, " +
+                               $"鎬婚攣瀹氭暟閲�: {totalLockQty}");
+
+                return totalLockQty;
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"CalculateOrderDetailLockQuantity澶辫触 - OrderDetailId: {orderDetailId}, Error: {ex.Message}");
+                return 0;
+            }
+        }
+
+        /// <summary>
+        /// 鏇存柊璁㈠崟鏄庣粏鐘舵��
+        /// </summary>
+        private async Task UpdateOrderDetailStatus(Dt_OutboundOrderDetail orderDetail)
+        {
+            try
+            {
+                int newStatus = orderDetail.OrderDetailStatus;
+
+                // 鏍规嵁瀹為檯鏋氫妇鍊艰皟鏁�
+                //  妫�鏌ユ槸鍚﹀凡瀹屾垚锛堝凡鍑哄簱鏁伴噺 >= 闇�姹傛暟閲忥級
+                if (orderDetail.OverOutQuantity >= orderDetail.NeedOutQuantity)
+                {
+                    newStatus = (int)OrderDetailStatusEnum.Over; // 宸插畬鎴�
+                }
+                //  妫�鏌ユ槸鍚︽湁閮ㄥ垎鍑哄簱鎴栨湁閿佸畾鏁伴噺
+                else if (orderDetail.OverOutQuantity > 0 || orderDetail.LockQuantity > 0)
+                {
+                    newStatus = (int)OrderDetailStatusEnum.Outbound; // 閮ㄥ垎瀹屾垚/杩涜涓�
+                }
+                // 鍚﹀垯涓烘柊璁㈠崟
+                else
+                {
+                    newStatus = (int)OrderDetailStatusEnum.New; // 鏂板缓
+                }
+
+                // 鍙湁鐘舵�佸彉鍖栨椂鎵嶆洿鏂�
+                if (orderDetail.OrderDetailStatus != newStatus)
+                {
+                    await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
+                        .SetColumns(it => new Dt_OutboundOrderDetail
+                        {
+                            OrderDetailStatus = newStatus,
+                        })
+                        .Where(it => it.Id == orderDetail.Id)
+                        .ExecuteCommandAsync();
+
+                    _logger.LogInformation($"鏇存柊璁㈠崟鏄庣粏鐘舵�� - OrderDetailId: {orderDetail.Id}, " +
+                                          $"鏃х姸鎬�: {orderDetail.OrderDetailStatus}, 鏂扮姸鎬�: {newStatus}, " +
+                                          $"宸插嚭搴�: {orderDetail.OverOutQuantity}/{orderDetail.NeedOutQuantity}, " +
+                                          $"閿佸畾鏁伴噺: {orderDetail.LockQuantity}");
+                }
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"UpdateOrderDetailStatus澶辫触 - OrderDetailId: {orderDetail.Id}, Error: {ex.Message}");
+                throw;
+            }
+        }
+
+        /// <summary>
+        /// 閲嶆柊璁$畻骞舵洿鏂拌鍗曠姸鎬�
+        /// </summary>
+        private async Task RecalculateOrderStatus(string orderNo)
+        {
+            try
+            {
+                // 鑾峰彇璁㈠崟鐨勬墍鏈夋槑缁�
+                var orderDetails = await _outboundOrderDetailService.Db.Queryable<Dt_OutboundOrderDetail>()
+                    .LeftJoin<Dt_OutboundOrder>((o, item) => o.OrderId == item.Id)
+                    .Where((o, item) => item.OrderNo == orderNo)
+                    .Select((o, item) => o)
+                    .ToListAsync();
+
+                if (!orderDetails.Any())
+                {
+                    _logger.LogWarning($"鏈壘鍒拌鍗曟槑缁� - OrderNo: {orderNo}");
+                    return;
+                }
+
+                // 妫�鏌ョ姸鎬�
+                bool allCompleted = true;
+                bool hasInProgress = false;
+
+                foreach (var detail in orderDetails)
+                {
+                    // 妫�鏌ユ槸鍚﹀畬鎴�
+                    if (detail.OverOutQuantity < detail.NeedOutQuantity)
+                    {
+                        allCompleted = false;
+                    }
+
+                    // 妫�鏌ユ槸鍚︽湁杩涜涓殑浠诲姟锛堥攣瀹氭垨閮ㄥ垎鎷i�夛級
+                    if (detail.LockQuantity > 0 ||
+                        detail.OrderDetailStatus == (int)OrderDetailStatusEnum.Outbound)
+                    {
+                        hasInProgress = true;
+                    }
+                }
+
+                var outboundOrder = await _outboundOrderService.Db.Queryable<Dt_OutboundOrder>()
+                    .FirstAsync(x => x.OrderNo == orderNo);
+
+                if (outboundOrder == null)
+                {
+                    _logger.LogWarning($"鏈壘鍒板嚭搴撹鍗� - OrderNo: {orderNo}");
+                    return;
+                }
+
+                int newStatus;
+                if (allCompleted)
+                {
+                    newStatus = (int)OutOrderStatusEnum.鍑哄簱瀹屾垚;
+                }
+                else if (hasInProgress)
+                {
+                    newStatus = (int)OutOrderStatusEnum.鍑哄簱涓�;
+                }
+                else
+                {
+                    newStatus = (int)OutOrderStatusEnum.鏈紑濮�;
+                }
+
+                if (outboundOrder.OrderStatus != newStatus)
+                {
+                    await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
+                        .SetColumns(x => new Dt_OutboundOrder
+                        {
+                            OrderStatus = newStatus,
+                            Operator = App.User.UserName,
+                        })
+                        .Where(x => x.OrderNo == orderNo)
+                        .ExecuteCommandAsync();
+
+                    _logger.LogInformation($"鏇存柊璁㈠崟鐘舵�� - OrderNo: {orderNo}, 鏃х姸鎬�: {outboundOrder.OrderStatus}, 鏂扮姸鎬�: {newStatus}");
+                }
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"RecalculateOrderStatus澶辫触 - OrderNo: {orderNo}, Error: {ex.Message}");
+                throw;
+            }
+        }
+
+
+        /// <summary>
+        /// 鍒犻櫎闆跺簱瀛樻暟鎹紙澧炲己鐗堬級
+        /// </summary>
+        private async Task DeleteZeroQuantityStockDetails(int stockId)
+        {
+            try
+            {
+                // 鏌ユ壘搴撳瓨鏁伴噺涓�0鐨勮褰�
+                var zeroStockDetails = await _stockService.StockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
+                    .Where(x => x.StockId == stockId && x.StockQuantity <= 0)
+                    .ToListAsync();
+
+                if (zeroStockDetails.Any())
+                {
+                    await _stockService.StockInfoDetailService.Db.Deleteable(zeroStockDetails).ExecuteCommandAsync();
+                    _logger.LogInformation($"鍒犻櫎{zeroStockDetails.Count}鏉¢浂搴撳瓨璁板綍 - StockId: {stockId}");
+                }
+            }
+            catch (Exception ex)
+            {
+                _logger.LogError($"DeleteZeroQuantityStockDetails澶辫触 - StockId: {stockId}, Error: {ex.Message}");
+                throw;
+            }
+        }
 
         private async Task HandleOutboundOrderToMESCompletion(Dt_OutboundOrder outboundOrder, string orderNo)
         {
@@ -622,7 +1049,7 @@
                         {
                             ReqCode = Guid.NewGuid().ToString(),
                             ReqTime = DateTime.Now.ToString(),
-                            BusinessType = "3",
+                            BusinessType = "2",
                             FactoryArea = outboundOrder.FactoryArea,
                             OperationType = 1,
                             Operator = outboundOrder.Operator,
@@ -640,42 +1067,63 @@
                             var detailLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
                                 .Where(x => x.OrderNo == orderNo &&
                                            x.OrderDetailId == detail.Id &&
-                                           x.Status == (int)OutLockStockStatusEnum.鎷i�夊畬鎴�)
+                                           (x.Status == (int)OutLockStockStatusEnum.鎷i�夊畬鎴� || x.Status == (int)OutLockStockStatusEnum.宸插洖搴�))
                                 .ToListAsync();
 
                             var detailModel = new AllocateDtoDetail
                             {
                                 MaterialCode = detail.MaterielCode,
-                                LineNo = detail.lineNo, // 娉ㄦ剰锛氳繖閲屽彲鑳介渶瑕佽皟鏁村瓧娈靛悕
+                                LineNo = detail.lineNo,
                                 WarehouseCode = detail.WarehouseCode,
-                                Qty = detail.OverOutQuantity, // 浣跨敤璁㈠崟鏄庣粏鐨勫凡鍑哄簱鏁伴噺
-                                //currentDeliveryQty = detail.OverOutQuantity,
-                                Unit = detail.Unit,
-                                Barcodes = detailLocks.Select(lockInfo => new BarcodeInfo
-                                {
-                                    Barcode = lockInfo.CurrentBarcode,
-                                    SupplyCode = lockInfo.SupplyCode,
-                                    BatchNo = lockInfo.BatchNo,
-                                    Unit = lockInfo.Unit,
-                                    Qty = lockInfo.PickedQty // 鏉$爜绾у埆鐨勬暟閲忎粛鐢ㄩ攣瀹氳褰�
-                                }).ToList()
+                                Qty = 0,
+                                Unit = detail.BarcodeUnit,
+                                Barcodes = new List<BarcodeInfo>()
                             };
+                            foreach (var item in detailLocks)
+                            {
+                                if (item.PickedQty > 0)
+                                {
+                                    var barModel = new BarcodeInfo
+                                    {
+                                        Barcode = item.CurrentBarcode,
+                                        SupplyCode = item.SupplyCode,
+                                        BatchNo = item.BatchNo,
+                                        Unit = detail.BarcodeUnit,
+                                        Qty = 0
+                                    };
+                                    // 鍗曚綅涓嶄竴鑷存椂杞崲
+                                    if (detail.BarcodeUnit != detail.Unit)
+                                    {
+                                        var convertResult = await _materialUnitService.ConvertAsync(item.MaterielCode, item.PickedQty, detail.Unit, detail.BarcodeUnit);
+                                        barModel.Unit = convertResult.Unit;
+                                        barModel.Qty = convertResult.Quantity;
+                                    }
+                                    else
+                                    {
+                                        barModel.Qty = item.PickedQty;
+                                    }
+                                    detailModel.Qty += barModel.Qty;
+                                    detailModel.Barcodes.Add(barModel);
+                                }
 
-                            allocatefeedmodel.Details.Add(detailModel);
-                        }
-                        var result = await _invokeMESService.FeedbackAllocate(allocatefeedmodel);
-                        if (result != null && result.code == 200)
-                        {
-                            await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
-                                   .SetColumns(x => x.ReturnToMESStatus == 1)
-                                   .Where(x => x.OrderId == outboundOrder.Id).ExecuteCommandAsync();
 
-                            await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
-                                  .SetColumns(x => new Dt_OutboundOrder
-                                  {
-                                      ReturnToMESStatus = 1,
-                                      Operator = App.User.UserName,
-                                  }).Where(x => x.OrderNo == orderNo).ExecuteCommandAsync();
+                                allocatefeedmodel.Details.Add(detailModel);
+                            }
+
+                            var result = await _invokeMESService.FeedbackAllocate(allocatefeedmodel);
+                            if (result != null && result.code == 200)
+                            {
+                                await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
+                                       .SetColumns(x => x.ReturnToMESStatus == 1)
+                                       .Where(x => x.OrderId == outboundOrder.Id).ExecuteCommandAsync();
+
+                                await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
+                                      .SetColumns(x => new Dt_OutboundOrder
+                                      {
+                                          ReturnToMESStatus = 1,
+                                          Operator = App.User.UserName,
+                                      }).Where(x => x.OrderNo == orderNo).ExecuteCommandAsync();
+                            }
                         }
                     }
                     else if (outboundOrder.OrderType == OutOrderTypeEnum.ReCheck.ObjToInt())
@@ -684,63 +1132,90 @@
                     }
                     else
                     {
-                        var feedmodel = new FeedbackOutboundRequestModel
+                        if (outboundOrder != null && outboundOrder.IsBatch == 0)
                         {
-                            reqCode = Guid.NewGuid().ToString(),
-                            reqTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
-                            business_type = outboundOrder.BusinessType,
-                            factoryArea = outboundOrder.FactoryArea,
-                            operationType = 1,
-                            Operator = outboundOrder.Operator,
-                            orderNo = outboundOrder.UpperOrderNo,
-                            documentsNO = outboundOrder.OrderNo,
-                            status = outboundOrder.OrderStatus,
-                            details = new List<FeedbackOutboundDetailsModel>()
-                        };
-
-
-                        foreach (var detail in orderDetails)
-                        {
-                            // 鑾峰彇璇ユ槑缁嗗搴旂殑鏉$爜淇℃伅锛堜粠閿佸畾璁板綍锛�
-                            var detailLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
-                                .Where(x => x.OrderNo == orderNo &&
-                                           x.OrderDetailId == detail.Id &&
-                                           x.Status == (int)OutLockStockStatusEnum.鎷i�夊畬鎴�)
-                                .ToListAsync();
-
-                            var detailModel = new FeedbackOutboundDetailsModel
+                            var feedmodel = new FeedbackOutboundRequestModel
                             {
-                                materialCode = detail.MaterielCode,
-                                lineNo = detail.lineNo, // 娉ㄦ剰锛氳繖閲屽彲鑳介渶瑕佽皟鏁村瓧娈靛悕
-                                warehouseCode = detail.WarehouseCode,
-                                qty = detail.OverOutQuantity, // 浣跨敤璁㈠崟鏄庣粏鐨勫凡鍑哄簱鏁伴噺
-                                currentDeliveryQty = detail.OverOutQuantity,
-                                unit = detail.Unit,
-                                barcodes = detailLocks.Select(lockInfo => new WIDESEA_DTO.Outbound.BarcodesModel
-                                {
-                                    barcode = lockInfo.CurrentBarcode,
-                                    supplyCode = lockInfo.SupplyCode,
-                                    batchNo = lockInfo.BatchNo,
-                                    unit = lockInfo.Unit,
-                                    qty = lockInfo.PickedQty // 鏉$爜绾у埆鐨勬暟閲忎粛鐢ㄩ攣瀹氳褰�
-                                }).ToList()
+                                reqCode = Guid.NewGuid().ToString(),
+                                reqTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
+                                business_type = outboundOrder.BusinessType,
+                                factoryArea = outboundOrder.FactoryArea,
+                                operationType = 1,
+                                Operator = outboundOrder.Operator,
+                                orderNo = outboundOrder.UpperOrderNo,
+                                documentsNO = outboundOrder.OrderNo,
+                                status = outboundOrder.OrderStatus,
+                                details = new List<FeedbackOutboundDetailsModel>()
                             };
+                            foreach (var detail in orderDetails)
+                            {
+                                // 鑾峰彇璇ユ槑缁嗗搴旂殑鏉$爜淇℃伅锛堜粠閿佸畾璁板綍锛�
+                                var detailLocks = await _outStockLockInfoService.Db.Queryable<Dt_OutStockLockInfo>()
+                                    .Where(x => x.OrderNo == orderNo &&
+                                               x.OrderDetailId == detail.Id &&
+                                               (x.Status == (int)OutLockStockStatusEnum.鎷i�夊畬鎴� || x.Status == (int)OutLockStockStatusEnum.宸插洖搴�))
+                                    .ToListAsync();
 
-                            feedmodel.details.Add(detailModel);
+                                var detailModel = new FeedbackOutboundDetailsModel
+                                {
+                                    materialCode = detail.MaterielCode,
+                                    lineNo = detail.lineNo, // 娉ㄦ剰锛氳繖閲屽彲鑳介渶瑕佽皟鏁村瓧娈靛悕
+                                    warehouseCode = detail.WarehouseCode,
+                                    qty = 0,
+                                    currentDeliveryQty = 0,
+                                    unit = detail.Unit,
+                                    barcodes = new List<WIDESEA_DTO.Outbound.BarcodesModel>()
+                                };
+                                foreach (var item in detailLocks)
+                                {
+                                    if (item.PickedQty > 0)
+                                    {
+                                        var barModel = new WIDESEA_DTO.Outbound.BarcodesModel
+                                        {
+                                            barcode = item.CurrentBarcode,
+                                            supplyCode = item.SupplyCode,
+                                            batchNo = item.BatchNo,
+                                            unit = item.BarcodeUnit,
+                                            qty = item.PickedQty
+                                        };
+                                        // 鍗曚綅涓嶄竴鑷存椂杞崲
+                                        if (detail.BarcodeUnit != detail.Unit)
+                                        {
+                                            var convertResult = await _materialUnitService.ConvertAsync(item.MaterielCode, item.PickedQty, detail.Unit, detail.BarcodeUnit);
+                                            barModel.unit = convertResult.Unit;
+                                            barModel.qty = convertResult.Quantity;
+                                        }
+                                        else
+                                        {
+                                            barModel.qty = item.PickedQty;
+                                        }
+                                        detailModel.qty += barModel.qty;
+                                        detailModel.currentDeliveryQty += barModel.qty;
+                                        detailModel.barcodes.Add(barModel);
+                                    }
+                                }
+                                feedmodel.details.Add(detailModel);
+                            }
+
+                            var result = await _invokeMESService.FeedbackOutbound(feedmodel);
+                            if (result != null && result.code == 200)
+                            {
+                                await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
+                                    .SetColumns(x => x.ReturnToMESStatus == 1)
+                                    .Where(x => x.OrderId == outboundOrder.Id)
+                                    .ExecuteCommandAsync();
+
+                                await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
+                                    .SetColumns(x => x.ReturnToMESStatus == 1)
+                                    .Where(x => x.OrderNo == orderNo)
+                                    .ExecuteCommandAsync();
+                            }
                         }
-                        var result = await _invokeMESService.FeedbackOutbound(feedmodel);
-                        if (result != null && result.code == 200)
+                        else if (outboundOrder != null && outboundOrder.IsBatch == 1)
                         {
-                            await _outboundOrderDetailService.Db.Updateable<Dt_OutboundOrderDetail>()
-                                .SetColumns(x => x.ReturnToMESStatus == 1)
-                                .Where(x => x.OrderId == outboundOrder.Id)
-                                .ExecuteCommandAsync();
-
-                            await _outboundOrderService.Db.Updateable<Dt_OutboundOrder>()
-                                .SetColumns(x => x.ReturnToMESStatus == 1)
-                                .Where(x => x.OrderNo == orderNo)
-                                .ExecuteCommandAsync();
+                            await _invokeMESService.BatchOrderFeedbackToMes(new List<string>() { outboundOrder.OrderNo }, 2);
                         }
+
                     }
                 }
             }
@@ -751,60 +1226,7 @@
 
         }
 
-        /// <summary>
-        /// 鍒犻櫎搴撳瓨鏁颁负0鐨勫簱瀛樻槑缁嗚褰�
-        /// </summary>
-        private async Task DeleteZeroQuantityStockDetails(int stockId)
-        {
-            try
-            {
-                // 鍒犻櫎搴撳瓨鏁伴噺涓�0鐨勮褰�
-                var deleteCount = await _stockService.StockInfoDetailService.Db.Deleteable<Dt_StockInfoDetail>()
-                    .Where(x => x.StockId == stockId &&
-                               x.StockQuantity == 0 &&
-                               (x.Status == StockStatusEmun.鍑哄簱瀹屾垚.ObjToInt() || x.Status ==
-                                          StockStatusEmun.鍏ュ簱瀹屾垚.ObjToInt())) // 鍙垹闄ゅ凡瀹屾垚鐘舵�佺殑闆跺簱瀛�
-                    .ExecuteCommandAsync();
 
-                if (deleteCount > 0)
-                {
-                    _logger.LogInformation($"鍒犻櫎{deleteCount}鏉¢浂搴撳瓨鏄庣粏璁板綍 - StockId: {stockId}");
-                }
-            }
-            catch (Exception ex)
-            {
-                _logger.LogWarning($"鍒犻櫎闆跺簱瀛樿褰曞け璐� - StockId: {stockId}, Error: {ex.Message}");
-                // 娉ㄦ剰锛氬垹闄ゅけ璐ヤ笉搴旇褰卞搷涓绘祦绋嬶紝璁板綍鏃ュ織鍚庣户缁�
-            }
-        }
-        /// <summary>
-        /// 澶勭悊鍥炲簱鐩稿叧鐨勬墍鏈夊簱瀛樻槑缁嗙姸鎬佸彉鏇�
-        /// </summary>
-        private async Task ProcessStockDetailsForReturn(Dt_Task returnTask, int stockId)
-        {
-            // 鑾峰彇璇ユ墭鐩樹笅鎵�鏈夐渶瑕佸洖搴撶殑搴撳瓨鏄庣粏
-            var stockDetails = await _stockService.StockInfoDetailService.Db.Queryable<Dt_StockInfoDetail>()
-                .Where(x => x.StockId == stockId &&
-                           x.StockQuantity > 0 &&
-                          (x.Status == StockStatusEmun.鍑哄簱閿佸畾.ObjToInt() || x.Status ==
-                                      StockStatusEmun.鍏ュ簱纭.ObjToInt()))  // 鍖呮嫭鍑哄簱閿佸畾鍜屽叆搴撶‘璁ょ殑
-                .ToListAsync();
-
-            foreach (var detail in stockDetails)
-            {
-
-                detail.Status = StockStatusEmun.鍏ュ簱瀹屾垚.ObjToInt();
-                detail.OutboundQuantity = 0;  // 娓呯┖鍑哄簱鏁伴噺       
-
-                _logger.LogInformation($"鏇存柊搴撳瓨鏄庣粏鐘舵�� - 鏉$爜: {detail.Barcode}, 鏁伴噺: {detail.StockQuantity}");
-            }
-
-            if (stockDetails.Any())
-            {
-                await _stockService.StockInfoDetailService.Db.Updateable(stockDetails).ExecuteCommandAsync();
-                _logger.LogInformation($"鍏辨洿鏂皗stockDetails.Count}涓簱瀛樻槑缁嗙姸鎬佷负鍏ュ簱瀹屾垚");
-            }
-        }
         public async Task<WebResponseContent> OutEmptyTaskCompleted(Dt_Task task)
         {
             WebResponseContent content = new WebResponseContent();
@@ -831,9 +1253,18 @@
 
 
                 task.TaskStatus = TaskStatusEnum.Finish.ObjToInt();
-                BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
-                _stockService.StockInfoService.Repository.DeleteAndMoveIntoHty(stockInfo, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
-                //_stockRepository.Db.Deleteable(stockInfo).ExecuteCommand();
+                // BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
+                var result = _task_HtyService.DeleteAndMoveIntoHty(task, OperateTypeEnum.浜哄伐鍒犻櫎);
+                if (!result)
+                {
+                    await Db.Deleteable(task).ExecuteCommandAsync();
+                }
+
+                var stockresult = _stockService.StockInfoService.Repository.DeleteAndMoveIntoHty(stockInfo, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
+                if (!stockresult)
+                { 
+                    _stockRepository.Db.Deleteable(stockInfo).ExecuteCommand();
+                }
                 _stockService.StockInfoService.DeleteData(stockInfo);
                 _locationStatusChangeRecordService.AddLocationStatusChangeRecord(locationInfo, beforeStatus, StockChangeType.Outbound.ObjToInt(), stockInfo.Details.FirstOrDefault()?.OrderNo ?? "", task.TaskNum);
 

--
Gitblit v1.9.3