wanshenmean
4 天以前 f7ec7a32e8cddcb976093c826e3a0d1ed61fb335
Code/WMS/WIDESEA_WMSServer/WIDESEA_TaskInfoService/TaskService_WCS.cs
@@ -1,26 +1,15 @@
using Mapster;
using MapsterMapper;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using System.DirectoryServices.Protocols;
using System.Text.Json;
using WIDESEA_Common.Constants;
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
@@ -182,22 +171,52 @@
                if (stockInfo == null) return WebResponseContent.Instance.Error("未找到对应库存信息");
                // 判断是不是极卷库任务
                //if (taskDto.WarehouseId == (int)WarehouseEnum.FJ1 || taskDto.WarehouseId == (int)WarehouseEnum.ZJ1)
                //{
                //    return WebResponseContent.Instance.OK();
                //}
                if (taskDto.WarehouseId == (int)WarehouseEnum.FJ1 || taskDto.WarehouseId == (int)WarehouseEnum.ZJ1)
                {
                    return await CompleteAgvInboundTaskAsync(taskDto);
                }
                return await ExecuteWithinTransactionAsync(async () =>
                {
                    WebResponseContent content = new WebResponseContent();
                    stockInfo.LocationCode = location.LocationCode;
                    stockInfo.LocationId = location.Id;
                    stockInfo.OutboundDate = task.Roadway switch
                    var now = DateTime.Now;
                    if (task.Roadway.Contains("GW"))
                    {
                        var r when r.Contains("GW") => DateTime.Now.AddHours(2),
                        var r when r.Contains("CW") => DateTime.Now.AddHours(1),
                        _ => DateTime.Now
                    };
                        if (stockInfo.Remark.IsNullOrEmpty())
                        {
                            stockInfo.OutboundDate = now.AddHours(OutboundTimeConstants.OUTBOUND_HOURS_GW1_FIRST);
                            stockInfo.Remark = StockRemarkConstants.GW1;
                        }
                        else if (stockInfo.Remark == StockRemarkConstants.GW1)
                        {
                            stockInfo.OutboundDate = now.AddHours(OutboundTimeConstants.OUTBOUND_HOURS_GW1_SECOND);
                            stockInfo.Remark = StockRemarkConstants.GW2;
                        }
                        else
                        {
                            stockInfo.OutboundDate = now.AddHours(OutboundTimeConstants.OUTBOUND_HOURS_GW1_FIRST);
                        }
                    }
                    else if (task.Roadway.Contains("CW"))
                    {
                        if (stockInfo.Remark == StockRemarkConstants.GW2)
                        {
                            stockInfo.OutboundDate = now.AddHours(OutboundTimeConstants.OUTBOUND_HOURS_CW1);
                            stockInfo.Remark = StockRemarkConstants.CW1;
                        }
                        else
                        {
                            stockInfo.OutboundDate = now.AddHours(OutboundTimeConstants.OUTBOUND_HOURS_CW1);
                        }
                    }
                    else
                    {
                        stockInfo.OutboundDate = now;
                    }
                    stockInfo.StockStatus = StockStatusEmun.入库完成.GetHashCode();
                    location.LocationStatus = LocationStatusEnum.InStock.GetHashCode();
@@ -207,18 +226,18 @@
                    if (!updateLocationResult || !updateStockResult)
                        return WebResponseContent.Instance.Error("任务完成失败");
                    // 调用MES托盘进站
                    var inboundRequest = new InboundInContainerRequest
                    {
                        EquipmentCode = "STK-GROUP-001",
                        ResourceCode = "STK-GROUP-001",
                        LocalTime = DateTime.Now,
                        ContainerCode = taskDto.PalletCode
                    };
                    var inboundResult = _mesService.InboundInContainer(inboundRequest);
                    if (inboundResult == null || inboundResult.Data == null || !inboundResult.Data.IsSuccess)
                    {
                        return content.Error($"任务完成失败:MES进站失败: {inboundResult?.Data?.Msg ?? inboundResult?.ErrorMessage ?? "未知错误"}");
                    }
                    //var inboundRequest = new InboundInContainerRequest
                    //{
                    //    EquipmentCode = "STK-GROUP-001",
                    //    ResourceCode = "STK-GROUP-001",
                    //    LocalTime = DateTime.Now,
                    //    ContainerCode = taskDto.PalletCode
                    //};
                    //var inboundResult = _mesService.InboundInContainer(inboundRequest);
                    //if (inboundResult == null || inboundResult.Data == null || !inboundResult.Data.IsSuccess)
                    //{
                    //    return content.Error($"任务完成失败:MES进站失败: {inboundResult?.Data?.Msg ?? inboundResult?.ErrorMessage ?? "未知错误"}");
                    //}
                    return await CompleteTaskAsync(task, "入库完成");
                });
            }
