HuBingJie
16 小时以前 ba998c70b77180668f295e65e07f3a62bf85e5ee
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
#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 命名空间:WIDESEA_TaskInfoService
 * 创建者:胡童庆
 * 创建时间:2024/8/2 16:13:36
 * 版本:V1.0.0
 * 描述:
 *
 * ----------------------------------------------------------------
 * 修改人:
 * 修改时间:
 * 版本:V1.0.1
 * 修改说明:
 * 
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
 
using Autofac.Core;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SqlSugar;
using System.Diagnostics;
using System.DirectoryServices.Protocols;
using System.Net;
using System.Reflection.Emit;
using System.Threading.Tasks;
using WIDESEA_Common.LocationEnum;
using WIDESEA_Common.OtherEnum;
using WIDESEA_Common.StockEnum;
using WIDESEA_Common.TaskEnum;
using WIDESEA_Core;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.BaseServices;
using WIDESEA_Core.Const;
using WIDESEA_Core.Enums;
using WIDESEA_Core.Helper;
using WIDESEA_DTO.Task;
using WIDESEA_DTO.ToMes;
using WIDESEA_IBasicService;
using WIDESEA_IInboundService;
using WIDESEA_IOutboundService;
using WIDESEA_IRecordService;
using WIDESEA_IStockService;
using WIDESEA_ITaskInfoService;
using WIDESEA_Model.Models;
 
namespace WIDESEA_TaskInfoService
{
    public partial class TaskService : ServiceBase<Dt_Task, IRepository<Dt_Task>>, ITaskService
    {
        private readonly IMapper _mapper;
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        private readonly IRepository<Dt_StockInfo> _stockRepository;
        private readonly IRepository<Dt_Warehouse> _warehouseRepository;
        private readonly IRepository<Dt_LocationInfo> _locationInfoRepository;
        private readonly IRepository<Dt_RoadwayInfo> _roadwayInforepository;
        private readonly IBasicService _basicService;
        private readonly IDt_ApiInfoService _dt_ApiInfoService;
        private readonly ILocationStatusChangeRecordService _locationStatusChangeRecordService;
        private readonly IStationMangerService _stationMangerService;
 
        public IRepository<Dt_Task> Repository => BaseDal;
 
        private Dictionary<string, OrderByType> _taskOrderBy = new()
            {
                {nameof(Dt_Task.Grade),OrderByType.Desc },
                {nameof(Dt_Task.CreateDate),OrderByType.Asc},
            };
 
        public TaskService(IRepository<Dt_Task> BaseDal, IMapper mapper, IUnitOfWorkManage unitOfWorkManage, IRepository<Dt_StockInfo> stockRepository, IBasicService basicService, IRepository<Dt_Warehouse> warehouseRepository, IRepository<Dt_LocationInfo> locationInfoRepository, IRepository<Dt_RoadwayInfo> roadwayInforepository, IDt_ApiInfoService dt_ApiInfoService, ILocationStatusChangeRecordService locationStatusChangeRecordService, IStationMangerService stationMangerService) : base(BaseDal)
        {
            _mapper = mapper;
            _unitOfWorkManage = unitOfWorkManage;
            _stockRepository = stockRepository;
            _basicService = basicService;
            _warehouseRepository = warehouseRepository;
            _locationInfoRepository = locationInfoRepository;
            _roadwayInforepository = roadwayInforepository;
            _dt_ApiInfoService = dt_ApiInfoService;
            _locationStatusChangeRecordService = locationStatusChangeRecordService;
            _stationMangerService=stationMangerService;
        }
        public int GetTaskNum(string sequenceName)
        {
            return Db.Ado.GetScalar($"SELECT NEXT VALUE FOR {sequenceName}").ObjToInt();
        }
 
