schangxiang@126.com
2025-09-18 49a51c068d62084bc4c3e77c4be94a20de556c4a
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
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Windows.Forms;
using logtxtWrite;
using wcftest.orm;
using wcftest.EnumDefine;
using Newtonsoft.Json;
using wcftest.sapEntity;
using System.Threading;
using wcftest.sendToSap;
using wcftest.sapEntity;
using wcftest.sql;
using wcftest.BussinessExtension.Handle;
using wcftest.BussinessExtension.Common;
using wcftest.Model;
using wcftest.BussinessExtension;
using wcftest.Model.Sys;
using wcftest.EnumDefine.Sys;
using wcftest.Model.Input;
using wcftest.Model.Output;
using wcftest.orm_test;
using wcftest.Utils.AuthFacotry;
using System.Linq.Expressions;
 
 
namespace wcftest.wcf
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的类名“apitest”。
    public class apitest : Iapitest
    {
        /// <summary>线程锁防止并发
        /// 线程锁防止并发
        /// </summary>
        public static System.Threading.Mutex single = new Mutex();
        //SapWcfService/
        //sendToSap.SapWcfServiceClient sendSap = new sendToSap.SapWcfServiceClient();
        wcfApi.ControlCenterWcfServiceClient wcsApi = new wcfApi.ControlCenterWcfServiceClient();
        // 获取设备信息
        Form1 form = Program.form1ObjPublic;
        //sendSap.WmsReverser();撤销
        #region 给WMS接口
        /// <summary> 呼叫托盘
        /// 呼叫托盘
        /// </summary>
        /// <param name="containerTypeId">托盘类型号(1是小托盘,2是大托盘)</param>
        public void callContainer(int containerTypeId)
        {
 
            if (containerTypeId < 1 || containerTypeId > 2)
            {
                logtxt.txtWrite("类名:taskApi/函数名:callContainer拆盘任务参数超出范围/ 托盘类型:" + containerTypeId.ToString(), 2);
            }
            try
            {
                //写入任务列表Task_Queue
                using (dbModel mod = new dbModel())
                {
                    Task_Queue CallContainerTaks = new Task_Queue();
                    CallContainerTaks.TaskType = ((int)TaskTypeEnum.入库拆盘).ToString();//任务类型
                    CallContainerTaks.OrderNumber = 0;//任务权重
                    CallContainerTaks.TaskStatus = "未下发";//任务状态
                    CallContainerTaks.PlateType = containerTypeId == 1 ? ((int)Sys_containerType.小托盘).ToString() : ((int)Sys_containerType.大托盘).ToString();//托盘类型
                    CallContainerTaks.CreateDate = DateTime.Now;
                    CallContainerTaks.Creator = "系统";
                    CallContainerTaks.UserProduct_Id = 1007;//账套id 老谢bug  
                    //垃圾值都赋值0 转到autoTask()里有说明
                    CallContainerTaks.FromPositionName = "0";
                    CallContainerTaks.ToPositionName = "0";
                    CallContainerTaks.DoCount = 0;//库区
                    CallContainerTaks.Direction = "0";//托盘高度
                    mod.Task_Queue.Add(CallContainerTaks);
                    mod.SaveChanges();
 
                    logtxt.txtWrite("类名:taskApi,函数名:callContainer  拆盘任务发送成功 containerType:" + containerTypeId.ToString(), 0);
 
                }
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("类名:taskApi/函数名:callContainer拆盘任务异常/ 托盘类型:" + containerTypeId.ToString() + logtxt.oneRow(ex.ToString()), 2);
 
            }
        }
 
        /// <summary>分拣确认
        /// 分拣确认
        /// </summary>
        /// <param name="PlateCode">托盘编号</param>
        /// <param name="Products">出库物料list</param>
        /// <param name="percentage"></param>
        /// <returns></returns>
        public string sortingConfirm(string PlateCode, string Products, string percentage)
        {
            resultMsg msgs = new resultMsg();
            //msgs.msg = "分拣失败!";
            //msgs.result = false;
            //msgs.status = 400;
            //return JsonConvert.SerializeObject(msgs);
            try
            {
                logtxt.txtWrite("类名:apitest/函数名:sortingConfirm收到分拣数据 托盘号PlateCode:" + PlateCode + ",出库物料列表Products:" + Products + ",百分比percentage:" + percentage
                    , 2);
                string plateCode = PlateCode;
                //记录
                List<sortingType> products = JsonConvert.DeserializeObject<List<sortingType>>(Products);
 
                //验证百分比 【EditBy shaocx,2022-10-15】
                if (Convert.ToInt32(percentage) <= 0)
                {
                    msgs.msg = "占用空间不能小于0";
                    msgs.result = false;
                    msgs.status = 400;
                    return JsonConvert.SerializeObject(msgs);
                }
 
                //验证输入的分拣数量 【EditBy shaocx,2022-06-08】
                if (products != null && products.Count > 0)
                {
                    foreach (var item in products)
                    {
                        if (item.finishedQuantity < 0)
                        {
                            msgs.msg = "分拣数量不能小于0";
                            msgs.result = false;
                            msgs.status = 400;
                            return JsonConvert.SerializeObject(msgs);
                        }
                    }
                }
                else
                {
                    msgs.msg = "没有分拣数据";
                    msgs.result = false;
                    msgs.status = 400;
                    return JsonConvert.SerializeObject(msgs);
                }
 
                var _creator = products[0].creator;
 
                #region 数据验证 【EditBy shaocx,2022-07-18】
 
                /*
                //判断分拣数据是否有重复的
                List<string> validateList = new List<string>();
                foreach (var item in products)
                {
                    var str = item.product_Id.ToString() + "-" + item.finishedQuantity.ToString() + "-" + item.trankNumber;
                    if (validateList.Contains(str))
                    {//验证不通过
                        msgs.msg = "分拣数据有重复,重复物料号:" + item.product_Id + ",数量:" + item.finishedQuantity + ",跟踪号:" + item.trankNumber;
                        msgs.result = false;
                        msgs.status = 400;
                        return JsonConvert.SerializeObject(msgs);
                    }
                    else
                    {
                        validateList.Add(str);
                    }
                }
                //*/
 
                #endregion
 
                List<MovMaterialEntity> moveMaterials = new List<MovMaterialEntity>();//移库实体集合
                List<GIMaterialEntity> resultSap_GIMaterialEntity_List = new List<GIMaterialEntity>();//出库实体集合
                using (dbModel mod = new dbModel())
                {
                    List<vvBase_ProductPosition> checkSortion = mod.vvBase_ProductPosition.Where(x => x.PlateCode.Trim() == PlateCode.Trim() && x.ContainerNo == "1").ToList();
                    if (checkSortion.Count < 1)
                    {
                        logtxt.txtWrite("类名:Form1/函数名:sortingConfirm重复分拣" + Products, 0);
                        msgs.msg = "此托盘没有分拣数据";
                        msgs.result = false;
                        msgs.status = 400;
                        return JsonConvert.SerializeObject(msgs);
                    }
                    logtxt.txtWrite("类名:Form1/函数名:sortingConfirm分拣收到信息是 " + Products, 0);
                    bool isEmpty = true;//记录库存是否出完变量
                    Task_Queue backTask = mod.Task_Queue.Where(x => x.PlateCode == plateCode).OrderByDescending(x => x.CreateDate).FirstOrDefault();
                    //if (backTask==null||Convert.ToInt32( backTask.TaskType)!=1)
                    //{
                    //    return;
                    //}
                    //查询当前托盘中所有的库存
                    List<Base_ProductPosition> currentProductPositionList = mod.Base_ProductPosition.Where(x => x.PlateCode == plateCode).ToList();
                    for (int i = 0; i < products.Count; i++)
                    {
                        int productId = products[i].product_Id;
                        string tracknumber = products[i].trankNumber;
                        //OrignStorage   && x.Product_Id ==(long) )   
                        decimal quantity = (decimal)products[i].finishedQuantity;//分拣数量
 
 
                        //因为这里是根据托盘号查询的,因此库存一定是在立体库中,不是在收货暂存区中 【EditBy shaocx,2022-03-08】
                        //Base_ProductPosition ProductPosition = mod.Base_ProductPosition.Where(x => x.PlateCode == plateCode && x.Product_Id == productId
                        //&& x.ProductStorage >= quantity && x.ExtendField04 == tracknumber).FirstOrDefault();
                        Base_ProductPosition ProductPosition = currentProductPositionList.Where(x => x.PlateCode == plateCode && x.Product_Id == productId
                          && x.ProductStorage >= quantity && x.ExtendField04 == tracknumber).OrderBy(x => x.ProductStorage).FirstOrDefault();//增加对数量的升序排序 【EditBy shaocx,2022-07-18】 
                        if (ProductPosition == null || ProductPosition.ProductPosition_Id == 0)
                        {
                            msgs.msg = "此托盘没有找到库存数据,产品id:" + productId + ",数量:" + quantity + ",跟踪号:" + tracknumber;
                            msgs.result = false;
                            msgs.status = 400;
                            return JsonConvert.SerializeObject(msgs);
                        }
                        //Base_ProductPosition ProductPosition = mod.Base_ProductPosition.Where(x => x.ProductPosition_Id == l_ProductPosition.ProductPosition_Id).FirstOrDefault();
 
                        //int orderId= (int)  backTask.Bill_Id;//出库单ID
                        // Sale_Order saleOrder=mod.Sale_Order.Find(orderId);//根据id 找到出库单
                        Sale_Order checkMoveType = mod.Sale_Order.FirstOrDefault(x => x.Order_Id == backTask.Bill_Id);
                        if (checkMoveType == null)
                        {
                            logtxt.txtWrite("类名:Form1/函数名:sortingConfirm分拣异常/托盘号 " + PlateCode + "找不到出库单", 2);
                            msgs.msg = "找不到出库单,是否已删除?";
                            msgs.result = false;
                            msgs.status = 400;
                            return JsonConvert.SerializeObject(msgs);
                        }
                        #region 写入出库记录
                        //OutInStockTask addOutTask = new OutInStockTask();
                        //addOutTask.taskName = "出库任务";
                        //addOutTask.orderCode = checkMoveType.OrderCode;
                        //addOutTask.trackNumber = tracknumber;
                        //addOutTask.materialNumber = ProductPosition.ProductCode;
                        //addOutTask.materialName = ProductPosition.ProductName;
                        //addOutTask.unit = ProductPosition.ExtendField05;
                        //addOutTask.quantity = -products[i].finishedQuantity;//注意:出库任务记录的数量是负数![EditBy shaocx,2022-03-07]
                        //addOutTask.creatDate = DateTime.Now;
                        ////增加字段 【EditBy shaocx,2022-03-06】
                        //addOutTask.PositionName = ProductPosition.PositionName;
                        //decimal cghw_ProductStorage = 0;
                        //decimal zcq__ProductStorage = 0;
                        //BussinessExtension.BussinessExtension.GetCurrentProductStorage(mod, addOutTask.materialNumber, out cghw_ProductStorage, out zcq__ProductStorage);
                        //addOutTask.CGHW_ProductStorage = cghw_ProductStorage;
                        //addOutTask.ZCG_ProductStorage = zcq__ProductStorage;
                        //mod.OutInStockTask.Add(addOutTask);//增加出库记录
                        OutInStockTaskHandler.AddOutInStockTask(ProductPosition.PlateCode, mod, OutInStockTaskName.出库任务, checkMoveType.OrderCode, tracknumber,
                                    ProductPosition.ProductCode, ProductPosition.ProductName, ProductPosition.SmallUnit,
                                    -products[i].finishedQuantity,//注意:出库任务记录的数量是负数![EditBy shaocx,2022-03-07]
                                    ProductPosition.PositionName, "分拣确认,库存出库", products[i].creator);
                        #endregion
                        Sale_OrderList checkMoveTypeList = mod.Sale_OrderList.FirstOrDefault(x => x.Order_Id == checkMoveType.Order_Id && x.ProductCode == ProductPosition.ProductCode);
                        #region Sap出库确认明细
                        GIMaterialEntity newSap = new GIMaterialEntity();
                        if (checkMoveTypeList != null)
                        {
                            //如果是手动出库 () 生产订单为空/销售订单为空/移动类型=201
                            if (checkMoveType.OrderType == "手动出库")
                            {
                                #region 手动出库
                                //判断移动类型不等于空
                                if (checkMoveTypeList.ExtendField01 != null)
                                {
                                    string moveType = ConvertMoveType(checkMoveTypeList.ExtendField01);//移动类型
                                    string trackNumber = ProductPosition.ExtendField04 == null ? "" : ProductPosition.ExtendField04;//跟踪号
                                    string materialCode = ProductPosition.ProductCode.Trim();//产品编号
                                    if (moveType != "311")
                                    {
                                        #region 非311
 
                                        newSap.WorkOrder = checkMoveTypeList.StoreOrderId + "#0#0";//生产订单  
                                        //如果库存数据没有跟踪号261不加E特殊类型符号
                                        if (string.IsNullOrEmpty(trackNumber))
                                        {
                                            newSap.MoveType = moveType;//移动类型
                                        }
                                        else
                                        {
                                            newSap.MoveType = moveType + "E";//移动类型
                                        }
 
                                        //如果生产订单为空
                                        //if (string.IsNullOrEmpty(checkMoveTypeList.StoreOrderId))
                                        //{
                                        newSap.SalesOrder = checkMoveTypeList.PackageName;//销售订单
                                        newSap.SalesOrderItem = checkMoveTypeList.NumberOfGiftBags;//
                                        //}
                                        newSap.Plant = "3TG1";
                                        newSap.MaterialCode = materialCode;
                                        newSap.StorageLocation = "G021";
                                        newSap.Quantity = products[i].finishedQuantity;
                                        resultSap_GIMaterialEntity_List.Add(newSap);
                                        #endregion
 
                                    }
                                    else
                                    {
                                        #region 311立库到平库
                                        #region sap发送数据
                                        MovMaterialEntity moveMaterial = new MovMaterialEntity();
 
 
                                        //有跟踪号 移动类型要加E  加E就要天销售单号和销售项号
                                        if (!string.IsNullOrEmpty(trackNumber))//ProductCode poInfoChild.ExtendField07 = item.SalesOrder;//销售单号 poInfoChild.SpecAlias = item.SalesOrderItem;//销售单项号
                                        {
                                            moveType += "E";
 
 
                                            moveMaterial.SalesOrder = checkMoveTypeList.PackageName;//销售订单
                                            moveMaterial.SalesOrderItem = checkMoveTypeList.NumberOfGiftBags;//
                                        }
                                        logtxt.txtWrite("发送的移动类型是" + moveType + "跟踪号:" + trackNumber, 0);//收到记录一条日志
                                        moveMaterial.MoveType = moveType;
                                        moveMaterial.Plant = "3TG1";
                                        moveMaterial.MaterialCode = materialCode;
                                        moveMaterial.FromStorageLocation = "G021";
                                        moveMaterial.ToStorageLocation = checkMoveType.GiftMessage;//转入仓
                                        moveMaterial.Quantity = products[i].finishedQuantity;
                                        moveMaterials.Add(moveMaterial);
                                        #endregion
                                    }
 
                                        #endregion
 
                                }
                                #endregion
                            }
                            else
                            {//按单出库
                                #region 出库任务
                                newSap.WorkOrder = backTask.BillCode + "#" + checkMoveType.StoreName + "#" + checkMoveTypeList.ExtendField10;
                                //判断有没有跟踪号
                                if (string.IsNullOrEmpty(ProductPosition.ExtendField04))
                                {
                                    newSap.MoveType = ProductPosition.Remark;
                                }
                                else
                                {
                                    string trackingNumber = ProductPosition.ExtendField04;//跟踪号
                                    //通过跟踪号查销售单号 和销售项号
                                    Purchase_OrderList sale_number = mod.Purchase_OrderList.FirstOrDefault(x => x.ExtendField04 == trackingNumber);
                                    if (sale_number != null)
                                    {
                                        newSap.SalesOrder = sale_number.ExtendField07;//销售订单号
                                        newSap.SalesOrderItem = sale_number.SpecAlias;//销售项号 
                                    }
                                    else
                                    {
                                        logtxt.txtWrite("类名:Form1/函数名:sortingConfirm分拣确认,通过跟踪号在po里查不到销售单号  跟踪号是:" + trackingNumber + "分拣托盘号:" + PlateCode + 2);
                                    }
                                    newSap.MoveType = ProductPosition.Remark + "E";//移动类型
 
                                }
                                #endregion
                                newSap.Plant = "3TG1";
                                newSap.MaterialCode = ProductPosition.ProductCode.Trim();//产品编号
                                newSap.StorageLocation = "G021";
                                newSap.Quantity = products[i].finishedQuantity;
                                resultSap_GIMaterialEntity_List.Add(newSap);
                            }
 
                        }
 
                        #endregion
 
                        #region 库存扣减
 
                        if (products[i].finishedQuantity == ProductPosition.ProductStorage)
                        {
                            //如果出库数量等于库存就删了这条库存
                            mod.Base_ProductPosition.Remove(ProductPosition);
                            currentProductPositionList.Remove(ProductPosition);//注意:要清除此数据,不加会导致库存扣减错误!  【EditBy shaocx,2022-07-18】
                            //前面已经记录了出入库记录了,这里就不需要记录了 【EditBy shaocx,2022-03-07】
                        }
                        else if (products[i].finishedQuantity < ProductPosition.ProductStorage)
                        {
                            //小于库存就改数量
                            isEmpty = false;
                            ProductPosition.ProductStorage = ProductPosition.ProductStorage - products[i].finishedQuantity;
                            //前面已经记录了出入库记录了,这里就不需要记录了 【EditBy shaocx,2022-03-07】
                            ProductPosition.ExtendField02 = "0";//出库数量
                            ProductPosition.ExtendField03 = "0";//=1是允许分拣
                            // ProductPosition.ContainerNo = "0";//解除锁定
                        }
                        else
                        {//增加 重复参数校验 [EditBy shaocx,2022-07-18]
                            logtxt.txtWrite("类名:Form1/函数名:sortingConfirm此托盘本次分拣物料" + products[i].product_Id + ",分拣数量" + products[i].finishedQuantity + "超过实际库存量" + ProductPosition.ProductStorage + ",请重新扫码托盘,重新分拣!", 0);
                            msgs.msg = "此托盘本次分拣物料" + products[i].product_Id + ",分拣数量" + products[i].finishedQuantity + "超过实际库存量" + ProductPosition.ProductStorage + ",请重新扫码托盘,重新分拣!";
                            msgs.result = false;
                            msgs.status = 400;
                            return JsonConvert.SerializeObject(msgs);
                        }
                        #endregion
                    }
                    //再次复位状态 
                    List<Base_ProductPosition> ProductPositionCheck = mod.Base_ProductPosition.Where(x => x.PlateCode == plateCode).ToList();
                    if (ProductPositionCheck.Count > 0)
                    {
                        foreach (var ProductItem in ProductPositionCheck)
                        {
                            ProductItem.ExtendField03 = "0";//不需要分拣状态
                            ProductItem.Remark = "";//移动类型
                        }
                    }
                    //修复有时候出现托盘上全部分拣,但是wms会创建余料回库的任务,但实际库存都没有的错误 【EditBy shaocx,2022-08-08】
                    //if (ProductPositionCheck.Count > products.Count)
                    //{
                    //    isEmpty = false;
                    //}
                    if (currentProductPositionList.Count == 0)
                    {
                        isEmpty = true;//已空盘
                    }
                    else
                    {
                        isEmpty = false;//未空盘
                    }
                    #region 判断是否要去叠盘
                    string position = backTask.DoCount + "-" + backTask.FromPositionName;
                    Base_Position unlock = mod.Base_Position.FirstOrDefault(x => x.PositionName == position);
                    if (isEmpty)//数量出完就去叠盘
                    {
                        string toPlace = "";
                        if (backTask.PlateType == "1")
                        {
                            toPlace = "1018";
                        }
                        else
                        {
                            toPlace = "1017";
                        }
 
                        //判断是否叠盘机满了,【EditBy shaocx,2022-03-08】
                        Base_Equipment fpMachine = null;
                        var isFull = Base_EquipmentHandler.FoldingPlateMachine_IsFull(mod, Convert.ToInt32(backTask.PlateType), ref fpMachine);
                        if (isFull)
                        {
                            var errMsg = fpMachine.DeviceName + "目前数量已满,数量为" + Convert.ToInt32(fpMachine.SurplusQuantity) + ",请稍等再操作!";
                            logtxt.txtWrite("类名:Form1/函数名:sortingConfirm" + errMsg, 0);
                            msgs.msg = errMsg;
                            msgs.result = false;
                            msgs.status = 400;
                            return JsonConvert.SerializeObject(msgs);
                        }
                        if (fpMachine != null)
                        {
                            Base_EquipmentHandler.FoldingPlateMachine_UpdateCurQuantityAddOne(mod, fpMachine);//增加数量1
                        }
 
 
                        Task_Queue addTask = new Task_Queue();
                        addTask.BillCode = "回库";//来源单号
                        addTask.TaskType = ((int)TaskTypeEnum.出库叠盘).ToString();
                        addTask.PlateType = backTask.PlateType;//器具种类-大托盘小托盘
                        addTask.PlateCode = plateCode;//母托盘编号
                        addTask.Bill_Id = 1111;// 单据id
                        addTask.OrderNumber = 0;//任务执行优先级
                        addTask.TaskStatus = "未下发";//任务状态
                        addTask.FromPositionName = backTask.ToPositionName;//起始地址
                        addTask.ToPositionName = toPlace;//目标地址
                        addTask.Direction = "1";//出库不需要托盘高度
                        addTask.DoCount = backTask.DoCount;//库区
                        addTask.CreateDate = DateTime.Now;
                        addTask.Creator = _creator;
                        addTask.UserProduct_Id = 1007;//账套id 老谢bug  
                        // addTask.IsDoing = (int)item.OrderList_Id;//记录出库明细表ID,出库确认用(只有出库用)
                        mod.Task_Queue.Add(addTask);
                        if (unlock != null)
                        {
                            //unlock.IsFreeze = 0;
                            unlock.IsFreeze = (int)IsFreezeEnum.无货;
                            unlock.IsLocked = 0;
                            unlock.Remark = "分拣任务确认-解锁库位!";
                            unlock.PositionLength = 0;
                        }
                        else
                        {
                            logtxt.txtWrite("类名:Form1/函数名:sortingConfirm分拣叠盘,解锁库位失败,找不到库位: " + position, 2);
                            msgs.msg = "解锁库位失败,找不到库位: " + position;
                            msgs.result = false;
                            msgs.status = 400;
                            return JsonConvert.SerializeObject(msgs);
                        }
                    }
                    else
                    {
                        //数量没出完就去回库
                        Task_Queue addTask = new Task_Queue();
                        addTask.BillCode = "回库";//来源单号
                        addTask.TaskType = ((int)TaskTypeEnum.余料回库).ToString();
                        addTask.PlateType = backTask.PlateType;//器具种类-大托盘小托盘
                        addTask.PlateCode = plateCode;//母托盘编号
                        addTask.Bill_Id = 1111;// 单据id
                        addTask.OrderNumber = 0;//任务执行优先级
                        addTask.TaskStatus = "未下发";//任务状态
                        addTask.FromPositionName = backTask.ToPositionName;//起始地址
                        addTask.ToPositionName = backTask.FromPositionName;//目标地址
                        addTask.DoCount = backTask.DoCount;//库区
                        int areaNo = (int)backTask.DoCount;
                        string height = "";
                        if (areaNo == 1)
                        {
                            height = "2";
                        }
                        else
                        {
                            height = "4";
                        }
                        addTask.Direction = height;//出库不需要托盘高度
                        addTask.CreateDate = DateTime.Now;
                        addTask.Creator = _creator;
                        addTask.UserProduct_Id = 1007;//账套id 老谢bug  
                        // addTask.IsDoing = (int)item.OrderList_Id;//记录出库明细表ID,出库确认用(只有出库用)
                        mod.Task_Queue.Add(addTask);
                        if (unlock != null)
                        {
                            unlock.PositionLength = Convert.ToInt32(percentage.Trim());
                        }
                    }
                    #endregion
                    //注释:由下面的SaveChanges一处执行 【Editby shaocx,2022-03-12】
                    //int saveok = mod.SaveChanges();
                    //#region 保存数据判断
                    //if (saveok < 1)
                    //{
                    //    saveok = mod.SaveChanges();
                    //}
                    //if (saveok < 1)
                    //{
                    //    msgs.msg = "分拣失败-保存数据未成功";
                    //    msgs.result = false;
                    //    msgs.status = 400;
                    //}
                    //else
                    //{
                    //    msgs.msg = "分拣成功";
                    //    msgs.result = true;
                    //    msgs.status = 200;
 
                    //}
                    //#endregion
 
                    if (resultSap_GIMaterialEntity_List.Count > 0)//SAP出库确认
                    {
                        //注意:这里要改为循环处理,因为如果混合再一起推送,会出问题 【EditBy shaocx,2022-10-11】
                        foreach (var resultSap_GIMaterialEntity in resultSap_GIMaterialEntity_List)
                        {
                            SapSendInfo sapGi = new SapSendInfo();
                            //注意!!!:这里的SendSapData还是序列化的这个list
                            List<GIMaterialEntity> newList = new List<GIMaterialEntity>();
                            newList.Add(resultSap_GIMaterialEntity);
                            sapGi.SendSapData = JsonConvert.SerializeObject(newList);//数据转string 保存
                            //sapGi.moveType = 1;//出库标志
                            sapGi.moveType = (int)MoveTypeForSapSend.出库;//出库标志
                            sapGi.creatTime = DateTime.Now;
                            sapGi.sendCount = 0;//发送次数
                            sapGi.voucherCode = sapGi.RetMsg = "";//sap凭证
                            sapGi.isFinish = 0;//是否完成
                            BussinessExtension.BussinessExtension.SetSapSendInfoByGIMaterialEntity(mod, sapGi, resultSap_GIMaterialEntity);//配置对象 [EditBy shaocx,2022-01-30]
                            mod.SapSendInfo.Add(sapGi);
                        }
                    }
                    if (moveMaterials.Count > 0)//发送311立库到平库
                    {
                        //替换下面的代码 【EditBy shaocx,2022-09-22】
                        SapSendInfoHandler.AddSapSendInfoForMove(mod, false, moveMaterials, "", "");
                        /*
                        SapSendInfo sapGi = new SapSendInfo();
                        sapGi.SendSapData = JsonConvert.SerializeObject(moveMaterials);//数据转string 保存
                        //sapGi.moveType = 2;//移库标志
                        sapGi.moveType = (int)MoveTypeForSapSend.移库;//移库标志
                        sapGi.creatTime = DateTime.Now;
                        sapGi.sendCount = 0;
                        sapGi.voucherCode = "";
                        sapGi.isFinish = 0;
                        BussinessExtension.BussinessExtension.SetSapSendInfoByMovMaterialEntity(mod, sapGi, moveMaterials);//配置对象 [EditBy shaocx,2022-01-30]
                        mod.SapSendInfo.Add(sapGi);
                        //*/
                    }
 
                    OperationLogHelper.AddOperationLogEntity(mod, _creator, "分拣托盘" + PlateCode, OperateTypeEnum.分拣, "");
 
                    int dd = mod.SaveChanges();
                    if (dd > 0)
                    {
                        logtxt.txtWrite("数据保存成功", 1);
                        msgs.msg = "分拣成功";
                        msgs.result = true;
                        msgs.status = 200;
                    }
                    else
                    {
                        logtxt.txtWrite("数据保存失败,数目为" + dd, 1);
                        msgs.msg = "分拣失败-保存数据未成功";
                        msgs.result = false;
                        msgs.status = 400;
                    }
                }
            }
            catch (Exception ex)
            {
                //logtxt.txtWrite("类名:Form1/函数名:sortingConfirm分拣异常/托盘号 " + PlateCode + "异常信息:" + ex.StackTrace.ToString(), 2);
                logtxt.txtWrite("类名:Form1/函数名:sortingConfirm分拣异常/托盘号 " + PlateCode + "异常信息:" + JsonConvert.SerializeObject(ex), 2);
                msgs.msg = "分拣失败-参数异常";
                msgs.result = false;
                msgs.status = 400;
            }
            return JsonConvert.SerializeObject(msgs);
        }
        /// <summary>把前端移动类型描述转换成sap格式,
        /// 把前端移动类型描述转换成sap格式
        /// </summary>
        /// <param name="stringMove">移动类型描述</param>
        /// <returns>返回SAP格式</returns>
        public string ConvertMoveType(string stringMove)
        {
            switch (stringMove.Trim())
            {
                case "发料到成本中心201": return "201";
                case "发料到生产订单261": return "261";
                case "发料到销售订单231": return "231";
                case "暂存区发料到生产订单261": return "261";
                case "311立库到平库": return "311";
                default: return "";
            }
        }
 
        #region 收货
 
        /// <summary>按单 收货和退货操作
        /// 按单 收货和退货操作
        /// </summary>
        /// <param name="receipt"></param>
        /// <returns></returns>
        public string receiptConvert(string receipt)
        {
            string msg = "";
            bool saveSueeccd = false;
            int numInfo = 0;
            List<GRMaterialEntity> grEntitys = new List<GRMaterialEntity>();
            receipiEntity results = JsonConvert.DeserializeObject<receipiEntity>(receipt);
 
            var _qrCode_Guid = results.qrCode_guid;
            bool isQrCode = false;//是否是二维码收货
            if (!string.IsNullOrEmpty(results.qrCode_guid))
            {//表示有 收货二维码
                isQrCode = true;
                if (results.dataList.Count > 1)
                {
                    var data23 = new
                    {
                        result = saveSueeccd,
                        msg = "使用二维码收货,只能收货一个项号的物料"
                    };
                    msg = JsonConvert.SerializeObject(data23);
                    return msg;
                }
 
 
                if (!string.IsNullOrEmpty(results.plateCode))
                {
                    var errMsg = "";
                    var res = PlateCodeHandler.ValiatePlateIsAllowZP(results.plateCode, ref errMsg);
                    if (!res)
                    {
                        var data23 = new
                        {
                            result = false,
                            msg = errMsg
                        };
                        msg = JsonConvert.SerializeObject(data23);
                        return msg;
                    }
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(results.plateCode))
                {
                    var data23 = new
                    {
                        result = saveSueeccd,
                        msg = "使用一维码收货,不支持收货时码盘"
                    };
                    msg = JsonConvert.SerializeObject(data23);
                    return msg;
                }
            }
 
            ////模拟写死,还得改回来 哦 
            //var data22 = new
            //{
            //    result = saveSueeccd,
            //    msg = "我错了"
            //};
            //msg = JsonConvert.SerializeObject(data22);
            //return msg;
 
            try
            {
                using (dbModel mod = new dbModel())
                {
                    //需要校验下 该库存是否存在 【Editby shaocx,2023-11-5】
                    if (!string.IsNullOrEmpty(results.qrCode_guid))
                    {//表示有 收货二维码
                        var isExistObj = mod.Base_ProductPosition.Where(x => x.qrCode_guid == results.qrCode_guid).FirstOrDefault();
                        if (isExistObj != null)
                        {
                            if (!string.IsNullOrEmpty(results.plateCode))
                            {//说明是 单独组盘操作
                                //更新码盘数据
                                isExistObj.PlateCode = results.plateCode;
                                int result = mod.SaveChanges();
                                if (result < 1)
                                {
                                    msg = "保存失败";
                                }
                                else
                                {
                                    msg = "执行成功,完成" + numInfo + "条信息";
                                    saveSueeccd = true;
                                }
                                var data99 = new
                                {
                                    result = saveSueeccd,
                                    msg = msg
                                };
                                msg = JsonConvert.SerializeObject(data99);
                                return msg;
 
                            }
                            else
                            {//说明是重复收货
                                var data99 = new
                                {
                                    result = saveSueeccd,
                                    msg = "该二维码已经收货了"
                                };
                                msg = JsonConvert.SerializeObject(data99);
                                return msg;
                            }
                        }
                    }
 
                    if (results.dataList.Count > 0)
                    {
                        string poCode = results.poCode.Trim();
                        string moveType = results.moveType.Trim();//具体详看枚举 MoveTypeForReceiptConvertEnum
                        Purchase_Order purchaseOrder = mod.Purchase_Order.FirstOrDefault(x => x.PoCode == poCode);
                        List<Purchase_OrderList> PurchaseList = mod.Purchase_OrderList.Where(x => x.ExtendField10 == poCode).ToList();
                        if (PurchaseList.Count > 0 && purchaseOrder != null)
                        {
                            int isFinish = 0;
                            foreach (var item in results.dataList)
                            {
                                if (item.quantity <= 0)
                                {//增加验证 【EditBy shaocx,2022-10-11】
                                    saveSueeccd = false;
                                    msg = "数量不能小于等于0";
                                    var data2 = new
                                    {
                                        result = saveSueeccd,
                                        msg
                                    };
                                    msg = JsonConvert.SerializeObject(data2);
                                    return msg;
                                }
 
                                Purchase_OrderList poItem = PurchaseList.FirstOrDefault(x => x.OrderList_Id == item.orderList_Id);
 
                                if (poItem == null)
                                {
                                    continue;
                                }
                                GRMaterialEntity grEntity = new GRMaterialEntity();
                                #region 发送sap
                                grEntity.Plant = "3TG1";
                                grEntity.StorageLocation = item.productBarCode;//存储位置
                                grEntity.PoNumber = poItem.ExtendField10;//采购单号
                                grEntity.PoItem = poItem.ItemNumber;//采购项号
                                grEntity.MaterialCode = poItem.ProductCode;
                                grEntity.MoveType = results.moveType;
                                grEntity.Quantity = item.quantity;// *item.unitConvert / item.unEnterQuantity;//未打印数量
                                #endregion
 
 
                                //if (moveType == "101")
                                if (moveType == ((int)MoveTypeForReceiptConvertEnum.收货).ToString())
                                {//101是指 收货,具体详看枚举 MoveTypeForReceiptConvertEnum
 
                                    decimal totalQty = (decimal)poItem.BigQty * (1 + (decimal)poItem.Overcharges / 100);//采购数量乘以容差
                                    decimal receivedQty = poItem.BigEnterQuantity == null ? 0 : (decimal)poItem.BigEnterQuantity;//已收数量
 
                                    decimal nowQty = receivedQty + (decimal)item.quantity;//已收数量加上本次收的数量
                                    if (totalQty >= nowQty)//验证有没有超收
                                    {
 
                                        if (nowQty >= (decimal)poItem.BigQty)
                                        {
                                            isFinish++;
 
                                        }
 
                                        numInfo++;
                                        #region 收货
                                        poItem.BigEnterQuantity = receivedQty + item.quantity;
                                        Base_ProductPosition addPP = new Base_ProductPosition();
                                        //where PositionName = '收货暂存区' and ProductStorage > 0 and PartStatus ='1'
                                        //ProductPosition.PositionName = "收货暂存区";
                                        addPP.PositionName = SysGlole.PositionName_SHZCQ;
                                        addPP.CreateDate = DateTime.Now;
                                        addPP.ModifyDate = DateTime.Now;
 
                                        //注意:这里处理支持二维码的方式 【Editby shaocx,2023-11-5】
                                        addPP.qrCode_guid = _qrCode_Guid;
                                        addPP.IsQrCode = isQrCode;
                                        addPP.BarCode = addPP.ExtendField06 = _qrCode_Guid;
 
                                        //库存数量
                                        addPP.ProductStorage = item.quantity * item.unitConvert / item.unEnterQuantity;//未打印数量
                                        addPP.OrignStorage = item.quantity * item.unitConvert / item.unEnterQuantity;//收货数量 ProductStorage
 
                                        //增加数量校验
                                        if (addPP.ProductStorage <= 0)
                                        {
                                            var data99 = new
                                            {
                                                result = false,
                                                msg = "库存数不能等于0"
                                            };
                                            msg = JsonConvert.SerializeObject(data99);
                                            return msg;
                                        }
 
                                        //修改可维护自动打印的参数 【Editby shaocx,2022-06-13】
                                        //ProductPosition.PartStatus = "1";//0表示不需要自动打印,1表示需要自动打印
                                        //// 0不打印 1:入库口打印机 2:出库口打印机
                                        //ProductPosition.PartStatus = results.isAutoPrint ? "1" : "0";//0表示不需要自动打印,1表示需要自动打印
                                        addPP.PartStatus = results.printFlag.ToString();//0表示不需要自动打印,1表示需要自动打印
                                        if (!string.IsNullOrEmpty(results.qrCode_guid))
                                        {//表示有 收货二维码
                                            addPP.PartStatus = "1";//写死为 入库口打印机
                                        }
 
                                        //处理库存中的托盘号问题 【Editby shaocx,2024-09-08】
                                        if (!string.IsNullOrEmpty(results.plateCode))
                                        {
                                            addPP.PlateCode = results.plateCode;
                                        }
 
                                        addPP.Product_Id = Convert.ToInt32(poItem.Product_Id);
                                        addPP.ProductCode = poItem.ProductCode;
                                        addPP.ProductName = poItem.ProductName;
                                        addPP.InStorageDate = DateTime.Now;
                                        addPP.PoCode = poItem.ExtendField10;//采购单号
                                        addPP.ItemNumber = poItem.ItemNumber;//采购项号
                                        addPP.ExtendField04 = poItem.ExtendField04;//跟踪号
                                        addPP.SaleCode = poItem.ExtendField07;//销售单号
                                        addPP.ExtendField08 = poItem.SpecAlias;//销售项号
 
                                        addPP.OriginPlace = "1";//打印次数
                                        addPP.LimitDate = item.limitDate;//限用日期 purchaseOrder  providerShortName providerShortName
                                        addPP.ProviderShortName = purchaseOrder.ProviderShortName;//供应商名称
                                        addPP.PlatUser_Id = 1;//必填垃圾信息
                                        addPP.UserProduct_Id = 1007;//必填垃圾信息
                                        addPP.ClassName = "采购入库";
                                        addPP.Class_Id = 0;
                                        addPP.MainID = 0;
                                        addPP.DetailID = 0;
                                        addPP.Storage_Id = 87;
                                        addPP.StorageName = "立体库";
                                        addPP.ProductModel = poItem.ProductName;
                                        addPP.ProductModel = "0";
                                        addPP.ConsignorCode = "GX30";
                                        addPP.ConsignorName = "广州西门子";
                                        addPP.Consignor_Id = 30;
                                        addPP.ExtendField10 = poItem.OrderList_Id.ToString();//这里记录 表purchase_orderlist的主键OrderList_Id值 【EditBy shaocx,2022-10-14】
                                        addPP.SmallUnit = poItem.BigUnit;
 
                                        mod.Base_ProductPosition.Add(addPP);
                                        //增加出入库记录 【EditBy shaocx,2022-03-07】
                                        OutInStockTaskHandler.AddOutInStockTask22(results.creator, mod, OutInStockTaskName.收货任务, addPP.ProductStorage, addPP, "按单收货-收货,收货暂存区,增加库存", addPP.PoCode);
                                        //按单收货
                                        grEntitys.Add(grEntity);//可以收货再发生sap
                                        #endregion
                                    }
                                    else
                                    {
                                        msg = "收货超出数量";
                                        saveSueeccd = false;
                                    }
                                }
                                else
                                {//退货
                                    //据我观察,必须是收货后的才能进行退后,未收货的不允许退哦 【EditBy shaocx,2022-10-14】
                                    if (poItem.BigEnterQuantity - item.quantity >= 0)
                                    {
                                        poItem.BigEnterQuantity = poItem.BigEnterQuantity - item.quantity;
                                        grEntitys.Add(grEntity);
                                        numInfo++;
 
                                        var query_OrderList_Id = poItem.OrderList_Id.ToString();
 
                                        //退货支持二维码 【EditBy shaocx,2024-07-58】
                                        var _list = mod.Base_ProductPosition.Where(x => x.PositionName == SysGlole.PositionName_SHZCQ
                                         && x.ExtendField10 != null && x.ExtendField10 == query_OrderList_Id).ToList();
                                        if (isQrCode)
                                        {
                                            _list = _list.Where(x => x.qrCode_guid == results.qrCode_guid).ToList();
                                        }
                                        Base_ProductPosition curStore = _list.FirstOrDefault();
                                        if (curStore == null)
                                        {
                                            //报错返回
                                            saveSueeccd = false;
                                            msg = "明细[采购项号:" + poItem.ItemNumber + ",物料:" + poItem.ProductName + "]没有被收货,因此不允许被退货";
                                            var data2 = new
                                            {
                                                result = saveSueeccd,
                                                msg
                                            };
                                            msg = JsonConvert.SerializeObject(data2);
                                            return msg;
                                        }
                                        //扣减暂存区数量
                                        if (curStore.ProductStorage < item.quantity)
                                        {
                                            //报错返回
                                            saveSueeccd = false;
                                            msg = "明细[采购项号:" + poItem.ItemNumber + ",物料:" + poItem.ProductName + "]收货数量" + curStore.ProductStorage + "不能小于退货数量" + item.quantity + ",因此不允许被退货";
                                            var data2 = new
                                            {
                                                result = saveSueeccd,
                                                msg
                                            };
                                            msg = JsonConvert.SerializeObject(data2);
                                            return msg;
                                        }
                                        curStore.ProductStorage = curStore.ProductStorage - item.quantity;
                                        string remark = "";
                                        if (curStore.ProductStorage == 0)
                                        {
                                            //表示全部退货了,库存删除
                                            mod.Base_ProductPosition.Remove(curStore);
                                            remark = "按单退货-退货,收货暂存区,全部退货,清空暂存区库存";
                                        }
                                        else
                                        {
                                            remark = "按单退货-退货,收货暂存区,减少库存";
                                        }
                                        //增加出入库记录 【EditBy shaocx,2022-10-14】
                                        OutInStockTaskHandler.AddOutInStockTask22(results.creator, mod, OutInStockTaskName.退货任务, item.quantity, curStore, remark, results.creator);
                                        //*/
                                    }
                                    else
                                    {
                                        msg = "退货库存不足";
                                        saveSueeccd = false;
                                    }
 
                                }
                            }
                            if (isFinish == results.dataList.Count)
                            {
                                purchaseOrder.StatusText = "完全交货";
                            }
                            else
                            {
                                purchaseOrder.StatusText = "部分交货";
                            }
 
                        }
                        if (grEntitys.Count > 0)
                        {
                            string sendSapGr = JsonConvert.SerializeObject(grEntitys);
                            var resultStr = receiptConfirm(sendSapGr);
                            ResultEntity fe = JsonConvert.DeserializeObject<ResultEntity>(resultStr);
                            if (fe.result == false)
                            {
                                msg = fe.msg;
                                saveSueeccd = false;
                            }
                        }
                        if (string.IsNullOrEmpty(msg))
                        {
                            OperationLogHelper.AddOperationLogEntity(mod, results.creator, "采购订单" + results.poCode.ToString() + "收货", OperateTypeEnum.按单收货, "");
 
                            int result = mod.SaveChanges();
                            #region 检查是否保存成功
                            for (int i = 0; i < 10; i++)
                            {
                                if (result < 1)
                                {
 
                                    result = mod.SaveChanges();
                                    if (i == 9 && result < 1)
                                    {
                                        msg = "保存失败";
                                    }
                                }
                                else
                                {
                                    msg = "执行成功,完成" + numInfo + "条信息";
                                    saveSueeccd = true;
                                    break;
                                }
 
                            }
                            #endregion
                        }
 
 
                    }
                }
            }
            catch (Exception ex)
            {
 
                msg = "执行失败";
            }
            var data = new
            {
                result = saveSueeccd,
                msg
            };
            msg = JsonConvert.SerializeObject(data);
            return msg;
        }
 
        /// <summary>调用方:在界面【物料标签打印】,选中并点击按钮“打印物料标签”,此时调用接口 api/storage/check/updateData,这时候要扣减收货暂存区的数量,调用wcftest的 subtractQty方法。
        /// 标签打印和码盘上架扣减收货数量
        /// </summary>
        /// <param name="subInfo">扣减list对象</param>
        /// <returns>扣减成功返回"成功",其余返回失败信息</returns>
        public bool subtractQty(string subInfo)
        {
            if (single.WaitOne())//增加线程锁防止并发
            {
                try
                {
                    logtxt.txtWrite("类名:Form1/函数名:subtractQty按单和码盘扣数量/ " + subInfo, 1);
                    List<subStroage> products = JsonConvert.DeserializeObject<List<subStroage>>(subInfo);
                    if (products.Count > 0)
                    {
                        for (int i = 0; i < products.Count; i++)
                        {
                            decimal subNumbeu = products[i].number;//需要扣减的数量
                            using (dbModel mod = new dbModel())
                            {
                                //查询收货物料
                                List<Base_ProductPosition> checkStroage = new List<Base_ProductPosition>();
                                string pocodu = products[i].poCode;
                                string productcode = products[i].productCode;
                                string trackting = "";
                                if (products[i].trackting != null)
                                {
                                    if (products[i].trackting != "")
                                    {
                                        trackting = products[i].trackting;
                                        checkStroage = mod.Base_ProductPosition.Where(x => x.ExtendField04 == trackting && x.ProductCode == productcode
                                           && x.PositionName == SysGlole.PositionName_SHZCQ  //增加收货暂存区的筛选 【Editby shaocx,2022-03-08】
                                            ).ToList();
                                    }
 
                                }
                                if (checkStroage.Count == 0)
                                {
                                    if (products[i].saleCode != null)
                                    {
                                        string SaleCode = products[i].saleCode;
                                        checkStroage = mod.Base_ProductPosition.Where(x => x.SaleCode == SaleCode && x.ProductCode == productcode
                                             && x.PositionName == SysGlole.PositionName_SHZCQ  //增加收货暂存区的筛选 【Editby shaocx,2022-03-08】
                                            ).ToList();
                                    }
                                }
                                if (checkStroage.Count == 0)
                                {
                                    checkStroage = mod.Base_ProductPosition.Where(x => x.ProductCode == productcode
                                         && x.PositionName == SysGlole.PositionName_SHZCQ  //增加收货暂存区的筛选 【Editby shaocx,2022-03-08】
                                        ).ToList();
                                }
 
                                #region 检查参数
                                if (checkStroage.Count == 0)
                                {
                                    // result = "没有这个物料";
                                    continue;
                                }
                                decimal sunStroage = (decimal)checkStroage.Sum(x => x.ProductStorage);//库存总数
                                //检查要扣的数量比库里数量多的话就返回错误
                                if (sunStroage < subNumbeu)
                                {
                                    //result = "缺料了要修改入库数量!";
                                    continue;
                                }
                                #endregion
                                #region 找到所有未打印数量大于0的收货记录
                                var logMsg = "";
                                foreach (var item in checkStroage)
                                {
                                    decimal stroageQty = (decimal)item.ProductStorage;
                                    if (stroageQty >= subNumbeu)
                                    {
                                        decimal? oldQty = item.ProductStorage;
                                        decimal? changeQty = subNumbeu;
                                        item.ProductStorage = stroageQty - subNumbeu;
                                        //增加出入库记录 【EditBy shaocx,2022-03-07】
                                        logMsg = "1标签打印和码盘上架扣减收货数量,原数量:" + oldQty + ",扣减数量" + changeQty;
                                        OutInStockTaskHandler.AddOutInStockTask22(item.Creator, mod, OutInStockTaskName.出库任务, changeQty, item, logMsg, pocodu);
 
                                        OperationLogHelper.AddOperationLogEntity(mod, item.Creator, logMsg, OperateTypeEnum.标签打印, "");
 
                                        mod.SaveChanges();
                                        // result = "成功";
                                        break;
                                    }
                                    else
                                    {
                                        item.ProductStorage = 0;
                                        subNumbeu -= stroageQty;
 
                                        //增加出入库记录 【EditBy shaocx,2022-03-07】
                                        logMsg = "2标签打印和码盘上架扣减收货数量,扣为0,原数量:" + stroageQty + ",扣减数量" + stroageQty;
                                        OutInStockTaskHandler.AddOutInStockTask22(item.Creator, mod, OutInStockTaskName.出库任务, stroageQty, item, logMsg, pocodu);
 
                                        OperationLogHelper.AddOperationLogEntity(mod, item.Creator, logMsg, OperateTypeEnum.标签打印, "");
                                    }
                                    if (subNumbeu == 0)
                                    {
                                        break;
                                    }
                                }
                                #endregion
                                mod.SaveChanges();
                            }
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    //result = "数据异常:";// +logtxt.oneRow(ex.ToString());
                    logtxt.txtWrite("类名:Form1/函数名:subtractQty按单和码盘扣除异常/ " + subInfo, 2);
                    return false;
                }
                finally { single.ReleaseMutex(); }//一轮结束
            }
            return true;
            //return ;
        }
 
        #endregion
 
        #region 组盘
 
        public string bindContiner(string receipt)
        {
            string msg = "";
            bool saveSueeccd = false;
            int numInfo = 0;
            bindContinerEntity results = JsonConvert.DeserializeObject<bindContinerEntity>(receipt);
            if (results.dataList == null || results.dataList.Count == 0)
            {
                var data23 = new
                {
                    result = false,
                    msg = "没有要处理的数据"
                };
                msg = JsonConvert.SerializeObject(data23);
                return msg;
            }
 
            if (!string.IsNullOrEmpty(results.plateCode))
            {
                var errMsg = "";
                var res = PlateCodeHandler.ValiatePlateIsAllowZP(results.plateCode, ref errMsg);
                if (!res)
                {
                    var data23 = new
                    {
                        result = false,
                        msg = errMsg
                    };
                    msg = JsonConvert.SerializeObject(data23);
                    return msg;
                }
            }
            else
            {
                if (results.isUnbind == false)
                {
                    var data23 = new
                    {
                        result = saveSueeccd,
                        msg = "托盘号不能为空"
                    };
                    msg = JsonConvert.SerializeObject(data23);
                    return msg;
                }
            }
 
            ////模拟写死,还得改回来 哦 
            //var data22 = new
            //{
            //    result = saveSueeccd,
            //    msg = "我错了"
            //};
            //msg = JsonConvert.SerializeObject(data22);
            //return msg;
 
            try
            {
                using (dbModel mod = new dbModel())
                {
                    foreach (var item in results.dataList)
                    {
                        var isExistObj = mod.Base_ProductPosition.Where(x => x.ExtendField06 == item.ExtendField06).ToList();
                        if (isExistObj != null && isExistObj.Count > 0)
                        {
                            foreach (var item2 in isExistObj)
                            {
                                if (results.isUnbind)
                                {
                                    //更新码盘数据
                                    if (item2.PlateCode == "")
                                    {
                                        var data23 = new
                                        {
                                            result = false,
                                            msg = "标签条码'" + item.ExtendField06 + "'重复扫码解绑"
                                        };
                                        msg = JsonConvert.SerializeObject(data23);
                                        return msg;
                                    }
                                    item2.PlateCode = "";
                                }
                                else
                                {
                                    //更新码盘数据
                                    if (item2.PlateCode == results.plateCode)
                                    {
                                        var data23 = new
                                        {
                                            result = false,
                                            msg = "标签条码'" + item.ExtendField06 + "'重复扫码码盘"
                                        };
                                        msg = JsonConvert.SerializeObject(data23);
                                        return msg;
                                    }
                                    item2.PlateCode = results.plateCode;
                                }
                                numInfo++;
                            }
                        }
                        else
                        {
                            var data23 = new
                            {
                                result = false,
                                msg = "没有找到标签条码'" + item.ExtendField06 + "'的库存"
                            };
                            msg = JsonConvert.SerializeObject(data23);
                            return msg;
                        }
                    }
 
                    int result = mod.SaveChanges();
                    if (result <= 0)
                    {
                        msg = "保存失败";
                    }
                    else
                    {
                        msg = "执行成功,完成" + numInfo + "条信息";
                        saveSueeccd = true;
                    }
                    var data99 = new
                    {
                        result = saveSueeccd,
                        msg = msg
                    };
                    msg = JsonConvert.SerializeObject(data99);
                    return msg;
                }
            }
            catch (Exception ex)
            {
 
                msg = "执行失败:" + ex.Message;
            }
            var data = new
            {
                result = saveSueeccd,
                msg
            };
            msg = JsonConvert.SerializeObject(data);
            return msg;
        }
 
 
        /// <summary>
        /// 通用验证数据
        /// </summary>
        /// <param name="receipt"></param>
        /// <returns></returns>
        public string validateDataCommon(string receipt)
        {
            string msg = "";
            bool saveSueeccd = false;
            validateDataEntity results = JsonConvert.DeserializeObject<validateDataEntity>(receipt);
            if (results == null)
            {
                var data23 = new
                {
                    result = false,
                    msg = "没有要处理的数据"
                };
                msg = JsonConvert.SerializeObject(data23);
                return msg;
            }
            if (results.flag == 1)
            {
                foreach (var item in results.dataList)
                {
                    if (string.IsNullOrEmpty(item.plateCode))
                    {
                        var data23 = new
                        {
                            result = saveSueeccd,
                            msg = "托盘号不能为空"
                        };
                        msg = JsonConvert.SerializeObject(data23);
                        return msg;
                    }
                    if (string.IsNullOrEmpty(item.ExtendField06))
                    {
                        var data23 = new
                        {
                            result = saveSueeccd,
                            msg = "标签条码不能为空"
                        };
                        msg = JsonConvert.SerializeObject(data23);
                        return msg;
                    }
                }
            }
 
            ////模拟写死,还得改回来 哦 
            //var data22 = new
            //{
            //    result = saveSueeccd,
            //    msg = "我错了"
            //};
            //msg = JsonConvert.SerializeObject(data22);
            //return msg;
 
            try
            {
                using (dbModel mod = new dbModel())
                {
                    msg = "";
                    if (results.flag == 1)
                    {
                        foreach (var item in results.dataList)
                        {
                            var isExistObj = mod.Base_ProductPosition.Where(x => x.ExtendField06 == item.ExtendField06).ToList();
                            if (isExistObj != null && isExistObj.Count > 0)
                            {
                                foreach (var item22 in isExistObj)
                                {
                                    if (!string.IsNullOrEmpty(item22.PlateCode) && item22.PlateCode != item.plateCode)
                                    {
                                        msg += "物料" + item.productName + ",标签条码" + item.ExtendField06 + "已经绑定到另一个托盘'" + item22.PlateCode + "'上了;";
 
                                    }
                                }
                            }
                        }
                    }
                    if (msg != "")
                    {
                        var data23 = new
                        {
                            result = false,
                            msg = msg + ",重新绑定到新托盘'" + results.dataList.First().plateCode + "'将会解除与原托盘的绑定,是否要继续操作?"
                        };
                        msg = JsonConvert.SerializeObject(data23);
                        return msg;
                    }
                    else
                    {
                        msg = "执行成功";
                        saveSueeccd = true;
                    }
                }
            }
            catch (Exception ex)
            {
 
                msg = "执行失败:" + ex.Message;
            }
            var data = new
            {
                result = saveSueeccd,
                msg
            };
            msg = JsonConvert.SerializeObject(data);
            return msg;
        }
 
        #endregion
 
 
        /// <summary>获取库存盘点列表
        /// 获取库存盘点列表
        /// </summary>
        /// <param name="takes"></param>
        /// <returns></returns>
        public string takeStock(string takes)
        {
            try
            {
                stockSearchEntity take = JsonConvert.DeserializeObject<stockSearchEntity>(takes);
                string StockWhere = "";
 
 
                //根据货位名称/采购单号/托盘号/物料名称/物料编号模糊查找
 
 
                if (!string.IsNullOrEmpty(take.search.materialCode))
                {
                    StockWhere = StockWhere + " and MateralCode like '%" + take.search.materialCode.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(take.search.materialName))
                {
                    StockWhere = StockWhere + " and MateralName like '%" + take.search.materialName.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(take.search.saleCode))
                {
                    StockWhere = StockWhere + " and ProcureCode like '%" + take.search.saleCode.Trim() + "%'";
                }
                string StockWhere_All = StockWhere, StockWhere_OnlySap = StockWhere, StockWhere_OnlyStock = StockWhere;
 
                if (take.positionTypeValue > 1)
                {
                    //string isOrAnd = StockWhere == "" ? " or " : " and ";
                    switch (take.positionTypeValue)
                    {
 
                        case 2:
                            StockWhere = StockWhere + "and StockQuantity > 0 and SapQuantity > 0";
                            break;
                        case 3:
                            StockWhere = StockWhere + "and SapQuantity = 0";
                            break;
                        case 4:
                            StockWhere = StockWhere + "and StockQuantity = 0 ";
                            break;
 
                    }
                }
 
 
                //获取盘点数据
 
                msgss<TakeStock> msg = new msgss<TakeStock>();
                using (dbModel mod = new dbModel())
                {
 
                    //获取盘点数据
                    var baseSql = "select * from [dbo].[" + "TakeStock" + "] where ID > 1  ";
                    string sql = baseSql + StockWhere;
                    List<TakeStock> takeStockSummary = mod.Database.SqlQuery<TakeStock>("select * from [dbo].[" + "TakeStock" + "] where ID = 1").ToList();
                    List<TakeStock> takeStock = mod.Database.SqlQuery<TakeStock>(sql).ToList();
                    List<TakeStock> fenyeRerult = new List<TakeStock>();
                    if (takeStock.Count > 0)
                    {
                        var allList = takeStockSummary.Concat(takeStock.ToList()).ToList();
                        if (take.IsLoadAllData)
                        {//只有确定加载全部数据时才加载全部数据 [EditBy shaocx,2022-03-07]
                            msg.status = 200;
                            msg.allDate = allList;
                        }
                        else
                        {//不加载全部,就过滤分页信息
                            StockWhere_All = StockWhere_All + "and StockQuantity > 0 and SapQuantity > 0";
                            StockWhere_OnlyStock = StockWhere_OnlyStock + "and SapQuantity = 0";
                            StockWhere_OnlySap = StockWhere_OnlySap + "and StockQuantity = 0 ";
                            StockWhere_All = baseSql + StockWhere_All;
                            StockWhere_OnlyStock = baseSql + StockWhere_OnlyStock;
                            StockWhere_OnlySap = baseSql + StockWhere_OnlySap;
                            GetSummaryTitle(mod, StockWhere_All, StockWhere_OnlyStock, StockWhere_OnlySap, allList);
                            //构造数据
                            msg.allDate = new List<TakeStock>();
                            TakeStock one = new TakeStock();
                            one.MateralName = allList[0].MateralName;
                            msg.allDate.Add(one);
 
                            msg.status = 200;
                            msg.total = takeStock.Count;
 
                            //假如每页数量 大于盘点数据
                            if (take.queryInfo.pagesize > takeStock.Count)
                            {
                                msg.date = takeStock;
                            }
                            else
                            {
                                #region 分页计算
                                int a = take.queryInfo.pagesize;
 
                                int b = take.queryInfo.pagenum;
                                int c = (int)Math.Ceiling((double)takeStock.Count / a);
                                int d = takeStock.Count % a;
                                int e = 0;
                                int f = a * (b - 1);
                                if (d != 0 && b == c)
                                {
                                    e = d + f;
 
                                }
                                else
                                {
                                    e = a + f;
                                }
 
 
 
                                for (int i = f; i < e; i++)
                                {
                                    fenyeRerult.Add(takeStock[i]);
                                }
                                msg.date = fenyeRerult;
                                #endregion
 
                            }
                        }
                    }
                    else
                    {
                        msg.status = 400;
                        msg.total = 1;
                        msg.date = null;
                    }
 
                    return JsonConvert.SerializeObject(msg);
                }
 
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                msgss<TakeStock> msg = new msgss<TakeStock>();
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
                return JsonConvert.SerializeObject(msg);
            }
 
        }
 
        /// <summary>
        /// 获取盘点数据的汇总字符串 [EditBy shaocx,2022-01-23]
        /// </summary>
        /// <param name="mod"></param>
        /// <param name="StockWhere_All"></param>
        /// <param name="StockWhere_OnlyStock"></param>
        /// <param name="StockWhere_OnlySap"></param>
        /// <param name="allTakeStock"></param>
        /// <returns></returns>
        private void GetSummaryTitle(dbModel mod, string StockWhere_All, string StockWhere_OnlyStock, string StockWhere_OnlySap, List<TakeStock> allTakeStock)
        {
            var takeStock_All = mod.Database.SqlQuery<TakeStock>(StockWhere_All).ToList();
            var takeStock_OnlyStock = mod.Database.SqlQuery<TakeStock>(StockWhere_OnlyStock).ToList();
            var takeStock_OnlySap = mod.Database.SqlQuery<TakeStock>(StockWhere_OnlySap).ToList();
 
            var msg = string.Format("数量差异数据:{0}条, 仅立库数据:{1}条, 仅SAP数据:{2}条。",
                takeStock_All == null ? 0 : takeStock_All.Count(),
                takeStock_OnlyStock == null ? 0 : takeStock_OnlyStock.Count(),
                takeStock_OnlySap == null ? 0 : takeStock_OnlySap.Count()
                );
            allTakeStock[0].MateralName = msg;
        }
        /// <summary>出入库任务列表
        /// 出入库任务列表
        /// </summary>
        /// <param name="pages">jison参数</param>
        /// <returns></returns>
        public string outInTaskList(string pages)
        {
            msgss<OutInStockTask> msg = new msgss<OutInStockTask>();
            msg.status = 400;
            msg.total = 1;
            msg.date = null;
            try
            {
 
                stockSearchEntity page = JsonConvert.DeserializeObject<stockSearchEntity>(pages);
                string StockWhere = " id>0";
                //根据日期筛选
 
 
                if (page.datatime != null)
                {
                    if (page.datatime.Length == 2)
                    {
 
                        StockWhere = StockWhere + "and creatDate > '" + page.datatime[0].ToString() + "' and  creatDate < '" + page.datatime[1].ToString() + "'";
                    }
                }
 
                //根据货位名称/采购单号/托盘号/物料名称/物料编号模糊查找
                if (!string.IsNullOrEmpty(page.search.creator))
                {
                    StockWhere = StockWhere + " and creator like '%" + page.search.creator.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.materialName))
                {
                    StockWhere = StockWhere + " and materialName like '%" + page.search.materialName.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.materialCode))
                {
                    StockWhere = StockWhere + " and materialNumber like '%" + page.search.materialCode.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.tranckNnmber))
                {
                    StockWhere = StockWhere + " and trackNumber like '%" + page.search.tranckNnmber.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.positionName))
                {//库位号
                    StockWhere = StockWhere + " and positionName='" + page.search.positionName + "' ";
                }
                if (!string.IsNullOrEmpty(page.search.placeCode))
                {//托盘号 [EditBy shaocx,2022-08-09]
                    StockWhere = StockWhere + " and ext1='" + page.search.placeCode + "' ";
                }
 
 
                if (page.positionTypeValue != 99)
                {
                    OutInStockTaskName _OutInStockTaskName = (OutInStockTaskName)Enum.Parse(typeof(OutInStockTaskName), page.positionTypeValue.ToString());
                    //string taskname = page.positionTypeValue == 1 ? "入库任务" : "出库任务";
                    StockWhere = StockWhere + " and taskName= '" + _OutInStockTaskName.ToString() + "'";
                }
                using (dbModel mod = new dbModel())
                {
                    //获取盘点数据
                    string sql = "select * from [dbo].[" + "OutInStockTask" + "] where " + StockWhere + " order by id desc ";//isFreeze    是否有货   先拿这个字段用 
 
                    List<OutInStockTask> takeStock = mod.Database.SqlQuery<OutInStockTask>(sql).ToList();
 
                    List<OutInStockTask> fenyeRerult = new List<OutInStockTask>();
                    if (takeStock.Count > 0)
                    {
                        msg.status = 200;
                        msg.total = takeStock.Count;
                        // msg.date = takeStock;
 
                        if (page.IsLoadAllData)
                        {//只有确定加载全部数据时才加载全部数据 [EditBy shaocx,2022-03-07]
                            msg.status = 200;
                            msg.allDate = takeStock.ToList();
                        }
                        else
                        {//不加载全部,就过滤分页信息
                            //假如每页数量 大于盘点数据
                            if (page.queryInfo.pagesize > takeStock.Count)
                            {
                                msg.date = takeStock;
                            }
                            else
                            {
                                #region 分页计算
                                int a = page.queryInfo.pagesize;
 
                                int b = page.queryInfo.pagenum;
                                int c = (int)Math.Ceiling((double)takeStock.Count / a);
                                int d = takeStock.Count % a;
                                int e = 0;
                                int f = a * (b - 1);
                                if (d != 0 && b == c)
                                {
                                    e = d + f;
 
                                }
                                else
                                {
                                    e = a + f;
                                }
 
 
 
                                for (int i = f; i < e; i++)
                                {
                                    fenyeRerult.Add(takeStock[i]);
                                }
                                msg.date = fenyeRerult;
                                #endregion
 
                            }
                        }
                    }
                }
                return JsonConvert.SerializeObject(msg);
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                msg = new msgss<OutInStockTask>();
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
                msg.msg = "异常:" + ex.Message;
                return JsonConvert.SerializeObject(msg);
            }
 
        }
 
        /// <summary>空库位统计
        /// 空库位统计
        /// </summary>
        /// <param name="pages">jison参数</param>
        /// <returns></returns>
        public string getPositionTotal(string pages)
        {
            msgss<emtypPosition> msg = new msgss<emtypPosition>();
            try
            {
                List<emtypPosition> emtyps = new List<emtypPosition>();//汇总数据
 
                using (dbModel mod = new dbModel())
                {
                    #region 一排空库位统计
 
                    BussinessExtension.BussinessExtension.EmptyPositionTongJiForArea1(mod, ref emtyps);
 
                    #endregion
 
                    #region 二排小库位空库位统计
 
                    //二排小库位
                    BussinessExtension.BussinessExtension.EmptyPositionTongJiForArea2_Small(mod, ref emtyps);
 
                    #endregion
 
                    #region 二排大托盘
 
                    BussinessExtension.BussinessExtension.EmptyPositionTongJiForArea2_Big(mod, ref emtyps);
 
                    #endregion
 
 
 
                    msg.status = 200;
                    msg.date = emtyps;
                    return JsonConvert.SerializeObject(msg);
                }
 
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("类apitest 方法 getPositionTotal" + ex.Message + ex.StackTrace.ToString(), 2);
                msg.status = 400;
                return JsonConvert.SerializeObject(msg); ;
            }
 
        }
 
        /// <summary>库存明细-只查询物料
        /// 库存明细
        /// </summary>
        /// <param name="pages">jison参数</param>
        /// <returns></returns>
        public string productStockInfo(string pages)
        {
            msgss<vvBase_ProductPosition_all> msg = new msgss<vvBase_ProductPosition_all>();
            msg.roleDelete = 0;
            msg.roleModifi = 0;
            msg.buttonAuth = "";
            try
            {
 
                stockSearchEntity page = JsonConvert.DeserializeObject<stockSearchEntity>(pages);
                roleMenu ROLEid = JsonConvert.DeserializeObject<roleMenu>(pages);
                string StockWhere = "";
                //根据日期筛选
                #region 搜索条件判断
                if (page.datatime != null)
                {
                    if (page.datatime.Length == 2)
                    {
                        StockWhere = "and InStorageDate > '" + page.datatime[0].ToString() + "' and  InStorageDate < '" + page.datatime[1].ToString() + "'";
                    }
                }
                if (!string.IsNullOrEmpty(page.search.BarCode))//条码
                {
                    StockWhere = StockWhere + "and BarCode like '%" + page.search.BarCode.Trim() + "%'";
                }
                if (page.QueryBarCodeFlagValue == QueryBarCodeFlagEnum.仅查询二维码)
                {
                    StockWhere = StockWhere + "and IsQrCode ='1'";
                }
                else if (page.QueryBarCodeFlagValue == QueryBarCodeFlagEnum.仅查询一维码)
                {
                    StockWhere = StockWhere + "and IsQrCode ='0'";
                }
 
                if (!string.IsNullOrEmpty(page.search.materialName))//物料名称
                {
                    StockWhere = StockWhere + "and ProductName like '%" + page.search.materialName.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.materialCode))//物料编号
                {
                    StockWhere = StockWhere + "and ProductCode like '%" + page.search.materialCode.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.placeCode))//托盘号
                {
                    StockWhere = StockWhere + "and PlateCode like '%" + page.search.placeCode.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.positionName))//库位名称
                {
                    StockWhere = StockWhere + "and PositionName like '%" + page.search.positionName.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.purchaseCode))//采购单号
                {
                    StockWhere = StockWhere + "and PoCode like '%" + page.search.purchaseCode.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.tranckNnmber))//跟踪号
                {
                    StockWhere = StockWhere + "and ExtendField04 like '%" + page.search.tranckNnmber.Trim() + "%'";
                }
                if (page.positionTypeValue > 0)//货位类型
                {
                    StockWhere = StockWhere + " and PositionType=" + page.positionTypeValue.ToString();
                }
 
                //增加查询条件
                if (page.search.IsLocked)
                {
                    StockWhere = StockWhere + " and IsLocked=1 ";
                }
                if (page.search.ContainerNo)
                {
                    StockWhere = StockWhere + " and ContainerNo='1' ";
                }
                if (page.search.IsFreeze)
                {
                    StockWhere = StockWhere + " and IsFreeze=0 ";
                }
                if (page.search.OnlyLocked)
                {
                    StockWhere = StockWhere + " and IsLocked=1  and ContainerNo <> '1' ";
                }
 
                #endregion
                using (dbModel mod = new dbModel())
                {
                    //使用权限
                    var authHandle = AuthFactory.GetHandle(mod, ROLEid, Menu_IdEnum.库存明细查询);
                    authHandle.GetButtonAuthStr<vvBase_ProductPosition_all>(ref msg);
 
                    /*
                    string roleSQL = "SELECT * FROM [YrtWMS_Siemens2].[dbo].[Sys_RoleAuth] WITH(NOLOCK) where Menu_Id=385 and Role_Id=" + ROLEid.role_Id;
                    var roleishave = mod.Database.SqlQuery<Sys_RoleAuth>(roleSQL).ToList();
                    if (roleishave.Count > 0)
                    {
                        if (roleishave[0].AuthValue.Contains("delete=1"))
                        {
                            msg.roleDelete = 1;
                            msg.buttonAuth += "delete;";
                        }
                        if (roleishave[0].AuthValue.Contains("updatePosition=1"))
                        {
                            msg.roleModifi = 1;
                            msg.buttonAuth += "updatePosition;";
                        }
                    }
                    //*/
                    //获取盘点数据
                    string sql = "select * from [dbo].[" + "vvBase_ProductPosition_all" + "] WITH(NOLOCK) where ProductStorage>0 " + StockWhere + " order by InStorageDate desc ";//isFreeze    是否有货   先拿这个字段用 
 
                    List<vvBase_ProductPosition_all> takeStockList = mod.Database.SqlQuery<vvBase_ProductPosition_all>(sql).ToList();
                    //增加 显示在库天数 [EditBy shaocx,2022-06-08]
                    takeStockList = BussinessExtension.BussinessExtension.CalcInStoreDays(takeStockList.ToList());
                    //用在库天数过滤数据  [EditBy shaocx,2022-06-08]
                    var errMsg = "";
                    takeStockList = BussinessExtension.BussinessExtension.FiltervvBase_ProductPositionByInStoreDays(takeStockList, page, ref errMsg);
                    if (!string.IsNullOrEmpty(errMsg))
                    {
 
                    }
 
                    List<vvBase_ProductPosition_all> fenyeRerult = new List<vvBase_ProductPosition_all>();
                    if (takeStockList.Count > 0)
                    {
                        msg.status = 200;
                        msg.total = takeStockList.Count;
                        if (page.IsLoadAllData)
                        {//只有确定加载全部数据时才加载全部数据 [EditBy shaocx,2022-03-07]
                            msg.status = 200;
                            msg.allDate = takeStockList.ToList();
                        }
                        else
                        {//不加载全部,就过滤分页信息
                            //假如每页数量 大于盘点数据
                            if (page.queryInfo.pagesize > takeStockList.Count)
                            {
                                msg.date = takeStockList;
                            }
                            else
                            {
                                #region 分页计算
                                int a = page.queryInfo.pagesize;
 
                                int b = page.queryInfo.pagenum;
                                int c = (int)Math.Ceiling((double)takeStockList.Count / a);
                                int d = takeStockList.Count % a;
                                int e = 0;
                                int f = a * (b - 1);
                                if (d != 0 && b == c)
                                {
                                    e = d + f;
 
                                }
                                else
                                {
                                    e = a + f;
                                }
 
 
 
                                for (int i = f; i < e; i++)
                                {
                                    fenyeRerult.Add(takeStockList[i]);
                                }
                                msg.date = fenyeRerult;
                                #endregion
 
                            }
                        }
                    }
                    else
                    {
                        msg.status = 400;
                        msg.total = 1;
                        msg.date = null;
                    }
 
                    return JsonConvert.SerializeObject(msg);
                }
 
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
                return JsonConvert.SerializeObject(msg);
            }
 
        }
 
 
        /// <summary>修改库存
        /// 修改库存
        /// </summary>
        /// <param name="updateInfo">json修改数据</param>
        /// <returns></returns>
        public string updateProductStock(string updateInfo)
        {
            try
            {
                msgss<string> msg = new msgss<string>();
                //msg.status = 400;
                //msg.total = 1;
                //msg.date = null;
                //msg.msg = "参数不能为空";
                //return JsonConvert.SerializeObject(msg);
 
                updateStock updateData = JsonConvert.DeserializeObject<updateStock>(updateInfo);
                if (updateData == null)
                {
                    msg.status = 400;
                    msg.total = 1;
                    msg.date = null;
                    msg.msg = "参数不能为空";
                    return JsonConvert.SerializeObject(msg);
                }
                //验证修改数量 【EditBy shaocx,2022-06-13】
                if (updateData.productStorage <= 0)
                {
                    msg.status = 400;
                    msg.total = 1;
                    msg.date = null;
                    msg.msg = "修改数量不能小于等于0";
                    return JsonConvert.SerializeObject(msg);
                }
                if (updateData.LimitDate == null)
                {
                    msg.status = 400;
                    msg.total = 1;
                    msg.date = null;
                    msg.msg = "限用日期不能为空";
                    return JsonConvert.SerializeObject(msg);
                }
 
 
                updateData.saleCode = updateData.saleCode != null ? updateData.saleCode.Trim() : "";
                updateData.saleItem = updateData.saleItem != null ? updateData.saleItem.Trim() : "";
                updateData.tracknumber = updateData.tracknumber != null ? updateData.tracknumber.Trim() : "";
                updateData.productCode = updateData.productCode != null ? updateData.productCode.Trim() : "";
 
                using (dbModel mod = new dbModel())
                {
                    //查找库存
                    VmaterialInfo materialInfo = mod.VmaterialInfo.FirstOrDefault(x => x.ProductCode == updateData.productCode);
 
                    Base_ProductPosition updateStock = mod.Base_ProductPosition.Find(updateData.stockId);
                    var logTitle = "物料编号/名称:" + updateStock.ProductCode + "/" + updateStock.ProductName + ",货位名称:" + updateStock.PositionName + ",托盘号:" + updateStock.BillCode + ",";
 
                    Base_ProductPosition old_updateStock = JsonConvert.DeserializeObject<Base_ProductPosition>(JsonConvert.SerializeObject(updateStock));//旧库存
 
                    VmaterialInfo materialInfoOriginal = mod.VmaterialInfo.FirstOrDefault(x => x.Product_Id == updateStock.Product_Id);
                    if (updateStock != null && materialInfo != null && materialInfoOriginal != null)
                    {
                        #region 修改
 
                        string operationInfo = logTitle + "";
                        if (updateStock.ExtendField04 != updateData.tracknumber)
                        {
                            operationInfo += "跟踪号" + updateStock.ExtendField04 + "改到" + updateData.tracknumber + ",";
                        }
                        if (updateStock.ProductStorage != updateData.productStorage)
                        {
                            operationInfo += "库存量" + updateStock.ProductStorage + "改到" + updateData.productStorage + ",";
                        }
                        if (updateStock.LimitDate != updateData.LimitDate)
                        {
                            operationInfo += "限用日期" + updateStock.LimitDate + "改到" + updateData.LimitDate + ",";
                        }
 
                        updateStock.ExtendField04 = updateData.tracknumber;//跟踪号
                        updateStock.ExtendField08 = updateData.saleItem;//销售项号
                        updateStock.SaleCode = updateData.saleCode;//销售单号
 
                        updateStock.Product_Id = Convert.ToInt32(materialInfo.Product_Id);//产品编号
 
                        //修改限用日期 [EditBy shaocx,2022-06-14]
                        updateStock.LimitDate = updateData.LimitDate;
 
                        decimal? old_ProductStorage = updateStock.ProductStorage;
                        //decimal? changeQty = old_ProductStorage - updateData.productStorage;
                        updateStock.ProductStorage = updateData.productStorage;//库存量
                        //增加出入库记录 【EditBy shaocx,2022-03-07】
                        OutInStockTaskHandler.AddOutInStockTask22(updateData.userName, mod, OutInStockTaskName.出库任务, old_updateStock.ProductStorage, old_updateStock, "人为修改库存,操作人:" + updateData.userName + "-出库记录," + operationInfo, "");
                        OutInStockTaskHandler.AddOutInStockTask22(updateData.userName, mod, OutInStockTaskName.入库任务, updateStock.ProductStorage, updateStock, "人为修改库存,操作人:" + updateData.userName + "-入库记录," + operationInfo, "");
 
 
                        int result = mod.SaveChanges();
                        if (result == 0)
                        {
                            //失败再保存一次
                            msg.status = 400;
                            msg.total = 1;
                            msg.date = null;
                        }
 
                        else
                        {
                            //删除成功
                            msg.status = 200;
                            msg.total = 1;
                            msg.date = null;
                            OperationLogHelper.SaveOperationLog(updateData.userName, "修改库存:" + operationInfo, OperateTypeEnum.修改库存);
                            logtxt.txtWrite("apitest-" + "updateProductStock-修改库存" + operationInfo, 2);
                        }
 
                        #endregion
                    }
                    else
                    {
                        msg.status = 400;
                        msg.total = 1;
                        msg.date = null;
                    }
                    return JsonConvert.SerializeObject(msg);
                }
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                msgss<string> msg = new msgss<string>();
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
                return JsonConvert.SerializeObject(msg);
 
            }
 
        }
        /// <summary>库存汇总
        /// 库存汇总
        /// </summary>
        /// <param name="pages">jison参数</param>
        /// <returns></returns>
        public string findProductStock(string pages)
        {
            msgss<vvBase_ProductPosition> msg = new msgss<vvBase_ProductPosition>();
            try
            {
 
                stockSearchEntity page = JsonConvert.DeserializeObject<stockSearchEntity>(pages);
 
                string StockWhere = "";
                //根据日期筛选
                #region 搜索条件判断
                if (page.datatime != null)
                {
                    if (page.datatime.Length == 2)
                    {
 
                        StockWhere = StockWhere + " and InStorageDate > '" + page.datatime[0].ToString() + "' and  InStorageDate < '" + page.datatime[1].ToString() + "'";
                    }
                }
 
                //根据货位名称/采购单号/托盘号/物料名称/物料编号模糊查找
 
                if (!string.IsNullOrEmpty(page.search.materialName))
                {
                    StockWhere = StockWhere + " and ProductName like '%" + page.search.materialName.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.materialCode))
                {
                    StockWhere = StockWhere + " and ProductCode like '%" + page.search.materialCode.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.tranckNnmber))
                {
                    StockWhere = StockWhere + " and ExtendField04 like '%" + page.search.tranckNnmber.Trim() + "%'";
                }
                if (page.positionTypeValue > 0)
                {
                    if (page.positionTypeValue == 66)
                    {
                        StockWhere = StockWhere + " and PositionType=1 and IsLocked=0 and ContainerNo=0";
                    }
                    else
                    {
                        StockWhere = StockWhere + " and PositionType=" + page.positionTypeValue.ToString();
                    }
 
                }
                #endregion
 
                using (dbModel mod = new dbModel())
                {
                    //获取盘点数据
                    string sql = "select * from [dbo].[" + "vvBase_ProductPosition" + "] where ProductStorage>0  " + StockWhere + " order by ProductPosition_Id desc ";//isFreeze    是否有货   先拿这个字段用 
 
                    List<vvBase_ProductPosition> takeStock = mod.Database.SqlQuery<vvBase_ProductPosition>(sql).ToList();
                    List<vvBase_ProductPosition> sunStockShou = new List<vvBase_ProductPosition>();//汇总后加入到集合
                    var StockGroup = takeStock.GroupBy(x => new { x.ExtendField04, x.ProductCode }).ToList();//x.SaleCode, x.ExtendField08 之前根据销售单号分组,后因为人工新建的料没有 所以改成跟踪号
                    foreach (var itemSum in StockGroup)
                    {
                        for (int i = 1; i < itemSum.ToList().Count; i++)
                        {
                            itemSum.ToList()[0].ProductStorage = itemSum.ToList()[0].ProductStorage + itemSum.ToList()[i].ProductStorage;
                        }
                        sunStockShou.Add(itemSum.ToList()[0]);
                    }
 
 
                    if (page.alarmValue == 1)//Brand_Id 预警值
                    {
                        takeStock = sunStockShou.Where(x => x.Brand_Id > 0 && x.ProductStorage <= x.Brand_Id).ToList();
                        if (string.IsNullOrEmpty(page.search.tranckNnmber))
                        {
 
                            #region 添加物料里预警值搜索
 
                            //查找物料里设置了预警值的
                            //  List<VmaterialInfo> warningValueName = mod.VmaterialInfo.Where(x => x.Brand_Id > 0&&).ToList();
                            string alarmValueSql = "select * from [dbo].[" + "VmaterialInfo" + "] where Brand_Id>0  ";
                            if (!string.IsNullOrEmpty(page.search.materialName))
                            {
                                alarmValueSql = alarmValueSql + " and ProductName like '%" + page.search.materialName.Trim() + "%'";
                            }
                            if (!string.IsNullOrEmpty(page.search.materialCode))
                            {
                                alarmValueSql = alarmValueSql + " and ProductCode like '%" + page.search.materialCode.Trim() + "%'";
                            }
                            List<VmaterialInfo> warningValueName = mod.Database.SqlQuery<VmaterialInfo>(alarmValueSql).ToList();
                            List<string> warningValue = warningValueName.Select(x => x.ProductCode).ToList();
                            //查找库存里所有物料编号
                            List<string> warningValueStock = sunStockShou.Select(x => x.ProductCode).ToList();
                            //设置了预警值库存里为零的    var Toplace = rowResultSpl.Where(x => !toPlaceList.Contains(x.PositionName)).ToList();
                            List<string> zeroStock = warningValue.Where(x => !warningValueStock.Contains(x)).ToList();
                            foreach (var item in zeroStock)
                            {
                                VmaterialInfo findZero = warningValueName.FirstOrDefault(x => x.ProductCode == item);
                                if (page.search.positionName != null && page.search.positionName.Trim() != "")
                                {
                                    if (findZero.ProductCode.Contains(page.search.positionName.Trim()) || findZero.ProductName.Contains(page.search.positionName.Trim()))
                                    {
                                        vvBase_ProductPosition zeroProduct = new vvBase_ProductPosition();
                                        zeroProduct.ProductCode = item;
                                        zeroProduct.ProductName = findZero.ProductName;
                                        zeroProduct.ProductStorage = 0;
                                        zeroProduct.SmallUnit = findZero.SmallUnit;
                                        zeroProduct.Brand_Id = findZero.Brand_Id;
                                        takeStock.Add(zeroProduct);
                                    }
                                }
                                else
                                {
                                    vvBase_ProductPosition zeroProduct = new vvBase_ProductPosition();
                                    zeroProduct.ProductCode = item;
                                    zeroProduct.ProductName = findZero.ProductName;
                                    zeroProduct.ProductStorage = 0;
                                    zeroProduct.SmallUnit = findZero.SmallUnit;
                                    zeroProduct.Brand_Id = findZero.Brand_Id;
                                    takeStock.Add(zeroProduct);
                                }
 
                            }
                            #endregion
 
                        }
 
 
                    }
                    else
                    {
                        takeStock = sunStockShou;
                    }
                    List<vvBase_ProductPosition> fenyeRerult = new List<vvBase_ProductPosition>();
                    if (takeStock.Count > 0)
                    {
                        msg.status = 200;
                        msg.total = takeStock.Count;
                        if (page.IsLoadAllData)
                        {//只有确定加载全部数据时才加载全部数据 [EditBy shaocx,2022-03-07]
                            msg.status = 200;
                            msg.allDate = takeStock.ToList();
                        }
                        else
                        {//不加载全部,就过滤分页信息
                            //假如每页数量 大于盘点数据
                            if (page.queryInfo.pagesize > takeStock.Count)
                            {
                                msg.date = takeStock;
                            }
                            else
                            {
                                #region 分页计算
                                int a = page.queryInfo.pagesize;
 
                                int b = page.queryInfo.pagenum;
                                int c = (int)Math.Ceiling((double)takeStock.Count / a);
                                int d = takeStock.Count % a;
                                int e = 0;
                                int f = a * (b - 1);
                                if (d != 0 && b == c)
                                {
                                    e = d + f;
 
                                }
                                else
                                {
                                    e = a + f;
                                }
 
 
 
                                for (int i = f; i < e; i++)
                                {
                                    fenyeRerult.Add(takeStock[i]);
                                }
                                msg.date = fenyeRerult;
                                #endregion
 
                            }
                        }
                    }
                    else
                    {
                        msg.status = 400;
                        msg.total = 1;
                        msg.date = null;
                    }
 
                    return JsonConvert.SerializeObject(msg);
                }
 
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
                return JsonConvert.SerializeObject(msg);
            }
 
        }
 
        /// <summary>查询过期库存预警 【EditBy shaocx,2022-08-06】
        /// 查询过期库存预警
        /// </summary>
        /// <param name="pages">jison参数</param>
        /// <returns></returns>
        public string findOldLibraryEarlyWarning(string pages)
        {
            msgss<vOldLibraryEarlyWarning> msg = new msgss<vOldLibraryEarlyWarning>();
            msg.roleDelete = 0;
            msg.roleModifi = 0;
 
            try
            {
 
                stockSearchEntity page = JsonConvert.DeserializeObject<stockSearchEntity>(pages);
                roleMenu ROLEid = JsonConvert.DeserializeObject<roleMenu>(pages);
                string StockWhere = "";
                //根据日期筛选
                #region 搜索条件判断
                if (page.datatime != null)
                {
                    if (page.datatime.Length == 2)
                    {
                        StockWhere = "and InStorageDate > '" + page.datatime[0].ToString() + "' and  InStorageDate < '" + page.datatime[1].ToString() + "'";
                    }
                }
                if (page.datatime_limit != null)
                {
                    if (page.datatime_limit.Length == 2)
                    {
                        StockWhere = "and limitDate > '" + page.datatime_limit[0].ToString() + "' and  limitDate < '" + page.datatime_limit[1].ToString() + "'";
                    }
                }
 
 
                if (page.search.Expired)//表示已过期 -ly
                {
                    StockWhere = StockWhere + "and LimitDay > 0";
                }
 
                if (!page.search.Expired && page.search.Days > 0)//表示即将在30天内过期
                {
                    //StockWhere = StockWhere + "and LimitDay >= -30 and LimitDay <= 0";
                    StockWhere = StockWhere + "and LimitDay >  -" + (int)page.search.Days + " and LimitDay <= 0";
                }
 
 
                if (!string.IsNullOrEmpty(page.search.BarCode))//条码
                {
                    StockWhere = StockWhere + "and BarCode like '%" + page.search.BarCode.Trim() + "%'";
                }
                if (page.QueryBarCodeFlagValue == QueryBarCodeFlagEnum.仅查询二维码)
                {
                    StockWhere = StockWhere + "and IsQrCode ='1'";
                }
                else if (page.QueryBarCodeFlagValue == QueryBarCodeFlagEnum.仅查询一维码)
                {
                    StockWhere = StockWhere + "and IsQrCode ='0'";
                }
 
                if (!string.IsNullOrEmpty(page.search.materialName))//物料名称
                {
                    StockWhere = StockWhere + "and ProductName like '%" + page.search.materialName.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.materialCode))//物料编号
                {
                    StockWhere = StockWhere + "and ProductCode like '%" + page.search.materialCode.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.placeCode))//托盘号
                {
                    StockWhere = StockWhere + "and PlateCode like '%" + page.search.placeCode.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.positionName))//库位名称
                {
                    StockWhere = StockWhere + "and PositionName like '%" + page.search.positionName.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.purchaseCode))//采购单号
                {
                    StockWhere = StockWhere + "and PoCode like '%" + page.search.purchaseCode.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.tranckNnmber))//跟踪号
                {
                    StockWhere = StockWhere + "and ExtendField04 like '%" + page.search.tranckNnmber.Trim() + "%'";
                }
 
                //增加查询条件
                if (page.search.IsLocked)
                {
                    StockWhere = StockWhere + " and IsLocked=1 ";
                }
                if (page.search.ContainerNo)
                {
                    StockWhere = StockWhere + " and ContainerNo='1' ";
                }
                if (page.search.IsFreeze)
                {
                    StockWhere = StockWhere + " and IsFreeze=0 ";
                }
                if (page.search.OnlyLocked)
                {
                    StockWhere = StockWhere + " and IsLocked=1  and ContainerNo <> '1' ";
                }
 
                if (page.positionTypeValue > 0)
                {
                    if (page.positionTypeValue == 66)
                    {
                        StockWhere = StockWhere + " and PositionType=1 and IsLocked=0 and ContainerNo=0";
                    }
                    else
                    {
                        StockWhere = StockWhere + " and PositionType=" + page.positionTypeValue.ToString();
                    }
 
                }
 
 
                #endregion
                using (dbModel mod = new dbModel())
                {
                    //使用权限
                    var authHandle = AuthFactory.GetHandle(mod, ROLEid, Menu_IdEnum.过期库存预警);
                    authHandle.GetButtonAuthStr<vOldLibraryEarlyWarning>(ref msg);
                    ////使用权限
                    //string roleSQL = "SELECT * FROM [YrtWMS_Siemens2].[dbo].[Sys_RoleAuth] WITH(NOLOCK) where Menu_Id=1571 and Role_Id=" + ROLEid.role_Id;
                    //var roleishave = mod.Database.SqlQuery<Sys_RoleAuth>(roleSQL).ToList();
                    //if (roleishave.Count > 0)
                    //{
                    //    if (roleishave[0].AuthValue.Contains("delete=1"))
                    //    {
                    //        msg.roleDelete = 1;
                    //    }
                    //    if (roleishave[0].AuthValue.Contains("updatePosition=1"))
                    //    {
                    //        msg.roleModifi = 1;
                    //    }
                    //}
 
                    //获取盘点数据
                    //排序,按照 过期天数降序排序
                    string sql = "select * from [dbo].[" + "vOldLibraryEarlyWarning" + "] where ProductStorage>0 " + StockWhere + " order by LimitDay desc ";//isFreeze    是否有货   先拿这个字段用 InStorageDate
 
                    List<vOldLibraryEarlyWarning> takeStockList = mod.Database.SqlQuery<vOldLibraryEarlyWarning>(sql).ToList();
                    ////增加 显示在库天数 [EditBy shaocx,2022-06-08]
                    //takeStockList = BussinessExtension.BussinessExtension.CalcInStoreDays(takeStockList.ToList());
                    ////用在库天数过滤数据  [EditBy shaocx,2022-06-08]
                    //var errMsg = "";
                    //takeStockList = BussinessExtension.BussinessExtension.FiltervvBase_ProductPositionByInStoreDays(takeStockList, page, ref errMsg);
                    //if (!string.IsNullOrEmpty(errMsg))
                    //{
 
                    //}
 
                    List<vOldLibraryEarlyWarning> fenyeRerult = new List<vOldLibraryEarlyWarning>();
                    if (takeStockList.Count > 0)
                    {
                        msg.status = 200;
                        msg.total = takeStockList.Count;
                        if (page.IsLoadAllData)
                        {//只有确定加载全部数据时才加载全部数据 [EditBy shaocx,2022-03-07]
                            msg.status = 200;
                            msg.allDate = takeStockList.ToList();
                        }
                        else
                        {//不加载全部,就过滤分页信息
                            //假如每页数量 大于盘点数据
                            if (page.queryInfo.pagesize > takeStockList.Count)
                            {
                                msg.date = takeStockList;
                            }
                            else
                            {
                                #region 分页计算
                                int a = page.queryInfo.pagesize;
 
                                int b = page.queryInfo.pagenum;
                                int c = (int)Math.Ceiling((double)takeStockList.Count / a);
                                int d = takeStockList.Count % a;
                                int e = 0;
                                int f = a * (b - 1);
                                if (d != 0 && b == c)
                                {
                                    e = d + f;
 
                                }
                                else
                                {
                                    e = a + f;
                                }
 
 
 
                                for (int i = f; i < e; i++)
                                {
                                    fenyeRerult.Add(takeStockList[i]);
                                }
                                msg.date = fenyeRerult;
                                #endregion
 
                            }
                        }
                    }
                    else
                    {
                        msg.status = 400;
                        msg.total = 1;
                        msg.date = null;
                    }
 
                    return JsonConvert.SerializeObject(msg);
                }
 
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
                return JsonConvert.SerializeObject(msg);
            }
 
 
        }
 
        /// <summary>查询反馈给SAP数据的记录  【EditBy shaocx,2022-02-01】
        /// 查询反馈给SAP数据的记录
        /// </summary>
        /// <param name="pages">jison参数</param>
        /// <returns></returns>
        public string findSendToSapData(string pages)
        {
            msgss<SapSendInfo> msg = new msgss<SapSendInfo>();
            try
            {
 
                sendToSapDataSearchEntity page = JsonConvert.DeserializeObject<sendToSapDataSearchEntity>(pages);
 
                string StockWhere = "";
                //根据日期筛选
                #region 搜索条件判断
                if (page.datatime != null)
                {
                    if (page.datatime.Length == 2)
                    {
 
                        StockWhere = StockWhere + " and creatTime > '" + page.datatime[0].ToString() + "' and  creatTime < '" + page.datatime[1].ToString() + "'";
                    }
                }
 
                //根据货位名称/采购单号/托盘号/物料名称/物料编号模糊查找
 
 
                if (!string.IsNullOrEmpty(page.search.materialCode))
                {
                    StockWhere = StockWhere + " and MaterialCode like '%" + page.search.materialCode.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.materialName))
                {
                    StockWhere = StockWhere + " and MaterialName like '%" + page.search.materialName.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.SalesOrder))
                {
                    StockWhere = StockWhere + " and SalesOrder like '%" + page.search.SalesOrder.Trim() + "%'";
                }
 
                if (!string.IsNullOrEmpty(page.positionTypeValue))
                {
                    StockWhere = StockWhere + " and moveType=" + page.positionTypeValue.ToString();
                }
                #endregion
 
                using (dbModel mod = new dbModel())
                {
                    //获取数据
                    string sql = "select * from [dbo].[" + "SapSendInfo" + "] where 1=1  " + StockWhere + " order by id desc ";
 
                    List<SapSendInfo> takeStock = mod.Database.SqlQuery<SapSendInfo>(sql).ToList();
 
                    List<SapSendInfo> fenyeRerult = new List<SapSendInfo>();
                    if (takeStock.Count > 0)
                    {
                        msg.status = 200;
                        msg.total = takeStock.Count;
                        if (page.IsLoadAllData)
                        {//只有确定加载全部数据时才加载全部数据 [EditBy shaocx,2022-03-07]
                            msg.status = 200;
                            msg.allDate = takeStock.ToList();
                        }
                        else
                        {//不加载全部,就过滤分页信息
                            //假如每页数量 大于盘点数据
                            if (page.queryInfo.pagesize > takeStock.Count)
                            {
                                msg.date = takeStock;
                            }
                            else
                            {
                                #region 分页计算
                                int a = page.queryInfo.pagesize;
 
                                int b = page.queryInfo.pagenum;
                                int c = (int)Math.Ceiling((double)takeStock.Count / a);
                                int d = takeStock.Count % a;
                                int e = 0;
                                int f = a * (b - 1);
                                if (d != 0 && b == c)
                                {
                                    e = d + f;
 
                                }
                                else
                                {
                                    e = a + f;
                                }
 
 
 
                                for (int i = f; i < e; i++)
                                {
                                    fenyeRerult.Add(takeStock[i]);
                                }
                                msg.date = fenyeRerult;
                                #endregion
 
                            }
                        }
                    }
                    else
                    {
                        msg.status = 400;
                        msg.total = 1;
                        msg.date = null;
                    }
 
                    return JsonConvert.SerializeObject(msg);
                }
 
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
                return JsonConvert.SerializeObject(msg);
            }
 
        }
 
 
        /// <summary>查询反馈给SAP数据失败的记录  【EditBy shaocx,2022-03-06】
        /// 查询反馈给SAP数据失败的记录
        /// </summary>
        /// <param name="pages">jison参数</param>
        /// <returns></returns>
        public string findSendToSapFailData(string pages)
        {
            msgss<SapSendFailRecodInfo> msg = new msgss<SapSendFailRecodInfo>();
            try
            {
 
                sendToSapDataFailSearchEntity page = JsonConvert.DeserializeObject<sendToSapDataFailSearchEntity>(pages);
 
                string StockWhere = "";
                //根据日期筛选
                #region 搜索条件判断
                if (page.datatime != null)
                {
                    if (page.datatime.Length == 2)
                    {
 
                        StockWhere = StockWhere + " and CreateTime > '" + page.datatime[0].ToString() + "' and  CreateTime < '" + page.datatime[1].ToString() + "'";
                    }
                }
 
                //根据货位名称/采购单号/托盘号/物料名称/物料编号模糊查找
 
 
                if (!string.IsNullOrEmpty(page.search.materialCode))
                {
                    StockWhere = StockWhere + " and MaterialCode like '%" + page.search.materialCode.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.materialName))
                {
                    StockWhere = StockWhere + " and MaterialName like '%" + page.search.materialName.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.SalesOrder))
                {
                    StockWhere = StockWhere + " and SalesOrder like '%" + page.search.SalesOrder.Trim() + "%'";
                }
                if (!string.IsNullOrEmpty(page.search.purchaseCode))
                {//采购单号
                    StockWhere = StockWhere + " and pocode = '" + page.search.purchaseCode.Trim() + "'";
                }
 
                if (!string.IsNullOrEmpty(page.positionTypeValue))
                {
                    StockWhere = StockWhere + " and MoveType=" + page.positionTypeValue.ToString();
                }
                #endregion
 
                using (dbModel mod = new dbModel())
                {
                    //获取数据
                    string sql = "select * from [dbo].[" + "SapSendFailRecodInfo" + "] where 1=1  " + StockWhere + " order by id desc ";
 
                    List<SapSendFailRecodInfo> takeStock = mod.Database.SqlQuery<SapSendFailRecodInfo>(sql).ToList();
 
                    List<SapSendFailRecodInfo> fenyeRerult = new List<SapSendFailRecodInfo>();
                    if (takeStock.Count > 0)
                    {
                        msg.status = 200;
                        msg.total = takeStock.Count;
                        if (page.IsLoadAllData)
                        {//只有确定加载全部数据时才加载全部数据 [EditBy shaocx,2022-03-07]
                            msg.status = 200;
                            msg.allDate = takeStock.ToList();
                        }
                        else
                        {//不加载全部,就过滤分页信息
                            //假如每页数量 大于盘点数据
                            if (page.queryInfo.pagesize > takeStock.Count)
                            {
                                msg.date = takeStock;
                            }
                            else
                            {
                                #region 分页计算
                                int a = page.queryInfo.pagesize;
 
                                int b = page.queryInfo.pagenum;
                                int c = (int)Math.Ceiling((double)takeStock.Count / a);
                                int d = takeStock.Count % a;
                                int e = 0;
                                int f = a * (b - 1);
                                if (d != 0 && b == c)
                                {
                                    e = d + f;
 
                                }
                                else
                                {
                                    e = a + f;
                                }
 
 
 
                                for (int i = f; i < e; i++)
                                {
                                    fenyeRerult.Add(takeStock[i]);
                                }
                                msg.date = fenyeRerult;
                                #endregion
 
                            }
                        }
                    }
                    else
                    {
                        msg.status = 400;
                        msg.total = 1;
                        msg.date = null;
                    }
 
                    return JsonConvert.SerializeObject(msg);
                }
 
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
                return JsonConvert.SerializeObject(msg);
            }
 
        }
 
 
 
        /// <summary>手动出库查找库存
        /// 
        /// </summary>
        /// <param name="pages">jison参数</param>
        /// <returns></returns>
        public string handfindProductStock(string pages)
        {
            msgss<vvBase_ProductPosition> msg = new msgss<vvBase_ProductPosition>();
            try
            {
 
                productStockEntity page = JsonConvert.DeserializeObject<productStockEntity>(pages);
 
                string StockWhere = "";
                //根据日期筛选
                if (page.datatime != null)
                {
                    if (page.datatime.Length == 2)
                    {
 
                        StockWhere = StockWhere + " and InStorageDate > '" + page.datatime[0].ToString() + "' and  InStorageDate < '" + page.datatime[1].ToString() + "'";
                    }
                }
 
                //根据货位名称/采购单号/托盘号/物料名称/物料编号模糊查找
                if (page.positionName.Trim() != "")
                {
                    string[] paparms = page.positionName.Trim().Split('/');
 
                    if (paparms[2].Trim() != "")
                    {
                        StockWhere = StockWhere + " and (ProductName like '%" + paparms[2].Trim() + "%' or ProductCode like '%" + paparms[2].Trim() + "%')";
                    }
                    StockWhere = paparms[1].Trim() == "" ? StockWhere : StockWhere + " and ExtendField04 = '" + paparms[1].Trim() + "'";
                    StockWhere = paparms[0].Trim() == "" ? StockWhere : StockWhere + " and positionName = '" + paparms[0].Trim() + "'";
                    // StockWhere = StockWhere + " and (ProductName like '%" + ProductName + "%' or ProductCode like '%" + ProductCode + "%' or ExtendField04='" + trackNumber + "')";
                }
 
                if (page.positionTypeValue > 0)
                {
                    if (page.positionTypeValue == 66)
                    {
                        StockWhere = StockWhere + " and PositionType=1 and IsLocked=0 and ContainerNo=0";
                    }
                    else
                    {
                        StockWhere = StockWhere + " and PositionType=" + page.positionTypeValue.ToString();
                    }
 
                }
 
                using (dbModel mod = new dbModel())
                {
                    //获取盘点数据
                    string sql = "select * from [dbo].[" + "vvBase_ProductPosition" + "] where ProductStorage>0  " + StockWhere + " order by ProductPosition_Id desc ";//isFreeze    是否有货   先拿这个字段用 
 
                    List<vvBase_ProductPosition> takeStock = mod.Database.SqlQuery<vvBase_ProductPosition>(sql).ToList();
                    List<vvBase_ProductPosition> sunStockShou = new List<vvBase_ProductPosition>();//汇总后加入到集合
                    var StockGroup = takeStock.GroupBy(x => new { x.ExtendField04, x.ProductCode }).ToList();//x.SaleCode, x.ExtendField08 之前根据销售单号分组,后因为人工新建的料没有 所以改成跟踪号
                    foreach (var itemSum in StockGroup)
                    {
                        for (int i = 1; i < itemSum.ToList().Count; i++)
                        {
                            itemSum.ToList()[0].ProductStorage = itemSum.ToList()[0].ProductStorage + itemSum.ToList()[i].ProductStorage;
                        }
                        sunStockShou.Add(itemSum.ToList()[0]);
                    }
 
 
                    if (page.alarmValue == 1)//Brand_Id 预警值
                    {
                        takeStock = sunStockShou.Where(x => x.Brand_Id > 0 && x.ProductStorage <= x.Brand_Id).ToList();
                    }
                    else
                    {
                        takeStock = sunStockShou;
                    }
                    List<vvBase_ProductPosition> fenyeRerult = new List<vvBase_ProductPosition>();
                    if (takeStock.Count > 0)
                    {
                        msg.status = 200;
                        msg.total = takeStock.Count;
                        // msg.date = takeStock;
 
                        //假如每页数量 大于盘点数据
                        if (page.queryInfo.pagesize > takeStock.Count)
                        {
                            msg.date = takeStock;
                        }
                        else
                        {
                            #region 分页计算
                            int a = page.queryInfo.pagesize;
 
                            int b = page.queryInfo.pagenum;
                            int c = (int)Math.Ceiling((double)takeStock.Count / a);
                            int d = takeStock.Count % a;
                            int e = 0;
                            int f = a * (b - 1);
                            if (d != 0 && b == c)
                            {
                                e = d + f;
 
                            }
                            else
                            {
                                e = a + f;
                            }
 
 
 
                            for (int i = f; i < e; i++)
                            {
                                fenyeRerult.Add(takeStock[i]);
                            }
                            msg.date = fenyeRerult;
                            #endregion
 
                        }
 
                    }
                    else
                    {
                        msg.status = 400;
                        msg.total = 1;
                        msg.date = null;
                    }
 
                    return JsonConvert.SerializeObject(msg);
                }
 
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
                return JsonConvert.SerializeObject(msg);
            }
 
        }
 
        /// <summary>删除库存
        /// 删除库存
        /// </summary>
        /// <param name="deleteId">库存ID</param>
        /// <returns></returns>
        public string DeleteProductStock(int deleteId, string userName)
        {
            try
            {
 
                msgss<string> msg = new msgss<string>();
                using (dbModel mod = new dbModel())
                {
                    if (deleteId < 1)
                    {
                        msg.status = 400;
                        msg.total = 1;
                        msg.date = null;
                    }
                    else
                    {
 
                        Base_ProductPosition deleteStock = mod.Base_ProductPosition.Find(deleteId);
                        if (deleteStock != null)
                        {
                            List<Base_ProductPosition> deleteStocks = mod.Base_ProductPosition.Where(x => x.PositionName == deleteStock.PositionName).ToList();
                            //只有一条库存的时候不可以删,删了托盘就出不来了
                            #region 删除操作
                            if (deleteStocks.Count == 1)
                            {
                                msg.status = 500;
                                msg.total = 1;
                                msg.date = null;
                            }
                            else
                            {
                                mod.Base_ProductPosition.Remove(deleteStock);
                                //增加出入库记录 【EditBy shaocx,2022-03-07】
                                OutInStockTaskHandler.AddOutInStockTask22(userName, mod, OutInStockTaskName.清库任务, deleteStock.ProductStorage, deleteStock, "操作人:" + userName + ",删除库存,清空库存", "");
                                int result = mod.SaveChanges();
                                if (result == 0)
                                {
                                    //失败再保存一次
                                    msg.status = 550;
                                    msg.total = 1;
                                    msg.date = null;
                                }
 
                                else
                                {
                                    //删除成功
                                    msg.status = 200;
                                    msg.total = 1;
                                    msg.date = null;
                                    OperationLogHelper.SaveOperationLog(userName, "库存明细-删除库存:" + deleteStock.PositionName + "物料名称:" + deleteStock.ProductCode, OperateTypeEnum.删除库存);
                                    logtxt.txtWrite("apitest-" + "库存明细-删除库存" + deleteStock.PositionName + "物料名称:" + deleteStock.ProductCode, 2);
                                }
 
                            }
                            #endregion
                        }
                    }
                    return JsonConvert.SerializeObject(msg);
                }
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                msgss<string> msg = new msgss<string>();
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
                return JsonConvert.SerializeObject(msg);
 
            }
 
        }
 
        /// <summary>移库
        /// 移库
        /// </summary>
        /// <param name="positionName">库位名称</param>
        /// <returns></returns>
        public string moveStock(string positionName, string username)
        {
            //移库直接返回错误 【EditBy shaocx,2022-09-22】
            msgss<string> msg3 = new msgss<string>();
            msg3.status = 400;
            msg3.total = 1;
            msg3.date = null;
            return JsonConvert.SerializeObject(msg3);
 
            //try
            //{
            //    positionName = positionName.Trim();
            //    msgss<string> msg = new msgss<string>();
            //    if (string.IsNullOrEmpty(positionName.Trim()))//判断库位是否为空
            //    {
            //        msg.status = 400;
            //        msg.total = 1;
            //        msg.date = null;
            //        return JsonConvert.SerializeObject(msg);
            //    }
            //    string[] positionname = positionName.Trim().Split('-');
            //    string sourcePlace = "";
            //    int areaCode = 0;
            //    if (positionname.Length != 4)//判断是否是库位格式
            //    {
            //        msg.status = 400;
            //        msg.total = 1;
            //        msg.date = null;
            //        return JsonConvert.SerializeObject(msg);
            //    }
            //    sourcePlace = positionname[1] + "-" + positionname[2] + "-" + positionname[3];//其实地址
            //    areaCode = Convert.ToInt32(positionname[0]);//库区
            //    if (areaCode != 1 && areaCode != 2)//重复判断库区格式
            //    {
            //        msg.status = 400;
            //        msg.total = 1;
            //        msg.date = null;
            //        return JsonConvert.SerializeObject(msg);
            //    }
            //    int layer = Convert.ToInt32(positionname[3]);//当前层
            //    string toplace = "";
            //    // Form1 form = new Form1();
            //    using (dbModel mod = new dbModel())
            //    {
            //        List<Base_ProductPosition> deleteStocks = mod.Base_ProductPosition.Where(x => x.PositionName == positionName).ToList();
            //        //锁定状态不允许移库
            //        Base_Position deleteStockisLock = mod.Base_Position.FirstOrDefault(x => x.PositionName == positionName && x.IsLocked == 0);
            //        if (deleteStockisLock == null)
            //        {
            //            msg.status = 400;
            //            msg.total = 1;
            //            msg.date = null;
            //            return JsonConvert.SerializeObject(msg);
            //        }
            //        int plateType = 0;//托盘类型
            //        #region 判断操作
            //        if (deleteStocks.Count < 1)//判断这个库位有没有信息
            //        {
            //            msg.status = 400;
            //            msg.total = 1;
            //            msg.date = null;
            //            return JsonConvert.SerializeObject(msg);
            //        }
 
            //        bool convertSucceed = Int32.TryParse(deleteStocks[0].PlateType, out plateType);
            //        if (!convertSucceed)//盘点托盘类型转换是否成功
            //        {
            //            msg.status = 400;
            //            msg.total = 1;
            //            msg.date = null;
            //            return JsonConvert.SerializeObject(msg);
            //        }
            //        #endregion
 
            //        int containterHeight = 0;//托盘高度类型
 
            //        #region 判断高度类型
 
            //        //2号库小库位
            //        //1-11   高度4
            //        //3,5,7,9,10  高度3
            //        //2,4,6,8,  高度1
            //        //2号库大托盘
            //        //1,13,14  高度4
            //        //2           高度3
            //        //6,9,12    高度2
            //        //4,5,7,8,10,11 高度1
            //        if (areaCode == 1)//1号库区都是库位
            //        {
            //            if (layer == 1 || layer == 11)
            //            {
            //                containterHeight = 2;
            //            }
            //            else
            //            {
            //                containterHeight = 1;
            //            }
            //        }
            //        else
            //        {
            //            if (plateType == 1)//2号库区小库位
            //            {
            //                #region 2号库区小库位
            //                if (layer == 1 || layer == 11)
            //                {
            //                    containterHeight = 4;
            //                }
            //                else if (layer == 3 || layer == 5 || layer == 7 || layer == 9 || layer == 10)
            //                {
            //                    containterHeight = 3;
            //                }
            //                else
            //                {
            //                    containterHeight = 1;
            //                }
            //                #endregion
 
            //            }
            //            else//2号库区大库位
            //            {
            //                #region 2号库区大库位
            //                if (layer == 1 || layer == 13 || layer == 14)
            //                {
            //                    containterHeight = 4;
            //                }
            //                else if (layer == 2)
            //                {
            //                    containterHeight = 3;
            //                }
            //                else if (layer == 6 || layer == 9 || layer == 12)
            //                {
            //                    containterHeight = 2;
            //                }
            //                else
            //                {
            //                    containterHeight = 1;
            //                }
            //                #endregion
 
            //            }
            //        }
            //        #endregion
            //        var findEmptyReason = "";
            //        bool isInMoreHighPosition = false;
            //        toplace = FindEmptyLocationHandler.findStorage("", true, ref isInMoreHighPosition, ref findEmptyReason, areaCode, Convert.ToInt32(deleteStocks[0].PlateType), containterHeight);//分配库位
 
            //        #region 写入任务表
            //        Task_Queue addTask = new Task_Queue();
            //        addTask.BillCode = "移库";//来源单号
            //        addTask.TaskType = ((int)TaskTypeEnum.移库).ToString();
            //        addTask.PlateType = deleteStocks[0].PlateType;//器具种类-大托盘小托盘
            //        addTask.PlateCode = deleteStocks[0].PlateCode;//母托盘编号
            //        addTask.Bill_Id = 0;// 单据id
            //        addTask.OrderNumber = 0;//任务执行优先级
            //        addTask.TaskStatus = "未下发";//任务状态
            //        addTask.FromPositionName = sourcePlace;//起始地址
            //        addTask.ToPositionName = toplace;//目标地址给空返回测量高度后重新写入
            //        addTask.Direction = areaCode == 1 ? "2" : "4";//出库不需要托盘高度
            //        addTask.DoCount = areaCode;//库区
            //        addTask.CreateDate = DateTime.Now;
            //        addTask.UserProduct_Id = 1007;//账套id 老谢bug  
            //        mod.Task_Queue.Add(addTask);
 
            //        #endregion
 
            //        //添加日志
            //        SystemHelper.addOperation(username, "移库:从" + positionName + "到" + toplace, "移库");
 
            //        int result = mod.SaveChanges();
            //        #region 失败再保存一次
            //        if (result == 0)//失败再保存一次
            //        {
            //            result = mod.SaveChanges();
            //            if (result == 0)
            //            {
            //                //返回失败
            //                msg.status = 400;
            //                msg.total = 1;
            //                msg.date = null;
            //            }
            //            else
            //            {
            //                //删除成功
            //                msg.status = 200;
            //                msg.total = 1;
            //                msg.date = null;
            //            }
            //        }
 
            //        else
            //        {
            //            //删除成功
            //            msg.status = 200;
            //            msg.total = 1;
            //            msg.date = null;
            //        }
            //        #endregion
 
            //        return JsonConvert.SerializeObject(msg);
            //    }
            //}
            //catch (Exception ex)
            //{
            //    logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
            //    msgss<string> msg = new msgss<string>();
            //    msg.status = 400;
            //    msg.total = 1;
            //    msg.date = null;
            //    return JsonConvert.SerializeObject(msg);
 
            //}
 
        }
 
        /// <summary>大屏综合信息
        /// 大屏综合信息
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public string getDeviceInfo(string startTime, string endTime)
        {
            string result = "";
            try
            {
                int[] list1 = totalInfo.list11;
                string[] list2 = totalInfo.list22;
                List<sendDeviceStatus> data = new List<sendDeviceStatus>();
                sendDeviceStatus runStatus = new sendDeviceStatus();
                runStatus.name = "设备运行时间";
                sendDeviceStatus waitStatus = new sendDeviceStatus();
                waitStatus.name = "设备等待时间";
                sendDeviceStatus alarmStatus = new sendDeviceStatus();
                alarmStatus.name = "设备报警时间";
                List<string> xdata = new List<string>();
                using (dbModel mod = new dbModel())
                {
                    DateTime _startTime = Convert.ToDateTime(startTime);
                    DateTime _endTime = Convert.ToDateTime(endTime);
                    List<deviceGeneralInfo> fiveDayDeviceInfo = mod.deviceGeneralInfo.Where(x => x.createTime >= _startTime && x.createTime <= _endTime).OrderByDescending(x => x.createTime)
                        //.Take(5)
                        .ToList();
                    if (fiveDayDeviceInfo.Count > 0)
                    {
 
                        foreach (var item in fiveDayDeviceInfo)
                        {
                            runStatus.xdata.Add(item.deviceRunTime.ToString() == null ? "0" : item.deviceRunTime.ToString());
                            alarmStatus.xdata.Add(item.deviceAlarmTime.ToString() == null ? "0" : item.deviceAlarmTime.ToString());
                            //重新计算等待时间
                            item.deviceWaitTime = 1440 - ((item.deviceRunTime ?? 0M) + (item.deviceAlarmTime ?? 0M));
                            waitStatus.xdata.Add(item.deviceWaitTime.ToString() == null ? "0" : item.deviceWaitTime.ToString());
                            xdata.Add(item.createTime.ToString().Split(' ')[0]);
                        }
 
                    }
 
                }
                data.Add(runStatus);
                data.Add(waitStatus);
 
                //x轴顺序重新排序 【Editby shaocx,2024-12-30】
                xdata = xdata.OrderBy(x => x).ToList();
                string[] legend = { "p设备运行时间", "p设备等待时间", "p设备异常时间" };
                var workpiece = new
                 {
                     data,
                     legend,
                     xdata
 
                 };
                data.Add(alarmStatus);
                var date = new
                {
                    list1,
                    list2,
                    workpiece
 
                };
                result = JsonConvert.SerializeObject(date);
                return result;
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("类名:Form1/函数名:writeOutTask出库写入任务异常/ " + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                return result;
            }
 
        }
 
        /// <summary>
        /// 分页查询 堆垛机运行统计
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string QueryPageDeviceGeneralInfo(string param)
        {
            msgss<deviceGeneralInfoForDetail> msg = new msgss<deviceGeneralInfoForDetail>();
            DeviceGeneralInfoInput page = JsonConvert.DeserializeObject<DeviceGeneralInfoInput>(param);
            try
            {
                using (dbModel mod = new dbModel())
                {
                    List<deviceGeneralInfoForDetail> fiveDayDeviceInfo = null;
                    if (page.datatime == null)
                    {
                        fiveDayDeviceInfo = mod.deviceGeneralInfoForDetail
                           .OrderByDescending(x => x.createTime)
                           .ToList();
                    }
                    else
                    {
                        DateTime _startTime = Convert.ToDateTime(page.datatime[0]);
                        DateTime _endTime = Convert.ToDateTime(page.datatime[1]);
                        fiveDayDeviceInfo = mod.deviceGeneralInfoForDetail
                           .Where(x => x.createTime >= _startTime && x.createTime <= _endTime)
                           .OrderByDescending(x => x.createTime)
                           .ToList();
                    }
 
                    if (fiveDayDeviceInfo.Count > 0)
                    {
                        foreach (var item in fiveDayDeviceInfo)
                        {
                            //重新计算等待时间
                            item.deviceWaitTime = 1440 - ((item.deviceRunTime ?? 0M) + (item.deviceAlarmTime ?? 0M));
                        }
                    }
 
                    List<deviceGeneralInfoForDetail> fenyeRerult = new List<deviceGeneralInfoForDetail>();
                    if (fiveDayDeviceInfo.Count > 0)
                    {
                        msg.status = 200;
                        msg.total = fiveDayDeviceInfo.Count;
                        if (page.IsLoadAllData)
                        {//只有确定加载全部数据时才加载全部数据 [EditBy shaocx,2022-03-07]
                            msg.status = 200;
                            msg.allDate = fiveDayDeviceInfo.ToList();
                        }
                        else
                        {//不加载全部,就过滤分页信息
                            //假如每页数量 大于盘点数据
                            if (page.queryInfo.pagesize > fiveDayDeviceInfo.Count)
                            {
                                msg.date = fiveDayDeviceInfo;
                            }
                            else
                            {
                                #region 分页计算
                                int a = page.queryInfo.pagesize;
 
                                int b = page.queryInfo.pagenum;
                                int c = (int)Math.Ceiling((double)fiveDayDeviceInfo.Count / a);
                                int d = fiveDayDeviceInfo.Count % a;
                                int e = 0;
                                int f = a * (b - 1);
                                if (d != 0 && b == c)
                                {
                                    e = d + f;
 
                                }
                                else
                                {
                                    e = a + f;
                                }
 
 
 
                                for (int i = f; i < e; i++)
                                {
                                    fenyeRerult.Add(fiveDayDeviceInfo[i]);
                                }
                                msg.date = fenyeRerult;
                                #endregion
 
                            }
                        }
                    }
                    else
                    {
                        msg.status = 400;
                        msg.total = 1;
                        msg.date = null;
                    }
 
 
                    return JsonConvert.SerializeObject(msg);
                }
 
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
 
                return JsonConvert.SerializeObject(msg);
            }
 
        }
 
        /// <summary>
        /// 分页查询 PO明细空物料号信息
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string QueryPagePurchaseEmptyMaterialCode(string param)
        {
            msgss<Purchase_OrderList_EmptyMaterialCode> msg = new msgss<Purchase_OrderList_EmptyMaterialCode>();
            Purchase_OrderList_EmptyMaterialCodeInput page = JsonConvert.DeserializeObject<Purchase_OrderList_EmptyMaterialCodeInput>(param);
            try
            {
                using (dbModel mod = new dbModel())
                {
                    List<Purchase_OrderList_EmptyMaterialCode> fiveDayDeviceInfo = new List<Purchase_OrderList_EmptyMaterialCode>();
 
                    Expression<Func<Purchase_OrderList_EmptyMaterialCode, bool>> predicate_datatime = x => 1 == 1;
                    if (page.datatime != null)
                    {
                        DateTime _startTime = Convert.ToDateTime(page.datatime[0]);
                        DateTime _endTime = Convert.ToDateTime(page.datatime[1]);
                        predicate_datatime = x => x.CreateTime >= _startTime && x.CreateTime <= _endTime;
                    }
                    Expression<Func<Purchase_OrderList_EmptyMaterialCode, bool>> predicate_poCode = x => 1 == 1;
                    if (!string.IsNullOrEmpty(page.search.PoCode))
                    {
                        predicate_poCode = x => x.PoCode == page.search.PoCode;
                    }
                    Expression<Func<Purchase_OrderList_EmptyMaterialCode, bool>> predicate_ItemNumber = x => 1 == 1;
                    if (!string.IsNullOrEmpty(page.search.ItemNumber))
                    {
                        predicate_poCode = x => x.ItemNumber == page.search.ItemNumber;
                    }
                    Expression<Func<Purchase_OrderList_EmptyMaterialCode, bool>> predicate_ProductName = x => 1 == 1;
                    if (!string.IsNullOrEmpty(page.search.ProductName))
                    {
                        predicate_poCode = x => x.ProductName == page.search.ProductName;
                    }
                    fiveDayDeviceInfo = mod.Purchase_OrderList_EmptyMaterialCode
                        .Where(predicate_datatime)
                        .Where(predicate_poCode)
                        .Where(predicate_ItemNumber)
                        .Where(predicate_ProductName)
                        .ToList();
 
 
                    List<Purchase_OrderList_EmptyMaterialCode> fenyeRerult = new List<Purchase_OrderList_EmptyMaterialCode>();
                    if (fiveDayDeviceInfo.Count > 0)
                    {
                        msg.status = 200;
                        msg.total = fiveDayDeviceInfo.Count;
                        if (page.IsLoadAllData)
                        {//只有确定加载全部数据时才加载全部数据 [EditBy shaocx,2022-03-07]
                            msg.status = 200;
                            msg.allDate = fiveDayDeviceInfo.ToList();
                        }
                        else
                        {//不加载全部,就过滤分页信息
                            //假如每页数量 大于盘点数据
                            if (page.queryInfo.pagesize > fiveDayDeviceInfo.Count)
                            {
                                msg.date = fiveDayDeviceInfo;
                            }
                            else
                            {
                                #region 分页计算
                                int a = page.queryInfo.pagesize;
 
                                int b = page.queryInfo.pagenum;
                                int c = (int)Math.Ceiling((double)fiveDayDeviceInfo.Count / a);
                                int d = fiveDayDeviceInfo.Count % a;
                                int e = 0;
                                int f = a * (b - 1);
                                if (d != 0 && b == c)
                                {
                                    e = d + f;
 
                                }
                                else
                                {
                                    e = a + f;
                                }
 
 
 
                                for (int i = f; i < e; i++)
                                {
                                    fenyeRerult.Add(fiveDayDeviceInfo[i]);
                                }
                                msg.date = fenyeRerult;
                                #endregion
 
                            }
                        }
                    }
                    else
                    {
                        msg.status = 400;
                        msg.total = 1;
                        msg.date = null;
                    }
 
 
                    return JsonConvert.SerializeObject(msg);
                }
 
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
 
                return JsonConvert.SerializeObject(msg);
            }
 
        }
 
 
        /// <summary>2d动画获取设备位置
        /// 2d动画获取设备位置
        /// </summary>
        /// <returns></returns>
        public int[] getDevicePosition(string param)
        {
 
            try
            {
 
                //form.textBox3.Text= deviceListInfo.rgv1.position.ToString();
                //form.textBox4.Text=deviceListInfo.rgv2.position.ToString();
                //form.textBox8.Text= deviceListInfo.srm1.position.ToString();
                //form.textBox9.Text=deviceListInfo.srm2.position.ToString();
 
                // int rgv1= form.textBox3.Text==""?0:Convert.ToInt32(form.textBox3.Text)
                int[] datelist = 
                {
                  deviceListInfo.rgv1.position,
                  deviceListInfo.rgv2.position,
                  deviceListInfo.srm1.position,
                  deviceListInfo.srm2.position,
                  totalInfo.list11[0],
                  totalInfo.list11[1]
                  //form.textBox3.Text==""?0:Convert.ToInt32(form.textBox3.Text),
                  //form.textBox4.Text==""?0:Convert.ToInt32(form.textBox4.Text),
                  //form.textBox8.Text==""?0:Convert.ToInt32(form.textBox8.Text),
                  //form.textBox9.Text==""?0:Convert.ToInt32(form.textBox9.Text),
                  //form.textBox10.Text==""?0:Convert.ToInt32(form.textBox10.Text),
                  //form.textBox11.Text==""?0:Convert.ToInt32(form.textBox11.Text)
                };
 
                return datelist;
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("类名:Form1/函数名:getDevicePosition动画获取设备位置/ " + ex.Message + "出错行号" + ex.StackTrace.ToString(), 2);
                int[] datelist = { 0, 0, 0, 0, 0, 0 };
                return datelist;
            }
 
        }
        /// <summary>出库看板信息
        /// 出库看板信息
        /// </summary>
        /// <returns></returns>
        public string outStockTaskList(string takes)
        {
            outStockList outList3 = new outStockList();//3号出口
            outList3.title = "3号出口";
            outStockList outList2 = new outStockList();//2号出口
            outList2.title = "2号出口";
            outStockList outList1 = new outStockList();//1号出口
            outList1.title = "1号出口";
            DateTime nowTime = DateTime.Now;
            try
            {
                using (dbModel mod = new dbModel())
                {
                    List<Task_Queue> outStockTask = mod.Task_Queue.Where(x => x.TaskType == "4" && x.TaskStatus == "已下发").OrderBy(x => x.CreateDate).ToList();
                    var taskOrderBY = outStockTask.GroupBy(x => x.ToPositionName);
                    foreach (var item in taskOrderBY)
                    {
 
                        switch (item.ToList()[0].ToPositionName)
                        {
 
 
                            case "1008":
                                #region 3号出口
 
                                outList3.total = item.ToList().Count();
                                foreach (var itemList in item.ToList())
                                {
                                    OutDatas outInfo1 = new OutDatas();
                                    string plateCode = itemList.PlateCode;
                                    outInfo1.userTrueName = itemList.BillCode;//出库单号
                                    List<Base_ProductPosition> outQyt = mod.Base_ProductPosition.Where(x => x.PlateCode == plateCode && (x.ContainerNo != "0" || x.ContainerNo != "")).ToList();
                                    var outTime = nowTime - (DateTime)itemList.CreateDate;
                                    int outtime = outTime.Days * 24 * 60 + outTime.Hours * 60 + outTime.Minutes;
                                    outInfo1.roleName = outtime.ToString();
                                    outInfo1.deptName = outQyt.Count;//一个托盘里出库物料种类数
                                    outList3.tableData.Add(outInfo1);
                                }
                                #endregion
                                break;
                            case "1003":
                                #region 2号出口
 
                                outList2.total = item.ToList().Count();
                                foreach (var itemList in item.ToList())
                                {
                                    OutDatas outInfo1 = new OutDatas();
                                    string plateCode = itemList.PlateCode;
                                    outInfo1.userTrueName = itemList.BillCode;//出库单号
                                    List<Base_ProductPosition> outQyt = mod.Base_ProductPosition.Where(x => x.PlateCode == plateCode && (x.ContainerNo != "0" || x.ContainerNo != "")).ToList();
                                    var outTime = nowTime - (DateTime)itemList.CreateDate;
                                    int outtime = outTime.Days * 24 * 60 + outTime.Hours * 60 + outTime.Minutes;
                                    outInfo1.roleName = outtime.ToString();
                                    outInfo1.deptName = outQyt.Count;//一个托盘里出库物料种类数
                                    outList2.tableData.Add(outInfo1);
                                }
                                #endregion
 
                                break;
                            case "1001":
                                #region 1号出口
 
                                outList1.total = item.ToList().Count();
                                foreach (var itemList in item.ToList())
                                {
                                    OutDatas outInfo1 = new OutDatas();
                                    string plateCode = itemList.PlateCode;
                                    outInfo1.userTrueName = itemList.BillCode;//出库单号
                                    List<Base_ProductPosition> outQyt = mod.Base_ProductPosition.Where(x => x.PlateCode == plateCode && (x.ContainerNo != "0" || x.ContainerNo != "")).ToList();
                                    var outTime = nowTime - (DateTime)itemList.CreateDate;
                                    int outtime = outTime.Days * 24 * 60 + outTime.Hours * 60 + outTime.Minutes;
                                    outInfo1.roleName = outtime.ToString();
                                    outInfo1.deptName = outQyt.Count;//一个托盘里出库物料种类数
                                    outList1.tableData.Add(outInfo1);
                                }
                                #endregion
 
                                break;
                        }
 
                    }
                }
 
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
 
            }
            var outList = new
            {
                outList3,
                outList2,
                outList1
            };
            return JsonConvert.SerializeObject(outList);
        }
        /// <summary>入库看板信息
        /// 入库看板信息
        /// </summary>
        /// <param name="takes"></param>
        /// <returns></returns>
        public string inStockTask(string takes)
        {
            List<OutDatas> inTaskListInfo = new List<OutDatas>();
            inTaskDatas bigInStock = new inTaskDatas();
            bigInStock.title = "2号入口-大托盘";
            inTaskDatas smallInStock = new inTaskDatas();
            smallInStock.title = "1号入口-小托盘";
            DateTime nowTime = DateTime.Now;
            try
            {
                using (dbModel mod = new dbModel())
                {
                    List<Task_Queue> outStockTask = mod.Task_Queue.Where(x => x.TaskType == "1" && (x.TaskStatus == "已下发" || x.TaskStatus == "下发中")).OrderBy(x => x.CreateDate).ToList();
                    if (outStockTask.Count > 0)
                    {
                        #region 获取大托盘入库明细
 
                        Task_Queue bigTask = outStockTask.FirstOrDefault(x => x.PlateType == "2");
 
                        if (bigTask != null)
                        {
                            List<Purchase_ShelveList> inTaskListBig = mod.Purchase_ShelveList.Where(x => x.Shelve_Id == bigTask.Bill_Id).ToList();
                            if (inTaskListBig.Count > 0)
                            {
                                foreach (var item in inTaskListBig)
                                {
                                    inTaskDataList datalist = new inTaskDataList();
                                    datalist.materialCode = item.ProductCode;
                                    datalist.materialName = item.ProductName;
                                    datalist.quantity = (decimal)item.Quantity;
                                    bigInStock.dataList.Add(datalist);
 
                                }
 
                            }
 
                        }
 
                        #endregion
                        #region 获取小托盘入库明细
                        Task_Queue smallTask = outStockTask.FirstOrDefault(x => x.PlateType == "1");
 
                        if (smallTask != null)
                        {
                            List<Purchase_ShelveList> inTaskListSmall = mod.Purchase_ShelveList.Where(x => x.Shelve_Id == smallTask.Bill_Id).ToList();
                            if (inTaskListSmall.Count > 0)
                            {
                                foreach (var item in inTaskListSmall)
                                {
                                    inTaskDataList datalist = new inTaskDataList();
                                    datalist.materialCode = item.ProductCode;
                                    datalist.materialName = item.ProductName;
                                    datalist.quantity = (decimal)item.Quantity;
                                    smallInStock.dataList.Add(datalist);
 
                                }
 
                            }
 
 
                        }
                        #endregion
 
                        #region 获取入库列表
                        if (outStockTask.Count > 0)
                        {
                            foreach (var item in outStockTask)
                            {
                                List<Purchase_ShelveList> inTaskList = mod.Purchase_ShelveList.Where(x => x.Shelve_Id == item.Bill_Id).ToList();
                                if (inTaskList.Count > 0)
                                {
 
                                    var EnterTime = nowTime - (DateTime)inTaskList[0].CreateDate;
                                    int enterTime = EnterTime.Days * 24 * 60 + EnterTime.Hours * 60 + EnterTime.Minutes;
                                    OutDatas addData = new OutDatas();
                                    addData.deptName = inTaskList.Count;
                                    addData.roleName = enterTime.ToString();
                                    addData.userTrueName = item.BillCode;
                                    inTaskListInfo.Add(addData);
                                }
                            }
                        }
                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
            }
            var boardlist = new { bigInStock, smallInStock };
 
            var data = new
            {
                inTaskListInfo,
                boardlist
 
            };
            return JsonConvert.SerializeObject(data);
        }
 
        #region 创建拼盘出库任务
 
        //原先的方法
        /*
        /// <summary>创建拼盘出库任务
        /// 创建拼盘出库任务
        /// </summary>
        /// <param name="containerCode">托盘高度</param>
        public void madeDish(string containerCode, string creator)
        {
            //调试,模拟
            throw new Exception("出现异常");
 
            string[] containerNo = containerCode.Trim().Split('-');
 
            if (containerNo.Length != 4)
            {
                return;
            }
            try
            {
                var _PlateCode = "";
                //写入任务列表Task_Queue
                using (dbModel mod = new dbModel())
                {
                    //判断是否有闲时移库任务在执行 [EditBy shaocx,2022-09-22]
                    var isExistRuningTask = FreeTimeMoveLocationTaskHandler.IsExistRuningTask(mod);
                    if (isExistRuningTask)
                    {
                        return;
                    }
 
                    Base_Position Position = mod.Base_Position.FirstOrDefault(x => x.PositionName == containerCode && x.IsLocked == 0);
                    if (Position != null)
                    {
                        List<Base_ProductPosition> productPositionList = mod.Base_ProductPosition.Where(x => x.PositionName == containerCode).ToList();
                        if (productPositionList.Count < 1)
                        {
                            logtxt.txtWrite("类名:taskApi,函数名:madeDish  Base_ProductPosition组盘出库 找不到库位数据:" + containerCode, 2);
                            return;
                        }
                        _PlateCode = productPositionList.FirstOrDefault().PlateCode;
                        foreach (var itemRemove in productPositionList)
                        {
                            mod.Base_ProductPosition.Remove(itemRemove);
                            //增加出入库记录 【EditBy shaocx,2022-03-07】
                            OutInStockTaskHandler.AddOutInStockTask22(creator, mod, OutInStockTaskName.清库任务, itemRemove.ProductStorage, itemRemove, "拼盘,清空库存", "", "");
                        }
                        //Position.IsFreeze = 0;
                        Position.IsFreeze = (int)IsFreezeEnum.无货;
                        Position.IsLocked = 1;
                        Position.Remark = "拼盘-锁定库位!";
                        Position.PositionType = 0;
                        Position.PositionLength = 0;
                    }
                    else
                    {
                        logtxt.txtWrite("类名:taskApi,函数名:madeDish  组盘出库 Position找不到库位数据或者被锁定:" + containerCode, 2);
                        return;
                    }
                    string sourcePlace = containerNo[1] + "-" + containerNo[2] + "-" + containerNo[3];
                    int areaCode = Convert.ToInt32(containerNo[0].Trim());
                    string toPlace = "";
                    int PlateType = 0;
                    if (areaCode != 1 && areaCode != 2)
                    {
                        return;
                    }
                    if (areaCode == 1)
                    {
                        toPlace = "1021";
                        PlateType = 1;
                    }
                    else
                    {
 
                        if (Convert.ToInt32(containerNo[2]) > 1 && Convert.ToInt32(containerNo[2]) < 10)
                        {
                            toPlace = "1021";
                            PlateType = 1;
                        }
                        else
                        {
                            toPlace = "1026";
                            PlateType = 2;
                        }
                    }
                    Task_Queue CallContainerTaks = new Task_Queue();
                    CallContainerTaks.TaskType = ((int)TaskTypeEnum.组盘出库).ToString();//任务类型
                    CallContainerTaks.OrderNumber = 0;//任务权重
                    CallContainerTaks.PlateCode = _PlateCode;//托盘号
                    CallContainerTaks.TaskStatus = "未下发";//任务状态
                    CallContainerTaks.PlateType = PlateType.ToString();//托盘类型
                    CallContainerTaks.CreateDate = DateTime.Now;
                    CallContainerTaks.Creator = creator;
                    CallContainerTaks.UserProduct_Id = 1007;//账套id 老谢bug  
                    //垃圾值都赋值0 转到autoTask()里有说明
                    CallContainerTaks.FromPositionName = sourcePlace;
                    CallContainerTaks.ToPositionName = toPlace;
                    CallContainerTaks.DoCount = areaCode;//库区
                    CallContainerTaks.Direction = "0";//托盘高度
                    mod.Task_Queue.Add(CallContainerTaks);
                    mod.SaveChanges();
                    logtxt.txtWrite("类名:taskApi,函数名:madeDish  组盘出库 库位:" + containerCode, 0);
                }
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("类名:taskApi/函数名:madeDish组盘出库/ 库位:" + containerCode + logtxt.oneRow(ex.ToString()), 2);
            }
        }
 
        //*/
 
        /// <summary>
        /// 创建拼盘出库任务
        /// </summary>
        /// <param name="containerCode">库位号</param>
        /// <param name="creator">创建人</param>
        public string madeDish(string containerCode, string creator)
        {
            resultMsg msgs = new resultMsg();
            msgs.result = false;
            msgs.status = 400;
            //////调试,模拟
            //msgs.msg = "我错了咋地!" + containerCode;
            //return JsonConvert.SerializeObject(msgs);
 
            var msg = "";
            var isRight = ExtendHelper.ValidateIsRightForPositionName(containerCode, ref msg);
            if (!isRight)
            {
                msgs.msg = msg;
                return JsonConvert.SerializeObject(msgs);
            }
            string[] containerNo = containerCode.Trim().Split('-');
 
            try
            {
                var _PlateCode = "";
                //写入任务列表Task_Queue
                using (dbModel mod = new dbModel())
                {
                    //判断是否有闲时移库任务在执行 [EditBy shaocx,2022-09-22]
                    var isExistRuningTask = FreeTimeMoveLocationTaskHandler.IsExistRuningTask(mod);
                    if (isExistRuningTask)
                    {
                        msgs.msg = "存在闲时移库任务在执行!";
                        return JsonConvert.SerializeObject(msgs);
                    }
 
 
                    Base_Position position = mod.Base_Position.FirstOrDefault(x => x.PositionName == containerCode && x.IsLocked == 0);
                    if (position != null)
                    {
                        List<Base_ProductPosition> productPositionList = mod.Base_ProductPosition.Where(x => x.PositionName == containerCode).ToList();
                        if (productPositionList.Count < 1)
                        {
                            logtxt.txtWrite("类名:taskApi,函数名:madeDish  Base_ProductPosition组盘出库 找不到库位数据:" + containerCode, 2);
                            msgs.msg = "根据库位" + containerCode + ",没找到库存";
                            return JsonConvert.SerializeObject(msgs);
                        }
                        if (position.IsLocked == 1)
                        {
                            logtxt.txtWrite("类名:taskApi,函数名:madeDish  Base_ProductPosition组盘出库 库位数据:" + containerCode
                                + ",已经被锁定了,不允许创建拼盘任务", 2);
                            msgs.msg = "根据库位" + containerCode + ",库位已经被锁定";
                            return JsonConvert.SerializeObject(msgs);
                        }
                        _PlateCode = productPositionList.FirstOrDefault().PlateCode;
 
                        var doingTaskList = BussinessExtension.BussinessExtension.GetDoingTaskListForPlateCode(mod, _PlateCode);
                        if (doingTaskList != null && doingTaskList.Count > 0)
                        {
                            logtxt.txtWrite("有未结束的任务占用托盘'" + _PlateCode + "',任务ID为:" + doingTaskList[0].Task_Id);
                            msgs.msg = "根据库位" + containerCode + ",有未结束的任务占用托盘'" + _PlateCode + "',任务ID为:" + doingTaskList[0].Task_Id;
                            return JsonConvert.SerializeObject(msgs);
                        }
                        var doingTaskList2 = BussinessExtension.BussinessExtension.GetDoingShelveTaskListForPlateCode(mod, _PlateCode);
                        if (doingTaskList2 != null && doingTaskList2.Count > 0)
                        {
                            logtxt.txtWrite("根据托盘号" + _PlateCode + ",有未结束的上架单据占用托盘'" + _PlateCode + "',上架单据为:" + doingTaskList2[0].ShelveCode);
                            msgs.msg = "根据托盘号" + _PlateCode + ",有未结束的上架单据占用托盘'" + _PlateCode + "',上架单据为:" + doingTaskList2[0].ShelveCode;
                            return JsonConvert.SerializeObject(msgs);
                        }
                        //创建拼盘出库任务,不再删除库存了。
                        foreach (var itemRemove in productPositionList)
                        {
                            itemRemove.Remark = "拼盘出库,库位" + itemRemove.PositionName + "和托盘进行解绑";
                            itemRemove.PositionName = "";//库位和托盘进行解绑 【Editby shaocx,2024-03-23】
                        }
                        //*/
                        position.IsFreeze = (int)IsFreezeEnum.无货;
                        position.IsLocked = 1;
                        position.Remark = "拼盘-锁定库位!";
                        position.PositionType = 0;
                        position.PositionLength = 0;
                    }
                    else
                    {
                        logtxt.txtWrite("类名:taskApi,函数名:madeDish  组盘出库 Position找不到库位数据或者被锁定:" + containerCode, 2);
                        msgs.msg = "根据库位" + containerCode + ",库位已经被锁定";
                        return JsonConvert.SerializeObject(msgs);
                    }
                    string sourcePlace = containerNo[1] + "-" + containerNo[2] + "-" + containerNo[3];
                    int areaCode = Convert.ToInt32(containerNo[0].Trim());
                    string toPlace = "";
                    int PlateType = 0;
                    if (areaCode != 1 && areaCode != 2)
                    {
                        msgs.msg = "根据库位" + containerCode + ",库区不是1或2";
                        return JsonConvert.SerializeObject(msgs);
                    }
                    if (areaCode == 1)
                    {
                        toPlace = "1021";
                        PlateType = 1;
                    }
                    else
                    {
 
                        if (Convert.ToInt32(containerNo[2]) > 1 && Convert.ToInt32(containerNo[2]) < 10)
                        {
                            toPlace = "1021";
                            PlateType = 1;
                        }
                        else
                        {
                            toPlace = "1026";
                            PlateType = 2;
                        }
                    }
                    Task_Queue CallContainerTaks = new Task_Queue();
                    CallContainerTaks.TaskType = ((int)TaskTypeEnum.组盘出库).ToString();//任务类型
                    CallContainerTaks.OrderNumber = 0;//任务权重
                    CallContainerTaks.PlateCode = _PlateCode;//托盘号
                    CallContainerTaks.TaskStatus = "未下发";//任务状态
                    CallContainerTaks.PlateType = PlateType.ToString();//托盘类型
                    CallContainerTaks.CreateDate = DateTime.Now;
                    CallContainerTaks.Creator = creator;
                    CallContainerTaks.UserProduct_Id = 1007;//账套id 老谢bug  
                    //垃圾值都赋值0 转到autoTask()里有说明
                    CallContainerTaks.FromPositionName = sourcePlace;
                    CallContainerTaks.ToPositionName = toPlace;
                    CallContainerTaks.DoCount = areaCode;//库区
                    CallContainerTaks.Direction = "0";//托盘高度
                    mod.Task_Queue.Add(CallContainerTaks);
                    mod.SaveChanges();
                    logtxt.txtWrite("类名:taskApi,函数名:madeDish  组盘出库 库位:" + containerCode, 0);
 
                    msgs.msg = "成功";
                    msgs.result = true;
                    msgs.status = 200;
                }
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("类名:taskApi/函数名:madeDish组盘出库/ 库位:" + containerCode + logtxt.oneRow(ex.ToString()), 2);
                msgs.msg = "根据库位" + containerCode + ",出现异常:" + ex.Message;
            }
 
            return JsonConvert.SerializeObject(msgs);
        }
 
        #endregion
 
 
 
        /// <summary> 按凭证退货
        /// 按凭证退货
        /// </summary>
        /// <param name="deviceCode">拆叠盘设备号</param>
        /// <returns></returns>
        public string resetChaiDieDevice(string deviceCode)
        {
            string msg = "";
            if (deviceCode.Trim() == "")
            {
                return "参数为空";
            }
            msg = "复位失败";
            try
            {
                using (dbModel mod = new dbModel())
                {
                    ContainerIsFullOrEmpty resetDevice = mod.ContainerIsFullOrEmpty.FirstOrDefault();
                    if (resetDevice != null)
                    {
                        switch (deviceCode)
                        {
                            case "1": resetDevice.ChaiBig++;
                                break;
                            case "2": resetDevice.ChaiSmall++;
                                break;
                            case "3": resetDevice.DieBig++;
                                break;
                            case "4": resetDevice.DieSmall++;
                                break;
                        }
                        int res = mod.SaveChanges();
                        if (res == 1)
                        {
                            msg = "复位成功";
                        }
 
                    }
                }
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "解锁库位失败  出错行号" + (string)ex.StackTrace, 2);
            }
            return msg;
 
        }
 
        /// <summary>删除wcs任务
        /// 
        /// </summary>
        /// <returns></returns>
        public string deleteTask(string containerCode = "")
        {
            string msg = "";
            Task_Queue taskDelete;
            try
            {
                string plateCode = containerCode.Trim();
                using (dbModel mod = new dbModel())
                {
                    taskDelete = mod.Task_Queue.FirstOrDefault(x => x.TaskStatus == "已下发" && x.PlateCode == plateCode);
                    if (taskDelete == null)
                    {
                        return msg = "此托盘号任务已完成";
                    }
                    if (plateCode == "")
                    {
                        return msg = "参数为空";
                    }
                    bool res = wcsApi.DealAllTask(containerCode.Trim());
                    if (res)
                    {
                        taskDelete.TaskStatus = "手工处理异常";
                        if (taskDelete.TaskType == "1")
                        {
                            Purchase_Shelve deleteInTaskCode = mod.Purchase_Shelve.FirstOrDefault(x => x.ShelveCode == taskDelete.BillCode);
                            if (deleteInTaskCode == null)
                            {
                                logtxt.txtWrite("删除wcs任务产生异常,托盘号:" + containerCode + "  单据编号:" + taskDelete.BillCode, 2);
                            }
                            else
                            {
                                deleteInTaskCode.OnShelveStatus = "手工处理异常";
                            }
                        }
                    }
                    int result = mod.SaveChanges();
                    logtxt.txtWrite("删除wcs任务产生异常,保存结果" + result, 1);
                    msg = res == true ? "删除成功" : "删除失败";
                }
 
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("删除wcs产生异常,托盘号:" + containerCode + "    " + ex.ToString(), 2);
                msg = "参数异常";
            }
            return msg;
 
        }
 
        /// <summary> 缺料单下载
        /// 缺料单下载
        /// </summary>
        /// <param name="orderCode">出库单号</param>
        /// <returns></returns>
        public string lackData(string orderCode)
        {
            string msg = "false";
            orderCode = orderCode.Trim();
            if (string.IsNullOrEmpty(orderCode))
            {
                return "false";
            }
            try
            {
                using (dbModel mod = new dbModel())
                {
                    lackOrder lastOrder = mod.lackOrder.Where(x => x.workCode == orderCode).OrderByDescending(x => x.lackId).FirstOrDefault();
                    if (lastOrder != null)
                    {
                        List<lackOrderList> lackList = mod.lackOrderList.Where(x => x.lackId == lastOrder.lackId).ToList();
                        if (lackList.Count > 0)
                        {
 
                            string[] lackOrderName ={ "跟踪号: ", 
                                                        lastOrder.trackCode.ToString() ,
                                                        " 出库单号:",
                                                         lastOrder.workCode.ToString(),
                                                          " 已完成总套数:",
                                                          lastOrder.finishCount.ToString(),
                                                           " 本次套数:",
                                                            (lastOrder.finishCount + lastOrder.counting).ToString()};
                            var data = new
                            {
                                lackname = lackOrderName,
                                dataList = lackList
 
                            };
                            msg = JsonConvert.SerializeObject(data);
                            //导出出库单后 改表的状态
                            Sale_Order saleorderStatus = mod.Sale_Order.FirstOrDefault(x => x.OrderCode == orderCode);
                            if (saleorderStatus != null)
                            {
                                //saleorderStatus.StatusText = "部分分配";
                                saleorderStatus.StatusText = Sale_Order_StatusEnum.部分分配.ToString();
                                saleorderStatus.StatusID = Convert.ToByte(Sale_Order_StatusEnum.部分分配);
                                List<Sale_OrderList> saleList = mod.Sale_OrderList.Where(x => x.Order_Id == saleorderStatus.Order_Id).ToList();
                                if (saleList.Count > 0)
                                {
                                    foreach (var item in saleList)
                                    {
                                        item.ExtendField03 = "部分分配";//明细分拣状态
                                        item.ValidQuantity = item.ValidQuantity - item.QuantityOrder;//未出库数量
                                        item.QuantityOrder = 0;//本次出库数量
 
                                    }
                                }
                                int resultSave = mod.SaveChanges();
                                if (resultSave < 1)//保存失败再保存一次
                                {
                                    mod.SaveChanges();
                                }
 
                            }
 
                        }
                    }
                    else
                    {//无缺料信息
                        var data = new
                        {
                            lackname = "无缺料",
                            dataList = new List<lackOrderList>()
 
                        };
                        msg = JsonConvert.SerializeObject(data);
                    }
                }
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "解锁库位失败  出错行号" + ex.StackTrace.ToString(), 2);
            }
 
 
            return msg;
 
        }
        ///解锁库位
        /// </summary>
        /// <param name="positionName">库位名称</param>
        /// <returns></returns>
        public string unlock(int isremove, string positionName, string username)
        {
            string msg = "";
 
 
            try
            {
                string PositionName = positionName.Trim();
                string[] containerNo = PositionName.Split('-');
                username = username == null ? "空" : username.Trim();
                if (containerNo.Length != 4)
                {
                    return "库位格式错误";
 
                }
                //写入任务列表Task_Queue
                using (dbModel mod = new dbModel())
                {
 
                    List<Base_ProductPosition> ProductPosition = mod.Base_ProductPosition.Where(x => x.PositionName == PositionName).ToList();
                    if (ProductPosition.Count > 0)
                    {
 
                        foreach (var itemRemovePosition in ProductPosition)
                        {
                            if (isremove == 1)
                            {
 
                                //清除库存
                                mod.Base_ProductPosition.Remove(itemRemovePosition);
                                //增加出入库记录 【EditBy shaocx,2022-03-07】
                                OutInStockTaskHandler.AddOutInStockTask22(username, mod, OutInStockTaskName.清库任务, itemRemovePosition.ProductStorage, itemRemovePosition, "解锁库位,清空库存", "");
                                OperationLogHelper.SaveOperationLog(username, "清空库存:库位:" + itemRemovePosition.PositionName + "物料名称:" + itemRemovePosition.ProductCode, OperateTypeEnum.清除库存);
                                logtxt.txtWrite("apitest-" + "unlock-解锁/删除库存" + itemRemovePosition.PositionName + "物料名称:" + itemRemovePosition.ProductCode, 2);
 
                            }
                            else
                            {
                                //复位库位
                                //ExtendField02 出库数量  ContainerNo=1 锁定(正在出库)  ExtendField03=1允许分拣 Remark 移动类型
                                itemRemovePosition.ExtendField02 = "0";
                                itemRemovePosition.ContainerNo = "0";
                                //增加物料锁定和解锁的时间和备注记录  [EditBy shaocx,2023-07-26]
                                itemRemovePosition.DoContainerNoTime = DateTime.Now;
                                itemRemovePosition.OpRemark = "界面解锁库位操作,解绑物料锁定";
 
                                itemRemovePosition.ExtendField03 = "0";
                                // baseData.addOperation(username, "复位库位:" + itemRemovePosition.PositionName, "复位库位");
                                logtxt.txtWrite("apitest-" + "unlock-解锁/删除库存" + itemRemovePosition.PositionName + "物料名称:" + itemRemovePosition.ProductCode, 2);
                            }
                        }
                    }
 
                    //复位库位状态
                    Base_Position Position = mod.Base_Position.FirstOrDefault(x => x.PositionName == PositionName);
 
                    if (Position != null)
                    {
                        //判断是否有任务占用
                        string[] positions = Position.PositionName.Split('-');
                        var position = positions[1] + "-" + positions[2] + "-" + positions[3];//格式: 01-03-01
                        var doingTaskList = BussinessExtension.BussinessExtension.GetDoingTaskList(mod, Convert.ToInt32(positions[0]), position);
                        if (doingTaskList != null && doingTaskList.Count > 0)
                        {
                            msg = "有未结束的任务占用库位'" + Position.PositionName + "',任务ID为:" + doingTaskList[0].Task_Id;
                            return msg;
                        }
 
                        if (isremove == 1)
                        {//移除库存
                            //Position.IsFreeze = 0;
                            Position.IsFreeze = (int)IsFreezeEnum.无货;
                            Position.IsLocked = 0;
                            Position.Remark = "人工[" + username + "]解锁库位操作-移除库存!";
                            Position.PositionLength = 0;
                        }
                        else
                        {
                            //Position.IsFreeze = 1;
                            //Position.IsFreeze = (int)IsFreezeEnum.有货;//库位解锁就一定有货吗,扯犊子 【EditBy shaocx,2022-09-22】
                            Position.IsLocked = 0;
                            Position.Remark = "人工[" + username + "]解锁库位操作!";
                        }
 
                    }
                    int result = mod.SaveChanges();
                    if (result > 0)
                    {
                        if (isremove == 1)
                        {
                            SystemHelper.addOperation(username, "清除库存: " + positionName, "清除库存");
                        }
                        else
                        {
                            SystemHelper.addOperation(username, "解锁库位: " + positionName, "解锁库位");
                        }
                        msg = "操作成功";
                    }
                }
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "解锁库位失败  出错行号" + ex.StackTrace.ToString(), 2);
                msg = ex.Message;
            }
 
            return msg;
 
        }
 
        /// <summary>查找物料信息
        /// 查找物料信息
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string findMaterial(string param)
        {
            msgss<VmaterialInfo> msg = new msgss<VmaterialInfo>();
            try
            {
                searchEntity page = JsonConvert.DeserializeObject<searchEntity>(param);
 
                string StockWhere = "";
                //根据日期筛选
                if (page.searchParam != null && page.searchParam != "")
                {
                    StockWhere = StockWhere + " and (ProductCode like '%" + page.searchParam.Trim() + "%' or ProductName like '%" + page.searchParam.Trim() + "%')";
 
                }
                if (page.check == true)
                {
                    StockWhere = StockWhere + " and Brand_Id>0 ";
                }
                using (dbModel mod = new dbModel())
                {
                    //获取盘点数据
                    string sql = "select * from [dbo].[" + "VmaterialInfo" + "] where Product_Id >0 " + StockWhere + " order by Product_Id desc ";//isFreeze    是否有货   先拿这个字段用 
 
                    List<VmaterialInfo> takeStock = mod.Database.SqlQuery<VmaterialInfo>(sql).ToList();
                    List<VmaterialInfo> fenyeRerult = new List<VmaterialInfo>();
                    if (takeStock.Count > 0)
                    {
                        msg.status = 200;
                        msg.total = takeStock.Count;
                        if (page.IsLoadAllData)
                        {//只有确定加载全部数据时才加载全部数据 [EditBy shaocx,2022-03-07]
                            //msg.allDate = takeStock.Take(20000).ToList();
                            msg.status = 200;
                            msg.allDate = takeStock.ToList();
                        }
                        else
                        {//不加载全部,就过滤分页信息
                            //假如每页数量 大于盘点数据
                            if (page.queryInfo.pagesize > takeStock.Count)
                            {
                                msg.date = takeStock;
                            }
                            else
                            {
                                #region 分页计算
                                int a = page.queryInfo.pagesize;
 
                                int b = page.queryInfo.pagenum;
                                int c = (int)Math.Ceiling((double)takeStock.Count / a);
                                int d = takeStock.Count % a;
                                int e = 0;
                                int f = a * (b - 1);
                                if (d != 0 && b == c)
                                {
                                    e = d + f;
 
                                }
                                else
                                {
                                    e = a + f;
                                }
 
 
 
                                for (int i = f; i < e; i++)
                                {
                                    fenyeRerult.Add(takeStock[i]);
                                }
                                msg.date = fenyeRerult;
                                #endregion
 
                            }
                        }
                    }
                    else
                    {
                        msg.status = 400;
                        msg.total = 1;
                        msg.date = null;
                    }
 
                    return JsonConvert.SerializeObject(msg);
                }
 
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
                return JsonConvert.SerializeObject(msg);
            }
        }
        /// <summary>物料增删改
        /// 物料增删改查
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string MaterialOperation(string param)
        {
 
 
            resultMsg msgs = new resultMsg();
            try
            {
                materialResult acceptParam = JsonConvert.DeserializeObject<materialResult>(param);
                #region 参数验证
                if (acceptParam == null)
                {
                    msgs.status = 400;
                    msgs.result = false;
                    msgs.msg = "参数为空";
                    return JsonConvert.SerializeObject(msgs);
                }
                if (acceptParam.OperationValue != 1 && acceptParam.OperationValue != 2 && acceptParam.OperationValue != 3)
                {
                    msgs.status = 400;
                    msgs.result = false;
                    msgs.msg = "参数为空";
                    return JsonConvert.SerializeObject(msgs);
                }
                #endregion
                using (dbModel mod = new dbModel())
                {
                    switch (acceptParam.OperationValue)
                    {
                        case 1://新建物料 Base_ProductInfo
                            #region 新建物料
                            Base_ProductInfo addmaterial = new Base_ProductInfo();
                            addmaterial.BigUnit = acceptParam.taskForm.BigUnit;
                            addmaterial.Brand_Id = acceptParam.taskForm.Brand_Id == null ? 0 : acceptParam.taskForm.Brand_Id;
                            addmaterial.CreateDate = DateTime.Now;
                            addmaterial.Creator = acceptParam.taskForm.Creator;
                            addmaterial.ModifyDate = DateTime.Now;
                            addmaterial.ProductCode = acceptParam.taskForm.ProductCode;
                            addmaterial.ProductName = acceptParam.taskForm.ProductName;
                            addmaterial.SmallUnit = acceptParam.taskForm.SmallUnit;
                            addmaterial.ProductModel = acceptParam.taskForm.ProductCode;
                            //非空值
                            addmaterial.UnitConvert = 1M;//大小单位转换
                            addmaterial.Provider_Id = 926;
                            addmaterial.ProviderCode = "PV201940371";
                            addmaterial.Consignor_Id = 30;
                            addmaterial.ConsignorCode = "GX30";
                            addmaterial.ConsignorName = "广州西门子";
                            addmaterial.UserProduct_Id = 1007;
                            addmaterial.UserProductCode = "100000001";
                            mod.Base_ProductInfo.Add(addmaterial);
                            int saveResult = mod.SaveChanges();
                            if (saveResult < 1)
                            {
                                saveResult = mod.SaveChanges();
                            }
                            if (saveResult < 1)
                            {
                                msgs.status = 400;
                                msgs.result = false;
                                msgs.msg = "新建物料失败";
                            }
                            else
                            {
                                msgs.status = 200;
                                msgs.result = true;
                                msgs.msg = "新建成功";
                            }
                            break;
                            #endregion
 
                        case 2://修改物料
                            Base_ProductInfo modify = mod.Base_ProductInfo.Find(acceptParam.taskForm.Product_Id);
                            if (modify != null)
                            {
                                modify.BigUnit = acceptParam.taskForm.BigUnit;
                                modify.Brand_Id = acceptParam.taskForm.Brand_Id == null ? 0 : acceptParam.taskForm.Brand_Id;
                                modify.Creator = acceptParam.taskForm.Creator;
                                modify.ModifyDate = DateTime.Now;
                                modify.ProductCode = acceptParam.taskForm.ProductCode;
                                modify.ProductName = acceptParam.taskForm.ProductName;
                                modify.SmallUnit = acceptParam.taskForm.SmallUnit;
                                modify.ProductModel = acceptParam.taskForm.ProductCode;
                                int updateResult = mod.SaveChanges();
                                if (updateResult < 1)
                                {
                                    updateResult = mod.SaveChanges();
                                }
                                if (updateResult < 1)
                                {
                                    msgs.status = 400;
                                    msgs.result = false;
                                    msgs.msg = "修改物料失败";
                                }
                                else
                                {
                                    msgs.status = 200;
                                    msgs.result = true;
                                    msgs.msg = "修改成功";
                                }
                            }
                            else
                            {
                                msgs.status = 400;
                                msgs.result = false;
                                msgs.msg = "修改物料失败--找不到这个物料";
                            }
 
                            break;
                        case 3://删除物料
                            #region 删除物料
                            Base_ProductInfo deleteMaterial = mod.Base_ProductInfo.Find(acceptParam.taskForm.Product_Id);
                            if (deleteMaterial != null)
                            {
                                mod.Base_ProductInfo.Remove(deleteMaterial);
                                int deleteResult = mod.SaveChanges();
                                if (deleteResult < 1)
                                {
                                    deleteResult = mod.SaveChanges();
                                }
                                if (deleteResult < 1)
                                {
                                    msgs.status = 400;
                                    msgs.result = false;
                                    msgs.msg = "删除物料失败";
                                }
                                else
                                {
                                    msgs.status = 200;
                                    msgs.result = true;
                                    msgs.msg = "删除成功";
                                }
                            }
                            else
                            {
                                msgs.status = 200;
                                msgs.result = true;
                                msgs.msg = "删除物料失败,找不到这个物料";
                            }
                            break;
                            #endregion
 
                        default:
                            break;
                    }
                }
 
 
 
            }
            catch (Exception ex)
            {
                msgs.status = 400;
                msgs.result = false;
                msgs.msg = "参数异常";
 
                logtxt.txtWrite("类名: " + "apitest" + "方法名:" + "MaterialOperation 物料增删改产生异常参数:" + param + " 信息:" + logtxt.oneRow(ex.ToString()), 2);
 
            }
 
            return JsonConvert.SerializeObject(msgs);
        }
        /// <summary>获取设备报警记录
        /// 获取设备报警记录
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string deviceAlarm(string param)
        {
            msgss<deviceAlarmMsg> msg = new msgss<deviceAlarmMsg>();
            try
            {
                productStockEntity page = JsonConvert.DeserializeObject<productStockEntity>(param);
 
                string StockWhere = "";
                //根据下拉框筛选
                if (page.positionTypeValue < 5)
                {
                    StockWhere = "and type = " + page.positionTypeValue;
                }
                //根据日期筛选
                if (page.datatime != null)
                {
                    if (page.datatime.Length == 2)
                    {
                        StockWhere = StockWhere + "and createtime > '" + page.datatime[0].ToString() + "' and  createtime < '" + page.datatime[1].ToString() + "'";
                    }
                }
                using (deviceOrm mod = new deviceOrm())
                {
                    //设备报警信息
                    string sql = "select * from [dbo].[" + "DevAlert" + "] where id >0 " + StockWhere + " and isfinished=1 order by id desc ";
 
                    List<DevAlert> takeStock = mod.Database.SqlQuery<DevAlert>(sql).ToList();
 
                    List<deviceAlarmMsg> devicefenyeRerults = new List<deviceAlarmMsg>();
                    List<DevAlert> fenyeRerult = new List<DevAlert>();
                    if (takeStock.Count > 0)
                    {
                        msg.status = 200;
                        if (page.IsLoadAllData)
                        {//只有确定加载全部数据时才加载全部数据 [EditBy shaocx,2022-03-07]
                            foreach (var item in takeStock)
                            {
                                deviceAlarmMsg deviceAlarm = new deviceAlarmMsg();
                                string[] name = form.alarmName(item.type, Convert.ToInt32(item.alertcode), Convert.ToInt32(item.eqname));
                                deviceAlarm.deviceName = name[0];
                                deviceAlarm.alarmInfo = name[1];
                                deviceAlarm.creatTime = (DateTime)item.createtime;
                                TimeSpan continuetime = (DateTime)item.finishtime - (DateTime)item.createtime;
                                deviceAlarm.continueTime = continuetime.Hours + "小时" + continuetime.Minutes + "分钟" + continuetime.Seconds + "秒";
                                devicefenyeRerults.Add(deviceAlarm);
                            }
                            msg.allDate = devicefenyeRerults;
                        }
                        else
                        {//不加载全部,就过滤分页信息
                            msg.total = takeStock.Count;
                            //假如每页数量 大于总数量
                            if (page.queryInfo.pagesize > takeStock.Count)
                            {
                                fenyeRerult = takeStock;
                            }
                            else
                            {
                                #region 分页计算
                                int a = page.queryInfo.pagesize;
 
                                int b = page.queryInfo.pagenum;
                                int c = (int)Math.Ceiling((double)takeStock.Count / a);
                                int d = takeStock.Count % a;
                                int e = 0;
                                int f = a * (b - 1);
                                if (d != 0 && b == c)
                                {
                                    e = d + f;
 
                                }
                                else
                                {
                                    e = a + f;
                                }
 
                                for (int i = f; i < e; i++)
                                {
                                    fenyeRerult.Add(takeStock[i]);
                                }
                                #endregion
                            }
                            foreach (var item in fenyeRerult)
                            {
                                deviceAlarmMsg deviceAlarm = new deviceAlarmMsg();
                                string[] name = form.alarmName(item.type, Convert.ToInt32(item.alertcode), Convert.ToInt32(item.eqname));
                                deviceAlarm.deviceName = name[0];
                                deviceAlarm.alarmInfo = name[1];
                                deviceAlarm.creatTime = (DateTime)item.createtime;
                                TimeSpan continuetime = (DateTime)item.finishtime - (DateTime)item.createtime;
                                deviceAlarm.continueTime = continuetime.Hours + "小时" + continuetime.Minutes + "分钟" + continuetime.Seconds + "秒";
                                devicefenyeRerults.Add(deviceAlarm);
                            }
                            msg.date = devicefenyeRerults;
                        }
                    }
                    else
                    {
                        msg.status = 400;
                        msg.total = 1;
                        msg.date = null;
                    }
 
                }
            }
            catch (Exception ex)
            {
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
                logtxt.txtWrite("类名: " + "apitest" + "方法名:" + "deviceAlarm" + "获取报警信息异常" + ex.ToString() + "--" + logtxt.oneRow(ex.ToString()), 2);
            }
            return JsonConvert.SerializeObject(msg);
        }
        /// <summary>获取设备报警记录统计
        /// 
        /// </summary>
        /// <param name="param">此参数不用</param>
        /// <returns></returns>
        public string deviceAlarms(string param)
        {
            msgss<DeviceAlarms> msg = new msgss<DeviceAlarms>();
            msg.status = 400;
            try
            {
                List<DeviceAlarms> deviceTotal = new List<DeviceAlarms>();
                DeviceAlarms srm1 = new DeviceAlarms();
                DeviceAlarms srm2 = new DeviceAlarms();
                DeviceAlarms rgv1 = new DeviceAlarms();
                DeviceAlarms rgv2 = new DeviceAlarms();
                string month = param == "" ? DateTime.Now.Month.ToString() : DateTime.Parse(param).Month.ToString();
                DateTime fristMonth = DateTime.Parse(DateTime.Now.ToString("yyyy-" + month + "-01"));
                DateTime lastMonth = DateTime.Parse(DateTime.Parse(DateTime.Now.ToString("yyyy-" + month + "-01")).AddMonths(1).AddMinutes(-1).ToString());
 
                using (deviceOrm mod = new deviceOrm())
                {
                    List<DevAlert> srm1Info = mod.DevAlert.Where(x => x.createtime > fristMonth && x.createtime < lastMonth && x.name == "Srm1").ToList();
                    #region 堆垛机1
                    var srm1Type = srm1Info.GroupBy(x => x.alertname).OrderByDescending(x => x.Count()).ToList();
 
                    TimeSpan srm1Span = new TimeSpan();
                    if (srm1Info.Count > 0)
                    {
                        foreach (var srm1item in srm1Info)
                        {
                            srm1Span = srm1Span + (TimeSpan)(srm1item.finishtime - srm1item.createtime);
                        }
                    }
                    srm1.AlarmTime = srm1Span.TotalHours.ToString("0.00");
 
                    srm1.DeviceName = "一号堆垛机";
                    srm1.AlarmNum = srm1Info.Count.ToString();
                    if (srm1Type.Count > 0)
                    {
                        srm1.AlarmName1 = srm1Type[0].Key;
                        if (srm1Type.Count > 1)
                        {
                            srm1.AlarmName2 = srm1Type[1].Key;
                            if (srm1Type.Count > 2)
                            {
                                srm1.AlarmName3 = srm1Type[2].Key;
                            }
                        }
 
                    }
                    #endregion
 
                    List<DevAlert> srm2Info = mod.DevAlert.Where(x => x.createtime > fristMonth && x.createtime < lastMonth && x.name == "Srm2").ToList();
                    #region 堆垛机2
                    var srm2Type = srm2Info.GroupBy(x => x.alertname).OrderByDescending(x => x.Count()).ToList();
 
                    TimeSpan srm2Span = new TimeSpan();
                    if (srm2Info.Count > 0)
                    {
                        foreach (var srm2item in srm2Info)
                        {
                            srm2Span = srm2Span + (TimeSpan)(srm2item.finishtime - srm2item.createtime);
                        }
                    }
                    srm2.AlarmTime = srm2Span.TotalHours.ToString("0.00");
 
                    srm2.DeviceName = "二号堆垛机";
                    srm2.AlarmNum = srm2Info.Count.ToString();
                    if (srm2Type.Count > 0)
                    {
                        srm2.AlarmName1 = srm2Type[0].Key;
                        if (srm2Type.Count > 1)
                        {
                            srm2.AlarmName2 = srm2Type[1].Key;
                            if (srm2Type.Count > 2)
                            {
                                srm2.AlarmName3 = srm2Type[2].Key;
                            }
                        }
 
                    }
                    #endregion
                    List<DevAlert> rgv1Info = mod.DevAlert.Where(x => x.createtime > fristMonth && x.createtime < lastMonth && x.name == "Rgv1").ToList();
                    #region 堆垛机1
                    var rgv1Type = rgv1Info.GroupBy(x => x.alertname).OrderByDescending(x => x.Count()).ToList();
 
                    TimeSpan rgv1Span = new TimeSpan();
                    if (rgv1Info.Count > 0)
                    {
                        foreach (var agv1item in rgv1Info)
                        {
                            rgv1Span = rgv1Span + (TimeSpan)(agv1item.finishtime - agv1item.createtime);
                        }
                    }
                    rgv1.AlarmTime = rgv1Span.TotalHours.ToString("0.00");
                    rgv1.DeviceName = "一号RGV";
                    rgv1.AlarmNum = rgv1Info.Count.ToString();
                    if (rgv1Type.Count > 0)
                    {
                        rgv1.AlarmName1 = rgv1Type[0].Key;
                        if (rgv1Type.Count > 1)
                        {
                            rgv1.AlarmName2 = rgv1Type[1].Key;
                            if (rgv1Type.Count > 2)
                            {
                                rgv1.AlarmName3 = rgv1Type[2].Key;
                            }
                        }
 
                    }
                    #endregion
                    List<DevAlert> rgv2Info = mod.DevAlert.Where(x => x.createtime > fristMonth && x.createtime < lastMonth && x.name == "Rgv2").ToList();
                    #region 二号RGV
                    var rgv2Type = rgv2Info.GroupBy(x => x.alertname).OrderByDescending(x => x.Count()).ToList();
 
                    TimeSpan rgv2Span = new TimeSpan();
                    if (rgv2Info.Count > 0)
                    {
                        foreach (var rgv2item in rgv2Info)
                        {
                            rgv2Span = rgv2Span + (TimeSpan)(rgv2item.finishtime - rgv2item.createtime);
                        }
                    }
                    rgv2.AlarmTime = rgv2Span.TotalHours.ToString("0.00");
                    rgv2.DeviceName = "二号RGV";
                    rgv2.AlarmNum = rgv2Info.Count.ToString();
                    if (rgv2Type.Count > 0)
                    {
                        rgv2.AlarmName1 = rgv2Type[0].Key;
                        if (rgv2Type.Count > 1)
                        {
                            rgv2.AlarmName2 = rgv2Type[1].Key;
                            if (rgv2Type.Count > 2)
                            {
                                rgv2.AlarmName3 = rgv2Type[2].Key;
                            }
                        }
 
                    }
                    #endregion
                }
                deviceTotal.Add(srm1);
                deviceTotal.Add(srm2);
                deviceTotal.Add(rgv1);
                deviceTotal.Add(rgv2);
                msg.status = 200;
                msg.date = deviceTotal;
 
            }
            catch (Exception)
            {
 
                throw;
            }
 
            return JsonConvert.SerializeObject(msg);
        }
        /// <summary>空托盘出入库
        /// 
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string emtypContainerOUtandIN(string param)
        {
            /*
            //我认为这个方法不用了 【EditBy shaocx,2022-09-22】
            resultMsg msgs = new resultMsg();
            msgs.status = 400;
            msgs.msg = "方法无效";
            return JsonConvert.SerializeObject(msgs);
            //*/
 
 
            resultMsg msgs = new resultMsg();
            msgs.status = 400;
            try
            {
                emtypContainerOUtandINclass emtypContainer = JsonConvert.DeserializeObject<emtypContainerOUtandINclass>(param);
                if (string.IsNullOrEmpty(emtypContainer.creator))
                {
                    msgs.msg = "操作人不能为空";
                    return JsonConvert.SerializeObject(msgs);
                }
                var findEmptyReason = "";
                using (dbModel mod = new dbModel())
                {
                    bool isInMoreHighPosition = false;
                    if (emtypContainer.name == null)//没有目标库位说明是入库
                    {
                        Task_Queue callContainerTaks = new Task_Queue();
                        callContainerTaks.BillCode = "空托盘入库";
                        string toplace = emtypContainer.type == "1" ? FindEmptyLocationHandler.findStorage(mod, "", true, ref isInMoreHighPosition, ref findEmptyReason, 1, 1, 2, 0) : FindEmptyLocationHandler.findStorage(mod, "", true, ref isInMoreHighPosition, ref findEmptyReason, 2, 2, 4, 0);
                        if (string.IsNullOrEmpty(toplace))
                        {
                            msgs.msg = "未找到合适的库位存放," + findEmptyReason;
                            return JsonConvert.SerializeObject(msgs);
                        }
 
                        callContainerTaks.TaskType = ((int)TaskTypeEnum.余料回库).ToString();//任务类型
                        callContainerTaks.OrderNumber = 0;//任务权重
                        callContainerTaks.TaskStatus = "未下发";//任务状态
                        callContainerTaks.PlateType = emtypContainer.type;//托盘类型  第二排没有空小托盘
                        callContainerTaks.CreateDate = DateTime.Now;
                        callContainerTaks.UserProduct_Id = 1007;//账套id 老谢bug  
                        //垃圾值都赋值0 转到autoTask()里有说明
                        callContainerTaks.FromPositionName = "1001";
                        callContainerTaks.Direction = "0";//托盘高度
                        callContainerTaks.ToPositionName = toplace;
                        callContainerTaks.CreateID = 0;//表示空托盘入库,注意:这个字段非常重要
                        callContainerTaks.Creator = emtypContainer.creator;
                        callContainerTaks.DoCount = emtypContainer.type == "1" ? 1 : 2;//库区
                        mod.Task_Queue.Add(callContainerTaks);
 
                        OperationLogHelper.AddOperationLogEntity(mod, emtypContainer.creator, "人工满空托回库", OperateTypeEnum.人工满空托回库, "");
 
                        int res = mod.SaveChanges();
                        if (res == 2)
                        {
                            msgs.status = 200;
                        }
                        else
                        {
                            res = mod.SaveChanges();
                            if (res == 2)
                            {
                                msgs.status = 200;
                            }
                            else
                            {
 
                                msgs.msg = "生成任务失败";
                            }
                        }
                    }
                    else
                    {
                        msgs.msg = "不支持的类型";
                    }
                }
 
            }
            catch (Exception ex)
            {
                msgs.status = 400;
                msgs.msg = "生成任务失败:" + ex.Message;
                logtxt.txtWrite("类名: " + "apitest" + "方法名:" + "emtypContainerOUtandIN 空托盘出入库产生异常参数:" + param + " 信息:" + logtxt.oneRow(ex.ToString()), 2);
 
            }
            return JsonConvert.SerializeObject(msgs);
 
            //*/
        }
 
        #region 闲时移库管理
 
        /// <summary>
        /// 分页查询 闲时移库
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string QueryPageFreeTimeMoveLocationTask(string param)
        {
            msgss<FreeTimeMoveLocationTaskOutput> msg = new msgss<FreeTimeMoveLocationTaskOutput>();
            QueryPageFoldingPlateMachineInput page = JsonConvert.DeserializeObject<QueryPageFoldingPlateMachineInput>(param);
            try
            {
                string StockWhere = "";
                //根据日期筛选
                #region 搜索条件判断
                if (page.StartTime != null)
                {
                    if (page.StartTime.Length == 2)
                    {
 
                        StockWhere = StockWhere + " and StartTime > '" + page.StartTime[0].ToString() + "' and  StartTime < '" + page.StartTime[1].ToString() + "'";
                    }
                }
                if (page.EndTime != null)
                {
                    if (page.EndTime.Length == 2)
                    {
 
                        StockWhere = StockWhere + " and EndTime > '" + page.EndTime[0].ToString() + "' and  EndTime < '" + page.EndTime[1].ToString() + "'";
                    }
                }
                if (page.CreateTime != null)
                {
                    if (page.CreateTime.Length == 2)
                    {
 
                        StockWhere = StockWhere + " and CreateTime > '" + page.CreateTime[0].ToString() + "' and  CreateTime < '" + page.CreateTime[1].ToString() + "'";
                    }
                }
 
                if (!string.IsNullOrEmpty(page.UserName))
                {
                    StockWhere = StockWhere + " and Creator like '%" + page.UserName.Trim() + "%'";
                }
 
                if (page.MoveStatus != null)
                {
                    StockWhere = StockWhere + " and MoveStatus=" + page.MoveStatus.ToString();
                }
                if (page.RunTime != null)
                {
                    StockWhere = StockWhere + " and RunTime=" + page.RunTime.ToString();
                }
                #endregion
 
                using (dbModel mod = new dbModel())
                {
                    //获取数据
                    string sql = "select * from [dbo].[" + "V_FreeTimeMoveLocationTaskPage" + "] WITH(NOLOCK) where 1=1  " + StockWhere + " order by LastModifyTime desc ";
 
                    List<FreeTimeMoveLocationTaskOutput> takeStock = mod.Database.SqlQuery<FreeTimeMoveLocationTaskOutput>(sql).ToList();
                    foreach (var item in takeStock)
                    {
                        if (item.MoveStatus == (int)MoveStatusEnum.执行中)
                        {
                            TimeSpan ts = DateTime.Now - Convert.ToDateTime(item.StartTime);
                            item.CurExcuteTime = ts.Minutes;//显示分钟
                        }
                    }
 
                    List<FreeTimeMoveLocationTaskOutput> fenyeRerult = new List<FreeTimeMoveLocationTaskOutput>();
                    if (takeStock.Count > 0)
                    {
                        msg.status = 200;
                        msg.total = takeStock.Count;
                        if (page.IsLoadAllData)
                        {//只有确定加载全部数据时才加载全部数据 [EditBy shaocx,2022-03-07]
                            msg.status = 200;
                            msg.allDate = takeStock.ToList();
                        }
                        else
                        {//不加载全部,就过滤分页信息
                            //假如每页数量 大于盘点数据
                            if (page.queryInfo.pagesize > takeStock.Count)
                            {
                                msg.date = takeStock;
                            }
                            else
                            {
                                #region 分页计算
                                int a = page.queryInfo.pagesize;
 
                                int b = page.queryInfo.pagenum;
                                int c = (int)Math.Ceiling((double)takeStock.Count / a);
                                int d = takeStock.Count % a;
                                int e = 0;
                                int f = a * (b - 1);
                                if (d != 0 && b == c)
                                {
                                    e = d + f;
 
                                }
                                else
                                {
                                    e = a + f;
                                }
 
 
 
                                for (int i = f; i < e; i++)
                                {
                                    fenyeRerult.Add(takeStock[i]);
                                }
                                msg.date = fenyeRerult;
                                #endregion
 
                            }
                        }
                    }
                    else
                    {
                        msg.status = 400;
                        msg.total = 1;
                        msg.date = null;
                    }
 
 
                    return JsonConvert.SerializeObject(msg);
                }
 
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
 
                return JsonConvert.SerializeObject(msg);
            }
 
        }
 
        /// <summary>
        /// 分页查询 闲时移库明细
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string QueryPageFreeTimeMoveLocationTaskDetails(string param)
        {
            msgss<V_FreeTimeMoveLocationTask> msg = new msgss<V_FreeTimeMoveLocationTask>();
            QueryPageFreeTimeMoveLocationTaskDetailsInput page = JsonConvert.DeserializeObject<QueryPageFreeTimeMoveLocationTaskDetailsInput>(param);
            try
            {
                string StockWhere = "";
                //根据日期筛选
                #region 搜索条件判断
                StockWhere = StockWhere + " and MainFreeMoveId=" + page.MainFreeMoveId.ToString();
                #endregion
 
                using (dbModel mod = new dbModel())
                {
                    //获取数据
                    string sql = "select * from [dbo].[" + "V_FreeTimeMoveLocationTask" + "] WITH(NOLOCK) where 1=1  " + StockWhere + " order by Task_Id desc ";
 
                    List<V_FreeTimeMoveLocationTask> takeStock = mod.Database.SqlQuery<V_FreeTimeMoveLocationTask>(sql).ToList();
 
                    List<V_FreeTimeMoveLocationTask> fenyeRerult = new List<V_FreeTimeMoveLocationTask>();
                    if (takeStock.Count > 0)
                    {
                        msg.status = 200;
                        msg.total = takeStock.Count;
                        //假如每页数量 大于盘点数据
                        if (page.queryInfo.pagesize > takeStock.Count)
                        {
                            msg.date = takeStock;
                        }
                        else
                        {
                            #region 分页计算
                            int a = page.queryInfo.pagesize;
 
                            int b = page.queryInfo.pagenum;
                            int c = (int)Math.Ceiling((double)takeStock.Count / a);
                            int d = takeStock.Count % a;
                            int e = 0;
                            int f = a * (b - 1);
                            if (d != 0 && b == c)
                            {
                                e = d + f;
 
                            }
                            else
                            {
                                e = a + f;
                            }
 
 
 
                            for (int i = f; i < e; i++)
                            {
                                fenyeRerult.Add(takeStock[i]);
                            }
                            msg.date = fenyeRerult;
                            #endregion
 
                        }
                    }
                    else
                    {
                        msg.status = 400;
                        msg.total = 1;
                        msg.date = null;
                    }
 
 
                    return JsonConvert.SerializeObject(msg);
                }
 
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
 
                return JsonConvert.SerializeObject(msg);
            }
 
        }
 
        /// <summary>
        /// 新增 闲时移库
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string AddFreeTimeMoveLocationTask(string param)
        {
            FunRetEntity msgs = new FunRetEntity();
            try
            {
                AddFoldingPlateMachineInput input = JsonConvert.DeserializeObject<AddFoldingPlateMachineInput>(param);
                return JsonConvert.SerializeObject(FreeTimeMoveLocationTaskHandler.Add(input));
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("类名: " + "apitest" + "方法名:" + "AddFreeTimeMoveLocationTask 增加闲时移库管理 异常参数:" + param + " 信息:" + logtxt.oneRow(ex.ToString()), 2);
                return JsonConvert.SerializeObject(FunRetEntity.Fail("异常:" + ex.Message));
            }
        }
 
        /// <summary>
        /// 编辑 闲时移库
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string UpdateFreeTimeMoveLocationTask(string param)
        {
            FunRetEntity msgs = new FunRetEntity();
            try
            {
                UpdateFoldingPlateMachineInput input = JsonConvert.DeserializeObject<UpdateFoldingPlateMachineInput>(param);
                return JsonConvert.SerializeObject(FreeTimeMoveLocationTaskHandler.Update(input));
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("类名: " + "apitest" + "方法名:" + "UpdateFreeTimeMoveLocationTask 编辑闲时移库管理 异常参数:" + param + " 信息:" + logtxt.oneRow(ex.ToString()), 2);
                return JsonConvert.SerializeObject(FunRetEntity.Fail("异常:" + ex.Message));
            }
        }
 
        /// <summary>
        /// 执行 闲时移库
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string ExcuteFreeTimeMoveLocationTask(string param)
        {
            FunRetEntity msgs = new FunRetEntity();
            try
            {
                ExcuteAndCancelFoldingPlateMachineInput input = JsonConvert.DeserializeObject<ExcuteAndCancelFoldingPlateMachineInput>(param);
                return JsonConvert.SerializeObject(FreeTimeMoveLocationTaskHandler.Excute(input));
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("类名: " + "apitest" + "方法名:" + "ExcuteFreeTimeMoveLocationTask 执行 闲时移库管理 异常参数:" + param + " 信息:" + logtxt.oneRow(ex.ToString()), 2);
                return JsonConvert.SerializeObject(FunRetEntity.Fail("异常:" + ex.Message));
            }
        }
 
        /// <summary>
        /// 取消 闲时移库
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string CancelFreeTimeMoveLocationTask(string param)
        {
            FunRetEntity msgs = new FunRetEntity();
            try
            {
                ExcuteAndCancelFoldingPlateMachineInput input = JsonConvert.DeserializeObject<ExcuteAndCancelFoldingPlateMachineInput>(param);
                return JsonConvert.SerializeObject(FreeTimeMoveLocationTaskHandler.Cancel(input));
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("类名: " + "apitest" + "方法名:" + "CancelFreeTimeMoveLocationTask 取消 闲时移库管理 异常参数:" + param + " 信息:" + logtxt.oneRow(ex.ToString()), 2);
                return JsonConvert.SerializeObject(FunRetEntity.Fail("异常:" + ex.Message));
            }
        }
 
        /// <summary>
        /// 人工结束 闲时移库
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string PersonStopFreeTimeMoveLocationTask(string param)
        {
            FunRetEntity msgs = new FunRetEntity();
            try
            {
                PersonStopFoldingPlateMachineInput input = JsonConvert.DeserializeObject<PersonStopFoldingPlateMachineInput>(param);
                return JsonConvert.SerializeObject(FreeTimeMoveLocationTaskHandler.PersonStop(input));
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("类名: " + "apitest" + "方法名:" + "PersonStopFreeTimeMoveLocationTask 人工结束 闲时移库管理 异常参数:" + param + " 信息:" + logtxt.oneRow(ex.ToString()), 2);
                return JsonConvert.SerializeObject(FunRetEntity.Fail("异常:" + ex.Message));
            }
        }
 
 
        #endregion
 
        #region 按单出库记录
 
        /// <summary>
        /// 分页查询 按单出库记录
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string QueryPageSale_Order_History(string param)
        {
            msgss<Sale_Order_History> msg = new msgss<Sale_Order_History>();
            QueryPageSale_Order_HistoryInput page = JsonConvert.DeserializeObject<QueryPageSale_Order_HistoryInput>(param);
            try
            {
                string StockWhere = "";
                //根据日期筛选
                #region 搜索条件判断
                if (page.CreateTime != null)
                {
                    if (page.CreateTime.Length == 2)
                    {
 
                        StockWhere = StockWhere + " and CreateTime > '" + page.CreateTime[0].ToString() + "' and  CreateTime < '" + page.CreateTime[1].ToString() + "'";
                    }
                }
 
                if (!string.IsNullOrEmpty(page.UserName))
                {
                    StockWhere = StockWhere + " and Creator like '%" + page.UserName.Trim() + "%'";
                }
 
                if (!string.IsNullOrEmpty(page.OrderCode))
                {
                    StockWhere = StockWhere + " and OrderCode='" + page.OrderCode.ToString() + "' ";
                }
                if (!string.IsNullOrEmpty(page.TrackingNumber))
                {
                    StockWhere = StockWhere + " and TrackingNumber='" + page.TrackingNumber.ToString() + "' ";
                }
 
                #endregion
 
                using (dbModel mod = new dbModel())
                {
                    //获取数据
                    string sql = "select * from [dbo].[" + "Sale_Order_History" + "] WITH(NOLOCK) where 1=1  " + StockWhere + " order by LastModifyTime desc ";
 
                    List<Sale_Order_History> takeStock = mod.Database.SqlQuery<Sale_Order_History>(sql).ToList();
 
 
                    List<Sale_Order_History> fenyeRerult = new List<Sale_Order_History>();
                    if (takeStock.Count > 0)
                    {
                        msg.status = 200;
                        msg.total = takeStock.Count;
                        if (page.IsLoadAllData)
                        {//只有确定加载全部数据时才加载全部数据 [EditBy shaocx,2022-03-07]
                            msg.status = 200;
                            msg.allDate = takeStock.ToList();
                        }
                        else
                        {//不加载全部,就过滤分页信息
                            //假如每页数量 大于盘点数据
                            if (page.queryInfo.pagesize > takeStock.Count)
                            {
                                msg.date = takeStock;
                            }
                            else
                            {
                                #region 分页计算
                                int a = page.queryInfo.pagesize;
 
                                int b = page.queryInfo.pagenum;
                                int c = (int)Math.Ceiling((double)takeStock.Count / a);
                                int d = takeStock.Count % a;
                                int e = 0;
                                int f = a * (b - 1);
                                if (d != 0 && b == c)
                                {
                                    e = d + f;
 
                                }
                                else
                                {
                                    e = a + f;
                                }
 
 
 
                                for (int i = f; i < e; i++)
                                {
                                    fenyeRerult.Add(takeStock[i]);
                                }
                                msg.date = fenyeRerult;
                                #endregion
 
                            }
                        }
                    }
                    else
                    {
                        msg.status = 400;
                        msg.total = 1;
                        msg.date = null;
                    }
 
 
                    return JsonConvert.SerializeObject(msg);
                }
 
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
 
                return JsonConvert.SerializeObject(msg);
            }
 
        }
 
        /// <summary>
        /// 分页查询 按单出库记录明细
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string QueryPageSale_Order_HistoryDetails(string param)
        {
            msgss<Sale_Order_History_Items> msg = new msgss<Sale_Order_History_Items>();
            QueryPageSale_Order_History_ItemsInput page = JsonConvert.DeserializeObject<QueryPageSale_Order_History_ItemsInput>(param);
            try
            {
                string StockWhere = "";
                //根据日期筛选
                #region 搜索条件判断
                StockWhere = StockWhere + " and Sale_Order_History_Id=" + page.Sale_Order_History_Id.ToString();
                #endregion
 
                using (dbModel mod = new dbModel())
                {
                    //获取数据
                    string sql = "select * from [dbo].[" + "Sale_Order_History_Items" + "] WITH(NOLOCK) where 1=1  " + StockWhere + " order by ID desc ";
 
                    List<Sale_Order_History_Items> takeStock = mod.Database.SqlQuery<Sale_Order_History_Items>(sql).ToList();
 
                    List<Sale_Order_History_Items> fenyeRerult = new List<Sale_Order_History_Items>();
                    if (takeStock.Count > 0)
                    {
                        msg.status = 200;
                        msg.total = takeStock.Count;
                        //假如每页数量 大于盘点数据
                        if (page.queryInfo.pagesize > takeStock.Count)
                        {
                            msg.date = takeStock;
                        }
                        else
                        {
                            #region 分页计算
                            int a = page.queryInfo.pagesize;
 
                            int b = page.queryInfo.pagenum;
                            int c = (int)Math.Ceiling((double)takeStock.Count / a);
                            int d = takeStock.Count % a;
                            int e = 0;
                            int f = a * (b - 1);
                            if (d != 0 && b == c)
                            {
                                e = d + f;
 
                            }
                            else
                            {
                                e = a + f;
                            }
 
 
 
                            for (int i = f; i < e; i++)
                            {
                                fenyeRerult.Add(takeStock[i]);
                            }
                            msg.date = fenyeRerult;
                            #endregion
 
                        }
                    }
                    else
                    {
                        msg.status = 400;
                        msg.total = 1;
                        msg.date = null;
                    }
 
 
                    return JsonConvert.SerializeObject(msg);
                }
 
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("出错信息" + ex.Message + "出错行号" + (string)ex.StackTrace, 2);
                msg.status = 400;
                msg.total = 1;
                msg.date = null;
 
                return JsonConvert.SerializeObject(msg);
            }
 
        }
 
 
        #endregion
 
        #region 权限
 
        /// <summary>
        /// 查询 某个菜单下的,某个角色的权限,考虑多个角色不?我看了,系统配置一个用户只能是一个角色,因此不需要考虑多个角色的情况
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string QueryButtonAuth(string param)
        {
            FunRetEntity msgs = new FunRetEntity();
            try
            {
                QueryButtonPermissionInput input = JsonConvert.DeserializeObject<QueryButtonPermissionInput>(param);
                if (string.IsNullOrEmpty(input.menu_IdEnum))
                {
                    return JsonConvert.SerializeObject(FunRetEntity.Fail("菜单ID不能为空"));
                }
                Menu_IdEnum menuIdEnum = (Menu_IdEnum)Enum.Parse(typeof(Menu_IdEnum), input.menu_IdEnum);
                var buttonAuth = SystemHelper.QueryButtonPermission(input.role_Id, menuIdEnum);
 
                return JsonConvert.SerializeObject(FunRetEntity.Success("成功", buttonAuth));
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("类名: " + "apitest" + "方法名:" + "QueryButtonAuth 查询 某个菜单下的,某个角色的权限 异常参数:" + param + " 信息:" + logtxt.oneRow(ex.ToString()), 2);
                return JsonConvert.SerializeObject(FunRetEntity.Fail("异常:" + ex.Message));
            }
        }
 
        #endregion
 
        #region 打印标签
 
 
        /// <summary>
        /// 重新打印 标签
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string RePrintBarCode(string param)
        {
            FunRetEntity msgs = new FunRetEntity();
            try
            {
                if (string.IsNullOrEmpty(param))
                {
                    return JsonConvert.SerializeObject(FunRetEntity.Fail("标签条码不能为空!"));
                }
                RePrintBarCodeInput input = JsonConvert.DeserializeObject<RePrintBarCodeInput>(param);
                if (input.barCode == null || input.barCode.Count == 0)
                {
                    return JsonConvert.SerializeObject(FunRetEntity.Fail("标签条码不能为空!"));
                }
                using (dbModel edm = new dbModel())
                {
                    foreach (var item in input.barCode)
                    {
                        var data = edm.Base_PositionPrint.Where(x => x.ExtendField06 == item).FirstOrDefault();
                        if (data == null)
                        {
                            return JsonConvert.SerializeObject(FunRetEntity.Fail("根据标签条码" + item + "没有找到打印数据!"));
                        }
 
                        if (data.printDevice == null)
                        {
                            return JsonConvert.SerializeObject(FunRetEntity.Fail("根据标签条码" + item + "查到的打印数据没有指定打印机!"));
                        }
 
                        data.isNeedPrint = 1;
                        edm.SaveChanges();
                    }
                }
                return JsonConvert.SerializeObject(FunRetEntity.Success("成功"));
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("类名: " + "apitest" + "方法名:" + "RePrintBarCode 重新打印 标签 异常参数:" + param + " 信息:" + logtxt.oneRow(ex.ToString()), 2);
                return JsonConvert.SerializeObject(FunRetEntity.Fail("异常:" + ex.Message));
            }
        }
 
 
        #endregion
 
 
        #region 维护库存预警天数
 
        /// <summary>
        /// 维护库存预警天数
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string UpdateStoreWarningDays(string param)
        {
            FunRetEntity msgs = new FunRetEntity();
            try
            {
                UpdateStoreWarningDaysInput input = JsonConvert.DeserializeObject<UpdateStoreWarningDaysInput>(param);
                return JsonConvert.SerializeObject(UpdateStoreWarningDaysHandler.Excute(input));
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("类名: " + "apitest" + "方法名:" + "UpdateStoreWarningDays 维护库存预警天数 异常参数:" + param + " 信息:" + logtxt.oneRow(ex.ToString()), 2);
                return JsonConvert.SerializeObject(FunRetEntity.Fail("异常:" + ex.Message));
            }
        }
 
        /// <summary>
        /// 获取库存预警天数
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public string GetStoreWarningDays(string param)
        {
            FunRetEntity msgs = new FunRetEntity();
            try
            {
                return JsonConvert.SerializeObject(UpdateStoreWarningDaysHandler.Get());
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("类名: " + "apitest" + "方法名:" + "GetStoreWarningDays 获取库存预警天数 信息:" + logtxt.oneRow(ex.ToString()), 2);
                return JsonConvert.SerializeObject(FunRetEntity.Fail("异常:" + ex.Message));
            }
        }
 
        #endregion
 
        #endregion
 
        #region 给WCS接口
 
        /// <summary>
        /// 返回给WCS 库区和目标库位
        /// </summary>
        /// <param name="taskId">PLC任务号</param>
        /// <param name="continerType">托盘类型</param>
        /// <param name="height">高度</param>
        /// <param name="wmsTaskId">WMS的任务ID</param>
        /// <returns>失败返回"",成功返回-例子"2-01-01-01" 2号库位1排1列1层</returns>
        public string getToPlace(int taskId, int continerType, int height, int wmsTaskId)
        {
            string toplace = "";
            try
            {
                var findEmptyReason = "";
                toplace = FindEmptyLocationHandler.toPlace(taskId, continerType, height, height, ref findEmptyReason, wmsTaskId);
                logtxt.txtWrite("类名:taskApi,函数名: getToPlace:wcs高度等级是:" + height + " 任务号是:" + taskId + " 托盘类型是:" + continerType + " 返回目标地址是 " + toplace
                    + ",原因findEmptyReason:" + findEmptyReason
                    , 1);
            }
            catch (Exception ex)
            {
 
                logtxt.txtWrite("类名:taskApi,异常函数名: getToPlace:wcs高度等级是:" + height + " 任务号是:" + taskId + " 托盘类型是:" + continerType + " 返回目标地址是 " + toplace + logtxt.oneRow(ex.ToString()), 2);
                toplace = "";
            }
            return toplace;
        }
        #endregion
 
        #region 调sap接口
 
        /// <summary>sap收货确认
        ///  sap收货确认
        /// </summary>
        /// <param name="receipt">json字符串</param>
        /// <returns>空表示成功,否则返回失败内容</returns>
        public string receiptConfirm(string receipt)
        {
            // 转入toPlace   转出fromPlace
            #region po单状态
            //StatusText = "新建";
            //StatusID = 1;
            //StatusText = "部分完成";
            //StatusID = 7;
            //StatusText = "完全交货";
            //StatusID =8 ;
            #endregion
 
            string msg = "";
            if (receipt == null)
            {
                var datax = new
                {
                    result = false,
                    msg = "参数不能为空"
                };
                msg = JsonConvert.SerializeObject(datax);
                return msg;
            }
 
            logtxt.txtWrite(receipt, 0);//收到记录一条日志
            try
            {
                using (dbModel mod = new dbModel())
                {
 
                    //转换收料信息
                    GRMaterialEntity[] results = JsonConvert.DeserializeObject<GRMaterialEntity[]>(receipt);
                    if (results.Length > 0)
                    {
                        //没有PO单就是手动收货
                        if (string.IsNullOrEmpty(results[0].PoNumber))
                        {
                            #region 无单收货
                            //转换成移库实体  [{"MaterialCode":"A7EQD-5130033087","Quantity":1,"MoveType":"262","toPlace":"G021","fromPlace":"G021","trackingNumber":"7615"}]
                            moveStock[] moveResults = JsonConvert.DeserializeObject<moveStock[]>(receipt);
                            //检查是否带跟踪号不带的移动类型 不带E
                            List<MovMaterialEntity> moveMaterials = new List<MovMaterialEntity>();//移库实体
                            List<GIMaterialEntity> GImaterals = new List<GIMaterialEntity>();//收货实体类
 
                            foreach (var itemGi in moveResults)
                            {
                                string moveType = itemGi.MoveType;
                                string trackingNum = itemGi.trackingNumber;
                                string materialCode = itemGi.MaterialCode;
                                //311是移库有转入仓和转出仓
                                if (moveType == "311")
                                {
                                    #region MyRegion
                                    MovMaterialEntity moveMaterial = new MovMaterialEntity();
                                    //有跟踪号 移动类型要加E  加E就要天销售单号和销售项号
                                    if (!string.IsNullOrEmpty(trackingNum))//ProductCode poInfoChild.ExtendField07 = item.SalesOrder;//销售单号 poInfoChild.SpecAlias = item.SalesOrderItem;//销售单项号
                                    {
                                        moveType += "E";
                                        Purchase_OrderList poList = mod.Purchase_OrderList.FirstOrDefault(x => x.ExtendField04 == trackingNum && x.ProductCode == materialCode);
                                        moveMaterial.SalesOrder = poList.ExtendField07;
                                        moveMaterial.SalesOrderItem = poList.SpecAlias;
                                    }
                                    logtxt.txtWrite("发送的移动类型是" + moveType + "跟踪号:" + trackingNum, 0);//收到记录一条日志
                                    moveMaterial.MoveType = moveType;
                                    moveMaterial.Plant = "3TG1";
                                    moveMaterial.MaterialCode = materialCode;
                                    moveMaterial.FromStorageLocation = itemGi.fromPlace;
                                    moveMaterial.ToStorageLocation = itemGi.toPlace;
                                    moveMaterial.Quantity = itemGi.Quantity;
                                    moveMaterials.Add(moveMaterial);
                                    #endregion
 
                                }
                                else
                                {
                                    #region MyRegion
                                    GIMaterialEntity GImateral = new GIMaterialEntity();
                                    if (!string.IsNullOrEmpty(trackingNum))//ProductCode poInfoChild.ExtendField07 = item.SalesOrder;//销售单号 poInfoChild.SpecAlias = item.SalesOrderItem;//销售单项号
                                    {
                                        moveType += "E";
                                        Purchase_OrderList poList = mod.Purchase_OrderList.FirstOrDefault(x => x.ExtendField04 == trackingNum && x.ProductCode == materialCode);
                                        if (poList == null)//根据跟踪号查不到数据 就赋值为空
                                        {
                                            GImateral.SalesOrder = "";
                                            GImateral.SalesOrderItem = "";
                                        }
                                        else
                                        {
                                            GImateral.SalesOrder = poList.ExtendField07 == null ? "" : poList.ExtendField07;
                                            GImateral.SalesOrderItem = poList.SpecAlias == null ? "" : poList.SpecAlias;
                                        }
                                    }
                                    GImateral.MoveType = moveType;
                                    GImateral.StorageLocation = "G021";
                                    GImateral.Plant = "3TG1";
                                    GImateral.MaterialCode = materialCode;
                                    GImateral.Quantity = itemGi.Quantity;
                                    GImateral.WorkOrder = "#0#0";
                                    GImaterals.Add(GImateral);
                                    #endregion
 
                                }
                            }
                            if (moveMaterials.Count > 0)//有数据说明是移库
                            {
                                string moveReceipt = JsonConvert.SerializeObject(moveMaterials);
                                msg = SAPHelper.moveStockConfirm(null, moveReceipt);
                            }
                            if (GImaterals.Count > 0)//有数据说明是退料
                            {
                                string GiReceipt = JsonConvert.SerializeObject(GImaterals);
                                msg = SAPHelper.StockOutConfirm(null, GiReceipt);
                            }
                            return msg;
                            #endregion
 
                        }
                    }
                    else
                    {
                        var data = new
                        {
                            result = false,
                            msg = "无此单号"
                        };
                        msg = JsonConvert.SerializeObject(data);
                        return msg;
                    }
 
                    //收货信息给SAP
                    var result = SAPHelper.ConfirmGR(results, out msg);
                    //注释以下方法,当收货信息推送给SAP失败后,也要允许他们进行收货打印标记  【EditBy shaocx,2022-09-30】
                    msg = "";//强制认为收货信息推送给SAP是成功的! 【EditBy shaocx,2022-09-30】
                    /*
                    if (result == false)
                    {
                        var data = new
                        {
                            result = false,
                            msg = "收货信息给SAP失败:" + msg
                        };
                        msg = JsonConvert.SerializeObject(data);
                        return msg;
                    }
                    //*/
                    //注释以下方法,改为调用 SAPHelper方法 【EditBy shaocx,2022-09-23】
                    /*
                    string info = sendSap.ConfirmGR(results, out msg);
                    form.textBox6.Text = DateTime.Now.ToString("dd-HH-mm-ss") + "收货,退货成功,凭证:" + info + "返回信息" + msg + "\r\n" + form.textBox6.Text;
                    if (msg == "")
                    {
                        logtxt.txtWrite("收货,退货成功,凭证:" + info, 0);
                    }
                    else
                    {
                        //这里是 收货,退货失败? [EditBy shaocx,2022-03-06]
                        logtxt.txtWrite("收货,退货失败,凭证:" + info + ",返回msg:" + msg, 0);
                        SapSendFailRecodInfoHandler.AddForSH(results, info, msg);//记录失败表
                    }
                    //*/
                }
            }
            catch (Exception ex)
            {
                logtxt.txtWrite("收货,退货执行异常" + ex.Message, 2);
                var data = new
                {
                    result = false,
                    msg = "执行异常"
                };
                msg = JsonConvert.SerializeObject(data);
                return msg;
            }
 
            var data1 = new
            {
                result = msg == "" ? true : false,
                msg = msg == "" ? "执行成功" : "执行失败",
            };
            msg = JsonConvert.SerializeObject(data1);
            return msg;
 
        }
        /// <summary>获取Po单
        ///  获取Po单
        /// </summary>
        /// <param name="PoCode">Po单</param>
        /// <returns></returns>
        public string getPoList(string PoCode)
        {
            DateTime timeInfo = DateTime.Now;
            string msg = "";
            try
            {
                using (dbModel mod = new dbModel())
                {
 
                    Purchase_Order poNumber = mod.Purchase_Order.Where(x => x.PoCode == PoCode).FirstOrDefault();
                    //PO表里查不到就SAP接口里获取采购信息
                    if (poNumber == null)
                    {//GetPurchaseOrder
                        #region 如果主表里没有数据就调ASP接口获取采购单
                        PurchaseOrderEntity resultPo = SAPHelper.GetPurchaseOrder(PoCode, out msg);
                        //PurchaseOrderEntity resultPo = sendSap.GetPurchaseOrder(PoCode, out msg);//改为调用SAPHelper 【Editby shaocx,2022-09-23】
                        if (msg != "")//获取失败返回空
                        {
                            var data = new
                            {
                                result = false,
                                msg = "找不到这个单号"
                            };
                            msg = JsonConvert.SerializeObject(data);
                            return msg;
                        }
                        List<string> rstPo = resultPo.Materials.Select(x => x.MaterialCode).ToList();
 
                        Purchase_Order poInfo = new Purchase_Order();
                        #region 主表数据
                        poInfo.PoCode = resultPo.PoNumber;//采购单号
                        poInfo.StatusText = "新建";//状态 providerShortName
                        poInfo.StatusID = 1;
                        poInfo.AuditRemark = resultPo.PurchaseOrg;//采购部门 VendorName
                        poInfo.ProviderShortName = resultPo.VendorName;
                        poInfo.CreateID = 1;
                        poInfo.Creator = resultPo.CreatedBy;
                        poInfo.CreateDate = DateTime.Now;
                        #region 数据库不可为空垃圾字段
                        poInfo.Storage_Id = 87;
                        poInfo.StorageName = "立体库";
                        poInfo.Consignor_Id = 30;
                        poInfo.ConsignorCode = "GX30";
                        poInfo.ConsignorName = "广州西门子";
                        poInfo.UserProductCode = "100000001";
                        poInfo.UserProduct_Id = 1007;
                        #endregion
                        #endregion
 
                        //添加PO单物料明细
                        List<Purchase_OrderList> poInfoList = new List<Purchase_OrderList>();
                        int number = 0;
                        //查找物料基础数据  找到po明细物料编号在数据库里有的集合
                        var checkMateria1s = (from p in mod.Base_ProductInfo where (from f in rstPo select f).Contains(p.ProductCode) select p).ToList();
 
                        #region 添加PO单物料明细
                        System.Collections.Generic.List<Purchase_OrderList_EmptyMaterialCode> insert_OrderList_EmptyMaterialCodeList = new List<Purchase_OrderList_EmptyMaterialCode>();
                        string lastTracknum = "";
                        foreach (var item in resultPo.Materials)
                        {
                            if (string.IsNullOrEmpty(item.MaterialCode))
                            {//写入PO明细空物料号表        【Editby shaocx,2025-09-09】
                                logtxt.txtWrite("采购单号:" + item.PoNumber + " 物料项号:" + item.PoItem + "物料编号为空", 2);
                                insert_OrderList_EmptyMaterialCodeList.Add(new Purchase_OrderList_EmptyMaterialCode()
                                {
                                    ID = Yitter.IdGenerator.YitIdHelper.NextId(),
                                    PoCode = poInfo.PoCode,
                                    BatchNumber = "",
                                    ItemNumber = item.PoItem,
                                    ProductName = item.MaterialName,
                                    CreateTime = DateTime.Now,
                                    Creator = resultPo.CreatedBy,
                                    Quantity = 0,
                                    LastModifier = resultPo.CreatedBy,
                                    LastModifyTime = DateTime.Now,
                                    Remark = ""
                                });
                                continue;//物料编号为空
                            }
                            string materialCode = item.MaterialCode;
                            long productId = 0;
 
                            #region 检查物料基础信息里是否有这个物料没有就新建
                            Base_ProductInfo checkMateria = checkMateria1s.FirstOrDefault(x => x.ProductCode == materialCode);
                            Base_ProductInfo newMateria = new Base_ProductInfo();
                            if (checkMateria == null)
                            {
                                newMateria.ProductCode = materialCode;//物料编号
                                newMateria.ProductName = item.MaterialName;//物料名称
                                newMateria.SmallUnit = item.BaseUnit;//库存单位
                                newMateria.BigUnit = item.Unit;//采购单位
                                newMateria.Enable = 1;//设置为可用 
                                newMateria.ProviderShortName = resultPo.VendorName;//供应商名称
                                newMateria.UnitConvert = 1M;//大小单位转换
                                newMateria.Brand_Id = 0;//库存预警量
                                ///////////////
                                newMateria.ProductModel = materialCode;
                                newMateria.Provider_Id = 926;
                                newMateria.ProviderCode = "PV201940371";
 
                                newMateria.Consignor_Id = 30;
                                newMateria.ConsignorCode = "GX30";
                                newMateria.ConsignorName = "广州西门子";
                                newMateria.UserProduct_Id = 1007;
                                newMateria.UserProductCode = "100000001";
                                mod.Base_ProductInfo.Add(newMateria);
                                mod.SaveChanges();
                                //通过新建获取产品ID
                                productId = newMateria.Product_Id;
                            }
                            else
                            {
                                //通过查询获取ID
                                productId = checkMateria.Product_Id;
                            }
                            #endregion
 
 
                            //Base_ProductInfo isNewMateria=mod.Base_ProductInfo
                            string trackingNum = "";
                            if (!string.IsNullOrEmpty(item.TrackingNo))
                            {
                                if (item.TrackingNo.Split('/')[0].Substring(0, 1) == "D")
                                {
                                    trackingNum = item.TrackingNo.Split('/')[0].Remove(0, 1);
                                }
                                else
                                {
                                    trackingNum = item.TrackingNo.Split('/')[0];
                                }
                            }
                            #region 添加出库明细
                            Purchase_OrderList poInfoChild = new Purchase_OrderList();
                            poInfoChild.ExtendField10 = item.PoNumber;//采购单号
                            poInfoChild.ItemNumber = item.PoItem;//采购项号
                            poInfoChild.Product_Id = productId;//产品id
                            poInfoChild.ProductCode = materialCode;//物料编号
                            poInfoChild.ProductName = item.MaterialName;//物料名称
                            poInfoChild.BigQty = item.Quantity;//采购数量
                            poInfoChild.BigUnit = item.Unit;//采购单位
                            poInfoChild.ExtendField04 = trackingNum;//跟踪号
                            poInfoChild.ExtendField07 = item.SalesOrder;//销售单号
                            poInfoChild.SpecAlias = item.SalesOrderItem;//销售单项号
                            poInfoChild.ProductBarCode = item.StorageLocation;//库区编号G021
                            poInfoChild.ExtendField02 = item.Plant;//工厂
 
                            try//UnEnterQuantity
                            {
                                poInfoChild.UnEnterQuantity = Convert.ToDecimal(item.ConvertDen2);   //订单单位转换系数 和下面单位转换有关,例如100kg(ConvertDen2)=126米(ConvertNum2)
                                poInfoChild.UnitConvert = Convert.ToDecimal(item.ConvertNum2);  //单位转换值    
                                poInfoChild.Overcharges = Convert.ToDecimal(item.OverDelTol);  //容差率上线
                            }
                            catch (Exception ex)
                            {
                                logtxt.txtWrite("采购单号:" + item.PoNumber + " 物料项号:" + item.PoItem + "物料编号:" + materialCode + " 单位转换或者容差转换失败", 2);
                                continue;//单位转换或者容差转换失败
 
                            }
 
                            //垃圾字段
                            poInfoChild.ProductModel = materialCode;
                            poInfo.Purchase_OrderList.Add(poInfoChild);
                            // poInfoList.Add(poInfoChild);
                            number++;
                            #endregion
                            #region 反推picklist 里的跟踪号
                            string saleOrder = item.SalesOrder;
                            string saleItemNumber = item.SalesOrderItem;
                            if (saleOrder != "" && lastTracknum != trackingNum)
                            {
                                if (trackingNum != "")
                                {
                                    //明细加跟踪号
                                    lastTracknum = trackingNum;
                                    List<Sale_OrderList> sendPicklistTrackNumber = mod.Sale_OrderList.Where(x => x.SaleCode == saleOrder && x.ExtendField06 == saleItemNumber && x.TrackingNumber == "").ToList();
 
                                    if (sendPicklistTrackNumber.Count > 0)
                                    {
                                        var orderTrack = sendPicklistTrackNumber.GroupBy(x => x.Order_Id);
                                        var orders = mod.Sale_Order.ToList();//一次读取不然出库单多的时候会卡死 2021-8-16 修改
                                        if (orderTrack != null)
                                        {
                                            foreach (var itemOrder in orderTrack)
                                            {
                                                long orderId = itemOrder.ToList()[0].Order_Id;
                                                Sale_Order addTrack = orders.FirstOrDefault(x => x.Order_Id == orderId);
                                                //if (addTrack != null && addTrack.OrderType == "SAP生产订单" && addTrack.StatusText == "新建")
                                                //if (addTrack != null && addTrack.OrderType == SysGlole.SAP_ORDER_TEXT && addTrack.StatusText == "新建")
                                                if (addTrack != null && addTrack.OrderType == SysGlole.SAP_ORDER_TEXT && addTrack.StatusText == Sale_Order_StatusEnum.新建.ToString())
                                                {
                                                    addTrack.TrackingNumber = trackingNum;
                                                    foreach (var itemList in itemOrder)
                                                    {
                                                        itemList.TrackingNumber = trackingNum;
                                                    }
                                                }
                                            }
                                        }
                                    }
 
 
                                }
 
 
                            }
                            #endregion
 
 
                        }
                        #endregion
                        //先保存主表 然后获取主表ID 再写入明细表
                        mod.Purchase_Order.Add(poInfo);
 
                        if (insert_OrderList_EmptyMaterialCodeList != null && insert_OrderList_EmptyMaterialCodeList.Count > 0)
                        {//写入PO明细空物料号表 【Editby shaocx,2025-09-09】
                            mod.Purchase_OrderList_EmptyMaterialCode.AddRange(insert_OrderList_EmptyMaterialCodeList);
                        }
 
                        int results = mod.SaveChanges();
                        for (int h = 0; h < 10; h++)
                        {
                            if (results < 1)
                            {
                                results = mod.SaveChanges();
                            }
                            else
                            {
                                break;
                            }
                        }
                        var data1 = new
                        {
                            result = true,
                            data = resultPo.Materials
                        };
                        msg = JsonConvert.SerializeObject(data1);
                        //JsonConvert.SerializeObject(str)
                        #endregion
 
                    }
 
                }
            }
            // DateTime timeInfo = DateTime.Now;
 
 
            catch (Exception ex)
            {
 
                logtxt.txtWrite("采购单号:" + PoCode + "产生异常" + ex.Message, 2);
                return "找不到这个单号";
            }
            var timeInfo1 = DateTime.Now - timeInfo;
            form.textBox6.Text = "po获取用时: " + timeInfo1 + "\r\n" + form.textBox6.Text;
            return msg;
        }
 
 
 
 
        /// <summary>按凭证退货
        /// 按凭证退货
        /// </summary>
        /// <param name="res"></param>
        /// <returns></returns>
        public string reverser(string res)
        {
            return SAPHelper.reverser(res);
        }
 
        #endregion
 
    }
}