1
wangxinhui
2025-06-12 29cf70e7b7cffea11956fd99ff559239744bb2bf
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 命名空间:WIDESEAWCS_TaskInfoService
 * 创建者:胡童庆
 * 创建时间:2024/8/2 16:13:36
 * 版本:V1.0.0
 * 描述:
 *
 * ----------------------------------------------------------------
 * 修改人:
 * 修改时间:
 * 版本:V1.0.1
 * 修改说明:
 * 
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
 
using AutoMapper;
using HslCommunication.Enthernet;
using Newtonsoft.Json;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_DTO.Agv;
using WIDESEAWCS_Common.APIEnum;
using WIDESEAWCS_Common.TaskEnum;
using WIDESEAWCS_Core;
using WIDESEAWCS_Core.BaseServices;
using WIDESEAWCS_Core.Enums;
using WIDESEAWCS_Core.Helper;
using WIDESEAWCS_DTO.BasicInfo;
using WIDESEAWCS_DTO.System;
using WIDESEAWCS_DTO.TaskInfo;
using WIDESEAWCS_IBasicInfoRepository;
using WIDESEAWCS_ITaskInfoRepository;
using WIDESEAWCS_ITaskInfoService;
using WIDESEAWCS_Model.Models;
using WIDESEAWCS_QuartzJob;
using WIDESEAWCS_QuartzJob.Models;
using WIDESEAWCS_QuartzJob.Repository;
using WIDESEAWCS_QuartzJob.Service;
using WIDESEAWCS_TaskInfoRepository;
using ICacheService = WIDESEAWCS_Core.Caches.ICacheService;
 
namespace WIDESEAWCS_TaskInfoService
{
    public partial class TaskService : ServiceBase<Dt_Task, ITaskRepository>, ITaskService
    {
        private readonly IMapper _mapper;
        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 List<Dt_ApiInfo> apiInfos;
 
        private Dictionary<string, OrderByType> _taskOrderBy = new()
            {
                {nameof(Dt_Task.Grade),OrderByType.Desc },
                {nameof(Dt_Task.TaskNum),OrderByType.Asc},
                {nameof(Dt_Task.CreateDate),OrderByType.Asc},
            };
 
        private List<Dt_Warehouse>? Warehouses = new List<Dt_Warehouse>();
 
        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 TaskService(ITaskRepository BaseDal, IMapper mapper, ICacheService cacheService, IRouterService routerService, ITaskExecuteDetailService taskExecuteDetailService, ITaskExecuteDetailRepository taskExecuteDetailRepository, IStationMangerRepository stationMangerRepository, IRouterRepository routerRepository, IApiInfoRepository apiInfoRepository) : base(BaseDal)
        {
            _mapper = mapper;
            _cacheService = cacheService;
            _routerService = routerService;
            _taskExecuteDetailService = taskExecuteDetailService;
            _taskExecuteDetailRepository = taskExecuteDetailRepository;
            _stationMangerRepository = stationMangerRepository;
            _routerRepository = routerRepository;
            _apiInfoRepository = apiInfoRepository;
 
            string? cacheStr = _cacheService.Get(nameof(Dt_Warehouse));
            if (!string.IsNullOrEmpty(cacheStr))
            {
                Warehouses = JsonConvert.DeserializeObject<List<Dt_Warehouse>>(cacheStr);
            }
 
 
            string? apiInfoStr = _cacheService.Get("apiInfos");
            if (!string.IsNullOrEmpty(apiInfoStr))
            {
                List<Dt_ApiInfo>? infos = JsonConvert.DeserializeObject<List<Dt_ApiInfo>>(apiInfoStr);
                if (infos == null || infos.Count == 0)
                {
                    apiInfos = new List<Dt_ApiInfo>();
                }
                else
                {
                    apiInfos = infos;
                }
            }
        }
 
