From a9edf162ac5dd98719c2f93ab0800c98673fd220 Mon Sep 17 00:00:00 2001
From: xiazhengtongxue <133085197+xiazhengtongxue@users.noreply.github.com>
Date: 星期三, 01 四月 2026 16:14:49 +0800
Subject: [PATCH] fix: 修复AGV任务下发,修改找空闲为深度优先等

---
 Code/WMS/WIDESEA_WMSServer/WIDESEA_BasicService/LocationInfoService.cs |  232 +++++++++++++++++++++++++++++++++++++++++++++++++++------
 1 files changed, 206 insertions(+), 26 deletions(-)

diff --git a/Code/WMS/WIDESEA_WMSServer/WIDESEA_BasicService/LocationInfoService.cs b/Code/WMS/WIDESEA_WMSServer/WIDESEA_BasicService/LocationInfoService.cs
index aeff75f..d4b8ccf 100644
--- a/Code/WMS/WIDESEA_WMSServer/WIDESEA_BasicService/LocationInfoService.cs
+++ b/Code/WMS/WIDESEA_WMSServer/WIDESEA_BasicService/LocationInfoService.cs
@@ -1,13 +1,18 @@
+using Mapster;
+using MapsterMapper;
+using WIDESEA_Common.CommonEnum;
 using WIDESEA_Common.LocationEnum;
+using WIDESEA_Common.StockEnum;
 using WIDESEA_Common.TaskEnum;
 using WIDESEA_Core;
 using WIDESEA_Core.BaseRepository;
 using WIDESEA_Core.BaseServices;
 using WIDESEA_Core.Utilities;
 using WIDESEA_DTO.Basic;
+using WIDESEA_DTO.Task;
 using WIDESEA_IBasicService;
+using WIDESEA_IRecordService;
 using WIDESEA_Model.Models;
-using WIDESEA_Common.CommonEnum;
 
 namespace WIDESEA_BasicService
 {
@@ -16,8 +21,11 @@
     /// </summary>
     public partial class LocationInfoService : ServiceBase<Dt_LocationInfo, IRepository<Dt_LocationInfo>>, ILocationInfoService
     {
+        private readonly IMapper _mapper;
         private readonly IRepository<Dt_Task> _taskRepository;
         private readonly IRepository<Dt_StockInfo> _stockInfoRepository;
+        private readonly IRecordService _recordService;
+        private readonly IRepository<Dt_Warehouse> _warehouseRepository;
 
         /// <summary>
         /// 鏋勯�犲嚱鏁�
@@ -28,10 +36,16 @@
         public LocationInfoService(
             IRepository<Dt_LocationInfo> baseDal,
             IRepository<Dt_Task> taskRepository,
-            IRepository<Dt_StockInfo> stockInfoRepository) : base(baseDal)
+            IRepository<Dt_StockInfo> stockInfoRepository,
+            IRepository<Dt_Warehouse> warehouseRepository,
+            IMapper mapper,
+            IRecordService recordService) : base(baseDal)
         {
             _taskRepository = taskRepository;
             _stockInfoRepository = stockInfoRepository;
+            _mapper = mapper;
+            _recordService = recordService;
+            _warehouseRepository = warehouseRepository;
         }
 
         /// <summary>
@@ -130,10 +144,10 @@
                 x.LocationStatus == LocationStatusEnum.Free.GetHashCode());
 
             return locations?
-                .OrderBy(x => x.Layer)
-                .ThenByDescending(x => x.Depth)
-                .ThenBy(x => x.Column)
-                .ThenBy(x => x.Row)
+                .OrderByDescending(x => x.Depth)  // 1. 娣卞害浼樺厛锛堜粠澶у埌灏忥級
+                .ThenBy(x => x.Layer)             // 2. 灞傛暟
+                .ThenBy(x => x.Column)            // 3. 鍒�
+                .ThenBy(x => x.Row)               // 4. 琛�
                 .FirstOrDefault();
         }
 