@@ -249,8 +268,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 +279,7 @@
                return await ExecuteWithinTransactionAsync(async () =>
                {
                    stockInfo.LocationId = 0;
                    stockInfo.LocationCode = null;
                    stockInfo.LocationCode = string.Empty;
                    stockInfo.OutboundDate = DateTime.Now;
                    location.LocationStatus = LocationStatusEnum.Free.GetHashCode();
@@ -270,22 +289,40 @@
                    if (!updateLocationResult || !updateStockResult)
                        return WebResponseContent.Instance.Error("任务完成失败");
                    // 调用MES托盘出站
                    var outboundRequest = new OutboundInContainerRequest
                    // 高温2号出库到CWSC1时,自动创建入库任务到常温1号巷道
                    WMSTaskDTO? inboundTaskDto = null;
                    if (task.TargetAddress == TaskAddressConstants.GW2_ADDRESS)
                    {
                        EquipmentCode = "STK-GROUP-001",
                        ResourceCode = "STK-GROUP-001",
                        LocalTime = DateTime.Now,
                        ContainerCode = taskDto.PalletCode,
                        ParamList = new List<ParamItem>()
                    };
                    var outboundResult = _mesService.OutboundInContainer(outboundRequest);
                    if (outboundResult == null || outboundResult.Data == null || !outboundResult.Data.IsSuccess)
                    {
                        return content.Error($"任务完成失败:MES出站失败: {outboundResult?.Data?.Msg ?? outboundResult?.ErrorMessage ?? "未知错误"}");
                        var inboundTask = new Dt_Task
                        {
                            TaskNum = await BaseDal.GetTaskNo(),
                            PalletCode = task.PalletCode,
                            PalletType = task.PalletType,
                            Roadway = "CW1",
                            TaskType = TaskInboundTypeEnum.Inbound.GetHashCode(),
                            TaskStatus = TaskInStatusEnum.InNew.GetHashCode(),
                            SourceAddress = task.TargetAddress,
                            TargetAddress = task.TargetAddress,
                            CurrentAddress = task.TargetAddress,
                            NextAddress = task.TargetAddress,
                            WarehouseId = (int)WarehouseEnum.CW1,
                            Grade = 1,
                            Creater = "system_auto"
                        };
                        await Repository.AddDataAsync(inboundTask);
                        inboundTaskDto = _mapper.Map<WMSTaskDTO>(inboundTask);
                    }
                    return await CompleteTaskAsync(task, "出库完成");
                    var completeResult = await CompleteTaskAsync(task, "出库完成");
                    if (!completeResult.Status)
                        return completeResult;
                    // 返回入库任务信息(如果有)
                    if (inboundTaskDto != null)
                    {
                        return content.OK("出库完成,已创建入库任务", inboundTaskDto);
                    }
                    return content.OK("出库完成");
                });
            }
            catch (Exception ex)
