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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
using Common;
using DataBase;
using Model;
using Model.ApiModel;
using Model.WcsModel;
using Newtonsoft.Json;
using NLog;
using NPOI.SS.Formula;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.PTG;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlTypes;
using System.Reflection;
using System.Text;
using static ICSharpCode.SharpZipLib.Zip.ExtendedUnixData;
 
namespace BLL.DAL
{
    [Obsolete]
    public class DALWcsMessage
    {
        #region JC09
        /// <summary>
        /// 获取与PLC交互的所有IP地址
        /// </summary>
        /// <returns></returns>
        public DataTable GetPlcIps()
        {
            try
            {
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append($"select * from WCSIP where isDel = 0;");
                return DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
            }
            catch (Exception ex)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(ex.Message, "系统错误:");
            }
 
            return null;
        }
 
        /// <summary>
        /// 获取与设备交互信息
        /// </summary>
        /// <returns></returns>
        public DataTable GetPlcInfos()
        {
            try
            {
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append($"select tb1.*,tb2.IP from WCSPlcInfo as tb1 " +
                    $"left join WCSIP as tb2 on tb1.PlcIP = tb2.Id where tb1.isDel = 0; ");
 
                return DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
            }
            catch (Exception ex)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(ex.Message, "系统错误:");
            }
 
