wangxinhui
2025-12-01 e3cfda747bd53f4550904d60cd13aa8f4e525739
ÏîÄ¿´úÂë/WCSServices/WIDESEAWCS_TaskInfoService/TaskService.cs
@@ -15,6 +15,7 @@
 *----------------------------------------------------------------*/
#endregion << ç‰ˆ æœ¬ æ³¨ é‡Š >>
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using SqlSugar;
@@ -37,6 +38,7 @@
using WIDESEAWCS_DTO.Agv;
using WIDESEAWCS_DTO.TaskInfo;
using WIDESEAWCS_IBasicInfoRepository;
using WIDESEAWCS_IBasicInfoService;
using WIDESEAWCS_ITaskInfoRepository;
using WIDESEAWCS_ITaskInfoService;
using WIDESEAWCS_Model.Models;
@@ -59,6 +61,7 @@
        private readonly IRouterRepository _routerRepository;
        private readonly IApiInfoRepository _apiInfoRepository;
        private readonly ILocationInfoRepository _locationInfoRepository;
        private readonly ILocationInfoService _locationInfoService;
        private Dictionary<string, OrderByType> _taskOrderBy = new()
            {
@@ -76,7 +79,7 @@
        public List<int> TaskRelocationTypes => typeof(TaskTypeEnum).GetEnumIndexList().Where(x => x >= 900 && x < 1000).ToList();
        public TaskService(ITaskRepository BaseDal, IMapper mapper, ICacheService cacheService, IRouterService routerService, ITaskExecuteDetailService taskExecuteDetailService, ITaskExecuteDetailRepository taskExecuteDetailRepository, IStationMangerRepository stationMangerRepository, IRouterRepository routerRepository, IApiInfoRepository apiInfoRepository,ILocationInfoRepository locationInfoRepository,IUnitOfWorkManage unitOfWorkManage) : base(BaseDal)
        public TaskService(ITaskRepository BaseDal, IMapper mapper, ICacheService cacheService, IRouterService routerService, ITaskExecuteDetailService taskExecuteDetailService, ITaskExecuteDetailRepository taskExecuteDetailRepository, IStationMangerRepository stationMangerRepository, IRouterRepository routerRepository, IApiInfoRepository apiInfoRepository,ILocationInfoRepository locationInfoRepository,IUnitOfWorkManage unitOfWorkManage, ILocationInfoService locationInfoService) : base(BaseDal)
        {
            _mapper = mapper;
            _cacheService = cacheService;
@@ -88,6 +91,7 @@
            _apiInfoRepository = apiInfoRepository;
            _locationInfoRepository = locationInfoRepository;
            _unitOfWorkManage = unitOfWorkManage;
            _locationInfoService = locationInfoService;
        }
        static object lock_taskReceive = new object();
        /// <summary>
@@ -111,7 +115,7 @@
                    List<Dt_StationManger> stationMangers = _stationMangerRepository.QueryData();
                    //下发任务组
                    string taskGroup= taskDTO.TaskGroupCode.IsNullOrEmpty() ? Guid.NewGuid().ToString().Replace("-","") : taskDTO.TaskGroupCode;
                    foreach (var item in taskDTO.Tasks)
                    foreach (var item in taskDTO.Tasks.OrderBy(x=>x.ToStationCode))
                    {
                        if (item.ToStationCode.IsNullOrEmpty()) throw new Exception($"任务{item.TaskCode}出库目标操作台不能为空");
                        //获取操作台
@@ -126,7 +130,7 @@
                        task.GroupId = taskGroup;
                        task.TaskType = TaskTypeEnum.Outbound.ObjToInt();
                        task.Roadway = locationInfo.RoadwayNo;
                        task.DeviceCode = "AGV";
                        task.DeviceCode = stationManger.CraneCode;
                        task.TaskState = TaskStatusEnum.AGV_Execute.ObjToInt();
                        tasks.Add(task);
                    }
@@ -152,7 +156,89 @@
            }
            return content;
        }
        static object lock_containerFlow = new object();
        /// <summary>
        /// å®¹å™¨å…¥åº“创建任务
        /// </summary>
        /// <returns></returns>
        public WebResponseContent ContainerFlow(ContainerFlowDTO containerFlowDTO, string deviceCode)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                lock (lock_containerFlow)
                {
                    List<Dt_LocationInfo> locationInfos = _locationInfoRepository.QueryData();
                    Dt_LocationInfo? locationInfo = locationInfos.FirstOrDefault(x=>x.PalletCode== containerFlowDTO.ContainerCode);
                    if (locationInfo != null) throw new Exception($"料箱号{containerFlowDTO.ContainerCode}已存在");
                    if (BaseDal.QueryFirst(x=>x.PalletCode==containerFlowDTO.ContainerCode)!=null) throw new Exception($"料箱号{containerFlowDTO.ContainerCode}任务已存在");
                    Dt_LocationInfo? noInLocation = locationInfos.FirstOrDefault(x => x.LocationStatus == LocationStatusEnum.Free.ObjToInt() && x.EnableStatus == EnableStatusEnum.Normal.ObjToInt());
                    if (noInLocation == null) throw new Exception($"可用货位不足!");
                    Dt_StationManger stationManger = _stationMangerRepository.QueryFirst(x => x.StationType == StationTypeEnum.StationType_OnlyInbound.ObjToInt() && x.StationDeviceCode == deviceCode);
                    //下发任务组
                    Dt_Task task = new Dt_Task();
                    task.PalletCode = containerFlowDTO.ContainerCode;
                    task.SourceAddress = containerFlowDTO.SlotCode;
                    task.CurrentAddress = containerFlowDTO.SlotCode;
                    task.NextAddress = stationManger.StationCode;
                    task.TargetAddress = "";
                    task.WMSId = "";
                    task.TaskType = TaskTypeEnum.Inbound.ObjToInt();
                    task.Roadway = noInLocation.RoadwayNo;
                    task.DeviceCode = stationManger.StationDeviceCode;
                    task.TaskState = TaskStatusEnum.CL_Executing.ObjToInt();
                    //添加任务
                    BaseDal.AddData(task);
                    _taskExecuteDetailService.AddTaskExecuteDetail(new List<int>() { task.TaskNum }, "创建入库任务");
                    content.OK("成功");
                }
            }
            catch (Exception ex)
            {
                content.Error($"错误信息:{ex.Message}");
            }
            return content;
        }
        static object lock_requestInTask = new object();
        /// <summary>
        /// ç”³è¯·å…¥åº“
        /// </summary>
        /// <returns></returns>
        public WebResponseContent RequestInTask(string stationCode,string barCode)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                lock (lock_requestInTask)
                {
                    Dt_Task task = BaseDal.QueryFirst(x => x.PalletCode == barCode && x.NextAddress == stationCode && x.TaskState == TaskStatusEnum.CL_Executing.ObjToInt());
                    if (task == null) throw new Exception($"{barCode}料箱未找到任务!");
                    Dt_LocationInfo? locationInfo = _locationInfoService.AssignLocation();
                    if (locationInfo == null) throw new Exception($"可用货位不足!");
                    task.NextAddress = locationInfo.LocationCode;
                    task.TargetAddress = locationInfo.LocationCode;
                    task.CurrentAddress = stationCode;
                    task.DeviceCode = "AGV";
                    task.TaskState = TaskStatusEnum.AGV_Execute.ObjToInt();
                    locationInfo.LocationStatus = LocationStatusEnum.Lock.ObjToInt();
                    //更新任务和货位数据
                    _unitOfWorkManage.BeginTran();
                    BaseDal.UpdateData(task);
                    _locationInfoRepository.UpdateData(locationInfo);
                    _unitOfWorkManage.CommitTran();
                    _taskExecuteDetailService.AddTaskExecuteDetail(new List<int>() { task.TaskNum }, $"分配货位{locationInfo.LocationCode}");
                    content.OK("成功");
                }
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                content.Error($"错误信息:{ex.Message}");
            }
            return content;
        }
        public static string Post(string serviceAddress, string requestJson = "", string contentType = "application/json", Dictionary<string, string>? headers = null)
        {
            string result = string.Empty;
@@ -208,7 +294,7 @@
                task.ModifyDate = DateTime.Now;
                BaseDal.UpdateData(task);
                _taskExecuteDetailService.AddTaskExecuteDetail(task.TaskNum, task.ExceptionMessage);
                _taskExecuteDetailService.AddTaskExecuteDetail(task, task.ExceptionMessage);
                content = WebResponseContent.Instance.OK();
            }
