1
huangxiaoqiang
2025-06-09 c4be9e236670cbca7e081fd4778523b339a1f624
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
using AngleSharp.Dom;
using AngleSharp.Io;
using Mapster;
using Masuit.Tools;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using SqlSugar;
using System.ComponentModel.Design;
using System.Linq.Expressions;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using WIDESEA_Cache;
using WIDESEA_Core.Const;
using WIDESEA_DTO.AGV;
using WIDESEA_DTO.WMS;
using WIDESEA_IServices;
using WIDESEA_IStorageSocketRepository;
using WIDESEA_IStorageSocketServices;
using WIDESEA_IStoragIntegrationServices;
using WIDESEA_Model.Models.AGV;
using WIDESEA_StorageSocketServices;
using WIDESEA_StorageTaskRepository;
using WIDESEAWCS_BasicInfoRepository;
using WIDESEAWCS_BasicInfoService;
using WIDESEAWCS_Model.Models;
 
namespace WIDESEA_StorageTaskServices;
 
public partial class Dt_TaskService : ServiceBase<Dt_Task, IDt_TaskRepository>, IDt_TaskService
{
    private readonly LogFactory LogFactory = new LogFactory();
    private readonly IUnitOfWorkManage _unitOfWorkManage;
    private readonly IStockInfoRepository _stockInfoRepository;
    private readonly IDt_StationManagerRepository _stationManagerRepository;
    private readonly IDt_StationManagerService _stationManagerService;
    private readonly IDt_Task_HtyRepository _task_HtyRepository;
    private readonly IMapper _mapper;
    private readonly ILocationInfoRepository _locationRepository;
    private readonly IDt_HandAutomaticRepository _handAutomaticRepository;
    private readonly IDt_HostErrorMessageRepository _errorMessageRepository;
 
    public Dt_TaskService(IDt_TaskRepository BaseDal,
                                IUnitOfWorkManage unitOfWorkManage,
                                IStockInfoRepository stockInfoRepository,
                                IDt_Task_HtyRepository task_HtyRepository,
                                IMapper mapper,
                                ILocationInfoRepository locationRepository,
                                IStockInfoDetailRepository stockInfoDetailRepository,
                                IDt_StationManagerRepository stationManagerRepository,
                                IDt_HandAutomaticRepository handAutomaticRepository,
                                IDt_StationManagerService stationManagerService,
                                IDt_HostErrorMessageRepository errorMessageRepository) : base(BaseDal)
    {
        _unitOfWorkManage = unitOfWorkManage;
        _stockInfoRepository = stockInfoRepository;
        _task_HtyRepository = task_HtyRepository;
        _mapper = mapper;
        _locationRepository = locationRepository;
        _stationManagerRepository = stationManagerRepository;
        _handAutomaticRepository = handAutomaticRepository;
        _stationManagerService = stationManagerService;
        _errorMessageRepository = errorMessageRepository;
    }
 
 
 