            return null;
        }
 
        /// <summary>
        /// 判断WCS是否自动模式 链接DB1
        /// </summary>
        /// <returns>true:自动模式 false:手动模式</returns>
        public bool GetIsWcsAutoDB1()
        {
            bool bl = false;
            try
            {
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append("select code from [dbo].[Dictionary] where TypeName = 'WCSAuto';");
                DataRow row = DataFactory.SqlDataBaseDB1().GetDataRowBySQL(sqlString);
                if (row != null)
                {
                    if (row["code"].ToString() == "0")
                    {
                        bl = true;
                    }
                }
 
                return bl;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
 
        /// <summary>
        /// 判断WCS是否自动模式 链接db2
        /// </summary>
        /// <returns>true:自动模式 false:手动模式</returns>
        public bool GetIsWcsAutoDB2()
        {
            bool bl = false;
            try
            {
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append("select code from [dbo].[Dictionary] where TypeName = 'WCSAuto';");
                DataRow row = DataFactory.SqlDataBaseDB2().GetDataRowBySQL(sqlString);
                if (row != null)
                {
                    if (row["code"].ToString() == "0")
                    {
                        bl = true;
                    }
                }
 
                return bl;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 获取当前工位偏移量信息
        /// </summary>
        /// <param name="plcInfoId">工位Id</param>
        /// <returns></returns>
        public DataTable GetPlcPos(string plcInfoId)
        {
            try
            {
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append($"select * from WCSPlcPos where isDel = 0 and PlcInfoId = '{plcInfoId}';");
 
                return DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
            }
            catch (Exception ex)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(ex.Message, "系统错误:");
            }
 
            return null;
        }
 
        /// <summary>
        /// 调用WMS接口获取储位地址
        /// </summary>
        /// <param name="palletNo">托盘号</param>
        /// <param name="startLocat">起始工位</param>
        /// <param name="endLocat">目标工位号(取货工位)</param>
        /// <param name="taskNo">任务号</param>
        /// <returns>返回wms反馈的信息</returns>
        public string GetLocations(string palletNo, string startLocat, ref string endLocat, ref string taskNo)
        {
            Logger logger = LogManager.GetCurrentClassLogger();
            try
            {
                string returnStr = "";
                StringBuilder sqlString = new StringBuilder();
                // 先判断此托盘的任务是否已生成任务
                sqlString.Append("select * from WCSTasks where Status in ('0','1') and Type = '0' ");
                sqlString.Append($"and PalletNo = '{palletNo}' and isdel = '0';");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                if (dt == null || dt.Rows.Count <= 0)
                {
                    LocatModel model = new LocatModel();
                    model.PalletNo = palletNo;
                    model.HouseNo = "W01";
                    model.RoadwayNo = "";
                    string json = JsonConvert.SerializeObject(model);
                    var response = Utility.Extra.HttpHelper.DoPost(DataFactory.GetWmsURL() + "/api/DownAPi/RequestLocation", json);
                    logger.Error(palletNo + "申请储位:" + response);
                    Tasks taskModels = JsonConvert.DeserializeObject<Tasks>(response);
                    if (taskModels.Success == "0")
                    {
                        // 永远只返回一条信息,因为是集合所以用循环插入写法;
                        DALWMSApi dal = new DALWMSApi();
                        var task = taskModels.TaskList;
                        task.Type = "0";                                // 任务类型 0:入库任务 1出库任务 2 移库任务
                        task.Origin = "WMS";
                        task.StartLocate = startLocat;                   // 起始位置
                        WCSResultModel result = dal.AddWcsTask(task);
                        taskNo = taskModels.TaskList.TaskNo; //任务号
                        if (result.stateCode == "1")
                        {
                            //修改储位信息 任务类型 执行状态 起始位置 目标位置
                            EditLocaetStatus("0", "0", "", task.EndLocate);
 
                            endLocat = task.EndRoadway;
                            returnStr = task.EndLocate;//"托盘号:" + palletNo + "\n" + "储位地址:" + task.EndLocate + "\n";
                        }
                        else
                        {
                            returnStr = "-1:" + result.errMsg;
                            return returnStr;
                        }
                    }
                    else
                    {
                        returnStr = "-1:" + taskModels.Message;
                        return returnStr;
                    }
                }
                else
                {
                    returnStr = dt.Rows[0]["EndLocat"].ToString();
                    endLocat = dt.Rows[0]["EndRoadway"].ToString();
                    taskNo = dt.Rows[0]["TaskNo"].ToString();
                }
 
                // 确定取货工位
                switch (endLocat)
                {
                    case "R01":
                        endLocat = "10";
                        break;
                    case "R02":
                        endLocat = "6";
                        break;
                }
 
                //returnStr = endLocat;
                return returnStr;
            }
            catch (Exception ex)
            {
                logger.Error("程序错误:" + ex.Message);
                throw ex;
            }
        }
 
        /// <summary>
        /// WCS自申请储位
        /// </summary>
        /// <param name="palletNo">托盘号</param>
        /// <param name="startLocat">起始工位</param>
        /// <param name="endLocat">目标工位号(取货工位)</param>
        /// <param name="taskNo">任务号</param>
        /// <returns>返回wms反馈的信息</returns>
        public string GetWcsLocations(string palletNo, string startLocat, ref string endLocat, ref string taskNo)
        {
            Logger logger = LogManager.GetCurrentClassLogger();
            try
            {
                string returnStr = "";
                StringBuilder sqlString = new StringBuilder();
                // 先判断此托盘的任务是否已生成任务
                // 验证任务是否已存在
                sqlString.Append($"select * from WCSTasks where IsDel = '0' and (Status = '0' or Status = '1') and PalletNo = '{palletNo}';");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                if (dt != null || dt.Rows.Count > 0)
                {
                    returnStr = "托盘" + palletNo + ";任务已存在!";
                    return returnStr;
                }
                if (dt == null || dt.Rows.Count <= 0)
                {
                    var response = GetLocateByRoadways(); //申请储位
                    logger.Error(palletNo + "申请储位:" + response);
                    // 永远只返回一条信息,因为是集合所以用循环插入写法;
                    DALWMSApi dal = new DALWMSApi();
                    WCSTasks task = new WCSTasks();
                    task.Type = "0";                                // 任务类型 0:入库任务 1出库任务 2 移库任务
                    task.Origin = "WCS";                            //来源
                    task.StartLocate = startLocat;                   // 起始位置
                    task.EndLocate = response.LocatNo;                   // 目标位置
                    task.EndRoadway = response.RoadwayNo;                   // 目标巷道
                    task.PalletNo = palletNo;                   // 托盘号
                    WCSResultModel result = dal.AddItsWcsTask(task);
                    if (result.stateCode == "1")
                    {
                        //修改储位信息 任务类型 执行状态 起始位置 目标位置
                        var IsUptLocate = EditLocaetStatus("0", "0", "", response.LocatNo);
                        if (IsUptLocate)
                        {
                            endLocat = response.RoadwayNo;
                            returnStr = response.LocatNo;
                        }
                        else
                        {
                            returnStr = "-1:" + "申请储位后任务储位修改失败";
                            return returnStr;
                        }
                    }
                    else
                    {
                        returnStr = "-1:" + result.errMsg;
                        return returnStr;
                    }
                }
                else
                {
                    returnStr = "-1:" + "申请储位失败";
                    return returnStr;
                }
 
                // 确定取货工位
                switch (endLocat)
                {
                    case "R01":
                        endLocat = "1";
                        break;
                    case "R02":
                        endLocat = "2";
                        break;
                    case "R03":
                        endLocat = "3";
                        break;
                    case "R04":
                        endLocat = "4";
                        break;
                    case "R05":
                        endLocat = "5";
                        break;
                    case "R06":
                        endLocat = "6";
                        break;
                    case "R07":
                        endLocat = "7";
                        break;
                }
 
                //returnStr = endLocat;
                return returnStr;
            }
            catch (Exception ex)
            {
                logger.Error("程序错误:" + ex.Message);
                throw ex;
            }
        }
 
        /// <summary>
        /// 插入任务明细表
        /// </summary>
        /// <param name="model">任务明细信息</param>
        public bool AddWCSTasksMonitor(WCSTasksMonitor model)
        {
            bool bl = false;
            StringBuilder sqlString = new StringBuilder();
            try
            {
                // 判断任务号是否位""
                if (model.TaskNo == "")
                {
                    // 根据托盘号获取对应的任务号
                    sqlString.Append($"select TaskNo from WCSTasks where Status = '1' and IsDel = '0' and PalletNo = '{model.PalletNo}';");
                    DataRow row = DataFactory.SqlDataBase().GetDataRowBySQL(sqlString);
                    if (row != null)
                    {
                        model.TaskNo = row["TaskNo"].ToString();
                    }
                }
 
                if (model.TaskNo == "")
                {
                    return bl;
                }
 
                // 插入任务明细表
                sqlString.Clear();
                sqlString.Append(@"INSERT INTO WCSTasksMonitor 
                 ( TaskNo , PlcId , PlcName , StartLocat , EndLocat , InteractiveMsg 
                , ErrorMsg,PalletNo,Status,IsDel ) VALUES (");
                sqlString.Append($"'{model.TaskNo}',{model.PlcId},'{model.PlcName}','{model.StartLocat}','{model.EndLocat}',");
                sqlString.Append($"'{model.InteractiveMsg}','{model.ErrorMsg}','{model.PalletNo}','{model.Status}','0');");
                int rowCount = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                if (rowCount > 0)
                {
                    bl = true;
                }
            }
            catch (Exception ex)
            {
                // 记录日志文件
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(ex.Message, "AddWCSTasksMonitor添加任务明细失败!");
 
                return bl;
            }
 
            return bl;
        }
 
        /// <summary>
        /// 更新任务状态
        /// </summary>
        /// <param name="TrayCode">托盘号</param>
        /// <param name="StateValue">任务状态  0: 等待执行 1: 正在执行 2: 执行完成 3: 异常结束 4: 任务取消</param>
        /// <returns>true:成功 flase:失败</returns>
        public bool SetWCSTasks(string palletNo, string StateValue, string EndLocatNo, string taskNo = "")
        {
            bool bl = false;
            try
            {
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append($"Update WCSTasks set FinishDate = '{DateTime.Now}', Status = '{StateValue}' ");
                //判断目标工位是否为空
                if (!string.IsNullOrEmpty(EndLocatNo))
                {
                    sqlString.Append($" ,EndLocat = '{EndLocatNo}'");
                }
                if (StateValue == "1")
                {
                    //任务状态为正在执行时修改为最高优先级
                    sqlString.Append($" ,Levels = '2'");
                }
                else if (StateValue == "2")
                {
                    //任务状态为执行完成时修改为正常优先级
                    sqlString.Append($" ,Levels = '2'");
                }
                sqlString.Append(" where Status not in ('3','2','4') ");
                if (!string.IsNullOrWhiteSpace(palletNo))
                {
                    sqlString.Append($" and PalletNo = '{palletNo}' ");
 
                }
                if (!string.IsNullOrWhiteSpace(taskNo))
                {
                    sqlString.Append($" and TaskNo = '{taskNo}' ");
                }
                else
                {
                    sqlString.Append(" ;");
                }
 
 
                int rowCount = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                if (rowCount > 0)
                {
                    bl = true;
                }
 
                return bl;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 获取任务信息
        /// </summary>
        /// <param name="status">0 等待执行 1 正在执行 2 执行完成 3 异常结束   4 任务取消</param>
        /// <param name="type">0 入库任务 1 出库任务  2 移库任务</param>
        /// <param name="palletNo">托盘号</param>
        /// <returns></returns>
        public DataTable GetWCSTasks(string status, string type, string palletNo = "", string startRoadway = "", string taskNo = "", string endRoadway = "")
        {
            try
            {
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append("select top 1 * from WCSTasks ");
                sqlString.Append($"where Status = '{status}' and IsDel = '0' ");
                if (taskNo != "")
                {
                    sqlString.Append($" and TaskNo = '{taskNo}' ");
                }
                if (palletNo != "")
                {
                    sqlString.Append($" and palletNo = '{palletNo}' ");
                }
                if (startRoadway != "")
                {
                    sqlString.Append($" and startRoadway = '{startRoadway}' ");
                }
                if (endRoadway != "")
                {
                    sqlString.Append($" and endRoadway = '{endRoadway}' ");
                }
                if (type != "")
                {
                    sqlString.Append($" and Type = '{type}' ");
                }
 
                sqlString.Append(" order by  Levels,Status,StartLocat,CreateTime asc; ");
                return DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
            }
            catch (Exception ex)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(ex.Message, "系统错误:");
            }
 
            return null;
        }
 
        /// <summary>
        /// 获取储位任务信息
        /// </summary>
        /// <param name="startlocat">起始货位</param>
        /// <returns></returns>
        public DataTable GetLocateTasks(string startlocat = "",string endlocat = "")
        {
            StringBuilder sqlString = new StringBuilder();
            sqlString.Append("select top 1 * from WCSTasks ");
            sqlString.Append($"where  IsDel = '0'");
            if (startlocat != "")
            {
                sqlString.Append($" and StartLocat = '{startlocat}' ");
            }
            if (endlocat != "")
            {
                sqlString.Append($" and EndLocat = '{endlocat}' ");
            }
            sqlString.Append(" order by  Levels,Status,StartLocat,CreateTime asc; ");
            return DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
        }
 
        /// <summary>
        /// 获取储位任务信息
        /// </summary>
        /// <param name="startlocat">起始货位</param>
        /// <returns></returns>
        public DataTable GetWCSDX(string skuno = "")
        {
            StringBuilder sqlString = new StringBuilder();
            sqlString.Append("select top 1 * from WCSMaterialRules where SkuNo = "+skuno);
            return DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
        }
 
        /// <summary>
        /// 调用WMS接口反馈任务接口
        /// </summary>
        /// <param name="model">任务完成状态</param>
        /// <returns></returns>
        public bool RequestTasks(TaskReques model)
        {
            bool bl = false;
            Logger logger = LogManager.GetCurrentClassLogger();
            try
            {
                StringBuilder sqlString = new StringBuilder();
                string json = JsonConvert.SerializeObject(model);
                var response = Utility.Extra.HttpHelper.DoPost(DataFactory.GetWmsURL() + "/api/DownAPi/ReceiveWcsSignal", json);
                logger.Error(model.taskNo + "任务反馈:" + response);
 
                //var response1 = JsonConvert.DeserializeObject(response);
                ResponseTasks taskModels = JsonConvert.DeserializeObject<ResponseTasks>(response);
                if (taskModels.StatusCode == "0")
                {
 
                    sqlString.Append($"Update WCSTasks set IsSuccess = '0' where TaskNo = '{model.taskNo}';");
                    DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                    bl = true;
                }
                else
                {
                    sqlString.Append($"Update WCSTasks set IsSuccess = '1',Information='{taskModels.Message}' where TaskNo = '{model.taskNo}';");
                    DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                    bl = false;
                }
            }
            catch (Exception ex)
            {
                logger.Error("程序错误:" + ex.Message);
            }
 
            return bl;
        }
 
        /// <summary>
        /// 调用WMS接口反馈任务满入异常接口
        /// </summary>
        /// <param name="model">任务信息</param>
        /// <returns></returns>
        public string RequestFullException(TaskReques model, string startLocat, ref string taskNo)
        {
            string returnStr = "";
            taskNo = ""; //任务号
            Logger logger = LogManager.GetCurrentClassLogger();
            try
            {
                StringBuilder sqlString = new StringBuilder();
                string json = JsonConvert.SerializeObject(model);
                var response = Utility.Extra.HttpHelper.DoPost(DataFactory.GetWmsURL() + "/api/DownAPi/FullException", json);
                logger.Error(model.taskNo + "任务反馈:" + response);
 
                //var response1 = JsonConvert.DeserializeObject(response);
                Tasks taskModels = JsonConvert.DeserializeObject<Tasks>(response);
                if (taskModels.Success == "0")
                {
                    // 永远只返回一条信息,因为是集合所以用循环插入写法;
                    DALWMSApi dal = new DALWMSApi();
                    var task = taskModels.TaskList;
                    task.Type = "0";                                // 任务类型 0:入库任务 1出库任务 2 移库任务
                    task.Origin = "WMS";
                    task.StartLocate = startLocat;                   // 起始位置
                    WCSResultModel result = dal.AddWcsTask(task);
 
                    if (result.stateCode == "1")
                    {
                        taskNo = taskModels.TaskList.TaskNo; //任务号
                        returnStr = task.EndLocate;
                    }
                    else
                    {
                        returnStr = "-1:" + result.errMsg;
                    }
                    sqlString.Append($"Update WCSTasks set IsSuccess = '0',  where TaskNo = '{model.taskNo}';");
                    DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                }
                else
                {
                    returnStr = "-1:" + taskModels.Message;
                    sqlString.Append($"Update WCSTasks set IsSuccess = '1', where TaskNo = '{model.taskNo}';");
                    DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                }
            }
            catch (Exception ex)
            {
                returnStr = "-1程序错误:" + ex.Message;
                logger.Error(returnStr);
            }
 
            return returnStr;
        }
 
        /// <summary>
        /// 调用WMS接口反馈空取异常接口
        /// </summary>
        /// <param name="model">任务信息</param>
        /// <returns></returns>
        public bool RequestEmptyException(TaskReques model)
        {
            bool bl = false;
            Logger logger = LogManager.GetCurrentClassLogger();
            try
            {
                StringBuilder sqlString = new StringBuilder();
                string json = JsonConvert.SerializeObject(model);
                var response = Utility.Extra.HttpHelper.DoPost(DataFactory.GetWmsURL() + "/api/DownAPi/EmptyException", json);
                logger.Error(model.taskNo + "任务反馈:" + response);
 
                //var response1 = JsonConvert.DeserializeObject(response);
                ResponseTasks taskModels = JsonConvert.DeserializeObject<ResponseTasks>(response);
                if (taskModels.Success == "0")
                {
 
                    sqlString.Append($"Update WCSTasks set IsSuccess = '0' where TaskNo = '{model.taskNo}';");
                    DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                    bl = true;
                }
                else
                {
                    sqlString.Append($"Update WCSTasks set IsSuccess = '1',Information='{taskModels.Message}' where TaskNo = '{model.taskNo}';");
                    DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                    bl = false;
                }
            }
            catch (Exception ex)
            {
                logger.Error("-1程序错误:" + ex.Message);
            }
 
            return bl;
        }
 
        /// <summary>
        /// 向赋码系统获取箱码信息
        /// </summary>
        /// <param name="boxCode"></param>
        /// <returns></returns>
        public WcsBoxInfo GetBoxInfo(string boxCode)
        {
            try
            {
                //获取是否存在当前箱码信息
                StringBuilder sqlString = new StringBuilder();
                // 先判断此托盘的任务是否已生成任务
                sqlString.Append($"select * from WcsBoxInfo where IsDel = '0' and BoxNo = '{boxCode}' ");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
 
                if (dt == null || dt.Rows.Count == 0)
                {
                    //调用赋码系统
                    var response = Utility.Extra.HttpHelper.DoPost(DataFactory.GetWmsURL() + "/api/DownAPi/RequestLocation", boxCode);
                    WcsBoxInfo boxInfo = JsonConvert.DeserializeObject<WcsBoxInfo>(response);
 
                    //添加箱码信息
                    sqlString.Clear();
                    sqlString.Append("insert into WcsBoxInfo (OrderCode,Line_No,LineDao,PORT,BoxNo,BoxNo2,BoxNo3,PalletNo,Qty,FullQty,Aflag,Status,SkuNo,SkuName,LotNo,LotText,Custom,CustomName,ProductionTime,ExpirationTime,CompleteTime,InspectMark,BitBoxMark,Standard,PackageStandard,StoreTime,QtyCount,QtyOrd,Opuser,IsDel,CreateTime,CreateUser,UpdateTime,UpdateUser)");
                    sqlString.Append($"Values ('{boxInfo.OrderCode}','{boxInfo.Line_No}','{boxInfo.LineDao}','{boxInfo.PORT}','{boxInfo.BoxNo}','{boxInfo.BoxNo2}','{boxInfo.BoxNo3}','','{boxInfo.Qty}','{boxInfo.FullQty}','{boxInfo.Aflag}','{boxInfo.Status}','{boxInfo.SkuNo}','{boxInfo.SkuName}','{boxInfo.LotNo}','{boxInfo.LotText}','{boxInfo.Custom}','{boxInfo.CustomName}','{boxInfo.ProductionTime}','{boxInfo.ExpirationTime}','{boxInfo.CompleteTime}','{boxInfo.InspectMark}','{boxInfo.BitBoxMark}','{boxInfo.Standard}','{boxInfo.PackageStandard}','{boxInfo.StoreTime}','{boxInfo.QtyCount}','{boxInfo.QtyOrd}','{boxInfo.Opuser}','0',getdate(),null,null,null)");
                    int isAdd = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                    if (isAdd == 1)
                    {
                        return boxInfo;
                    }
                    else
                    {
                        return null;
                    }
 
 
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
 
                throw ex;
            }
        }
 
        /// <summary>
        /// 变更储位(需要的值 任务类型 状态 (入库与PLC:目标位置、出库:起始位置、移库两个都需要)
        /// </summary>
        /// <param name="type">任务类型 0:入库 1:出库 2:移库 3:PLC申请</param>
        /// <param name="status">执行状态 0 等待执行 1 正在执行 2 执行完成 3 异常结束 4 任务取消</param>
        /// <param name="startLocat">起始位置</param>
        /// <param name="endLocat">目标位置</param>
        /// <returns></returns>
        public bool EditLocaetStatus(string type, string status, string startLocat, string endLocat)
        {
            try
            {
                bool isTrue = false;
                int upt = 0;
                StringBuilder sqlString = new StringBuilder();
                #region 赋值状态
 
                string start = ""; //起始储位状态
                string end = ""; //目标储位状态
                string qita = ""; //用于WMS
                //修改的状态 0:空储位 1:有物品 2:入库中 3:出库中 4:移入中 5:移除中
                //任务类型 0入 1出 2移 3 PLC申请
                switch (type)
                {
                    case "0"://入库
                    case "3"://PLC入库
                        //任务状态
                        switch (status)
                        {
                            case "0": //等待执行
                            case "1": //正在执行
                                end = "2"; //目标储位状态 //入库中
                                break;
                            case "2": //执行完成
                                end = "1"; //目标储位状态 //有物品
                                break;
                            case "3": //异常结束
                                //不变
                                break;
                            case "4": //取消
                                end = "0"; //目标储位状态 //空储位
                                break;
                            default: //其它
                                break;
                        }
 
                        break;
                    case "1": //出库
                        //任务状态
                        switch (status)
                        {
                            case "0": //等待执行
                            case "1": //正在执行
                                start = "3"; //起始储位状态 出库中
                                break;
                            case "2": //执行完成
                                start = "0"; //起始储位状态 空储位
                                break;
                            case "3": //异常结束
                                //不变
                                break;
                            case "4": //取消
                                start = "1"; //起始储位状态 有物品
                                break;
                            default: //其它
                                break;
                        }
 
                        break;
                    case "2": //移库
                        //任务状态
                        switch (status)
                        {
                            case "0": //等待执行
                            case "1": //正在执行
                                end = "4"; //目标储位状态 移入中
                                start = "5"; //起始储位状态 移出中
                                break;
                            case "2": //执行完成
                                end = "1"; //目标储位状态 有物品
                                start = "0"; //起始储位状态 空储位
                                break;
                            case "3": //异常结束
                                //不变
                                break;
                            case "4": //取消
                                end = "0"; //目标储位状态 空储位
                                start = "1"; //起始储位状态 有物品
                                break;
                            default: //其它
                                break;
                        }
 
                        break;
                    default:
 
                        break;
                }
 
                #endregion
                //验证起始状态或目标状态不为空
                if (!string.IsNullOrEmpty(end))
                {
                    sqlString.Append($"update WCSStorageLocat set Status = '{end}' where LocatNo = '{endLocat}';");
                }
                if (!string.IsNullOrEmpty(start))
                {
                    sqlString.Append($"update WCSStorageLocat set Status = '{start}' where LocatNo = '{startLocat}';");
                }
                if (!string.IsNullOrEmpty(end) || !string.IsNullOrEmpty(start))
                {
                    upt = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                }
 
                if (upt >= 1)
                {
                    isTrue = true;
                }
                return isTrue;
            }
            catch (Exception ex)
            {
 
                throw ex;
            }
        }
        #endregion
 
        #region 申请储位
 
        //申请储位(包含组托的信息)
        public WCSStorageLocat RequestLocation()
        {
            try
            {
                #region
 
                try
                {
                    WCSStorageLocat locate = new WCSStorageLocat();
                    locate = GetLocateByRoadways();
 
                    return locate;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                #endregion
 
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
 
        /// <summary>
        /// 申请储位(包含组托的信息)
        /// <returns></returns>
        private WCSStorageLocat GetLocateByRoadways()
        {
            try
            {
                #region 入库分配规则
                StringBuilder sqlString = new StringBuilder();
                WCSStorageLocat locate = new WCSStorageLocat();
                //string txt = !string.IsNullOrEmpty(roadway) ? $" and RoadwayNo = '{roadway}'" : "";
                sqlString.Append("select RoadwayNo from WCSStorageLocat where IsDel = '0' and WareHouseNo = 'W01' group by RoadwayNo order by RoadwayNo");
 
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
 
                if (dt == null || dt.Rows.Count == 0)
                {
                    return null;
                }
                else
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        locate = GetLocateByRoadway(dt.Rows[i]["RoadwayNo"].ToString());
                        if (locate != null)
                        {
                            break;
                        }
                    }
                }
 
                #endregion
 
                return locate;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
 
        /// <summary>
        /// 取当前巷最优位置
        /// </summary>
        /// <param name="roadwayNo">巷道号</param>
        /// <returns></returns>
        private WCSStorageLocat GetLocateByRoadway(string roadwayNo)
        {
            var str = "''";
            StringBuilder sqlString = new StringBuilder();
            //查询该巷道并且标志为正常的的储位
            do
            {
                sqlString.Clear();
                //var sql = $"select * from WCSStorageLocat where IsDel = 0 and Flag = 0 and [Status] = 0 and RoadwayNo = '{roadwayNo}' and LocatNo not in({str}) ";
                //sql += "order by ";
                //sql += "Row , Depth desc, ";
                sqlString.Append($"select * from WCSStorageLocat where IsDel = 0 and Flag = 0 and [Status] = 0 and RoadwayNo = '{roadwayNo}' and LocatNo not in({str}) order by Row , Depth desc");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                List<WCSStorageLocat> list = (List<WCSStorageLocat>)DataTableHelper.DataTableToIList<WCSStorageLocat>(dt);
                if (dt != null || dt.Rows.Count >= 1)
                {
                    foreach (var item in list)
                    {
                        var isOk = LocateIsOk(item);
                        if (isOk)
                        {
                            return item;
                        }
                        else
                        {
                            if (str.Length > 0)
                            {
                                str += ",";
                            }
                            str += $"'{item.LocatNo}'";
                        }
                    }
                }
                else
                {
                    return null;
                }
 
            } while (true);
        }
 
 
        public bool LocateIsOk(WCSStorageLocat model)
        {
 
            if (model.Depth == "01")
            {
                return true;
            }
            else
            {
                //获取深度为1的储位信息
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append($"select top 1 * from WCSStorageLocat where IsDel = '0' and [Row] = {model.Row} and [Column] = {model.Column} and Layer = {model.Layer} and Depth = '01' ");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                //var locate = db.Queryable<WCSStorageLocat>().First(m => m.IsDel == "0" && m.LocateGroup == model.LocateGroup && m.Depth == "01");
                if (dt == null || dt.Rows.Count == 0)
                {
                    return false;
                }
                else
                {
                    //前面储位状态为空且不能是损坏状态的
                    if (dt.Rows[0]["Status"].ToString() == "0" && dt.Rows[0]["Flag"].ToString() != "2")
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
        }
 
        #endregion
 
 
 
        #region 标准版数据交互
 
 
 
        /// <summary>
        /// 根据托盘号获取组盘信息
        /// </summary>
        /// <param name="palletNo"></param>
        /// <returns></returns>
        public DataRow GetWcsPalletBind(string palletNo)
        {
            try
            {
                //select Top 1 * from WCSPalletBind where PalletNo = 'T2300017'
                StringBuilder sqlString = new StringBuilder();
                sqlString.Clear();
                sqlString.Append("select Top 1 * from WCSPalletBind ");
                sqlString.Append($" where palletNo = '{palletNo}' ");
                sqlString.Append(" order by  CreateTime desc ");
                DataRow aa = DataFactory.SqlDataBase().GetDataRowBySQL(sqlString);
                return aa;
            }
            catch (Exception ex)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(ex.Message, "系统错误:");
            }
            return null;
        }
 
        /// <summary>
        /// 获取空托盘任务信息
        /// </summary>
        /// <param name="status">0 等待执行 1 正在执行 2 执行完成 3 异常结束   4 任务取消</param>
        /// <param name="type">0 入库任务 1 出库任务  2 移库任务</param>
        /// <param name="lotNo">批次号</param>
        /// <returns></returns>
        public DataTable GetWCSSupallTasks(string status, string type, string lotNo = "")
        {
            bool bl = false;
            try
            {
                //获取空托盘入库任务
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append("select top 1 * from WCSTasks ");
                sqlString.Append($"where Status = '{status}' and IsDel = '0' ");
                if (lotNo != "")
                {
                    sqlString.Append($" and LotNo = '{lotNo}' ");
                }
                if (type != "")
                {
                    sqlString.Append($" and Type = '{type}' ");
                }
 
                sqlString.Append(" and StartRoadway != '' order by  Levels desc,CreateTime asc; ");
                var taskList = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                //获取数据后清空sqlString
                sqlString.Clear();
                //修改空托盘入库任务改为出库任务
                sqlString.Append($"Update WCSTasks set Type);");
                int rowCount = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                if (rowCount > 0)
                {
                    bl = true;
                    return taskList;
                }
                return null;
 
            }
            catch (Exception ex)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(ex.Message, "系统错误:");
            }
 
            return null;
        }
 
        /// <summary>
        /// 获取指定入口货物信息
        /// </summary>
        /// <param name="conveyor">入库口</param>
        /// <returns></returns>
        public DataTable GetWCSConveyorInfo(string conveyor = "")
        {
            try
            {
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append("select * from WCSConveyorInfo ");
                sqlString.Append("where Status = '1' and IsDel = '0' and isEndLot = '0' ");
                if (!string.IsNullOrWhiteSpace(conveyor))
                {
                    sqlString.Append($" and Conveyor = '{conveyor}';");
                }
 
                return DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
            }
            catch (Exception ex)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(ex.Message, "系统错误:");
            }
 
            return null;
        }
 
        /// <summary>
        /// 存储托盘组托信息
        /// </summary>
        /// <param name="model">组托信息</param>
        /// <returns>true:成功  false:失败</returns>
        public bool AddWCSPalletBind(WCSPalletBind model)
        {
            bool bl = false;
            try
            {
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append(@"INSERT INTO WCSPalletBind 
                 ( LocatNo , PalletNo , SkuQty , SkuWeight , Status , ErrorMsg 
                , TaskType , SkuType , SubPallet , LotNo  , LotText , SupplierLot , IsBale ,
                 IsBelt  ) VALUES (");
                sqlString.Append($"'{model.LocatNo}','{model.PalletNo}','{model.SkuQty}','{model.SkuWeight}','{model.Status}',");
                sqlString.Append($"'{model.ErrorMsg}','{model.TaskType}','{model.SkuType}','{model.SubPallet}','{model.LotNo}',");
                sqlString.Append($"'{model.LotText}','{model.SupplierLot}','{model.IsBale}','{model.IsBelt}');");
                int rowCount = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                if (rowCount > 0)
                {
                    bl = true;
                }
            }
            catch (Exception ex)
            {
                // 记录日志文件
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(ex.Message, "SetWCSPalletBind存储组盘信息失败");
 
                return bl;
 
            }
 
            return bl;
        }
 
        /// <summary>
        /// 调用WMS接口获取储位地址
        /// </summary>
        /// <param name="PalletNo">托盘号</param>
        /// <param name="model">组盘信息</param>
        /// <param name="endLocat">目标工位号(取货工位)</param>
        /// <returns>返回wms反馈的信息</returns>
        public string GetLocation(string palletNo, WCSPalletBind model, ref string endLocat)
        {
            try
            {
                string returnStr = "";
                StringBuilder sqlString = new StringBuilder();
                // 先判断此托盘的任务是否已生成任务
                sqlString.Append("select * from WCSTasks where Status in ('0','1') and Type = '0' ");
                sqlString.Append($"and PalletNo = '{palletNo}' and isdel = '0';");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                if (dt == null || dt.Rows.Count <= 0)
                {
                    string json = JsonConvert.SerializeObject(model);
                    var response = Utility.Extra.HttpHelper.DoPost("http://192.168.220.130:8081/api/DownAPi/RequestLocation", json);
                    ResponseTasks taskModels = JsonConvert.DeserializeObject<ResponseTasks>(response);
                    //Logger logger = LogManager.GetCurrentClassLogger();
                    //logger.Error("申请储位原因:", response);
                    if (taskModels.Success == "0")
                    {
                        // 永远只返回一条信息,因为是集合所以用循环插入写法;
                        DALWMSApi dal = new DALWMSApi();
                        WCSTasks task = taskModels.TaskList;
 
                        // 添加任务信息
                        task.StartLocate = model.StationNum;
                        task.LotNo = model.LotNo;
                        task.SupplierLot = model.SupplierLot;
                        task.PalletType = model.SubPallet == "0" ? "0" : "1";
                        WCSResultModel result = dal.AddWcsTask(task);
                        if (result.stateCode == "1")
                        {
                            endLocat = task.EndRoadway;
                            returnStr = "托盘号:" + palletNo + "\n" + "储位地址:" + task.EndLocate + "\n";
                            // 插入组托信息
                            this.AddWCSPalletBind(model);
 
                            // 插入任务明细表
                            WCSTasksMonitor tasksMonitor = new WCSTasksMonitor();
                            tasksMonitor.TaskNo = task.TaskNo;
                            tasksMonitor.PlcId = int.Parse(model.PlcId);
                            tasksMonitor.PlcName = model.StationNum;
                            tasksMonitor.StartLocat = model.StationNum;
                            tasksMonitor.InteractiveMsg = "向WMS申请储位信息成功";
                            tasksMonitor.PalletNo = palletNo;
                            tasksMonitor.EndLocat = task.EndLocate;
                            tasksMonitor.Status = "2";              // 执行完成
                            this.AddWCSTasksMonitor(tasksMonitor);
                        }
                        else
                        {
                            returnStr = "-1:" + result.errMsg;
                            return returnStr;
                        }
 
                    }
                    else
                    {
                        returnStr = "-1:" + taskModels.Message;
                        return returnStr;
                    }
                }
                else
                {
                    endLocat = dt.Rows[0]["EndRoadway"].ToString();
                }
 
                // 确定取货工位
                switch (endLocat)
                {
                    case "R11":
                        endLocat = "2";
                        break;
                    case "R12":
                        endLocat = "6";
                        break;
                    case "R13":
                        endLocat = "10";
                        break;
                }
 
                // 记录日志文件
                returnStr = endLocat;
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(returnStr, "申请储位");
 
                return returnStr;
            }
            catch (Exception ex)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(ex.Message, "程序异常:申请储位失败!");
                throw ex;
            }
        }
 
        /// <summary>
        /// 调用WMS接口申请空托盘垛
        /// </summary>
        /// <param name="skuNo">物料号</param>
        /// <param name="endLocat">送货工位号</param>
        /// <returns></returns>
        public string GetSupperPalletLocation(string skuNo = "", string endLocat = "")
        {
            try
            {
                return "";
                //string returnStr = "";
                //StringBuilder sqlString = new StringBuilder();
                //sqlString.Clear();
                //string json = JsonConvert.SerializeObject(skuNo);
                //var response = Utility.Extra.HttpHelper.DoPost("http://192.168.220.130:8081/api/DownAPi/PalletLocation", json);
                ////var response = Utility.Extra.HttpHelper.DoPost("http://localhost:13243/api/DownAPi/PalletLocation", json);
                //var taskModels = JsonConvert.DeserializeObject<Tasks>(response);
 
 
                //if (taskModels.Success == "0")
                //{
                //    if (taskModels.Message == "任务已申请!")
                //    {
                //        return null;
                //    }
                //    // 永远只返回一条信息,因为是集合所以用循环插入写法;
                //    DALWMSApi dal = new DALWMSApi();
                //    foreach (var item in taskModels.TaskList)
                //    {
                //        WCSTasks task = item;
                //        //根据托盘号获取
 
                //        // 添加任务信息
                //        task.EndLocat = item.EndLocat != "" ? item.EndLocat : skuNo == "100099" ? "41" : skuNo == "100098" ? "23" : "33";
                //        task.LotNo = "";
                //        task.SupplierLot = "";
                //        task.PalletType = "";
                //        WCSResultModel result = dal.AddWcsTask(task);
                //        if (result.stateCode == "1")
                //        {
                //            endLocat = task.EndRoadway;
                //            returnStr = "托盘号:" + task.PalletNo + "\n" + "储位地址:" + task.StartLocat + "\n";
 
                //            // 插入任务明细表
                //            WCSTasksMonitor tasksMonitor = new WCSTasksMonitor();
                //            tasksMonitor.TaskNo = task.TaskNo;
                //            tasksMonitor.PlcId = 0;
                //            tasksMonitor.PlcName = "";
                //            tasksMonitor.StartLocat = task.StartLocat;
                //            tasksMonitor.InteractiveMsg = "向WMS申请空托盘信息成功";
                //            tasksMonitor.PalletNo = task.PalletNo;
                //            tasksMonitor.EndLocat = task.EndLocat;
                //            tasksMonitor.Status = "2";              // 执行完成
                //            this.AddWCSTasksMonitor(tasksMonitor);
                //        }
                //        else
                //        {
                //            returnStr = "-1:" + result.errMsg;
                //            return returnStr;
                //        }
 
                //        // 确定取货工位
                //        switch (task.StartRoadway)
                //        {
                //            case "R11":
                //                endLocat = "3";
                //                break;
                //            case "R12":
                //                endLocat = "4";
                //                break;
                //            case "R13":
                //                endLocat = "11";
                //                break;
                //        }
 
                //        // 记录日志文件
                //        returnStr += "目标位置:" + endLocat + "\n";
                //        Logger logger = LogManager.GetCurrentClassLogger();
                //        logger.Error(returnStr, "申请空托盘");
 
 
                //    }
 
                //    return returnStr;
 
 
                //}
                //else
                //{
                //    returnStr = "-1:" + taskModels.Message;
                //    return returnStr;
                //}
 
            }
            catch (Exception ex)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(ex.Message, "程序异常:申请空托盘失败!");
                throw ex;
            }
        }
 
        /// <summary>
        /// 获取报警基础信息
        /// </summary>
        /// <returns>报警信息基础表</returns>
        public DataTable GetWcsAlarmInfo()
        {
            try
            {
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append("select * from WCSAlarmInfo order by PlcIP;");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
 
 
 
 
 
        #endregion
 
        #region 07版本,标准版弄好后删除
 
 
        /// <summary>
        /// 获取未完成的任务自动
        /// </summary>
        /// <param name="state">任务状态0:未下发 1:已下发 3:已完成</param>
        /// <returns>任务信息</returns>
        public DataTable GetWmsTasks(string state, string taskType, string Palno = "")
        {
            try
            {
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append("select top 1 * from TaskMonitor ");
                sqlString.Append("where State = '" + state + "' and Source = 'WMS' and IsDel = '0' ");
                if (Palno != "")
                {
                    sqlString.Append(" and Palno = '" + Palno + "' ");
                }
                sqlString.Append(" and taskType = '" + taskType + "' ");
                sqlString.Append(" order by  PriorityLevel desc,CreateTime asc; ");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                if (dt == null || dt.Rows.Count == 0)
                {
                    return null;
                }
 
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 根据出入库口获取正在执行的出入库任务
        /// </summary>
        /// <param name="InitialAddre">通道口</param>
        /// <param name="taskType">in:入库  out:出库</param>
        /// <returns>true:不存在任务  false:存在任务</returns>
        public bool GetTasks(string InitialAddre, string taskType)
        {
            bool bl = false;
            try
            {
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append("select * from TaskMonitor ");
                sqlString.Append("where State = '1' and Source = 'WMS' and IsDel = '0' ");
                sqlString.Append("and taskType = '" + taskType + "' and InitialAddre = '" + InitialAddre + "' ");
                sqlString.Append("order by  PriorityLevel desc,CreateTime asc; ");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                if (dt == null || dt.Rows.Count == 0)
                {
                    bl = true;
                }
 
                return bl;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 创建任务
        /// </summary>
        /// <param name="taskModel">任务表实体类</param>
        public int SetTaskMonitor(TaskMonitorDto taskModel)
        {
            try
            {
                int isSucceed = 0;
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append(@"INSERT INTO TaskMonitor(TaskNo,TaskType,InitialAddre
, Palno, TargetAddre, State, IsSucceed, ErrorStr, PriorityLevel, Source
, Demo, CreateTime, IsDel) values ('");
                sqlString.Append(taskModel.TaskNo + "','" + taskModel.TaskType + "','" + taskModel.InitialAddre + "','");
                sqlString.Append(taskModel.Palno + "','" + taskModel.TargetAddre + "',0,'0','0','0','WMS','',GETDATE(),'0')");
                int rowCount = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                if (rowCount > 0)
                {
                    return isSucceed;
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 更新任务状态
        /// </summary>
        /// <param name="TrayCode">托盘号</param>
        /// <param name="StateValue">任务状态</param>
        /// <returns>true:成功 flase:失败</returns>
        public bool SetWmsTasks(string TrayCode, string StateValue)
        {
            bool bl = false;
            try
            {
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append("Update TaskMonitor set State = '" + StateValue + "' where Palno = '" + TrayCode + "' and State != '3';");
                int rowCount = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                if (rowCount > 0)
                {
                    bl = true;
                }
 
                return bl;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 获取报警基础信息
        /// </summary>
        /// <returns>报警信息基础表</returns>
        public DataTable GetErrorInfor()
        {
            try
            {
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append("select * from [CS_AlarmInfo] order by M;");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 向报警表写入错误信息
        /// </summary>
        public void SetErrorMessage(string errorType, string errorCode, string messageStr)
        {
            try
            {
                // State: 0=未处理  1=已处理
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append("insert into CS_Alarm (Name,ErrorCode,AlarmName,State) ");
                sqlString.Append("VALUES ('" + errorType + "','" + errorCode + "','" + messageStr + "','0');");
                DataFactory.SqlDataBase().ExecuteBySql(sqlString);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 判断当前报警信息是否已存在
        /// </summary>
        /// <param name="errorCode">MB点位</param>
        /// <returns>false:不存在  true:已存在</returns>
        public bool GetErrorMessage(string errorCode)
        {
            bool bl = false;
            try
            {
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append("select count(*) from CS_Alarm where errorCode = '" + errorCode + "';");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                if (dt.Rows[0][0].ToString() != "0")
                {
                    bl = true;
                }
 
                return bl;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 删除跺机和运输线所有报警信息
        /// </summary>
        public void DelErrorMessage()
        {
            try
            {
                // State: 0=未处理  1=已处理
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append("delete from CS_Alarm;");
                DataFactory.SqlDataBase().ExecuteBySql(sqlString);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 通知wms任务完成
        /// </summary>
        /// <param name="palNo">托盘号</param>
        /// <param name="locationCode">储位地址</param>
        /// <param name="taskType">任务类型 1 入库任务 2:出库任务</param>
        public void WcsinWms(string palNo, string locationCode, string taskType)
        {
            try
            {
                string returnStr = "";
                DALWMSApi api = new DALWMSApi();
                var LocationModel = new ApiLocationModel();
                if (taskType == "1")
                {
                    // 入库完成
                    LocationModel = api.PutStorage(palNo, locationCode);
                }
                else
                {
                    // 出库完成
                    LocationModel = api.OutStorage(palNo, locationCode);
                }
 
                if (LocationModel.Code == "01")
                {
                    returnStr = "托盘号:'" + palNo + "'任务完成";
                }
                else
                {
                    this.SetErrorMessage(LocationModel.OutMode, LocationModel.Code, palNo + "任务失败!");
                    returnStr = "托盘号:'" + palNo + "'任务失败";
                    //switch (LocationModel.Code)
                    //{
                    //    case "-11": returnStr = palNo + ":-11参数错误!"; break;
                    //    case "-101": returnStr = palNo + ":-101无组盘信息!"; break;
                    //    case "-102": returnStr = palNo + ":-102非仓库托盘"; break;
                    //    default: break;
                    //}
                }
 
 
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 调用WMS接口获取储位地址
        /// </summary>
        /// <param name="Palno">托盘号</param>
        /// <returns>返回wms反馈的信息</returns>
        public string GetLocation(string palNo, string height, string inPort)
        {
            try
            {
                string returnStr = "";
                // 向WMS申请储位
                LocationInfo location = new LocationInfo();
                location.palNo = palNo;
                location.height = int.Parse(height);
                string json = JsonConvert.SerializeObject(location);
                DALWMSApi api = new DALWMSApi();
                var LocationModel = api.GetLocation(palNo, int.Parse(height));
                // Liudl 2022-12-31 Edit 接口调用改为程序内部调用
                //var response = Utility.Extra.HttpHelper.DoPost("192.168.1.35:57061/api/WMSApi/getLocation", json);
                //ApiLocationModel LocationModel = JsonConvert.DeserializeObject<ApiLocationModel>(response);
                // 判断储位是否申请成功   01:成功  -11:参数错误 -101:没有组盘信息 -102:没有此托盘
                if (LocationModel.Code == "01")
                {
                    // 生成入库任务,插入任务表
                    TaskMonitorDto taskModel = new TaskMonitorDto();
                    taskModel.TaskNo = "in";
                    taskModel.TaskType = "in";
                    taskModel.InitialAddre = inPort;
                    taskModel.Palno = palNo;
                    taskModel.TargetAddre = LocationModel.LocationCode;
                    taskModel.State = "0";
                    taskModel.IsSucceed = LocationModel.Code;
                    taskModel.ErrorStr = LocationModel.OutMode;
                    taskModel.PriorityLevel = 0;
                    taskModel.Source = "WMS";
                    taskModel.IsDel = 0;
 
                    this.SetTaskMonitor(taskModel);
 
                    returnStr = "托盘号:'" + palNo + "'申请储位成功,储位地址为:'" + LocationModel.LocationCode + "'";
                }
                else
                {
                    // 向led屏幕插入信息 Liudl 未完成
                    // 插入报警信息
                    this.SetErrorMessage(LocationModel.OutMode, LocationModel.Code, palNo + "申请储位地址失败!");
                    switch (LocationModel.Code)
                    {
                        case "-11": returnStr = palNo + ":-S11参数错误!"; break;
                        case "-101": returnStr = palNo + ":-S101无组盘信息!"; break;
                        case "-102": returnStr = palNo + ":-S102非仓库托盘"; break;
                        default: break;
                    }
                }
 
                // 记录日志文件
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(returnStr, "申请储位");
 
                return returnStr;
            }
            catch (Exception ex)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(ex.Message, "程序异常:申请储位失败!");
                throw ex;
            }
        }
 
        /// <summary>
        /// 判断此托盘是否已分配任务
        /// </summary>
        /// <param name="palNo">托盘号</param>
        /// <returns></returns>
        public string IsTaskMonitor(string palNo)
        {
            string Location = "";
            try
            {
                StringBuilder strSQL = new StringBuilder();
                strSQL.Append($"select TargetAddre from TaskMonitor where Palno ='{palNo}' and TaskType = 'in' and IsDel = '0' and State <> '3';");
                DataTable dtI = DataFactory.SqlDataBase().GetDataTableBySQL(strSQL);
                if (dtI != null && dtI.Rows.Count > 0)
                {
                    Location = "托盘号:'" + palNo + "'申请储位成功,储位地址为:'" + dtI.Rows[0]["TargetAddre"] + "'";
                }
 
                return Location;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
 
 
        #region 分拣方法
        /// <summary>
        /// 查询任务是否绑定并获取分道
        /// </summary>
        /// <param name="barcode">条码信息</param>
        /// <returns></returns>
        public string GetBarcodeAndRoute(string barcode)
        {
            StringBuilder sqlString = new StringBuilder();
            try
            {
                sqlString.Append($"select * from WCSBoxInfo where BoxNo = '{barcode}' ;");
                DataRow row = DataFactory.SqlDataBase().GetDataRowBySQL(sqlString);
                //已获取箱支关系
                if (row != null)
                {
                    sqlString.Clear();
                    DataTable dt2 = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                    var SkuNo = dt2.Rows[0]["SkuNo"].ToString();
                    var LotNo = dt2.Rows[0]["LotNo"].ToString();
                    var SkuName = dt2.Rows[0]["SkuName"].ToString();
                    var EndLotFlag = dt2.Rows[0]["EndLotFlag"].ToString(); //结批标识0:未结批,1:已结批
                    //更改分拣任务状态为预结批
                    if (EndLotFlag == "1")
                    {
                        sqlString.Clear();
                        sqlString.Append($"update WCSPickLinoBind set IDState = '2' where SkuNo = '{SkuNo}' and LotNo = '{LotNo}';");
                        int count = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                        if (count == 0)
                        {
                            return "4";
                        }
                    }
 
                    sqlString.Append($"select * from WCSPickLinoBind where SkuNo = '{SkuNo}' and LotNo = '{LotNo}' and IDState = '1' ;");
                    int rowCount = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                    //箱码已绑定
                    if (rowCount >= 1)
                    {
                        //下发分道信息(预留:在同一种物料绑定多个通道时,通过随机数,随机分配物料已绑定的道号)
                        //PS:需要和PLC确定访问方式,分配完成后是否需要清空扫码仪缓存位,如果不清空,则需要在
                        //WcsBoxInfo表中添加“已分配状态”,用来控制每次的分道号和上次分配的是一样的
                        DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                        int[] array = new int[rowCount];
 
                        for (int j = 0; j < rowCount; j++)
                        {
                            array[j] = int.Parse(dt.Rows[j]["LineDao"].ToString());
                        }
                        Random random = new Random();
                        int randomIndex = random.Next(0, array.Length);
                        int randomElement = array[randomIndex];
                        Console.WriteLine("随机取出的分道为: " + randomElement);
 
                        //给PLC下发道号码垛规则等信息
                        string lineDao = randomElement.ToString();
                        PickLinoBind LineInfo = new PickLinoBind();
                        LineInfo.Chang = dt.Rows[randomElement]["Chang"].ToString();
                        LineInfo.Kuan = dt.Rows[randomElement]["Kuan"].ToString();
                        LineInfo.Gao = dt.Rows[randomElement]["Gao"].ToString();
                        //通过PLC提供的地址写入
                        //写入………
 
 
                        return "0";
                    }
                    //箱码未绑定
                    else
                    {
                        //自动绑定分道,并下发给PLC道号
                        sqlString.Clear();
                        sqlString.Append($"select * from WCSPickLino where PickType = 0 and Picked < '4' and IDState =0 ;");
                        rowCount = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
 
                        if (rowCount >= 1)//有可分配的码垛工位
                        {
 
                            //获取码垛规则
                            StringBuilder skuSql = new StringBuilder();
                            skuSql.Append($"select * from WCSMaterialRules where SkuNo = '{SkuNo}'  and IsDel = '0' ;");
                            DataTable sku = DataFactory.SqlDataBase().GetDataTableBySQL(skuSql);
                            if (sku == null || sku.Rows.Count == 0)
                            {
                                return "1";//未获取到该品种码垛规则,需要人工维护
                            }
 
                            //创建到PickLindBind表该物料的绑定任务
                            DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                            //查找可用道号
                            int[] array = { 1, 2, 3, 4 };
                            StringBuilder LineDao = new StringBuilder();
                            LineDao.Append($"select * from WCSPickLinoBind where " +
                                $"PickLinoID = {int.Parse(dt.Rows[0]["ID"].ToString())} and LineDao = {""}");
                            DataTable dt1 = DataFactory.SqlDataBase().GetDataTableBySQL(skuSql);
 
                            PickLinoBind locat = new PickLinoBind()
                            {
                                PickLinoID = int.Parse(dt.Rows[0]["ID"].ToString()),
                                TaskNo = "固定值,测试",
                                Type = "固定值,测试",
                                LotNo = LotNo,
                                SkuNo = SkuNo,
                                SkuName = SkuName,
                                Chang = sku.Rows[0]["Chang"].ToString(),//……需要修改通过物料
                                Kuan = sku.Rows[0]["Kuan"].ToString(),
                                Gao = sku.Rows[0]["Gao"].ToString(),
                                AddTime = DateTime.Parse(DateTime.Now.ToString()),
                                IDState = "1",
                                LineDao = dt1.Rows[0]["LineDao"].ToString(),
                                Level = "1",
                            };
                            //将locat insert到pickLinoBind中
                            // 插入任务明细表
                            sqlString.Clear();
                            sqlString.Append(@"INSERT INTO WCSPickLinoBind 
                                            ( PickLinoID , TaskNo , Type , LotNo , SkuNo , SkuName 
                                            , Chang,Kuan,Gao,AddTime,IDState,LineDao,Level) VALUES (");
                            sqlString.Append($"{locat.PickLinoID},{locat.TaskNo},'{locat.Type}','{locat.LotNo}','{locat.SkuNo}',");
                            sqlString.Append($"'{locat.SkuName}','{locat.Chang}','{locat.Kuan}','{locat.Gao}',{locat.AddTime},");
                            sqlString.Append($"'1','{locat.LineDao}','1');");
                            rowCount = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                            if (rowCount > 0)
                            {
                                //给PLC下发道号码垛规则等信息
                                string lineDao = locat.LineDao;
                                PickLinoBind LineInfo = new PickLinoBind();
                                LineInfo.Chang = locat.Chang;
                                LineInfo.Kuan = locat.Kuan;
                                LineInfo.Gao = locat.Gao;
                                //通过PLC提供的地址写入
                                //写入………
 
                                return "0";
                            }
                            else
                            {
                                return "3";
                            }
 
                        }
                        else//码垛工位已满,不分配
                        {
                            return "2";
                        }
                    }
                }
                //未获取箱支关系
                else
                {
                    //未获取到箱码信息,调用赋码系统接口程序获取箱信息,并将箱信息写入WCSPickLinoBind表中
                    WcsBoxInfo BoxInfo = new WcsBoxInfo();
                    BoxInfo = GetBoxInfo(barcode);
                    return "5";
                }
 
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 机器人请求插码
        /// </summary>
        /// <param name="model">任务信息</param>
        /// <returns></returns>
        public string GetBarcodeIN(string barcode, string palletNo)
        {
            StringBuilder sqlString = new StringBuilder();
            try
            {
                if (palletNo.Length > 8)
                {
                    return "1";//托盘号错误
                }
                if (CheckBarcodeRepeat(barcode))
                {
                    return "2";//箱码重复
                }
                //允许插码,更改箱支关系表中此箱码Aflag状态为2
                sqlString.Append($"UPDATE WCSBoxInfo set Aflag = '2' where BoxNo = '{barcode}'  and Aflag = '1' and Status = '0';");
                int IsUptLocate = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
 
                if (IsUptLocate == 1)
                {
                    return "0";
                }
                else
                {
                    return "3";//修改插码状态失败
                }
            }
            catch (Exception)
            {
 
                throw;
            }
        }
 
        public bool CheckBarcodeRepeat(string barcode)
        {
            try
            {
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append($"select * from WCSBoxInfo where BoxNo = '{barcode}' and Aflag in ('0','2');");//查找当前箱码是否 0:未分道或 2:已插码
                DataRow row = DataFactory.SqlDataBase().GetDataRowBySQL(sqlString);
                if (row == null)
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 组盘
        /// </summary>
        /// <param name="model">任务信息</param>
        /// <returns></returns>
        public bool GroupPallno(string stationNum, string palletNo)
        {
            bool T = false;
            StringBuilder sqlString = new StringBuilder();
            try
            {
                sqlString.Append($"select * form WCSPickLinoBind where  LineDao = '{stationNum}'");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                var Sku = dt.Rows[0]["Sku"].ToString();
                var LotNo = dt.Rows[0]["LotNo"].ToString();
 
                //判断箱支表已插码未组盘的当前托盘号箱信息
                sqlString.Clear();
                sqlString.Append($"select * from WCSBoxInfo where Sku = '{Sku}' and LotNo = '{LotNo}'" +
                    $" and PalletNo = '{palletNo}' and Aflag = '2'");
                DataTable dt1 = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
                if (dt1.Rows.Count == 0)
                {
                    return T;//空托盘不需要组盘
                }
 
                //提交组盘信息……
                foreach (var item in dt1.Rows)
                {
                    //提交当前托盘上的箱支关系
                    if (GroupBoxInfo(palletNo))
                    {
                        //提交成功后更改组盘状态
                        sqlString.Clear();
                        sqlString.Append($"UPDATE WCSBoxInfo set Status = '1' where Sku = '{Sku}' and LotNo = '{LotNo}'" +
                            $" and PalletNo = '{palletNo}' and Aflag = '2'");
                        int count = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                        if (count == 0)
                        {
                            return T;//修改组盘状态失败
                        }
                        T = true;
                    }
                }
                return T;
            }
            catch (Exception ex)
            {
 
                throw ex;
            }
        }
 
        /// <summary>
        /// 向WMS提交组盘信息
        /// </summary>
        /// <param name="palletNo"></param>
        /// <returns></returns>
        public bool GroupBoxInfo(string palletNo)
        {
            try
            {
                //获取是否存在当前箱码信息
                StringBuilder sqlString = new StringBuilder();
                sqlString.Append($"select * from WcsBoxInfo where IsDel = '0' and PalletNo = '{palletNo}' ");
                DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sqlString);
 
                if (dt == null || dt.Rows.Count == 0)
                {
                    //调用WMS系统
                    var response = Utility.Extra.HttpHelper.DoPost(DataFactory.GetWmsURL() + "/api/DownAPi/RequestLocation", palletNo);
                    WcsBoxInfo boxInfo = JsonConvert.DeserializeObject<WcsBoxInfo>(response);
 
                    //添加箱码信息
                    sqlString.Clear();
                    sqlString.Append("insert into WcsBoxInfo (OrderCode,Line_No,LineDao,PORT,BoxNo,BoxNo2,BoxNo3,PalletNo,Qty,FullQty,Aflag,Status,SkuNo,SkuName,LotNo,LotText,Custom,CustomName,ProductionTime,ExpirationTime,CompleteTime,InspectMark,BitBoxMark,Standard,PackageStandard,StoreTime,QtyCount,QtyOrd,Opuser,IsDel,CreateTime,CreateUser,UpdateTime,UpdateUser)");
                    sqlString.Append($"Values ('{boxInfo.OrderCode}','{boxInfo.Line_No}','{boxInfo.LineDao}','{boxInfo.PORT}','{boxInfo.BoxNo}','{boxInfo.BoxNo2}','{boxInfo.BoxNo3}','','{boxInfo.Qty}','{boxInfo.FullQty}','{boxInfo.Aflag}','{boxInfo.Status}','{boxInfo.SkuNo}','{boxInfo.SkuName}','{boxInfo.LotNo}','{boxInfo.LotText}','{boxInfo.Custom}','{boxInfo.CustomName}','{boxInfo.ProductionTime}','{boxInfo.ExpirationTime}','{boxInfo.CompleteTime}','{boxInfo.InspectMark}','{boxInfo.BitBoxMark}','{boxInfo.Standard}','{boxInfo.PackageStandard}','{boxInfo.StoreTime}','{boxInfo.QtyCount}','{boxInfo.QtyOrd}','{boxInfo.Opuser}','0',getdate(),null,null,null)");
                    int isAdd = DataFactory.SqlDataBase().ExecuteBySql(sqlString);
                    if (isAdd == 1)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
 
 
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
 
                throw ex;
            }
        }
 
        #endregion
    }
 
    /// <summary>
    /// 返回wms实体类
    /// </summary>
    public class ExportLibraryDto
    {
        /// <summary>
        /// 任务号
        /// </summary>
        public string TaskNo { get; set; }
        /// <summary>
        /// 任务类型
        /// </summary>
        public string TaskType { get; set; }
        /// <summary>
        /// 托盘编码
        /// </summary>
        public string StockCode { get; set; }
        /// <summary>
        /// 储位编码
        /// </summary>
        public string SlotCode { get; set; }
        /// <summary>
        /// 目标地址(可能是仓库口、可能是移库后的储位)
        /// </summary>
        public string TargetPosition { get; set; }
        /// <summary>
        /// 托盘要经过的巷道口
        /// </summary>
        public string LaneWayPosition { get; set; }
        /// <summary>
        /// 目标储位经过的巷道口
        /// </summary>
        public string TargetLaneWayPosition { get; set; }
 
        public int Order { get; set; }
 
    }
 
    /// <summary>
    /// 任务监控实体类
    /// </summary>
    public class TaskMonitorDto
    {
        /// <summary>
        /// 任务号
        /// </summary>
        public string TaskNo { get; set; }
        /// <summary>
        /// 任务类型
        /// </summary>
        public string TaskType { get; set; }
        /// <summary>
        /// 托盘编码
        /// </summary>
        public string Palno { get; set; }
        /// <summary>
        /// 起始地址
        /// </summary>
        public string InitialAddre { get; set; }
        /// <summary>
        /// 目标地址
        /// </summary>
        public string TargetAddre { get; set; }
 
        /// <summary>
        /// 状态 01等待  02进行中 03已完成
        /// </summary>
        public string State { get; set; }
 
        /// <summary>
        /// 是否成功
        /// </summary>
        public string IsSucceed { get; set; }
 
        /// <summary>
        /// 错误信息
        /// </summary>
        public string ErrorStr { get; set; }
 
        /// <summary>
        /// 优先级
        /// </summary>
        public int? PriorityLevel { get; set; }
 
        /// <summary>
        /// 来源
        /// </summary>
        public string Source { get; set; }
 
        /// <summary>
        /// 是否成功
        /// </summary>
        public string Demo { get; set; }
 
        /// <summary>
        /// 是否删除
        /// </summary>
        public int? IsDel { get; set; }
    }
 
    /// <summary>
    /// 申请储位实体类
    /// </summary>
    public class LocationInfo
    {
        /// <summary>
        /// 托盘号
        /// </summary>
        public string palNo { get; set; }
        /// <summary>
        /// 高度
        /// </summary>
        public int height { get; set; }
    }
}