@@ -165,7 +179,48 @@
         /// <returns>鏇存柊鏄惁鎴愬姛</returns>
         public async Task<bool> UpdateLocationInfoAsync(Dt_LocationInfo locationInfo)
         {
-            return await BaseDal.UpdateDataAsync(locationInfo);
+            var beforeLocation = await BaseDal.QueryFirstAsync(x => x.Id == locationInfo.Id);
+            var result = await BaseDal.UpdateDataAsync(locationInfo);
+            if (!result)
+                return false;
+
+            return beforeLocation == null
+                || await _recordService.AddLocationChangeRecordAsync(beforeLocation, locationInfo, LocationChangeType.HandUpdate, remark: "璐т綅鏇存柊");
+        }
+
+        public override WebResponseContent UpdateData(Dt_LocationInfo entity)
+        {
+            var beforeLocation = BaseDal.QueryFirst(x => x.Id == entity.Id);
+            var result = base.UpdateData(entity);
+            if (!result.Status || beforeLocation == null)
+                return result;
+
+            var saveRecordResult = _recordService.AddLocationChangeRecordAsync(beforeLocation, entity, LocationChangeType.HandUpdate, remark: "璐т綅鏇存柊").GetAwaiter().GetResult();
+            return saveRecordResult ? result : WebResponseContent.Instance.Error("璐т綅鐘舵�佸彉鏇磋褰曚繚瀛樺け璐�");
+        }
+
+        public override WebResponseContent UpdateData(List<Dt_LocationInfo> entities)
+        {
+            var beforeLocations = entities
+                .Select(entity => BaseDal.QueryFirst(x => x.Id == entity.Id))
+                .Where(location => location != null)
+                .ToDictionary(location => location!.Id, location => location!);
+
+            var result = base.UpdateData(entities);
+            if (!result.Status)
+                return result;
+
+            foreach (var entity in entities)
+            {
+                if (!beforeLocations.TryGetValue(entity.Id, out var beforeLocation))
+                    continue;
+
+                var saveRecordResult = _recordService.AddLocationChangeRecordAsync(beforeLocation, entity, LocationChangeType.HandUpdate, remark: "鎵归噺璐т綅鏇存柊").GetAwaiter().GetResult();
+                if (!saveRecordResult)
+                    return WebResponseContent.Instance.Error("璐т綅鐘舵�佸彉鏇磋褰曚繚瀛樺け璐�");
+            }
+
+            return result;
         }
 
         /// <summary>
@@ -197,7 +252,7 @@
                     // 濡傛灉鏂扮殑搴撲綅娌℃湁鎵惧埌瀵瑰簲鐨勪换鍔�
                     if (internalTransferTask == null)
                     {
-                        return content.OK("鑾峰彇鍒扮Щ搴撲换鍔�", await HandleNoTaskAtLocation(outboundTask.SourceAddress, newLocationID, outboundTask));
+                        return content.OK("鑾峰彇鍒扮Щ搴撲换鍔�", await HandleNoTaskAtLocation(newLocationID, outboundTask));
                     }
 
                     // 鐩存帴杩斿洖涓�娣变綅鍑哄簱浠诲姟
@@ -228,27 +283,23 @@
             int relativeLine = line % 2 == 1 ? line + 1 : line - 1;
 
             // 鏋勫缓鏂扮殑搴撲綅ID
-            string[] newLocationParts = new string[] { relativeLine.ToString().PadLeft(3, '0'), locationInfo.Column.ToString(), locationInfo.Layer.ToString() };
+            string[] newLocationParts = new string[] { relativeLine.ToString().PadLeft(3, '0'), locationInfo.Column.ToString().PadLeft(3, '0'), locationInfo.Layer.ToString().PadLeft(3, '0') };
             return string.Join("-", newLocationParts);
         }
 
         /// <summary>
         /// 澶勭悊娌℃湁浠诲姟鐨勫簱浣嶆儏鍐�
         /// </summary>
-        /// <param name="originalLocationID">鍘熷搴撲綅ID</param>
         /// <param name="newLocationID">鏂扮殑搴撲綅ID</param>
         /// <param name="outboundTask">鍑哄簱浠诲姟</param>
         /// <returns>鐢熸垚鐨勭Щ搴撲换鍔℃垨鍘熷鍑哄簱浠诲姟</returns>