        public WebResponseContent TaskCompleted(int taskNum)
        {
            try
            {
                Dt_Task task = BaseDal.QueryFirst(x => x.TaskNum == taskNum);
                if (task != null)
                {
                    task.TaskState = TaskStatusEnum.Finish.ObjToInt();
                    BaseDal.DeleteAndMoveIntoHty(task, App.User?.UserId == 0 ? OperateTypeEnum.自动完成 : OperateTypeEnum.人工完成);
                }
                string? url = apiInfos.FirstOrDefault(x => x.ApiCode == APIEnum.FeedBackWMSTaskCompleted.ToString())?.ApiAddress;
                if (string.IsNullOrEmpty(url))
                {
                    _taskExecuteDetailService.AddTaskExecuteDetail(taskNum, $"未找到WMS任务完成接口,请检查接口配置");
                    UpdateTaskExceptionMessage(taskNum, $"未找到WMS任务完成接口,请检查接口配置");
                    return WebResponseContent.Instance.Error($"{taskNum},未找到WMS任务完成接口,请检查接口配置");
                }
                string responseStr = HttpHelper.Get(url + "?taskNum=" + taskNum);
                WebResponseContent content = JsonConvert.DeserializeObject<WebResponseContent>(responseStr) ?? WebResponseContent.Instance.Error($"{taskNum},未接收到任务完成返回值");
                return content;
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
        public WebResponseContent AgvCarrying(int row,int startColumn, int endColumn, int startlayer,int targetLayer)
        {
            try
            {
                List<Dt_Task> tasks = new List<Dt_Task>();
                for (int i = startColumn; i <= endColumn; i++)
                {
                    string column = i.ToString();
                    if (i<10)
                    {
                        column = "0" + i.ToString();
                    }
                    string layer = targetLayer.ToString();
                    if (targetLayer<10)
                    {
                        layer = "0"+targetLayer.ToString();
                    }
                    Dt_Task task = new Dt_Task()
                    {
                        WarehouseId = 7,
                        TaskNum = DateTime.Now.ToString("yyMMddHHmm").ObjToInt() + i,
                        PalletCode= DateTime.Now.ToString("yyMMddHHmm") +i,
                        PalletType=0,
                        DeviceCode="AGV_CP",
                        Roadway= "AGV_CP",
                        TaskType =999,
                        SourceAddress=string.Format($"AGV_CP-00{row}-0{column}-00{startlayer}-01"),
                        CurrentAddress=string.Format($"AGV_CP-00{row}-0{column}-00{startlayer}-01"),
                        TargetAddress= string.Format($"AGV_CP-00{row}-0{column}-00{layer}-01"),
                        NextAddress= string.Format($"AGV_CP-00{row}-0{column}-00{layer}-01"),
                        Grade=0,
                        WMSId=0,
                        AgvTaskNum = "CP" + DateTime.Now.ToString("yyMMddHHmm").ObjToInt() + i,
                        TaskState = TaskStatusEnum.New.ObjToInt(),
                        Remark= "测试空框"
                    };
                    tasks.Add(task);
                }
                BaseDal.AddData(tasks);
                return WebResponseContent.Instance.OK("");
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error(ex.Message);
            }
 
        }
        /// <summary>
        /// 接收WMS任务信息
        /// </summary>
        /// <param name="taskDTOs">WMS任务对象集合</param>
        /// <returns>返回处理结果</returns>
        public WebResponseContent ReceiveWMSTask([NotNull] List<WMSTaskDTO> taskDTOs)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                bool flag = false;
                List<Dt_Task> tasks = new List<Dt_Task>();
                foreach (var item in taskDTOs)
                {
                    if (BaseDal.QueryFirst(x => x.TaskNum == item.TaskNum || x.PalletCode == item.PalletCode) != null)
                    {
                        flag = true;
                        continue;
                    }
                    Dt_Task task = _mapper.Map<Dt_Task>(item);
                    task.Creater = "WMS";
                    task.TaskState = (int)TaskStatusEnum.New;
                    task.CurrentAddress = item.SourceAddress;
 
                    Dt_Router? router;
 
                    TaskTypeGroup taskTypeGroup = item.TaskType.GetTaskTypeGroup();
                    if (string.IsNullOrEmpty(item.AGVArea))
                    {
                        Dt_StationManger stationManger;
                        if (taskTypeGroup == TaskTypeGroup.InboundGroup)
                        {
                            stationManger = _stationMangerRepository.QueryFirst(x => x.StationCode == item.SourceAddress || x.StationDeviceCode == item.SourceAddress);
                            if (stationManger==null && task.TaskType==TaskTypeEnum.InProduct.ObjToInt())
                            {
                                stationManger = _stationMangerRepository.QueryFirst(x => x.StackerCraneCode==task.SourceAddress);
                                //转换成品仓起点站台
                                item.SourceAddress = stationManger.StationCode;
                                task.CurrentAddress = stationManger.StationCode;
                                task.SourceAddress = stationManger.StationCode;
                            }
                        }
                        else
                        {
                            stationManger = _stationMangerRepository.QueryFirst(x => x.StackerCraneCode == item.RoadWay || x.Remark==item.RoadWay);
                        }
                        if (stationManger == null)
                        {
                            return WebResponseContent.Instance.Error($"未找到站台配置信息");
                        }
 
                        List<Dt_Router> routers = _routerRepository.QueryData(x => x.InOutType == item.TaskType && (item.SourceAddress == x.StartPosi || item.RoadWay == x.StartPosi /*|| item.RoadWay == x.ChildPosiDeviceCode || item.RoadWay == x.ChildPosi*/));
                        router = routers.FirstOrDefault();
                        if (router == null)
                        {
                            return WebResponseContent.Instance.Error($"未找到路由配置信息");
                        }
 
                        if (routers.Count == 1)
                        {
                            if (taskTypeGroup == TaskTypeGroup.InboundGroup && item.TargetAddress == stationManger.StackerCraneCode)
                            {
                                task.NextAddress = router.NextPosi;
                                task.DeviceCode = stationManger.StationDeviceCode;
                            }
                            else if (item.TaskType == TaskTypeEnum.MesMatReturn.ObjToInt() && !router.IsEnd)
                            {
                                task.NextAddress = router.NextPosi;
                                task.DeviceCode = router.ChildPosi;
                            }
                            else if ((item.TaskType == TaskTypeEnum.MesPalletLargeReturn.ObjToInt() || item.TaskType == TaskTypeEnum.MesPalletSmallReturn.ObjToInt()) && router.IsEnd)
                            {
                                task.NextAddress = router.NextPosi;
                                task.DeviceCode = router.ChildPosi;
                            }
                            else if (item.TaskType == TaskTypeEnum.MesOutbound.ObjToInt() || item.TaskType == TaskTypeEnum.MesHandOutbound.ObjToInt() || item.TaskType == TaskTypeEnum.MesHandPickOutbound.ObjToInt() || (item.TaskType == TaskTypeEnum.OutAllocate.ObjToInt() && item.RoadWay.Contains("BC")))
                            {
                                task.NextAddress = router.NextPosi;
                                task.DeviceCode = stationManger.StackerCraneCode;
                                if (item.TaskType == TaskTypeEnum.MesOutbound.ObjToInt() && task.TargetAddress== "SCUTL-001")
                                {
                                    task.TaskState = TaskStatusEnum.MesPending.ObjToInt();
                                }
                                else
                                {
                                    task.TaskState = TaskStatusEnum.SC_Execute.ObjToInt();
                                }
                            }
                            else if (item.TaskType == TaskTypeEnum.MesOutbound.ObjToInt() && item.RoadWay.Contains("ZH"))
                            {
                                task.NextAddress = stationManger.StackerCraneStationCode;
                                task.DeviceCode = stationManger.StackerCraneCode;
                                task.TaskState = TaskStatusEnum.SC_Execute.ObjToInt();
                            }
                            else
                            {
                                task.NextAddress = taskTypeGroup == TaskTypeGroup.InboundGroup ? task.TargetAddress : router.NextPosi;
                                if (item.RoadWay.Contains("AGV_FL")|| (item.RoadWay.Contains("AGV_CP") && taskTypeGroup == TaskTypeGroup.OutbondGroup))
                                {
                                    task.DeviceCode = item.RoadWay;
                                    task.AgvTaskNum = item.RoadWay + DateTime.Now.ToString("yyyyMMdd") + item.TaskNum;
                                }
                                else if(item.RoadWay.Contains("AGV_CP") && taskTypeGroup == TaskTypeGroup.InboundGroup)
                                {
                                    task.DeviceCode = stationManger.StationDeviceCode;
                                    task.AgvTaskNum = task.Roadway + DateTime.Now.ToString("yyyyMMdd") + item.TaskNum;
                                }
                                else
                                {
                                    task.DeviceCode = stationManger.StationDeviceCode;
                                }
                            }
                        }
                        else
                        {
                            if (item.RoadWay=="AGV_CP")
                            {
                                Dt_Router routerSelect = _routerRepository.QueryFirst(x => x.InOutType == item.TaskType && item.RoadWay == x.StartPosi && x.NextPosi==item.TargetAddress);
                                if (routerSelect != null)
                                {
                                    task.NextAddress = routerSelect.NextPosi;
                                    task.DeviceCode = routerSelect.ChildPosi;
                                    task.AgvTaskNum = item.RoadWay + DateTime.Now.ToString("yyyyMMdd") + item.TaskNum;
                                }
                                else
                                {
                                    return content.Error("未找到路由信息");
                                }
                            }
                            else
                            {
                                List<Dt_Router> dt_Routers = _routerService.QueryNextRoutes(item.SourceAddress, item.RoadWay, item.TaskType);
                                if (dt_Routers != null && dt_Routers.Count > 0)
                                {
                                    task.NextAddress = dt_Routers.FirstOrDefault().NextPosi;
                                    task.DeviceCode = dt_Routers.FirstOrDefault().ChildPosi;
                                }
                                else
                                {
                                    task.NextAddress = "";
                                    task.DeviceCode = "";
                                }
                            }
                        }
                    }
                    else
                    {
                        if (taskTypeGroup == TaskTypeGroup.OutbondGroup)
                        {
                            task.AgvTaskNum = item.AGVArea + DateTime.Now.ToString("yyyyMMdd") + item.TaskNum;
                            List<Dt_Router> routers = _routerRepository.QueryData(x => x.InOutType == item.TaskType && item.AGVArea == x.NextPosi);
                            if (routers.FirstOrDefault() == null)
                            {
                                return WebResponseContent.Instance.Error($"未找到路由配置信息");
                            }
                            router = routers.FirstOrDefault();
                            task.NextAddress = router?.StartPosi ?? "";
                            task.DeviceCode = item.RoadWay;
                            task.TaskState = TaskStatusEnum.SC_Execute.ObjToInt();
                        }
                        else
                        {
                            if (task.Roadway!="SC01_ZH")
                            {
                                task.AgvTaskNum = item.AGVArea + DateTime.Now.ToString("yyyyMMdd") + item.TaskNum;
                            }
                            List<Dt_Router> routers = _routerRepository.QueryData(x => x.InOutType == item.TaskType && item.AGVArea == x.StartPosi);
                            if (routers.FirstOrDefault() == null)
                            {
                                return WebResponseContent.Instance.Error($"未找到路由配置信息");
                            }
                            router = routers.FirstOrDefault();
                            Dt_StationManger? stationManger = _stationMangerRepository.QueryData(x => true).FirstOrDefault(x=>x.StationCode== router?.NextPosi);
                            if (stationManger == null)
                            {
                                return WebResponseContent.Instance.Error($"未找到站台配置信息");
                            }
                            task.NextAddress = stationManger?.AGVStationCode ?? "";
                            task.DeviceCode = stationManger?.Remark ?? "";
                            if (task.Roadway != "SC01_ZH")
                            {
                                task.TaskState = TaskStatusEnum.AGV_Execute.ObjToInt();
                            }
                            else
                            {
                                task.TaskState = TaskStatusEnum.AGV_Executing.ObjToInt();
                            }
                        }
                    }
 
                    tasks.Add(task);
                }
                BaseDal.AddData(tasks);
 
                _taskExecuteDetailService.AddTaskExecuteDetail(tasks.Select(x => x.TaskNum).ToList(), "接收WMS任务");
 
                content = (flag || tasks.Count > 0) ? WebResponseContent.Instance.OK("成功") : WebResponseContent.Instance.Error("失败");
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error($"任务接收错误,错误信息:{ex.Message}");
            }
            return content;
        }
 
