bklLiudl
2024-07-23 675b8bcc4a3630d95e3d0b97d933e63442075ecb
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
using Common;
using DataBase;
using Model;
using Model.MessageModel;
using Model.WcsModel;
using Model.WmsModel;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlTypes;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
 
namespace BLL.DAL
{
    public class DALWMSApi
    {
        public ApiLocationModel GetLocation(string palno, int height)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(palno))
                {
                    new LogHelper().WriteLog("GetLocation方法:托盘号为空 [-11]");
                    return new ApiLocationModel() { Code = "-11" }; // 参数为空
                }
 
                string ordNo = "";
                string locationCode = "";
                string oldLocationCode = "";
                StringBuilder strSQL = new StringBuilder();
 
                // 1.查看绑定托盘 
                strSQL.Append($"select OrdNo,LocationCode from IPalletBind where palNo ='{palno}' and Statu = '01' and IsDel = '0';");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(strSQL);
                if (dt != null && dt.Rows.Count > 0)
                {
                    ordNo = dt.Rows[0]["OrdNo"].ToString();
                    // 1.1 指定库位
                    locationCode = dt.Rows[0]["LocationCode"].ToString();
                }
 
                // 2.查看是否是空托盘
                strSQL.Clear();
                strSQL.Append($"select LocationCode from IPalletEmptyIn where palNo ='{palno}' and Statu = '01' and IsDel = '0';");
                DataTable dtIn = DataFactory.SqlDataBase().GetDataTableBySQL(strSQL);
 
                //// 已分配储位生成入库任务
                //strSQL.Clear();
                //strSQL.Append($"select TargetAddre from TaskMonitor where Palno ='{palno}' and TaskType = 'in' and IsDel = '0' and Statu = '1';");
                //DataTable dtI = DataFactory.SqlDataBase().GetDataTableBySQL(strSQL);
                //if (dtI != null && dtI.Rows.Count > 0)
                //{
                //    locationCode = dt.Rows[0]["TargetAddre"].ToString();
                //}
 