-        private async Task<Dt_Task> HandleNoTaskAtLocation(string originalLocationID, string newLocationID, Dt_Task outboundTask)
+        private async Task<Dt_Task> HandleNoTaskAtLocation(string newLocationID, Dt_Task outboundTask)
         {
             // 鍒ゆ柇璇ヤ綅缃槸鍚︽湁搴撳瓨
-            var stockInfo = await _stockInfoRepository.QueryFirstAsync(x => x.LocationCode == newLocationID);
-            if (stockInfo == null)
-            {
-                // 濡傛灉娌℃湁搴撳瓨锛岀洿鎺ヨ繑鍥炲綋鍓嶅嚭搴撲换鍔�
-                return outboundTask;
-            }
-
+            var stockInfo = await _stockInfoRepository.QueryDataNavFirstAsync(x =>
+                            x.LocationCode == newLocationID &&
+                            x.StockStatus == StockStatusEmun.鍏ュ簱瀹屾垚.GetHashCode() &&
+                            x.LocationDetails.LocationStatus == LocationStatusEnum.InStock.GetHashCode());
             if (stockInfo == null)
             {
                 // 濡傛灉娌℃湁搴撳瓨锛岀洿鎺ヨ繑鍥炲綋鍓嶅嚭搴撲换鍔�
@@ -262,20 +313,142 @@
             var newTransferTask = new Dt_Task
             {
                 CreateDate = DateTime.Now,
-                Creater = App.User.UserName,
-                CurrentAddress = originalLocationID,
+                Creater = App.User.UserName ?? "system",
+                CurrentAddress = newLocationID,
                 Grade = 99,
                 NextAddress = emptyLocation.LocationCode,
                 PalletCode = stockInfo.PalletCode,
                 Remark = "绉诲簱",
                 Roadway = stockInfo.LocationDetails.RoadwayNo,
-                SourceAddress = originalLocationID,
+                SourceAddress = newLocationID,
                 TaskNum = taskNo,
                 TargetAddress = emptyLocation.LocationCode,
-                TaskType = TaskTypeEnum.Relocation.GetHashCode()
+                TaskType = TaskRelocationTypeEnum.Relocation.GetHashCode(),
+                TaskStatus = TaskRelocationStatusEnum.RelocationNew.GetHashCode(),
+                WarehouseId = stockInfo.WarehouseId
             };
 
-            return await _taskRepository.Db.Insertable(newTransferTask).ExecuteReturnEntityAsync();
+            var createdTask = await _taskRepository.Db.Insertable(newTransferTask).ExecuteReturnEntityAsync();
+            var beforeStock = CloneStockSnapshot(stockInfo);
+            var beforeSourceLocation = stockInfo.LocationDetails == null ? null : CloneLocationSnapshot(stockInfo.LocationDetails);
+            var beforeTargetLocation = CloneLocationSnapshot(emptyLocation);
+
+            // 鍒涘缓绉诲簱浠诲姟鍚庯紝绔嬪嵆閿佸畾搴撳瓨鍜岀浉鍏宠揣浣嶏紝閬垮厤骞跺彂閲嶅鍒嗛厤
+            stockInfo.StockStatus = StockStatusEmun.绉诲簱閿佸畾.GetHashCode();
+            var updateStockResult = await _stockInfoRepository.UpdateDataAsync(stockInfo);
+
+            var locationsToUpdate = new List<Dt_LocationInfo>();
+            if (stockInfo.LocationDetails != null)
+            {
+                stockInfo.LocationDetails.LocationStatus = LocationStatusEnum.InStockLock.GetHashCode();
+                locationsToUpdate.Add(stockInfo.LocationDetails);
+            }
+
+            emptyLocation.LocationStatus = LocationStatusEnum.FreeLock.GetHashCode();
+            locationsToUpdate.Add(emptyLocation);
+
+            var updateLocationResult = await BaseDal.UpdateDataAsync(locationsToUpdate);
+            if (!updateStockResult || !updateLocationResult)
+            {
+                throw new Exception("鍒涘缓绉诲簱浠诲姟鍚庢洿鏂板簱瀛樼姸鎬佹垨璐т綅鐘舵�佸け璐�");
+            }
+
+            var saveStockRecordResult = await _recordService.AddStockChangeRecordAsync(
+                beforeStock,
+                stockInfo,
+                StockChangeTypeEnum.Relocation,
+                createdTask.TaskNum,
+                createdTask.OrderNo,
+                "绉诲簱浠诲姟棰勫崰搴撳瓨");
+            if (!saveStockRecordResult)
+            {
+                throw new Exception("鍒涘缓绉诲簱浠诲姟鍚庤褰曞簱瀛樺彉鏇村け璐�");
+            }
+
+            if (beforeSourceLocation != null && stockInfo.LocationDetails != null)
+            {
+                var saveSourceLocationRecordResult = await _recordService.AddLocationChangeRecordAsync(
+                    beforeSourceLocation,
+                    stockInfo.LocationDetails,
+                    LocationChangeType.RelocationAssignLocation,
+                    createdTask.TaskNum,
+                    createdTask.OrderNo,
+                    null,
+                    "绉诲簱浠诲姟閿佸畾婧愯揣浣�");
+                if (!saveSourceLocationRecordResult)
+                {
+                    throw new Exception("鍒涘缓绉诲簱浠诲姟鍚庤褰曟簮璐т綅鍙樻洿澶辫触");
+                }
+            }
+
+            var saveTargetLocationRecordResult = await _recordService.AddLocationChangeRecordAsync(
+                beforeTargetLocation,
+                emptyLocation,
+                LocationChangeType.RelocationAssignLocation,
+                createdTask.TaskNum,
+                createdTask.OrderNo,
+                null,
+                "绉诲簱浠诲姟閿佸畾鐩爣璐т綅");
+            if (!saveTargetLocationRecordResult)
+            {
+                throw new Exception("鍒涘缓绉诲簱浠诲姟鍚庤褰曠洰鏍囪揣浣嶅彉鏇村け璐�");
+            }
+
+            return createdTask;
+        }
+
+        private static Dt_LocationInfo CloneLocationSnapshot(Dt_LocationInfo location)
+        {
+            return new Dt_LocationInfo
+            {
+                Id = location.Id,
+                WarehouseId = location.WarehouseId,
+                LocationCode = location.LocationCode,
+                LocationName = location.LocationName,
+                RoadwayNo = location.RoadwayNo,
+                Row = location.Row,
+                Column = location.Column,
+                Layer = location.Layer,
+                Depth = location.Depth,
+                LocationType = location.LocationType,
+                LocationStatus = location.LocationStatus,
+                EnableStatus = location.EnableStatus,
+                Remark = location.Remark
+            };
+        }
+
+        private static Dt_StockInfo CloneStockSnapshot(Dt_StockInfo stockInfo)
+        {
+            return new Dt_StockInfo
+            {
+                Id = stockInfo.Id,
+                PalletCode = stockInfo.PalletCode,
+                PalletType = stockInfo.PalletType,
+                LocationId = stockInfo.LocationId,
+                LocationCode = stockInfo.LocationCode,
+                WarehouseId = stockInfo.WarehouseId,
+                StockStatus = stockInfo.StockStatus,
+                Remark = stockInfo.Remark,
+                OutboundDate = stockInfo.OutboundDate,
+                Details = stockInfo.Details?.Select(detail => new Dt_StockInfoDetail
+                {
+                    Id = detail.Id,
+                    StockId = detail.StockId,
+                    MaterielCode = detail.MaterielCode,
+                    MaterielName = detail.MaterielName,
+                    OrderNo = detail.OrderNo,
+                    BatchNo = detail.BatchNo,
+                    ProductionDate = detail.ProductionDate,
+                    EffectiveDate = detail.EffectiveDate,
+                    SerialNumber = detail.SerialNumber,
+                    StockQuantity = detail.StockQuantity,
+                    OutboundQuantity = detail.OutboundQuantity,
+                    Status = detail.Status,
+                    Unit = detail.Unit,
+                    InboundOrderRowNo = detail.InboundOrderRowNo,
+                    Remark = detail.Remark
+                }).ToList()
+            };
         }
 
         /// <summary>
@@ -324,11 +497,18 @@
         /// <param name="layer">灞傛暟</param>
         /// <param name="depth">娣卞害</param>
         /// <returns>璐т綅淇℃伅瀵硅薄</returns>
-        private static Dt_LocationInfo CreateLocationInfo(string roadwayNo, int row, int col, int layer, int depth)
+        private Dt_LocationInfo CreateLocationInfo(string roadwayNo, int row, int col, int layer, int depth)
         {
+            var warehouse = _warehouseRepository.QueryData(x => x.WarehouseCode == roadwayNo).FirstOrDefault();
+
+            if (warehouse == null)
+            {
+                throw new InvalidOperationException($"鏈壘鍒板贩閬撶紪鍙蜂负 {roadwayNo} 鐨勪粨搴撲俊鎭�");
+            }
+
             return new Dt_LocationInfo
             {
-                WarehouseId = 0,
+                WarehouseId = warehouse.WarehouseId,
                 Row = row,
                 Column = col,
                 Layer = layer,
@@ -337,7 +517,7 @@
                 EnableStatus = EnableStatusEnum.Normal.GetHashCode(),
                 LocationStatus = LocationStatusEnum.Free.GetHashCode(),
                 LocationType = LocationTypeEnum.Undefined.GetHashCode(),
-                LocationCode = $"{row:D3}-{col:D3}-{layer:D3}",
+                LocationCode = $"{roadwayNo}-{row:D3}-{col:D3}-{layer:D3}",
                 LocationName = $"{roadwayNo}宸烽亾{row:D3}琛寋col:D3}鍒梴layer:D3}灞倇depth:D2}娣�"
             };
         }

--
Gitblit v1.9.3