        /// <summary>
        /// 根据托盘号、起始地址向WMS请求任务
        /// </summary>
        /// <param name="palletCode">托盘号</param>
        /// <param name="sourceAddress">起始地址</param>
        /// <returns></returns>
        public WebResponseContent RequestWMSTask(string palletCode, string sourceAddress, string materielBoxCode = "")
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                Dt_StationManger stationManger = _stationMangerRepository.QueryFirst(x => x.StationCode == sourceAddress);
                if (stationManger == null)
                {
                    return WebResponseContent.Instance.Error($"未找到站台信息");
                }
                string address = AppSettings.Get("WMSApiAddress");
                if (string.IsNullOrEmpty(address))
                {
                    return WebResponseContent.Instance.Error($"未找到WMSApi地址");
                }
                string responseStr = "";
                if (!string.IsNullOrEmpty(materielBoxCode))
                {
                    responseStr = HttpHelper.Get($"{address}/api/Task/DeviceRequestInboundTask?stationCode={sourceAddress}&roadwayNo={stationManger.StackerCraneCode}&palletCode={palletCode}&materielBoxCode={materielBoxCode}");
                }
                else
                {
                    responseStr = HttpHelper.Get($"{address}/api/Task/DeviceRequestInboundTask?stationCode={sourceAddress}&roadwayNo={stationManger.StackerCraneCode}&palletCode={palletCode}");
                }
                WebResponseContent? responseContent = JsonConvert.DeserializeObject<WebResponseContent>(responseStr);
                if (responseContent != null && responseContent.Status && responseContent.Data != null)
                {
                    WMSTaskDTO? taskDTO = JsonConvert.DeserializeObject<WMSTaskDTO>(responseContent.Data.ToString());
                    if (taskDTO != null)
                    {
                        content = ReceiveWMSTask(new List<WMSTaskDTO> { taskDTO });
                    }
                }
 
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
        public WebResponseContent RequestWMSZHTask(string agvTaskCode, string palletCode, string palletType, string materialLot)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                Dt_Task task = BaseDal.QueryFirst(x => x.AgvTaskNum == agvTaskCode);
                if (task != null)
                {
                    return WebResponseContent.Instance.Error($"任务号{task.TaskNum}对应任务已存在");
                }
                string address = AppSettings.Get("WMSApiAddress");
                if (string.IsNullOrEmpty(address))
                {
                    return WebResponseContent.Instance.Error($"未找到WMSApi地址");
                }
                string responseStr = "";
                if (string.IsNullOrEmpty(materialLot))
                {
                    return content.Error("物料批次为空");
                    
                }
                responseStr = HttpHelper.Get($"{address}/api/Task/RequestZHInboundTask?agvTaskCode={agvTaskCode}&palletCode={palletCode}&palletType={palletType}&materialLot={materialLot}");
                WebResponseContent? responseContent = JsonConvert.DeserializeObject<WebResponseContent>(responseStr);
                if (responseContent != null && responseContent.Status && responseContent.Data != null)
                {
                    WMSTaskDTO? taskDTO = JsonConvert.DeserializeObject<WMSTaskDTO>(responseContent.Data.ToString());
                    if (taskDTO != null)
                    {
                        taskDTO.AGVTaskNum = agvTaskCode;
                        content = ReceiveWMSTask(new List<WMSTaskDTO> { taskDTO });
                    }
                }
                else
                {
                    content.Error(responseContent.Message);
                }
 
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="palletCode"></param>
        /// <param name="sourceAddress"></param>
        /// <returns></returns>
        public WebResponseContent RequestWMSTaskSimple(string palletCode, string sourceAddress)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                string address = AppSettings.Get("WMSApiAddress");
                if (string.IsNullOrEmpty(address))
                {
                    return WebResponseContent.Instance.Error($"未找到WMSApi地址");
                }
                string responseStr = HttpHelper.Get($"{address}/api/Task/DeviceRequestInboundTaskSimple?stationCode={sourceAddress}&palletCode={palletCode}");
                WebResponseContent? responseContent = JsonConvert.DeserializeObject<WebResponseContent>(responseStr);
                if (responseContent != null && responseContent.Status && responseContent.Data != null)
                {
                    WMSTaskDTO? taskDTO = JsonConvert.DeserializeObject<WMSTaskDTO>(responseContent.Data.ToString());
                    if (taskDTO != null)
                    {
                        content = ReceiveWMSTask(new List<WMSTaskDTO> { taskDTO });
                    }
                }
 
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="palletCode"></param>
        /// <param name="sourceAddress"></param>
        /// <param name="roadway"></param>
        /// <returns></returns>
        //public WebResponseContent RequestWMSTask(string palletCode, string sourceAddress, string roadway)
        //{
        //    WebResponseContent content = new WebResponseContent();
        //    try
        //    {
        //        string address = AppSettings.Get("WMSApiAddress");
        //        if (string.IsNullOrEmpty(address))
        //        {
        //            return WebResponseContent.Instance.Error($"未找到WMSApi地址");
        //        }
        //        string responseStr = HttpHelper.Get($"{address}/api/Task/DeviceRequestInboundTask?stationCode={sourceAddress}&roadwayNo={roadway}&palletCode={palletCode}");
        //        WebResponseContent? responseContent = JsonConvert.DeserializeObject<WebResponseContent>(responseStr);
        //        if (responseContent != null && responseContent.Status && responseContent.Data != null)
        //        {
        //            WMSTaskDTO? taskDTO = JsonConvert.DeserializeObject<WMSTaskDTO>(responseContent.Data.ToString());
        //            if (taskDTO != null)
        //            {
        //                content = ReceiveWMSTask(new List<WMSTaskDTO> { taskDTO });
        //            }
        //        }
 