                // 3.托盘出库后重新回库,返回原库位地址.
                strSQL.Clear();
                strSQL.Append($@"
SELECT dl.LocationCode
FROM dbo.log_Store ls
    LEFT OUTER JOIN dbo.DepotsLocation dl
        ON dl.LocationCode = ls.LocationCode
WHERE ls.Palno = '{palno}'
      AND ls.IsDel = 0
      AND dl.TurnoverDemand = '03';");
                DataTable dtDL = DataFactory.SqlDataBase().GetDataTableBySQL(strSQL);
 
                if (dtDL != null && dtDL.Rows.Count > 0)
                {
                    oldLocationCode = dtDL.Rows[0]["LocationCode"].ToString();
                }
 
                // 4.1 判断是否是空托
                if (dtIn == null || dtIn.Rows.Count <= 0)
                {
                    // 4.2 不是空托,并且不是回库的不可调用
                    if (string.IsNullOrWhiteSpace(ordNo)
                        && string.IsNullOrWhiteSpace(oldLocationCode))
                    {
                        new LogHelper().WriteLog("GetLocation方法:无组盘,无空托盘入库 [-101]");
                        return new ApiLocationModel() { Code = "-101" }; //没贴该条码的托盘
                    }
                }
                else
                {
                    // 4.2 是空托盘,是否指定库位
                    if (string.IsNullOrWhiteSpace(locationCode))
                    {
                        locationCode = dtIn.Rows[0]["LocationCode"].ToString();
                    }
                }
 
                // 5. 是否指定库位 
                if (string.IsNullOrWhiteSpace(locationCode))
                {
                    // 5.1 没指定库位,将回库库位给定 其他情况上面已排除.
                    locationCode = oldLocationCode;
                }
                else
                {
                    // 5.2 指定库位,原库位数据全部变动.更新为指定的库位
                    strSQL.Clear();
                    strSQL.Append($@"
UPDATE dbo.DepotsLocation SET TurnoverDemand='02' WHERE LocationCode='{oldLocationCode}' AND IsDel=0;
UPDATE dbo.Picking SET Addre='{locationCode}' WHERE Addre='{oldLocationCode}' AND Palno='{palno}' AND IsDel=0;
UPDATE dbo.log_Store SET LocationCode='{locationCode}' WHERE LocationCode='{oldLocationCode}' AND Palno='{palno}' AND IsDel=0;
");
                    DataFactory.SqlDataBase().ExecuteBySql(strSQL);
                }
 
                // 6. 根据库位地址,查询库位详细信息
                strSQL.Clear();
                if (string.IsNullOrWhiteSpace(locationCode))
                {
                    // 6.1 自动分配库位.
                    strSQL.Append($@"
select top(1) * 
from View_GetEmptyPos 
where Height >={height} 
order by Height, LLayer, LRow, LColumn");
                }
                else
                {
                    // 6.2 回库,或已指定库位.
                    strSQL.Append($@"
select top(1) * 
from dbo.DepotsLocation 
where LocationCode='{locationCode}'");
                }
 
                IDataReader dtReader = DataFactory.SqlDataBase().GetDataReaderBySQL(strSQL);
                if (dtReader != null)
                {
                    DepotsLocation dl = ModelConvertHelper<DepotsLocation>.ReaderToModel(dtReader);
                    if (dl == null)
                    {
                        new LogHelper().WriteLog($"GetLocation方法:错误,无库位 [-105] LocationCode='{locationCode}' palNo='{palno}'");
                        return new ApiLocationModel() { Code = "-105" };
                    }
                    DAL_Pub pub = new DAL_Pub();
                    locationCode = dl.LocationCode;
                    pub.UpdateDeopotsLocation(dl.LocationCode, "03");   //待入库
                    if (string.IsNullOrEmpty(ordNo)) //订单号为空则为空托盘入库.
                    {
                        pub.UpdatePalletEmptyInStatus(palno, "02");
                    }
                    else
                    {
                        pub.UpdatePalletBind(palno, 2);//托盘绑定正在处理
                    }
 
                    new LogHelper().WriteLog($"GetLocation方法:访问成功 [01] LocationCode='{locationCode}' palNo='{palno}' height='{height}'");
                    InsOrUpLog(new WhCmd()
                    {
                        CMDStatu = 2,
                        CMDType = "in",
                        CreateUser = "WCS",
                        Height = height,
                        Palno = palno,
                        OldAddre = locationCode,
                        TaskID = ordNo,
                        IsDel = 1
                    });
                    return new ApiLocationModel()
                    {
                        Code = "01",
                        LocationCode = dl.LocationCode,
                        LocationX = dl.LColumn.ToString(),
                        LocationY = dl.LRow.ToString(),
                        LocationZ = dl.LLayer.ToString(),
                        LocationD = dl.Long.ToString()
                    };
                }
                new LogHelper().WriteLog($"GetLocation方法:错误,无库位 [-104] LocationCode='{locationCode}' palNo='{palno}'");
                return new ApiLocationModel() { Code = "-104" };
            }
            catch (Exception ex)
            {
                new LogHelper().WriteLog($"GetLocation方法:异常 [-103] palNo='{palno}'  " + ex.ToString());
                return new ApiLocationModel() { Code = "-103" };
            }
        }
 
        /// <summary>
        /// 上架成功
        /// </summary>
        /// <returns></returns>
        public ApiLocationModel PutStorage(string palno, string locationCode)
        {
            try
            {
                DAL_Pub pub = new DAL_Pub();
 
                string ordNo = "";
                string departGuid = "";
                StringBuilder strSQL = new StringBuilder();
                strSQL.Append($@"
SELECT 1
FROM dbo.log_Store ls
    LEFT OUTER JOIN dbo.DepotsLocation dl
        ON dl.LocationCode = ls.LocationCode
WHERE ls.Palno = '{palno}'
      AND ls.IsDel = 0
      AND dl.TurnoverDemand = '03';");
                // 待入库,直接更新库位状态即可.
                DataTable dtPan = DataFactory.SqlDataBase().GetDataTableBySQL(strSQL);
                if (dtPan != null && dtPan.Rows.Count > 0)
                {
                    pub.UpdateDeopotsLocation(locationCode, "02");   //合格
 
                    strSQL.Clear();
                    strSQL.Append($"UPDATE CheckTask SET statu='03' WHERE LocationCode1='{locationCode}' AND Palno1='{palno}'");
                    DataFactory.SqlDataBase().ExecuteBySql(strSQL);
 
                    // 回库表删除
                    strSQL.Clear();
                    strSQL.Append($"UPDATE dbo.Picking SET IsDel=1 WHERE Addre='{locationCode}' AND Palno='{palno}'");
                    DataFactory.SqlDataBase().ExecuteBySql(strSQL);
                }
 
                strSQL.Clear();
                strSQL.Append($"select * from IPalletBind where palNo ='{palno}' and Statu = '02' and IsDel = '0';");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(strSQL);
                if (dt != null && dt.Rows.Count > 0)
                {
                    ordNo = dt.Rows[0]["OrdNo"].ToString();
                    departGuid = dt.Rows[0]["DepartGuid"].ToString();
                }
                //排除出库重新组盘的业务点.如果是则继续执行后续操作即可.
                if (string.IsNullOrWhiteSpace(ordNo) && dtPan != null && dtPan.Rows.Count > 0)
                {
                    new LogHelper().WriteLog($"PutStorage:托盘入库成功-回库/盘库 [01] LocationCode='{locationCode}' palNo='{palno}'");
                    InsOrUpLog(new WhCmd()
                    {
                        CMDStatu = 1,
                        CMDType = "out",
                        CreateUser = "WCS",
                        OldAddre = locationCode,
                        Palno = palno,
                        IsDel = 1,
                        TaskID = ordNo
                    });
                    return new ApiLocationModel() { Code = "01" };
                }
 
                strSQL.Clear();
                strSQL.Append($"select 1 from IPalletEmptyIn where palNo ='{palno}' and Statu = '02' and IsDel = '0';");
                DataTable dtIn = DataFactory.SqlDataBase().GetDataTableBySQL(strSQL);
                if (dtIn == null || dtIn.Rows.Count <= 0)
                {
                    if (string.IsNullOrWhiteSpace(ordNo))
                    {
                        new LogHelper().WriteLog($"PutStorage:错误,无组盘,无空托入库单 [-101] LocationCode='{locationCode}' palNo='{palno}'");
                        return new ApiLocationModel() { Code = "-101" }; //没贴该条码的托盘
                    }
                }
 
                if (!string.IsNullOrEmpty(ordNo))
                {
                    //非空托处理
                    IDALPalletBind pb = new DALPalletBind();
 
                    //修改库位状态
                    pub.UpdateDeopotsLocation(locationCode, "02");
                    //修改托盘绑定状态 入库完成
                    pub.UpdatePalletBindStatus(palno, ordNo, "03");
 
                    IList<PalletBind> pbLst = new List<PalletBind>();
                    bool br = pb.GetPalletBind(palno, ref pbLst);
                    //修改库存明细表
                    pub.UpdateLogStore(locationCode, pbLst);
                    //修改库存表
                    pub.UpdateLogStoreMat(palno, pbLst);
 
                    //修改入库单状态  所有数据调整完毕后才可以修改单据状态
                    pub.UpdateErp(palno);
 
                    new LogHelper().WriteLog($"PutStorage:组盘-托盘入库成功 [01] LocationCode='{locationCode}' palNo='{palno}'");
                    InsOrUpLog(new WhCmd()
                    {
                        CMDStatu = 1,
                        CMDType = "in",
                        CreateUser = "WCS",
                        OldAddre = locationCode,
                        Palno = palno,
                        IsDel = 1,
                        TaskID = ordNo
                    });
                    return new ApiLocationModel() { Code = "01" };
                }
                else
                {
                    //修改空托入库表状态
                    int count = 0;
                    var r = pub.GetPalletEmptyCount(palno, ref count);
                    if (r != -1)
                    {
                        //更新库存明细表
                        pub.UpdatePalletLogStore(locationCode, palno, count);
                        // 修改库位状态
                        pub.UpdateDeopotsLocation(locationCode, "02");   //合格/空托盘
                        pub.UpdatePalletEmptyInStatus(palno, "03"); //更新库存表
                        pub.DelPalletEmptyIn(palno);
 
                        new LogHelper().WriteLog($"PutStorage:空托-托盘入库成功 [01] LocationCode='{locationCode}' palNo='{palno}'");
                        InsOrUpLog(new WhCmd()
                        {
                            CMDStatu = 1,
                            CMDType = "in",
                            CreateUser = "WCS",
                            OldAddre = locationCode,
                            Palno = palno,
                            IsDel = 1,
                            TaskID = ordNo
                        });
                        return new ApiLocationModel() { Code = "01" };
                    }
                }
                new LogHelper().WriteLog($"PutStorage:错误,无业务覆盖 [-201] LocationCode='{locationCode}' palNo='{palno}'");
                return new ApiLocationModel() { Code = "-201" };
            }
            catch (Exception ex)
            {
                new LogHelper().WriteLog($"PutStorage:异常 [-202] LocationCode='{locationCode}' palNo='{palno}'  " + ex.ToString());
                return new ApiLocationModel() { Code = "-202" };//异常
            }
        }
 
        /// <summary>
        /// 出库完成
        /// </summary>
        /// <param name="palno"></param>
        /// <param name="locationCode"></param>
        /// <returns></returns>
        public ApiLocationModel OutStorage(string palno, string locationCode)
        {
            try
            {
                DAL_Pub pub = new DAL_Pub();
                string ordNo = "";
                // 盘库的出库流程是什么? log_Store记录不进行修改吗?
                StringBuilder strSql = new StringBuilder();
                strSql.Append($"select DISTINCT OrdNo from View_ErpOutDetail where Palno='{palno}' and LocationCode='{locationCode}' and Statu='02'");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(strSql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        ordNo = dr["OrdNo"].ToString();
 
                        int r = pub.UpdateStore(ordNo, palno, locationCode);
                        if (r == 1)
                        {
                            pub.InsertPicking(ordNo, palno, locationCode);
                            pub.UpdateOut(ordNo, palno, locationCode);
                        }
                    }
                }
                else// 没有出库单的出库,重新组盘.
                {
                    strSql.Clear();
                    strSql.Append($"UPDATE dbo.DepotsLocation SET TurnoverDemand='03' WHERE LocationCode='{locationCode}' AND TurnoverDemand='04'");
                    DataFactory.SqlDataBase().ExecuteBySql(strSql);
                }
 
                // 盘库出库
                strSql.Clear();
                strSql.Append($"SELECT CDNO FROM View_CheckTask_Userinfo WHERE IsDel=0 AND Palno1='{palno}' AND LocationCode1='{locationCode}'");
                DataTable dtCT = DataFactory.SqlDataBase().GetDataTableBySQL(strSql);
                if (dtCT != null && dtCT.Rows.Count > 0)
                {
                    string CDNO = dtCT.Rows[0]["CDNO"].ToString();
                    strSql.Clear();
                    strSql.Append($"UPDATE CheckTask SET statu='04' WHERE CDNO='{CDNO}'");
                    DataFactory.SqlDataBase().ExecuteBySql(strSql);
 
                    strSql.Clear();
                    strSql.Append($"UPDATE dbo.DepotsLocation SET TurnoverDemand='03' WHERE LocationCode='{locationCode}'");
                    DataFactory.SqlDataBase().ExecuteBySql(strSql);
                }
 
                new LogHelper().WriteLog($"OutStorage:出库成功 [01] LocationCode='{locationCode}' palNo='{palno}'");
                InsOrUpLog(new WhCmd()
                {
                    CMDStatu = 1,
                    CMDType = "out",
                    CreateUser = "WCS",
                    OldAddre = locationCode,
                    Palno = palno,
                    IsDel = 1,
                    TaskID = ordNo
                });
                return new ApiLocationModel() { Code = "01" };
            }
            catch (Exception ex)
            {
                new LogHelper().WriteLog($"OutStorage:异常 [-202] LocationCode='{locationCode}' palNo='{palno}'  " + ex.ToString());
                return new ApiLocationModel() { Code = "-202" }; //异常
            }
        }
 
        /// <summary>
        /// 给wcs发送指令.
        /// </summary>
        /// <param name="depotsLocation"></param>
        /// <returns></returns>
        public bool Send(string palno, string locationCode, string OutMode)
        {
            //return true;
            try
            {
                StringBuilder stringBuilder = new StringBuilder();
                // 02 出库单使用  04:出库中 空托盘根据此判断
                stringBuilder.Append($"SELECT * FROM dbo.DepotsLocation WHERE LocationCode='{locationCode}' AND TurnoverDemand ='02'");
                IDataReader dtReader = DataFactory.SqlDataBase().GetDataReaderBySQL(stringBuilder);
                if (dtReader == null)
                {
                    new LogHelper().WriteLog($"Send:错误,无库存[-301] LocationCode='{locationCode}'");
                    return false;
                }
                DepotsLocation depotsLocation = ModelConvertHelper<DepotsLocation>.ReaderToModel(dtReader);
                if (depotsLocation == null)
                {
                    new LogHelper().WriteLog($"Send:错误,无库存[-301] LocationCode='{locationCode}'");
                    return false;
                }
                ApiLocationModel apiLocation = new ApiLocationModel()
                {
                    Code = "1",
                    LocationCode = depotsLocation.LocationCode,
                    LocationX = depotsLocation.LColumn.ToString(),
                    LocationY = depotsLocation.LRow.ToString(),
                    LocationZ = depotsLocation.LLayer.ToString(),
                    LocationD = depotsLocation.Long.ToString(),
                    OutMode = OutMode //出库口,后续看是哪个字段.
                };
 
                #region 使用接口对接
                //string jsonLoc = JsonHelper.ObjectToJson(apiLocation);
 
                //string serviceUrl = ConfigHelper.GetAppSettings("WCSAPI") + jsonLoc;
                ////创建Web访问对象
                //HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri(serviceUrl));
                ////通过Web访问对象获取响应内容
                //HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                ////通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
                //StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                ////string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
                //string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
 
                //reader.Close();
                //if (myResponse != null)
                //    myResponse.Close();
                //if (myRequest != null)
                //    myRequest.Abort();
                #endregion
 
                #region 利用中间表对接
                stringBuilder.Clear();
                // 插入任务表
                stringBuilder.Append("INSERT INTO TaskMonitor(TaskNo,TaskType,InitialAddre, Palno, TargetAddre, State, IsSucceed, ErrorStr, PriorityLevel, Source,Demo,CreateTime,IsDel) values ");
                stringBuilder.Append($"('out','out','{locationCode}','{palno}','{OutMode}','0','0','','0','WMS','',GETDATE(),'0')");
                int rowCount = DataFactory.SqlDataBase().ExecuteBySql(stringBuilder);
                #endregion
 
                string ordNo = "";
                StringBuilder strSql = new StringBuilder();
                strSql.Append($"select DISTINCT OrdNo from View_ErpOutDetail where Palno='{palno}' and LocationCode='{locationCode}' and Statu='01'");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(strSql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        ordNo = dr["OrdNo"].ToString();
                    }
                }
                new LogHelper().WriteLog($"Send:出库指令下发成功[01] LocationCode='{locationCode}' OutMode='{OutMode}'");
                InsOrUpLog(new WhCmd()
                {
                    CMDStatu = 0,
                    CMDType = "out",
                    CreateUser = "WCS",
                    OldAddre = locationCode,
                    Palno = palno,
                    Demo = "出库口:" + OutMode,
                    TaskID = ordNo
 
                });
                return true;
            }
            catch (Exception ex)
            {
                new LogHelper().WriteLog($"OutStorage:异常 [-302] LocationCode='{locationCode}' " + ex.ToString());
                return false;
            }
        }
 
 
        /// <summary>
        /// 空托盘给wcs发送指令.
        /// </summary>
        /// <param name="depotsLocation"></param>
        /// <returns></returns>
        public bool Send1(string palno, string locationCode, string OutMode)
        {
            //return true;
            try
            {
                StringBuilder stringBuilder = new StringBuilder();
                // 02 出库单使用  04:出库中 空托盘根据此判断
                stringBuilder.Append($"SELECT * FROM dbo.DepotsLocation WHERE LocationCode='{locationCode}' AND TurnoverDemand in ('02','04')");
                IDataReader dtReader = DataFactory.SqlDataBase().GetDataReaderBySQL(stringBuilder);
                if (dtReader == null)
                {
                    new LogHelper().WriteLog($"Send:错误,无库存[-301] LocationCode='{locationCode}'");
                    return false;
                }
                DepotsLocation depotsLocation = ModelConvertHelper<DepotsLocation>.ReaderToModel(dtReader);
                if (depotsLocation == null)
                {
                    new LogHelper().WriteLog($"Send:错误,无库存[-301] LocationCode='{locationCode}'");
                    return false;
                }
                ApiLocationModel apiLocation = new ApiLocationModel()
                {
                    Code = "1",
                    LocationCode = depotsLocation.LocationCode,
                    LocationX = depotsLocation.LColumn.ToString(),
                    LocationY = depotsLocation.LRow.ToString(),
                    LocationZ = depotsLocation.LLayer.ToString(),
                    LocationD = depotsLocation.Long.ToString(),
                    OutMode = OutMode //出库口,后续看是哪个字段.
                };
 
                #region 使用接口对接
                //string jsonLoc = JsonHelper.ObjectToJson(apiLocation);
 
                //string serviceUrl = ConfigHelper.GetAppSettings("WCSAPI") + jsonLoc;
                ////创建Web访问对象
                //HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri(serviceUrl));
                ////通过Web访问对象获取响应内容
                //HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                ////通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
                //StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                ////string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
                //string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
 
                //reader.Close();
                //if (myResponse != null)
                //    myResponse.Close();
                //if (myRequest != null)
                //    myRequest.Abort();
                #endregion
 
                #region 利用中间表对接
                stringBuilder.Clear();
                // 插入任务表
                stringBuilder.Append("INSERT INTO TaskMonitor(TaskNo,TaskType,InitialAddre, Palno, TargetAddre, State, IsSucceed, ErrorStr, PriorityLevel, Source,Demo,CreateTime,IsDel) values ");
                stringBuilder.Append($"('out','out','{locationCode}','{palno}','{OutMode}','0','0','','0','WMS','',GETDATE(),'0')");
                int rowCount = DataFactory.SqlDataBase().ExecuteBySql(stringBuilder);
                #endregion
 
                string ordNo = "";
                StringBuilder strSql = new StringBuilder();
                strSql.Append($"select DISTINCT OrdNo from View_ErpOutDetail where Palno='{palno}' and LocationCode='{locationCode}' and Statu='01'");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(strSql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        ordNo = dr["OrdNo"].ToString();
                    }
                }
                new LogHelper().WriteLog($"Send:出库指令下发成功[01] LocationCode='{locationCode}' OutMode='{OutMode}'");
                InsOrUpLog(new WhCmd()
                {
                    CMDStatu = 0,
                    CMDType = "out",
                    CreateUser = "WCS",
                    OldAddre = locationCode,
                    Palno = palno,
                    Demo = "出库口:" + OutMode,
                    TaskID = ordNo
 
                });
                return true;
            }
            catch (Exception ex)
            {
                new LogHelper().WriteLog($"OutStorage:异常 [-302] LocationCode='{locationCode}' " + ex.ToString());
                return false;
            }
        }
 