        /// <summary>
        /// 任务信息推送至WCS
        /// </summary>
        /// <returns></returns>
        public WebResponseContent PushTasksToWCS(List<Dt_Task> tasks, string agvDescription = "")
        {
            try
            {
                List<WMSTaskDTO> taskDTOs = _mapper.Map<List<WMSTaskDTO>>(tasks);
                taskDTOs.ForEach(x =>
                {
                    x.AGVArea = agvDescription;
                });
 
                var ConfigsAPIInfo = _dt_ApiInfoService.GetConfigsByAPIInfo(CateGoryConst.CONFIG_WCS_IPAddress, SysConfigConst.WCSReceiveTask);      //获取到wcs全部类型的接口
                string WCSReceiveTaskAPI = ConfigsAPIInfo.ApiAddress + ConfigsAPIInfo.ApiName;
 
                var respon = HttpHelper.Post(WCSReceiveTaskAPI, JsonConvert.SerializeObject(taskDTOs));
                if (respon != null)
                {
                    WebResponseContent respone = JsonConvert.DeserializeObject<WebResponseContent>(respon.ToString());
                    if (respone.Status)
                    {
                        return WebResponseContent.Instance.OK();
                    }
                    else
                    {
                        return WebResponseContent.Instance.Error($"下发出库失败,原因:{respone.Message}!");
                    }
                }
                else
                {
                    return WebResponseContent.Instance.Error("任务下发失败!");
                }
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
        
 
 
        /// <summary>
        /// 判断巷道内移库
        /// </summary>
        /// <param name="TaskNum"></param>
        /// <param name="SourceAddress"></param>
        /// <returns></returns>
        public WebResponseContent IsRelocations(int TaskNum)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                List<Dt_LocationInfo> loca = new List<Dt_LocationInfo>();
 
                Dt_Task task = BaseDal.QueryFirst(x => x.TaskNum == TaskNum);
                if (task == null) return content.Error($"未找到该任务信息,任务号:{TaskNum}");
                string Locatask = task.SourceAddress;
 
                //获取到深库位编号
                Dt_LocationInfo DeepLocation = _basicService.LocationInfoService.Repository.QueryFirst(x => x.LocationCode == Locatask);
                if(DeepLocation == null) return content.Error($"未找到该货位信息,货位编号:{Locatask}");
 
                //进行获取浅库位编号
                int locrow = DeepLocation.Row == 1 ? 2 : 3;
                Dt_LocationInfo ShallowLocation = _basicService.LocationInfoService.Repository.QueryFirst(x =>x.Row== locrow && x.Layer== DeepLocation.Layer && x.Column== DeepLocation.Column && x.RoadwayNo== DeepLocation.RoadwayNo);
                if (ShallowLocation == null) return content.Error($"未找到货位编号:{Locatask}的浅货位");
 
                if (ShallowLocation.LocationStatus == (int)LocationStatusEnum.Free)
                {
                    return content.OK(data: task);  //直接返回当前查询的任务
                }
 
 
                //如果有货,则生成移库任务
                if (ShallowLocation.LocationStatus == (int)LocationStatusEnum.InStock)
                {
                    Dt_StockInfo dt_Stock = _stockRepository.QueryFirst(x => x.LocationCode == ShallowLocation.LocationCode);
                    if (dt_Stock == null) return content.Error($"货位编号:{Locatask}的浅货位库存异常,请检查!!!");
 
                    //进行获取新的库位
                    Dt_LocationInfo? Nextlocation = _basicService.LocationInfoService.GetLocation(DeepLocation.RoadwayNo);//获取到新库位
                    if (Nextlocation == null)
                    {
                        return content.Error($"货位分配失败,未找到可分配货位");
                    }
                    ShallowLocation.LocationStatus = (int)LocationStatusEnum.Lock;
                    Nextlocation.LocationStatus = (int)LocationStatusEnum.Lock;
                    loca.Add(ShallowLocation);
                    loca.Add(Nextlocation);
 
                    _unitOfWorkManage.BeginTran();
                    //生成移动任务
                    Dt_Task dt_Task = new()
                    {
                        PalletCode = dt_Stock.PalletCode,
                        TaskNum = GetTaskNum(nameof(SequenceEnum.SeqTaskNum)),
                        Roadway = Nextlocation.RoadwayNo,
                        TaskType = TaskRelocationTypeEnum.Relocation.ObjToInt(),
                        TaskStatus = TaskRelocationStatusEnum.RelocationNew.ObjToInt(),
                        SourceAddress = ShallowLocation.LocationCode,
                        TargetAddress = Nextlocation.LocationCode,
                        CurrentAddress = ShallowLocation.LocationCode,
                        NextAddress = Nextlocation.LocationCode,
                        Grade = 1,
                        Creater = "WMS",
                        Depth = Nextlocation.Depth,
                        CreateDate = DateTime.Now,
                    };
 
                    _locationInfoRepository.UpdateData(loca);
                    BaseDal.AddData(dt_Task);   //新增任务
                    _unitOfWorkManage.CommitTran();
 
                    return content.OK(data: dt_Task);
                }
                else
                {
                    return content.Error($"货位编号:{Locatask}的浅货位状态异常,浅货位编号:{ShallowLocation.LocationCode}");
                }
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                throw;
            }
        }
 
        /// <summary>
        /// 任务完成
        /// </summary>
        /// <param name="taskNum">任务编号</param>
        /// <param name="HowWorks">模式(1:自动,2:手动)</param>
        /// <returns></returns>
        public WebResponseContent TaskCompleted(int taskNum)
        {
            WebResponseContent content = new WebResponseContent();
 
            Dt_Task task = BaseDal.QueryFirst(x => x.TaskNum == taskNum);
            if (task == null) return WebResponseContent.Instance.Error("未找到任务信息");
            switch (task.TaskType)
            {
                case (int)TaskRelocationTypeEnum.Relocation:
                    return RelocationInTaskCompleted(task);
                case (int)TaskInboundTypeEnum.Inbound:
                    return InboundTaskCompleted(task);
                case (int)TaskOutboundTypeEnum.Outbound:
                    return OutboundTaskCompleted(task);
                default: return content.Error($"任务类型错误,任务号:{task.TaskNum}");
            }
        }
 