        //    }
        //    catch (Exception ex)
        //    {
        //        content = WebResponseContent.Instance.Error(ex.Message);
        //    }
        //    return content;
        //}
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sourceAddress"></param>
        /// <param name="palletCode"></param>
        /// <param name="heightType"></param>
        /// <param name="roadways"></param>
        /// <returns></returns>
        public WebResponseContent RequestWMSTask(string palletCode, string sourceAddress,  int heightType, List<string> roadways)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                string address = AppSettings.Get("WMSApiAddress");
                if (string.IsNullOrEmpty(address))
                {
                    return WebResponseContent.Instance.Error($"未找到WMSApi地址");
                }
                string responseStr = HttpHelper.Post($"{address}/api/Task/DeviceRequestInboundTaskByRoadways?stationCode={sourceAddress}&palletCode={palletCode}&heightType={heightType}", roadways.Serialize());
                WebResponseContent? responseContent = JsonConvert.DeserializeObject<WebResponseContent>(responseStr);
                if (responseContent != null && responseContent.Status && responseContent.Data != null)
                {
                    WMSTaskDTO? taskDTO = JsonConvert.DeserializeObject<WMSTaskDTO>(responseContent.Data.ToString());
                    if (taskDTO != null)
                    {
                        content = ReceiveWMSTask(new List<WMSTaskDTO> { taskDTO });
                    }
                }
 
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
 