@@ -250,7 +336,7 @@
                BaseDal.UpdateData(task);
                _taskExecuteDetailService.AddTaskExecuteDetail(task.TaskNum, $"人工恢复挂起任务,恢复挂起时任务状态【{task.TaskState}】");
                _taskExecuteDetailService.AddTaskExecuteDetail(task, $"人工恢复挂起任务,恢复挂起时任务状态【{task.TaskState}】");
                content = WebResponseContent.Instance.OK();
            }
@@ -291,7 +377,7 @@
                BaseDal.UpdateData(task);
                _taskExecuteDetailService.AddTaskExecuteDetail(task.TaskNum, $"人工将任务状态从【{oldState}】回滚到【{task.TaskState}】");
                _taskExecuteDetailService.AddTaskExecuteDetail(task, $"人工将任务状态从【{oldState}】回滚到【{task.TaskState}】");
                content = WebResponseContent.Instance.OK();
            }
@@ -339,7 +425,7 @@
                AgvTaskFlowDTO agvTaskFlowDTO = new AgvTaskFlowDTO()
                {
                    RequestId = Guid.NewGuid().ToString().Replace("-", ""),
                    ContainerCode = code
                    MissionCode = code
                };
                string request = JsonConvert.SerializeObject(agvTaskFlowDTO, settings);
                string response = HttpHelper.Post(url, request);