        /// <summary>
        /// 移库完成方法
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public WebResponseContent RelocationInTaskCompleted(Dt_Task task)
        {
            WebResponseContent webResponse = new WebResponseContent();
            try
            {
                Dt_StockInfo stockInfo = _stockRepository.QueryFirst(x => x.PalletCode == task.PalletCode);
                Dt_LocationInfo locationpoint = _basicService.LocationInfoService.Repository.QueryFirst(x => x.LocationCode == task.SourceAddress);
                Dt_LocationInfo locationEnd = _basicService.LocationInfoService.Repository.QueryFirst(x => x.LocationCode == task.TargetAddress);
                List<Dt_LocationInfo> loca = new List<Dt_LocationInfo>();
                stockInfo.LocationCode = locationEnd.LocationCode;
                stockInfo.StockStatus = StockStatusEmun.已入库.ObjToInt();
                locationpoint.LocationStatus = LocationStatusEnum.Free.ObjToInt();
                locationEnd.LocationStatus = LocationStatusEnum.InStock.ObjToInt();
                loca.Add(locationpoint);
                loca.Add(locationEnd);
 
                _unitOfWorkManage.BeginTran();
                _stockRepository.UpdateData(stockInfo);
                _basicService.LocationInfoService.Repository.UpdateData(loca);
                BaseDal.DeleteData(task);
                BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? OperateTypeEnum.自动完成 : OperateTypeEnum.人工完成);
 
                WebResponseContent content = MES_TransferCompletionFeedback(task);
                //content.Status = true;
 
                if (!content.Status)
                {
                    _unitOfWorkManage.RollbackTran();
                    return content;
                }
 
                _unitOfWorkManage.CommitTran();
                return webResponse.OK();
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                return webResponse.Error($"移库任务完成失败,任务id:{task.TaskNum}");
                throw;
            }
            
        }
 