@@ -396,19 +433,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("任务完成失败");
@@ -431,6 +462,13 @@
        {
            try
            {
                var dt_Task = await BaseDal.QueryFirstAsync(x => x.TargetAddress == taskDto.TargetAddress);
                if (!dt_Task.IsNullOrEmpty())
                {
                    var taskDTO = dt_Task.Adapt<WMSTaskDTO>();
                    return WebResponseContent.Instance.OK("任务创建成功", taskDTO);
                }
                var stockInfo = await _stockInfoService.Repository.QueryDataNavFirstAsync(x => x.LocationDetails.WarehouseId == taskDto.WarehouseId && x.LocationDetails.LocationStatus == LocationStatusEnum.InStock.GetHashCode() && x.StockStatus == StockStatusEmun.空托盘库存.GetHashCode());
                if (stockInfo == null)
                    return WebResponseContent.Instance.Error("未找到对应的库存信息");
@@ -451,12 +489,22 @@
                    TaskNum = await BaseDal.GetTaskNo(),
                    Creater = "system",
                };
                var taskDtos = task.Adapt<WMSTaskDTO>();
                var addResult = await BaseDal.AddDataAsync(task) > 0;
                if (!addResult)
                    return WebResponseContent.Instance.Error("任务创建失败");
                return WebResponseContent.Instance.OK("任务创建成功", taskDtos);
                return await ExecuteWithinTransactionAsync(async () =>
                {
                    var locationInfo = await _locationInfoService.GetLocationInfoAsync(stockInfo.LocationId);
                    locationInfo.LocationStatus = LocationStatusEnum.InStockLock.GetHashCode();
                    var updateLocationResult = await _locationInfoService.UpdateLocationInfoAsync(locationInfo);
                    if (!updateLocationResult)
                        return WebResponseContent.Instance.Error("任务创建失败");
                    var taskDtos = task.Adapt<WMSTaskDTO>();
                    var addResult = await BaseDal.AddDataAsync(task) > 0;
                    if (!addResult)
                        return WebResponseContent.Instance.Error("任务创建失败");
                    return WebResponseContent.Instance.OK("任务创建成功", taskDtos);
                });
            }
            catch (Exception ex)
            {
@@ -483,7 +531,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 +541,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("任务完成失败");
@@ -525,95 +567,25 @@
        /// <param name="taskId"></param>
        /// <param name="newStatus"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> UpdateTaskByStatusAsync(int taskId, int newStatus)
        public async Task<WebResponseContent> UpdateTaskByStatusAsync(UpdateTaskDto taskDto)
        {
            try
            {
                var tasks = await BaseDal.QueryFirstAsync(s => s.TaskNum == taskId);
                if (tasks == null)
                var taskInfo = await BaseDal.QueryFirstAsync(s => s.TaskNum == taskDto.Id);
                if (taskInfo == null)
                    return WebResponseContent.Instance.Error("未找到对应的任务");
                tasks.TaskStatus = newStatus;
                await BaseDal.UpdateDataAsync(tasks);
                taskInfo.TaskStatus = taskDto.NewStatus;
                taskInfo.NextAddress = taskDto.NextAddress;
                taskInfo.CurrentAddress = taskDto.CurrentAddress;
                await BaseDal.UpdateDataAsync(taskInfo);
                return WebResponseContent.Instance.OK("修改成功", tasks);
                return WebResponseContent.Instance.OK("修改成功", taskInfo);
            }
            catch (Exception ex)
            {
                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>
        /// 根据巷道确定目标地址(支持多出库口轮询)
        /// </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>
@@ -673,8 +645,9 @@
                var taskList = new List<Dt_Task>();
                foreach (var stock in stocksToProcess)
                {
                    // 根据巷道确定目标地址
                    var targetAddress = DetermineTargetAddress(
                    // 根据巷道确定目标地址(优先根据 Remark 确定,Remark 为空则根据巷道配置)
                    var targetAddress = DetermineTargetAddressByRemark(
                        stock.Remark ?? "",
                        stock.LocationDetails?.RoadwayNo ?? "",
                        targetAddressMap);
@@ -859,18 +832,19 @@
                    if (stockInfo.LocationId > 0 || !string.IsNullOrWhiteSpace(stockInfo.LocationCode))
                        return WebResponseContent.Instance.Error($"托盘[{stockPalletCode}]库存已绑定货位,不能创建机械手{taskName}任务");
                }
                var section = App.Configuration.GetSection("RobotTaskAddressRules").GetSection(targetLineNo).GetChildren().Select(c => c.Value).ToArray();
                var task = new Dt_Task
                {
                    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,
                    TargetAddress = targetLineNo,
                    CurrentAddress = sourceLineNo,
                    SourceAddress = section[0],
                    TargetAddress = section[1],
                    CurrentAddress = targetLineNo,
                    NextAddress = targetLineNo,
                    WarehouseId = stockInfo?.WarehouseId ?? 1,
                    Grade = 1,
@@ -882,7 +856,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)
@@ -891,6 +865,96 @@
            }
        }
        /// <summary>
        /// 手动创建任务
        /// </summary>
        /// <param name="dto">手动创建任务参数</param>
        /// <returns></returns>
        public async Task<WebResponseContent> CreateManualTaskAsync(CreateManualTaskDto dto)
        {
            try
            {
                int taskType;
                int taskStatus;
                switch (dto.TaskType)
                {
                    case "入库":
                        taskType = TaskInboundTypeEnum.Inbound.GetHashCode();
                        taskStatus = TaskInStatusEnum.InNew.GetHashCode();
                        break;
                    case "出库":
                        taskType = TaskOutboundTypeEnum.Outbound.GetHashCode();
                        taskStatus = TaskOutStatusEnum.OutNew.GetHashCode();
                        break;
                    case "移库":
                        taskType = TaskRelocationTypeEnum.Relocation.GetHashCode();
                        taskStatus = TaskRelocationStatusEnum.RelocationNew.GetHashCode();
                        break;
                    default:
                        return WebResponseContent.Instance.Error($"不支持的任务类型: {dto.TaskType}");
                }
                int taskNum = await BaseDal.GetTaskNo();
                var task = new Dt_Task
                {
                    TaskNum = taskNum,
                    PalletCode = dto.Barcode,
                    SourceAddress = dto.SourceAddress,
                    TargetAddress = dto.TargetAddress,
                    TaskType = taskType,
                    TaskStatus = taskStatus,
                    Grade = dto.Grade,
                    Roadway = dto.TargetAddress,
                    WarehouseId = dto.WarehouseId,
                    CurrentAddress = dto.SourceAddress,
                    NextAddress = dto.TargetAddress,
                    Creater = "manual",
                    CreateDate = DateTime.Now,
                    ModifyDate = DateTime.Now
                };
                var wmsTaskDtos = new List<WMSTaskDTO>()
                {
                    new()
                    {
                        TaskNum = task.TaskNum,
                        PalletCode = task.PalletCode,
                        SourceAddress = task.SourceAddress,
                        TargetAddress = task.TargetAddress,
                        TaskType = task.TaskType,
                        Roadway = task.Roadway,
                        TaskStatus = task.TaskStatus,
                        WarehouseId = task.WarehouseId
                    }
                };
               return await _unitOfWorkManage.BeginTranAsync(async () =>
                {
                    // 4. 保存到数据库
                    var result = await BaseDal.AddDataAsync(task) > 0;
                    if (!result)
                        return WebResponseContent.Instance.Error("创建任务失败");
                    var wcsResult = _httpClientHelper.Post<WebResponseContent>(
                        "http://localhost:9292/api/Task/ReceiveManualTask",
                        wmsTaskDtos.ToJson());
                    if (!wcsResult.IsSuccess || !wcsResult.Data.Status)
                        return WebResponseContent.Instance.Error($"任务已创建但发送给WCS失败: {wcsResult.Data?.Message}");
                    return WebResponseContent.Instance.OK($"手动创建任务成功,任务号: {taskNum}");
                });
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error($"手动创建任务异常: {ex.Message}");
            }
        }
        #endregion WCS逻辑处理
    }
}
}