From a200871400d465620d45189b8068fafd0d95e01a Mon Sep 17 00:00:00 2001
From: wanshenmean <cathay_xy@163.com>
Date: 星期二, 31 三月 2026 10:38:05 +0800
Subject: [PATCH] refactor: 整理TaskService任务流程结构

---
 Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService_AGV.cs |  737 +++++++++++++++++++++++++--------------------
 Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService_WCS.cs |  120 +------
 Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService.cs     |   94 +++++
 3 files changed, 519 insertions(+), 432 deletions(-)

diff --git a/Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService.cs b/Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService.cs
index d1d3f8e..fe278a6 100644
--- a/Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService.cs
+++ b/Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService.cs
@@ -74,5 +74,97 @@
             _unitOfWorkManage = unitOfWorkManage;
         }
 
+        /// <summary>
+        /// 鏌ユ壘鎵樼洏鏄惁瀛樺湪鏈畬鎴愪换鍔°��
+        /// </summary>
+        private async Task<WebResponseContent> GetTaskByPalletCodeAsync(string palletCode)
+        {
+            try
+            {
+                var task = await BaseDal.QueryFirstAsync(s => s.PalletCode == palletCode);
+                if (task == null)
+                    return WebResponseContent.Instance.Error("鏈壘鍒板搴旂殑浠诲姟");
+
+                var taskDto = _mapper.Map<WMSTaskDTO>(task);
+                return WebResponseContent.Instance.OK("鏌ヨ鎴愬姛", taskDto);
+            }
+            catch (Exception ex)
+            {
+                return WebResponseContent.Instance.Error($"鏌ヨ浠诲姟澶辫触: {ex.Message}");
+            }
+        }
+
+        /// <summary>
+        /// 淇濆瓨浠诲姟鍘嗗彶銆�
+        /// </summary>
+        private async Task<WebResponseContent> SaveTaskHistoryAsync(Dt_Task task, string operateType)
+        {
+            var historyTask = _mapper.Map<Dt_Task_Hty>(task);
+            historyTask.InsertTime = DateTime.Now;
+            historyTask.OperateType = operateType;
+
+            var saved = await _task_HtyService.Repository.AddDataAsync(historyTask) > 0;
+            return saved
+                ? WebResponseContent.Instance.OK()
+                : WebResponseContent.Instance.Error("浠诲姟鍘嗗彶淇濆瓨澶辫触");
+        }
+
+        /// <summary>
+        /// 淇濆瓨搴撳瓨鍘嗗彶銆�
+        /// </summary>
+        private async Task<WebResponseContent> SaveStockHistoryAsync(Dt_StockInfo stockInfo, string operateType)
+        {
+            var historyStock = _mapper.Map<Dt_StockInfo_Hty>(stockInfo);
+            historyStock.InsertTime = DateTime.Now;
+            historyStock.OperateType = operateType;
+
+            var saved = await _stockInfo_HtyService.Repository.AddDataAsync(historyStock) > 0;
+            return saved
+                ? WebResponseContent.Instance.OK()
+                : WebResponseContent.Instance.Error("搴撳瓨鍘嗗彶淇濆瓨澶辫触");
+        }
+
+        /// <summary>
+        /// 瀹屾垚浠诲姟鍚庣粺涓�澶勭悊銆�
+        /// </summary>
+        private async Task<WebResponseContent> CompleteTaskAsync(Dt_Task task, string operateType = "")
+        {
+            var deleteTaskResult = await BaseDal.DeleteDataAsync(task);
+            if (!deleteTaskResult)
+                return WebResponseContent.Instance.Error("浠诲姟瀹屾垚澶辫触");
+
+            return await SaveTaskHistoryAsync(task, operateType);
+        }
+
+        /// <summary>
+        /// 鏍规嵁宸烽亾纭畾鐩爣鍦板潃锛屾敮鎸佸鍑哄簱鍙h疆璇€��
+        /// </summary>
+        private string DetermineTargetAddress(string roadway, Dictionary<string, List<string>> addressMap)
+        {
+            if (string.IsNullOrWhiteSpace(roadway))
+                return "10080";
+
+            string? matchedPrefix = null;
+            foreach (var kvp in addressMap)
+            {
+                if (roadway.Contains(kvp.Key))
+                {
+                    matchedPrefix = kvp.Key;
+                    break;
+                }
+            }
+
+            if (matchedPrefix == null)
+                return "10080";
+
+            if (!addressMap.TryGetValue(matchedPrefix, out var addresses) || addresses == null || addresses.Count == 0)
+                return "10080";
+
+            if (addresses.Count == 1)
+                return addresses[0];
+
+            return _roundRobinService.GetNextAddress(matchedPrefix, addresses);
+        }
+
     }
-}
\ No newline at end of file
+}
diff --git a/Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService_AGV.cs b/Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService_AGV.cs
index 0be014a..3e77721 100644
--- a/Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService_AGV.cs
+++ b/Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService_AGV.cs
@@ -1,26 +1,13 @@
 using Mapster;
-using MapsterMapper;
-using Microsoft.Extensions.Configuration;
-using SqlSugar;
-using System.DirectoryServices.Protocols;
 using System.Text.Json;
 using WIDESEA_Common.LocationEnum;
 using WIDESEA_Common.StockEnum;
 using WIDESEA_Common.TaskEnum;
 using WIDESEA_Common.WareHouseEnum;
 using WIDESEA_Core;
-using WIDESEA_Core.BaseRepository;
-using WIDESEA_Core.BaseServices;
-using WIDESEA_Core.Core;
 using WIDESEA_Core.Enums;
 using WIDESEA_Core.Helper;
-using WIDESEA_DTO.GradingMachine;
-using WIDESEA_DTO.MES;
-using WIDESEA_DTO.Stock;
 using WIDESEA_DTO.Task;
-using WIDESEA_IBasicService;
-using WIDESEA_IStockService;
-using WIDESEA_ITaskInfoService;
 using WIDESEA_Model.Models;
 
 namespace WIDESEA_TaskInfoService
