From 5dee92e9e70a61f5b0308474a0334f414cce8835 Mon Sep 17 00:00:00 2001
From: wanshenmean <cathay_xy@163.com>
Date: 星期五, 06 三月 2026 17:17:57 +0800
Subject: [PATCH] feat: 实现自动出库任务创建方法

---
 Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService.cs |  241 +++++++++++++++++++++++++++++++++++++++++++++--
 1 files changed, 227 insertions(+), 14 deletions(-)

diff --git a/Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService.cs b/Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService.cs
index 2a799c9..e02e62f 100644
--- a/Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService.cs
+++ b/Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService.cs
@@ -1,5 +1,5 @@
 锘縰sing AutoMapper;
-using Microsoft.AspNetCore.Components.Forms;
+using Microsoft.Extensions.Configuration;
 using SqlSugar;
 using System.Text.Json;
 using WIDESEA_Common.LocationEnum;
@@ -8,7 +8,6 @@
 using WIDESEA_Core;
 using WIDESEA_Core.BaseRepository;
 using WIDESEA_Core.BaseServices;
-using WIDESEA_Core.Helper;
 using WIDESEA_DTO;
 using WIDESEA_DTO.Task;
 using WIDESEA_IBasicService;
@@ -24,6 +23,7 @@
         private readonly IStockInfoService _stockInfoService;
         private readonly ILocationInfoService _locationInfoService;
         private readonly HttpClientHelper _httpClientHelper;
+        private readonly IConfiguration _configuration;
 
         public IRepository<Dt_Task> Repository => BaseDal;
 
@@ -41,13 +41,17 @@
             IMapper mapper,
             IStockInfoService stockInfoService,
             ILocationInfoService locationInfoService,
-            HttpClientHelper httpClientHelper) : base(BaseDal)
+            HttpClientHelper httpClientHelper,
+            IConfiguration configuration) : base(BaseDal)
         {
             _mapper = mapper;
             _stockInfoService = stockInfoService;
             _locationInfoService = locationInfoService;
             _httpClientHelper = httpClientHelper;
+            _configuration = configuration;
         }
+
+        #region WCS閫昏緫澶勭悊
 
         /// <summary>
         /// 鍒涘缓浠诲姟锛堢粍鐩樺叆搴撲换鍔°�佺┖鎵樼洏鍥炲簱浠诲姟锛�
@@ -56,9 +60,13 @@
         {
             try
             {
+                WebResponseContent content = await GetTasksByPalletCodeAsync(taskDto.PalletCode);
+                if (content.Status)
+                {
+                    return content;
+                }
+
                 if (string.IsNullOrWhiteSpace(taskDto.PalletCode) ||
-                    string.IsNullOrWhiteSpace(taskDto.SourceAddress) ||
-                    string.IsNullOrWhiteSpace(taskDto.TargetAddress) ||
                     string.IsNullOrWhiteSpace(taskDto.Roadway))
                 {
                     return WebResponseContent.Instance.Error("鏃犳晥鐨勪换鍔¤鎯�");
@@ -69,14 +77,22 @@
                     return WebResponseContent.Instance.Error("鏃犳晥鐨勪换鍔¤鎯�");
                 }
 
+                // 浣跨敤 switch 琛ㄨ揪寮忔槧灏勪换鍔$被鍨�
+                int taskInboundType = taskDto.TaskType switch
+                {
+                    TaskTypeEnum.Inbound => TaskInboundTypeEnum.Inbound.GetHashCode(),
+                    TaskTypeEnum.InEmpty => TaskInboundTypeEnum.InEmpty.GetHashCode(),
+                    _ => 0 // 鐞嗚涓婁笉浼氳蛋鍒拌繖閲岋紝鍥犱负宸茬粡楠岃瘉杩囦簡
+                };
+
                 var task = new Dt_Task
                 {
-                    TaskNum = 0,
+                    TaskNum = await BaseDal.GetTaskNo(),
                     PalletCode = taskDto.PalletCode,
                     PalletType = taskDto.PalletType,
                     Roadway = taskDto.Roadway,
-                    TaskType = taskDto.TaskType.GetHashCode(),
-                    TaskStatus = TaskStatusEnum.New.GetHashCode(),
+                    TaskType = taskInboundType,
+                    TaskStatus = TaskInStatusEnum.InNew.GetHashCode(),
                     SourceAddress = taskDto.SourceAddress,
                     TargetAddress = taskDto.TargetAddress,
                     CurrentAddress = taskDto.SourceAddress,
@@ -153,7 +169,7 @@
                 task.CurrentAddress = task.SourceAddress;
                 task.NextAddress = locationInfo.LocationCode;
                 task.TargetAddress = locationInfo.LocationCode;
-                task.TaskStatus = TaskStatusEnum.Line_Finish.GetHashCode();
+                task.TaskStatus = TaskInStatusEnum.Line_InFinish.GetHashCode();
 
                 var updateResult = await BaseDal.UpdateDataAsync(task);
                 var locationResult = await _locationInfoService.UpdateLocationInfoAsync(locationInfo);
@@ -259,6 +275,12 @@
         {
             try
             {
+                WebResponseContent content = await GetTasksByPalletCodeAsync(taskDto.PalletCode);
+                if (content.Status)
+                {
+                    return content;
+                }
+
                 //var tasks = await BaseDal.QueryAsync(s => s.PalletCode == palletCode);
                 //if (tasks == null || !tasks.Any())
                 //    return WebResponseContent.Instance.Error("鏈壘鍒板搴旂殑浠诲姟");
@@ -280,8 +302,9 @@
         {
             try
             {
+
                 var stockInfo = await _stockInfoService.Repository.QueryFirstAsync(x => x.LocationDetails.WarehouseId == taskDto.WarehouseId && x.LocationDetails.LocationStatus == LocationStatusEnum.InStock.GetHashCode() && x.StockStatus == StockStatusEmun.绌烘墭鐩樺簱瀛�.GetHashCode());
-                if(stockInfo == null)
+                if (stockInfo == null)
                     return WebResponseContent.Instance.Error("鏈壘鍒板搴旂殑搴撳瓨淇℃伅");
 
                 var task = new Dt_Task()
@@ -300,7 +323,7 @@
                     TaskNum = await BaseDal.GetTaskNo(),
                     Creater = "system",
                 };
-                 var taskDtos = _mapper.Map<List<WMSTaskDTO>>(task);
+                var taskDtos = _mapper.Map<List<WMSTaskDTO>>(task);
                 return WebResponseContent.Instance.OK("鏌ヨ鎴愬姛", taskDtos);
             }
             catch (Exception ex)
@@ -308,6 +331,197 @@
                 return WebResponseContent.Instance.Error($"鏌ヨ浠诲姟澶辫触: {ex.Message}");
             }
         }
+
+        /// <summary>
+        /// 淇敼浠诲姟鐘舵�侊紙鏍规嵁浠诲姟ID淇敼涓烘寚瀹氱姸鎬侊級
+        /// </summary>
+        /// <param name="taskId"></param>
+        /// <param name="newStatus"></param>
+        /// <returns></returns>
+        public async Task<WebResponseContent> UpdateTaskByStatusAsync(int taskId, int newStatus)
+        {
+            try
+            {
+                var tasks = await BaseDal.QueryFirstAsync(s => s.TaskNum == taskId);
+                if (tasks == null)
+                    return WebResponseContent.Instance.Error("鏈壘鍒板搴旂殑浠诲姟");
+
+                tasks.TaskStatus = newStatus;
+                await BaseDal.UpdateDataAsync(tasks);
+
+                return WebResponseContent.Instance.OK("淇敼鎴愬姛", tasks);
+            }
+            catch (Exception ex)
+            { 
+                return WebResponseContent.Instance.Error($"淇敼澶辫触: {ex.Message}");
+            }
+        }
+
+
+        /// <summary>
+        /// 鏌ユ壘鎵樼洏鏄惁鏈変换鍔�
+        /// </summary>
+        /// <param name="palletCode"></param>
+        /// <returns></returns>
+        private async Task<WebResponseContent> GetTasksByPalletCodeAsync(string palletCode)
+        {
+            try
+            {
+                var tasks = await BaseDal.QueryFirstAsync(s => s.PalletCode == palletCode);
+                if (tasks == null)
+                    return WebResponseContent.Instance.Error("鏈壘鍒板搴旂殑浠诲姟");
+                var taskDtos = _mapper.Map<List<WMSTaskDTO>>(tasks);
+                return WebResponseContent.Instance.OK("鏌ヨ鎴愬姛", taskDtos);
+            }
+            catch (Exception ex)
+            {
+                return WebResponseContent.Instance.Error($"鏌ヨ浠诲姟澶辫触: {ex.Message}");
+            }
+        }
+
+        /// <summary>
+        /// 鏍规嵁宸烽亾纭畾鐩爣鍦板潃
+        /// </summary>
+        private string DetermineTargetAddress(string roadway, Dictionary<string, string> addressMap)
+        {
+            if (string.IsNullOrWhiteSpace(roadway))
+                return "10080"; // 榛樿鍦板潃
+
+            foreach (var kvp in addressMap)
+            {
+                if (roadway.Contains(kvp.Key))
+                    return kvp.Value;
+            }
+
+            return "10080"; // 榛樿鍦板潃
+        }
+
+        /// <summary>
+        /// 鑷姩鍒涘缓鍑哄簱浠诲姟 - 鏌ヨ鍒版湡搴撳瓨骞跺垱寤轰换鍔�
+        /// </summary>
+        public async Task<WebResponseContent> CreateAutoOutboundTasksAsync()
+        {
+            try
+            {
+                // 1. 鏌ヨ鍒版湡搴撳瓨
+                var expiredStocks = await _stockInfoService.Repository
+                    .QueryAsync(s => s.OutboundDate <= DateTime.Now
+                        && s.StockStatus == StockStatusEmun.鍏ュ簱瀹屾垚.GetHashCode());
+
+                if (expiredStocks == null || !expiredStocks.Any())
+                {
+                    return WebResponseContent.Instance.OK("鏃犲埌鏈熷簱瀛橀渶瑕佸鐞�");
+                }
+
+                // 鍔犺浇浣嶇疆璇︽儏
+                foreach (var stock in expiredStocks)
+                {
+                    if (stock.LocationId > 0)
+                    {
+                        stock.LocationDetails = await _locationInfoService.Repository
+                            .GetFirstAsync(s => s.Id == stock.LocationId);
+                    }
+                }
+
+                // 杩囨护鏈変綅缃笖浣嶇疆鏈夊簱瀛樼殑璁板綍
+                expiredStocks = expiredStocks
+                    .Where(s => s.LocationDetails != null
+                        && s.LocationDetails.LocationStatus == LocationStatusEnum.InStock.GetHashCode())
+                    .ToList();
+
+                if (!expiredStocks.Any())
+                {
+                    return WebResponseContent.Instance.OK("鏃犵鍚堟潯浠剁殑鍒版湡搴撳瓨");
+                }
+
+                // 2. 妫�鏌ュ凡瀛樺湪鐨勪换鍔�
+                var palletCodes = expiredStocks.Select(s => s.PalletCode).ToList();
+                var existingTasks = await Repository.QueryAsync(t =>
+                    palletCodes.Contains(t.PalletCode)
+                    && (t.TaskStatus == TaskStatusEnum.New.GetHashCode()
+                        || t.TaskStatus == TaskStatusEnum.Executing.GetHashCode()
+                        || t.TaskInStatus == TaskInStatusEnum.InNew.GetHashCode()));
+
+                var processedPallets = existingTasks.Select(t => t.PalletCode).ToHashSet();
+
+                // 3. 绛涢�夐渶瑕佸鐞嗙殑搴撳瓨
+                var stocksToProcess = expiredStocks
+                    .Where(s => !processedPallets.Contains(s.PalletCode))
+                    .ToList();
+
+                if (!stocksToProcess.Any())
+                {
+                    return WebResponseContent.Instance.OK("鎵�鏈夊埌鏈熷簱瀛樺凡瀛樺湪浠诲姟");
+                }
+
+                // 4. 鑾峰彇閰嶇疆鐨勭洰鏍囧湴鍧�鏄犲皠
+                var targetAddressMap = _configuration.GetSection("AutoOutboundTask:TargetAddresses")
+                    .Get<Dictionary<string, string>>()
+                    ?? new Dictionary<string, string>();
+
+                // 5. 鎵归噺鍒涘缓浠诲姟
+                var taskList = new List<Dt_Task>();
+                foreach (var stock in stocksToProcess)
+                {
+                    // 鏍规嵁宸烽亾纭畾鐩爣鍦板潃
+                    var targetAddress = DetermineTargetAddress(
+                        stock.LocationDetails?.RoadwayNo ?? "",
+                        targetAddressMap);
+
+                    var task = new Dt_Task
+                    {
+                        WarehouseId = stock.WarehouseId,
+                        PalletCode = stock.PalletCode,
+                        PalletType = stock.PalletType,
+                        SourceAddress = stock.LocationCode,
+                        CurrentAddress = stock.LocationCode,
+                        NextAddress = targetAddress,
+                        TargetAddress = targetAddress,
+                        Roadway = stock.LocationDetails?.RoadwayNo ?? "",
+                        TaskType = TaskTypeEnum.Outbound.GetHashCode(),
+                        TaskStatus = TaskStatusEnum.New.GetHashCode(),
+                        Grade = 1,
+                        TaskNum = await Repository.GetTaskNo(),
+                        Creater = "system_auto"
+                    };
+                    taskList.Add(task);
+                }
+
+                var addResult = await BaseDal.AddDataAsync(taskList) > 0;
+                if (!addResult)
+                {
+                    return WebResponseContent.Instance.Error($"鎵归噺鍒涘缓浠诲姟澶辫触锛屽叡 {taskList.Count} 涓换鍔�");
+                }
+
+                // 6. 閫氱煡 WCS锛堝紓姝ワ紝涓嶅奖鍝嶄富娴佺▼锛�
+                _ = Task.Run(async () =>
+                {
+                    foreach (var task in taskList)
+                    {
+                        try
+                        {
+                            var wmstaskDto = _mapper.Map<WMSTaskDTO>(task);
+                            await _httpClientHelper.Post<WebResponseContent>(
+                                "http://logistics-service/api/logistics/notifyoutbound",
+                                JsonSerializer.Serialize(wmstaskDto));
+                        }
+                        catch (Exception ex)
+                        {
+                            // WCS 閫氱煡澶辫触涓嶅奖鍝嶄换鍔″垱寤猴紝璁板綍鏃ュ織鍗冲彲
+                            Console.WriteLine($"WCS 閫氱煡澶辫触锛屼换鍔$紪鍙�: {task.TaskNum}, 閿欒: {ex.Message}");
+                        }
+                    }
+                });
+
+                return WebResponseContent.Instance.OK($"鎴愬姛鍒涘缓 {taskList.Count} 涓嚭搴撲换鍔�", taskList.Count);
+            }
+            catch (Exception ex)
+            {
+                return WebResponseContent.Instance.Error($"鑷姩鍒涘缓鍑哄簱浠诲姟澶辫触: {ex.Message}");
+            }
+        }
+
+        #endregion WCS閫昏緫澶勭悊
 
         #region 鍒嗗鏌滄帴鍙�
 
@@ -436,7 +650,6 @@
                     var result = await BaseDal.AddDataAsync(taskList) > 0;
                     var wmstaskDto = result ? _mapper.Map<WMSTaskDTO>(taskList) : null;
 
-
                     var httpResponse = _httpClientHelper.Post<WebResponseContent>("http://logistics-service/api/logistics/notifyoutbound", JsonSerializer.Serialize(wmstaskDto)).Data;
                     if (result && httpResponse != null)
                     {
@@ -491,6 +704,6 @@
             }
         }
 
-        #endregion
+        #endregion 鍒嗗鏌滄帴鍙�
     }
-}
+}
\ No newline at end of file

--
Gitblit v1.9.3