        /// <summary>
        /// 分配巷道
        /// </summary>
        /// <param name="taskNum"></param>
        /// <param name="roadwayNos"></param>
        /// <returns></returns>
        public WebResponseContent RequestWMSAssignRoadway(int taskNum, List<string> roadwayNos)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                string address = AppSettings.Get("WMSApiAddress");
                if (string.IsNullOrEmpty(address))
                {
                    return WebResponseContent.Instance.Error($"未找到WMSApi地址");
                }
                string responseStr = HttpHelper.Post($"{address}/api/Task/AssignRoadway?taskNum={taskNum}", roadwayNos.Serialize());
                WebResponseContent? responseContent = JsonConvert.DeserializeObject<WebResponseContent>(responseStr);
                if (responseContent != null && responseContent.Status && responseContent.Data != null)
                {
                    return responseContent;
                }
 
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="roadwayNos"></param>
        /// <param name="palletCode"></param>
        /// <param name="heightType"></param>
        /// <returns></returns>
        public WebResponseContent RequestWMSAssignRoadway(List<string> roadwayNos, string palletCode, int heightType)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                string address = AppSettings.Get("WMSApiAddress");
                if (string.IsNullOrEmpty(address))
                {
                    return WebResponseContent.Instance.Error($"未找到WMSApi地址");
                }
                string responseStr = HttpHelper.Post($"{address}/api/Task/AssignRoadwayByHeightAndCode?palletCode={palletCode}&heightType={heightType}", roadwayNos.Serialize());
                WebResponseContent? responseContent = JsonConvert.DeserializeObject<WebResponseContent>(responseStr);
                if (responseContent != null && responseContent.Status && responseContent.Data != null)
                {
                    return responseContent;
                }
 
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
 