@@ -29,403 +16,495 @@
     {
         #region 鏋佸嵎搴撲换鍔℃ā鍧�
 
-        public string AGV_OutTaskComplete = WIDESEA_Core.Helper.AppSettings.Configuration["AGV_OutTaskComplete"]; // 涓婃姤AGV鍑哄簱杈撻�佺嚎瀹屾垚
-        public string WCS_ReceiveTask = WIDESEA_Core.Helper.AppSettings.Configuration["WCS_ReceiveTask"]; // WMS杈撻�佺嚎浠诲姟涓嬪彂
+        public string AGV_OutTaskComplete = WIDESEA_Core.Helper.AppSettings.Configuration["AGV_OutTaskComplete"];
+        public string WCS_ReceiveTask = WIDESEA_Core.Helper.AppSettings.Configuration["WCS_ReceiveTask"];
 
         /// <summary>
-        /// 鍑哄叆搴撶敵璇�
+        /// 鍑哄叆搴撶敵璇枫��
         /// </summary>
-        /// <param name="applyInOutDto">璇锋眰鍙傛暟</param>
-        /// <returns></returns>
         public async Task<AGVResponse> ApplyInOutAsync(ApplyInOutDto applyInOutDto)
         {
-            AGVResponse aGVResponse = new AGVResponse();
+            AGVResponse response = new AGVResponse();
+
             try
             {
-                // 鍙傛暟楠岃瘉
-                if (applyInOutDto == null) return aGVResponse.Error("璇锋眰鍙傛暟涓嶈兘涓虹┖");
-                if (string.IsNullOrWhiteSpace(applyInOutDto.TrayNumber)) return aGVResponse.Error("鎵樼洏鍙蜂笉鑳戒负绌�");
-                if (string.IsNullOrWhiteSpace(applyInOutDto.TaskId)) return aGVResponse.Error("浠诲姟鍙蜂笉鑳戒负绌�");
-                if (string.IsNullOrWhiteSpace(applyInOutDto.MaterialType)) return aGVResponse.Error("鐗╂枡绫诲瀷涓嶈兘涓虹┖");
-                if (string.IsNullOrWhiteSpace(applyInOutDto.MaterialName)) return aGVResponse.Error("鐗╂枡鎻忚堪涓嶈兘涓虹┖");
-                if (string.IsNullOrWhiteSpace(applyInOutDto.ReqTime)) return aGVResponse.Error("璇锋眰鏃堕棿涓嶈兘涓虹┖");
-                if (applyInOutDto.Floor != 1 && applyInOutDto.Floor != 2) return aGVResponse.Error($"妤煎眰娈甸敊璇紝蹇呴』涓�1(妯″垏娈�)鎴�2(鍗风粫娈�)锛屽綋鍓嶅�硷細{applyInOutDto.Floor}");
-                if (applyInOutDto.YinYang != 1 && applyInOutDto.YinYang != 2) return aGVResponse.Error($"闃撮槼鏋侀敊璇紝蹇呴』涓�1(闃存瀬)鎴�2(闃虫瀬)锛屽綋鍓嶅�硷細{applyInOutDto.YinYang}");
-                if (applyInOutDto.InOut != 1 && applyInOutDto.InOut != 2) return aGVResponse.Error($"鍑哄叆搴撶被鍨嬮敊璇紝蹇呴』涓�1(鍏ュ簱)鎴�2(鍑哄簱)锛屽綋鍓嶅�硷細{applyInOutDto.InOut}");
-                if (applyInOutDto.InOut == 1) // 鍏ュ簱
-                {
-                    if (applyInOutDto.Width == null || applyInOutDto.Width <= 0) return aGVResponse.Error("鍏ュ簱鏃跺搴︿笉鑳戒负绌轰笖蹇呴』澶т簬0");
-                    if (string.IsNullOrWhiteSpace(applyInOutDto.Group)) return aGVResponse.Error("鍏ュ簱鏃舵暣鎵樼粍鍒笉鑳戒负绌�");
-                }
-                // 妫�鏌ヤ换鍔℃槸鍚﹀凡瀛樺湪
+                var validationMessage = ValidateApplyInOutRequest(applyInOutDto);
+                if (validationMessage != null)
+                    return response.Error(validationMessage);
+
                 var existingTask = await BaseDal.QueryFirstAsync(x => x.PalletCode == applyInOutDto.TrayNumber);
-                if (existingTask != null) return aGVResponse.Error($"WMS宸叉湁褰撳墠浠诲姟锛屼笉鍙噸澶嶄笅鍙戯紝浠诲姟鍙凤細{applyInOutDto.TaskId}");
-                // 鍒涘缓浠诲姟
-                Dt_Task task = new Dt_Task
-                {
-                    OrderNo = applyInOutDto.TaskId, // 浣跨敤AGV鐨勪换鍔″彿
-                    PalletCode = applyInOutDto.TrayNumber,
-                    PalletType = applyInOutDto.Floor,
-                    //WarehouseId = applyInOutDto.YinYang,
-                    Grade = 1,
-                    Creater = "AGV",
-                    CreateDate = DateTime.Now,
-                    Remark = $"鐗╂枡绫诲瀷锛歿applyInOutDto.MaterialType}锛岀墿鏂欐弿杩帮細{applyInOutDto.MaterialName}"
-                };
-                // 鏍规嵁闃存瀬/闃虫瀬璁剧疆宸烽亾鍜岀珯鍙�
-                if (applyInOutDto.YinYang == 1) // 闃存瀬
-                {
-                    // 璐х墿鍒拌揪鍚庡垎閰嶈揣鐗╀綅
-                    task.Roadway = WarehouseEnum.FJ1.ToString();
-                    task.WarehouseId = (int)WarehouseEnum.FJ1;
-                    task.SourceAddress = applyInOutDto.InOut == 1 ? "D10010" : "D10020"; // 鍏ュ簱鍙�/鍑哄簱鍙�
-                    task.NextAddress = "D10080"; // 闃存瀬鍏叡鍑哄簱鍙�
-                    task.TargetAddress = "闃存瀬鍗峰簱";
-                }
-                else if (applyInOutDto.YinYang == 2) // 闃虫瀬
-                {
-                    task.Roadway = WarehouseEnum.ZJ1.ToString();
-                    task.WarehouseId = (int)WarehouseEnum.ZJ1;
-                    task.SourceAddress = applyInOutDto.InOut == 1 ? "D10100" : "D10090"; // 鍏ュ簱鍙�/鍑哄簱鍙�
-                    task.NextAddress = "D10160"; // 闃虫瀬鍏叡鍑哄簱鍙�
-                    task.TargetAddress = "姝f瀬鍗峰簱";
-                }
-                // 鏍规嵁鍑哄叆搴撶被鍨嬭缃洰鏍囧湴鍧�
-                if (applyInOutDto.InOut == 1) // 鍏ュ簱
-                {
-                    var stockInfo = await _stockInfoService.GetStockInfoAsync(applyInOutDto.TrayNumber);
-                    if (stockInfo != null) return aGVResponse.Error($"褰撳墠鎵樼洏{applyInOutDto.TrayNumber}宸茬粡鍏ュ簱浜�");
+                if (existingTask != null)
+                    return response.Error($"WMS宸叉湁褰撳墠浠诲姟锛屼笉鍙噸澶嶄笅鍙戯紝浠诲姟鍙凤細{applyInOutDto.TaskId}");
 
-                    task.TaskType = (int)TaskInboundTypeEnum.Inbound;
-                    task.TaskStatus = (int)TaskInStatusEnum.InNew;
-                    task.CurrentAddress = task.SourceAddress; // 褰撳墠鍦ㄥ叆搴撳彛
-                    // 淇濆瓨浠诲姟
-                    var result = await BaseDal.AddDataAsync(task);
-                }
-                else // 鍑哄簱
-                {
-                    // 鍒ゆ柇鏄惁绉诲簱
-                    task.TaskType = (int)TaskOutboundTypeEnum.Outbound;
-                    task.TaskStatus = (int)TaskOutStatusEnum.OutNew;
-                    task.CurrentAddress = task.SourceAddress; // 褰撳墠鍦ㄥ叆搴撳彛
-                    // 鏌ユ壘搴撳瓨
-                    var stockInfo = await _stockInfoService.GetStockInfoAsync(applyInOutDto.TrayNumber);
-                    if (stockInfo == null) return aGVResponse.Error($"鏈壘鍒版墭鐩榹applyInOutDto.TrayNumber}鐨勫簱瀛樹俊鎭�");
-                    // 楠岃瘉搴撳瓨鎵�灞炴槸鍚︽纭�
-                    if (stockInfo.WarehouseId != applyInOutDto.YinYang) return aGVResponse.Error($"鎵樼洏{applyInOutDto.TrayNumber}涓嶅睘浜庡綋鍓峽(applyInOutDto.YinYang == 1 ? "闃存瀬" : "闃虫瀬")}");
-                    if (stockInfo.StockStatus != (int)StockStatusEmun.鍏ュ簱瀹屾垚) return aGVResponse.Error($"鎵樼洏{applyInOutDto.TrayNumber}姝e湪绉诲姩涓紝璇风◢鍚庯紒");
-                    task.SourceAddress = stockInfo.LocationCode; // 婧愬湴鍧�涓鸿揣浣�
-                    task.CurrentAddress = stockInfo.LocationCode; // 褰撳墠浣嶇疆鍦ㄨ揣浣�
-                    task.TargetAddress = applyInOutDto.YinYang == 1 ? "D10020" : "D10090"; // 鐩爣鍦板潃涓哄嚭搴撳彛
+                var task = BuildAgvTask(applyInOutDto);
 
-                    // 淇濆瓨浠诲姟
-                    var result = await BaseDal.AddDataAsync(task);
-                    // 鍒ゆ柇鏄惁绉诲簱
-                    //var transferTask = await _locationInfoService.TransferCheckAsync(result);
+                if (applyInOutDto.InOut == 1)
+                {
+                    var inboundResult = await CreateAgvInboundTaskAsync(task, applyInOutDto);
+                    if (inboundResult != null)
+                        return inboundResult;
+                }
+                else
+                {
+                    var outboundResult = await CreateAgvOutboundTaskAsync(task, applyInOutDto);
+                    if (outboundResult != null)
+                        return outboundResult;
                 }
 
-                // 鏋勫缓鍝嶅簲鏁版嵁
-                AGVDataDto aGVDataDto = new AGVDataDto
-                {
-                    DevId = applyInOutDto.InOut == 1 ? task.SourceAddress : task.TargetAddress,
-                    TrayNumber = task.PalletCode,
-                    Group = applyInOutDto.Group,
-                    Width = applyInOutDto.Width ?? 0,
-                    LabelNumber = applyInOutDto.LabelNumber,
-                    ProductNo = applyInOutDto.ProductNo,
-                    ProductName = applyInOutDto.ProductName,
-                    Quantity = applyInOutDto.Quantity,
-                    UomCode = applyInOutDto.UomCode,
-                    ProductType = applyInOutDto.ProductType,
-                    Equipment = applyInOutDto.Equipment,
-                    ProductionDate = applyInOutDto.ProductionDate,
-                    LowerLimitTime = applyInOutDto.LowerLimitTime,
-                    WarningTime = applyInOutDto.WarningTime,
-                    OverdueTime = applyInOutDto.OverdueTime
-                };
-
-                return aGVResponse.OK(aGVDataDto);
+                return response.OK(BuildAgvDataDto(task, applyInOutDto));
             }
             catch (Exception ex)
             {
-                return aGVResponse.Error($"WMS浠诲姟鍒涘缓鎺ュ彛閿欒: {ex.Message}");
+                _unitOfWorkManage.RollbackTran();
+                return response.Error($"WMS浠诲姟鍒涘缓鎺ュ彛閿欒: {ex.Message}");
             }
         }
 
         /// <summary>
-        /// 鎵嬪姩鍑哄簱瀹屾垚鍙嶉缁橝GV
+        /// 鎵嬪姩鍑哄簱瀹屾垚鍙嶉缁橝GV銆�
         /// </summary>
-        /// <param name="outTaskCompleteDto">璇锋眰鍙傛暟</param>
-        /// <returns></returns>
         public async Task<WebResponseContent> OutTaskComplete(OutTaskCompleteDto outTaskCompleteDto)
         {
-            WebResponseContent webResponse = new WebResponseContent();
+            WebResponseContent response = new WebResponseContent();
+
             try
             {
-                if (outTaskCompleteDto == null) return webResponse.Error("璇锋眰鍙傛暟涓嶈兘涓虹┖");
-                if (string.IsNullOrWhiteSpace(outTaskCompleteDto.TaskId)) return webResponse.Error("浠诲姟鍙蜂笉鑳戒负绌�");
-                if (string.IsNullOrWhiteSpace(outTaskCompleteDto.DevId)) return webResponse.Error("鍑哄簱鍙g紪鍙蜂笉鑳戒负绌�");
+                var validationMessage = ValidateOutTaskCompleteRequest(outTaskCompleteDto);
+                if (validationMessage != null)
+                    return response.Error(validationMessage);
+
                 var task = await BaseDal.QueryFirstAsync(x => x.OrderNo == outTaskCompleteDto.TaskId);
-                if (task == null) return webResponse.Error("鏈壘鍒颁换鍔′俊鎭�");
+                if (task == null)
+                    return response.Error("鏈壘鍒颁换鍔′俊鎭�");
+
                 outTaskCompleteDto.ReqTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                 var httpResponse = _httpClientHelper.Post<AGVResponse>(AGV_OutTaskComplete, outTaskCompleteDto.ToJson()).Data;
-                // 鍒ゆ柇杩滅▼鎺ュ彛杩斿洖鏄惁鎴愬姛
-                if (httpResponse != null && httpResponse.Data != null)
-                {
-                    AGVResponse agvResponse = httpResponse;
-                    // 鏍规嵁code瀛楁鍒ゆ柇锛宑ode涓簍rue琛ㄧず鎴愬姛
-                    if (agvResponse.Code == true)
-                    {
-                        var stockInfo = await _stockInfoService.GetStockInfoAsync(task.PalletCode);
-                        if (stockInfo == null) return webResponse.Error($"鏈壘鍒版墭鐩榹task.PalletCode}鐨勫簱瀛樹俊鎭�");
-                        var locationInfo = await _locationInfoService.GetLocationInfoAsync(stockInfo.LocationCode);
-                        if (locationInfo == null) return webResponse.Error($"鏈壘鍒版墭鐩榹stockInfo.LocationCode}鐨勮揣浣嶄俊鎭�");
-                        if (stockInfo.StockStatus != (int)StockStatusEmun.鍑哄簱閿佸畾 || locationInfo.LocationStatus != (int)LocationStatusEnum.InStockLock)
-                        {
-                            return webResponse.Error($"褰撳墠搴撳瓨{stockInfo.StockStatus}鎴栬�呰揣浣峽locationInfo.LocationStatus}鐘舵�佷俊鎭敊璇�");
-                        }
-                        locationInfo.LocationStatus = (int)LocationStatusEnum.Free;
-                        _unitOfWorkManage.BeginTran();
-                        BaseDal.DeleteData(task);
-                        _locationInfoService.UpdateData(locationInfo);
-                        _stockInfoService.DeleteData(stockInfo);
-                        _unitOfWorkManage.CommitTran();
-                        return webResponse.OK(agvResponse.Msg);
-                    }
-                    else
-                    {
-                        // 澶辫触锛氳繑鍥濧GV杩斿洖鐨勯敊璇俊鎭�
-                        return webResponse.Error(string.IsNullOrWhiteSpace(agvResponse.Msg)
-                            ? "AGV鎺ュ彛璋冪敤澶辫触"
-                            : agvResponse.Msg);
-                    }
-                }
-                else
-                {
-                    // HTTP璇锋眰鏈韩澶辫触
-                    return webResponse.Error(httpResponse?.Msg ?? "AGV鎺ュ彛璋冪敤寮傚父");
-                }
+                if (httpResponse == null || httpResponse.Data == null)
+                    return response.Error(httpResponse?.Msg ?? "AGV鎺ュ彛璋冪敤寮傚父");
+
+                if (!httpResponse.Code)
+                    return response.Error(string.IsNullOrWhiteSpace(httpResponse.Msg) ? "AGV鎺ュ彛璋冪敤澶辫触" : httpResponse.Msg);
+
+                var syncResult = await CompleteLocalOutboundAfterAgvAckAsync(task);
+                return syncResult.Status ? response.OK(httpResponse.Msg) : syncResult;
             }
             catch (Exception ex)
             {
                 _unitOfWorkManage.RollbackTran();
-                return webResponse.Error($"WMS浠诲姟瀹屾垚鎺ュ彛閿欒锛歿ex.Message}");
+                return response.Error($"WMS浠诲姟瀹屾垚鎺ュ彛閿欒锛歿ex.Message}");
             }
         }
 
-        ///// <summary>
-        ///// 浠诲姟瀹屾垚鎺ュ彛
-        ///// </summary>
-        ///// <param name="wCSTask"></param>
-        ///// <returns></returns>
-        //public async Task<WebResponseContent> TaskCompleted(WCSTaskDTO wCSTask)
-        //{
-        //    WebResponseContent webResponse = new WebResponseContent();
-        //    try
-        //    {
-        //        Dt_Task task = await BaseDal.QueryFirstAsync(x => x.TaskId == wCSTask.TaskNum && x.PalletCode == wCSTask.PalletCode);
-        //        if (task == null) return webResponse.Error("鏈壘鍒颁换鍔′俊鎭�");
-        //        // 鍑哄簱瀹屾垚鍙嶉
-        //        OutTaskCompleteDto outTaskCompleteDto = new OutTaskCompleteDto()
-        //        {
-        //            TaskId = task.OrderNo,
-        //            DevId = task.TargetAddress,
-        //            ReqTime = DateTime.Now.ToString()
-        //        };
-        //        return await OutTaskComplete(outTaskCompleteDto);
-        //    }
-        //    catch (Exception ex)
-        //    {
-        //        return webResponse.Error($"WMS浠诲姟瀹屾垚鎺ュ彛閿欒锛歿ex.Message}");
-        //    }
-        //}
         /// <summary>
-        /// 杈撻�佺嚎鐢宠杩涘叆
+        /// 杈撻�佺嚎鐢宠杩涘叆銆�
         /// </summary>
-        /// <param name="applyEnterDto">璇锋眰鍙傛暟</param>
-        /// <returns></returns>
         public async Task<AGVResponse> ApplyEnterAsync(ApplyEnterDto applyEnterDto)
         {
-            AGVResponse aGVResponse = new AGVResponse();
+            AGVResponse response = new AGVResponse();
+
             try
             {
-                // 鍙傛暟楠岃瘉
-                if (applyEnterDto == null) return aGVResponse.Error("璇锋眰鍙傛暟涓嶈兘涓虹┖");
-                if (string.IsNullOrWhiteSpace(applyEnterDto.DevId)) return aGVResponse.Error("璁惧缂栧彿涓嶈兘涓虹┖");
-                if (string.IsNullOrWhiteSpace(applyEnterDto.TaskId)) return aGVResponse.Error("浠诲姟鍙蜂笉鑳戒负绌�");
-                if (applyEnterDto.InOut != 1 && applyEnterDto.InOut != 2) return aGVResponse.Error($"鍑哄叆搴撶被鍨嬮敊璇紝蹇呴』涓�1(鍏ュ簱)鎴�2(鍑哄簱)锛屽綋鍓嶅�硷細{applyEnterDto.InOut}");
+                var validationMessage = ValidateApplyEnterRequest(applyEnterDto);
+                if (validationMessage != null)
+                    return response.Error(validationMessage);
 
-                // 鏌ヨ浠诲姟鏄惁瀛樺湪
                 var task = await BaseDal.QueryFirstAsync(x => x.OrderNo == applyEnterDto.TaskId);
-                if (task == null) return aGVResponse.Error($"鏈壘鍒颁换鍔′俊鎭紝浠诲姟鍙凤細{applyEnterDto.TaskId}");
-                if (applyEnterDto.InOut == 1 && task.TaskType == (int)TaskInboundTypeEnum.Inbound && task.TaskStatus == (int)TaskInStatusEnum.InNew)
-                {
-                    aGVResponse.OK();
-                }
-                else if (applyEnterDto.InOut == 2 && task.TaskType == (int)TaskOutboundTypeEnum.Outbound && task.TaskStatus == (int)TaskStatusEnum.Line_Finish)
-                {
-                    aGVResponse.OK();
-                }
-                return aGVResponse.Error($"杈撻�佺嚎{applyEnterDto.DevId}褰撳墠绻佸繖锛岃绋嶅悗閲嶈瘯");
+                if (task == null)
+                    return response.Error($"鏈壘鍒颁换鍔′俊鎭紝浠诲姟鍙凤細{applyEnterDto.TaskId}");
 
-                // Dt_Task.SourceAddress璇㈤棶wcs绔欏彴1-闃存瀬鍏ュ彛鍙獶10010鍜孌10020锛�2-闃虫瀬D10090鍜孌10100鏄惁鏈夎揣鐗�
-                //var httpResponse = _httpClientHelper.Post<WebResponseContent>("http://127.0.0.1:9999/api/Task/ApplyInOut", JsonSerializer.Serialize(task)).Data;
-                //if (httpResponse != null && httpResponse.Status == true)
-                //{
-                //    _unitOfWorkManage.BeginTran();
-                //    task.TaskStatus = (int)TaskStatusEnum.AGV_Executing;
-                //    await BaseDal.UpdateDataAsync(task);
-                //    _unitOfWorkManage.CommitTran();
-                //    return aGVResponse.OK();
-                //}
-                //else
-                //{
-                //    return aGVResponse.Error($"绔欏彴{task.SourceAddress}宸茬粡杞借揣");
-                //}
+                if (CanApplyEnter(task, applyEnterDto))
+                    return response.OK();
+
+                return response.Error($"杈撻�佺嚎{applyEnterDto.DevId}褰撳墠绻佸繖锛岃绋嶅悗閲嶈瘯");
             }
             catch (Exception ex)
             {
-                //_unitOfWorkManage.RollbackTran();
-                return aGVResponse.Error($"WMS杈撻�佺嚎鐢宠鎺ュ彛閿欒锛歿ex.Message}");
+                return response.Error($"WMS杈撻�佺嚎鐢宠鎺ュ彛閿欒锛歿ex.Message}");
             }
         }
 
         /// <summary>
-        /// 鍙栨斁璐у畬鎴�
+        /// 鍙栨斁璐у畬鎴愩��
         /// </summary>
-        /// <param name="taskCompleteDto">璇锋眰鍙傛暟</param>
-        /// <returns></returns>
         public async Task<AGVResponse> TaskCompleteAsync(TaskCompleteDto taskCompleteDto)
         {
-            AGVResponse aGVResponse = new AGVResponse();
+            AGVResponse response = new AGVResponse();
+
             try
             {
-                if (taskCompleteDto == null) return aGVResponse.Error("璇锋眰鍙傛暟涓嶈兘涓虹┖");
-                if (string.IsNullOrWhiteSpace(taskCompleteDto.TaskId)) return aGVResponse.Error("浠诲姟鍙蜂笉鑳戒负绌�");
-                if (string.IsNullOrWhiteSpace(taskCompleteDto.DevId)) return aGVResponse.Error("璁惧缂栧彿涓嶈兘涓虹┖");
-                if (taskCompleteDto.InOut != 1 && taskCompleteDto.InOut != 2) return aGVResponse.Error($"鍑哄叆搴撶被鍨嬮敊璇紝蹇呴』涓�1(鍏ュ簱)鎴�2(鍑哄簱)锛屽綋鍓嶅�硷細{taskCompleteDto.InOut}");
+                var validationMessage = ValidateTaskCompleteRequest(taskCompleteDto);
+                if (validationMessage != null)
+                    return response.Error(validationMessage);
+
                 var task = await BaseDal.QueryFirstAsync(x => x.OrderNo == taskCompleteDto.TaskId);
-                if (task == null) return aGVResponse.Error($"鏈壘鍒颁换鍔′俊鎭紝浠诲姟鍙凤細{taskCompleteDto.TaskId}");
-                if (taskCompleteDto.InOut == 2)
-                {
-                    var stockInfo = await _stockInfoService.GetStockInfoAsync(task.PalletCode);
-                    if (stockInfo == null) return aGVResponse.Error($"鏈壘鍒版墭鐩榹task.PalletCode}鐨勫簱瀛樹俊鎭�");
-                    var locationInfo = await _locationInfoService.GetLocationInfoAsync(stockInfo.LocationCode);
-                    if (locationInfo == null) return aGVResponse.Error($"鏈壘鍒版墭鐩榹stockInfo.LocationCode}鐨勮揣浣嶄俊鎭�");
-                    if (stockInfo.StockStatus != (int)StockStatusEmun.鍑哄簱閿佸畾 || locationInfo.LocationStatus != (int)LocationStatusEnum.InStockLock)
-                    {
-                        return aGVResponse.Error($"褰撳墠搴撳瓨{stockInfo.StockStatus}鎴栬�呰揣浣峽locationInfo.LocationStatus}鐘舵�佷俊鎭敊璇�");
-                    }
-                    locationInfo.LocationStatus = (int)LocationStatusEnum.Free;
-                    task.TaskStatus = (int)TaskOutStatusEnum.OutFinish;
-                    _unitOfWorkManage.BeginTran();
-                    _stockInfoService.DeleteData(stockInfo);
-                    await _locationInfoService.UpdateLocationInfoAsync(locationInfo);
-                    BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
-                    _unitOfWorkManage.CommitTran();
-                }
-                else
-                {
-                    //鏌ユ壘鍙敤璐т綅
-                    var availableLocation = await _locationInfoService.GetLocationInfo(task.Roadway);
+                if (task == null)
+                    return response.Error($"鏈壘鍒颁换鍔′俊鎭紝浠诲姟鍙凤細{taskCompleteDto.TaskId}");
 
-                    if (availableLocation == null) return aGVResponse.Error("鏃犲彲鐢ㄧ殑鍏ュ簱璐т綅");
-
-                    task.TargetAddress = availableLocation.LocationCode;
-                    // 閫氱煡WCS鍏ュ簱
-                    var wcsTaskDto = _mapper.Map<WCSTaskDTO>(task);
-                    var httpResponse = _httpClientHelper.Post<WebResponseContent>(WCS_ReceiveTask, JsonSerializer.Serialize(wcsTaskDto));
-                    if (httpResponse == null) return aGVResponse.Error("涓嬪彂WCS澶辫触");
-
-                    task.TaskStatus = (int)TaskStatusEnum.Line_Executing;
-                    task.Dispatchertime = DateTime.Now;
-                    var locationInfo = await _locationInfoService.GetLocationInfoAsync(task.TargetAddress);
-                    if (locationInfo == null) return aGVResponse.Error($"鏈壘鍒版墭鐩榹task.TargetAddress}鐨勮揣浣嶄俊鎭�");
-                    if (locationInfo.LocationStatus != (int)LocationStatusEnum.InStock)
-                    {
-                        return aGVResponse.Error($"褰撳墠璐т綅{locationInfo.LocationStatus}鐘舵�佷俊鎭敊璇�");
-                    }
-                    Dt_StockInfo dt_Stock = new Dt_StockInfo()
-                    {
-                        PalletCode = task.PalletCode,
-                        StockStatus = (int)StockStatusEmun.鍏ュ簱纭,
-                        LocationCode = locationInfo.LocationCode,
-                        WarehouseId = task.WarehouseId,
-                        Creater = "AGV",
-                        CreateDate = DateTime.Now
-                    };
-                    locationInfo.LocationStatus = (int)LocationStatusEnum.FreeLock;
-                    _unitOfWorkManage.BeginTran();
-                    BaseDal.UpdateData(task);
-                    _locationInfoService.UpdateData(locationInfo);
-                    _stockInfoService.AddData(dt_Stock);
-                    _unitOfWorkManage.CommitTran();
-                }
-                return aGVResponse.OK();
+                return taskCompleteDto.InOut == 2
+                    ? await CompleteAgvOutboundTaskAsync(task)
+                    : await CompleteAgvInboundTaskAsync(task);
             }
             catch (Exception ex)
             {
                 _unitOfWorkManage.RollbackTran();
-                return aGVResponse.Error($"WMS鍙栨斁璐у畬鎴愭帴鍙i敊璇細{ex.Message}");
+                return response.Error($"WMS鍙栨斁璐у畬鎴愭帴鍙i敊璇細{ex.Message}");
             }
         }
 
         /// <summary>
-        /// 浠诲姟鍙栨秷
+        /// 浠诲姟鍙栨秷銆�
         /// </summary>
-        /// <param name="taskCancelDto">璇锋眰鍙傛暟</param>
-        /// <returns></returns>
         public async Task<AGVResponse> TaskCancelAsync(TaskCancelDto taskCancelDto)
         {
-            AGVResponse aGVResponse = new AGVResponse();
+            AGVResponse response = new AGVResponse();
+
             try
             {
-                if (taskCancelDto == null) return aGVResponse.Error("璇锋眰鍙傛暟涓嶈兘涓虹┖");
-                if (string.IsNullOrWhiteSpace(taskCancelDto.TaskId)) return aGVResponse.Error("浠诲姟鍙蜂笉鑳戒负绌�");
+                var validationMessage = ValidateTaskCancelRequest(taskCancelDto);
+                if (validationMessage != null)
+                    return response.Error(validationMessage);
 
                 var task = await BaseDal.QueryFirstAsync(x => x.OrderNo == taskCancelDto.TaskId);
-                // 娌℃湁浠诲姟寮哄埗鍙栨秷
-                if (task == null) return aGVResponse.OK();
+                if (task == null)
+                    return response.OK();
 
                 if (task.TaskStatus == (int)TaskInStatusEnum.InNew)
-                {
-                    task.TaskStatus = (int)TaskInStatusEnum.InCancel;
-                    // 鍏ュ簱浠诲姟鐩存帴鍒犻櫎
-                    _unitOfWorkManage.BeginTran();
-                    BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
-                    _unitOfWorkManage.CommitTran();
-                    return aGVResponse.OK();
-                }
-                else if (task.TaskStatus == (int)TaskOutStatusEnum.OutNew)
-                {
-                    // 鍑哄簱浠诲姟鎭㈠搴撳瓨
-                    var stockInfo = await _stockInfoService.GetStockInfoAsync(task.PalletCode);
-                    if (stockInfo == null) return aGVResponse.Error($"鏈壘鍒版墭鐩榹task.PalletCode}鐨勫簱瀛樹俊鎭�");
-                    var locationInfo = await _locationInfoService.GetLocationInfoAsync(stockInfo.LocationCode);
-                    if (locationInfo == null) return aGVResponse.Error($"鏈壘鍒版墭鐩榹stockInfo.LocationCode}鐨勮揣浣嶄俊鎭�");
-                    if (stockInfo.StockStatus != (int)StockStatusEmun.鍑哄簱閿佸畾 || locationInfo.LocationStatus != (int)LocationStatusEnum.InStockLock)
-                    {
-                        return aGVResponse.Error($"褰撳墠搴撳瓨{stockInfo.StockStatus}鎴栬�呰揣浣峽locationInfo.LocationStatus}鐘舵�佷俊鎭敊璇�");
-                    }
-                    stockInfo.StockStatus = (int)StockStatusEmun.鍏ュ簱瀹屾垚;
-                    locationInfo.LocationStatus = (int)LocationStatusEnum.InStock;
-                    task.TaskStatus = (int)TaskOutStatusEnum.OutCancel;
-                    _unitOfWorkManage.BeginTran();
-                    _locationInfoService.UpdateData(locationInfo);
-                    _stockInfoService.UpdateData(stockInfo);
-                    BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
-                    _unitOfWorkManage.CommitTran();
-                    return aGVResponse.OK();
-                }
-                return aGVResponse.Error("浠诲姟宸茬粡鍦ㄦ墽琛屼腑锛屼笉鍙彇娑�");
+                    return CancelAgvInboundTask(task);
+
+                if (task.TaskStatus == (int)TaskOutStatusEnum.OutNew)
+                    return await CancelAgvOutboundTaskAsync(task);
+
+                return response.Error("浠诲姟宸茬粡鍦ㄦ墽琛屼腑锛屼笉鍙彇娑�");
             }
             catch (Exception ex)
             {
                 _unitOfWorkManage.RollbackTran();
-                return aGVResponse.Error($"WMS浠诲姟鍙栨秷鎺ュ彛閿欒锛歿ex.Message}");
+                return response.Error($"WMS浠诲姟鍙栨秷鎺ュ彛閿欒锛歿ex.Message}");
             }
         }
 
+        private static string? ValidateApplyInOutRequest(ApplyInOutDto dto)
+        {
+            if (dto == null) return "璇锋眰鍙傛暟涓嶈兘涓虹┖";
+            if (string.IsNullOrWhiteSpace(dto.TrayNumber)) return "鎵樼洏鍙蜂笉鑳戒负绌�";
+            if (string.IsNullOrWhiteSpace(dto.TaskId)) return "浠诲姟鍙蜂笉鑳戒负绌�";
+            if (string.IsNullOrWhiteSpace(dto.MaterialType)) return "鐗╂枡绫诲瀷涓嶈兘涓虹┖";
+            if (string.IsNullOrWhiteSpace(dto.MaterialName)) return "鐗╂枡鎻忚堪涓嶈兘涓虹┖";
+            if (string.IsNullOrWhiteSpace(dto.ReqTime)) return "璇锋眰鏃堕棿涓嶈兘涓虹┖";
+            if (dto.Floor != 1 && dto.Floor != 2) return $"妤煎眰娈甸敊璇紝蹇呴』涓�1(妯″垏娈�)鎴�2(鍗风粫娈�)锛屽綋鍓嶅�硷細{dto.Floor}";
+            if (dto.YinYang != 1 && dto.YinYang != 2) return $"闃撮槼鏋侀敊璇紝蹇呴』涓�1(闃存瀬)鎴�2(闃虫瀬)锛屽綋鍓嶅�硷細{dto.YinYang}";
+            if (dto.InOut != 1 && dto.InOut != 2) return $"鍑哄叆搴撶被鍨嬮敊璇紝蹇呴』涓�1(鍏ュ簱)鎴�2(鍑哄簱)锛屽綋鍓嶅�硷細{dto.InOut}";
+            if (dto.InOut == 1 && (dto.Width == null || dto.Width <= 0)) return "鍏ュ簱鏃跺搴︿笉鑳戒负绌轰笖蹇呴』澶т簬0";
+            if (dto.InOut == 1 && string.IsNullOrWhiteSpace(dto.Group)) return "鍏ュ簱鏃舵暣鎵樼粍鍒笉鑳戒负绌�";
+            return null;
+        }
+
+        private static string? ValidateOutTaskCompleteRequest(OutTaskCompleteDto dto)
+        {
+            if (dto == null) return "璇锋眰鍙傛暟涓嶈兘涓虹┖";
+            if (string.IsNullOrWhiteSpace(dto.TaskId)) return "浠诲姟鍙蜂笉鑳戒负绌�";
+            if (string.IsNullOrWhiteSpace(dto.DevId)) return "鍑哄簱鍙g紪鍙蜂笉鑳戒负绌�";
+            return null;
+        }
+
+        private static string? ValidateApplyEnterRequest(ApplyEnterDto dto)
+        {
+            if (dto == null) return "璇锋眰鍙傛暟涓嶈兘涓虹┖";
+            if (string.IsNullOrWhiteSpace(dto.DevId)) return "璁惧缂栧彿涓嶈兘涓虹┖";
+            if (string.IsNullOrWhiteSpace(dto.TaskId)) return "浠诲姟鍙蜂笉鑳戒负绌�";
+            if (dto.InOut != 1 && dto.InOut != 2) return $"鍑哄叆搴撶被鍨嬮敊璇紝蹇呴』涓�1(鍏ュ簱)鎴�2(鍑哄簱)锛屽綋鍓嶅�硷細{dto.InOut}";
+            return null;
+        }
+
+        private static string? ValidateTaskCompleteRequest(TaskCompleteDto dto)
+        {
+            if (dto == null) return "璇锋眰鍙傛暟涓嶈兘涓虹┖";
+            if (string.IsNullOrWhiteSpace(dto.TaskId)) return "浠诲姟鍙蜂笉鑳戒负绌�";
+            if (string.IsNullOrWhiteSpace(dto.DevId)) return "璁惧缂栧彿涓嶈兘涓虹┖";
+            if (dto.InOut != 1 && dto.InOut != 2) return $"鍑哄叆搴撶被鍨嬮敊璇紝蹇呴』涓�1(鍏ュ簱)鎴�2(鍑哄簱)锛屽綋鍓嶅�硷細{dto.InOut}";
+            return null;
+        }
+
+        private static string? ValidateTaskCancelRequest(TaskCancelDto dto)
+        {
+            if (dto == null) return "璇锋眰鍙傛暟涓嶈兘涓虹┖";
+            if (string.IsNullOrWhiteSpace(dto.TaskId)) return "浠诲姟鍙蜂笉鑳戒负绌�";
+            return null;
+        }
+
+        private Dt_Task BuildAgvTask(ApplyInOutDto dto)
+        {
+            var task = new Dt_Task
+            {
+                OrderNo = dto.TaskId,
+                PalletCode = dto.TrayNumber,
+                PalletType = dto.Floor,
+                Grade = 1,
+                Creater = "AGV",
+                CreateDate = DateTime.Now,
+                Remark = $"鐗╂枡绫诲瀷锛歿dto.MaterialType}锛岀墿鏂欐弿杩帮細{dto.MaterialName}"
+            };
+
+            if (dto.YinYang == 1)
+            {
+                task.Roadway = WarehouseEnum.FJ1.ToString();
+                task.WarehouseId = (int)WarehouseEnum.FJ1;
+                task.SourceAddress = dto.InOut == 1 ? "D10010" : "D10020";
+                task.NextAddress = "D10080";
+                task.TargetAddress = "闃存瀬鍗峰簱";
+            }
+            else
+            {
+                task.Roadway = WarehouseEnum.ZJ1.ToString();
+                task.WarehouseId = (int)WarehouseEnum.ZJ1;
+                task.SourceAddress = dto.InOut == 1 ? "D10100" : "D10090";
+                task.NextAddress = "D10160";
+                task.TargetAddress = "姝f瀬鍗峰簱";
+            }
+
+            return task;
+        }
+
+        private AGVDataDto BuildAgvDataDto(Dt_Task task, ApplyInOutDto dto)
+        {
+            return new AGVDataDto
+            {
+                DevId = dto.InOut == 1 ? task.SourceAddress : task.TargetAddress,
+                TrayNumber = task.PalletCode,
+                Group = dto.Group,
+                Width = dto.Width ?? 0,
+                LabelNumber = dto.LabelNumber,
+                ProductNo = dto.ProductNo,
+                ProductName = dto.ProductName,
+                Quantity = dto.Quantity,
+                UomCode = dto.UomCode,
+                ProductType = dto.ProductType,
+                Equipment = dto.Equipment,
+                ProductionDate = dto.ProductionDate,
+                LowerLimitTime = dto.LowerLimitTime,
+                WarningTime = dto.WarningTime,
+                OverdueTime = dto.OverdueTime
+            };
+        }
+
+        private async Task<AGVResponse?> CreateAgvInboundTaskAsync(Dt_Task task, ApplyInOutDto dto)
+        {
+            AGVResponse response = new AGVResponse();
+            var stockInfo = await _stockInfoService.GetStockInfoAsync(dto.TrayNumber);
+            if (stockInfo != null)
+                return response.Error($"褰撳墠鎵樼洏{dto.TrayNumber}宸茬粡鍏ュ簱浜�");
+
+            task.TaskType = (int)TaskInboundTypeEnum.Inbound;
+            task.TaskStatus = (int)TaskInStatusEnum.InNew;
+            task.CurrentAddress = task.SourceAddress;
+
+            var addResult = await BaseDal.AddDataAsync(task) > 0;
+            return addResult ? null : response.Error("鍏ュ簱浠诲姟鍒涘缓澶辫触");
+        }
+
+        private async Task<AGVResponse?> CreateAgvOutboundTaskAsync(Dt_Task task, ApplyInOutDto dto)
+        {
+            AGVResponse response = new AGVResponse();
+            var stockInfo = await _stockInfoService.GetStockInfoAsync(dto.TrayNumber);
+            if (stockInfo == null)
+                return response.Error($"鏈壘鍒版墭鐩榹dto.TrayNumber}鐨勫簱瀛樹俊鎭�");
+
+            if (stockInfo.WarehouseId != dto.YinYang)
+                return response.Error($"鎵樼洏{dto.TrayNumber}涓嶅睘浜庡綋鍓峽(dto.YinYang == 1 ? "闃存瀬" : "闃虫瀬")}");
+
+            if (stockInfo.StockStatus != (int)StockStatusEmun.鍏ュ簱瀹屾垚)
+                return response.Error($"鎵樼洏{dto.TrayNumber}姝e湪绉诲姩涓紝璇风◢鍚庯紒");
+
+            var locationInfo = await _locationInfoService.GetLocationInfoAsync(stockInfo.LocationCode);
+            if (locationInfo == null)
+                return response.Error($"鏈壘鍒版墭鐩榹stockInfo.LocationCode}鐨勮揣浣嶄俊鎭�");
+
+            if (locationInfo.LocationStatus != (int)LocationStatusEnum.InStock)
+                return response.Error($"褰撳墠璐т綅{locationInfo.LocationStatus}鐘舵�佷俊鎭敊璇�");
+
+            task.TaskType = (int)TaskOutboundTypeEnum.Outbound;
+            task.TaskStatus = (int)TaskOutStatusEnum.OutNew;
+            task.SourceAddress = stockInfo.LocationCode;
+            task.CurrentAddress = stockInfo.LocationCode;
+            task.TargetAddress = dto.YinYang == 1 ? "D10020" : "D10090";
+
+            stockInfo.StockStatus = (int)StockStatusEmun.鍑哄簱閿佸畾;
+            locationInfo.LocationStatus = (int)LocationStatusEnum.InStockLock;
+
+            _unitOfWorkManage.BeginTran();
+            var addTaskResult = await BaseDal.AddDataAsync(task) > 0;
+            var updateLocationResult = await _locationInfoService.UpdateLocationInfoAsync(locationInfo);
+            var updateStockResult = await _stockInfoService.UpdateStockAsync(stockInfo);
+            if (!addTaskResult || !updateLocationResult || !updateStockResult)
+            {
+                _unitOfWorkManage.RollbackTran();
+                return response.Error("鍑哄簱浠诲姟鍒涘缓澶辫触");
+            }
+
+            _unitOfWorkManage.CommitTran();
+            return null;
+        }
+
+        private async Task<WebResponseContent> CompleteLocalOutboundAfterAgvAckAsync(Dt_Task task)
+        {
+            var stockInfo = await _stockInfoService.GetStockInfoAsync(task.PalletCode);
+            if (stockInfo == null)
+                return WebResponseContent.Instance.Error($"鏈壘鍒版墭鐩榹task.PalletCode}鐨勫簱瀛樹俊鎭�");
+
+            var locationInfo = await _locationInfoService.GetLocationInfoAsync(stockInfo.LocationCode);
+            if (locationInfo == null)
+                return WebResponseContent.Instance.Error($"鏈壘鍒版墭鐩榹stockInfo.LocationCode}鐨勮揣浣嶄俊鎭�");
+
+            if (stockInfo.StockStatus != (int)StockStatusEmun.鍑哄簱閿佸畾 || locationInfo.LocationStatus != (int)LocationStatusEnum.InStockLock)
+                return WebResponseContent.Instance.Error($"褰撳墠搴撳瓨{stockInfo.StockStatus}鎴栬�呰揣浣峽locationInfo.LocationStatus}鐘舵�佷俊鎭敊璇�");
+
+            locationInfo.LocationStatus = (int)LocationStatusEnum.Free;
+
+            _unitOfWorkManage.BeginTran();
+            var deleteTaskResult = BaseDal.DeleteData(task);
+            var updateLocationResult = _locationInfoService.UpdateData(locationInfo);
+            var deleteStockResult = _stockInfoService.DeleteData(stockInfo);
+            if (!deleteTaskResult || !updateLocationResult.Status || !deleteStockResult.Status)
+            {
+                _unitOfWorkManage.RollbackTran();
+                return WebResponseContent.Instance.Error("AGV瀹屾垚鍥炰紶鍚庯紝鏈湴浠诲姟/搴撳瓨/璐т綅鏇存柊澶辫触");
+            }
+
+            _unitOfWorkManage.CommitTran();
+            return WebResponseContent.Instance.OK();
+        }
+
+        private bool CanApplyEnter(Dt_Task task, ApplyEnterDto dto)
+        {
+            return dto.InOut == 1
+                ? task.TaskType == (int)TaskInboundTypeEnum.Inbound && task.TaskStatus == (int)TaskInStatusEnum.InNew
+                : task.TaskType == (int)TaskOutboundTypeEnum.Outbound && task.TaskStatus == (int)TaskStatusEnum.Line_Finish;
+        }
+
+        private async Task<AGVResponse> CompleteAgvOutboundTaskAsync(Dt_Task task)
+        {
+            AGVResponse response = new AGVResponse();
+            var stockInfo = await _stockInfoService.GetStockInfoAsync(task.PalletCode);
+            if (stockInfo == null)
+                return response.Error($"鏈壘鍒版墭鐩榹task.PalletCode}鐨勫簱瀛樹俊鎭�");
+
+            var locationInfo = await _locationInfoService.GetLocationInfoAsync(stockInfo.LocationCode);
+            if (locationInfo == null)
+                return response.Error($"鏈壘鍒版墭鐩榹stockInfo.LocationCode}鐨勮揣浣嶄俊鎭�");
+
+            if (stockInfo.StockStatus != (int)StockStatusEmun.鍑哄簱閿佸畾 || locationInfo.LocationStatus != (int)LocationStatusEnum.InStockLock)
+                return response.Error($"褰撳墠搴撳瓨{stockInfo.StockStatus}鎴栬�呰揣浣峽locationInfo.LocationStatus}鐘舵�佷俊鎭敊璇�");
+
+            locationInfo.LocationStatus = (int)LocationStatusEnum.Free;
+            task.TaskStatus = (int)TaskOutStatusEnum.OutFinish;
+
+            _unitOfWorkManage.BeginTran();
+            var deleteStockResult = _stockInfoService.DeleteData(stockInfo);
+            var updateLocationResult = await _locationInfoService.UpdateLocationInfoAsync(locationInfo);
+            BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
+            if (!deleteStockResult.Status || !updateLocationResult)
+            {
+                _unitOfWorkManage.RollbackTran();
+                return response.Error("鍑哄簱瀹屾垚鍚庯紝鏈湴搴撳瓨鎴栬揣浣嶆洿鏂板け璐�");
+            }
+
+            _unitOfWorkManage.CommitTran();
+            return response.OK();
+        }
+
+        private async Task<AGVResponse> CompleteAgvInboundTaskAsync(Dt_Task task)
+        {
+            AGVResponse response = new AGVResponse();
+            var availableLocation = await _locationInfoService.GetLocationInfo(task.Roadway);
+            if (availableLocation == null)
+                return response.Error("鏃犲彲鐢ㄧ殑鍏ュ簱璐т綅");
+
+            task.TargetAddress = availableLocation.LocationCode;
+
+            var wcsTaskDto = _mapper.Map<WCSTaskDTO>(task);
+            var httpResponse = _httpClientHelper.Post<WebResponseContent>(WCS_ReceiveTask, JsonSerializer.Serialize(wcsTaskDto));
+            if (httpResponse == null || httpResponse.Data == null || !httpResponse.Data.Status)
+                return response.Error(httpResponse?.Data?.Message ?? "涓嬪彂WCS澶辫触");
+
+            task.TaskStatus = (int)TaskStatusEnum.Line_Executing;
+            task.Dispatchertime = DateTime.Now;
+
+            var locationInfo = await _locationInfoService.GetLocationInfoAsync(task.TargetAddress);
+            if (locationInfo == null)
+                return response.Error($"鏈壘鍒版墭鐩榹task.TargetAddress}鐨勮揣浣嶄俊鎭�");
+
+            if (locationInfo.LocationStatus != (int)LocationStatusEnum.Free)
+                return response.Error($"褰撳墠璐т綅{locationInfo.LocationStatus}鐘舵�佷俊鎭敊璇�");
+
+            Dt_StockInfo stockInfo = new Dt_StockInfo
+            {
+                PalletCode = task.PalletCode,
+                StockStatus = (int)StockStatusEmun.鍏ュ簱纭,
+                LocationCode = locationInfo.LocationCode,
+                WarehouseId = task.WarehouseId,
+                Creater = "AGV",
+                CreateDate = DateTime.Now
+            };
+
+            locationInfo.LocationStatus = (int)LocationStatusEnum.FreeLock;
+
+            _unitOfWorkManage.BeginTran();
+            var updateTaskResult = BaseDal.UpdateData(task);
+            var updateLocationResult = _locationInfoService.UpdateData(locationInfo);
+            var addStockResult = _stockInfoService.AddData(stockInfo);
+            if (!updateTaskResult || !updateLocationResult.Status || !addStockResult.Status)
+            {
+                _unitOfWorkManage.RollbackTran();
+                return response.Error("鍏ュ簱瀹屾垚鍚庯紝鏈湴浠诲姟銆佸簱瀛樻垨璐т綅鏇存柊澶辫触");
+            }
+
+            _unitOfWorkManage.CommitTran();
+            return response.OK();
+        }
+
+        private AGVResponse CancelAgvInboundTask(Dt_Task task)
+        {
+            AGVResponse response = new AGVResponse();
+            task.TaskStatus = (int)TaskInStatusEnum.InCancel;
+
+            _unitOfWorkManage.BeginTran();
+            BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
+            _unitOfWorkManage.CommitTran();
+            return response.OK();
+        }
+
+        private async Task<AGVResponse> CancelAgvOutboundTaskAsync(Dt_Task task)
+        {
+            AGVResponse response = new AGVResponse();
+            var stockInfo = await _stockInfoService.GetStockInfoAsync(task.PalletCode);
+            if (stockInfo == null)
+                return response.Error($"鏈壘鍒版墭鐩榹task.PalletCode}鐨勫簱瀛樹俊鎭�");
+
+            var locationInfo = await _locationInfoService.GetLocationInfoAsync(stockInfo.LocationCode);
+            if (locationInfo == null)
+                return response.Error($"鏈壘鍒版墭鐩榹stockInfo.LocationCode}鐨勮揣浣嶄俊鎭�");
+
+            if (stockInfo.StockStatus != (int)StockStatusEmun.鍑哄簱閿佸畾 || locationInfo.LocationStatus != (int)LocationStatusEnum.InStockLock)
+                return response.Error($"褰撳墠搴撳瓨{stockInfo.StockStatus}鎴栬�呰揣浣峽locationInfo.LocationStatus}鐘舵�佷俊鎭敊璇�");
+
+            stockInfo.StockStatus = (int)StockStatusEmun.鍏ュ簱瀹屾垚;
+            locationInfo.LocationStatus = (int)LocationStatusEnum.InStock;
+            task.TaskStatus = (int)TaskOutStatusEnum.OutCancel;
+
+            _unitOfWorkManage.BeginTran();
+            var updateLocationResult = _locationInfoService.UpdateData(locationInfo);
+            var updateStockResult = _stockInfoService.UpdateData(stockInfo);
+            BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? OperateTypeEnum.鑷姩瀹屾垚 : OperateTypeEnum.浜哄伐瀹屾垚);
+            if (!updateLocationResult.Status || !updateStockResult.Status)
+            {
+                _unitOfWorkManage.RollbackTran();
+                return response.Error("鍑哄簱浠诲姟鍙栨秷澶辫触");
+            }
+
+            _unitOfWorkManage.CommitTran();
+            return response.OK();
+        }
+
         #endregion 鏋佸嵎搴撲换鍔℃ā鍧�
     }
 }
