wangxinhui
2025-11-30 f2b85c65234e0dcdd3fcce4dafbe16933b7f1b48
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 命名空间:WIDESEAWCS_TaskInfoService
 * 创建者:胡童庆
 * 创建时间:2024/8/2 16:13:36
 * 版本:V1.0.0
 * 描述:
 *
 * ----------------------------------------------------------------
 * 修改人:
 * 修改时间:
 * 版本:V1.0.1
 * 修改说明:
 * 
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
using AutoMapper;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using System.Diagnostics.CodeAnalysis;
using System.DirectoryServices.Protocols;
using System.Net.Http.Headers;
using System.Security.Policy;
using WIDESEA_DTO.Agv;
using WIDESEA_External.Model;
using WIDESEAWCS_Common;
using WIDESEAWCS_Common.APIEnum;
using WIDESEAWCS_Common.TaskEnum;
using WIDESEAWCS_Core;
using WIDESEAWCS_Core.BaseRepository;
using WIDESEAWCS_Core.BaseServices;
using WIDESEAWCS_Core.Enums;
using WIDESEAWCS_Core.Helper;
using WIDESEAWCS_Core.LogHelper;
using WIDESEAWCS_DTO;
using WIDESEAWCS_DTO.Agv;
using WIDESEAWCS_DTO.TaskInfo;
using WIDESEAWCS_IBasicInfoRepository;
using WIDESEAWCS_ITaskInfoRepository;
using WIDESEAWCS_ITaskInfoService;
using WIDESEAWCS_Model.Models;
using WIDESEAWCS_QuartzJob.Models;
using WIDESEAWCS_QuartzJob.Repository;
using WIDESEAWCS_QuartzJob.Service;
using ICacheService = WIDESEAWCS_Core.Caches.ICacheService;
 
namespace WIDESEAWCS_TaskInfoService
{
    public partial class TaskService : ServiceBase<Dt_Task, ITaskRepository>, ITaskService
    {
        private readonly IMapper _mapper;
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        private readonly ICacheService _cacheService;
        private readonly IRouterService _routerService;
        private readonly ITaskExecuteDetailService _taskExecuteDetailService;
        private readonly ITaskExecuteDetailRepository _taskExecuteDetailRepository;
        private readonly IStationMangerRepository _stationMangerRepository;
        private readonly IRouterRepository _routerRepository;
        private readonly IApiInfoRepository _apiInfoRepository;
        private readonly ILocationInfoRepository _locationInfoRepository;
 
        private Dictionary<string, OrderByType> _taskOrderBy = new()
            {
                {nameof(Dt_Task.Grade),OrderByType.Desc },
                {nameof(Dt_Task.TaskNum),OrderByType.Asc},
                {nameof(Dt_Task.CreateDate),OrderByType.Asc},
            };
 
 
        public Dictionary<string, OrderByType> TaskOrderBy { get { return _taskOrderBy; } set { _taskOrderBy = value; } }
 
        public List<int> TaskInboundTypes => typeof(TaskTypeEnum).GetEnumIndexList().Where(x => x >= 500 && x < 900).ToList();
 