        /// <summary>
        /// 分配巷道
        /// </summary>
        /// <param name="roadwayNos"></param>
        /// <param name="taskNum"></param>
        /// <param name="heightType"></param>
        /// <returns></returns>
        public WebResponseContent RequestWMSAssignRoadway(List<string> roadwayNos, int taskNum, int heightType)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                string address = AppSettings.Get("WMSApiAddress");
                if (string.IsNullOrEmpty(address))
                {
                    return WebResponseContent.Instance.Error($"未找到WMSApi地址");
                }
                string responseStr = HttpHelper.Post($"{address}/api/Task/AssignRoadway?taskNum={taskNum}&heightType={heightType}", roadwayNos.Serialize());
                WebResponseContent? responseContent = JsonConvert.DeserializeObject<WebResponseContent>(responseStr);
                if (responseContent != null && responseContent.Status && responseContent.Data != null)
                {
                    return responseContent;
                }
 
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
 
        /// <summary>
        /// 分配巷道
        /// </summary>
        /// <param name="roadwayNos"></param>
        /// <returns></returns>
        public WebResponseContent RequestWMSAssignRoadway(List<string> roadwayNos)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                string address = AppSettings.Get("WMSApiAddress");
                if (string.IsNullOrEmpty(address))
                {
                    return WebResponseContent.Instance.Error($"未找到WMSApi地址");
                }
                string responseStr = HttpHelper.Post($"{address}/api/Task/SingleAssignRoadway", roadwayNos.Serialize());
                WebResponseContent? responseContent = JsonConvert.DeserializeObject<WebResponseContent>(responseStr);
                if (responseContent != null && responseContent.Status && responseContent.Data != null)
                {
                    return responseContent;
                }
 
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
 
