qinchulong
2025-03-29 039a4a5433e7f80adc88b491b549e5d9486e4f9a
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
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
using System;
using System.Collections.Generic;
using System.Text;
using WIDESEA_WCS.WCSClient;
using WIDESEA_Entity.DomainModels;
using WIDESEA_Services.Repositories;
using System.Linq;
using System.Threading;
using WIDESEA_Core.Utilities;
using System.Diagnostics;
using Quartz.Impl;
using WIDESEA_Common.CutomerModel;
using WIDESEA_Common;
using WIDESEA_Services.IRepositories;
using WIDESEA_Common.Tools;
using WIDESEA_Services.Services;
using WIDESEA_Services;
using WIDESEA_Core.EFDbContext;
using System.Threading.Tasks;
using WIDESEA_WCS.SchedulerExecute;
using Newtonsoft.Json;
using HslCommunication;
using WIDESEA_Core.ManageUser;
using WIDESEA_WCS.Jobs;
 
namespace WIDESEA_WCS
{
    public class WCSService
    {
        public static bool iswlx = true;
        public static bool choose = true;
        public static string type = "";
        /// <summary>
        /// PLC连接集合
        /// </summary>
        public static List<PLCClient> Clients;
 
        /// <summary>
        /// PLC连接失败集合
        /// </summary>
        public static List<PLCClient> ClientsNoConn;
 
        /// <summary>
        /// 调度中心
        /// </summary>
        public static ISchedulerCenterServer scheduler;
 
        /// <summary>
        /// Job集合
        /// </summary>
        static List<JobOptions> jobs = new List<JobOptions>();
 
        #region 开启服务
        /// <summary>
        /// 开启服务
        /// </summary>
        /// <returns></returns>
        public static WebResponseContent StartService()
        {
            WebResponseContent responseContent = new WebResponseContent();
            try
            {
                if (!CheckServerState().Status)//开启服务之前检查调度是否已开启及PLC是否已连接
                {
                    WIDESEA.Helper.GetToken();
                    WebResponseContent content = ConnectServer();
                    if (content.Status)
                    {
                        responseContent = StartSchedule();
                        if (!responseContent.Status)
                        {
                            DisconnectServer();
                        }
                    }
                    else
                    {
                        DisconnectServer();
                        responseContent = content;
                    }
                }
                else
                {
                    responseContent = WebResponseContent.Instance.Error("服务已开启");
                }
            }
            catch (Exception ex)
            {
                responseContent = responseContent.Error(ex.Message);
            }
            return responseContent;
        }
        #endregion
 
        #region 关闭服务
        /// <summary>
        /// 关闭服务(调度及PLC连接)
        /// </summary>
        /// <returns></returns>
        public static WebResponseContent CloseService()
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                if (scheduler != null)
                {
                    CloseSchedule();
                    DisconnectServer();
                    scheduler = null;
                    content = content.OK();
                }
                else
                {
                    content = WebResponseContent.Instance.Error("任务调度已停止");
                }
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
        #endregion
 
        #region 检查服务状态
        /// <summary>
        /// 检查服务状态
        /// </summary>
        /// <returns></returns>
        public static WebResponseContent CheckServerState()
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                if (scheduler != null && Clients.Any())
                {
                    content = content.OK(message: "");
                }
                else
                {
                    CloseService();
                    content = content.Error(message: "服务已关闭");
                }
                //if (ClientsNoConn!=null && ClientsNoConn.Count>0)
                //{
                //    foreach (var item in ClientsNoConn)
                //    {
                //        string msg = item.Connect();
                //        if (msg.Contains("连接成功"))
                //        {
                //            ClientsNoConn.Remove(item);
                //            Clients.Add(item);
                //        }
                //    }
                //}
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
        #endregion
 
        #region 暂停或恢复指定的计划任务
        /// <summary>
        /// 暂停或恢复指定的计划任务
        /// </summary>
        /// <param name="job"></param>
        /// <returns></returns>
        public static WebResponseContent PauseOrResumeJob(SaveModel saveModel)
        {
            return dt_equipmentinfoRepository.Instance.DbContextBeginTransaction(() =>
            {
                Idt_equipmentinfoRepository repository = new dt_equipmentinfoRepository(new WIDESEA_Core.EFDbContext.VOLContext());
                dt_equipmentinfo equipmentinfo = repository.FindFirst(x => x.equipment_name == saveModel.MainData["equipNum"].ToString());
                if (equipmentinfo == null)
                    return WebResponseContent.Instance.Error($"未找到该设备【{saveModel.MainData["equipNum"]}】");
                if (equipmentinfo.equipment_state == EquipmentState.Enable.ToString())
                    equipmentinfo.equipment_state = EquipmentState.Disenable.ToString();
                else
                    equipmentinfo.equipment_state = EquipmentState.Enable.ToString();
                if (dt_equipmentinfoRepository.Instance.Update(equipmentinfo, true) <= 0)
                    return WebResponseContent.Instance.Error("设备状态修改失败");
                JobOptions options = new JobOptions { JobName = equipmentinfo.equipment_name, JobGroup = equipmentinfo.equipment_type };
                if (scheduler == null)
                    return WebResponseContent.Instance.OK("设备状态修改成功");
 
                if (!scheduler.IsExistScheduleJobAsync(options).Result)
                {
                    return WebResponseContent.Instance.OK("设备状态修改成功");
                }
                if (saveModel.MainData["equipStatus"].ToString() == EquipmentState.Enable.ToString())
                {
                    return scheduler.PauseJob(options).Result;
                }
                else
                {
                    return scheduler.ResumeJob(options).Result;
                }
            });
 
        }
        #endregion
 
        #region 开启调度
        /// <summary>
        /// 开启调度
        /// </summary>
        /// <returns></returns>
        public static WebResponseContent StartSchedule()
        {
            WebResponseContent responseContent = new WebResponseContent();
            try
            {
                StdSchedulerFactory factory = new StdSchedulerFactory();
                scheduler = new SchedulerCenterServer(factory);
                List<JobOptions> jobOptions = VV_DispatchRepository.Instance.FindToJobOptions(x => true && x.Enable == EquipmentState.Enable.ToString()
                && x.JobName!="正极1号AGV" && x.JobName != "正极2号AGV" && x.JobName != "负极2号AGV" && x.JobGroup != "EquipmentType_Stacker");
                jobOptions.ForEach(x => { x.JobParams = Clients.Where(y => y.PLCName == x.JobName).FirstOrDefault(); });
                if (!jobOptions.Any())
                {
                    responseContent = WebResponseContent.Instance.Error("当前未配置调度");
                    return responseContent;
                }
 
                for (int i = 0; i < jobOptions.Count; i++)
                {
                    WebResponseContent content = scheduler.AddScheduleJobAsync(jobOptions[i]).Result;
                    if (!content.Status)
                    {
                        factory = null;
                        scheduler = null;
                        return content;
                    }
                }
 
                responseContent = scheduler.StartScheduleAsync().Result;
 
            }
            catch (Exception ex)
            {
                responseContent = responseContent.Error(ex.Message);
                scheduler = null;
            }
            return responseContent;
        }
        #endregion
 