        public List<int> TaskOutboundTypes => typeof(TaskTypeEnum).GetEnumIndexList().Where(x => x >= 100 && x < 500).ToList();
 
        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)
        {
            _mapper = mapper;
            _cacheService = cacheService;
            _routerService = routerService;
            _taskExecuteDetailService = taskExecuteDetailService;
            _taskExecuteDetailRepository = taskExecuteDetailRepository;
            _stationMangerRepository = stationMangerRepository;
            _routerRepository = routerRepository;
            _apiInfoRepository = apiInfoRepository;
            _locationInfoRepository = locationInfoRepository;
            _unitOfWorkManage = unitOfWorkManage;
        }
        static object lock_taskReceive = new object();
        /// <summary>
        /// 接收WMS任务信息
        /// </summary>
        /// <param name="taskDTOs">WMS任务对象集合</param>
        /// <returns>返回处理结果</returns>
        public WebResponseContent ReceiveWMSTask([NotNull] WMSTaskDTO taskDTO)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                lock (lock_taskReceive)
                {
                    List<Dt_Task> tasks = new List<Dt_Task>();
                    List<Dt_LocationInfo> locationInfos = _locationInfoRepository.GetCanOut(taskDTO.Tasks.Select(x=>x.ContainerCode).ToList());
                    TasksItem? tasksItem = taskDTO.Tasks.FirstOrDefault(x => !locationInfos.Select(t => t.PalletCode).Contains(x.ContainerCode));
                    if (tasksItem != null) throw new Exception($"任务{tasksItem.TaskCode}料箱号{tasksItem.ContainerCode}不存在");
                    Dt_LocationInfo? noOutLocation = locationInfos.FirstOrDefault(x=>x.LocationStatus != LocationStatusEnum.InStock.ObjToInt() || x.EnableStatus != EnableStatusEnum.Normal.ObjToInt());
                    if (noOutLocation != null) throw new Exception($"料箱{noOutLocation.PalletCode}货位{noOutLocation.LocationCode}状态不可出库");
                    List<Dt_StationManger> stationMangers = _stationMangerRepository.QueryData();
                    //下发任务组
                    string taskGroup= taskDTO.TaskGroupCode.IsNullOrEmpty() ? Guid.NewGuid().ToString().Replace("-","") : taskDTO.TaskGroupCode;
                    foreach (var item in taskDTO.Tasks)
                    {
                        if (item.ToStationCode.IsNullOrEmpty()) throw new Exception($"任务{item.TaskCode}出库目标操作台不能为空");
                        //获取操作台
                        Dt_StationManger? stationManger = stationMangers.FirstOrDefault(x => x.PickStationCode == item.ToStationCode);
                        if (stationManger == null) throw new Exception($"任务{item.TaskCode}出库目标操作台{item.ToStationCode}不存在");
                        Dt_Task task = _mapper.Map<Dt_Task>(item);
                        Dt_LocationInfo locationInfo = locationInfos.FirstOrDefault(x=>x.PalletCode==item.ContainerCode);
                        task.SourceAddress = locationInfo.LocationCode;
                        task.CurrentAddress = locationInfo.LocationCode;
                        task.NextAddress = stationManger.PickStationCode;
                        task.TargetAddress = stationManger.PickStationCode;
                        task.GroupId = taskGroup;
                        task.TaskType = TaskTypeEnum.Outbound.ObjToInt();
                        task.Roadway = locationInfo.RoadwayNo;
                        task.DeviceCode = "AGV";
                        task.TaskState = TaskStatusEnum.AGV_Execute.ObjToInt();
                        tasks.Add(task);
                    }
 
                    locationInfos.ForEach(x =>
                    {
                        x.LocationStatus=LocationStatusEnum.Lock.ObjToInt();
                    });
                    //添加任务更新货位数据
                    _unitOfWorkManage.BeginTran();
                    BaseDal.AddData(tasks);
                    _locationInfoRepository.UpdateData(locationInfos);
                    _unitOfWorkManage.CommitTran();
 
                    _taskExecuteDetailService.AddTaskExecuteDetail(tasks.Select(x => x.TaskNum).ToList(), "接收WMS任务");
 
                    content = tasks.Count > 0 ? content.OK("成功") : content.Error("失败");
                }
            }
            catch (Exception ex)
            {
                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;
            DateTime beginDate = DateTime.Now;
            try
            {
                using (HttpContent httpContent = new StringContent(requestJson))
                {
                    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
 
                    using HttpClient httpClient = new HttpClient();
                    httpClient.Timeout = new TimeSpan(0, 0, 30);
                    string LoginToken = AppSettings.Get("MESLoginToken");
                    headers = new Dictionary<string, string>
                    {
                        //正式
                        { "LoginToken", LoginToken }
                    };
                    if (headers != null)
                    {
                        foreach (var header in headers)
                            httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                    HttpResponseMessage responseMessage = httpClient.PostAsync(serviceAddress, httpContent).Result;
                    result = responseMessage.Content.ReadAsStringAsync().Result;
                }
                return result;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                Logger.Add(serviceAddress, requestJson == null ? "" : requestJson, result, beginDate);
            }
        }
 
        /// <summary>
        /// 更新任务异常信息显示
        /// </summary>
        /// <param name="taskNum">任务号</param>
        /// <param name="message">异常信息</param>
        public WebResponseContent UpdateTaskExceptionMessage(int taskNum, string message)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                Dt_Task task = BaseDal.QueryFirst(x => x.TaskNum == taskNum);
                if (task == null) return WebResponseContent.Instance.Error($"未找到该任务信息,任务号:【{taskNum}】");
                task.TaskState = (int)TaskStatusEnum.Pending;
                task.ExceptionMessage = message;
                task.ModifyDate = DateTime.Now;
                BaseDal.UpdateData(task);
 
                _taskExecuteDetailService.AddTaskExecuteDetail(task.TaskNum, task.ExceptionMessage);
 
                content = WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
 
        /// <summary>
        /// 恢复挂起任务
        /// </summary>
        /// <param name="taskNum">任务号</param>
        /// <returns>返回处理结果</returns>
        public WebResponseContent TaskStatusRecovery(int taskNum)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                Dt_Task task = BaseDal.QueryFirst(x => x.TaskNum == taskNum);
                if (task == null) return WebResponseContent.Instance.Error($"未找到该任务信息,任务号:【{taskNum}】");
                if (task.TaskState != (int)TaskStatusEnum.Pending)
                {
                    return content = WebResponseContent.Instance.Error($"该任务状态不可恢复,任务号:【{taskNum}】,任务状态:【{task.TaskState}】");
                }
 
                Dt_TaskExecuteDetail taskExecuteDetail = _taskExecuteDetailRepository.QueryFirst(x => x.TaskId == task.TaskId && x.IsNormal, new Dictionary<string, OrderByType> { { nameof(Dt_TaskExecuteDetail.TaskDetailId), OrderByType.Desc } });
                if (taskExecuteDetail != null)
                {
                    task.TaskState = taskExecuteDetail.TaskState;
                }
                else
                {
                    task.TaskState = (int)TaskStatusEnum.New;
                }
 
                task.ExceptionMessage = string.Empty;
 
                BaseDal.UpdateData(task);
 
                _taskExecuteDetailService.AddTaskExecuteDetail(task.TaskNum, $"人工恢复挂起任务,恢复挂起时任务状态【{task.TaskState}】");
 
                content = WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
 
        /// <summary>
        /// 回滚任务状态
        /// </summary>
        /// <param name="taskNum">任务号</param>
        /// <returns>返回处理结果</returns>
        public WebResponseContent RollbackTaskStatusToLast(int taskNum)
        {
            WebResponseContent content = new();
            try
            {
                Dt_Task task = BaseDal.QueryFirst(x => x.TaskNum == taskNum);
                if (task == null) return WebResponseContent.Instance.Error($"未找到该任务信息,任务号:【{taskNum}】");
 
                int oldState = task.TaskState;
                Dt_TaskExecuteDetail taskExecuteDetail = _taskExecuteDetailRepository.QueryFirst(x => x.TaskId == task.TaskId && x.TaskState < task.TaskState && x.TaskState > 0, new Dictionary<string, OrderByType> { { nameof(Dt_TaskExecuteDetail.TaskDetailId), OrderByType.Desc } });
                if (taskExecuteDetail != null)
                {
                    task.TaskState = taskExecuteDetail.TaskState;
                    task.CurrentAddress = taskExecuteDetail.CurrentAddress;
                    task.NextAddress = taskExecuteDetail.NextAddress;
                }
                else
                {
                    return content = WebResponseContent.Instance.Error($"未找到任务明细信息,该任务状态不可回滚到上一步,任务号:【{taskNum}】,任务状态:【{task.TaskState}】");
                }
 
                task.ExceptionMessage = string.Empty;
 
                BaseDal.UpdateData(task);
 
                _taskExecuteDetailService.AddTaskExecuteDetail(task.TaskNum, $"人工将任务状态从【{oldState}】回滚到【{task.TaskState}】");
 
                content = WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
 
        
        /// <summary>
        /// 接受WMS手动完成任务
        /// </summary>
        /// <param name="taskNum"></param>
        /// <returns></returns>
        public WebResponseContent RecWMSTaskCompleted(int taskNum)
        {
            try
            {
                Dt_Task task = BaseDal.QueryFirst(x => x.TaskNum == taskNum);
                if (task != null)
                {
                    task.TaskState = TaskStatusEnum.Finish.ObjToInt();
                    BaseDal.DeleteAndMoveIntoHty(task, OperateTypeEnum.人工完成);
                }
                return WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
        /// <summary>
        /// AGV任务放行
        /// </summary>
        /// <returns></returns>
        public WebResponseContent AgvTaskFlow(string code)
        {
            WebResponseContent content=new WebResponseContent();
            try
            {
                string? url = _apiInfoRepository.QueryFirst(x => x.ApiCode == APIEnum.AgvTaskFlow.ToString())?.ApiAddress;
                if (string.IsNullOrEmpty(url)) throw new Exception($"{code},未找到AGV任务放行接口,请检查接口配置");
                AgvTaskFlowDTO agvTaskFlowDTO = new AgvTaskFlowDTO()
                {
                    RequestId = Guid.NewGuid().ToString().Replace("-", ""),
                    ContainerCode = code
                };
                string request = JsonConvert.SerializeObject(agvTaskFlowDTO, settings);
                string response = HttpHelper.Post(url, request);
                AgvResponseContent agvResponse = JsonConvert.DeserializeObject<AgvResponseContent>(response) ?? throw new Exception($"{code},未接收到AGV任务放行返回值");
                if (!agvResponse.Success) throw new Exception($"料箱{code},AGV任务放行错误,信息:{agvResponse.Message}");
                content.OK();
            }
            catch (Exception ex)
            {
                content.Error(ex.Message);
            }
            return content;
        }
        /// <summary>
        /// WMS料箱到达拣选位上报
        /// </summary>
        /// <returns></returns>
        public WebResponseContent WMSPickUp(string stationCode,string pickCode)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                string? url = _apiInfoRepository.QueryFirst(x => x.ApiCode == APIEnum.WMSPickArrivedUp.ToString())?.ApiAddress;
                if (string.IsNullOrEmpty(url)) throw new Exception($"未找到WMS料箱到达拣选位上报接口,请检查接口配置");
                ContainerArriveDTO containerArriveDTO = new ContainerArriveDTO()
                {
                    SlotCode = stationCode,
                    ContainerCode = pickCode
                };
                string request = JsonConvert.SerializeObject(containerArriveDTO, settings);
                string response = HttpHelper.Post(url, request);
                WMSResponseContent wMSResponse = JsonConvert.DeserializeObject<WMSResponseContent>(response) ?? throw new Exception($"{pickCode},未接收到WMS料箱到达拣选位上报返回值");
                if (wMSResponse.Code != "0") throw new Exception($"料箱{pickCode}WMS料箱到达拣选位上报错误,信息:{wMSResponse.Msg}");
                content.OK();
            }
            catch (Exception ex)
            {
                content.Error(ex.Message);
            }
            return content;
        }
        /// <summary>
        /// 任务完成
        /// </summary>
        /// <param name="taskNum"></param>
        /// <returns></returns>
        public WebResponseContent TaskCompleted(int taskNum)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                Dt_Task task = BaseDal.QueryFirst(x => x.TaskNum == taskNum);
                if (task != null && task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.OutbondGroup)//出库任务逻辑
                {
                    Dt_LocationInfo locationInfo = _locationInfoRepository.QueryFirst(x=>x.PalletCode==task.PalletCode);
                    if (locationInfo.LocationStatus != LocationStatusEnum.Lock.ObjToInt())
                    {
                        return content.Error($"{locationInfo.LocationCode}货位状态不正确");
                    }
                    task.TaskState = TaskStatusEnum.Finish.ObjToInt();
                    locationInfo.LocationStatus = LocationStatusEnum.Free.ObjToInt();
                    locationInfo.PalletCode = "";
                    _unitOfWorkManage.BeginTran();
                    _locationInfoRepository.UpdateData(locationInfo);
                    BaseDal.DeleteAndMoveIntoHty(task, App.User?.UserId == 0 ? OperateTypeEnum.自动完成 : OperateTypeEnum.人工完成);
                    _unitOfWorkManage.CommitTran();
                }
                else if(task != null && task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.InboundGroup)//入库任务逻辑
                {
                    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}");
                }
                content.OK("任务完成");
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                content.Error(ex.Message);
            }
            return content;
        }
    }
}