        /// <summary>
        /// 向WMS申请分配货位
        /// </summary>
        /// <param name="taskNum">任务号</param>
        /// <param name="roadwayNo">巷道号</param>
        /// <returns></returns>
        public string? RequestAssignLocation(int taskNum, string roadwayNo)
        {
            string address = AppSettings.Get("WMSApiAddress");
            if (string.IsNullOrEmpty(address)) throw new Exception("未找到WMSApi地址");
            string responseStr = HttpHelper.Get($"{address}/api/Task/AssignInboundTaskLocation?taskNum={taskNum}&roadwayNo={roadwayNo}");
 
            WebResponseContent? responseContent = JsonConvert.DeserializeObject<WebResponseContent>(responseStr);
            if (responseContent != null && responseContent.Status && responseContent.Data != null)
            {
                return responseContent.Data.ToString();
            }
 
            return "";
        }
 
        /// <summary>
        /// 向WMS申请分配货位
        /// </summary>
        /// <param name="taskNum"></param>
        /// <param name="roadwayNo"></param>
        /// <param name="heightType"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public string? RequestAssignLocationByHeight(int taskNum, string roadwayNo, int heightType)
        {
            string address = AppSettings.Get("WMSApiAddress");
            if (string.IsNullOrEmpty(address)) throw new Exception("未找到WMSApi地址");
            string responseStr = HttpHelper.Get($"{address}/api/Task/AssignInboundTaskLocationByHeight?taskNum={taskNum}&roadwayNo={roadwayNo}&heightType={heightType}");
 
            WebResponseContent? responseContent = JsonConvert.DeserializeObject<WebResponseContent>(responseStr);
            if (responseContent != null && responseContent.Status && responseContent.Data != null)
            {
                return responseContent.Data.ToString();
            }
 
            return "";
        }
 
        /// <summary>
        /// 根据设备编号、任务类型分组(可选)按照优先级以及创建时间排序查询任务池新增的任务
        /// </summary>
        /// <param name="deviceNo">设备编号</param>
        /// <param name="taskTypeGroup">任务类型分组(可选)</param>
        /// <returns></returns>
        public Dt_Task? QuertStackerCraneTask(string deviceNo, TaskTypeGroup? taskTypeGroup = null)
        {
            if (taskTypeGroup == null)
                return BaseDal.QueryFirst(x => x.DeviceCode == deviceNo && x.TaskState == (int)TaskStatusEnum.New, TaskOrderBy);
            if (taskTypeGroup.Value == TaskTypeGroup.InboundGroup)
                return BaseDal.QueryFirst(x => x.DeviceCode == deviceNo && TaskInboundTypes.Contains(x.TaskType) && x.TaskState == (int)TaskStatusEnum.SC_Execute, TaskOrderBy);
            if (taskTypeGroup.Value == TaskTypeGroup.OutbondGroup)
                return BaseDal.QueryFirst(x => x.DeviceCode == deviceNo && TaskOutboundTypes.Contains(x.TaskType) && x.TaskState == (int)TaskStatusEnum.SC_Execute, TaskOrderBy);
            return null;
        }
 
        /// <summary>
        /// 根据设备编号、当前地址按照优先级以及创建时间排序查询任务池新增的任务
        /// </summary>
        /// <param name="deviceNo">设备编号</param>
        /// <param name="currentAddress">当前地址</param>
        /// <returns>返回任务实体对象,可能为null</returns>
        public Dt_Task QueryStackerCraneTask(string deviceNo, string currentAddress = "")
        {
            if (string.IsNullOrEmpty(currentAddress))
                return BaseDal.QueryFirst(x => x.DeviceCode == deviceNo && x.TaskState == (int)TaskStatusEnum.SC_Execute, TaskOrderBy);
            else
                return BaseDal.QueryFirst(x => x.DeviceCode == deviceNo && x.CurrentAddress == currentAddress && x.TaskState == (int)TaskStatusEnum.SC_Execute, TaskOrderBy);
        }
 