        /// <summary>
        /// 插入或修改whcmd表数据.
        /// </summary>
        /// <param name="whCmd"></param>
        /// <returns></returns>
        private bool InsOrUpLog(WhCmd whCmd)
        {
            try
            {
                // 1.1 根据订单,没有则插入
                StringBuilder sb = new StringBuilder();
                sb.Append($"SELECT 1 FROM dbo.WH_CMD WHERE OldAddre='{whCmd.OldAddre}' AND Palno='{whCmd.Palno}' AND CMDStatu<>1 AND IsDel=0");
                DataTable dtCMD = DataFactory.SqlDataBase().GetDataTableBySQL(sb);
                //if (dtCMD != null && dtCMD.Rows.Count > 0)
                //{
                //    // 1.2 已经有值,不需要插入,更改即可
                //    sb.Clear();
                //    string NowAddre = string.IsNullOrWhiteSpace(whCmd.NowAddre) ? whCmd.OldAddre : whCmd.NowAddre;
                //    sb.Append($"UPDATE dbo.WH_CMD SET CMDStatu={whCmd.CMDStatu},IsDel={whCmd.IsDel},OldAddre='{NowAddre}' WHERE Palno='{whCmd.Palno}' AND OldAddre='{whCmd.OldAddre}' AND CMDType='{whCmd.CMDType}' AND CMDStatu<>1 AND IsDel=0;");
                //    int resU = DataFactory.SqlDataBase().ExecuteBySql(sb);
                //    if (resU > 0)
                //    {
                //        return true;
                //    }
                //    return false;
                //}
                sb.Clear();
                sb.Append($@"
INSERT INTO dbo.WH_CMD
(
    TaskID,
    Palno,
    Height,
    CMDType,
    OldAddre,
    CMDStatu,
    CreateUser,
    CreateTime,
    Demo,
    IsDel
)
VALUES
(   '{whCmd.TaskID}',
    '{whCmd.Palno}',
    {whCmd.Height},
    '{whCmd.CMDType}',
    '{whCmd.OldAddre}',
    {whCmd.CMDStatu},
    '{whCmd.CreateUser}',
    GETDATE(),
    '{whCmd.Demo}',
    '{whCmd.IsDel}');");
                int res = DataFactory.SqlDataBase().ExecuteBySql(sb);
                if (res > 0)
                {
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }
 
 
        #region WCS提供的添加任务接口  Liudl
        /// <summary>
        /// WCS接受WMS下发的任务(单条任务)
        /// </summary>
        /// <param name="models">任务信息</param>
        /// <returns>反馈信息</returns>
        public WCSResultModel AddWcsTasks(WCSTasks models)
        {
            WCSResultModel result = new WCSResultModel();
            result.stateCode = "0";
            try
            {
                models.Type = models.TaskType;
                var res = AddWcsTask(models);
                if (res.stateCode == "-1")
                {
                    result.stateCode = "-1";
                    result.errMsg = res.errMsg + ";";
                }
                else if (res.stateCode == "1")
                {
                    result.stateCode = "0";
                    result.errMsg = models.TaskNo + "任务" + res.errMsg + ";";
                }
            }
            catch (Exception ex)
            {
                return new WCSResultModel() { stateCode = "-1", errMsg = ex.Message };
            }
 
            return result;
        }
 
 
        /// <summary>
        /// WCS接受WMS下发的任务(单条任务)
        /// </summary>
        /// <param name="models">任务信息</param>
        /// <returns>反馈信息</returns>
        public WCSResultModel AddWcsTask(WCSTasks models)
        {
            WCSResultModel result = new WCSResultModel();
            try
            {
                StringBuilder sqlString = new StringBuilder();
                // 验证任务是否已存在
                sqlString.Append($"select count(Id) from WCSTasks where TaskNo = '{models.TaskNo}';");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                if (dt.Rows[0][0].ToString() != "0")
                {
                    result.stateCode = "-1";
                    result.errMsg = "任务:" + models.TaskNo + ";已存在!";
                    return result;
                }
                if (models.Type == "0")
                {
                    models.Levels = "1.5";
                }
                else
                {
                    models.Levels = "2";
                }
 
                // 新增任务
                sqlString.Clear();
                sqlString.Append("INSERT INTO WCSTasks (TaskNo,Type,Status,Origin,StartRoadway,StartLocat,EndLocat,EndRoadway,PalletNo,");
                sqlString.Append("PalletType,LotNo,SupplierLot,SkuNo,SkuName,Qty,Levels) VALUES (");
                sqlString.Append($"'{models.TaskNo}','{models.Type}','0','WMS','{models.StartRoadway}','{models.StartLocate}',");
                sqlString.Append($"'{models.EndLocate}','{models.EndRoadway}','{models.PalletNo}','{models.PalletType}','{models.LotNo}','{models.SupplierLot}',");
                sqlString.Append($"'{models.SkuNo}','{models.SkuName}','{models.Qty}','{models.Levels}');");//,'{models.IsBale}','{models.IsBelt}',
                //sqlString.Append($"'{models.IsStacking1}','{models.IsStacking2}','{models.IsStacking3}','{models.Dismantling}');");
                var num = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                if (num <= 0)
                {
                    return new WCSResultModel() { stateCode = "-1", errMsg = "插入失败" };
                }
                else if (num >= 1)
                {
                    return new WCSResultModel() { stateCode = "1", errMsg = "插入成功" };
                }
            }
            catch (Exception ex)
            {
                return new WCSResultModel() { stateCode = "-1", errMsg = ex.Message };
            }
 
            return new WCSResultModel() { stateCode = "0" };
        }
 
        /// <summary>
        /// WCS自申请储位任务(单条任务)
        /// </summary>
        /// <param name="models">任务信息</param>
        /// <returns>反馈信息</returns>
        public WCSResultModel AddItsWcsTask(WCSTasks models)
        {
            WCSResultModel result = new WCSResultModel();
            StringBuilder sqlString = new StringBuilder();
            try
            {
                if (models.Type == "0")
                {
                    //入库
                    models.Levels = "1.5";
                }
                else
                {
                    //出、移库
                    models.Levels = "2";
                }
 
                // 新增任务
                models.TaskNo = GetTaskNo();
                sqlString.Append( "insert into WCSTasks (TaskNo,Type,Status,Origin,StartRoadway,StartLocat,EndLocat,EndRoadway,PalletNo,PalletType,LotNo,SupplierLot,SkuNo,SkuName,Qty,Levels,SyncWms,Demo) VALUES (");
                sqlString.Append($"'{models.TaskNo}','{models.Type}','0','{models.Origin}','{models.StartRoadway}','{models.StartLocate}',");
                sqlString.Append($"'{models.EndLocate}','{models.EndRoadway}','{models.PalletNo}','{models.PalletType}','{models.LotNo}','{models.SupplierLot}',");
                sqlString.Append($"'{models.SkuNo}','{models.SkuName}','{models.Qty}','{models.Levels}','0','因WMS断开链接,WCS自申请。');");
                
                var num = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                if (num <= 0)
                {
                    return new WCSResultModel() { stateCode = "-1", errMsg = "插入失败" };
                }
                else if (num >= 1)
                {
                    return new WCSResultModel() { stateCode = "1", errMsg = "插入成功" };
                }
            }
            catch (Exception ex)
            {
                return new WCSResultModel() { stateCode = "-1", errMsg = ex.Message };
            }
 
            return new WCSResultModel() { stateCode = "0" };
        }
        /// <summary>
        /// 获取最新任务号
        /// </summary>
        /// <returns></returns>
        public string GetTaskNo()
        {
            try
            {
                var taskStr = "";
                //TK2023091900003
                var codeFlag = "CS";
                var time = DateTime.Now.ToString("yyyyMMdd").Trim();
 
 
                StringBuilder sqlString = new StringBuilder();
                // 验证任务是否已存在
                sqlString.Append($"select TaskNo from WCSTasks where TaskNo like '{codeFlag + time}%' order by TaskNo desc;");
 
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                if (dt.Rows.Count != 0)
                {
                    var s = dt.Rows[0];
                    var maxNo = dt.Rows[0][0].ToString();
                    if (string.IsNullOrWhiteSpace(maxNo))
                    {
                        taskStr = codeFlag + time + "00001";
                    }
                    else
                    {
                        int lastNo = Convert.ToInt32(maxNo.Substring(10, 5)) + 1;
                        taskStr = codeFlag + time + (lastNo.ToString().PadLeft(5, '0'));
 
                    }
                }
                else
                {
                    taskStr = codeFlag + time + "00001";
                }
 
 
                return taskStr;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
 
        /// <summary>
        /// wms多条任务取消\完成接口
        /// </summary>
        /// <param name="models">任务信息</param>
        /// <returns>反馈信息</returns>
        public WCSResultModel FinshTasks(WCSTasks models)
        {
            WCSResultModel result = new WCSResultModel();
            result.stateCode = "0";
            try
            {
                var res = FinshTask(models);
                if (res.stateCode == "-1")
                {
                    result.stateCode = "-1";
                    result.errMsg = res.errMsg + ";";
                }
                else if (res.stateCode == "1")
                {
                    result.stateCode = "1";
                    result.errMsg = models.TaskNo + "任务" + res.errMsg + ";";
 
                }
            }
            catch (Exception ex)
            {
                return new WCSResultModel() { stateCode = "-1", errMsg = ex.Message };
            }
 
            return result;
        }
 
        /// <summary>
        /// WCS接受WMS下发的任务(单条任务)
        /// </summary>
        /// <param name="models">任务信息</param>
        /// <returns>反馈信息</returns>
        public WCSResultModel FinshTask(WCSTasks models)
        {
            WCSResultModel result = new WCSResultModel();
            DALWcsMessage wcsMySql = new DALWcsMessage();
            try
            {
                StringBuilder sqlString = new StringBuilder();
 
                // 修改任务
                sqlString.Clear();
                int a = models.Status == "2" ? 0 : 1;
                //判断任务是否完成
                sqlString.Append($"Update WCSTasks set Status = 2,IsSuccess = {a},FinishDate = '{DateTime.Now}' where TaskNo = '{models.TaskNo}'");
                var num = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                if (num <= 0)
                {
                    return new WCSResultModel() { stateCode = "-1", errMsg = "修改失败" };
                }
                else if (num >= 1)
                {
                    // 任务明细实体类
                    WCSTasksMonitor tasksMonitor = new WCSTasksMonitor();
                    tasksMonitor.TaskNo = models.TaskNo;
                    tasksMonitor.PlcId = 0;
                    tasksMonitor.PlcName = "";
                    tasksMonitor.Status = "2";                  // 执行完成
                    // 写入任务明细表
                    tasksMonitor.StartLocat = models.StartLocate;
                    tasksMonitor.InteractiveMsg = models.Status == "2" ? "任务已手动完成" : "任务已手动取消";
                    tasksMonitor.PalletNo = models.PalletNo;
                    tasksMonitor.EndLocat = models.EndLocate;
                    wcsMySql.AddWCSTasksMonitor(tasksMonitor);
 
                    return new WCSResultModel() { stateCode = "1", errMsg = "修改成功" };
                }
            }
            catch (Exception ex)
            {
                return new WCSResultModel() { stateCode = "-1", errMsg = ex.Message };
            }
 
            return new WCSResultModel() { stateCode = "0" };
        }
 
        public WCSResultModel EditLocaetStatus(List<WmsLocat> model)
        {
            try
            {
                StringBuilder sqlString = new StringBuilder();
                sqlString.Clear();
 
                sqlString.Append($"update WCSStorageLocat set Status = '{model[0].Status}',Flag = '{model[0].Flag}' where LocatNo in (");
                string str = "";
                foreach (var item in model)
                {
                    str += "'"+ item.LocatNo +"',";
                }
                str = str.Substring(0, str.Length-1);
                sqlString.Append($"{str});");
 
                int num = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
 
                if (num <= 0)
                {
                    return new WCSResultModel() { stateCode = "-1", errMsg = "失败" };
                }
                else if(num > 0)
                {
                    return new WCSResultModel() { stateCode = "0", errMsg = "成功" };
                }
            }
            catch (Exception ex)
            {
 
                return new WCSResultModel() { stateCode = "-1", errMsg = ex.Message };
            }
            return new WCSResultModel() { stateCode = "0" };
        }
 
        #endregion
 
        #region 调用WMS接口
 
        #endregion
    }
}