        #region 停止调度
        /// <summary>
        /// 停止调度
        /// </summary>
        /// <returns></returns>
        public static WebResponseContent CloseSchedule()
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                content = scheduler.StopScheduleAsync().Result;
            }
            catch (Exception ex)
            {
                content = content.Error(ex.Message);
            }
            return content;
        }
        #endregion
 
        #region 连接PLC
        /// <summary>
        /// 连接PLC
        /// </summary>
        /// <returns></returns>
        public static WebResponseContent ConnectServer()
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                if (Clients != null)
                {
                    DisconnectServer();
                }
                //if (ClientsNoConn==null)
                //{
                //    ClientsNoConn = new List<PLCClient>();
                //}
                jobs = new List<JobOptions>();
                jobs = VV_DispatchRepository.Instance.FindJobOptions(x => true);
                List<string> plcNames = VV_DispatchRepository.Instance.FindToJobOptions(x => true && x.Enable == EquipmentState.Enable.ToString() && x.JobName != "正机2号分切机5012").Select(x => x.JobName).ToList();
                // List<string> plcNames = VV_DispatchRepository.Instance.FindToJobOptions(v=>).ToList(); http://192.168.12.251:8099
                if (plcNames.Count == 0)
                    return content = WebResponseContent.Instance.Error("当前无PLC连接配置或设备被禁用");
                Clients = new List<PLCClient>();
 
                List<dt_plcinfohead> plcinfoheads = dt_plcinfoheadRepository.Instance.Find(x => plcNames.Contains(x.plcinfo_name));
 
                foreach (dt_plcinfohead item in plcinfoheads)
                {
                    PLCClient client = new PLCClient(item.plcinfo_type, item)
                    {
                        PLCName = item.plcinfo_name,
                        PLCDescroption = item.plcinfo_remark,
                        PLCDownLoc = item.plcinfo_down
                    };
                    string msg = client.Connect();
                    if (msg.Contains("连接成功"))
                    {
                        jobs.Where(x => x.JobName == item.plcinfo_name).FirstOrDefault().PLCConnectState = msg;
                        Clients.Add(client);
                    }
                    //else
                    //{
                    //    ClientsNoConn.Add(client);
                    //}
                }
                content = WebResponseContent.Instance.OK("PLC连接成功!");
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
                Clients = null;
            }
            return content;
        }
        #endregion
 
        #region 断开与PLC的连接
        /// <summary>
        /// 断开与PLC的连接
        /// </summary>
        /// <returns></returns>
        public static WebResponseContent DisconnectServer()
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                if (Clients.Any() && Clients != null)
                {
                    for (int i = 0; i < Clients.Count; i++)
                    {
                        Clients[i]?.Disconnect();
                    }
                    content = WebResponseContent.Instance.OK(message: "已断开与PLC的连接!");
                }
                else
                {
                    content = WebResponseContent.Instance.Error("当前与PLC无连接!");
                }
                Clients = null;
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error(ex.Message);
            }
            return content;
        }
        #endregion
 
        #region ThreadMethod PLC连接内置线程 方法
        static void Read(PLCClient client)
        {
            //Console.Out.WriteLine(client.Read("DB3.0", "INT"));
        }
        #endregion
 
        #region 获取任务触发器状态
        /// <summary>
        /// 获取任务触发器状态
        /// </summary>
        /// <returns></returns>
        public static WebResponseContent GetTaskStaus()
        {
            WebResponseContent responseContent = new WebResponseContent();
            List<TaskInfoDto> taskInfoDtos = new List<TaskInfoDto>();
            if (jobs.FirstOrDefault() == null)
                jobs = VV_DispatchRepository.Instance.FindJobOptions(x => true);
 
            for (int i = 0; i < jobs.Count; i++)
            {
                List<TaskInfoDto> temp = new List<TaskInfoDto>();
                if (scheduler == null)
                {
                    temp = new List<TaskInfoDto>
                    {
                        new TaskInfoDto()
                        {
                            JobId = jobs[i].JobName.ObjToString(),
                            JobGroup = jobs[i].JobGroup,
                            TriggerId = "",
                            TriggerGroup = "",
                            TriggerStatus = "不存在",
                            IsConnected = Clients.Where(x=>x.PLCName == jobs[i].JobName).FirstOrDefault()?.IsConnected??false
                        }
                    };
                }
                else
                {
                    temp = scheduler.GetTaskStaus(jobs[i]).Result;
                }
 
                taskInfoDtos.AddRange(temp);
            }
            return WebResponseContent.Instance.OK(data: taskInfoDtos);
        }
        #endregion
 
        #region 立即执行 一个任务
        /// <summary>
        /// 立即执行 一个任务
        /// </summary>
        /// <param name="jobName"></param>
        /// <returns></returns>
        public static WebResponseContent ExecuteJobAsync(string jobName)
        {
            WebResponseContent result = new WebResponseContent();
            try
            {
                JobOptions job = jobs.Where(x => x.JobName == jobName).FirstOrDefault();
                if (job == null)
                {
                    result = WebResponseContent.Instance.Error($"立即执行计划任务失败:未找到该任务计划,任务计划:{jobName}");
                }
                else
                {
                    result = scheduler.ExecuteJobAsync(job).Result;
                }
 
            }
            catch (Exception ex)
            {
                result.Message = $"立即执行计划任务失败:【{ex.Message}】";
            }
 
            return result;
        }
        #endregion
 
        #region 获取任务触发器状态
        /// <summary>
        /// 获取任务触发器状态
        /// </summary>
        /// <returns></returns>
        public static PageGridData<TaskInfoDto> GetPageData()
        {
            try
            {
                List<TaskInfoDto> taskInfoDtos = new List<TaskInfoDto>();
                if (jobs.FirstOrDefault() == null)
                    jobs = VV_DispatchRepository.Instance.FindJobOptions(x => true);
 
                for (int i = 0; i < jobs.Count; i++)
                {
                    List<TaskInfoDto> temp = new List<TaskInfoDto>();
                    if (scheduler == null)
                    {
 
                        temp = new List<TaskInfoDto>
                        {
                            new TaskInfoDto()
                            {
                                JobId = jobs[i].JobName.ObjToString(),
                                JobGroup = jobs[i].JobGroup,
                                TriggerId = "",
                                TriggerGroup = "",
                                TriggerStatus = "不存在",
                                PLCConnetState = jobs[i].PLCConnectState,
                                IsConnected = false
                            }
                        };
                    }
                    else
                    {
                        temp = scheduler.GetTaskStaus(jobs[i]).Result;
                        if (Clients != null)
                        {
                            for (int j = 0; j < temp.Count; j++)
                            {
                                temp[j].IsConnected = Clients.Where(x => x.PLCName == temp[j].JobId).FirstOrDefault()?.IsConnected ?? false;
                            }
                        }
                    }
 
                    taskInfoDtos.AddRange(temp);
                }
                return new PageGridData<TaskInfoDto> { rows = taskInfoDtos, total = taskInfoDtos?.Count ?? 0 };
            }
            catch (Exception ex)
            {
                return new PageGridData<TaskInfoDto> { rows = null, total = 0, status = 404, msg = ex.Message };
            }
 
        }
        #endregion
 
        public static JobOptions GetJobOptions(string jobName)
        {
            return jobs.Where(x => x.JobName == jobName).FirstOrDefault();
        }
        private static int _MESCallLock = 0;
        public static ResultMaterstateUp Updatestockstate(MESupdateMaterStateRequest request)
        {
            WriteLog.Info("更新物料信息MES调我们的接口").Write("开始,缓存架编号:" + request.Devid + "\t" + "物料条码:" + request.BarCode + "\t" + "物料状态:" + request.MaterialStatus + "\t" + DateTime.Now, "更新物料信息");
            if (Interlocked.Exchange(ref _MESCallLock, 1) == 0)
            {
                ResultMaterstateUp result = new ResultMaterstateUp();
                try
                {
                    VOLContext Context = new VOLContext();
                    Ibase_ware_locationRepository locRepository = new base_ware_locationRepository(Context);
                    Ibill_group_stockRepository groupRepository = new bill_group_stockRepository(Context);
                    Idt_agvtaskRepository agvRepository = new dt_agvtaskRepository(Context);
                    WebResponseContent responseContent = new WebResponseContent();
                    responseContent = locRepository.DbContextBeginTransaction(() =>
                    {
                        var stockisexist = groupRepository.FindFirst(v=>v.BarCode== request.BarCode);
                        if (stockisexist!=null)
                        {
                            throw new Exception("当前条码已存在库存"+ request.BarCode);
                        }
                        var location = locRepository.FindFirst(v => v.down_code == request.Devid || v.upper_code == request.Devid);
                        if (string.IsNullOrEmpty(request.MaterialStatus))
                        {
                            throw new Exception("物料状态不能为空");
                        }
                        var task = agvRepository.FindFirst(f => f.agv_fromaddress == location.upper_code || f.agv_fromaddress == location.down_code);
                        if (task != null)
                        {
                            result.Message = "该货位有正在进行的任务,不能绑定";
                            result.Code = 1;
                            MESAPIInvoke.GetInterfaceInfo("Updatestockstate", "物料条码:" + request.BarCode, request.Devid, result.Code, result.Message);
                            WriteLog.Info("更新物料信息MES调我们的接口").Write("异常,缓存架编码:" + request.Devid + "\t" + "反馈结果" + result.Code + "\t" + "反馈信息" + result.Message + "\t" + DateTime.Now, "更新物料信息");
                            return WebResponseContent.Instance.Error(result.Message);
                        }
                        var stock = groupRepository.Find(v => v.location_id == location.id).OrderByDescending(v => v.created_time).FirstOrDefault();
                        string materialtype = request.BarCode.Split('*')[2];
                        if (stock == null)
                        {
                            bill_group_stock bill_Group = new bill_group_stock()
                            {
                                first_tb = 1,
                                BarCode = request.BarCode,
                                created_time = DateTime.Now,
                                created_user = "admin",
                                stock_id = new Guid(),
                                location_id = location.id,
                                MaterialType = materialtype,
                                MaterialStatus = request.MaterialStatus,
                                updated_time = DateTime.Now,
                                updated_user = "admin"
                            };
                            if (request.Devid.Contains("JJK"))
                            {
                                bill_Group.FQ_Status = "";
                                bill_Group.GY_Status = "";
                                bill_Group.QX_Status = "";
                                bill_Group.FQ_Status = "";
                            }
                            else
                            {
                                bill_Group.TB_Status = request.Devid.Contains("TB") ? request.MaterialStatus : "nou";
                                bill_Group.GY_Status = request.Devid.Contains("GY") ? request.MaterialStatus : "nou";
                                bill_Group.FQ_Status = request.Devid.Contains("FQ") || request.Devid.Contains("ZZLJ") ? request.MaterialStatus : "nou";
                                bill_Group.QX_Status = request.Devid.Contains("QX") ? request.MaterialStatus : "nou";
                            }
                            groupRepository.Add(bill_Group, true);
                            location.location_state = LocationStateEnum.LocationState_Stored.ToString();
                            locRepository.Update(location, true);
                            for (int i = 0; i < 10; i++)
                            {
                                var st = groupRepository.FindFirst(f => f.BarCode == request.BarCode);
                                WriteLog.Info("货位id").Write(request.Devid + "\t" + st.location_id + "\t" + st.BarCode + "\t" + st.MaterialStatus + "\t" + DateTime.Now, "货位id");
                                if (string.IsNullOrEmpty(st.location_id.ToString()))
                                {
                                    st.location_id = location.id;
                                    groupRepository.Update(st, true);
                                }
                                if (st.MaterialStatus == "nou")
                                {
                                    st.MaterialStatus = request.MaterialStatus;
                                    groupRepository.Update(st, true);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                        else
                        {
                            if (location.equipment_type == "TBHCJ")
                            {
                                stock.TB_Status = request.MaterialStatus;
                            }
                            else if (location.equipment_type == "GYHCJ" && location.area == "FJSL")
                            {
                                stock.TB_Status = request.MaterialStatus;
                            }
                            else if (location.equipment_type == "GYHCJ" && location.area == "ZJSL")
                            {
                                stock.QX_Status = request.MaterialStatus;
                            }
                            else if (location.equipment_type == "QXHCJ" && location.area == "FJSL")
                            {
                                stock.GY_Status = request.MaterialStatus;
                            }
                            else if (location.equipment_type == "QXHCJ" && location.area == "ZJSL")
                            {
                                stock.TB_Status = request.MaterialStatus;
                            }
                            else if (location.equipment_type == "FQHCJ" && location.area == "FJSL")
                            {
                                stock.QX_Status = request.MaterialStatus;
                            }
                            else if (location.equipment_type == "FQHCJ" && location.area == "ZJSL")
                            {
                                stock.GY_Status = request.MaterialStatus;
                            }
                            else if (location.equipment_type == "ZZLJ")
                            {
                                stock.FQ_Status = request.MaterialStatus;
                            }
                            else if (location.equipment_type == "JJK")
                            {
                                stock.TB_Status = "";
                                stock.FQ_Status = "";
                                stock.QX_Status = "";
                                stock.GY_Status = "";
                            }
                            if (stock.BarCode == request.BarCode)
                            {
                                result.Message = "请不要重复绑定该物料";
                                result.Code = 0;
                                MESAPIInvoke.GetInterfaceInfo("Updatestockstate", "物料条码:" + request.BarCode, request.Devid, result.Code, result.Message);
                            }
                            else
                            {
                                stock.BarCode = request.BarCode;
                            }
                            stock.MaterialStatus = request.MaterialStatus;
                            stock.MaterialType = materialtype;
                            stock.location_id = location.id;
                            stock.created_time = DateTime.Now;
                            stock.updated_time = DateTime.Now;
                            groupRepository.Update(stock, true);
                            for (int i = 0; i < 10; i++)
                            {
                                var st = groupRepository.FindFirst(f => f.BarCode == request.BarCode);
                                WriteLog.Info("货位id").Write(request.Devid + "\t" + st.location_id + "\t" + st.BarCode + "\t" + st.MaterialStatus + "\t" + DateTime.Now, "货位id");
                                if (string.IsNullOrEmpty(st.location_id.ToString()))
                                {
                                    st.location_id = location.id;
                                    groupRepository.Update(st, true);
                                }
                                if (st.MaterialStatus == "nou")
                                {
                                    st.MaterialStatus = request.MaterialStatus;
                                    groupRepository.Update(st, true);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            location.location_state = LocationStateEnum.LocationState_Stored.ToString();
                            locRepository.Update(location, true);
                        }
 
                        if (location.area == "ZJSL")
                        {
                            PLCClient plc = WCSService.Clients.Find(v => v.PLCName == "正极1号AGV");
                            if (plc == null)
                            {
                                result.Message = "正极1号AGVplc未连接上";
                                result.Code = 1;
                                MESAPIInvoke.GetInterfaceInfo("Updatestockstate", "物料条码:" + request.BarCode, request.Devid, result.Code, result.Message);
                                return WebResponseContent.Instance.Error(result.Message);
                            }
                            if (request.MaterialStatus == "OK")
                            {
                                plc.WriteValue(ConveyorLineInfoDBName.MaterOK.ToString(), request.Devid, 1);
                            }
                            else
                            {
                                plc.WriteValue(ConveyorLineInfoDBName.MaterNG.ToString(), request.Devid, 1);
                            }
                        }
                        else if (location.area == "FJSL")
                        {
                            PLCClient plc = WCSService.Clients.Find(v => v.PLCName == "负极1号AGV");
                            if (plc == null)
                            {
                                result.Message = "负极1号AGVplc未连接上";
                                result.Code = 1;
                                MESAPIInvoke.GetInterfaceInfo("Updatestockstate", "物料条码:" + request.BarCode, request.Devid, result.Code, result.Message);
                                return WebResponseContent.Instance.Error(result.Message);
                            }
                            if (request.MaterialStatus == "OK")
                            {
                                plc.WriteValue(ConveyorLineInfoDBName.MaterOK.ToString(), request.Devid, 1);
                            }
                            else
                            {
                                plc.WriteValue(ConveyorLineInfoDBName.MaterNG.ToString(), request.Devid, 1);
                            }
                        }
                        result.Code = 0;
                        return WebResponseContent.Instance.OK();
                    });
                    if (responseContent.Status == false)
                    {
                        throw new Exception(responseContent.Message);
                    }
                    WriteLog.Info("更新物料信息MES调我们的接口").Write("结束,缓存架编码:" + request.Devid + "\t" + "物料条码" + request.BarCode + "\t" + "物料状态" + request.MaterialStatus + "\t" + "反馈结果" + result.Code + "\t" + "反馈信息" + result.Message + "\t" + DateTime.Now, "更新物料信息");
                    return result;
                }
                catch (Exception ex)
                {
                    result.Message = ex.Message;
                    result.Code = 1;
                    MESAPIInvoke.GetInterfaceInfo("Updatestockstate", "物料条码:" + request.BarCode, request.Devid, result.Code, result.Message);
                    WriteLog.Info("更新物料信息MES调我们的接口").Write("异常,缓存架编码:" + request.Devid + "\t" + "物料条码" + request.BarCode + "\t" + "物料状态" + request.MaterialStatus + "\t" + "反馈结果" + result.Code + "\t" + "反馈信息" + result.Message + "\t" + DateTime.Now, "更新物料信息");
                }
                finally
                {
                    Interlocked.Exchange(ref _MESCallLock, 0);
                }
                return result;
            }
            else
            {
                ResultMaterstateUp result = new ResultMaterstateUp();
                result.Message = "请勿重复调用";
                result.Code = 1;
                MESAPIInvoke.GetInterfaceInfo("Updatestockstate", "物料条码:" + request.BarCode, request.Devid, result.Code, result.Message);
                WriteLog.Info("更新物料信息MES调我们的接口").Write("异常,缓存架编码:" + request.Devid + "\t" + "物料条码" + request.BarCode + "\t" + "物料状态" + request.MaterialStatus + "\t" + "反馈结果" + result.Code + "\t" + "反馈信息" + result.Message + "\t" + DateTime.Now, "更新物料信息");
                return result;
            }
        }
        /// <summary>
        /// MES查看AGV库位状态
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static List<ResultLocationState> GetLocationState(string Devid)
        {
            List<ResultLocationState> result = new List<ResultLocationState>();
            try
            {
                if (Devid != null)
                {
                    var Id = base_ware_locationRepository.Instance.FindFirst(v => v.down_code == Devid || v.upper_code == Devid);
                    var location = bill_group_stockRepository.Instance.FindFirst(v => v.location_id == Id.id);
                    ResultLocationState content = new ResultLocationState();
                    content.BarCode = location.BarCode;
                    content.MaterialStatus = location.MaterialStatus;
                    content.MaterialType = location.MaterialType;
                    content.Devid = Devid;
                    result.Add(content);
                }
                else
                {
                    var IdList = base_ware_locationRepository.Instance.Find(v => 1 == 1).ToList();
                    for (int i = 0; i < IdList.Count; i++)
                    {
                        ResultLocationState content = new ResultLocationState();
                        var locationList = bill_group_stockRepository.Instance.FindFirst(v => v.location_id == IdList[i].id);
                        if (locationList != null)
                        {
                            content.BarCode = locationList.BarCode;
                            content.MaterialStatus = locationList.MaterialStatus;
                            content.MaterialType = locationList.MaterialType;
                            content.Devid = Devid;
                        }
                        else
                        {
                            content.BarCode = "";
                            content.MaterialStatus = "";
                            content.MaterialType = "";
                            content.Devid = IdList[i].down_code;//暂时不知道给那个
                        }
                        result.Add(content);
 
                    }
 
                }
                //
                //result.Code = 0;
            }
            catch (Exception ex)
            {
                //result.Code = 1;
            }
            return result;
        }
        /// <summary>
        /// 三楼卷绕上料请求逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static ResultMaterstateUp Uprequest(UpThreerequest request)
        {
 
            VOLContext Context = new VOLContext();
            ResultMaterstateUp result = new ResultMaterstateUp();
            Idt_task_numberRepository tasknumberRep = new dt_task_numberRepository(Context);
            dt_task_numberService tasknumber = new dt_task_numberService(tasknumberRep);
            Ibase_ware_locationRepository locRepository = new base_ware_locationRepository(Context);
            Ibase_routing_tableRepository routingRepository = new base_routing_tableRepository(Context);
            Ibill_pda_groupdiskRepository pdaRepository = new bill_pda_groupdiskRepository(Context);
            Idt_agvtaskRepository agvRepository = new dt_agvtaskRepository(Context);
            IJROutBindRepository jrRepository = new JROutBindRepository(Context);
            Ibill_group_stockRepository groupRepository = new bill_group_stockRepository(Context);
            try
            {
                WriteLog.Info("卷绕上料").Write("开始,请求:" + request.Uprequest + "\t" + "设备编号:" + request.UpequipNo + "\t" + "工单号:" + request.UpbatchNo + DateTime.Now, "卷绕上料");
                if (request.Uprequest == "1")
                {
                    PLCClient plc = WCSService.Clients.Find(v => v.PLCName == "正极2号AGV");
                    var task = agvRepository.FindFirst(f => f.agv_toaddress == request.UpequipNo);
                    if (task == null)
                    {
                        string isWork = null;
 
                        //获取上料请求
                        if (request.UpequipNo == "ZJSL-JRSB003" || request.UpequipNo == "ZJSL-JRSB007" || request.UpequipNo == "ZJSL-JRSB010" || request.UpequipNo == "ZJSL-JRSB014" || request.UpequipNo == "ZJSL-JRSB019" || request.UpequipNo == "ZJSL-JRSB023" || request.UpequipNo == "ZJSL-JRSB026" || request.UpequipNo == "ZJSL-JRSB030" || request.UpequipNo == "ZJSL-JRSB035" || request.UpequipNo == "ZJSL-JRSB039")
                        {
                            isWork = plc.ReadValue(ConveyorLineInfoDBName.R_JRSB1_UPrequest.ToString(), request.UpequipNo).ToString();
                        }
                        else if (request.UpequipNo == "ZJSL-JRSB004" || request.UpequipNo == "ZJSL-JRSB008" || request.UpequipNo == "ZJSL-JRSB009" || request.UpequipNo == "ZJSL-JRSB013" || request.UpequipNo == "ZJSL-JRSB020" || request.UpequipNo == "ZJSL-JRSB024" || request.UpequipNo == "ZJSL-JRSB025" || request.UpequipNo == "ZJSL-JRSB029" || request.UpequipNo == "ZJSL-JRSB036" || request.UpequipNo == "ZJSL-JRSB040")
                        {
                            isWork = plc.ReadValue(ConveyorLineInfoDBName.R_JRSB2_UPrequest.ToString(), request.UpequipNo).ToString();
                        }
                        else if (request.UpequipNo == "FJSL-JRSB001" || request.UpequipNo == "FJSL-JRSB005" || request.UpequipNo == "FJSL-JRSB012" || request.UpequipNo == "FJSL-JRSB016" || request.UpequipNo == "FJSL-JRSB017" || request.UpequipNo == "FJSL-JRSB021" || request.UpequipNo == "FJSL-JRSB028" || request.UpequipNo == "FJSL-JRSB032" || request.UpequipNo == "FJSL-JRSB033" || request.UpequipNo == "FJSL-JRSB037")
                        {
                            isWork = plc.ReadValue(ConveyorLineInfoDBName.R_JRSB3_UPrequest.ToString(), request.UpequipNo).ToString();
                        }
                        else if (request.UpequipNo == "FJSL-JRSB002" || request.UpequipNo == "FJSL-JRSB006" || request.UpequipNo == "FJSL-JRSB011" || request.UpequipNo == "FJSL-JRSB015" || request.UpequipNo == "FJSL-JRSB018" || request.UpequipNo == "FJSL-JRSB022" || request.UpequipNo == "FJSL-JRSB027" || request.UpequipNo == "FJSL-JRSB031" || request.UpequipNo == "FJSL-JRSB034" || request.UpequipNo == "FJSL-JRSB038")
                        {
                            isWork = plc.ReadValue(ConveyorLineInfoDBName.R_JRSB4_UPrequest.ToString(), request.UpequipNo).ToString();
                        }
                        WriteLog.Info("卷绕上料口请求").Write(request.UpequipNo + "\t" + isWork + DateTime.Now, "卷绕上料口请求");
                        if (bool.Parse(isWork))
                        {
                            dt_agvtask agvtask = new dt_agvtask
                            {
                                agv_barcode = "",
                                agv_code = "正极2号AGV",
                                agv_createtime = DateTime.Now,
                                agv_fromaddress = "nou",
                                agv_grade = 1,
                                agv_materbarcode = "daiding",
                                agv_qty = 1,
                                agv_tasknum = "KH-" + tasknumber.GetTaskNumber(tasknumberRep),
                                agv_taskstate = "WaitStockOut",
                                agv_tasktype = "TaskType_Outbound",
                                agv_toaddress = request.UpequipNo,
                                agv_userid = "WCS",
                                agv_worktype = 1,
                                agv_materielid = request.UpbatchNo
                            };
                            List<string> StockList = new List<string> { "ZJXL-FBT001", "ZJXL-FBT002" };
                            MESback WMSbackresult = MESAPIInvoke.OutNeedStosk(agvtask.agv_tasknum, StockList, 4, request.UpbatchNo, "", agvtask.agv_toaddress);
                            if (WMSbackresult == null)
                            {
                                result.Code = 1;
                                result.Message = WMSbackresult.Message;
                                WriteLog.Info("卷绕上料").Write(request.UpequipNo + "要料失败" + WMSbackresult.Message + "\t" + DateTime.Now, "卷绕上料");
                                return result;
                            }
                            agvRepository.Add(agvtask, true);
                            result.Code = 0;
                            result.MaterialType = request.UpbatchNo;
                            result.BarCode = null;
                            WriteLog.Info("卷绕上料").Write("结束,任务号:" + agvtask.agv_tasknum + "\t" + "请求:" + request.Uprequest + "\t" + "设备编号:" + request.UpequipNo + "\t" + "工单号:" + request.UpbatchNo + "\t" + DateTime.Now, "卷绕上料");
                        }
                        else
                        {
                            result.Code = 1;
                            result.Message = "上料口请求是:" + isWork;
                            WriteLog.Info("卷绕上料").Write("结束,请求:" + request.Uprequest + "\t" + "设备编号:" + request.UpequipNo + "\t" + "工单号:" + request.UpbatchNo + "\t" + "上料口请求:" + isWork + DateTime.Now, "卷绕上料");
                            return result;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.Code = 1;
                result.Message = ex.Message;
                WriteLog.Info("卷绕上料").Write("异常,请求:" + request.Uprequest + "\t" + "设备编号:" + request.UpequipNo + "\t" + "工单号:" + request.UpbatchNo + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + DateTime.Now, "卷绕上料");
                MESAPIInvoke.GetInterfaceInfo("Uprequest", request.Uprequest, request.UpequipNo, result.Code, result.Message);
            }
            return result;
        }
        /// <summary>
        /// 入库物料确认搬走
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static ResultMaterstateUp InStockMaterMove(MEStockMaterMoveRequest request)
        {
            VOLContext Context = new VOLContext();
            ResultMaterstateUp result = new ResultMaterstateUp();
            Ibase_ware_locationRepository locRepository = new base_ware_locationRepository(Context);
            Ibill_group_stockRepository groupRepository = new bill_group_stockRepository(Context);
            try
            {
                WriteLog.Info("入库物料确认搬走MES调我们的接口").Write("开始,缓存架编号:" + request.Devid + "\t" + "物料类型:" + request.MaterialType + "\t" + DateTime.Now, "入库物料确认搬走");
                var location = locRepository.FindFirst(v => v.upper_code == request.Devid || v.down_code == request.Devid);
                if (location == null)
                {
                    result.Code = 0;
                    MESAPIInvoke.GetInterfaceInfo("InStockMaterMove", "物料类型:" + request.MaterialType, request.Devid, result.Code, result.Message);
                    WriteLog.Info("入库物料确认搬走MES调我们的接口结束").Write("结束,缓存架编号:" + request.Devid + "\t" + "物料类型:" + request.MaterialType + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息" + result.Message + "\t" + DateTime.Now, "入库物料确认搬走");
                    return result;
                }
                location.location_state = LocationStateEnum.LocationState_Empty.ToString();
                location.created_time = DateTime.Now;
                locRepository.Update(location, true);
                var stock = groupRepository.FindFirst(v => v.MaterialType == request.MaterialType && v.location_id == location.id);
                if (stock == null)
                {
                    result.Code = 0;
                    MESAPIInvoke.GetInterfaceInfo("InStockMaterMove", "物料类型:" + request.MaterialType, request.Devid, result.Code, result.Message);
                    WriteLog.Info("入库物料确认搬走MES调我们的接口结束").Write("结束,缓存架编号:" + request.Devid + "\t" + "物料类型:" + request.MaterialType + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息" + result.Message + "\t" + DateTime.Now, "入库物料确认搬走");
                    return result;
                }
                stock.location_id = null;
                groupRepository.Update(stock, true);
                result.Code = 0;
                MESAPIInvoke.GetInterfaceInfo("InStockMaterMove", "物料类型:" + request.MaterialType, request.Devid, result.Code, result.Message);
                WriteLog.Info("入库物料确认搬走MES调我们的接口结束").Write("结束,缓存架编号:" + request.Devid + "\t" + "物料类型:" + request.MaterialType + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息" + result.Message + "\t" + DateTime.Now, "入库物料确认搬走");
            }
            catch (Exception ex)
            {
                result.Code = 1;
                result.Message = ex.Message;
                MESAPIInvoke.GetInterfaceInfo("InStockMaterMove", "物料类型:" + request.MaterialType, request.Devid, result.Code, result.Message);
                WriteLog.Info("入库物料确认搬走MES调我们的接口异常").Write("异常,缓存架编号:" + request.Devid + "\t" + "物料类型:" + request.MaterialType + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息" + result.Message + "\t" + DateTime.Now, "入库物料确认搬走");
            }
            return result;
        }
 
        /// <summary>
        /// 出库物料绑定 UpdateAGVTaskState 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static ResultMaterstateUp OutStockMaterBind(MEStockMaterBindRequest request)
        {
            VOLContext Context = new VOLContext();
            ResultMaterstateUp result = new ResultMaterstateUp();
            Ibase_ware_locationRepository locRepository = new base_ware_locationRepository(Context);
            Ibill_group_stockRepository groupRepository = new bill_group_stockRepository(Context);
            Idt_agvtaskRepository agvRepository = new dt_agvtaskRepository(Context);
            Idt_task_numberRepository tasknumberRep = new dt_task_numberRepository(Context);
            IJROutBindRepository jrRepository = new JROutBindRepository(Context);
            dt_task_numberService tasknumber = new dt_task_numberService(tasknumberRep);
            try
            {//2293.0 
                //WriteLog.Info("出库物料绑定MES调我们的接口").Write("开始,任务号:" + request.TaskID + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + choose + "\t" + type + "\t" + DateTime.Now, "出库物料绑定");
                WriteLog.Info("出库物料绑定").Write($"\n{DateTime.Now}开始,{JsonConvert.SerializeObject(request)}\n", "出库物料绑定");
                if (string.IsNullOrEmpty(request.TaskID))
                {
                    dt_agvtask task = new dt_agvtask();
                    if (request.MaterialType == "空托盘")
                    {
                        PLCClient plc = WCSService.Clients.Find(v => v.PLCName == "正极提升机");
                        if (request.Devid.Contains("Z") && (choose == true || type == "空托盘"))
                        {
                            //空盘物流线001DB1002.1893.0 BOOL
                            string isZWork = plc.ReadValue(ConveyorLineInfoDBName.R_ZKPHLXLocation.ToString(), plc.PLCDescroption).ToString();
                            WriteLog.Info("空盘回流线的请求").Write("正极:" + isZWork + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + DateTime.Now, "空盘回流线的请求");
                            if (isZWork == "False")
                            {
                                choose = false;
                                type = request.MaterialType;
                                result.Code = 1;
                                result.Message = "正极空盘回流线没有请求";
                                MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "choose:" + choose + "type" + type);
                                WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束," + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + type + "\t" + DateTime.Now, "出库物料绑定");
                                return result;
                            }
                            
                            //DB1002.93.0  BOOL
                            string ZWLXWork = plc.ReadValue(ConveyorLineInfoDBName.R_ZWLX2_UPrequest.ToString(), plc.PLCDescroption).ToString();
                            SchedulerExecuteBase.GetEquipmentInfo("WLX002", "正极物流线上料请求:" + ZWLXWork, "", "", "");
                            //获取空盘回流线负极货位是否有料
                            if (bool.Parse(ZWLXWork))
                            {
                                if (request.CacheDevid.Substring(0, 2) == "ZJ")
                                {
                                    OperateResult<bool> isWork = plc.SiemensPLCClient.SiemensS7NetClient.ReadBool("DB1.102.1");
                                    if (!isWork.Content)
                                    {
                                        WriteLog.Info("出库物料绑定").Write($"\n{DateTime.Now}开始:Z正极DB1.102.1结果为" + isWork.Content, "出库物料绑定");
                                        result.Code = 1;
                                        result.Message = "当前提升机有货";
                                        return result;
                                    }
                                    var tasks = agvRepository.FindFirst(f => f.agv_toaddress == "ZJSL-WLX002" && f.agv_fromaddress == "ZJXL-KPHLX001");
                                    if (tasks != null)
                                    {
                                        choose = false;
                                        type = request.MaterialType;
                                        result.Code = 1;
                                        result.Message = "AGV有正极物流线的任务";
                                        MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "choose:" + choose + "type" + type);
                                        WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束,任务号:" + task.agv_tasknum + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + type + "\t" + DateTime.Now, "出库物料绑定");
                                        return result;
                                    }
                                    task = new dt_agvtask
                                    {
                                        agv_fromaddress = "ZJXL-KPHLX001",
                                        agv_toaddress = "ZJSL-WLX002"
                                    };
                                }
                                else if (request.CacheDevid.Substring(0, 2) == "FJ")
                                {
                                    OperateResult<bool> isWork = plc.SiemensPLCClient.SiemensS7NetClient.ReadBool("DB1.114.1");
                                    if (!isWork.Content)
                                    {
                                        WriteLog.Info("出库物料绑定").Write($"\n{DateTime.Now}开始:Z负极DB1.114.1结果为" + isWork.Content, "出库物料绑定");
                                        result.Code = 1;
                                        result.Message = "当前提升机有货";
                                        return result;
                                    }
                                    var tasks = agvRepository.FindFirst(f => f.agv_toaddress == "FJSL-WLX002" && f.agv_fromaddress == "ZJXL-KPHLX001");
                                    if (tasks != null)
                                    {
                                        choose = false;
                                        type = request.MaterialType;
                                        result.Code = 1;
                                        result.Message = "AGV有负极物流线的任务";
                                        MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "choose:" + choose + "type" + type);
                                        WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束,任务号:" + task.agv_tasknum + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + type + "\t" + DateTime.Now, "出库物料绑定");
                                        return result;
                                    }
                                    task = new dt_agvtask
                                    {
                                        agv_fromaddress = "ZJXL-KPHLX001",
                                        agv_toaddress = "FJSL-WLX002"
                                    };
                                }
                                task.agv_materielid = request.MaterialType;
                                task.agv_qty = 1;
                                task.agv_tasknum = "KH-" + tasknumber.GetTaskNumber(tasknumberRep);
                                task.agv_grade = 1;
                                task.agv_materbarcode = "";
                                task.agv_barcode = "";
                                task.agv_code = "负极2号AGV";
                                task.agv_createtime = DateTime.Now;
                                task.agv_taskstate = "Create";
                                task.agv_tasktype = "TaskType_Outbound";
                                task.agv_userid = "WCS";
                                task.agv_worktype = 2;
                                agvRepository.Add(task, true);
                                choose = true;
                                type = "";
                                result.Code = 0;
                                MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "choose:" + choose + "type" + type);
                                WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束,任务号:" + task.agv_tasknum + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + DateTime.Now, "出库物料绑定");
                            }
                            else
                            {
                                choose = false;
                                type = request.MaterialType;
                                result.Code = 1;
                                result.Message = "物流线没有请求";
                                MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "choose:" + choose + "type" + type);
                                WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束,任务号:" + task.agv_tasknum + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + type + "\t" + DateTime.Now, "出库物料绑定");
                            }
                        }
                        else if (request.Devid.Contains("F") && (choose == true || type == "空托盘"))
                        {
                            //DB1002.2293.0 BOOL
                            string isZWork = plc.ReadValue(ConveyorLineInfoDBName.R_FKPHLXLocation.ToString(), plc.PLCDescroption).ToString();
                            WriteLog.Info("空盘回流线的请求").Write("负极:" + isZWork + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + DateTime.Now, "空盘回流线的请求");
                            if (isZWork == "False")
                            {
                                choose = false;
                                type = request.MaterialType;
                                result.Code = 1;
                                result.Message = "负极空盘回流线没有请求";
                                MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "choose:" + choose + "type" + type);
                                WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束," + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + type + "\t" + DateTime.Now, "出库物料绑定");
                                return result;
                            }
                            //DB1002.1293.0 BOOL
                            string FWLXWork = plc.ReadValue(ConveyorLineInfoDBName.R_FWLX2_UPrequest.ToString(), plc.PLCDescroption).ToString();
                            SchedulerExecuteBase.GetEquipmentInfo("WLX002", "负极物流线上料请求:" + FWLXWork, "", "", "");
                            //获取空盘回流线负极货位是否有料
                            if (bool.Parse(FWLXWork))
                            {
                                if (request.CacheDevid.Substring(0, 2) == "ZJ")
                                {
                                    OperateResult<bool> isWork = plc.SiemensPLCClient.SiemensS7NetClient.ReadBool("DB1.102.1");
                                    if (!isWork.Content)
                                    {
                                        WriteLog.Info("出库物料绑定").Write($"\n{DateTime.Now}开始:F正极DB1.102.1结果为" + isWork.Content, "出库物料绑定");
                                        result.Code = 1;
                                        result.Message = "当前提升机有货";
                                        return result;
                                    }
                                    var tasks = agvRepository.FindFirst(f => f.agv_toaddress == "ZJSL-WLX002" && f.agv_fromaddress== "FJXL-KPHLX001");
                                    if (tasks != null)
                                    {
                                        choose = false;
                                        type = request.MaterialType;
                                        result.Code = 1;
                                        result.Message = "AGV有正极物流线的任务";
                                        MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "choose:" + choose + "type" + type);
                                        WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束,任务号:" + task.agv_tasknum + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + type + "\t" + DateTime.Now, "出库物料绑定");
                                        return result;
                                    }
                                    task = new dt_agvtask
                                    {
                                        agv_fromaddress = "FJXL-KPHLX001",
                                        agv_toaddress = "ZJSL-WLX002"
                                    };
                                }
                                else if (request.CacheDevid.Substring(0, 2) == "FJ")
                                {
                                    OperateResult<bool> isWork = plc.SiemensPLCClient.SiemensS7NetClient.ReadBool("DB1.114.1");
                                    if (!isWork.Content)
                                    {
                                        WriteLog.Info("出库物料绑定").Write($"\n{DateTime.Now}开始:F正极DB1.114.1结果为" + isWork.Content, "出库物料绑定");
                                        result.Code = 1;
                                        result.Message = "当前提升机有货";
                                        return result;
                                    }
                                    var tasks = agvRepository.FindFirst(f => f.agv_toaddress == "FJSL-WLX002" && f.agv_fromaddress == "FJXL-KPHLX001");
                                    if (tasks != null)
                                    {
                                        choose = false;
                                        type = request.MaterialType;
                                        result.Code = 1;
                                        result.Message = "AGV有负极物流线的任务";
                                        MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "choose:" + choose + "type" + type);
                                        WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束,任务号:" + task.agv_tasknum + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + type + "\t" + DateTime.Now, "出库物料绑定");
                                        return result;
                                    }
                                    task = new dt_agvtask
                                    {
                                        agv_fromaddress = "FJXL-KPHLX001",
                                        agv_toaddress = "FJSL-WLX002"
                                    };
                                }
                                task.agv_materielid = request.MaterialType;
                                task.agv_qty = 1;
                                task.agv_tasknum = "KH-" + tasknumber.GetTaskNumber(tasknumberRep);
                                task.agv_grade = 1;
                                task.agv_materbarcode = "";
                                task.agv_barcode = "";
                                task.agv_code = "负极2号AGV";
                                task.agv_createtime = DateTime.Now;
                                task.agv_taskstate = "Create";
                                task.agv_tasktype = "TaskType_Outbound";
                                task.agv_userid = "WCS";
                                task.agv_worktype = 2;
                                agvRepository.Add(task, true);
                                choose = true;
                                type = "";
                                result.Code = 0;
                                MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "choose:" + choose + "type" + type);
                                WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束,任务号:" + task.agv_tasknum + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + DateTime.Now, "出库物料绑定");
                            }
                            else
                            {
                                choose = false;
                                type = request.MaterialType;
                                result.Code = 1;
                                result.Message = "物流线没有请求 ";
                                MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "choose:" + choose + "type" + type);
                                WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束,任务号:" + task.agv_tasknum + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + type + "\t" + DateTime.Now, "出库物料绑定");
                            }
                        }
                    }
                    else if (request.MaterialType == "隔膜空托盘")
                    {
                        PLCClient tsjplc = WCSService.Clients.Find(v => v.PLCName == "正极提升机");
                        if (request.Devid.Contains("Z") && (choose == true || type == "隔膜空托盘"))
                        {
                            string isZWork = tsjplc.ReadValue(ConveyorLineInfoDBName.R_ZKPHLXLocation.ToString(), tsjplc.PLCDescroption).ToString();
                            WriteLog.Info("空盘回流线的请求").Write("正极:" + isZWork + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + DateTime.Now, "空盘回流线的请求");
                            if (isZWork == "False")
                            {
                                choose = false;
                                type = request.MaterialType;
                                result.Code = 1;
                                result.Message = "正极空盘回流线没有请求";
                                MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "choose:" + choose + "type" + type);
                                WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束," + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + type + "\t" + DateTime.Now, "出库物料绑定");
                                return result;
                            }
                            string isZGMWork = tsjplc.ReadValue(ConveyorLineInfoDBName.R_ZGMWork.ToString(), tsjplc.PLCDescroption).ToString();
                            string isZState = tsjplc.ReadValue(ConveyorLineInfoDBName.R_ZGMState.ToString(), tsjplc.PLCDescroption).ToString();
                            //获取空盘回流线负极货位是否有料
                            if (bool.Parse(isZGMWork) && int.Parse(isZState) == 1)
                            {
                                task = new dt_agvtask
                                {
                                    agv_fromaddress = "ZJXL-KPHLX001",
                                    agv_toaddress = "GMSL-LJHCX001"
                                };
                                task.agv_materielid = request.MaterialType;
                                task.agv_qty = 1;
                                task.agv_tasknum = "KH-" + tasknumber.GetTaskNumber(tasknumberRep);
                                task.agv_grade = 1;
                                task.agv_materbarcode = "";
                                task.agv_barcode = "";
                                task.agv_code = "负极2号AGV";
                                task.agv_createtime = DateTime.Now;
                                task.agv_taskstate = "Create";
                                task.agv_tasktype = "TaskType_Outbound";
                                task.agv_userid = "WCS";
                                task.agv_worktype = 2;
                                agvRepository.Add(task, true);
                                result.Code = 0;
                                choose = true;
                                type = "";
                                MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "choose:" + choose + "type" + type);
                                WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束,任务号:" + task.agv_tasknum + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + DateTime.Now, "出库物料绑定");
                            }
                            else
                            {
                                choose = false;
                                type = request.MaterialType;
                                result.Code = 1;
                                result.Message = "隔膜缓存线没有请求 ";
                                MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "choose:" + choose + "type" + type);
                                WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束,任务号:" + task.agv_tasknum + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + type + "\t" + DateTime.Now, "出库物料绑定");
                            }
                        }
                        else if (request.Devid.Contains("F") && (choose == true || type == "隔膜空托盘"))
                        {
                            string isZWork = tsjplc.ReadValue(ConveyorLineInfoDBName.R_FKPHLXLocation.ToString(), tsjplc.PLCDescroption).ToString();
                            WriteLog.Info("空盘回流线的请求").Write("负极:" + isZWork + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + DateTime.Now, "空盘回流线的请求");
                            if (isZWork == "False")
                            {
                                choose = false;
                                type = request.MaterialType;
                                result.Code = 1;
                                result.Message = "负极空盘回流线没有请求";
                                MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "choose:" + choose + "type" + type);
                                WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束," + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + type + "\t" + DateTime.Now, "出库物料绑定");
                                return result;
                            }
                            string isFGMWork = tsjplc.ReadValue(ConveyorLineInfoDBName.R_FGMWork.ToString(), tsjplc.PLCDescroption).ToString();
                            string isFState = tsjplc.ReadValue(ConveyorLineInfoDBName.R_FGMState.ToString(), tsjplc.PLCDescroption).ToString();
                            //获取空盘回流线负极货位是否有料
                            if (bool.Parse(isFGMWork) && int.Parse(isFState) == 1)
                            {
                                task = new dt_agvtask
                                {
                                    agv_fromaddress = "FJXL-KPHLX001",
                                    agv_toaddress = "GMSL-LJHCX002",
                                };
                                task.agv_materielid = request.MaterialType;
                                task.agv_qty = 1;
                                task.agv_tasknum = "KH-" + tasknumber.GetTaskNumber(tasknumberRep);
                                task.agv_grade = 1;
                                task.agv_materbarcode = "";
                                task.agv_barcode = "";
                                task.agv_code = "负极2号AGV";
                                task.agv_createtime = DateTime.Now;
                                task.agv_taskstate = "Create";
                                task.agv_tasktype = "TaskType_Outbound";
                                task.agv_userid = "WCS";
                                task.agv_worktype = 2;
                                agvRepository.Add(task, true);
                                choose = true;
                                type = "";
                                result.Code = 0;
                                MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "choose:" + choose + "type" + type);
                                WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束,任务号:" + task.agv_tasknum + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + DateTime.Now, "出库物料绑定");
                            }
                            else
                            {
                                choose = false;
                                type = request.MaterialType;
                                result.Code = 1;
                                result.Message = "隔膜缓存线没有请求";
                                MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "choose:" + choose + "type" + type);
                                WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束,任务号:" + task.agv_tasknum + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + type + "\t" + DateTime.Now, "出库物料绑定");
                            }
                        }
                    }
                    else
                    {
                        if (choose == true)
                        {
                            task = new dt_agvtask()
                            {
                                agv_materbarcode = request.MaterialType,
                                agv_barcode = "",
                                agv_code = "负极2号AGV",
                                agv_createtime = DateTime.Now,
                                agv_fromaddress = request.Devid,
                                agv_grade = 1,
                                agv_materielid = "",
                                agv_qty = 1,
                                agv_tasknum = "KH-" + tasknumber.GetTaskNumber(tasknumberRep),
                                agv_taskstate = "Create",
                                agv_tasktype = "TaskType_Outbound",
                                agv_toaddress = request.BarCode,
                                agv_userid = "WCS",
                                agv_worktype = 1
                            };
                            agvRepository.Add(task, true);
                            choose = true;
                            result.Code = 0;
                            MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "choose:" + choose + "type" + type);
                            WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束,任务号:" + task.agv_tasknum + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + DateTime.Now, "出库物料绑定");
                        }
                        else
                        {
                            choose = false;
                            result.Code = 1;
                            result.Message = "choose:" + choose.ToString();
                            MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message + "type" + type);
                            WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束,任务号:" + task.agv_tasknum + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + request.CacheDevid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + type + "\t" + DateTime.Now, "出库物料绑定");
                        }
                    }
                }
                else
                {
                    if (request.TaskID.Contains("GH-")) { request.TaskID = request.TaskID.Remove(0, 3); }
                    var agvtask = agvRepository.FindFirst(v => v.agv_tasknum == request.TaskID);
                    if (agvtask == null)
                    {
                        if (request.Devid.Contains("FBT"))
                        {
                            MESback WMSbackresult = new MESback();
                            WMSbackresult = MESAPIInvoke.OutStockMaterMove(request.Devid, request.MaterialType, 4, request.sum);
                            if (WMSbackresult.Code > 0) { result.Code = 1; result.Message = "分拨台出库确认搬走接口MES不通过"; return result; }
                        }
                        result.Code = 0;
                        result.Message = "未查询到当前任务号的信息";
                        MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message);
                        WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束,任务号:" + request.TaskID + "\t" + "物料类型:" +
                            request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" +
                            "缓存架编号:" + request.Devid + "\t" + "反馈结果:" + result.Code + "\t" +
                            "反馈信息:" + result.Message + "\t" + DateTime.Now, "出库物料绑定");
                        return result;
                    }
 
                    if (agvtask.agv_toaddress == "nou" && agvtask.agv_fromaddress == "nou")
                    {
                        var location = locRepository.FindFirst(v => v.upper_code == request.Devid || v.down_code == request.Devid);
                        if (location == null)
                        {
                            result.Message = "未查询到当前任务的货位信息";
                            result.Code = 1;
                            MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message);
                            WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束1,任务号:" + request.TaskID + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + DateTime.Now, "出库物料绑定");
                            return result;
                        }
                        location.location_state = LocationStateEnum.LocationState_Stored.ToString();
                        locRepository.Update(location, true);
                        if (request.Devid.Contains("Z"))
                        {
                            agvtask.agv_toaddress = "ZJSL-WLX001";
                        }
                        else
                        {
                            agvtask.agv_toaddress = "FJSL-WLX001";
                        }
                        var stock = groupRepository.FindFirst(v => v.BarCode == request.BarCode);
                        if (stock == null)
                        {
                            bill_group_stock bill_Group = new bill_group_stock()
                            {
                                Remark1 = agvtask.agv_remark,
                                first_tb = 1,
                                TB_Status = request.Devid.Contains("TB") ? request.MaterialStatus : "",
                                BarCode = request.BarCode,
                                GY_Status = request.Devid.Contains("GY") ? request.MaterialStatus : "",
                                created_time = DateTime.Now,
                                created_user = "admin",
                                stock_id = new Guid(),
                                FQ_Status = request.Devid.Contains("FQ") || request.Devid.Contains("ZZLJ") ? request.MaterialStatus : "",
                                location_id = location.id,
                                MaterialType = request.MaterialType,
                                MaterialStatus = request.MaterialStatus == null || request.MaterialStatus == "" ? "" : request.MaterialStatus,
                                QX_Status = request.Devid.Contains("QX") ? request.MaterialStatus : "",
                                updated_time = DateTime.Now,
                                updated_user = "admin"
                            };
                            groupRepository.Add(bill_Group, true);
                        }
                        else
                        {
                            stock.MaterialStatus = request.MaterialStatus;
                            stock.MaterialType = request.MaterialType;
                            stock.location_id = location.id;
                            stock.Remark1 = agvtask.agv_remark;
                            groupRepository.Update(stock, true);
                        }
                        agvtask.agv_fromaddress = request.Devid;
                        agvtask.agv_taskstate = "Create";
                        agvtask.agv_materbarcode = request.BarCode;
                        agvtask.agv_materielid = request.MaterialType;
                        agvRepository.Update(agvtask, true);
                        result.Code = 0;
                        MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message);
                        WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束,任务号:" + request.TaskID + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + DateTime.Now, "出库物料绑定");
                    }
                    else if (agvtask.agv_toaddress.Contains("JR"))
                    {
                        string barcodes = "";
                        for (int i = 0; i < request.BarCodes.Count(); i++)
                        {
                            barcodes = request.BarCodes[i] + ",";
                            WriteLog.Info("MES卷绕绑定条码").Write("卷绕绑定条码:" + request.Devid + "\t" + request.BarCodes[i] + DateTime.Now, "MES卷绕绑定条码");
                        }
 
                        /*2023.8.2新增 冠宏传递卷绕长度*/
                        agvtask.size = request.size;
                        agvRepository.Update(agvtask, true);
                        WriteLog.Info("卷绕size").Write($"冠宏MES请求:{JsonConvert.SerializeObject(request)}", "卷绕size");
 
                        WebResponseContent content = new WebResponseContent();
                        jrRepository.DbContextBeginTransaction(() =>
                        {
                            var bind = jrRepository.FindFirst(f => f.Devid == request.Devid);
                            bind.barcode = request.BarCode;
                            bind.Devid = request.Devid;
                            bind.materialtype = request.MaterialType;
                            bind.sum = request.sum;
                            bind.taskid = request.TaskID;
                            bind.barcodes = barcodes;
                            bind.size = request.size;
                            jrRepository.Update(bind, true);
                            result.Code = 0;
                            MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message);
                            WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束2,任务号:" + request.TaskID + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + "数量:" + request.sum + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + DateTime.Now, "出库物料绑定");
                            return WebResponseContent.Instance.OK();
                        });
 
                    }
                    else if (agvtask.agv_toaddress.Contains("SB"))
                    {
                        var loc = locRepository.FindFirst(f => f.down_code == request.Devid || f.upper_code == request.Devid);
                        var stock = groupRepository.FindFirst(f => f.BarCode == request.BarCode);
                        if (stock == null)
                        {
                            bill_group_stock bill_Group_Stock = new bill_group_stock()
                            {
                                BarCode = request.BarCode,
                                created_time = DateTime.Now,
                                MaterialStatus = request.MaterialStatus,
                                MaterialType = request.MaterialType,
                                location_id = loc.id,
                                Remark1 = agvtask.agv_remark,
                                stock_id = new Guid(),
                                updated_time = DateTime.Now,
                                updated_user = "admin",
                                created_user = "admin",
                                GY_Status = "",
                                FQ_Status = "",
                                QX_Status = "",
                                TB_Status = "",
                                first_tb = 1
                            };
                            groupRepository.Add(bill_Group_Stock, true);
                        }
                        else
                        {
                            stock.GY_Status = "";
                            stock.FQ_Status = "";
                            stock.QX_Status = "";
                            stock.TB_Status = "";
                            stock.MaterialStatus = request.MaterialStatus;
                            stock.MaterialType = request.MaterialType;
                            stock.location_id = loc.id;
                            groupRepository.Update(stock, true);
                        }
                        agvtask.agv_fromaddress = request.Devid;
                        agvtask.agv_taskstate = "Create";
                        agvtask.agv_materbarcode = request.BarCode;
                        agvtask.agv_materielid = request.MaterialType;
                        agvRepository.Update(agvtask, true);
                        result.Code = 0;
                        MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message);
                        WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束3,任务号:" + request.TaskID + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + DateTime.Now, "出库物料绑定");
                    }
                    else if (agvtask.agv_toaddress.Contains("HCJ") || agvtask.agv_toaddress.Contains("ZZLJ"))
                    {
                        var location = locRepository.FindFirst(v => v.down_code == agvtask.agv_toaddress || v.upper_code == agvtask.agv_toaddress);
                        var loc = locRepository.FindFirst(f => f.down_code == request.Devid || f.upper_code == request.Devid);
                        if (location == null)
                        {
                            result.Message = "未查询到当前任务的货位信息";
                            result.Code = 1;
                            MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message);
                            WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束,任务号:" + request.TaskID + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + DateTime.Now, "出库物料绑定");
                            return result;
                        }
                        if (!request.MaterialType.Contains("空托盘"))
                        {
                            var stock = groupRepository.FindFirst(f => f.BarCode == request.BarCode);
                            if (stock == null)
                            {
                                bill_group_stock bill_Group_Stock = new bill_group_stock()
                                {
                                    BarCode = request.BarCode,
                                    created_time = DateTime.Now,
                                    location_id = loc.id,
                                    MaterialStatus = request.MaterialStatus,
                                    MaterialType = request.MaterialType,
                                    Remark1 = agvtask.agv_remark,
                                    stock_id = new Guid(),
                                    updated_time = DateTime.Now,
                                    updated_user = "admin",
                                    created_user = "admin",
                                    GY_Status = "",
                                    FQ_Status = "",
                                    QX_Status = "",
                                    TB_Status = "",
                                    first_tb = 1
                                };
                                groupRepository.Add(bill_Group_Stock, true);
                            }
                            else
                            {
                                stock.GY_Status = "";
                                stock.FQ_Status = "";
                                stock.QX_Status = "";
                                stock.TB_Status = "";
                                stock.MaterialStatus = request.MaterialStatus;
                                stock.MaterialType = request.MaterialType;
                                stock.location_id = loc.id;
                                groupRepository.Update(stock, true);
                            }
                        }
                        agvtask.agv_fromaddress = request.Devid;
                        agvtask.agv_taskstate = "Create";
                        agvtask.agv_materbarcode = request.BarCode;
                        agvtask.agv_materielid = request.MaterialType;
                        agvRepository.Update(agvtask, true);
                        result.Code = 0;
                        MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message);
                        WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束4,任务号:" + request.TaskID + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + DateTime.Now, "出库物料绑定");
                    }
                }
            }
            catch (Exception ex)
            {
                result.Code = 1;
                result.Message = ex.Message;
                MESAPIInvoke.GetInterfaceInfo("OutStockMaterBind", request.TaskID, request.Devid, result.Code, result.Message);
                WriteLog.Info("出库物料绑定MES调我们的接口").Write("异常,任务号:" + request.TaskID + "\t" + "物料类型:" + request.MaterialType + "\t" + "物料状态" + request.MaterialStatus + "\t" + "物料条码" + request.BarCode + "\t" + "缓存架编号:" + request.Devid + "\t" + "反馈结果:" + result.Code + "\t" + "反馈信息:" + result.Message + "\t" + DateTime.Now, "出库物料绑定");
            }
            return result;
        }
 
        public static ResultMaterstateUp UpdateAGVTaskState(MEStockMaterBindRequest request)
        {
            ResultMaterstateUp responseContent = new ResultMaterstateUp();
            try
            {
                VOLContext Context = new VOLContext();
                UserContext userContext=new UserContext();
                Idt_task_numberRepository tasknumberRep = new dt_task_numberRepository(Context);
                dt_task_numberService tasknumber = new dt_task_numberService(tasknumberRep);
                Ibase_ware_locationRepository locationRepository = new base_ware_locationRepository(Context);
                Ibase_routing_tableRepository routingRepository = new base_routing_tableRepository(Context);
                Ibill_pda_groupdiskRepository pdaRepository = new bill_pda_groupdiskRepository(Context);
                Idt_agvtaskRepository agvtaskRepository = new dt_agvtaskRepository(Context);
                Ibill_group_stockRepository group_StockRepository = new bill_group_stockRepository(Context);
                Idt_agvtask_htyRepository agvtask_HtyRepository = new dt_agvtask_htyRepository(Context);
                var agvTask = agvtaskRepository.FindFirst(v => v.agv_tasknum == request.TaskID);
                WriteLog.Info("手动完成任务").Write("UpdateAGVTaskState,任务号:" + agvTask.agv_tasknum + DateTime.Now, "手动完成任务");
                if (agvTask == null)
                {
                    throw new Exception(string.Format("未查询到手动完成任务:" + request.TaskID));
                    responseContent.Code = 1;
                    return responseContent;
                }
                if (userContext.UserName=="ME1")
                {
                    if (agvTask.agv_code=="负极1号AGV"|| agvTask.agv_code == "正极1号AGV")
                    {
 
                    }
                    else { 
                        throw new Exception(string.Format($"账号【{userContext.UserName}】无权限完成【{agvTask.agv_code}】AGV任务" + request.TaskID)); }
                }
                else if (userContext.UserName == "ME3")
                {
                    if (agvTask.agv_code == "负极2号AGV" || agvTask.agv_code == "正极2号AGV")
                    {
 
                    }
                    else
                    {
                        throw new Exception(string.Format($"账号【{userContext.UserName}】无权限完成【{agvTask.agv_code}】AGV任务" + request.TaskID));
                    }
                }
                else
                {
                    throw new Exception(string.Format($"账号【{userContext.UserName}】无权限完成【{agvTask.agv_code}】AGV任务" + request.TaskID));
                }
                PLCClient plcClient = WCSService.Clients.Find(v => v.PLCName == agvTask.agv_code);
                //起点货位改为空
                var fromloc = locationRepository.FindFirst(f => f.upper_code == agvTask.agv_fromaddress || f.down_code == agvTask.agv_fromaddress);
                if (fromloc != null)
                {
                    fromloc.location_state = LocationStateEnum.LocationState_Empty.ToString();
                    locationRepository.Update(fromloc, true);
                }
                //如果是设备就不用更改,是缓存架货位状态为已存储,(库存表)location_id=(货位表)的货位
                base_ware_location location = locationRepository.FindFirst(f => f.upper_code == agvTask.agv_toaddress || f.down_code == agvTask.agv_toaddress);
                bill_group_stock stock = new bill_group_stock();
                if (agvTask.agv_fromaddress.Contains("0201") && agvTask.agv_toaddress.Contains("ZZLJ"))
                {
                    location.location_state = LocationStateEnum.LocationState_Stored.ToString();
                    locationRepository.Update(location, true);
                }
                else if (agvTask.agv_fromaddress.Contains("WLX") && agvTask.agv_toaddress.Contains("0101"))
                {
                    location.location_state = LocationStateEnum.LocationState_Stored.ToString();
                    locationRepository.Update(location, true);
                    MESback WMSbackresult = MESAPIInvoke.InStockMaterBind(agvTask.agv_toaddress, "空托盘", agvTask.agv_tasknum, "OK", 3);
                    if (WMSbackresult.Code > 0)
                    {
                        responseContent.Code = 1;
                        responseContent.Message = WMSbackresult.Message;
                        WriteLog.Info("手动完成任务").Write("手动完成任务失败,任务号:" + agvTask.agv_tasknum + responseContent.Message + DateTime.Now, "手动完成任务");
                        return responseContent;
                    }
                }
                else if (agvTask.agv_toaddress.Contains("JR"))
                {
                    if (agvTask.agv_taskstate == AGVTaskStateEnum.Complete.ToString())
                    {
                        var iswork = agvtaskRepository.FindFirst(f => f.agv_remark == "true" && f.agv_tasknum == agvTask.agv_tasknum);
                        if (iswork != null)
                        {
                            MESback WMSbackresult = new MESback();
                            WMSbackresult = MESAPIInvoke.OutStockMaterMove(agvTask.agv_fromaddress, agvTask.agv_materielid, 4, Convert.ToInt32(iswork.agv_qty), agvTask.agv_tasknum);
                            if (WMSbackresult.Code > 0) { new Exception(WMSbackresult.Message); }
                        }
                    }
 
                }
                else if (agvTask.agv_toaddress.Contains("HXWLX"))
                { //如果是进烘箱的任务,需要告诉WMS两个进烘箱物料的条码和位置,需要问胡工怎么给他值
                    if (agvTask.agv_fromaddress.Contains("KPHLX"))
                    {
                        var materials = WebApiHelper.ParseFromJson<List<BakingClass>>(agvTask.agv_materbarcode);
                        MESback WMSbackresult = MESAPIInvoke.BakingFeedingBinding(agvTask.agv_toaddress, materials);
                        if (WMSbackresult.Code > 0) { new Exception(WMSbackresult.Message); }
                    }
                    else
                    {
                        WebResponseContent content = new WebResponseContent();
                        content = group_StockRepository.DbContextBeginTransaction(() =>
                          {
                              var materbarcode = agvTask.agv_materbarcode.Split(";");
                              List<BakingClass> materials = new List<BakingClass>();
                              for (int i = 0; i < materbarcode.Count(); i++)
                              {
                                  BakingClass bakingClass = new BakingClass();
                                  stock = group_StockRepository.Find(f => f.BarCode == materbarcode[i]).OrderByDescending(f => f.created_time).FirstOrDefault();
                                  bakingClass.BarCode = materbarcode[i];
                                  bakingClass.MaterialType = stock.MaterialType;
                                  materials.Add(bakingClass);
                                  group_StockRepository.Delete(stock, true);
                                  WriteLog.Info("烘烤").Write("materials" + materials[i].BarCode + "\t" + materials[i].MaterialType + "\t" + bakingClass.BarCode + "\t" + bakingClass.MaterialType + DateTime.Now, "烘烤物料条码");
                              }
                              MESback WMSbackresult = MESAPIInvoke.BakingFeedingBinding(agvTask.agv_toaddress, materials);
                              if (WMSbackresult.Code > 0) { return content = WebResponseContent.Instance.Error(WMSbackresult.Message); }
                              //如果终点地址是去烘烤箱的删除库存
                              location.location_state = LocationStateEnum.LocationState_Empty.ToString();
                              locationRepository.Update(location, true);
                              return WebResponseContent.Instance.OK();
                          });
                        if (content.Status == false)
                        {
                            responseContent.Code = 1;
                            responseContent.Message = "手动完成任务失败";
                            return responseContent;
                        }
                    }
                }
                else
                {
                    stock = group_StockRepository.FindFirst(f => f.BarCode == agvTask.agv_materbarcode);
                    if (!agvTask.agv_toaddress.Contains("SB") && !agvTask.agv_fromaddress.Contains("WLX") && !agvTask.agv_toaddress.Contains("JJK") && !agvTask.agv_toaddress.Contains("WLX"))
                    {
                        if (stock == null)
                        {
                            bill_group_stock newstock = new bill_group_stock
                            {
                                BarCode = agvTask.agv_materbarcode,
                                MaterialType = agvTask.agv_materielid,
                                MaterialStatus = agvTask.agv_materbarcode.Split('*')[6],
                                first_tb = 0,
                                location_id = location.id,
                                TB_Status = "",
                                FQ_Status = "",
                                GY_Status = "",
                                QX_Status = "",
                                created_time = DateTime.Now,
                                created_user = "WCS",
                                updated_time = DateTime.Now,
                                updated_user = "WCS"
                            };
                            group_StockRepository.Add(newstock, true);
                        }
                        else
                        {
                            stock.location_id = location.id;
                            group_StockRepository.Update(stock, true);
                        }
 
                        location.location_state = LocationStateEnum.LocationState_Stored.ToString();
                        locationRepository.Update(location, true);
                        if (agvTask.agv_toaddress.Contains("HCJ") || agvTask.agv_toaddress.Contains("CBJ") || agvTask.agv_toaddress.Contains("ZZLJ"))
                        {
                            if (stock.MaterialStatus == "OK")
                            {
                                plcClient.WriteValue(ConveyorLineInfoDBName.MaterOK.ToString(), agvTask.agv_toaddress, 0);
                            }
                            else if (stock.MaterialStatus == "nou") { }
                            else
                            {
                                plcClient.WriteValue(ConveyorLineInfoDBName.MaterNG.ToString(), agvTask.agv_toaddress, 0);
                            }
 
                        }
                        //如果终点地址是库内,需要给WMS反馈入库物料绑定
                        if (agvTask.agv_toaddress.Contains("0101"))
                        {
                            MESback WMSbackresult = MESAPIInvoke.InStockMaterBind(agvTask.agv_toaddress, agvTask.agv_materielid, agvTask.agv_materbarcode, agvTask.agv_materbarcode.Split('*')[6], 3);
                            if (WMSbackresult.Code > 0) { new Exception(WMSbackresult.Message); }
                        }
                    }
                    else if (agvTask.agv_toaddress.Contains("SB"))
                    {
                        //如果终点地址是去设备
                        location.location_state = LocationStateEnum.LocationState_Empty.ToString();
                        locationRepository.Update(location, true);
                        group_StockRepository.Delete(stock, true);
                    }
                    else if (agvTask.agv_toaddress.Contains("WLX"))
                    {
                        if (agvTask.agv_code.Contains("正"))
                        {
                            //添加物料条码,三楼输送线出口取前两个条码
                            var barcode = tasknumberRep.FindFirst(v => v.taskno == 1);
                            barcode.numtype = barcode.numtype + agvTask.agv_materbarcode + ";";
                            tasknumberRep.Update(barcode, true);
                        }
                        else
                        {
                            //添加物料条码,三楼输送线出口取前两个条码
                            var barcode = tasknumberRep.FindFirst(v => v.taskno == 2);
                            barcode.numtype = barcode.numtype + agvTask.agv_materbarcode + ";";
                            tasknumberRep.Update(barcode, true);
                        }
                    }
                    else if (agvTask.agv_toaddress.Contains("JJK"))
                    {
                        if (stock.MaterialStatus == "OK")
                        {
                            plcClient.WriteValue(ConveyorLineInfoDBName.MaterOK.ToString(), agvTask.agv_toaddress, 0);
                        }
                        else
                        {
                            plcClient.WriteValue(ConveyorLineInfoDBName.MaterNG.ToString(), agvTask.agv_toaddress, 0);
                        }
                        if (agvTask.agv_toaddress.Contains("Z"))
                        {
                            MESback WMSbackresult = MESAPIInvoke.InStockMaterBind(agvTask.agv_toaddress, agvTask.agv_materielid, agvTask.agv_materbarcode, agvTask.agv_materbarcode.Split('*')[6], 1);
                            if (WMSbackresult.Code > 0) { new Exception(WMSbackresult.Message); }
                        }
                        else if (agvTask.agv_toaddress.Contains("F"))
                        {
                            MESback WMSbackresult = MESAPIInvoke.InStockMaterBind(agvTask.agv_toaddress, agvTask.agv_materielid, agvTask.agv_materbarcode, agvTask.agv_materbarcode.Split('*')[6], 2);
                            if (WMSbackresult.Code > 0) { new Exception(WMSbackresult.Message); }
                        }
 
                    }
                }
                agvtask_HtyRepository.AddTaskHistorys(agvTask, OperateType.ManualCompletion.ToString(),userContext.UserName);
                agvtaskRepository.Delete(agvTask, true);
                responseContent.Code = 0;
            }
            catch (Exception ex)
            {
                responseContent.Code = 1;
                responseContent.Message = ex.Message;
            }
            return responseContent;
        }
 
        public static ResultMaterstateUp DeleteAGVTaskState(MEStockMaterBindRequest request)
        {
            ResultMaterstateUp result = new ResultMaterstateUp();
            try
            {
                UserContext userContext = new UserContext();
                VOLContext Context = new VOLContext();
                WebResponseContent responseContent = new WebResponseContent();
                Idt_task_numberRepository tasknumberRep = new dt_task_numberRepository(Context);
                dt_task_numberService tasknumber = new dt_task_numberService(tasknumberRep);
                Ibase_ware_locationRepository locationRepository = new base_ware_locationRepository(Context);
                Ibase_routing_tableRepository routingRepository = new base_routing_tableRepository(Context);
                Ibill_pda_groupdiskRepository pdaRepository = new bill_pda_groupdiskRepository(Context);
                Idt_agvtaskRepository agvtaskRepository = new dt_agvtaskRepository(Context);
                Ibill_group_stockRepository group_StockRepository = new bill_group_stockRepository(Context);
                Idt_agvtask_htyRepository agvtask_HtyRepository = new dt_agvtask_htyRepository(Context);
                var agvTask = agvtaskRepository.FindFirst(v => v.agv_tasknum == request.TaskID);
                if (userContext.UserName == "ME1")
                {
                    if (agvTask.agv_code == "负极1号AGV" || agvTask.agv_code == "正极1号AGV")
                    {
 
                    }
                    else
                    {
                        throw new Exception(string.Format($"账号【{userContext.UserName}】无权限删除【{agvTask.agv_code}】AGV任务" + request.TaskID));
                    }
                }
                else if (userContext.UserName == "ME3")
                {
                    if (agvTask.agv_code == "负极2号AGV" || agvTask.agv_code == "正极2号AGV")
                    {
 
                    }
                    else
                    {
                        throw new Exception(string.Format($"账号【{userContext.UserName}】无权限删除【{agvTask.agv_code}】AGV任务" + request.TaskID));
                    }
                }
                else
                {
                    throw new Exception(string.Format($"账号【{userContext.UserName}】无权限删除【{agvTask.agv_code}】AGV任务" + request.TaskID));
                }
                PLCClient plcClient = WCSService.Clients.Find(v => v.PLCName == agvTask.agv_code);
                if (plcClient == null)
                {
                    WriteLog.Info("DeleteAGVTaskState").Write("取消任务失败," + agvTask.agv_code + "plc未连接" + "\t" + DateTime.Now, "DeleteAGVTaskState");
                    result.Code = 1;
                    result.Message = "取消任务失败";
                    return result;
                }
                plcClient.WriteValue(TaskDBName.taskID.ToString(), agvTask.agv_tasknum);
                Task.Delay(2000).Wait();
                string taskId = plcClient.ReadValue(TaskDBName.taskID.ToString()).ToString();
                if (taskId == agvTask.agv_tasknum)
                {
                    plcClient.WriteValue(TaskDBName.taskInteractiveW.ToString(), 2);
                    for (int i = 0; i < 5; i++)
                    {
                        Task.Delay(2000).Wait();
                        var agvnumber = Convert.ToInt32(plcClient.ReadValue(TaskDBName.taskInteractiveW.ToString()));
                        if (agvnumber != 2)
                        {
                            plcClient.WriteValue(TaskDBName.taskInteractiveW.ToString(), 2);
                        }
                        else
                        {
                            break;
                        }
                    }
                    Task.Delay(2000).Wait();
                    int TaskInteractive = Convert.ToInt32(plcClient.ReadValue(TaskDBName.taskInteractiveR.ToString()));
                    if (TaskInteractive == 1)
                    {
                        plcClient.WriteValue(TaskDBName.taskInteractiveW.ToString(), 0);
                        for (int i = 0; i < 5; i++)
                        {
                            Task.Delay(2000).Wait();
                            var agvnumber = Convert.ToInt32(plcClient.ReadValue(TaskDBName.taskInteractiveW.ToString()));
                            if (agvnumber != 0)
                            {
                                plcClient.WriteValue(TaskDBName.taskInteractiveW.ToString(), 0);
                            }
                            else
                            {
                                break;
                            }
                        }
                        Task.Delay(2000).Wait();
                        int TaskInteractiver = Convert.ToInt32(plcClient.ReadValue(TaskDBName.taskInteractiveR.ToString()));
                        if (TaskInteractiver == 0)
                        {
                            responseContent = agvtaskRepository.DbContextBeginTransaction(() =>
                            {
                                agvtask_HtyRepository.AddTaskHistorys(agvTask, OperateType.CancelManually.ToString(), userContext.UserName);
                             
                                WriteLog.Info("DeleteAGVTaskState").Write("DeleteAGVTaskState" + agvTask.agv_tasknum + DateTime.Now, "DeleteAGVTaskState");
                                var location = locationRepository.FindFirst(f => f.upper_code == agvTask.agv_fromaddress || f.down_code == agvTask.agv_fromaddress);
                                if (location != null)
                                {
                                    location.location_state = LocationStateEnum.LocationState_Empty.ToString();
                                    locationRepository.Update(location, true);
                                }
                                var stock = group_StockRepository.FindFirst(v => v.BarCode == agvTask.agv_materbarcode);
                                if (stock != null)
                                {
                                    group_StockRepository.Delete(stock, true);
                                }
                                var toloc = locationRepository.FindFirst(f => f.upper_code == agvTask.agv_toaddress || f.down_code == agvTask.agv_toaddress);
                                if (toloc != null)
                                {
                                    toloc.location_state = LocationStateEnum.LocationState_Empty.ToString();
                                    locationRepository.Update(toloc, true);
                                }
                                agvtaskRepository.Delete(agvTask, true);
                                result.Code = 0;
                                return WebResponseContent.Instance.OK();
                            });
                        }
                        else
                        {
                            WriteLog.Info("DeleteAGVTaskState").Write("取消任务失败,AGV的taskInteractiveR的值不为0,是" + TaskInteractiver + "\t" + DateTime.Now, "DeleteAGVTaskState");
                            result.Code = 1;
                            result.Message = "取消任务失败";
                            return result;
                        }
                    }
                    else
                    {
                        WriteLog.Info("DeleteAGVTaskState").Write("取消任务失败,AGV的taskInteractiveR的值不为1,是" + TaskInteractive + "\t" + DateTime.Now, "DeleteAGVTaskState");
                        result.Code = 1;
                        result.Message = "取消任务失败";
                        return result;
                    }
                }
                else
                {
                    WriteLog.Info("DeleteAGVTaskState").Write("取消任务失败,AGV的taskId的值与写入的taskId不一致,写入的taskId是" + agvTask.agv_tasknum + "\t" + DateTime.Now, "DeleteAGVTaskState");
                    result.Code = 1;
                    result.Message = "取消任务失败";
                    return result;
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return result;
        }
 
        public static ResulAbnormalState GetAbnormalState(AbnormalId abnormalId)
        {
            ResulAbnormalState responseContent = new ResulAbnormalState();
            try
            {
                VOLContext Context = new VOLContext();
                Idt_task_numberRepository tasknumberRep = new dt_task_numberRepository(Context);
                dt_task_numberService tasknumber = new dt_task_numberService(tasknumberRep);
                Ibase_ware_locationRepository locationRepository = new base_ware_locationRepository(Context);
                Ibase_routing_tableRepository routingRepository = new base_routing_tableRepository(Context);
                Ibill_pda_groupdiskRepository pdaRepository = new bill_pda_groupdiskRepository(Context);
                Idt_agvtaskRepository agvtaskRepository = new dt_agvtaskRepository(Context);
                Ibill_group_stockRepository group_StockRepository = new bill_group_stockRepository(Context);
                Idt_agvtask_htyRepository agvtask_HtyRepository = new dt_agvtask_htyRepository(Context);
                var agvTask = new dt_agvtask();
                if (abnormalId.taskId.Contains("GH-"))
                {
                    string taskId = abnormalId.taskId.Remove(0, 3);
                    agvTask = agvtaskRepository.FindFirst(v => v.agv_tasknum == taskId);
                }
                else
                {
                    agvTask = agvtaskRepository.FindFirst(v => v.agv_tasknum == abnormalId.taskId);
                }
                dt_agvtask newagvtask = new dt_agvtask
                {
                    agv_materbarcode = agvTask.agv_materbarcode,
                    agv_barcode = agvTask.agv_barcode,
                    agv_code = agvTask.agv_code,
                    agv_createtime = DateTime.Now,
                    agv_realesstime = DateTime.Now,
                    agv_fromaddress = agvTask.agv_fromaddress,
                    agv_grade = 1,
                    agv_materielid = agvTask.agv_materielid,
                    agv_qty = 1,
                    agv_tasknum = "KH-" + tasknumber.GetTaskNumber(tasknumberRep),
                    agv_taskstate = "WaitStockOut",
                    agv_tasktype = "TaskType_Outbound",
                    agv_toaddress = agvTask.agv_toaddress,
                    agv_userid = "WCS",
                    agv_remark = agvTask.agv_remark
                };
                if (newagvtask.agv_materielid == "空托盘")
                {
                    newagvtask.agv_worktype = 2;
                }
                else
                {
                    newagvtask.agv_worktype = 1;
                }
                //调用WMS呼叫物料出库
                if (newagvtask.agv_code == "正极1号AGV")
                {
                    //调用WMS呼叫物料出库
                    List<string> StockList = new List<string> { "ZXD0201", "ZXC0201", "ZXB0201", "ZXA0201" };
                    MESback WMSbackresult = MESAPIInvoke.OutNeedStosk(newagvtask.agv_tasknum, StockList, 3, newagvtask.agv_materielid, "", newagvtask.agv_remark);
                    if (WMSbackresult == null || WMSbackresult.Code > 0) 
                    {
                        var agvtaskold = agvtaskRepository.FindFirst(v => v.agv_fromaddress == "错误展示");
                        agvtaskold.ErrMsg = WMSbackresult.Message.ToString();
                        agvtaskold.agv_createtime = DateTime.Now;
                        agvtaskRepository.Update(agvtaskold, true);
                        throw new Exception($"失败,任务号:{newagvtask.agv_tasknum}"); 
                    }
                }
                else if (newagvtask.agv_code == "负极1号AGV")
                {
                    //调用WMS呼叫物料出库
                    List<string> StockList = new List<string> { "FXD0201", "FXC0201", "FXB0201", "FXA0201" };
                    MESback WMSbackresult = MESAPIInvoke.OutNeedStosk(newagvtask.agv_tasknum, StockList, 3, newagvtask.agv_materielid, "", newagvtask.agv_remark);
                    if (WMSbackresult == null || WMSbackresult.Code > 0) 
                    {
                        var agvtaskold = agvtaskRepository.FindFirst(v => v.agv_fromaddress == "错误展示");
                        agvtaskold.ErrMsg = WMSbackresult.Message.ToString();
                        agvtaskold.agv_createtime = DateTime.Now;
                        agvtaskRepository.Update(agvtaskold, true);
                        throw new Exception($"失败,任务号:{newagvtask.agv_tasknum}"); 
                    }
                }
                else if (newagvtask.agv_toaddress.Contains("JR") && newagvtask.agv_code == "负极2号AGV")
                {
                    List<string> StockList = new List<string> { "FJXL-FBT001", "FJXL-FBT002" };
                    MESback WMSbackresult = MESAPIInvoke.OutNeedStosk(newagvtask.agv_tasknum, StockList, 4, newagvtask.agv_materielid, "", newagvtask.agv_toaddress);
                    if (WMSbackresult == null || WMSbackresult.Code > 0) 
                    {
                        var agvtaskold = agvtaskRepository.FindFirst(v => v.agv_fromaddress == "错误展示");
                        agvtaskold.ErrMsg = WMSbackresult.Message.ToString();
                        agvtaskold.agv_createtime = DateTime.Now;
                        agvtaskRepository.Update(agvtaskold, true);
                        throw new Exception($"失败,任务号:{newagvtask.agv_tasknum}"); 
                    }
                }
                else if (newagvtask.agv_toaddress.Contains("JR") && newagvtask.agv_code == "正极2号AGV")
                {
                    List<string> StockList = new List<string> { "ZJXL-FBT001", "ZJXL-FBT002" };
                    MESback WMSbackresult = MESAPIInvoke.OutNeedStosk(newagvtask.agv_tasknum, StockList, 4, newagvtask.agv_materielid, "", newagvtask.agv_toaddress);
                    if (WMSbackresult == null || WMSbackresult.Code > 0) 
                    {
                        var agvtaskold = agvtaskRepository.FindFirst(v => v.agv_fromaddress == "错误展示");
                        agvtaskold.ErrMsg = WMSbackresult.Message.ToString();
                        agvtaskold.agv_createtime = DateTime.Now;
                        agvtaskRepository.Update(agvtaskold, true);
                        throw new Exception($"失败,任务号:{newagvtask.agv_tasknum}"); 
                    }
                }
 
                agvtaskRepository.Add(newagvtask, true);
                WriteLog.Info("GetAbnormalState").Write("GetAbnormalState" + newagvtask.agv_tasknum + DateTime.Now, "GetAbnormalState");
                agvtask_HtyRepository.AddTaskHistory(agvTask, OperateType.Abnormal.ToString());
                agvtaskRepository.Delete(agvTask, true);
                responseContent.Code = 0;
                MESAPIInvoke.GetInterfaceInfo("GetAbnormalState", abnormalId.taskId, "", responseContent.Code, responseContent.Message);
            }
            catch (Exception ex)
            {
                responseContent.Code = 1;
                responseContent.Message = ex.Message;
                MESAPIInvoke.GetInterfaceInfo("GetAbnormalState", abnormalId.taskId, "", responseContent.Code, responseContent.Message);
            }
            return responseContent;
        }
 
        public static List<LocationInfo> Getlocationwork(LocationworkRequest request)
        {
            VOLContext Context = new VOLContext();
            ResultMaterstateUp result = new ResultMaterstateUp();
            Ibase_ware_locationRepository locRepository = new base_ware_locationRepository(Context);
            List<LocationInfo> locationInfo = new List<LocationInfo>();
            try
            {
                var client = WCSService.Clients;
                PLCClient zagvplc = client.Find(v => v.PLCName == "正极1号AGV");
                PLCClient fagvplc = client.Find(v => v.PLCName == "负极1号AGV");
                if (string.IsNullOrEmpty(request.PLCDescroption))
                {
                    var cbjlocation = locRepository.Find(f => f.down_code.Contains("CBJ") || f.upper_code.Contains("ZZLJ") || f.upper_code.Contains("JJK")).Select(s => s.down_code).ToList();
                    var location = locRepository.Find(w => !w.upper_code.Contains("CBJ") && w.upper_code.Contains("HCJ")).Select(s => s.upper_code).ToList();
                    string isZWork = "";
                    foreach (var item in cbjlocation)
                    {
                        if (item.Contains("ZJSL") || item.Contains("ZJXL"))
                        {
                            LocationInfo locInfo = new LocationInfo();
                            isZWork = zagvplc.ReadValue(ConveyorLineInfoDBName.R_Location_iswork.ToString(), item).ToString();
                            locInfo.Devid = item;
                            locInfo.name = zagvplc.PLCName;
                            if (isZWork == "1")
                            {
                                isZWork = "空";
                            }
                            else if (isZWork == "2")
                            {
                                isZWork = "有货";
                            }
                            locInfo.iswork = isZWork;
                            locationInfo.Add(locInfo);
                        }
                        else
                        {
                            LocationInfo locInfo = new LocationInfo();
                            isZWork = fagvplc.ReadValue(ConveyorLineInfoDBName.R_Location_iswork.ToString(), item).ToString();
                            locInfo.Devid = item;
                            locInfo.name = fagvplc.PLCName;
                            if (isZWork == "1")
                            {
                                isZWork = "空";
                            }
                            else if (isZWork == "2")
                            {
                                isZWork = "有货";
                            }
                            locInfo.iswork = isZWork;
                            locationInfo.Add(locInfo);
                        }
                    }
                    foreach (var item in location)
                    {
                        if (item.Contains("ZJSL") || item.Contains("ZJXL"))
                        {
                            LocationInfo locInfo = new LocationInfo();
                            isZWork = zagvplc.ReadValue(ConveyorLineInfoDBName.R_Location_iswork.ToString(), item).ToString();
                            locInfo.Devid = item;
                            locInfo.name = zagvplc.PLCName;
                            if (isZWork == "1")
                            {
                                isZWork = "空";
                            }
                            else if (isZWork == "2")
                            {
                                isZWork = "有货";
                            }
                            locInfo.iswork = isZWork;
                            locationInfo.Add(locInfo);
                        }
                        else
                        {
                            LocationInfo locInfo = new LocationInfo();
                            isZWork = fagvplc.ReadValue(ConveyorLineInfoDBName.R_Location_iswork.ToString(), item).ToString();
                            locInfo.Devid = item;
                            locInfo.name = fagvplc.PLCName;
                            if (isZWork == "1")
                            {
                                isZWork = "空";
                            }
                            else if (isZWork == "2")
                            {
                                isZWork = "有货";
                            }
                            locInfo.iswork = isZWork;
                            locationInfo.Add(locInfo);
                        }
                    }
                }
                else
                {
                    var location = locRepository.Find(f => f.upper_code.Contains(request.PLCDescroption) || f.down_code.Contains(request.PLCDescroption));
                    string isZWork = "";
                    string Devid = "";
                    foreach (var item in location)
                    {
                        if (item.upper_code.Contains("ZJSL") || item.down_code.Contains("ZJXL"))
                        {
                            if (item.down_code.Contains("CBJ") || item.upper_code.Contains("ZZLJ") || item.upper_code.Contains("JJK"))
                            {
                                isZWork = zagvplc.ReadValue(ConveyorLineInfoDBName.R_Location_iswork.ToString(), item.down_code).ToString();
                                Devid = item.down_code;
                            }
                            else
                            {
                                isZWork = zagvplc.ReadValue(ConveyorLineInfoDBName.R_Location_iswork.ToString(), item.upper_code).ToString();
                                Devid = item.upper_code;
                            }
                            LocationInfo locInfo = new LocationInfo();
                            locInfo.Devid = Devid;
                            locInfo.name = zagvplc.PLCName;
                            if (isZWork == "1")
                            {
                                isZWork = "空";
                            }
                            else if (isZWork == "2")
                            {
                                isZWork = "有货";
                            }
                            locInfo.iswork = isZWork;
                            locationInfo.Add(locInfo);
                        }
                        else
                        {
                            if (item.down_code.Contains("CBJ") || item.upper_code.Contains("ZZLJ") || item.upper_code.Contains("JJK"))
                            {
                                isZWork = fagvplc.ReadValue(ConveyorLineInfoDBName.R_Location_iswork.ToString(), item.down_code).ToString();
                                Devid = item.down_code;
                            }
                            else
                            {
                                isZWork = fagvplc.ReadValue(ConveyorLineInfoDBName.R_Location_iswork.ToString(), item.upper_code).ToString();
                                Devid = item.upper_code;
                            }
                            LocationInfo locInfo = new LocationInfo();
                            locInfo.Devid = Devid;
                            locInfo.name = fagvplc.PLCName;
                            if (isZWork == "1")
                            {
                                isZWork = "空";
                            }
                            else if (isZWork == "2")
                            {
                                isZWork = "有货";
                            }
                            locInfo.iswork = isZWork;
                            locationInfo.Add(locInfo);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
 
            }
            return locationInfo;
        }
 
        public static ResultMaterstateUp DeleteTask(MESDeleteRequest request)
        {
            VOLContext Context = new VOLContext();
            ResultMaterstateUp result = new ResultMaterstateUp();
            Ibase_ware_locationRepository locRepository = new base_ware_locationRepository(Context);
            Idt_agvtaskRepository agvRepository = new dt_agvtaskRepository(Context);
            Idt_agvtask_htyRepository agvtask_HtyRepository = new dt_agvtask_htyRepository(Context);
            try
            {
                WriteLog.Info("删除任务MES调我们的接口").Write(request.taskid + "\t" + DateTime.Now, "DeleteTask");
                if (request.taskid.Contains("GH-")) { request.taskid = request.taskid.Remove(0, 3); }
                var agvtask = agvRepository.FindFirst(v => v.agv_tasknum == request.taskid);
                if (agvtask == null)
                {
                    result.Code = 0;
                    result.Message = "没有当前任务号";
                    MESAPIInvoke.GetInterfaceInfo("DeleteTask", request.taskid, "", result.Code, result.Message);
                    return result;
                }
                else
                {
                    var fromlocation = locRepository.FindFirst(f => f.down_code == agvtask.agv_fromaddress || f.upper_code == agvtask.agv_fromaddress);
                    fromlocation.location_state = LocationStateEnum.LocationState_Empty.ToString();
                    locRepository.Update(fromlocation, true);
                    var tolocation = locRepository.FindFirst(f => f.down_code == agvtask.agv_toaddress || f.upper_code == agvtask.agv_toaddress);
                    tolocation.location_state = LocationStateEnum.LocationState_Empty.ToString();
                    locRepository.Update(tolocation, true);
                    agvtask_HtyRepository.AddTaskHistory(agvtask, OperateType.Delete.ToString());
                    agvRepository.Delete(agvtask, true);
                    result.Code = 0;
                    MESAPIInvoke.GetInterfaceInfo("DeleteTask", request.taskid, "", result.Code, result.Message);
                    WriteLog.Info("出库物料绑定MES调我们的接口").Write("结束," + request.taskid + "\t" + DateTime.Now, "DeleteTask");
                }
            }
            catch (Exception ex)
            {
                result.Code = 1;
                result.Message = ex.Message;
                MESAPIInvoke.GetInterfaceInfo("DeleteTask", request.taskid, "", result.Code, result.Message);
                WriteLog.Info("删除任务MES调我们的接口").Write("异常," + request.taskid + "\t" + ex.Message + "\t" + DateTime.Now, "DeleteTask");
            }
            return result;
        }
        public static ResultMaterstateUp DeleteZHXBarCode()
        {
            ResultMaterstateUp result = new ResultMaterstateUp();
            try
            {
                VOLContext Context = new VOLContext();
                WebResponseContent responseContent = new WebResponseContent();
                Idt_task_numberRepository tasknumberRep = new dt_task_numberRepository(Context);
                Ibill_group_stockRepository group_StockRepository = new bill_group_stockRepository(Context);
                responseContent = tasknumberRep.DbContextBeginTransaction(() =>
                {
                    var barcodelist = tasknumberRep.FindFirst(v => v.taskno == 1);
                    WriteLog.Info("没有删除之前的正极烘箱条码").Write(barcodelist + "\t" + DateTime.Now, "没有删除之前的正极烘箱条码");
                    string[] BarCodelist = barcodelist.numtype.Split(";");
                    string newBarcode = "";
                    if (BarCodelist.Length <= 2)
                    {
                        barcodelist.numtype = "";
                        tasknumberRep.Update(barcodelist, true);
                        for (int i = 1; i <= BarCodelist.Length; i++)
                        {
                            var stock = group_StockRepository.FindFirst(v => v.BarCode == BarCodelist[i - 1]);
                            if (stock != null)
                            {
                                group_StockRepository.Delete(stock, true);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 2; i < BarCodelist.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(BarCodelist[i]))
                            {
                                newBarcode = newBarcode + BarCodelist[i] + ";";
                            }
                        }
                        barcodelist.numtype = newBarcode;
                        tasknumberRep.Update(barcodelist, true);
                        var stock1 = group_StockRepository.FindFirst(v => v.BarCode == BarCodelist[0]);
                        if (stock1 != null)
                        {
                            group_StockRepository.Delete(stock1, true);
                        }
                        var stock2 = group_StockRepository.FindFirst(v => v.BarCode == BarCodelist[1]);
                        if (stock2 != null)
                        {
                            group_StockRepository.Delete(stock2, true);
                        }
 
                    }
                    result.Code = 0;
                    return WebResponseContent.Instance.OK();
                });
            }
            catch (Exception ex)
            {
                throw;
            }
            return result;
        }
        public static ResultMaterstateUp DeleteFHXBarCode()
        {
            ResultMaterstateUp result = new ResultMaterstateUp();
            try
            {
                VOLContext Context = new VOLContext();
                WebResponseContent responseContent = new WebResponseContent();
                Idt_task_numberRepository tasknumberRep = new dt_task_numberRepository(Context);
                Ibill_group_stockRepository group_StockRepository = new bill_group_stockRepository(Context);
                responseContent = tasknumberRep.DbContextBeginTransaction(() =>
                {
                    var barcodelist = tasknumberRep.FindFirst(v => v.taskno == 2);
                    WriteLog.Info("没有删除之前的负极烘箱条码").Write(barcodelist + "\t" + DateTime.Now, "没有删除之前的负极烘箱条码");
                    string[] BarCodelist = barcodelist.numtype.Split(";");
                    string newBarcode = "";
                    if (BarCodelist.Length <= 2)
                    {
                        barcodelist.numtype = "";
                        tasknumberRep.Update(barcodelist, true);
                        for (int i = 1; i <= BarCodelist.Length; i++)
                        {
                            var stock = group_StockRepository.FindFirst(v => v.BarCode == BarCodelist[i - 1]);
                            if (stock != null)
                            {
                                group_StockRepository.Delete(stock, true);
                            }
                        }
                    }
                    else
                    {
                        for (int i = 2; i < BarCodelist.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(BarCodelist[i]))
                            {
                                newBarcode = newBarcode + BarCodelist[i] + ";";
                            }
                        }
                        barcodelist.numtype = newBarcode;
                        tasknumberRep.Update(barcodelist, true);
                        var stock1 = group_StockRepository.FindFirst(v => v.BarCode == BarCodelist[0]);
                        if (stock1 != null)
                        {
                            group_StockRepository.Delete(stock1, true);
                        }
                        var stock2 = group_StockRepository.FindFirst(v => v.BarCode == BarCodelist[1]);
                        if (stock2 != null)
                        {
                            group_StockRepository.Delete(stock2, true);
                        }
                    }
                    result.Code = 0;
                    return WebResponseContent.Instance.OK();
                });
            }
            catch (Exception ex)
            {
                throw;
            }
            return result;
        }
 
        public static WebResponseContent AddHKOneTask(string HKNo) 
        {
            VOLContext Context = new VOLContext();
            Idt_agvtaskRepository agvRepository = new dt_agvtaskRepository(Context);
            Ibase_routing_tableRepository routingRepository = new base_routing_tableRepository(Context);
            Idt_task_numberRepository tasknumberRep = new dt_task_numberRepository(Context);
            dt_task_numberService tasknumber = new dt_task_numberService(tasknumberRep);
            WebResponseContent responseContent = new WebResponseContent();
            try
            {
                PLCClient plc = WCSService.Clients.Find(v => v.PLCName == HKNo);
                if (plc == null)
                    throw new Exception(string.Format("{0}PLC为连接", HKNo));
 
                var task = new List<dt_agvtask>();
                if (plc.PLCDescroption.Contains("ZJSL"))
                {
                    task = agvRepository.Find(f => f.agv_toaddress.Contains("ZJSL-GMHX")).ToList();
                }
                else
                {
                    task = agvRepository.Find(f => f.agv_toaddress.Contains("FJSL-GMHX")).ToList();
                }
                if (task.Count >= 1)
                    throw new Exception("当前存在任务");
                //获取隔膜烘箱上料请求
                string isWork = plc.ReadValue(ConveyorLineInfoDBName.R_HKSB_UPrequest.ToString(), plc.PLCDescroption).ToString();
                PLCClient hcxplc = WCSService.Clients.Find(v => v.PLCName == "正极提升机");
                string isZGMWork = hcxplc.ReadValue(ConveyorLineInfoDBName.R_ZGMWork.ToString(), hcxplc.PLCDescroption).ToString();
                string isFGMWork = hcxplc.ReadValue(ConveyorLineInfoDBName.R_FGMWork.ToString(), hcxplc.PLCDescroption).ToString();
                string isZState = hcxplc.ReadValue(ConveyorLineInfoDBName.R_ZGMState.ToString(), hcxplc.PLCDescroption).ToString();
                string isFState = hcxplc.ReadValue(ConveyorLineInfoDBName.R_FGMState.ToString(), hcxplc.PLCDescroption).ToString();
                
                
                var route = routingRepository.Find(f => f.route_end == plc.PLCDescroption);
                foreach (var r in route)
                {
                    if (bool.Parse(isZGMWork) && int.Parse(isZState) == 2)
                    {
                        dt_agvtask agvtask = new dt_agvtask
                        {
                            agv_materbarcode = "A" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "," + "B" + DateTime.Now.ToString("yyyy-MM-dd-HH-MM-SS"),
                            agv_barcode = "",
                            agv_code = "负极2号AGV",
                            agv_createtime = DateTime.Now,
                            agv_realesstime = DateTime.Now,
                            agv_fromaddress = r.route_began,
                            agv_grade = 1,
                            agv_materielid = "隔膜物料",
                            agv_qty = 1,
                            agv_tasknum = "KH-" + tasknumber.GetTaskNumber(tasknumberRep),
                            agv_taskstate = "Create",
                            agv_tasktype = "TaskType_Outbound",
                            agv_toaddress = plc.PLCDescroption,
                            agv_userid = "WCS",
                            agv_worktype = 1
                        };
                        agvRepository.Add(agvtask, true);
                        WriteLog.Info("AddHKOneTask").Write("AddHKOneTask" + "手动添加任务成功" + agvtask.agv_tasknum + DateTime.Now, "AddHKOneTask");
                    }
                    else if (bool.Parse(isFGMWork) && int.Parse(isFState) == 2)
                    {
                        dt_agvtask agvtask = new dt_agvtask
                        {
                            agv_materbarcode = "A" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ";" + "B" + DateTime.Now.ToString("yyyy-MM-dd-HH-MM-SS"),
                            agv_barcode = "",
                            agv_code = "负极2号AGV",
                            agv_createtime = DateTime.Now,
                            agv_realesstime = DateTime.Now,
                            agv_fromaddress = r.route_began,
                            agv_grade = 1,
                            agv_materielid = "隔膜物料",
                            agv_qty = 1,
                            agv_tasknum = "KH-" + tasknumber.GetTaskNumber(tasknumberRep),
                            agv_taskstate = "Create",
                            agv_tasktype = "TaskType_Outbound",
                            agv_toaddress = plc.PLCDescroption,
                            agv_userid = "WCS",
                            agv_worktype = 1
                        };
                        agvRepository.Add(agvtask, true);
                        WriteLog.Info("AddHKOneTask").Write("AddHKOneTask" + "手动添加任务成功"+agvtask.agv_tasknum + DateTime.Now, "AddHKOneTask");
                    }
                }
 
                responseContent.Status = true;
            }
            catch (Exception ex)
            {
                responseContent.Message = ex.Message.ToString();
                responseContent.Status = false;
            }
            return responseContent;
        }
 
        public static WebResponseContent AddHKTowTask(string HKNo)
        {
            
            VOLContext Context = new VOLContext();
            Idt_agvtaskRepository agvRepository = new dt_agvtaskRepository(Context);
            Ibase_routing_tableRepository routingRepository = new base_routing_tableRepository(Context);
            Idt_task_numberRepository tasknumberRep = new dt_task_numberRepository(Context);
            dt_task_numberService tasknumber = new dt_task_numberService(tasknumberRep);
            Ibill_group_stockRepository groupRepository = new bill_group_stockRepository(Context);
            WebResponseContent responseContent = new WebResponseContent();
            try
            {
 
                PLCClient plc = WCSService.Clients.Find(v => v.PLCName == HKNo);
                if (plc == null)
                    throw new Exception(string.Format("{0}PLC为连接", HKNo));
                var hxtask = agvRepository.FindFirst(f => f.agv_fromaddress.Contains("KPHLX") && f.agv_toaddress == plc.PLCDescroption);
                if (hxtask != null) 
                {
                    throw new Exception("当前存在回流任务");
                }
                var task = new List<dt_agvtask>();
                if (plc.PLCDescroption.Contains("ZJSL"))
                {
                    task = agvRepository.Find(f => f.agv_remark.Contains("ZJSL") && f.agv_taskstate == "WaitStockOut").ToList();
                }
                else
                {
                    task = agvRepository.Find(f => f.agv_remark.Contains("FJSL") && f.agv_taskstate == "WaitStockOut").ToList();
                }
                if (task.Count >= 1)
                    throw new Exception("当前存在任务");
                var stock = groupRepository.Find(v => v.Remark1 == plc.PLCDescroption).ToList();
                if (stock.Count >= 1)
                    throw new Exception("当前存在库存任务");
                WebResponseContent content = new WebResponseContent();
                string[] tasknum = tasknumber.GetTaskNumber(tasknumberRep, 2).Split(";");
                responseContent = agvRepository.DbContextBeginTransaction(() =>
                {
                    for (int i = 0; i < 4; i++)
                    {
                        dt_agvtask agvtask = new dt_agvtask
                        {
                            agv_materbarcode = "daiding",
                            agv_barcode = "",
                            //   agv_code = "正极1号AGV",
                            agv_createtime = DateTime.Now,
                            agv_realesstime = DateTime.Now,
                            agv_fromaddress = "nou",
                            agv_grade = 1,
                            agv_materielid = "",
                            agv_qty = 1,
                            agv_tasknum = "KH-" + tasknum[i],
                            agv_taskstate = "WaitStockOut",
                            agv_tasktype = "TaskType_Outbound",
                            agv_toaddress = "nou",
                            agv_userid = "WCS",
                            agv_worktype = 1,
                            agv_remark = plc.PLCDescroption
                        };
                        if (plc.PLCDescroption.Contains("ZJSL"))
                        {
                            agvtask.agv_code = "正极1号AGV";
                            //调用WMS呼叫物料出库
                            List<string> StockList = new List<string> { "ZXD0201", "ZXC0201", "ZXB0201", "ZXA0201" };
                            MESback WMSbackresult = MESAPIInvoke.OutNeedStosk(agvtask.agv_tasknum, StockList, 3, "", "", plc.PLCDescroption);
                            WriteLog.Info($"{HKNo}手动上料").Write($"正极1号AGV,MES返回数据:{JsonConvert.SerializeObject(WMSbackresult)},时间:" + DateTime.Now + "", $"{HKNo}手动上料");
                            if (WMSbackresult == null) { throw new Exception($"失败,任务号:{agvtask.agv_tasknum}"); }
                            agvRepository.Add(agvtask, true);
                            WriteLog.Info("Z_HKSB_UpTask").Write("Z_HKSB_UpTask" + agvtask.agv_tasknum + DateTime.Now, "Z_HKSB_UpTask");
                        }
                        else
                        {
                            agvtask.agv_code = "负极1号AGV";
                            //调用WMS呼叫物料出库
                            List<string> StockList = new List<string> { "FXD0201", "FXC0201", "FXB0201", "FXA0201" };
                            MESback WMSbackresult = MESAPIInvoke.OutNeedStosk(agvtask.agv_tasknum, StockList, 3, "", "", plc.PLCDescroption);
                            WriteLog.Info($"{HKNo}手动上料").Write($"负极1号AGV,MES返回数据:{JsonConvert.SerializeObject(WMSbackresult)},时间:" + DateTime.Now + "", $"{HKNo}手动上料");
                            if (WMSbackresult == null) { throw new Exception($"失败,任务号:{agvtask.agv_tasknum}"); }
                            agvRepository.Add(agvtask, true);
                            WriteLog.Info("Z_HKSB_UpTask").Write("Z_HKSB_UpTask" + agvtask.agv_tasknum + DateTime.Now, "Z_HKSB_UpTask");
                        }
                    }
                    plc.WriteValue(ConveyorLineInfoDBName.R_HKSB_IsWorkBatchNo.ToString(), plc.PLCDescroption, false).ToString();
                    return WebResponseContent.Instance.OK();
                });
 
                responseContent.Status = true;
            }
            catch (Exception ex)
            {
                responseContent.Message = ex.Message.ToString();
                responseContent.Status = false;
            }
            return responseContent;
        }
 
    }
}