        /// <summary>
        /// 根据设备编号、当前地址按照优先级以及创建时间排序查询任务池入库类型的新增的任务
        /// </summary>
        /// <param name="deviceNo">设备编号</param>
        /// <param name="currentAddress">当前地址</param>
        /// <returns>返回任务实体对象,可能为null</returns>
        public Dt_Task QueryStackerCraneInTask(string deviceNo, string currentAddress = "")
        {
            if (string.IsNullOrEmpty(currentAddress))
                return BaseDal.QueryFirst(x => x.DeviceCode == deviceNo && TaskInboundTypes.Contains(x.TaskType) && x.TaskState == (int)TaskStatusEnum.SC_Execute, TaskOrderBy);
            else
                return BaseDal.QueryFirst(x => x.DeviceCode == deviceNo && TaskInboundTypes.Contains(x.TaskType) && x.TaskState == (int)TaskStatusEnum.SC_Execute && x.CurrentAddress == currentAddress, TaskOrderBy);
        }
 
        /// <summary>
        /// 根据设备编号、当前地址按照优先级以及创建时间排序查询任务池出库类型的新增的任务
        /// </summary>
        /// <param name="deviceNo">设备编号</param>
        /// <param name="currentAddress">当前地址</param>
        /// <returns>返回任务实体对象,可能为null</returns>
        public Dt_Task QueryStackerCraneOutTask(string deviceNo, string currentAddress = "")
        {
            if (string.IsNullOrEmpty(currentAddress))
                return BaseDal.QueryFirst(x => x.DeviceCode == deviceNo && TaskOutboundTypes.Contains(x.TaskType) && x.TaskState == (int)TaskStatusEnum.SC_Execute, TaskOrderBy);
            else
                return BaseDal.QueryFirst(x => x.DeviceCode == deviceNo && TaskOutboundTypes.Contains(x.TaskType) && x.TaskState == (int)TaskStatusEnum.SC_Execute && x.CurrentAddress == currentAddress, TaskOrderBy);
        }
 
        /// <summary>
        /// 根据设备编号、当前地址按照优先级以及创建时间排序查询任务池出库类型的新增的任务
        /// </summary>
        /// <param name="deviceNo">设备编号</param>
        /// <param name="currentAddress">当前地址</param>
        /// <returns>返回任务实体对象集合,可能为null</returns>
        public List<Dt_Task> QueryStackerCraneOutTasks(string deviceNo, List<string> outStationCodes)
        {
            return BaseDal.QueryData(x => x.DeviceCode == deviceNo && TaskOutboundTypes.Contains(x.TaskType) && x.TaskState == (int)TaskStatusEnum.SC_Execute && outStationCodes.Contains(x.CurrentAddress), TaskOrderBy);
        }
 
        /// <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.TaskId, 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.TaskId, $"人工恢复挂起任务,恢复挂起时任务状态【{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.TaskId, $"人工将任务状态从【{oldState}】回滚到【{task.TaskState}】");
 
                content = WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
 
        public WebResponseContent SendSecureReplyToAgv(int taskNum)
        {
            try
            {
                Dt_Task WaitToTask = BaseDal.QueryFirst(x => x.TaskState == TaskStatusEnum.AGV_WaitToExecute.ObjToInt() && x.TaskNum == taskNum);
                AgvSecureReplyDTO replyDTO = new AgvSecureReplyDTO()
                {
                    ReqCode = Guid.NewGuid().ToString().Replace("-", ""), //WaitToTask.TaskNum.ToString(),
                    taskCode = WaitToTask.AgvTaskNum,
                };
                WebResponseContent content = AgvSecureReply(replyDTO);
                if (content.Status)
                {
                    WaitToTask.TaskState = TaskStatusEnum.AGV_Executing.ObjToInt();
                }
                else
                {
                    WaitToTask.TaskState = TaskStatusEnum.Exception.ObjToInt();
                    WaitToTask.ExceptionMessage = content.Message;
                }
                UpdateData(WaitToTask);
 
                return WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
        /// <summary>
        /// //判断移库货位任务是否已存在,如存在先执行
        /// </summary>
        public Dt_Task QueryStackerExistTask(string PalletCode, string locationCode)
        {
            return BaseDal.QueryFirst(x => x.PalletCode == PalletCode && x.SourceAddress == locationCode && (x.TaskState == (int)TaskStatusEnum.SC_Execute || x.TaskState == (int)TaskStatusEnum.SC_Executing));
        }
        /// <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);
            }
        }
    }
}