@@ -409,25 +495,37 @@
                }
                else if(task != null && task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.InboundGroup)//入库任务逻辑
                {
                    string? url = _apiInfoRepository.QueryFirst(x => x.ApiCode == APIEnum.WMSInBoundBack.ToString())?.ApiAddress;
                    if (string.IsNullOrEmpty(url))
                    //string? url = _apiInfoRepository.QueryFirst(x => x.ApiCode == APIEnum.WMSInBoundBack.ToString())?.ApiAddress;
                    //if (string.IsNullOrEmpty(url))
                    //{
                    //    _taskExecuteDetailService.AddTaskExecuteDetail(taskNum, $"未找到WMS入库上报接口,请检查接口配置");
                    //    UpdateTaskExceptionMessage(taskNum, $"未找到WMS入库上报接口,请检查接口配置");
                    //    return content.Error($"{taskNum},未找到WMS入库上报接口,请检查接口配置");
                    //}
                    //ContainerInFinishDTO containerInFinishDTO = new ContainerInFinishDTO()
                    //{
                    //    TaskCode= task.TaskNum.ToString(),
                    //    ContainerCode = task.PalletCode,
                    //    FromStationCode = task.SourceAddress,
                    //    ToLocationCode = task.TargetAddress
                    //};
                    //string request = JsonConvert.SerializeObject(containerInFinishDTO, settings);
                    ////调用接口
                    //string response = HttpHelper.Post(url, request);
                    //WMSResponseContent wMSResponse = JsonConvert.DeserializeObject<WMSResponseContent>(response) ??throw new Exception($"{taskNum},未接收到WMS入库上报返回值");
                    //if (wMSResponse.Code!="0") throw new Exception($"入库任务{task.TaskNum}WMS入库上报错误,信息:{wMSResponse.Msg}");
                    Dt_LocationInfo locationInfo = _locationInfoRepository.QueryFirst(x => x.LocationCode == task.TargetAddress);
                    if (locationInfo.LocationStatus != LocationStatusEnum.Lock.ObjToInt())
                    {
                        _taskExecuteDetailService.AddTaskExecuteDetail(taskNum, $"未找到WMS入库上报接口,请检查接口配置");
                        UpdateTaskExceptionMessage(taskNum, $"未找到WMS入库上报接口,请检查接口配置");
                        return content.Error($"{taskNum},未找到WMS入库上报接口,请检查接口配置");
                        return content.Error($"{locationInfo.LocationCode}货位状态不正确");
                    }
                    ContainerInFinishDTO containerInFinishDTO = new ContainerInFinishDTO()
                    {
                        TaskCode= task.TaskNum.ToString(),
                        ContainerCode = task.PalletCode,
                        FromStationCode = task.SourceAddress,
                        ToLocationCode = task.TargetAddress
                    };
                    string request = JsonConvert.SerializeObject(containerInFinishDTO, settings);
                    //调用接口
                    string response = HttpHelper.Post(url, request);
                    WMSResponseContent wMSResponse = JsonConvert.DeserializeObject<WMSResponseContent>(response) ??throw new Exception($"{taskNum},未接收到WMS入库上报返回值");
                    if (wMSResponse.Code!="0") throw new Exception($"入库任务{task.TaskNum}WMS入库上报错误,信息:{wMSResponse.Msg}");
                    task.TaskState = TaskStatusEnum.Finish.ObjToInt();
                    locationInfo.LocationStatus = LocationStatusEnum.InStock.ObjToInt();
                    locationInfo.PalletCode = task.PalletCode;
                    _unitOfWorkManage.BeginTran();
                    _locationInfoRepository.UpdateData(locationInfo);
                    BaseDal.DeleteAndMoveIntoHty(task, App.User?.UserId == 0 ? OperateTypeEnum.自动完成 : OperateTypeEnum.人工完成);
                    _unitOfWorkManage.CommitTran();
                }
                content.OK("任务完成");
            }