diff --git a/Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService_WCS.cs b/Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService_WCS.cs
index 76a54ef..4ee2d5b 100644
--- a/Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService_WCS.cs
+++ b/Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService_WCS.cs
@@ -249,8 +249,8 @@
                 {
                     OutTaskCompleteDto outTaskCompleteDto = new OutTaskCompleteDto()
                     {
-                        TaskId = task.OrderNo,
-                        DevId = task.TargetAddress,
+                        TaskId = task.OrderNo ?? string.Empty,
+                        DevId = task.TargetAddress ?? string.Empty,
                         ReqTime = DateTime.Now.ToString()
                     };
                     return await OutTaskComplete(outTaskCompleteDto);
@@ -260,7 +260,7 @@
                 return await ExecuteWithinTransactionAsync(async () =>
                 {
                     stockInfo.LocationId = 0;
-                    stockInfo.LocationCode = null;
+                    stockInfo.LocationCode = string.Empty;
                     stockInfo.OutboundDate = DateTime.Now;
 
                     location.LocationStatus = LocationStatusEnum.Free.GetHashCode();
@@ -396,19 +396,13 @@
                     if (!updateLocationResult || !updateStockResult)
                         return WebResponseContent.Instance.Error("浠诲姟瀹屾垚澶辫触");
 
-                    // 淇濆瓨浠诲姟鍘嗗彶
-                    var historyTask = _mapper.Map<Dt_Task_Hty>(task);
-                    historyTask.InsertTime = DateTime.Now;
-                    historyTask.OperateType = "绌烘墭鐩樺叆搴撳畬鎴�";
-                    if (await _task_HtyService.Repository.AddDataAsync(historyTask) <= 0)
-                        return WebResponseContent.Instance.Error("浠诲姟鍘嗗彶淇濆瓨澶辫触");
+                    var saveTaskHistoryResult = await SaveTaskHistoryAsync(task, "绌烘墭鐩樺叆搴撳畬鎴�");
+                    if (!saveTaskHistoryResult.Status)
+                        return saveTaskHistoryResult;
 
-                    // 淇濆瓨搴撳瓨鍘嗗彶
-                    var historyStock = _mapper.Map<Dt_StockInfo_Hty>(stockInfo);
-                    historyStock.InsertTime = DateTime.Now;
-                    historyStock.OperateType = "绌烘墭鐩樺叆搴撳畬鎴�";
-                    if (await _stockInfo_HtyService.Repository.AddDataAsync(historyStock) <= 0)
-                        return WebResponseContent.Instance.Error("搴撳瓨鍘嗗彶淇濆瓨澶辫触");
+                    var saveStockHistoryResult = await SaveStockHistoryAsync(stockInfo, "绌烘墭鐩樺叆搴撳畬鎴�");
+                    if (!saveStockHistoryResult.Status)
+                        return saveStockHistoryResult;
 
                     var deleteResult = await BaseDal.DeleteDataAsync(task);
                     if (!deleteResult) return WebResponseContent.Instance.Error("浠诲姟瀹屾垚澶辫触");
@@ -483,7 +477,7 @@
                 return await ExecuteWithinTransactionAsync(async () =>
                 {
                     stockInfo.LocationId = 0;
-                    stockInfo.LocationCode = null;
+                    stockInfo.LocationCode = string.Empty;
                     stockInfo.StockStatus = StockStatusEmun.鍑哄簱瀹屾垚.GetHashCode();
 
                     location.LocationStatus = LocationStatusEnum.Free.GetHashCode();
@@ -493,19 +487,13 @@
                     if (!updateLocationResult || !updateStockResult)
                         return WebResponseContent.Instance.Error("浠诲姟瀹屾垚澶辫触");
 
-                    // 淇濆瓨浠诲姟鍘嗗彶
-                    var historyTask = _mapper.Map<Dt_Task_Hty>(task);
-                    historyTask.InsertTime = DateTime.Now;
-                    historyTask.OperateType = "绌烘墭鐩樺嚭搴撳畬鎴�";
-                    if (await _task_HtyService.Repository.AddDataAsync(historyTask) <= 0)
-                        return WebResponseContent.Instance.Error("浠诲姟鍘嗗彶淇濆瓨澶辫触");
+                    var saveTaskHistoryResult = await SaveTaskHistoryAsync(task, "绌烘墭鐩樺嚭搴撳畬鎴�");
+                    if (!saveTaskHistoryResult.Status)
+                        return saveTaskHistoryResult;
 
-                    // 淇濆瓨搴撳瓨鍘嗗彶
-                    var historyStock = _mapper.Map<Dt_StockInfo_Hty>(stockInfo);
-                    historyStock.InsertTime = DateTime.Now;
-                    historyStock.OperateType = "绌烘墭鐩樺嚭搴撳畬鎴�";
-                    if (await _stockInfo_HtyService.Repository.AddDataAsync(historyStock) <= 0)
-                        return WebResponseContent.Instance.Error("搴撳瓨鍘嗗彶淇濆瓨澶辫触");
+                    var saveStockHistoryResult = await SaveStockHistoryAsync(stockInfo, "绌烘墭鐩樺嚭搴撳畬鎴�");
+                    if (!saveStockHistoryResult.Status)
+                        return saveStockHistoryResult;
 
                     var deleteResult = await BaseDal.DeleteDataAsync(task);
                     if (!deleteResult) return WebResponseContent.Instance.Error("浠诲姟瀹屾垚澶辫触");
@@ -542,78 +530,6 @@
             {
                 return WebResponseContent.Instance.Error($"淇敼澶辫触: {ex.Message}");
             }
-        }
-
-        /// <summary>
-        /// 鏌ユ壘鎵樼洏鏄惁鏈変换鍔�
-        /// </summary>
-        /// <param name="palletCode"></param>
-        /// <returns></returns>
-        private async Task<WebResponseContent> GetTaskByPalletCodeAsync(string palletCode)
-        {
-            try
-            {
-                var task = await BaseDal.QueryFirstAsync(s => s.PalletCode == palletCode);
-                if (task == null)
-                    return WebResponseContent.Instance.Error("鏈壘鍒板搴旂殑浠诲姟");
-                var taskDto = _mapper.Map<WMSTaskDTO>(task);
-                return WebResponseContent.Instance.OK("鏌ヨ鎴愬姛", taskDto);
-            }
-            catch (Exception ex)
-            {
-                return WebResponseContent.Instance.Error($"鏌ヨ浠诲姟澶辫触: {ex.Message}");
-            }
-        }
-
-        /// <summary>
-        /// 瀹屾垚浠诲姟鍚庣粺涓�澶勭悊锛堝垹闄や换鍔℃暟鎹級
-        /// </summary>
-        private async Task<WebResponseContent> CompleteTaskAsync(Dt_Task task, string operateType = "")
-        {
-            var deleteTaskResult = await BaseDal.DeleteDataAsync(task);
-            if (!deleteTaskResult) return WebResponseContent.Instance.Error("浠诲姟瀹屾垚澶辫触");
-
-            var historyTask = _mapper.Map<Dt_Task_Hty>(task);
-            historyTask.InsertTime = DateTime.Now;
-            historyTask.OperateType = operateType;
-            var saveResult = await _task_HtyService.Repository.AddDataAsync(historyTask) > 0;
-            if (!saveResult) return WebResponseContent.Instance.Error("浠诲姟鍘嗗彶淇濆瓨澶辫触");
-
-            return WebResponseContent.Instance.OK("浠诲姟瀹屾垚");
-        }
-
-        /// <summary>
-        /// 鏍规嵁宸烽亾纭畾鐩爣鍦板潃锛堟敮鎸佸鍑哄簱鍙h疆璇級
-        /// </summary>
-        private string DetermineTargetAddress(string roadway, Dictionary<string, List<string>> addressMap)
-        {
-            if (string.IsNullOrWhiteSpace(roadway))
-                return "10080";
-
-            // 鏌ユ壘鍖归厤鐨勫贩閬撳墠缂�
-            string matchedPrefix = null;
-            foreach (var kvp in addressMap)
-            {
-                if (roadway.Contains(kvp.Key))
-                {
-                    matchedPrefix = kvp.Key;
-                    break;
-                }
-            }
-
-            if (matchedPrefix == null)
-                return "10080";
-
-            var addresses = addressMap[matchedPrefix];
-            if (addresses == null || addresses.Count == 0)
-                return "10080";
-
-            // 鍗曚釜鍦板潃锛岀洿鎺ヨ繑鍥�
-            if (addresses.Count == 1)
-                return addresses[0];
-
-            // 澶氫釜鍦板潃锛屼娇鐢ㄨ疆璇㈡湇鍔�
-            return _roundRobinService.GetNextAddress(matchedPrefix, addresses);
         }
 
         /// <summary>
@@ -865,7 +781,7 @@
                     TaskNum = await BaseDal.GetTaskNo(),
                     PalletCode = palletCode,
                     PalletType = stockInfo?.PalletType ?? 0,
-                    Roadway = stock.Roadway,
+                    Roadway = stock.Roadway ?? string.Empty,
                     TaskType = taskType.GetHashCode(),
                     TaskStatus = TaskRobotStatusEnum.RobotNew.GetHashCode(),
                     SourceAddress = sourceLineNo,
@@ -882,7 +798,7 @@
                 if (!result)
                     return WebResponseContent.Instance.Error($"鏈烘鎵媨taskName}浠诲姟鍒涘缓澶辫触");
 
-                var wmstaskDto = _mapper.Map<WMSTaskDTO>(task);
+                var wmstaskDto = _mapper.Map<WMSTaskDTO>(task) ?? new WMSTaskDTO();
                 return WebResponseContent.Instance.OK($"鏈烘鎵媨taskName}浠诲姟鍒涘缓鎴愬姛", wmstaskDto);
             }
             catch (Exception ex)

--
Gitblit v1.9.3