        /// <summary>
        /// 入库任务完成
        /// </summary>
        /// <param name="tasknum"></param>
        /// <returns></returns>
        public WebResponseContent InboundTaskCompleted(Dt_Task task)
        {
            try
            {
                Dt_Warehouse warehouse = _warehouseRepository.QueryFirst(x => x.WarehouseId == task.WarehouseId);
                Dt_StockInfo stockInfo = _stockRepository.Db.Queryable<Dt_StockInfo>().Where(x => x.PalletCode == task.PalletCode && x.WarehouseId == task.WarehouseId).First();
                if (stockInfo == null)
                {
                    return WebResponseContent.Instance.Error($"未找到托盘对应的组盘信息");
                }
                //if (!string.IsNullOrEmpty(stockInfo.LocationCode))
                //{
                //    return WebResponseContent.Instance.Error($"该托盘已绑定货位");
                //}
                Dt_LocationInfo dt_LocationInfo = _locationInfoRepository.QueryFirst(x => x.LocationCode == task.TargetAddress);
                if (dt_LocationInfo == null)
                {
                    return WebResponseContent.Instance.Error("未找到库位");
                }
                dt_LocationInfo.LocationStatus = LocationStatusEnum.InStock.ObjToInt();
                stockInfo.StockStatus = StockStatusEmun.入库完成.ObjToInt();
 
                _unitOfWorkManage.BeginTran();
                //修改货位状态为有货
                _locationInfoRepository.UpdateData(dt_LocationInfo);
                //修改库存状态
                _stockRepository.UpdateData(stockInfo);
                task.TaskStatus = (int)TaskInStatusEnum.InFinish;
                //删除任务添加历史
                BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId > 0 ? OperateTypeEnum.人工完成 : OperateTypeEnum.自动完成);
 
 
                WebResponseContent content = TaskCompletionFeedback(task);
                //content.Status = true;
                if (!content.Status)
                {
                    _unitOfWorkManage.RollbackTran();
                    return content;
                }
 
                //Thread.Sleep(5000);
 
                _unitOfWorkManage.CommitTran();
            }
            catch (Exception)
            {
                _unitOfWorkManage.RollbackTran();
                throw;
            }
            return WebResponseContent.Instance.OK();
        }
 
        /// <summary>
        /// 出库任务完成
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public WebResponseContent OutboundTaskCompleted(Dt_Task task)
        {
            WebResponseContent webResponse = new WebResponseContent();
            try
            {
                Dt_StockInfo stockInfo = _stockRepository.QueryFirst(x => x.PalletCode == task.PalletCode);
                if (stockInfo == null) return webResponse.Error($"任务编号:{task.TaskNum},未找到托盘:{stockInfo.PalletCode}的库存信息");
                Dt_LocationInfo locationInfo = _locationInfoRepository.QueryFirst(x => x.LocationCode == task.SourceAddress);
                if (locationInfo == null) return webResponse.Error($"任务编号:{task.TaskNum},未找到托盘:{stockInfo.PalletCode}的货位信息");
 
 
                stockInfo.StockStatus = StockStatusEmun.出库完成.ObjToInt();
                
                int beforeStatus = locationInfo.LocationStatus;
                locationInfo.LocationStatus =(int)LocationStatusEnum.Free;
                task.TaskStatus = TaskOutStatusEnum.OutFinish.ObjToInt();
 
                _unitOfWorkManage.BeginTran();
 
                _stockRepository.DeleteData(stockInfo);
                _locationInfoRepository.UpdateData(locationInfo);   //修改成空货位
 
                BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId == 0 ? OperateTypeEnum.自动完成 : OperateTypeEnum.人工完成);
                _locationStatusChangeRecordService.AddLocationStatusChangeRecord(locationInfo, beforeStatus, StockStatusEmun.出库完成.ObjToInt(), "1", task.TaskNum);
                WebResponseContent content = TaskCompletionFeedback(task);
                //content.Status = true;
 
                if (!content.Status)
                {
                    _unitOfWorkManage.RollbackTran();
                    return content;
                }
                //Thread.Sleep(5000);
                _unitOfWorkManage.CommitTran();
                return webResponse.OK();
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                return webResponse.Error($"出库任务完成失败,任务id:{task.TaskNum},错误原因:{ex.Message}");
                throw;
            }
            
        }
 
 
 
 
 
 
 
        //==============================================移库完成反馈接口====================================================
        /// <summary>
        /// 上传移库任务完成给MES
        /// </summary>
        /// <param name="dt_Task"></param>
        /// <returns></returns>
        public WebResponseContent MES_TransferCompletionFeedback(Dt_Task dt_Task)
        {
            WebResponseContent webResponse = new WebResponseContent();
 
            try
            {
                string locationCode = null;
                if (dt_Task.TaskType == (int)TaskOutboundTypeEnum.Outbound)
                {
                    locationCode = dt_Task.SourceAddress;
                }
                else
                {
                    locationCode = dt_Task.TargetAddress;
                }
                TransferRequest transferRequest = new TransferRequest()
                {
                    //业务id,任务id后续进行更改
                    taskId = dt_Task.MEStaskId,   //任务id
                    businessId = dt_Task.MESbusinessId,   //业务id
                    sourceLocationCode = dt_Task.SourceAddress,
                    locationCode = locationCode,
                    palletCode = dt_Task.PalletCode,
                    status = "FINISH",
                    errorStatus = "NORMAL",
                    errorInfo = "",
                };
 
                //获取接口进行调取
                var ConfigsAPIInfo = _dt_ApiInfoService.GetConfigsByAPIInfo(CateGoryConst.CONFIG_MES_IPAddress, SysConfigConst.MESTransferCompletionFeedback);      //获取到wcs全部类型的接口
                string WCSReceiveTaskAPI = ConfigsAPIInfo.ApiAddress + ConfigsAPIInfo.ApiName;
                if (WCSReceiveTaskAPI == null)
                {
                   return webResponse.Error($"出库失败,未配置MES移库完成反馈接口");
                }
                var respon = HttpHelper.Post(WCSReceiveTaskAPI, JsonConvert.SerializeObject(transferRequest));
                if (respon != null)
                {
                   var response = JsonConvert.DeserializeObject<ApiResponse<object>>(respon);
                   if (response.Success)
                   {
                       return webResponse.OK();
                   }
                   else
                   {
                       return webResponse.Error($"调取接口失败,反馈参数原因:{response.Message}");
                   }
                }
                else
                {
                   return webResponse.Error($"调取接口失败,反馈参数为空");
                }
 
                return webResponse.OK();
            }
            catch (Exception ex)
            {
                return webResponse.Error($"移库任务上传失败!原因:{ex.Message}");
                throw;
            }
        }
 
 
        /// <summary>
        /// 上传出入库任务完成给MES
        /// </summary>
        /// <param name="dt_Task"></param>
        /// <returns></returns>
        public WebResponseContent TaskCompletionFeedback(Dt_Task dt_Task)
        {
            WebResponseContent webResponse = new WebResponseContent();
 
            try
            {
                string locationCode = null;
                if (dt_Task.TaskType == (int)TaskOutboundTypeEnum.Outbound)
                {
                    locationCode = dt_Task.SourceAddress;
                }
                else
                {
                    locationCode = dt_Task.TargetAddress;
                }
                TaskNotification transferRequest = new TaskNotification()
                    {
                        //业务id,任务id后续进行更改
                        taskId = dt_Task.MEStaskId,   //任务id
                        businessId = dt_Task.MESbusinessId,   //业务id
                        palletCode = dt_Task.PalletCode,
                        subPalletCode = dt_Task.MESsubPalletCode,//子托盘编码
                        locationCode = locationCode,
                        errorStatus = "NORMAL",
                        errorInfo = "",
                    };
 
                //获取接口进行调取
                var ConfigsAPIInfo = _dt_ApiInfoService.GetConfigsByAPIInfo(CateGoryConst.CONFIG_MES_IPAddress, SysConfigConst.MESTaskFeedback);      //获取到wcs全部类型的接口
                string WCSReceiveTaskAPI = ConfigsAPIInfo.ApiAddress + ConfigsAPIInfo.ApiName;
                if (WCSReceiveTaskAPI == null)
                {
                    return webResponse.Error($"任务反馈MES失败,未配置MES任务完成反馈接口");
                }
                
                // 添加调试信息
                string requestJson = JsonConvert.SerializeObject(transferRequest);
                //Console.WriteLine($"MES反馈接口URL: {WCSReceiveTaskAPI}");
                //Console.WriteLine($"MES反馈请求数据: {requestJson}");
                
                // 使用修复后的PostSync方法(已在PostSync中设置默认请求头)
                var respon = HttpHelper.Post(WCSReceiveTaskAPI, requestJson);
                if (respon != null)
                {
                    var response = JsonConvert.DeserializeObject<ApiResponse<object>>(respon);
                    if (response.Success)
                    {
                        return webResponse.OK();
                    }
                    else
                    {
                        return webResponse.Error($"调取接口失败,反馈参数原因:{response.Message}");
                    }
                }
                else
                {
                    return webResponse.Error($"调取接口失败,反馈参数为空");
                }
            }
            catch (Exception ex)
            {
                return webResponse.Error($"任务任务上传失败!原因:{ex.Message}");
                throw;
            }
        }
 
        public ApiResponse<object> MESresponse(string Message, bool Success,int  Code)
        {
            ApiResponse<object> apiResponse = new ApiResponse<object>();
            apiResponse.Message = Message;
            apiResponse.Success = Success;
            apiResponse.Code = 1;
            return apiResponse;
        }
 
        /// <summary>
        /// 取消任务接口
        /// </summary>
        /// <param name="taskNum">任务号</param>
        /// <returns></returns>
        public WebResponseContent Cancelinventory(int taskNum)
        {
            WebResponseContent webResponse = new WebResponseContent();
            try
            {
                // 查找任务
                Dt_Task task = BaseDal.QueryFirst(x => x.TaskNum == taskNum &&(x.TaskStatus == TaskOutStatusEnum.OutNew.ObjToInt()|| x.TaskStatus == TaskRelocationStatusEnum.RelocationNew.ObjToInt()|| x.TaskStatus == TaskInStatusEnum.Line_InExecuting.ObjToInt()));
                if (task == null)
                {
                    return webResponse.Error($"未找到任务号为【{taskNum}】的任务信息");
                }
 
                bool res;
                switch (task.TaskType)
                {
                    case (int)TaskInboundTypeEnum.Inbound:
                        res = task.TaskStatus == TaskInStatusEnum.Line_InExecuting.ObjToInt();
                        break;
                    case (int)TaskOutboundTypeEnum.Outbound:
                        res = task.TaskStatus == TaskOutStatusEnum.OutNew.ObjToInt();
                        break;
                    case (int)TaskRelocationTypeEnum.Relocation:
                        res = task.TaskStatus == TaskRelocationStatusEnum.RelocationNew.ObjToInt();
                        break;
                    default:
                        res = false;
                        break;
                }
                if (!res) return WebResponseContent.Instance.Error("任务状态异常");
 
                Dt_StockInfo stockInfo = _stockRepository.QueryFirst(x => x.PalletCode == task.PalletCode);
 
                _unitOfWorkManage.BeginTran();
 
                int stockmsseg;
                int locationmsseg;
                bool taskmsseg;
                if (task.TaskType == TaskOutboundTypeEnum.Outbound.ObjToInt() || task.TaskType == TaskRelocationTypeEnum.Relocation.ObjToInt())
                {
                    stockmsseg = _stockRepository.Db.Updateable<Dt_StockInfo>()
                  .SetColumns(x => x.StockStatus == StockStatusEmun.入库完成.ObjToInt())
                  .Where(x => x.PalletCode == task.PalletCode)
                  .ExecuteCommand();
                    locationmsseg = _locationInfoRepository.Db.Updateable<Dt_LocationInfo>()
          .SetColumns(x => x.LocationStatus == LocationStatusEnum.InStock.ObjToInt())
          .Where(x => x.LocationCode == stockInfo.LocationCode)
          .ExecuteCommand();
                    taskmsseg = BaseDal.DeleteData(task);
                }
                else
                {
                    locationmsseg = _locationInfoRepository.Db.Updateable<Dt_LocationInfo>()
                    .SetColumns(x => x.LocationStatus == LocationStatusEnum.Free.ObjToInt())
                    .Where(x => x.LocationCode == stockInfo.LocationCode)
                    .ExecuteCommand();
                    stockmsseg = _stockRepository.DeleteData(stockInfo).ObjToInt();
                    taskmsseg = BaseDal.DeleteData(task);
                }
                BaseDal.DeleteAndMoveIntoHty(task, App.User.UserId > 0 ? OperateTypeEnum.人工完成 : OperateTypeEnum.自动完成);
                //获取接口进行调取
                var ConfigsAPIInfo = _dt_ApiInfoService.GetConfigsByAPIInfo(CateGoryConst.CONFIG_WCS_IPAddress, SysConfigConst.WCSCancelinventory);      //获取到wcs全部类型的接口
                string WCSReceiveTaskAPI = ConfigsAPIInfo.ApiAddress + ConfigsAPIInfo.ApiName;
                if (WCSReceiveTaskAPI == null)
                {
                    _unitOfWorkManage.RollbackTran();
 
                    return webResponse.Error($"任务手动取消失败,未配置WCS任务手动取消反馈接口");
                }
                var respon = HttpHelper.Get(WCSReceiveTaskAPI, JsonConvert.SerializeObject(task.TaskNum));
 
                if (respon == null)
                {
                    _unitOfWorkManage.RollbackTran();
 
                    return webResponse.Error($"调取接口失败,反馈参数为空");
                }
                var response = JsonConvert.DeserializeObject<ApiResponse<object>>(respon);
                if (!response.Success)
                {
                    _unitOfWorkManage.RollbackTran();
 
                    return webResponse.Error($"调取接口失败,反馈参数原因:{response.Message}");
                }
                if (stockmsseg <= 0 && locationmsseg <= 0 && taskmsseg)
                    {
                    _unitOfWorkManage.RollbackTran();
                    return webResponse.Error("任务取消失败");
                    }
 
                //获取接口进行调取
                var MESConfigsAPIInfo = _dt_ApiInfoService.GetConfigsByAPIInfo(CateGoryConst.CONFIG_MES_IPAddress, SysConfigConst.MEScancelTask);      //获取到MES全部类型的接口
                string MEScancelTask = ConfigsAPIInfo.ApiAddress + ConfigsAPIInfo.ApiName;
                if (MEScancelTask == null)
                {
                    _unitOfWorkManage.RollbackTran();
                    return webResponse.Error($"任务手动完成失败,未配置WCS任务手动完成反馈接口");
                }
                var MES = new
                {
                    businessId = task.MESbusinessId,
                    taskId = task.MEStaskId,
                    palletCode = task.PalletCode
                };
                var MESrespon = HttpHelper.Post(MEScancelTask, JsonConvert.SerializeObject(MES));
                if (respon == null)
                {
                    _unitOfWorkManage.RollbackTran();
                    return webResponse.Error($"调取接口失败,反馈参数为空");
                }
                var MESresponse = JsonConvert.DeserializeObject<ApiResponse<object>>(respon);
                if (!response.Success)
                {
                    _unitOfWorkManage.RollbackTran();
                    return webResponse.Error($"调取接口失败,反馈参数原因:{response.Message}");
                }
                _unitOfWorkManage.CommitTran();
                return webResponse.OK("任务取消成功");
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                return webResponse.Error($"取消任务失败,原因:{ex.Message}");
            }
        }
 
        /// <summary>
        /// 创建货位
        /// </summary>
        /// <param name="locationInfo"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResponse<object> createLocation(List<LocationInfoDto> locationInfo)
        {
            List<Dt_LocationInfo> dt_LocationInfoList = new List<Dt_LocationInfo>();
            foreach (var item in locationInfo)
            {
                Dt_LocationInfo dt_LocationInfo = new Dt_LocationInfo()
                {
                    LocationCode = item.locationCode,
                    LocationName = item.locationName,
                    RoadwayNo = item.roadwayNo,
                    Row = item.row,
                    Column = item.column,
                    Layer = item.layer,
                    Depth = (int)item.depth,
                    LocationType = item.locationType,
                    LocationStatus = item.locationStatus,
                    EnableStatus = item.enableStatus == true ? 1 : 0,
                    Remark = item.remark,
                    CreateDate = DateTime.Now,
                    Creater = App.User.UserName,
                };
                dt_LocationInfoList.Add(dt_LocationInfo);
            }
            int res = _locationInfoRepository.AddData(dt_LocationInfoList);
            if (res <= 0)
            {
                return MESresponse($"创建货位失败",false);
            }
            return MESresponse($"", true);
        }
 
        /// <summary>
        /// 修改货位
        /// </summary>
        /// <param name="locationInfo"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResponse<object> updateLocation(LocationInfoDto locationInfo)
        {
            Dt_LocationInfo dt_LocationInfo = new Dt_LocationInfo()
            {
                LocationCode = locationInfo.locationCode,
                LocationName = locationInfo.locationName,
                RoadwayNo = locationInfo.roadwayNo,
                Row = locationInfo.row,
                Column = locationInfo.column,
                Layer = locationInfo.layer,
                Depth = (int)locationInfo.depth,
                LocationType = locationInfo.locationType,
                LocationStatus = locationInfo.locationStatus,
                EnableStatus = locationInfo.enableStatus == true ? 1 : 0,
                Remark = locationInfo.remark,
                CreateDate = DateTime.Now,
            };
            bool res = _locationInfoRepository.Db.Updateable(dt_LocationInfo)
    .Where(x => x.LocationCode == dt_LocationInfo.LocationCode)
    .ExecuteCommand() > 0;
            if (!res)
            {
                return MESresponse($"修改货位失败",false);
            }
            return MESresponse($"", true);
        }
 
        /// <summary>
        /// 删除货位
        /// </summary>
        /// <param name="locationCode"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResponse<object> deleteLocation(List<string> locationCode)
        {
            WebResponseContent webResponseContent = new WebResponseContent();
            int res = _locationInfoRepository.Db.Deleteable<Dt_LocationInfo>().Where(x => locationCode.Contains(x.LocationCode)).ExecuteCommand();
            if (res <= 0)
            {
                return MESresponse($"删除货位失败",false);
            }
            return MESresponse($"", true);
        }
 
 
        public static string GetLastPart(string locationCode)
        {
            string[] parts = locationCode.Split('-');
            return parts[parts.Length - 1];
        }
 
 
        /// <summary>
        /// 出库
        /// </summary>
        /// <param name="locationCode"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public WebResponseContent chuku(string locationCode)
        {
 
            try
            {
                Dt_StockInfo dt_StockInfo =  _stockRepository.QueryFirst(x => x.LocationCode.StartsWith("SC01") && x.StockStatus == 6);
                int result = GetLastPart(dt_StockInfo.LocationCode).ObjToInt(); // 返回 "C03"
 
                List<Dt_Task> dt_s = new List<Dt_Task>();
                //生成移动任务
                Dt_Task dt_Task = new()
                {
                    PalletCode = dt_StockInfo.PalletCode,
                    TaskNum = GetTaskNum(nameof(SequenceEnum.SeqTaskNum)),
                    Roadway = "SC01",
                    TaskType = TaskOutboundTypeEnum.Outbound.ObjToInt(),
                    TaskStatus = TaskOutStatusEnum.OutNew.ObjToInt(),
                    SourceAddress = dt_StockInfo.LocationCode,
                    TargetAddress = "1006",
                    CurrentAddress = dt_StockInfo.LocationCode,
                    NextAddress = "1006",
                    Grade = 1,
                    Creater = "MES",
                    Depth = result,
                    CreateDate = DateTime.Now,
                    MEStaskId = "EXTASK20251020002",
                    MESbusinessId = "EXBUS20251020002",
                    MESsubPalletCode = dt_StockInfo.MESsubPalletCode,
                    OutboundPlatform = "1005"
                };
 
                ////创建组盘信息
                //var dt_Stock = new Dt_StockInfo
                //{
                //    PalletCode = dt_Task.PalletCode,
                //    PalletType = 1,
                //    LocationCode = locationCode,
                //    StockStatus = 6,
                //    Creater = "WMS",
                //    CreateDate = DateTime.Now,
                //    MESsubPalletCode = dt_Task.MESsubPalletCode,
                //};
 
                Dt_LocationInfo dt_LocationInfo = _locationInfoRepository.QueryFirst(x => x.LocationCode == dt_StockInfo.LocationCode);
                dt_LocationInfo.LocationStatus = (int)LocationStatusEnum.InStockLock;
                dt_StockInfo.StockStatus = 7;
 
                bool l = _locationInfoRepository.UpdateData(dt_LocationInfo);
                bool s = _stockRepository.UpdateData(dt_StockInfo);
                int t = BaseDal.AddData(dt_Task);
                bool ss = s.ObjToBool();
                bool tt = t.ObjToBool();
 
 
                if (!l && !ss && tt)
                {
                    _unitOfWorkManage.RollbackTran();
                }
 
                dt_s.Add(dt_Task);
                var respon = PushTasksToWCS(dt_s, "");
                if (respon.Status)
                {
                    _unitOfWorkManage.CommitTran();  //提交事务
                    return WebResponseContent.Instance.OK();
                }
                return WebResponseContent.Instance.Error();
            }
            catch
            {
                _unitOfWorkManage.RollbackTran();
                return WebResponseContent.Instance.Error();
 
            }
        }
 
        /// <summary>
        /// 手动完成接口
        /// </summary>
        /// <param name="taskNum"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public WebResponseContent ManualTaskCompleted(int taskNum)
        {
            WebResponseContent webResponse = new WebResponseContent();
            try
            {
                // 查找任务
                Dt_Task task = BaseDal.QueryFirst(x => x.TaskNum == taskNum);
                if (task == null)
                {
                    return webResponse.Error($"未找到任务号为【{taskNum}】的任务信息");
                }
 
 
                Dt_StockInfo stockInfo = _stockRepository.QueryFirst(x => x.PalletCode == task.PalletCode);
 
                _unitOfWorkManage.BeginTran();
 
                Dt_StockInfo stockmsseg;
                Dt_LocationInfo locationmsseg1 = null;
                Dt_LocationInfo locationmsseg2 = null;
                bool taskmsseg;
                bool task_htymsseg;
 
                bool location1;
                bool location2 = false;
 
                bool resstock;
                if (task.TaskType == TaskInboundTypeEnum.Inbound.ObjToInt() || task.TaskType == TaskRelocationTypeEnum.Relocation.ObjToInt())
                {
                    stockmsseg = _stockRepository.QueryFirst(x => x.LocationCode == task.TargetAddress);
                    if (stockmsseg == null) { return webResponse.Error("未找到库存信息"); };
                    stockmsseg.StockStatus = StockStatusEmun.入库完成.ObjToInt();
                     resstock = _stockRepository.UpdateData(stockmsseg);
                    if (task.TaskType == TaskRelocationTypeEnum.Relocation.ObjToInt())
                    {
                        locationmsseg1 = _locationInfoRepository.QueryFirst(x => x.LocationCode == task.TargetAddress);
                        locationmsseg2 = _locationInfoRepository.QueryFirst(x => x.LocationCode == task.CurrentAddress);
                        if (locationmsseg1 == null || locationmsseg2 == null) { webResponse.Error("未找到货位信息"); }
                        locationmsseg1.LocationStatus = LocationStatusEnum.InStock.ObjToInt();
                        locationmsseg2.LocationStatus = LocationStatusEnum.Free.ObjToInt();
                        location1 = _locationInfoRepository.UpdateData(locationmsseg1);
                        location2 = _locationInfoRepository.UpdateData(locationmsseg2);
                    }
                    else
                    {
                        locationmsseg1 = _locationInfoRepository.QueryFirst(x => x.LocationCode == task.TargetAddress);
                        if (locationmsseg1 == null) { webResponse.Error("未找到货位信息"); }
                        locationmsseg1.LocationStatus = LocationStatusEnum.InStock.ObjToInt();
                        location1 = _locationInfoRepository.UpdateData(locationmsseg1);
                        
                    }
                }
                else
                {
                    stockmsseg = _stockRepository.QueryFirst(x => x.LocationCode == task.CurrentAddress);
                    if (stockmsseg == null) { return webResponse.Error("未找到库存信息"); }
                    resstock = _stockRepository.DeleteData(stockmsseg);
                    locationmsseg1 = _locationInfoRepository.QueryFirst(x => x.LocationCode == task.CurrentAddress);
                    if (locationmsseg1 == null) { webResponse.Error("未找到货位信息"); }
                    locationmsseg1.LocationStatus = LocationStatusEnum.InStock.ObjToInt();
                    location1 = _locationInfoRepository.UpdateData(locationmsseg1);
                }
 
                taskmsseg = BaseDal.DeleteData(task);
 
                task_htymsseg = BaseDal.DeleteAndMoveIntoHty(task,OperateTypeEnum.人工完成);
                //获取接口进行调取
                var ConfigsAPIInfo = _dt_ApiInfoService.GetConfigsByAPIInfo(CateGoryConst.CONFIG_WCS_IPAddress, SysConfigConst.WCSManualTaskCompleted);      //获取到wcs全部类型的接口
                string WCSReceiveTaskAPI = ConfigsAPIInfo.ApiAddress + ConfigsAPIInfo.ApiName;
                if (WCSReceiveTaskAPI == null)
                {
                    _unitOfWorkManage.RollbackTran();
                    return webResponse.Error($"任务手动完成失败,未配置WCS任务手动完成反馈接口");
                }
                var respon = HttpHelper.Get(WCSReceiveTaskAPI, JsonConvert.SerializeObject(task.TaskNum));
                if (respon == null)
                {
                    _unitOfWorkManage.RollbackTran();
                    return webResponse.Error($"调取接口失败,反馈参数为空");
                }
                var response = JsonConvert.DeserializeObject<ApiResponse<object>>(respon);
                if (!response.Success)
                {
                    _unitOfWorkManage.RollbackTran();
                    return webResponse.Error($"调取接口失败,反馈参数原因:{response.Message}");
                }
                if (!(resstock && task_htymsseg && taskmsseg && task.TaskType ==TaskOutboundTypeEnum.Outbound.ObjToInt() ? location1 : (location1 && location2)))
                    {
                    _unitOfWorkManage.RollbackTran();
                    return webResponse.Error($"任务手动完成失败");
                }
 
                //获取接口进行调取
                var MESConfigsAPIInfo = _dt_ApiInfoService.GetConfigsByAPIInfo(CateGoryConst.CONFIG_MES_IPAddress, SysConfigConst.MESmockComplete);      //获取到wcs全部类型的接口
                string MESmockComplete = ConfigsAPIInfo.ApiAddress + ConfigsAPIInfo.ApiName;
                if (MESConfigsAPIInfo == null)
                {
                    _unitOfWorkManage.RollbackTran();
                    return webResponse.Error($"任务手动完成失败,未配置WCS任务手动完成反馈接口");
                }
                var MES = new
                {
                    businessId = task.MESbusinessId,
                    taskId = task.MEStaskId,
                    palletCode = task.PalletCode
            };
                var MESrespon = HttpHelper.Post(MESmockComplete, JsonConvert.SerializeObject(MES));
                if (respon == null)
                {
                    _unitOfWorkManage.RollbackTran();
                    return webResponse.Error($"调取接口失败,反馈参数为空");
                }
                var MESresponse = JsonConvert.DeserializeObject<ApiResponse<object>>(respon);
                if (!response.Success)
                {
                    _unitOfWorkManage.RollbackTran();
                    return webResponse.Error($"调取接口失败,反馈参数原因:{response.Message}");
                }
                _unitOfWorkManage.CommitTran();
                return webResponse.OK("任务手动完成成功");
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                return webResponse.Error($"任务手动完成失败,原因:{ex.Message}");
            }
        }
    }
}