    #region 外部接口方法
    public WebResponseContent InboundTask(TaskDTO taskDTO)
    {
        WebResponseContent content = new WebResponseContent();
        try
        {
            //var HandAutomatic = _handAutomaticRepository.QueryFirst(x => true && x.HandAutomatic == "Automatic");
            //if (HandAutomatic != null)
            //{
            //    return content.Error("当前不是手动模式");
            //}
            var station = _stationManagerRepository.QueryFirst(x => x.HostName == taskDTO.SourceAddress && x.stationType == 1);
            if (station == null)
            {
                return content.Error("未找到入库站台信息");
            }
            Dt_Task task = BaseDal.QueryFirst(x => x.PalletCode == taskDTO.PalletCode);
            if (task != null)
            {
                return content.Error("该托盘已存在任务");
            }
            var location = GetLocation();
            Dt_Task taskNew = new Dt_Task()
            {
                TaskNum = BaseDal.GetTaskNo().Result,
                PalletCode = taskDTO.PalletCode,
                Dispatchertime = DateTime.Now,
                Grade = 1,
                SeqNo = Convert.ToInt32(0),
                CommandID = Convert.ToInt32(0),
                SourceAddress = station.stationName,
                TargetAddress = location.LocationCode,
                CurrentAddress = station.stationName,
                NextAddress = location.LocationCode,
                TaskType = (int)TaskInboundTypeEnum.Inbound,
                TaskState = (int)TaskInStatusEnum.InNew,
                Roadway = "PDA",
            };
            task_call task_Call = new task_call()
            {
                d_task_type = "32" ,
                d_floor = "1",
                d_involed1 = taskNew.SourceAddress,
                d_involed2 = InsertHyphenEveryTwoChars(taskNew.TargetAddress),
                d_involed5 = taskNew.TaskNum.ToString(),
            };
            location.LocationStatus = (int)LocationEnum.Lock;
            _locationRepository.UpdateData(location);
            BaseDal.AddData(taskNew);
            var x = SqlSugarHelper.DbAGV.Insertable(task_Call).ExecuteCommand();
            LogFactory.GetLog("插入数据到AGV").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(x)}", "");
            LogFactory.GetLog("PDA").InfoFormat(true, $"InboundTask请求参数:{JsonConvert.SerializeObject(taskDTO)}{Environment.NewLine}", "");
            return content.OK("入库任务下发成功!");
        }
        catch (Exception ex)
        {
            return content.Error(ex.Message);
        }
    }
 
    public WebResponseContent SamplingInboundTask(TaskDTO taskDTO)
    {
        WebResponseContent content = new WebResponseContent();
        try
        {
            //var HandAutomatic = _handAutomaticRepository.QueryFirst(x => true && x.HandAutomatic == "Automatic");
            //if (HandAutomatic != null)
            //{
            //    return content.Error("当前不是手动模式");
            //}
            var station = _stationManagerRepository.QueryFirst(x => x.HostName == taskDTO.SourceAddress && x.stationType == 1);
            if (station == null)
            {
                return content.Error("未找到入库站台信息");
            }
            Dt_Task task = BaseDal.QueryFirst(x => x.PalletCode == taskDTO.PalletCode);
            if (task != null)
            {
                return content.Error("该托盘已存在任务");
            }
            var stock = _stockInfoRepository.QueryFirst(x => x.PalletCode == taskDTO.PalletCode);
            if (stock == null)
            {
                return content.Error("该托盘库存不存在");
            }
            var location = _locationRepository.QueryFirst(x => x.LocationCode == stock.LocationCode);
            
            Dt_Task taskNew = new Dt_Task()
            {
                TaskNum = BaseDal.GetTaskNo().Result,
                PalletCode = taskDTO.PalletCode,
                Dispatchertime = DateTime.Now,
                Grade = 1,
                SeqNo = Convert.ToInt32(0),
                CommandID = Convert.ToInt32(0),
                SourceAddress = station.stationName,
                TargetAddress = stock.LocationCode,
                CurrentAddress = station.stationName,
                NextAddress = stock.LocationCode,
                TaskType = (int)TaskInboundTypeEnum.InQuality,
                TaskState = (int)TaskInStatusEnum.InNew,
                Roadway = "PDA",
            };
            task_call task_Call = new task_call()
            {
                d_task_type = "32",
                d_floor = "1",
                d_involed1 = taskNew.SourceAddress,
                d_involed2 = InsertHyphenEveryTwoChars(taskNew.TargetAddress),
                d_involed5 = taskNew.TaskNum.ToString(),
            };
            location.LocationStatus = (int)LocationEnum.Lock;
            _locationRepository.UpdateData(location);
            BaseDal.AddData(taskNew);
            var x = SqlSugarHelper.DbAGV.Insertable(task_Call).ExecuteCommand();
            LogFactory.GetLog("插入数据到AGV").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(x)}", "");
            LogFactory.GetLog("PDA").InfoFormat(true, $"SamplingInboundTask请求参数:{JsonConvert.SerializeObject(taskDTO)}{Environment.NewLine}", "");
            return content.OK("抽检入库任务下发成功!");
        }
        catch (Exception ex)
        {
            return content.Error(ex.Message);
        }
    }
    public WebResponseContent OutboundTask(TaskDTO taskDTO)
    {
        WebResponseContent content = new WebResponseContent();
        try
        {
            StationStatus stationOut = _stationManagerService.GetStationStatus("B001");
            if (stationOut == null)
            {
                return content.Error("获取出库站台信息失败,请重新出库");
            }
            Dt_StationManager station;
            if (stationOut.WorkstationO == "0")
            {
                station = _stationManagerRepository.QueryFirst(x => x.stationName == "B001::1" && x.stationType == 2);
            }
            else if (stationOut.WorkstationT == "0")
            {
                station = _stationManagerRepository.QueryFirst(x => x.stationName == "B001::2" && x.stationType == 2);
            }
            else
            {
                return content.Error("出库站台状态不是空闲,请确认再下发出库任务");
            }
            if (station == null)
            {
                return content.Error("未找到出库站台信息");
            }
 
            Dt_Task task = BaseDal.QueryFirst(x => x.PalletCode == taskDTO.PalletCode);
            if (task != null)
            {
                return content.Error("该托盘已存在任务");
            }
            Dt_Task taskNew = new Dt_Task()
            {
                TaskNum = BaseDal.GetTaskNo().Result,
                PalletCode = taskDTO.PalletCode,
                Dispatchertime = DateTime.Now,
                Grade = 1,
                SeqNo = Convert.ToInt32(0),
                CommandID = Convert.ToInt32(0),
                SourceAddress =  taskDTO.SourceAddress,
                TargetAddress = station.stationName,
                CurrentAddress = taskDTO.SourceAddress,
                NextAddress = station.stationName,
                TaskType = (int)TaskOutboundTypeEnum.Outbound,
                TaskState = (int)TaskOutStatusEnum.OutNew,
                Roadway = "PDA",
            };
            task_call task_Call = new task_call()
            {
                d_task_type = "64",
                d_floor = "1",
                d_involed1 = InsertHyphenEveryTwoChars(taskNew.SourceAddress),
                d_involed2 = taskNew.TargetAddress,
                d_involed5 = taskNew.TaskNum.ToString(),
            };
            BaseDal.AddData(taskNew);
            var x = SqlSugarHelper.DbAGV.Insertable(task_Call).ExecuteCommand();
            LogFactory.GetLog("插入数据到AGV").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(x)}", "");
            LogFactory.GetLog("PDA").InfoFormat(true, $"OutboundTask请求参数:{JsonConvert.SerializeObject(taskDTO)}{Environment.NewLine}", "");
            return content.OK("出库任务下发成功!");
        }
        catch (Exception ex)
        {
            return content.Error(ex.Message);
        }
    }
    public WebResponseContent SamplingOutboundTask(TaskDTO taskDTO)
    {
        WebResponseContent content = new WebResponseContent();
        try
        {
 
            StationStatus stationOut = _stationManagerService.GetStationStatus("B002");
            if (stationOut == null)
            {
                return content.Error("获取出库站台信息失败,请重新出库");
            }
            Dt_StationManager station;
            if (stationOut.WorkstationO == "0")
            {
                station = _stationManagerRepository.QueryFirst(x => x.stationName == "B002::1" && x.stationType == 1);
            }
            else if (stationOut.WorkstationT == "0")
            {
                station = _stationManagerRepository.QueryFirst(x => x.stationName == "B002::2" && x.stationType == 1);
            }
            else
            {
                return content.Error("出库站台状态不是空闲,请确认再下发出库任务");
            }
            if (station == null)
            {
                return content.Error("未找到出库站台信息");
            }
            var stock = _stockInfoRepository.QueryFirst(x => x.LocationCode == taskDTO.SourceAddress);
            if (stock == null)
            {
                return content.Error("该库位库存不存在");
            }
            Dt_Task task = BaseDal.QueryFirst(x => x.PalletCode == stock.PalletCode);
            if (task != null)
            {
                return content.Error("该托盘已存在任务");
            }
 
            var location = _locationRepository.QueryFirst(x => x.LocationCode == stock.LocationCode);
            if (location.LocationStatus != (int)LocationEnum.InStock)
            {
                return content.Error("该库位不是有货状态,请确认状态再下发任务!");
            }
            station.stationHasTask = "抽检出库";
            _stationManagerRepository.UpdateData(station);
 
            Dt_Task taskNew = new Dt_Task()
            {
                TaskNum = BaseDal.GetTaskNo().Result,
                PalletCode = stock.PalletCode,
                Dispatchertime = DateTime.Now,
                Grade = 1,
                SeqNo = Convert.ToInt32(0),
                CommandID = Convert.ToInt32(0),
                TargetAddress = station.stationName,
                SourceAddress = stock.LocationCode,
                NextAddress = station.stationName,
                CurrentAddress = stock.LocationCode,
                TaskType = (int)TaskOutboundTypeEnum.OutQuality,
                TaskState = (int)TaskOutStatusEnum.OutNew,
                Roadway = "PDA",
            };
            task_call task_Call = new task_call()
            {
                d_task_type = "128",
                d_floor = "1",
                d_involed1 = InsertHyphenEveryTwoChars(taskNew.SourceAddress),
                d_involed2 = taskNew.TargetAddress,
                d_involed5 = taskNew.TaskNum.ToString(),
            };
            BaseDal.AddData(taskNew);
            var x = SqlSugarHelper.DbAGV.Insertable(task_Call).ExecuteCommand();
            LogFactory.GetLog("插入数据到AGV").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(x)}", "");
            LogFactory.GetLog("PDA").InfoFormat(true, $"SamplingOutboundTask请求参数:{JsonConvert.SerializeObject(taskDTO)}{Environment.NewLine}", "");
            return content.OK("抽检出库任务下发成功!");
        }
        catch (Exception ex)
        {
            return content.Error(ex.Message);
        }
    }
 
    public string InsertHyphenEveryTwoChars(string input)
    {
        if (string.IsNullOrEmpty(input))
        {
            return input;
        }
 
        StringBuilder result = new StringBuilder();
 
        for (int i = 0; i < input.Length; i += 2)
        {
            // 添加两个字符
            result.Append(input.Substring(i, 2));
 
            // 如果不是最后两个字符,添加一个连字符
            if (i + 2 < input.Length)
            {
                result.Append('-');
            }
        }
 
        return result.ToString();
    }
 
    public DtLocationInfo GetLocation()
    {
        List<DtLocationInfo> locations = _locationRepository.QueryData(x => x.LocationStatus == (int)LocationEnum.Free);
        var location = locations.OrderBy(x => x.Row).ThenBy(x => x.Column).ThenBy(x => x.Layer).FirstOrDefault();
        if(location != null)
        {
            var task = BaseDal.QueryFirst(x => x.SourceAddress == location.LocationName || x.TargetAddress == location.LocationName);
            if(task != null)
            {
                GetLocation();
            }
        }
        return location;
    }
 
    public WebResponseContent TaskComplete(int? TaskNum)
    {
        WebResponseContent content = new WebResponseContent();
        try
        {
            var task = BaseDal.QueryFirst(x => x.TaskNum == TaskNum);
            if (task != null)
            {
                switch (task.TaskType)
                {
                    case (int)TaskInboundTypeEnum.Inbound:
                        LogFactory.GetLog("任务完成").InfoFormat(true, "入库任务", "");
                        return CompleteInboundTask(task);
 
                    case (int)TaskOutboundTypeEnum.Outbound:
 
                        LogFactory.GetLog("任务完成").InfoFormat(true, "出库任务", "");
                        return CompleteOutboundTask(task);
 
                    case (int)TaskRelocationTypeEnum.Relocation:
                        return CompleteRelocationboundTask(task);
 
                    case (int)TaskOutboundTypeEnum.OutQuality:
                        return CompleteSamplingOutboundTask(task);
 
                    case (int)TaskInboundTypeEnum.InQuality:
                        return CompleteSamplingInboundTask(task);
 
                    default:
                        return content.Error("任务类型不存在");
                }
            }
            else
            {
                return content.Error("未找到任务");
            }
        }
        catch (Exception ex)
        {
            return content.Error(ex.Message);
        }
    }
    public WebResponseContent TaskStatus(Dt_Task task)
    {
        WebResponseContent content = new WebResponseContent();
        try
        {
            if (task != null)
            {
                switch (task.TaskType)
                {
                    case (int)TaskInboundTypeEnum.Inbound:
                    case (int)TaskInboundTypeEnum.InQuality:
                        task.TaskState = (int)TaskInStatusEnum.AGV_InExecuting;
                        BaseDal.Update(task);
                        break;
                    case (int)TaskOutboundTypeEnum.Outbound:
                    case (int)TaskOutboundTypeEnum.OutQuality:
                    case (int)TaskStationTypeEnum.StationToStation:
                        task.TaskState = (int)TaskOutStatusEnum.AGV_OutExecuting;
                        BaseDal.Update(task);
                        break;
                    case (int)TaskRelocationTypeEnum.Relocation:
                        task.TaskState = (int)TaskRelocationStatusEnum.AGV_RelocationExecuting;
                        BaseDal.Update(task);
                        break;
                    case (int)TaskFireAlarmTypeEnum.FireAlarmOut:
                        task.TaskState = (int)TaskFireAlarmStatusEnum.AGV_FireAlarmExecuting;
                        BaseDal.Update(task);
                        break;
 
                    default:
                        return content.Error("任务类型不存在");
                }
                return content.OK();
            }
            else
            {
                return content.Error("未找到任务");
            }
        }
        catch (Exception ex)
        {
            return content.Error(ex.Message);
        }
    }
 
    public WebResponseContent CompleteInboundTask(Dt_Task task)
    {
        WebResponseContent content = new WebResponseContent();
        try
        {
            _unitOfWorkManage.BeginTran();
            task.TaskState = 215;
            var locationInf = _locationRepository.QueryFirst(x => x.LocationCode == task.TargetAddress);
            locationInf.LocationStatus = 2;
            var stock = new DtStockInfo()
            {
                PalletCode = task.PalletCode,
                LocationCode = task.TargetAddress,
                CreateDate = DateTime.Now,
                Creater = "system",
                LocationId = locationInf.Id,
            };
            SqlSugarHelper.DbWMS.Insertable(stock).ExecuteCommand();
            _locationRepository.UpdateData(locationInf);
            TaskMoveHty(task);
            _unitOfWorkManage.CommitTran();
 
            LogFactory.GetLog("入库任务完成").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(task)}", "");
            return content.OK();
        }
        catch (Exception ex)
        {
            _unitOfWorkManage.RollbackTran();
 
            LogFactory.GetLog("入库任务完成").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(ex.Message)}", "");
            return content.Error(ex.Message);
        }
    }
 
    public WebResponseContent CompleteSamplingInboundTask(Dt_Task task)
    {
        WebResponseContent content = new WebResponseContent();
        try
        {
            _unitOfWorkManage.BeginTran();
            task.TaskState = 215;
            var locationInf = _locationRepository.QueryFirst(x => x.LocationCode == task.TargetAddress);
            locationInf.LocationStatus = (int)LocationEnum.InStock;
            _locationRepository.UpdateData(locationInf);
            TaskMoveHty(task);
            _unitOfWorkManage.CommitTran();
 
            LogFactory.GetLog("抽检入库任务完成").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(task)}", "");
            return content.OK();
        }
        catch (Exception ex)
        {
            _unitOfWorkManage.RollbackTran();
            LogFactory.GetLog("抽检入库任务完成").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(ex.Message)}", "");
            return content.Error(ex.Message);
        }
    }
 
    public WebResponseContent CompleteOutboundTask(Dt_Task task)
    {
        WebResponseContent content = new WebResponseContent();
        try
        {
            _unitOfWorkManage.BeginTran();
            task.TaskState = 135;
 
            AddStcokHty(task.PalletCode, task.SourceAddress);
 
            TaskMoveHty(task);
 
            _unitOfWorkManage.CommitTran();
            LogFactory.GetLog("出库任务完成").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(task)}", "");
            return content.OK();
        }
        catch (Exception ex)
        {
            _unitOfWorkManage.RollbackTran();
            LogFactory.GetLog("出库任务完成").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(ex.Message)}", "");
            return content.Error(ex.Message);
        }
    }
 
    public WebResponseContent CompleteFireAlarmboundTask(Dt_Task task)
    {
        WebResponseContent content = new WebResponseContent();
        try
        {
            _unitOfWorkManage.BeginTran();
            task.TaskState = (int)TaskFireAlarmStatusEnum.AGV_FireAlarmFinish;
 
            AddStcokHty(task.PalletCode,task.SourceAddress);
 
            TaskMoveHty(task);
            _unitOfWorkManage.CommitTran();
            LogFactory.GetLog("火警出库任务完成").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(task)}", "");
            return content.OK();
        }
        catch (Exception ex)
        {
            _unitOfWorkManage.RollbackTran();
            LogFactory.GetLog("火警出库任务完成").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(ex.Message)}", "");
            return content.Error(ex.Message);
        }
    }
 
    public void AddStcokHty(string  PalletCode,string Location)
    {
        //var stock = _stockInfoRepository.QueryFirst(x => x.PalletCode == PalletCode); 
        var stock = SqlSugarHelper.DbWMS.Queryable<DtStockInfo>().Where(x => x.PalletCode == PalletCode).First();
        if (stock != null)
        {
            DtStockInfo_Hty stockInfo_Hty = stock.Adapt<DtStockInfo_Hty>();
            stockInfo_Hty.ModifyDate = DateTime.Now;
 
            AddStockInfoHty(stockInfo_Hty);
 
            //_stockInfoRepository.DeleteData(stock);
            SqlSugarHelper.DbWMS.Deleteable(stock).ExecuteCommand();
        }
        var locationInf = _locationRepository.QueryFirst(x => x.LocationCode == Location);
        if (locationInf != null)
        {
            locationInf.LocationStatus = 0;
            _locationRepository.UpdateData(locationInf);
        }
    }
 
    public WebResponseContent CompleteSamplingOutboundTask(Dt_Task task)
    {
        WebResponseContent content = new WebResponseContent();
        try
        {
            _unitOfWorkManage.BeginTran();
 
            task.TaskState = 135;
            TaskMoveHty(task);
 
            _unitOfWorkManage.CommitTran();
            LogFactory.GetLog("抽检出库任务完成").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(task)}", "");
            return content.OK();
        }
        catch (Exception ex)
        {
            _unitOfWorkManage.RollbackTran();
            LogFactory.GetLog("抽检出库任务完成").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(ex.Message)}", "");
            return content.Error(ex.Message);
        }
    }
 
    public WebResponseContent CompleteRelocationboundTask(Dt_Task task)
    {
        WebResponseContent content = new WebResponseContent();
        try
        {
            _unitOfWorkManage.BeginTran();
            task.TaskState = 315;
            var locationInf = _locationRepository.QueryFirst(x => x.LocationCode == task.TargetAddress);
            var location = _locationRepository.QueryFirst(x => x.LocationCode == task.SourceAddress);
            locationInf.LocationStatus = 2;
            location.LocationStatus = 0;
 
            var stock = _stockInfoRepository.QueryFirst(x => x.PalletCode == task.PalletCode);
 
            stock.LocationCode = locationInf.LocationCode;
            stock.LocationId = locationInf.Id;
 
 
            _stockInfoRepository.UpdateData(stock);
            _locationRepository.UpdateData(locationInf);
            _locationRepository.UpdateData(location);
            TaskMoveHty(task);
            _unitOfWorkManage.CommitTran();
            LogFactory.GetLog("移库任务完成").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(task)}", "");
            return content.OK();
        }
        catch (Exception ex)
        {
            _unitOfWorkManage.RollbackTran();
            LogFactory.GetLog("移库任务完成").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(ex.Message)}", "");
            return content.Error(ex.Message);
        }
    }
 
    public void UpdateTask(string SourceAddress,string TargetAddress, string PalletCode)
    {
        var task = BaseDal.QueryFirst(x => x.PalletCode == PalletCode);
        if (task != null)
        {
            task.SourceAddress = SourceAddress;
            task.TargetAddress = TargetAddress;
            BaseDal.UpdateData(task);
            InsertAGVTask(task);
        }
    }
    private int InsertAGVTask(Dt_Task task)
    {
        var AgvTask = SqlSugarHelper.DbAGV.Queryable<task_call>().Where(x => x.d_involed5 == task.TaskNum.ToString()).First();
        if (AgvTask != null)
        {
            string SourceAddress = string.Empty;
            string TargetAddress = string.Empty;
            if (task.TaskType == (int)TaskInboundTypeEnum.Inbound)
            {
                SourceAddress = task.SourceAddress;
                TargetAddress = InsertHyphenEveryTwoChars(task.TargetAddress);
            }
            else if (task.TaskType == (int)TaskOutboundTypeEnum.Outbound)
            {
                SourceAddress = InsertHyphenEveryTwoChars(task.SourceAddress);
                TargetAddress = task.TargetAddress;
            }
            else if (task.TaskType == (int)TaskRelocationTypeEnum.Relocation)
            {
                TargetAddress = InsertHyphenEveryTwoChars(task.TargetAddress);
                SourceAddress = InsertHyphenEveryTwoChars(task.SourceAddress);
            }
            else if (task.TaskType == (int)TaskStationTypeEnum.StationToStation)
            {
                TargetAddress = task.TargetAddress;
                SourceAddress = task.SourceAddress;
            }
            else if (task.TaskType == (int)TaskFireAlarmTypeEnum.FireAlarmOut)
            {
                TargetAddress = task.TargetAddress;
                SourceAddress = task.SourceAddress;
            }
 
            AgvTask.d_involed1 = SourceAddress;
            AgvTask.d_involed2 = TargetAddress;
            var x = SqlSugarHelper.DbAGV.Updateable(AgvTask).ExecuteCommand();
            LogFactory.GetLog("插入数据到AGV").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(x)}", "");
            return x;
        }
        else
        {
            string SourceAddress = string.Empty;
            string TargetAddress = string.Empty;
            string AGVType = string.Empty;
            if (task.TaskType == (int)TaskInboundTypeEnum.Inbound)
            {
                SourceAddress = task.SourceAddress;
                AGVType = "2";
                TargetAddress = InsertHyphenEveryTwoChars(task.TargetAddress);
            }
            else if (task.TaskType == (int)TaskOutboundTypeEnum.Outbound)
            {
                SourceAddress = InsertHyphenEveryTwoChars(task.SourceAddress);
                TargetAddress = task.TargetAddress;
                AGVType = "4";
            }
            else if (task.TaskType == (int)TaskRelocationTypeEnum.Relocation)
            {
                TargetAddress = InsertHyphenEveryTwoChars(task.TargetAddress);
                SourceAddress = InsertHyphenEveryTwoChars(task.SourceAddress);
                AGVType = "16";
            }
            else if (task.TaskType == (int)TaskStationTypeEnum.StationToStation)
            {
                TargetAddress = task.TargetAddress;
                SourceAddress = task.SourceAddress;
                AGVType = "8";
            }
            else if (task.TaskType == (int)TaskFireAlarmTypeEnum.FireAlarmOut)
            {
                TargetAddress = task.TargetAddress;
                SourceAddress = task.SourceAddress;
                AGVType = "1";
            }
            task_call task_Call = new task_call()
            {
                d_task_type = AGVType,
                d_floor = "1",
                d_involed1 = SourceAddress,
                d_involed2 = TargetAddress,
                d_involed5 = task.TaskNum.ToString(),
            };
            var x = SqlSugarHelper.DbAGV.Insertable(task_Call).ExecuteCommand();
            LogFactory.GetLog("插入数据到AGV").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(x)}", "");
            return x;
        }
    }
    public WebResponseContent TaskMoveHty(Dt_Task task)
    {
        WebResponseContent content = new WebResponseContent();
        try
        {
            _unitOfWorkManage.BeginTran();
            var taskHtyNG = CreateHistoricalTask(task);
 
            var taskNum = task.TaskNum.ToString();
            var isTaskHtyAdd = _task_HtyRepository.AddData(taskHtyNG) > 0;
            var isTaskDelete = Delete(task.TaskId);
            var AgvTask = SqlSugarHelper.DbAGV.Queryable<task_call>().Where(x => x.d_involed5 == taskNum).First();
            if (AgvTask != null)
            {
                var x=SqlSugarHelper.DbAGV.Deleteable(AgvTask).ExecuteCommand();
                LogFactory.GetLog("插入数据到AGV").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(x)}", "");
            }
            _unitOfWorkManage.CommitTran();
            return content.OK();
        }
        catch (Exception ex)
        {
            _unitOfWorkManage.RollbackTran();
            LogFactory.GetLog("删除任务").InfoFormat(true, $"请求参数:{JsonConvert.SerializeObject(ex.Message)}", "");
            return content.Error(ex.Message);
        }
    }
 
    public WebResponseContent GetTaskInfo()
    {
        WebResponseContent content = new WebResponseContent();
        try
        {
            Expression<Func<Dt_Task, bool>> expression = x => true;
            if (!App.User.IsSuperAdmin)
            {
                expression = x => x.Creater == App.User.UserName;
            }
 
            var task = BaseDal.QueryData(x => true).ToList();
            var newTask = task.OrderByDescending(x => x.CreateDate).Select(x => new
            {
                x.TaskNum,
                x.PalletCode,
                x.SourceAddress,
                x.TargetAddress,
                TaskType = new List<string> { GetTaskTypeDesc(x.TaskType) }[0], // 每个任务独立生成 TaskType
                TaskState = new List<string> { GetTaskStateDesc(x.TaskState) }[0] // 每个任务独立生成 TaskState
            }).ToList();
 
            content = WebResponseContent.Instance.OK(data: newTask);
        }
        catch (Exception ex)
        {
            content = WebResponseContent.Instance.Error(ex.Message);
        }
        return content;
    }
 
    public WebResponseContent GetHostError()
    {
        WebResponseContent content = new WebResponseContent();
        try
        {
            Expression<Func<Dt_Task, bool>> expression = x => true;
            if (!App.User.IsSuperAdmin)
            {
                expression = x => x.Creater == App.User.UserName;
            }
 
            var now = DateTime.Now;
            var startOfDay = new DateTime(now.Year, now.Month, now.Day);
            var newTask = _errorMessageRepository.QueryData(x =>x.CreateDate> startOfDay).OrderByDescending(x => x.CreateDate).Select(x => new
            {
                x.id,
                x.ErrorCode,
                x.ErrorMessage,
                x.Grade,
                x.CreateDate
            }).ToList();
 
            content = WebResponseContent.Instance.OK(data: newTask);
        }
        catch (Exception ex)
        {
            content = WebResponseContent.Instance.Error(ex.Message);
        }
        return content;
    }
    
 
    public string GetTaskTypeDesc(int taskType)
    {
        return taskType switch
        {
            (int)TaskInboundTypeEnum.Inbound => TaskInboundTypeEnum.Inbound.GetIntegralRuleTypeEnumDesc(),
            (int)TaskRelocationTypeEnum.Relocation => TaskRelocationTypeEnum.Relocation.GetIntegralRuleTypeEnumDesc(),
            (int)TaskStationTypeEnum.StationToStation => TaskStationTypeEnum.StationToStation.GetIntegralRuleTypeEnumDesc(),
            (int)TaskFireAlarmTypeEnum.FireAlarmOut => TaskFireAlarmTypeEnum.FireAlarmOut.GetIntegralRuleTypeEnumDesc(),
            (int)TaskOutboundTypeEnum.Outbound => TaskOutboundTypeEnum.Outbound.GetIntegralRuleTypeEnumDesc(),
            (int)TaskOutboundTypeEnum.OutQuality => TaskOutboundTypeEnum.OutQuality.GetIntegralRuleTypeEnumDesc(),
        };
    }
    public string GetTaskStateDesc(int? taskState)
    {
        return taskState switch
        {
            (int)TaskInStatusEnum.InNew => TaskInStatusEnum.InNew.GetIntegralRuleTypeEnumDesc(),
            (int)TaskInStatusEnum.AGV_InExecuting => TaskInStatusEnum.AGV_InExecuting.GetIntegralRuleTypeEnumDesc(),
            (int)TaskInStatusEnum.AGV_InFinish => TaskInStatusEnum.AGV_InFinish.GetIntegralRuleTypeEnumDesc(),
            (int)TaskRelocationStatusEnum.RelocationNew => TaskRelocationStatusEnum.RelocationNew.GetIntegralRuleTypeEnumDesc(),
            (int)TaskRelocationStatusEnum.AGV_RelocationExecuting => TaskRelocationStatusEnum.AGV_RelocationExecuting.GetIntegralRuleTypeEnumDesc(),
            (int)TaskRelocationStatusEnum.AGV_RelocationFinish => TaskRelocationStatusEnum.AGV_RelocationFinish.GetIntegralRuleTypeEnumDesc(),
            (int)TaskOutStatusEnum.OutNew => TaskOutStatusEnum.OutNew.GetIntegralRuleTypeEnumDesc(),
            (int)TaskOutStatusEnum.AGV_OutExecuting => TaskOutStatusEnum.AGV_OutExecuting.GetIntegralRuleTypeEnumDesc(),
            (int)TaskOutStatusEnum.AGV_OutFinish => TaskOutStatusEnum.AGV_OutFinish.GetIntegralRuleTypeEnumDesc(),
            (int)TaskFireAlarmStatusEnum.FireAlarmNew => TaskFireAlarmStatusEnum.FireAlarmNew.GetIntegralRuleTypeEnumDesc(),
            (int)TaskFireAlarmStatusEnum.AGV_FireAlarmExecuting => TaskFireAlarmStatusEnum.AGV_FireAlarmExecuting.GetIntegralRuleTypeEnumDesc(),
            (int)TaskFireAlarmStatusEnum.FireAlarmFinish => TaskFireAlarmStatusEnum.FireAlarmFinish.GetIntegralRuleTypeEnumDesc(),
        };
    }
 
    #endregion 外部接口方法
 
    #region private 内部方法
 
    /// <summary>
    /// 创建历史任务记录
    /// </summary>
    /// <param name="task"></param>
    /// <returns></returns>
    public Dt_Task_Hty CreateHistoricalTask(Dt_Task task, bool isHand = false)
    {
        task.CurrentAddress = task.NextAddress;
 
        // 创建历史任务
        var taskHty = _mapper.Map<Dt_Task_Hty>(task);
        taskHty.FinishTime = DateTime.Now;
        taskHty.TaskId = 0;
        taskHty.OperateType = isHand ? (int)OperateTypeEnum.人工删除 : App.User.UserName != null ? (int)OperateTypeEnum.人工完成 : (int)OperateTypeEnum.自动完成;
        taskHty.SourceId = task.TaskId;
        if (isHand)
        {
            taskHty.Creater = App.User.UserName != null ? App.User.UserName : "System";
        }
        return taskHty;
    }
    /// <summary>
    /// 删除一个任务
    /// </summary>
    /// <param name="id">任务ID</param>
    /// <returns>是否删除成功</returns>
    public bool Delete(int id)
    {
        return BaseDal.Delete(id);
    }
    private void AddStockInfoHty(DtStockInfo_Hty dtStock)
    {
        var isStockAdd = SqlSugarHelper.DbWMS.InsertNav(dtStock).IncludesAllFirstLayer().ExecuteCommand();
        if (!isStockAdd)
        {
            throw new Exception("库存历史信息添加失败");
        }
    }
 
    public override WebResponseContent DeleteData(object[] key)
    {
        WebResponseContent content = new WebResponseContent();
        // 创建历史任务实例模型
        try
        {
            foreach (var item in key)
            {
                //var task = BaseDal.QueryFirst(x => x.TaskId == Convert.ToInt32(item));
                //var taskHty = task.Adapt<Dt_Task_Hty>();
                //taskHty.Creater = App.User.UserName != null ? App.User.UserName : "System";
                //_taskHtyRepository.AddData(taskHty);
 
                //return base.DeleteData(key);
                Dt_Task task = BaseDal.QueryFirst(x => x.TaskId == Convert.ToInt32(item));
                if (task == null)
                {
                    return content.Error("未找到任务信息!");
                }
                var taskHtyNG = CreateHistoricalTask(task, true);
 
                // 执行数据库事务
 
                // 添加历史任务
                var isTaskHtyAdd = _task_HtyRepository.AddData(taskHtyNG) > 0;
 
                // 删除任务数据
                var isTaskDelete = BaseDal.Delete(task.TaskId);
            }
            return content.OK("删除成功!");
        }
        catch (Exception ex)
        {
            return content.Error("删除任务异常:" + ex.Message);
        }
    }
 
    #endregion private 内部方法
}