yxj
2025-04-02 0f7cfd3e4bf160d6aba48514c89a1aae723ed5a7
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
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Http;
using WebAPI.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Diagnostics;
using System.Threading;
using System.Globalization;
namespace WebAPI.Controllers.SCGL.日计划管理
{
    public class JIT_DayPlanPlatFormBillController : ApiController
    {
        List<PRD_Inventory> ListInventory;//库存明细
        private json objJsonResult = new json();
        public DataSet ds = new DataSet();
        public WebServer webserver = new WebServer();
        SQLHelper.ClsCN oCN = new SQLHelper.ClsCN();
        Sc_WorkBillSortBillMain omdelMian = new Sc_WorkBillSortBillMain();
        public static string BillType = "4610";
        Pub_Class.ClsXt_SystemParameter oSystemParameter = new Pub_Class.ClsXt_SystemParameter();
 
        #region 生产日计划平台 查询
        [Route("JIT_DayPlanPlatFormBill/JIT_DayPlanPlatFormBillList")]
        [HttpGet]
        public object JIT_DayPlanPlatFormBillList(string sWhere, string user)
        {
            try
            {
                //查看权限
                if (!DBUtility.ClsPub.Security_Log("Sc_WorkBillSortBill_Query", 1, false, user))
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "无查看权限!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                omdelMian = JsonConvert.DeserializeObject<Sc_WorkBillSortBillMain>(sWhere);
 
                ds = oCN.RunProcReturn($"exec h_p_JIT_Sc_WorkBillSortBill_Query '{omdelMian.HPlanBeginDate}',{(omdelMian.HProdORGID == null ? 0 : omdelMian.HProdORGID)},'{omdelMian.HSeOrderBillNo}'" +
                    $",'{omdelMian.HPlanEndDate.AddDays(1)}',{omdelMian.HMaterID},'{omdelMian.HICMOBillNo}',{omdelMian.HWorkShopID}" +
                    $",'{omdelMian.HMastersDate}','{omdelMian.sWheres}'", "h_p_JIT_Sc_WorkBillSortBill_Query");
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = ds.Tables[0];
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
 
        /// <summary>
        /// 根据ID查询 齐套状态 和 锁定状态
        /// </summary>
        /// <param name="sWhere"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        [Route("JIT_DayPlanPlatFormBill/JIT_DayPlanPlatFormBillHinterIDList")]
        [HttpGet]
        public object JIT_DayPlanPlatFormBillHinterIDList(string sWhere,int num)
        {
            try
            {
                if (num == 1)
                {
                    ds = oCN.RunProcReturn($"select isnull(DATEDIFF(DAY,GETDATE(),CONVERT(varchar(10),max(HMasterDate),20))+1,0) DayNum from  Sc_WorkBillSortBillSub where HInterID in ({sWhere}) and  HMasterDate>=CONVERT(varchar(10),GETDATE(),20) and HLockedSub=1", "Sc_WorkBillSortBillSub");
                }
                else if (num == 2)
                {
                    ds = oCN.RunProcReturn($"select CONVERT(varchar(10),HMasterDate,20) HMasterDate,HComplete,HInterID from  Sc_WorkBillSortBillSub where HInterID in ({sWhere}) and  HMasterDate>=CONVERT(varchar(10),GETDATE(),20) and (HComplete='齐套' or  HComplete='未齐套') ", "Sc_WorkBillSortBillSub");
                }
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = ds.Tables[0];
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
 
        /// <summary>
        /// 根据点击行标题时间查询缺料分析
        /// </summary>
        /// <param name="sWhere"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        [Route("JIT_DayPlanPlatFormBill/JIT_DayPlanPlatFormBillHDateTimeList")]
        [HttpGet]
        public object JIT_DayPlanPlatFormBillHDateTimeList(string sWhere)
        {
            try
            {
                MaterialShorAnalysis Report = JsonConvert.DeserializeObject<MaterialShorAnalysis>(sWhere);
 
                ds = oCN.RunProcReturn($"exec h_p_JIT_MaterialShorAnalysisReportList {Report.HORGID},'{Report.HBEGINDATE}','{Report.HENDDATE}' ", "h_p_JIT_PODemandPlanBill_ReportList");
 
               
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = ds.Tables[0];
                //objJsonResult.list = columnNameList;
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 生产日计划平台 保存
        [Route("JIT_DayPlanPlatFormBill/JIT_DayPlanPlatFormBill_btnSave")]
        [HttpPost]
        public object JIT_DayPlanPlatFormBill_btnSave([FromBody] JObject sMainSub)
        {
            var _value = sMainSub["sMainSub"].ToString();
            string msg1 = _value.ToString();
            oCN.BeginTran();
            //保存主表
            objJsonResult = AddBillMain(msg1);
            if (objJsonResult.code == "0")
            {
                oCN.RollBack();
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = objJsonResult.Message;
                objJsonResult.data = null;
                return objJsonResult;
            }
            oCN.Commit();
            objJsonResult.code = "1";
            objJsonResult.count = 1;
            objJsonResult.Message = "单据保存成功!";
            objJsonResult.data = null;
            return objJsonResult;
        }
 
        public json AddBillMain(string msg1)
        {
            string[] sArray = msg1.Split(new string[] { "&和" }, StringSplitOptions.RemoveEmptyEntries);
            string msg2 = sArray[0].ToString();
            string user = sArray[1].ToString();
 
            try
            {
                Stopwatch sw = new Stopwatch();//计时器
                sw.Start();//开始计时
 
                if (!DBUtility.ClsPub.Security_Log("Sc_WorkBillSortBill_Edit", 1, false, user))
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "无保存权限!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                LogService.CustomWriteLog("1:"+msg2, DateTime.Now.ToString("yyyy-MM-dd"));
                //JSON序列化转换字典集合
                List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                List<object> jb = JsonConvert.DeserializeObject<List<object>>(msg2);
                foreach (JObject item in jb)
                {
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    foreach (var itm in item.Properties())
                    {
                        dic.Add(itm.Name, itm.Value.ToString());
                    }
                    list.Add(dic);
                }
 
                LogService.CustomWriteLog("2:", DateTime.Now.ToString("yyyy-MM-dd"));
                int TrueCount = 0, SumCount = 0;
                LogService.CustomWriteLog("list.Count:"+ list.Count, DateTime.Now.ToString("yyyy-MM-dd"));
 
                string sReturn = "";
                oSystemParameter.ShowBill(ref sReturn);
                for (int i = 0; i < list.Count; i++)
                {                                     
                    TrueCount = 0;
                    SumCount = 0;
                    long HInterID = 0;
                    var HBillNo = "";
                    if (list[i]["单据号"].ToString() == "" && list[i]["hmainid"].ToString() == "")
                    {
                        LogService.CustomWriteLog("2.01:" + i, DateTime.Now.ToString("yyyy-MM-dd"));
                        var HICMOBillNo = list[i]["生产订单号"].ToString();
                        var HOrderType = list[i]["订单类型"].ToString();
                        var HICMOEntrySEQ = list[i]["生产订单明细行号"].ToString();
                        var HWorkShopID = list[i]["HWorkShopID"].ToString();
                        var HSourceID = list[i]["HSourceID"].ToString();
                        var HYX = list[i]["优先级"].ToString();
                        var HProdORGID = list[i]["HProdORGID"].ToString();
                        var HMaterID = list[i]["HMaterID"].ToString();
                        var HMaterName = list[i]["物料名称"].ToString();
                        var HMaterModel = list[i]["规格型号"].ToString().Replace("'", "''");
                        var HUnitID = list[i]["HUnitID"].ToString();
                        var HSeOrderBillQty = list[i]["销售订单数量"].ToString();
                        //var HOrderNeedQty = list[i]["订单需求数量"].ToString();
                        var HSplitQty = list[i]["拆单数量"].ToString();
                        var HDayPlanSumQty = list[i]["日计划数量总量"].ToString();
                        var HPlanBeginDate = list[i]["计划开始日期"].ToString();
                        var HPlanEndDate = list[i]["计划结束日期"].ToString();
                        var HSeOrderBillNo = list[i]["销售订单号"].ToString();
                        var HICMOBillType = list[i]["生产订单单据类型"].ToString();
                        var HSourceStockInQty = list[i]["产线入库数量"].ToString();
                        var HLeftPlanQty = list[i]["未排数量"].ToString();
                        var HOrderLev = list[i]["订单等级"].ToString();
                        var HMainSourceInterID = list[i]["源单主内码"].ToString();
                        var HMainSourceEntryID = list[i]["源单子内码"].ToString();
                        var HPlanQty = list[i]["计划数量"].ToString();
                        var HEmpID = list[i]["HEmpID"].ToString();
                        var HWorkQty = list[i]["小时产能"].ToString();
                        var HSourceName = list[i]["生产资源"].ToString();
                        var HWorkQty_ProdLine = list[i]["产线总产能"].ToString();
 
                        LogService.CustomWriteLog("2.05:" + i, DateTime.Now.ToString("yyyy-MM-dd"));
 
                        if (oSystemParameter.omodel.WMS_CampanyName != "添康科技") //系统参数  客户定制化名称     空白为通用
                        {
                            if (HSourceID == "" || HSourceID == "0")
                            {
                                objJsonResult.code = "0";
                                objJsonResult.count = 0;
                                objJsonResult.Message = $"第{i + 1}行生产资源不能为空!";
                                objJsonResult.data = null;
                                return objJsonResult;
                            }
                        }
                        ds = oCN.RunProcReturn($"select HInterID,HICMOBillNo from Sc_WorkBillSortBillMain with(nolock) where HMainSourceInterID={HMainSourceInterID}" +
                            $" and HMainSourceEntryID={HMainSourceEntryID} and HICMOBillNo='{HICMOBillNo}' and HICMOEntrySEQ={HICMOEntrySEQ} and HSourceID={HSourceID}", "Sc_WorkBillSortBillMain");
 
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            objJsonResult.code = "0";
                            objJsonResult.count = 0;
                            objJsonResult.Message = $"第{i + 1}行生产资源有重复,请修改!";
                            objJsonResult.data = null;
                            return objJsonResult;
                        }
 
                        //新增单据号 id
                        HBillNo = DBUtility.ClsPub.CreateBillCode_Prod(BillType, ref DBUtility.ClsPub.sExeReturnInfo, true);//获得一个新的单据号
                        HInterID = DBUtility.ClsPub.CreateBillID_Prod(BillType, ref DBUtility.ClsPub.sExeReturnInfo);//获得一个新的id
 
                        string sql = $"insert into Sc_WorkBillSortBillMain(HInterID,HBillNo,HYear,HPeriod,HBillType," +
                            "HBillSubType,HDate,HBillStatus,HMaker,HMakeDate,HICMOBillNo,HOrderType," +
                            "HICMOEntrySEQ,HWorkShopID,HSourceID, HYX, HProdORGID," +
                            " HMaterID, HMaterName, HMaterModel, HUnitID, HSeOrderBillQty," +
                            " HOrderNeedQty, HSplitQty, HDayPlanSumQty,HPlanBeginDate," +
                            "HSeOrderBillNo,HICMOBillType,HSourceStockInQty,HLeftPlanQty,HOrderLev,HPreparatDate," +
                            "HMainSourceInterID,HMainSourceEntryID,HICMOInterID_Sec,HICMOEntryID_Sec,HPlanQty" +
                            ",HICMOInterID,HICMOEntryID,HPlanEndDate,HEmpID,HWorkQty,HSourceName,HWorkQty_ProdLine)values" +
                            $"({HInterID},'{HBillNo}',{DateTime.Now.Year},{DateTime.Now.Month},'{BillType}'," +
                            $"'{BillType}',GETDATE(),1,'{user}',getdate(),'{HICMOBillNo}','{HOrderType}'," +
                            $"{(HICMOEntrySEQ == "" ? 0.ToString() : HICMOEntrySEQ)},{(HWorkShopID == "" ? 0.ToString() : HWorkShopID)},{(HSourceID == "" ? 0.ToString() : HSourceID)}, {(HYX == "" ? 0.ToString() : HYX)}, {(HProdORGID == "" ? 0.ToString() : HProdORGID)}," +
                            $" {(HMaterID == "" ? 0.ToString() : HMaterID)}, '{HMaterName}', '{HMaterModel}', {(HUnitID == "" ? 0.ToString() : HUnitID)}, {(HSeOrderBillQty == "" ? 0.ToString() : HSeOrderBillQty)}," +
                            $" 0, {(HSplitQty == "" ? 0.ToString() : HSplitQty)}, {(HDayPlanSumQty == "" ? 0.ToString() : HDayPlanSumQty)},'{HPlanBeginDate}'," +
                            $"'{HSeOrderBillNo}','{HICMOBillType}',{(HSourceStockInQty == "" ? 0.ToString() : HSourceStockInQty)},{(HLeftPlanQty == "" ? 0.ToString() : HLeftPlanQty)},'{HOrderLev}',getdate()," +
                            $"{HMainSourceInterID},{HMainSourceEntryID},{HMainSourceInterID},{HMainSourceEntryID},{HPlanQty}," +
                            $"{HMainSourceInterID},{HMainSourceEntryID},'{HPlanEndDate}','{HEmpID}','{HWorkQty}','{HSourceName}','{HWorkQty_ProdLine}')";
 
                        //LogService.Write("sql:" + sql);
                        //主表
                        oCN.RunProc(sql);
                    }
                    else
                    {
                        LogService.CustomWriteLog("2.0:" + i, DateTime.Now.ToString("yyyy-MM-dd"));
                        HBillNo = list[i]["单据号"].ToString();
                        HInterID = int.Parse(list[i]["hmainid"].ToString());
                        var HMainSourceInterID = list[i]["源单主内码"].ToString();
                        var HMainSourceEntryID = list[i]["源单子内码"].ToString();
                        var HICMOBillNo = list[i]["生产订单号"].ToString();
                        var HICMOEntrySEQ = list[i]["生产订单明细行号"].ToString();
                        var HSourceID = list[i]["HSourceID"].ToString();
                        var HYX = list[i]["优先级"].ToString();
                        var HWorkQty = list[i]["小时产能"].ToString();
                        var HProdTimes = list[i]["生产周期"].ToString();
                        var HReadyTimes = list[i]["开工余量"].ToString();
                        var HLastBeginDate = list[i]["最迟开工日期"].ToString();
                        var HLastEndDate = list[i]["最迟完工日期"].ToString();
                        var HOrderNeedQty = list[i]["订单需求数量"].ToString();
                        var HOrderCommitDate = list[i]["订单交货期"].ToString();
                        var HPlanEndDate = list[i]["计划结束日期"].ToString();
                        var HSplitQty = list[i]["拆单数量"].ToString();
                        var HSourceName = list[i]["生产资源"].ToString();
                        var HWorkQty_ProdLine = list[i]["产线总产能"].ToString();
 
                        var HOrderType = list[i]["订单类型"].ToString();
                        var HWorkShopID = list[i]["HWorkShopID"].ToString();
                        var HProdORGID = list[i]["HProdORGID"].ToString();
                        var HMaterID = list[i]["HMaterID"].ToString();
                        var HMaterName = list[i]["物料名称"].ToString();
                        var HMaterModel = list[i]["规格型号"].ToString().Replace("'", "''");
                        var HUnitID = list[i]["HUnitID"].ToString();
                        var HSeOrderBillQty = list[i]["销售订单数量"].ToString();
                        var HDayPlanSumQty = list[i]["日计划数量总量"].ToString();
                        var HPlanBeginDate = list[i]["计划开始日期"].ToString();
                        var HSeOrderBillNo = list[i]["销售订单号"].ToString();
                        var HICMOBillType = list[i]["生产订单单据类型"].ToString();
                        var HSourceStockInQty = list[i]["产线入库数量"].ToString();
                        var HLeftPlanQty = list[i]["未排数量"].ToString();
                        var HOrderLev = list[i]["订单等级"].ToString();
                        var HPlanQty = list[i]["计划数量"].ToString();
                        var HEmpID = list[i]["HEmpID"].ToString();
 
                        LogService.CustomWriteLog("2.1:"+i, DateTime.Now.ToString("yyyy-MM-dd"));
                        
                        if (oSystemParameter.omodel.WMS_CampanyName != "添康科技") //系统参数  客户定制化名称     空白为通用
                        {
                            if (HSourceID == "" || HSourceID == "0")
                            {
                                objJsonResult.code = "0";
                                objJsonResult.count = 0;
                                objJsonResult.Message = $"第{i + 1}行生产资源不能为空!";
                                objJsonResult.data = null;
                                return objJsonResult;
                            }
                        }
 
                        var str = 0;
                        if (!int.TryParse(HYX, out str))
                        {
                            objJsonResult.code = "0";
                            objJsonResult.count = 0;
                            objJsonResult.Message = $"第{i + 1}行优先级:{HYX},请输入数字!";
                            objJsonResult.data = null;
                            return objJsonResult;
                        }
 
                        if (oSystemParameter.omodel.WMS_CampanyName == "添康科技") //系统参数  客户定制化名称     空白为通用
                        {
                            //看有几台生产资源协同生产
                            string[] HSourceNameArr = HSourceName.Split(new char[]{'&'});
 
                            if (HSourceNameArr.Length >= 2)
                            {
                                for (int s = 0; s < HSourceNameArr.Length; s++)
                                {
                                    if (s == 0)
                                    {
                                        ds = oCN.RunProcReturn("select HItemID from Gy_Source with(nolock) where HName = '" + HSourceNameArr[s] + "'", "Gy_Source");
 
                                        var HSourceID_Child = ds.Tables[0].Rows[0]["HItemID"];
 
                                        oCN.RunProc($"update Sc_WorkBillSortBillMain set HSourceID={(HSourceID_Child == "" ? 0.ToString() : HSourceID_Child)}" +
                                            $",HYX={HYX},HWorkQty={HWorkQty},HProdTimes={HProdTimes},HReadyTimes={HReadyTimes},HLastBeginDate='{HLastBeginDate}'" +
                                            $",HLastEndDate='{HLastEndDate}',HOrderNeedQty={HOrderNeedQty},HOrderCommitDate='{HOrderCommitDate}'" +
                                            $",HPlanEndDate='{HPlanEndDate}',HSplitQty={HSplitQty},HSourceName='{HSourceName}',HWorkQty_ProdLine={HWorkQty_ProdLine}" +
                                            $" where HInterID={list[i]["hmainid"].ToString()} and HBillNo='{list[i]["单据号"].ToString()}'");
                                    }
                                    else
                                    {
                                        ds = oCN.RunProcReturn("select HItemID from Gy_Source with(nolock) where HName = '" + HSourceNameArr[s] + "'", "Gy_Source");
 
                                        var HSourceID_Child = ds.Tables[0].Rows[0]["HItemID"];
 
                                        //新增协同生产资源的排产记录
                                        ds = oCN.RunProcReturn($"select HInterID,HICMOBillNo from Sc_WorkBillSortBillMain with(nolock) where HMainSourceInterID={HMainSourceInterID}" +
                           $" and HMainSourceEntryID={HMainSourceEntryID} and HICMOBillNo='{HICMOBillNo}' and HICMOEntrySEQ={HICMOEntrySEQ} and HSourceID={HSourceID_Child}", "Sc_WorkBillSortBillMain");
 
                                        if (ds.Tables[0].Rows.Count > 0)
                                        {
                                            objJsonResult.code = "0";
                                            objJsonResult.count = 0;
                                            objJsonResult.Message = $"第{i + 1}行生产资源有重复,请修改!";
                                            objJsonResult.data = null;
                                            return objJsonResult;
                                        }
 
                                        //新增单据号 id
                                        var HBillNo_New = DBUtility.ClsPub.CreateBillCode_Prod(BillType, ref DBUtility.ClsPub.sExeReturnInfo, true);//获得一个新的单据号
                                        var HInterID_New = DBUtility.ClsPub.CreateBillID_Prod(BillType, ref DBUtility.ClsPub.sExeReturnInfo);//获得一个新的id
 
                                        string sql = $"insert into Sc_WorkBillSortBillMain(HInterID,HBillNo,HYear,HPeriod,HBillType," +
                                            "HBillSubType,HDate,HBillStatus,HMaker,HMakeDate,HICMOBillNo,HOrderType," +
                                            "HICMOEntrySEQ,HWorkShopID,HSourceID, HYX, HProdORGID," +
                                            " HMaterID, HMaterName, HMaterModel, HUnitID, HSeOrderBillQty," +
                                            " HOrderNeedQty, HSplitQty, HDayPlanSumQty,HPlanBeginDate," +
                                            "HSeOrderBillNo,HICMOBillType,HSourceStockInQty,HLeftPlanQty,HOrderLev,HPreparatDate," +
                                            "HMainSourceInterID,HMainSourceEntryID,HICMOInterID_Sec,HICMOEntryID_Sec,HPlanQty" +
                                            ",HICMOInterID,HICMOEntryID,HPlanEndDate,HEmpID,HWorkQty,HSourceName,HWorkQty_ProdLine,HRemark)values" +
                                            $"({HInterID_New},'{HBillNo_New}',{DateTime.Now.Year},{DateTime.Now.Month},'{BillType}'," +
                                            $"'{BillType}',GETDATE(),1,'{user}',getdate(),'{HICMOBillNo}','{HOrderType}'," +
                                            $"{(HICMOEntrySEQ == "" ? 0.ToString() : HICMOEntrySEQ)},{(HWorkShopID == "" ? 0.ToString() : HWorkShopID)},{(HSourceID_Child == "" ? 0.ToString() : HSourceID_Child)}, {(HYX == "" ? 0.ToString() : HYX)}, {(HProdORGID == "" ? 0.ToString() : HProdORGID)}," +
                                            $" {(HMaterID == "" ? 0.ToString() : HMaterID)}, '{HMaterName}', '{HMaterModel}', {(HUnitID == "" ? 0.ToString() : HUnitID)}, {(HSeOrderBillQty == "" ? 0.ToString() : HSeOrderBillQty)}," +
                                            $" 0, {(HSplitQty == "" ? 0.ToString() : HSplitQty)}, {(HDayPlanSumQty == "" ? 0.ToString() : HDayPlanSumQty)},'{HPlanBeginDate}'," +
                                            $"'{HSeOrderBillNo}','{HICMOBillType}',{(HSourceStockInQty == "" ? 0.ToString() : HSourceStockInQty)},{(HLeftPlanQty == "" ? 0.ToString() : HLeftPlanQty)},'{HOrderLev}',getdate()," +
                                            $"{HMainSourceInterID},{HMainSourceEntryID},{HMainSourceInterID},{HMainSourceEntryID},{HPlanQty}," +
                                            $"{HMainSourceInterID},{HMainSourceEntryID},'{HPlanEndDate}','{HEmpID}','{HWorkQty}','{HSourceName}','{HWorkQty_ProdLine}','{"协同生产"}')";
 
                                        //LogService.Write("sql:" + sql);
                                        //主表
                                        oCN.RunProc(sql);
 
                                        //插入子表数据
                                        for (int j = 0; j < 180; j++)
                                        {                                           
                                            //主表有数据 子表无数据
                                            //if (j == 180 - 1 && SumCount == 0 && HInterID_New != 0 && HBillNo_New != "")
                                            //{
                                            //    objJsonResult = AddBillSub(HInterID_New.ToString(), HBillNo_New, DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd").ToString()), 0, list[i]);
                                            //}
 
 
                                            if (list[i][DateTime.Now.AddDays(j).ToString("yyyy-MM-dd")].ToString() != "")
                                            {
                                                ////保存子表
                                                objJsonResult = AddBillSub(HInterID_New == 0 ? list[i]["hmainid"].ToString() : HInterID_New.ToString()
                                                    , HBillNo_New == "" ? list[i]["单据号"].ToString() : HBillNo_New
                                                     , DateTime.Parse(DateTime.Now.AddDays(j).ToString("yyyy-MM-dd").ToString())
                                                     , 0
                                                     , list[i]);
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                ds = oCN.RunProcReturn($"select HInterID,HICMOBillNo from Sc_WorkBillSortBillMain with(nolock) where HMainSourceInterID={HMainSourceInterID}" +
                             $" and HMainSourceEntryID={HMainSourceEntryID} and HICMOBillNo='{HICMOBillNo}' and HICMOEntrySEQ={HICMOEntrySEQ} and HSourceID={HSourceID}", "Sc_WorkBillSortBillMain");
 
                                if (ds.Tables[0].Rows.Count > 1)
                                {
                                    LogService.CustomWriteLog("第" + i + 1 + "行生产资源有重复,请修改", DateTime.Now.ToString("yyyy-MM-dd"));
                                    LogService.CustomWriteLog($"select * from  Sc_WorkBillSortBillMain where HMainSourceInterID={HMainSourceInterID}" +
                                      $" and HMainSourceEntryID={HMainSourceEntryID} and HICMOBillNo='{HICMOBillNo}' and HICMOEntrySEQ={HICMOEntrySEQ} and HSourceID={HSourceID}", DateTime.Now.ToString("yyyy-MM-dd"));
                                    objJsonResult.code = "0";
                                    objJsonResult.count = 0;
                                    objJsonResult.Message = $"第{i + 1}行生产资源有重复,请修改!";
                                    objJsonResult.data = null;
                                    return objJsonResult;
                                }
                                LogService.CustomWriteLog("2.2:" + i, DateTime.Now.ToString("yyyy-MM-dd"));
 
                                oCN.RunProc($"update Sc_WorkBillSortBillMain set HSourceID={(HSourceID == "" ? 0.ToString() : HSourceID)},HYX={HYX}" +
                                    $",HWorkQty={HWorkQty},HProdTimes={HProdTimes},HReadyTimes={HReadyTimes},HLastBeginDate='{HLastBeginDate}'" +
                                    $",HLastEndDate='{HLastEndDate}',HOrderNeedQty={HOrderNeedQty},HOrderCommitDate='{HOrderCommitDate}',HPlanEndDate='{HPlanEndDate}',HSplitQty={HSplitQty},HSourceName='{HSourceName}',HWorkQty_ProdLine={HWorkQty_ProdLine}" +
                                    $" where HInterID={list[i]["hmainid"].ToString()} and HBillNo='{list[i]["单据号"].ToString()}'");
                            }
                        }
                        else
                        {
                            ds = oCN.RunProcReturn($"select HInterID,HICMOBillNo from Sc_WorkBillSortBillMain with(nolock) where HMainSourceInterID={HMainSourceInterID}" +
                             $" and HMainSourceEntryID={HMainSourceEntryID} and HICMOBillNo='{HICMOBillNo}' and HICMOEntrySEQ={HICMOEntrySEQ} and HSourceID={HSourceID}", "Sc_WorkBillSortBillMain");
 
                            if (ds.Tables[0].Rows.Count > 1)
                            {
                                LogService.CustomWriteLog("第" + i + 1 + "行生产资源有重复,请修改", DateTime.Now.ToString("yyyy-MM-dd"));
                                LogService.CustomWriteLog($"select * from  Sc_WorkBillSortBillMain where HMainSourceInterID={HMainSourceInterID}" +
                                  $" and HMainSourceEntryID={HMainSourceEntryID} and HICMOBillNo='{HICMOBillNo}' and HICMOEntrySEQ={HICMOEntrySEQ} and HSourceID={HSourceID}", DateTime.Now.ToString("yyyy-MM-dd"));
                                objJsonResult.code = "0";
                                objJsonResult.count = 0;
                                objJsonResult.Message = $"第{i + 1}行生产资源有重复,请修改!";
                                objJsonResult.data = null;
                                return objJsonResult;
                            }
                            LogService.CustomWriteLog("2.2:" + i, DateTime.Now.ToString("yyyy-MM-dd"));
 
                            oCN.RunProc($"update Sc_WorkBillSortBillMain set HSourceID={(HSourceID == "" ? 0.ToString() : HSourceID)},HYX={HYX}" +
                                $",HWorkQty={HWorkQty},HProdTimes={HProdTimes},HReadyTimes={HReadyTimes},HLastBeginDate='{HLastBeginDate}'" +
                                $",HLastEndDate='{HLastEndDate}',HOrderNeedQty={HOrderNeedQty},HOrderCommitDate='{HOrderCommitDate}',HPlanEndDate='{HPlanEndDate}',HSplitQty={HSplitQty},HSourceName='{HSourceName}',HWorkQty_ProdLine={HWorkQty_ProdLine}" +
                                $" where HInterID={list[i]["hmainid"].ToString()} and HBillNo='{list[i]["单据号"].ToString()}'");
                        }                       
                    }
 
                    oCN.RunProc($"update Sc_WorkBillSortBillMain set HDayPlanSumQty={list[i]["日计划数量总量"].ToString()} where HInterID={(HInterID==0?int.Parse(list[i]["hmainid"].ToString()):HInterID)} and HBillNo='{(HBillNo==""?list[i]["单据号"].ToString(): HBillNo)}'");
 
                    int SumDay = 0; //动态两月之差 DateTime.Now.AddMonths(1).AddDays(-1).Subtract(DateTime.Now).Days;
 
                    // 统计总天数
                    HashSet<DateTime> uniqueDates = new HashSet<DateTime>();
 
                    foreach (var key in list[i].Keys)
                    {
                        if (DateTime.TryParseExact(key, "yyyy-M-d", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date))
                        {
                            uniqueDates.Add(date);
                        }
                    }
 
                    SumDay = uniqueDates.Count;
 
                    if (oSystemParameter.omodel.WMS_CampanyName == "添康科技") //系统参数  客户定制化名称     空白为通用
                    {
                        SumDay = 180;
                    }            
 
                    LogService.CustomWriteLog("2.3:" + i, DateTime.Now.ToString("yyyy-MM-dd"));
                    for (int j = 0; j < SumDay; j++)
                    {
                        //主表子表都有数据
                        if (list[i][DateTime.Now.AddDays(j).ToString("yyyy-MM-dd")].ToString() != "")
                        {
                            SumCount += 1;
                            ////保存子表
                            objJsonResult = AddBillSub(HInterID == 0 ? list[i]["hmainid"].ToString() : HInterID.ToString()
                                , HBillNo == "" ? list[i]["单据号"].ToString() : HBillNo
                                 , DateTime.Parse(DateTime.Now.AddDays(j).ToString("yyyy-MM-dd").ToString())
                                 , Math.Round(double.Parse(list[i][DateTime.Now.AddDays(j).ToString("yyyy-MM-dd")].ToString()),1)
                                 , list[i]);
                            if (objJsonResult.count == 1)
                            {
                                TrueCount += 1;
                            }
                        }
                        //主表有数据 子表无数据
                        if (j == SumDay-1 && SumCount == 0 && HInterID != 0 && HBillNo != "")
                        {
                            //LogService.CustomWriteLog("3:"+ HInterID+","+ HBillNo, DateTime.Now.ToString("yyyy-MM-dd"));
                            objJsonResult = AddBillSub(HInterID.ToString(), HBillNo, DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd").ToString()), 0, list[i]);
                        }
                    }
 
                    LogService.CustomWriteLog("2.4:" + i, DateTime.Now.ToString("yyyy-MM-dd"));
 
                    if (TrueCount != SumCount)
                    {
                        objJsonResult.code = "0";
                        objJsonResult.count = 0;
                        objJsonResult.Message = objJsonResult.Message;
                        objJsonResult.data = null;
                        return objJsonResult;
                    }
 
                   
                }
 
                LogService.CustomWriteLog("2.5:", DateTime.Now.ToString("yyyy-MM-dd"));
 
                //同步日计划工单
                oCN.RunProc("exec REALESE_SC_ICMOBILLSTATUS_TMP");
 
                LogService.CustomWriteLog("2.6:", DateTime.Now.ToString("yyyy-MM-dd"));
                sw.Stop();//结束计时
                LogService.Write($"========================1.排产订单总用时:" + sw.Elapsed);
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = null;
                objJsonResult.data = null;
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
 
        public json AddBillSub(string HInterID, string HBillNo, DateTime date, double HQTY, Dictionary<string, string> dic)
        {
            string sReturn = "";
            oSystemParameter.ShowBill(ref sReturn);
 
            //获取表格数据
            ds = oCN.RunProcReturn($"select * from  h_v_JIT_Sc_WorkBillSortBill_PC where 单据号='{HBillNo}'", "h_v_JIT_Sc_WorkBillSortBill_PC");
            int count = 0;
            if (ds.Tables[0].Rows.Count > 0)
            {
                if (oSystemParameter.omodel.WMS_CampanyName == "添康科技") //系统参数  客户定制化名称     空白为通用
                {
                    //判断子表是否有当日的日期以及日期所对应的数量
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        if (DateTime.Parse(ds.Tables[0].Rows[i]["日计划生产日期"].ToString()) == date)
                        {
                            oCN.RunProc($"update Sc_WorkBillSortBillSub set HMasterDate='{date}',HQty={HQTY},HUseTimes={(dic["产线总产能"] == "0" ? 0 : HQTY / float.Parse(dic["产线总产能"].ToString()))}" +
                                $"  where HInterID={HInterID} and HEntryID={ds.Tables[0].Rows[i]["hsubid"].ToString()}");
                            count += 1;
                        }
                    }
                }
                else
                {
                    //判断子表是否有当日的日期以及日期所对应的数量
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        if (DateTime.Parse(ds.Tables[0].Rows[i]["日计划生产日期"].ToString()) == date)
                        {
                            oCN.RunProc($"update Sc_WorkBillSortBillSub set HMasterDate='{date}',HQty={HQTY},HUseTimes={(dic["小时产能"] == "0" ? 0 : HQTY / float.Parse(dic["小时产能"].ToString()))}" +
                                $"  where HInterID={HInterID} and HEntryID={ds.Tables[0].Rows[i]["hsubid"].ToString()}");
                            count += 1;
                        }
                    }
                }               
            }
           
            if (count != 1)
            {
                if (oSystemParameter.omodel.WMS_CampanyName == "添康科技") //系统参数  客户定制化名称     空白为通用
                {
                    //插入子表
                    oCN.RunProc("insert into Sc_WorkBillSortBillSub(HInterID,HSEQ," +
                        "HMasterDate,HQty,HUseTimes)" +
                                $"values({HInterID}, {(ds.Tables[0].Rows.Count + 1)}," +
                                $" '{date}', {HQTY},{ ((dic["产线总产能"] == "0.0000" ? 0 : dic["产线总产能"] == "0" ? 0 : HQTY / float.Parse(dic["产线总产能"].ToString())).ToString() == "非数字" ? 0 : dic["产线总产能"] == "0.0000" ? 0 : dic["产线总产能"] == "0" ? 0 : HQTY / float.Parse(dic["产线总产能"].ToString())) })");
                }
                else
                {
                    //插入子表
                    oCN.RunProc("insert into Sc_WorkBillSortBillSub(HInterID,HSEQ," +
                        "HMasterDate,HQty,HUseTimes)" +
                                $"values({HInterID}, {(ds.Tables[0].Rows.Count + 1)}," +
                                $" '{date}', {HQTY},{ ((dic["小时产能"] == "0.0000" ? 0 : dic["小时产能"] == "0" ? 0 : HQTY / float.Parse(dic["小时产能"].ToString())).ToString() == "非数字" ? 0 : dic["小时产能"] == "0.0000" ? 0 : dic["小时产能"] == "0" ? 0 : HQTY / float.Parse(dic["小时产能"].ToString())) })");
                }                         
            }
 
            
            if (oSystemParameter.omodel.WMS_CampanyName == "添康科技") //系统参数  客户定制化名称     空白为通用
            {
                //把排产订单完工日期反写到金蝶销售订单上
                string sql = "exec h_p_JIT_UpdateEndDateToERP " + HInterID + ",'" + HBillNo + "'";
                oCN.RunProc(sql);
            }
 
            objJsonResult.code = "1";
            objJsonResult.count = 1;
            objJsonResult.Message = null;
            objJsonResult.data = null;
            return objJsonResult;
        }
        #endregion
 
        #region 生产日计划平台 齐套分析
 
        #region 清单配料方式
        public class PRD_PPBOM
        {
            /// <summary>
            /// 日计划工单号
            /// </summary>
            public string HMainICMOBillNo { get; set; }
            /// <summary>
            /// 日计划工单FID
            /// </summary>
            public long HInterID { get; set; }
            /// <summary>
            /// 日计划明细FEntryID
            /// </summary>
            public long HEntryID { get; set; }
            /// <summary>
            /// 生产用料清单单号
            /// </summary>
            public string HBillNo { get; set; }
            /// <summary>
            /// 生产订单单号
            /// </summary>
            public string HICMOBillNo { get; set; }
            /// <summary>
            /// 生产订单内码
            /// </summary>
            public string HICMOInterID { get; set; }
            /// <summary>
            /// 父级物料ID
            /// </summary>
            public string FMaterialID { get; set; }
            /// <summary>
            /// 父级物料数量
            /// </summary>
            public decimal FQty { get; set; }
            /// <summary>
            /// 子项物料ID
            /// </summary>
            public string FMATERIALID2 { get; set; }
            /// <summary>
            /// 子项物料名称
            /// </summary>
            public string FNumber { get; set; }
            /// <summary>
            /// 需求数量
            /// </summary>
            public decimal FNeedQty { get; set; }
            /// <summary>
            /// 即时库存
            /// </summary>
            public decimal FBASEQTY { get; set; }
 
            /// <summary>
            /// 生产订单主码
            /// </summary>
            public string HICMOInterID_Sec { get; set; }
            /// <summary>
            /// 生产订单子码
            /// </summary>
            public string HICMOEntryID_Sec { get; set; }
 
            /// <summary>
            /// 日计划数量
            /// </summary>
            public string HQty { get; set; }
 
            /// <summary>
            /// 日计划日期
            /// </summary>
            public DateTime HMasterDate { get; set; }
 
            /// <summary>
            /// 订单等级
            /// </summary>
            public string HOrderLev { get; set; }
 
            /// <summary>
            /// 库存组织
            /// </summary>
            public string FStockOrgId { get; set; }
            /// <summary>
            /// 组织名称
            /// </summary>
            public string OrgFnumber { get; set; }
 
            /// <summary>
            /// 单位用量
            /// </summary>
            public decimal dwyl { get; set; }
 
            /// <summary>
            /// 预计消耗用量
            /// </summary>
            public decimal PlanCount { get; set; }
            /// <summary>
            /// 物料属性
            /// </summary>
            public int FErpClsID { get; set; }
 
            /// <summary>
            /// 车间
            /// </summary>
            public string HWorkShopID { get; set; }
 
            /// <summary>
            /// 车间编码
            /// </summary>
            public string FHWorkShopNumber { get; set; }
 
 
        }
        #endregion
 
        #region 即时库存
        public class PRD_Inventory
        {
            /// <summary>
            /// 物料ID
            /// </summary>
            public string FMATERIALID { get; set; }
            /// <summary>
            /// 物料编码
            /// </summary>
            public string FNumber { get; set; }
            /// <summary>
            /// 即时库存
            /// </summary>
            public decimal FBASEQTY { get; set; }
 
            /// <summary>
            /// 库存组织
            /// </summary>
            public string FStockOrgId { get; set; }
 
            /// <summary>
            /// 库存货主类型
            /// </summary>
            public string FOwnerTypeId { get; set; }
            /// <summary>
            /// 库存货主
            /// </summary>
            public string FOwnerId { get; set; }
 
            /// <summary>
            /// 货主编码
            /// </summary>
            public string FOwnerNumber { get; set; }
 
            /// <summary>
            /// 仓库
            /// </summary>
            public string FSTOCKID { get; set; }
 
            /// <summary>
            /// 仓库编码
            /// </summary>
            public string FStockNumber { get; set; }
            /// <summary>
            /// 批号
            /// </summary>
            public string HLOT { get; set; }
            /// <summary>
            /// id
            /// </summary>
            public string HInventoryFID { get; set; }
        }
        #endregion
 
        #region 车间仓库对照列表
        public class PRD_WorkHouseCompar
        {
            /// <summary>
            /// 组织
            /// </summary>
            public string FORGID { get; set; }
            /// <summary>
            /// 车间
            /// </summary>
            public string FWORKSHOPID { get; set; }
            /// <summary>
            /// 仓库
            /// </summary>
            public string FSTOCKID { get; set; }
        }
        #endregion
 
        #region 日计划+生产订单
        public class DayPlanPickedModel
        {
            /// <summary>
            /// 订单入库数量 按照生产订单明细行
            /// </summary>
            public decimal FCXStockInQty { get; set; }
            /// <summary>
            ///  主生产订单子内码  
            /// </summary>
            public string FPRDMOENTYID { get; set; }
            /// <summary>
            ///  物料单位用量
            /// </summary>
            public decimal dwyl { get; set; }
            /// <summary>
            ///  已领数量
            /// </summary>
            public decimal FPickedQty { get; set; }
            /// <summary>
            /// 剩余可用数量
            /// </summary>
            public decimal FRemainPickedQty { get; set; }
            /// <summary>
            ///  物料  
            /// </summary>
            public string FMATERIALID { get; set; }
 
        }
        #endregion
 
        #region 存储临时需要插入数据
        public class CompleteAnalysisTempModel
        {
            /// <summary>
            /// 主生产订单主内码:FHMainICMOInterIDr 
            /// </summary>
            public string FHMainICMOInterIDr { get; set; }
            /// <summary>
            ///  主生产订单子内码:FHMainICMOEntryID  
            /// </summary>
            public string FHMainICMOEntryID { get; set; }
            /// <summary>
            ///  日计划订单单号:HMainICMOBillNo 
            /// </summary>
            public string HMainICMOBillNo { get; set; }
            /// <summary>
            ///  日计划订单主内码:FHICMOInterID 
            /// </summary>
            public string FHICMOInterID { get; set; }
            /// <summary>
            ///  日计划订单子内码:FHICMOEntryID  
            /// </summary>
            public string FHICMOEntryID { get; set; }
            /// <summary>
            ///  子件物料:FHMaterID  
            /// </summary>
            public string FHMaterID { get; set; }
 
            /// <summary>
            ///  库存组织:FHStockOrgID
            /// </summary>
            public string FHStockOrgID { get; set; }
 
            /// <summary>
            ///生产组织:FHPRDORGID 
            /// </summary>
            public string FHPRDORGID { get; set; }
 
            /// <summary>
            /// 生产订单号:FPRDBillNo 
            /// </summary>
            public string FPRDBillNo { get; set; }
            /// <summary>
            /// 标识
            /// </summary>
            public string FIdentificat { get; set; }
            /// <summary>
            ///  货主名称:FOwnerName 
            /// </summary>
            public string FOwnerName { get; set; }
            /// <summary>
            ///  货主编码:FOwnerId
            /// </summary>
            public string FOwnerId { get; set; }
            /// <summary>
            /// 货主类型:FOwnerTypeId        
            /// </summary>
            public string FOwnerTypeId { get; set; }
            /// <summary>
            /// 齐套状态
            /// </summary>
            public string FComPlete { get; set; }
            /// <summary>
            ///  数量
            /// </summary>
            public string FHUseQty { get; set; }
            /// <summary>
            ///  及时库存数量:FHStockQty 
            /// </summary>
            public decimal FHStockQty { get; set; }
            /// <summary>
            ///可用数量:FHLeftQty 
            /// </summary>
            public decimal FHLeftQty { get; set; }
 
            /// <summary>
            /// 缺料数量
            /// </summary>
            public decimal FLackCount { get; set; }
            /// <summary>
            /// 占用数量
            /// </summary>
            public decimal FOccupyCount { get; set; }
            /// <summary>
            /// 占用领料数量
            /// </summary>
            public decimal FOccupyPickedCount { get; set; }
 
            /// <summary>
            /// 单位用量:FUnitDosage  
            /// </summary>
            public decimal FUnitDosage { get; set; }
            /// <summary>
            /// 计划总数量:FSumPlanCount 
            /// </summary>
            public decimal FSumPlanCount { get; set; }
            /// <summary>
            /// 齐套数量:FCompleteCount q
            /// </summary>
            public decimal FCompleteCount { get; set; }
            public decimal FCompleteCount1 { get; set; }
            /// <summary>
            /// 日计划日期
            /// </summary>
            public DateTime FPlanDate { get; set; }
            //物料类型
            public int FErpClsID { get; set; }
            //仓库
            public string FStock { get; set; }
            //车间
            public string FWorkShop { get; set; }
            //批号
            public string HLOT { get; set; }
            public string HInventoryFID { get; set; }
 
        }
        #endregion
 
        #region 齐套分析    原调用方法
 
        public object JIT_CompleteSetAnalysis_Old(string sWhere, string user)
        {
            try
            {
                Stopwatch sw = new Stopwatch();
                omdelMian = JsonConvert.DeserializeObject<Sc_WorkBillSortBillMain>(sWhere);
                string sql = $"exec JIT_qtfx {omdelMian.HProdORGID},{omdelMian.HWorkShopID},'{user}' ";
                ds = oCN.RunProcReturn(sql, "JIT_qtfx");
                //LogService.Write("齐套分析sql:" + sql);
                List<PRD_PPBOM> BomList = new List<PRD_PPBOM>();
                DataTable resulTable = ds.Tables[0];
 
                if (ds.Tables[0].Rows.Count < 1 || ds == null)
                {
                    //释放齐套操作 避免多人同时进行齐套分析
                    oCN.RunProc($"update T_PRD_QTFX set FSTATUS = 0 where FPRDORGID ={omdelMian.HProdORGID} and FSTATUS = 1 ");
 
                    objJsonResult.code = "1";
                    objJsonResult.count = 1;
                    objJsonResult.Message = "没有需要进行齐套分析的数据";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                if (resulTable.Rows[0][0].ToString().Contains("失败"))
                {
                    //释放齐套操作 避免多人同时进行齐套分析
                    oCN.RunProc($"update T_PRD_QTFX set FSTATUS = 0 where FPRDORGID ={omdelMian.HProdORGID} and FSTATUS = 1 ");
 
                    objJsonResult.code = "1";
                    objJsonResult.count = 1;
                    objJsonResult.Message = resulTable.Rows[0][0].ToString();
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                else
                {
                    BomList = ds.ToModelList<PRD_PPBOM>();
                }
 
                string fDayPlanFids = string.Empty;
                string fDayPlanFEntryids = string.Empty;
                if (BomList.Count == 0)
                {
                    //释放齐套操作 避免多人同时进行齐套分析
                    oCN.RunProc($"update T_PRD_QTFX set FSTATUS = 0 where FPRDORGID ={omdelMian.HProdORGID} and FSTATUS = 1 ");
 
                    objJsonResult.code = "1";
                    objJsonResult.count = 1;
                    objJsonResult.Message = "没有需要进行齐套分析的数据";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                else
                {
                    List<string> fidList = BomList.Select(x => x.HInterID.ToString()).Distinct().ToList();
                    List<string> fentryidList = BomList.Select(x => x.HEntryID.ToString()).Distinct().ToList();
                    fDayPlanFids = string.Join(",", fidList);
                    fDayPlanFEntryids = string.Join(",", fentryidList);
                }
                //LogService.Write("日计划工单ids" + fDayPlanFids);
 
                sw.Start();//开始计时
 
                //获取当前即时库存 库存数量+库存组织+物料+货主+仓库   
                //原查询即时库存方式:select * from h_v_jit_InventoryList
                ds = oCN.RunProcReturn(@" 
exec h_p_jit_Inventory_UsableList
", "h_p_jit_Inventory_UsableList");
                ListInventory = ds.ToModelList<PRD_Inventory>();
                //车间 仓库对照列表 
                ds = oCN.RunProcReturn(@" 
SELECT DISTINCT T1.HOrgId FORGID,HWorkShopID FWORKSHOPID,HWHID FSTOCKID FROM Gy_WorkWarehouseBillMain T1 
JOIN Gy_WorkWarehouseBillMainSub T2 ON T1.HInterID=T2.HInterID 
", "Gy_WorkWarehouseBillMain");
                List<PRD_WorkHouseCompar> pRD_WorkHouseCompar = ds.ToModelList<PRD_WorkHouseCompar>();
                int i = 1;//用于进度条的加载
                //日计划+生产订单子表编码ID
                var DatePlanList = BomList.GroupBy(p => new { p.HMasterDate, p.HICMOEntryID_Sec }).Select(x => new PRD_PPBOM { HMasterDate = x.Key.HMasterDate, HICMOEntryID_Sec = x.Key.HICMOEntryID_Sec }).ToList();
                //取应发数量 FMustQty 不要取值需求数量FNeedQty 领料数据
                string LLsql = string.Format(@"exec h_p_jit_PPBOMList '{0}'", fDayPlanFids);
                List<DayPlanPickedModel> DayPlanPickedModel = new List<DayPlanPickedModel>();
                //LogService.Write("LLsql:" + LLsql);
                ds = oCN.RunProcReturn(LLsql, "SC_WORKBILLSORTBILLMAIN");
                //LogService.Write(JsonConvert.SerializeObject(ds));
                DayPlanPickedModel = ds.ToModelList<DayPlanPickedModel>();
                //LogService.Write(JsonConvert.SerializeObject(DayPlanPickedModel));
                //CompleteAnalysisTempModel 用于存储临时需要插入数据
                List<CompleteAnalysisTempModel> completeAnalysisTempModel = new List<CompleteAnalysisTempModel>();
                //创建字典 用于储存物料 + 占用数量
                Dictionary<string, decimal> occupyDic = new Dictionary<string, decimal>();
                //LogService.Write($"齐套分析,数据准备阶段,用时" + sw.Elapsed + "总行数:" + BomList.Count);
                //LogService.Write($"齐套分析,数据准备阶段,用时" + sw.Elapsed + "总需要循环的bom数量:" + DatePlanList.Count);
 
                //第一个循环 日计划工单明细 一天+一个工单 一个循环
                int o = 0;
                foreach (var item in DatePlanList)
                {
                    o++;
                    //LogService.Write("循环:" + o);
                    //日计划用料清单明细 每一天的实际用料情况
                    var _BomList = BomList.Where(x => x.HMasterDate == item.HMasterDate && x.HICMOEntryID_Sec == item.HICMOEntryID_Sec).ToList();
                    //每一个物料进行库存计算
                    foreach (var _item in _BomList)
                    {
                        //车间仓库 对照表 每个日计划同属一个车间 A,B
                        var _pRD_WorkHouseCompar = pRD_WorkHouseCompar.Where(c => c.FWORKSHOPID == _item.HWorkShopID).ToList();
                        decimal jskcQty = 0;//用于计算
                        decimal jskcQty2 = 0;//用于计算当时那个计算节点的即时库存
                        //计算当前这几个仓库总的库存量 
                        if (_pRD_WorkHouseCompar.Count > 0)
                        {
                            foreach (var _WorkHouse in _pRD_WorkHouseCompar)
                            {
                                //库存数据匹配
                                List<PRD_Inventory> _ListInventory = ListInventory.Where(c => c.FNumber == _item.FNumber && c.FBASEQTY > 0 && c.FSTOCKID == _WorkHouse.FSTOCKID).ToList();
                                if (_ListInventory.Count > 0)
                                {
                                    foreach (var Inventory in _ListInventory)
                                    {
                                        jskcQty += Inventory.FBASEQTY;
                                    }
                                }
                            }
                        }
                        //找出物料被其它订单占用数量
                        decimal occupyMaterial = 0;
                        if (occupyDic.ContainsKey(_item.HWorkShopID + _item.FMATERIALID2))
                        {
                            occupyMaterial = occupyDic[_item.HWorkShopID + _item.FMATERIALID2];
                        }
                        //虚拟日计划用料清单 需求数量 
                        decimal planNeed = _item.PlanCount; //不参与计算 用于记录
                        decimal need = _item.PlanCount;//参与计算
                        decimal FOccupyPickedCount = 0;//占用领料单数量
                                                       //找到领用数量
                        var _DayPlanPickedModel = DayPlanPickedModel.Where(c => c.FPRDMOENTYID == _item.HICMOEntryID_Sec && c.FMATERIALID == _item.FMATERIALID2).FirstOrDefault();
                       
                        if (_DayPlanPickedModel.FRemainPickedQty >= need)
                        {
                            //领料数量满足了当前这个需求量 直接齐套 不需要去占用仓库
                            completeAnalysisTempModel.Add(new CompleteAnalysisTempModel
                            {
                                FHMainICMOInterIDr = _item.HICMOInterID_Sec,
                                FHMainICMOEntryID = _item.HICMOEntryID_Sec,
                                FHICMOInterID = _item.HInterID.ToString(),
                                FHICMOEntryID = _item.HEntryID.ToString(),
                                FHMaterID = _item.FMATERIALID2,
                                FErpClsID = _item.FErpClsID,
                                FHStockOrgID = _item.FStockOrgId,
                                FHPRDORGID = _item.FStockOrgId,
                                FPRDBillNo = _item.HICMOBillNo,
                                HMainICMOBillNo = _item.HMainICMOBillNo,
                                FOwnerTypeId = "",
                                FUnitDosage = _item.dwyl,//单位用量
                                FSumPlanCount = planNeed,//计划总数量
                                FCompleteCount1 = planNeed, //齐套数量
                                FLackCount = 0,//缺料数量
                                FHStockQty = jskcQty2,//即时库存
                                FHLeftQty = jskcQty,//可用数量
                                FOccupyCount = occupyMaterial,//占用数量
                                FOccupyPickedCount = planNeed,//占用领料数量
                                FComPlete = "齐套",
                                FPlanDate = item.HMasterDate, // 日计划日期
                                FWorkShop = _item.HWorkShopID //车间
                            });
                            //扣除剩余可用领料数量
                            _DayPlanPickedModel.FRemainPickedQty -= need;
                            //LogService.Write($"h" + need);
                            //循环下一个物料
                            continue;
                        }
                        else
                        {
                            //LogService.Write($"kxs" + need);
                            need -= _DayPlanPickedModel.FRemainPickedQty; //剩余需求数量
                            //LogService.Write($"i1" + need);
                            FOccupyPickedCount = _DayPlanPickedModel.FRemainPickedQty;
                            _DayPlanPickedModel.FRemainPickedQty = 0;
                            //LogService.Write($"i" + need);
                        }
                        if (_pRD_WorkHouseCompar.Count > 0)
                        {
                            //缺料数量 需求数量 - 实际库存  >0 ? 一个物料不管占用多少条 库存+货主 数据 缺料数量是同一个数量
                            decimal _fLackCount = need > jskcQty ? (need - jskcQty) : 0;
                            //LogService.Write($"j" + _fLackCount);
                            //LogHelper.Info("组织:" + _item.FStockOrgId + " ,及时库存" + jskcQty);
                            //总库存为0了 直接给出 缺料数量
                            if (jskcQty == 0)
                            {
                                completeAnalysisTempModel.Add(new CompleteAnalysisTempModel
                                {
                                    FHMainICMOInterIDr = _item.HICMOInterID_Sec,
                                    FHMainICMOEntryID = _item.HICMOEntryID_Sec,
                                    FHICMOInterID = _item.HInterID.ToString(),
                                    FHICMOEntryID = _item.HEntryID.ToString(),
                                    FHMaterID = _item.FMATERIALID2,
                                    FErpClsID = _item.FErpClsID,
                                    FHStockOrgID = _item.FStockOrgId,
                                    FHPRDORGID = _item.FStockOrgId,
                                    FPRDBillNo = _item.HICMOBillNo,
                                    HMainICMOBillNo = _item.HMainICMOBillNo,
                                    FOwnerTypeId = "",
                                    FUnitDosage = _item.dwyl,//单位用量
                                    FSumPlanCount = planNeed,//计划总数量
                                    FCompleteCount1 = FOccupyPickedCount, //齐套数量
                                    FLackCount = need,//缺料数量
                                    FHStockQty = jskcQty2,//即时库存
                                    FHLeftQty = jskcQty,//可用数量
                                    FOccupyCount = occupyMaterial,//占用数量
                                    FOccupyPickedCount = FOccupyPickedCount,//占用领料数量
                                    FComPlete = "未齐套",
                                    FPlanDate = item.HMasterDate, // 日计划日期
                                    FWorkShop = _item.HWorkShopID //车间
                                });
                                //终止该物料计算 进入下一个
                                continue;
                            }
 
                            //LogService.Write($"k" + 2);
                            foreach (var WorkHouse in _pRD_WorkHouseCompar)
                            {
                                //库存数据匹配
                                List<PRD_Inventory> _ListInventory = ListInventory.Where(c => c.FNumber == _item.FNumber && c.FBASEQTY > 0 && c.FSTOCKID == WorkHouse.FSTOCKID).ToList();
                                //需求数量 占用完后可以跳出车间仓库循环
                                if (need == 0)
                                    break;
                                if (_ListInventory.Count > 0)
                                {
                                    foreach (var Inventory in _ListInventory)
                                    {
                                        if (need == 0)
                                            break;
                                        //齐套数量 
                                        decimal fCompleteCount = need >= Inventory.FBASEQTY ? Inventory.FBASEQTY : need;
                                        if (!occupyDic.ContainsKey(_item.HWorkShopID + _item.FMATERIALID2))
                                        {
                                            occupyDic.Add(_item.HWorkShopID + _item.FMATERIALID2, fCompleteCount);
                                        }
                                        else
                                        {
                                            occupyMaterial = occupyDic[_item.HWorkShopID + _item.FMATERIALID2];
                                            occupyDic[_item.HWorkShopID + _item.FMATERIALID2] = occupyMaterial + fCompleteCount;
                                        }
                                        completeAnalysisTempModel.Add(new CompleteAnalysisTempModel
                                        {
                                            FHMainICMOInterIDr = _item.HICMOInterID_Sec,
                                            FHMainICMOEntryID = _item.HICMOEntryID_Sec,
                                            FHICMOInterID = _item.HInterID.ToString(),
                                            FHICMOEntryID = _item.HEntryID.ToString(),
                                            FHMaterID = _item.FMATERIALID2,
                                            FHStockOrgID = _item.FStockOrgId,
                                            FHPRDORGID = _item.FStockOrgId,
                                            FErpClsID = _item.FErpClsID,
                                            FPRDBillNo = _item.HICMOBillNo,
                                            HMainICMOBillNo = _item.HMainICMOBillNo,
                                            FOwnerTypeId = Inventory.FOwnerTypeId,
                                            FOwnerId = Inventory.FOwnerId,
                                            FUnitDosage = _item.dwyl,//单位用量
                                            FSumPlanCount = planNeed,//计划总数量
                                            FCompleteCount1 = fCompleteCount + FOccupyPickedCount, //齐套数量
                                            FLackCount = _fLackCount,//缺料数量
                                            FHStockQty = jskcQty2,//即时库存
                                            FHLeftQty = jskcQty,//可用数量
                                            FOccupyCount = occupyMaterial,//占用数量
                                            FOccupyPickedCount = FOccupyPickedCount,//领料占用数量
                                            FComPlete = jskcQty >= need ? "齐套" : "未齐套",
                                            FPlanDate = item.HMasterDate, // 日计划日期
                                            FStock = Inventory.FSTOCKID,//仓库
                                            FWorkShop = _item.HWorkShopID, //车间
                                            HLOT = Inventory.HLOT, //批号
                                            HInventoryFID = Inventory.HInventoryFID //id
                                        });
                                        //扣减总库存数量
                                        jskcQty = jskcQty >= fCompleteCount ? jskcQty - fCompleteCount : 0;
                                        //剩余日计划需求数量
                                        need = need >= Inventory.FBASEQTY ? need - Inventory.FBASEQTY : 0;
                                        //扣减消耗库存
                                        Inventory.FBASEQTY = Inventory.FBASEQTY - fCompleteCount;
                                    }
                                }
                            }
                        }
                        //没有车间仓库数据 既没有可用库存 为未齐套
                        else
                        {
                            if (occupyDic.ContainsKey(_item.HWorkShopID + _item.FMATERIALID2))
                            {
                                occupyMaterial = occupyDic[_item.HWorkShopID + _item.FMATERIALID2];
                            }
                            completeAnalysisTempModel.Add(new CompleteAnalysisTempModel
                            {
                                FHMainICMOInterIDr = _item.HICMOInterID_Sec,
                                FHMainICMOEntryID = _item.HICMOEntryID_Sec,
                                FHICMOInterID = _item.HInterID.ToString(),
                                FHICMOEntryID = _item.HEntryID.ToString(),
                                FHMaterID = _item.FMATERIALID2,
                                FErpClsID = _item.FErpClsID,
                                FHStockOrgID = _item.FStockOrgId,
                                FHPRDORGID = _item.FStockOrgId,
                                FPRDBillNo = _item.HICMOBillNo,
                                HMainICMOBillNo = _item.HMainICMOBillNo,
                                FOwnerTypeId = "",
                                FUnitDosage = _item.dwyl,//单位用量
                                FSumPlanCount = planNeed,//计划总数量
                                FCompleteCount1 = planNeed - need, //齐套数量
                                FLackCount = need,//缺料数量
                                FHStockQty = jskcQty2,//即时库存
                                FHLeftQty = jskcQty,//可用数量
                                FOccupyCount = occupyMaterial,//占用数量
                                FOccupyPickedCount = FOccupyPickedCount,//占用领料数量
                                FComPlete = "未齐套",
                                FPlanDate = item.HMasterDate, // 日计划日期
                                FWorkShop = _item.HWorkShopID //车间
                            });
                        }
                    }
                    //Thread.Sleep(6000);
                    i++;
                }
                //LogService.Write($"齐套分析,数据准备完成,保存到Model实体,总行数:{completeAnalysisTempModel.Count},耗时:" + sw.Elapsed);
                List<string> sqlList = new List<string>();
                DataTable insertDT = new DataTable();
                insertDT.TableName = "JIT_MOMaterReadysBill";
                insertDT.Columns.Add("FID", typeof(long));
                insertDT.Columns.Add("FDOCUMENTSTATUS", typeof(string));
                insertDT.Columns.Add("FHMAINICMOINTERIDR", typeof(long));
                insertDT.Columns.Add("FHMAINICMOENTRYID", typeof(long));
                insertDT.Columns.Add("FHICMOINTERID", typeof(long));
                insertDT.Columns.Add("FHICMOENTRYID", typeof(long));
                insertDT.Columns.Add("FHMATERID", typeof(long));
                insertDT.Columns.Add("FHSTOCKORGID", typeof(long));
                insertDT.Columns.Add("FHSTOCKQTY", typeof(decimal));
                insertDT.Columns.Add("FHLEFTQTY", typeof(decimal));
                insertDT.Columns.Add("FHPRDORGID", typeof(long));
                insertDT.Columns.Add("FUNITDOSAGE", typeof(decimal));
                insertDT.Columns.Add("FSUMPLANCOUNT", typeof(decimal));
                insertDT.Columns.Add("FPRDBILLNO", typeof(string));
                insertDT.Columns.Add("HMainICMOBillNo", typeof(string));
                insertDT.Columns.Add("FOWNERID", typeof(long));
                insertDT.Columns.Add("FOWNERTYPEID", typeof(string));
                insertDT.Columns.Add("FPLANDATE", typeof(DateTime));
                insertDT.Columns.Add("FCOMPLETE", typeof(string));
                insertDT.Columns.Add("FLACKCOUNT", typeof(decimal));
                insertDT.Columns.Add("FOCCUPYCOUNT", typeof(decimal));
                insertDT.Columns.Add("FCOMPLETECOUNT1", typeof(decimal));
                insertDT.Columns.Add("FERPCLSID", typeof(string));
                insertDT.Columns.Add("FWORKSHOPID", typeof(long));
                insertDT.Columns.Add("FSTOCKID", typeof(long));
                insertDT.Columns.Add("FOCCUPYPICKEDCOUNT", typeof(decimal));
                insertDT.Columns.Add("HLOT", typeof(long));
                insertDT.Columns.Add("HInventoryFID", typeof(string));
                int jdtmmm = 1;
                ds = oCN.RunProcReturn("select max(HInterID)FID FROM  JIT_MOMaterReadysBill", "JIT_MOMaterReadysBill");
                int maxFid = int.Parse(ds.Tables[0].Rows[0][0].ToString() == "" ? "0" : ds.Tables[0].Rows[0][0].ToString());
                foreach (var item in completeAnalysisTempModel)
                {
                    DataRow dr = insertDT.NewRow();
                    dr["FID"] = maxFid + jdtmmm;
                    dr["FDOCUMENTSTATUS"] = "A";
                    dr["FHMAINICMOINTERIDR"] = item.FHMainICMOInterIDr;
                    dr["FHMAINICMOENTRYID"] = item.FHMainICMOEntryID;
                    dr["FHICMOINTERID"] = item.FHICMOInterID;
                    dr["FHICMOENTRYID"] = item.FHICMOEntryID;
                    dr["FHMATERID"] = item.FHMaterID;
                    dr["FHSTOCKORGID"] = item.FHStockOrgID;
                    dr["FHSTOCKQTY"] = item.FHStockQty;
                    dr["FHLEFTQTY"] = item.FHLeftQty;
                    dr["FHPRDORGID"] = item.FHPRDORGID;
                    dr["FUNITDOSAGE"] = item.FUnitDosage;
                    dr["FSUMPLANCOUNT"] = item.FSumPlanCount;
                    dr["FPRDBILLNO"] = item.FPRDBillNo;
                    dr["HMainICMOBillNo"] = item.HMainICMOBillNo;
                    dr["FOWNERID"] = item.FOwnerId == null ? "0" : item.FOwnerId;
                    dr["FOWNERTYPEID"] = item.FOwnerTypeId;
                    dr["FPLANDATE"] = item.FPlanDate.ToString("yyyy-MM-dd");
                    dr["FCOMPLETE"] = item.FComPlete;
                    dr["FLACKCOUNT"] = item.FLackCount;
                    dr["FOCCUPYCOUNT"] = item.FOccupyCount;
                    dr["FCOMPLETECOUNT1"] = item.FCompleteCount1;
                    dr["FERPCLSID"] = item.FErpClsID;
                    dr["FWORKSHOPID"] = item.FWorkShop == null ? "0" : item.FWorkShop;
                    dr["FSTOCKID"] = item.FStock == null ? "0" : item.FStock;
                    dr["FOCCUPYPICKEDCOUNT"] = item.FOccupyPickedCount;
                    dr["HLOT"] = item.HLOT == null? "0" : item.HLOT;
                    dr["HInventoryFID"] = item.HInventoryFID == null ? "0" : item.HInventoryFID;
                    insertDT.Rows.Add(dr);
                    jdtmmm++;
                }
 
                insertDT.EndLoadData(); // 灌入数据结束
                //插入之前执行下清空语句(测试是否能够防止重复生成)
                string deletesql = $"delete from JIT_MOMaterReadysBill  where HICMOInterID  in ({fDayPlanFids}) ";
                oCN.RunProc(deletesql);
                // 批量插入到数据库
                foreach (DataRow item in insertDT.Rows)
                {
                    oCN.RunProc("insert into JIT_MOMaterReadysBill(HInterID,HDocumentStatus,HMainICMOInterID,HMainICMOEntryID,HICMOInterID" +
                            ", HICMOEntryID, HMaterID, HStockORGID, HStockQty, HLeftQty" +
                            ", HProdORGID, HUnitDosage, HSumPlanQty, HICMOBillNo, HOwnerID" +
                            ", HOwnerTypeID, HPlanDate, HComplete, HLackQty, HOccupyQty" +
                            ", HCompleteQty1, HErpClsID, HWorkShopID, HWHID, HOccupyPickedQTY,HMainICMOBillNo" +
                            ",HLOT,HInventoryFID)values" +
                             $"({item["FID"].ToString()}, 1, {item["FHMAINICMOINTERIDR"].ToString()}, {item["FHMAINICMOENTRYID"].ToString()}, {item["FHICMOINTERID"].ToString()}" +
                             $", {item["FHICMOENTRYID"].ToString()}, {item["FHMATERID"].ToString()}, {item["FHSTOCKORGID"].ToString()}, {item["FHSTOCKQTY"].ToString()}, {item["FHLEFTQTY"].ToString()}" +
                             $" , {item["FHPRDORGID"].ToString()}, {item["FUNITDOSAGE"].ToString()}, {item["FSUMPLANCOUNT"].ToString()}, '{item["FPRDBILLNO"].ToString()}', {item["FOWNERID"].ToString()}" +
                             $", '{item["FOWNERTYPEID"].ToString()}', '{item["FPLANDATE"].ToString()}','{item["FCOMPLETE"].ToString()}', {item["FLACKCOUNT"].ToString()}, {item["FOCCUPYCOUNT"].ToString()}" +
                             $", {item["FCOMPLETECOUNT1"].ToString()}, {item["FERPCLSID"].ToString()}, {item["FWORKSHOPID"].ToString()}, {item["FSTOCKID"].ToString()}, {item["FOCCUPYPICKEDCOUNT"].ToString()}, '{item["HMainICMOBillNo"].ToString()}'" +
                             $",{item["HLOT"].ToString()},'{item["HInventoryFID"].ToString()}')");
                }
                //LogService.Write("批量插入到数据库用时:" + sw.Elapsed);
                //执行完成后 更新日计划工单状态
                string updatesql = string.Format(@"
update Sc_WorkBillSortBillSub set HComplete = '未齐套' where HEntryID IN 
(select distinct HICMOEntryID from JIT_MOMaterReadysBill
 where  isnull(HComplete,'未齐套') ='未齐套'
 and HICMOEntryID in ({0})
 )", fDayPlanFEntryids);
                //LogService.Write(Context, updatesql);
                oCN.RunProc(updatesql);
                updatesql = string.Format(@"
update Sc_WorkBillSortBillSub set HComplete  = '齐套' 
where HEntryID IN ({0}) and HComplete  <>'未齐套'
", fDayPlanFEntryids);
                //LogService.Write(updatesql);
                oCN.RunProc(updatesql);
                //释放齐套操作 避免多人同时进行齐套分析
                oCN.RunProc($"update T_PRD_QTFX set FSTATUS = 0 where FPRDORGID ={omdelMian.HProdORGID} and FSTATUS = 1 ");
                sw.Stop();//结束计时
                //LogService.Write("齐套分析运行总时长:" + sw.Elapsed);
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "操作成功";
                objJsonResult.data = null;
                return objJsonResult;
            }
            catch (Exception e)
            {
                LogService.Write("操作失败:" + e.Message.ToString());
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.Message.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
 
        #endregion
 
        #region 齐套分析调用方法    20250402
 
        [Route("JIT_DayPlanPlatFormBill/JIT_CompleteSetAnalysis")]
        [HttpGet]
        public object JIT_CompleteSetAnalysis(string sWhere, string user)
        {
            try
            {
                string sErrMsg = "";
                if (oSystemParameter.ShowBill(ref sErrMsg) == true)
                {
                    if (oSystemParameter.omodel.WMS_CampanyName == "帅威"
                        || oSystemParameter.omodel.WMS_CampanyName == "凯贝奈特"
                        || oSystemParameter.omodel.WMS_CampanyName == "添康科技"
                        || oSystemParameter.omodel.WMS_CampanyName == "宝工")     //系统参数  客户定制化名称     空白为通用
                    {
                        objJsonResult = (json)JIT_CompleteSetAnalysis_Old(sWhere, user);
                    }
                    else
                    {
                        objJsonResult = (json)JIT_CompleteSetAnalysis_New(sWhere, user);
                    }
                    return objJsonResult;
                }
                else
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "获取系统参数失败! " + sErrMsg;
                    objJsonResult.data = null;
                    return objJsonResult;
                }
            }
            catch (Exception e)
            {
                LogService.Write("齐套分析操作失败:" + e.Message.ToString());
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.Message.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
 
        /// <summary>
        /// 齐套分析    新调用方法
        /// </summary>
        /// <returns></returns>
        public object JIT_CompleteSetAnalysis_New(string sWhere, string user)
        {
            try
            {
                omdelMian = JsonConvert.DeserializeObject<Sc_WorkBillSortBillMain>(sWhere);
                string HWorkShopID = omdelMian.HWorkShopID.ToString();
                var HStockOrgID = omdelMian.HProdORGID;
 
                ds = oCN.RunProcReturn("exec h_p_JIT_CompleteSetAnalysis " + HWorkShopID.ToString() + ",'" + user + "'," + HStockOrgID.ToString(), "h_p_JIT_CompleteSetAnalysis");
                if (ds == null || ds.Tables[0].Rows.Count == 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "齐套分析发生错误!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                else if (DBUtility.ClsPub.isLong(ds.Tables[0].Rows[0]["HBack"]) == 1)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = DBUtility.ClsPub.isStrNull(ds.Tables[0].Rows[0]["HRemark"]);
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                else
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 1;
                    objJsonResult.Message = DBUtility.ClsPub.isStrNull(ds.Tables[0].Rows[0]["HRemark"]);    //运算成功
                    objJsonResult.data = null;
                    return objJsonResult;
                }
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "齐套分析失败!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
 
        #endregion
 
        #endregion
 
        #region 生产日计划平台 提料运算
 
        #region 日计划展开数据明细
        public class DayPlanPpbom
        {
 
            /// <summary>
            /// 日计划工单主ID
            /// </summary>
            public long FID { get; set; }
            /// <summary>
            /// 生产订单号
            /// </summary>
            public string FBILLNO { get; set; }
            /// <summary>
            /// 日计划明细日期
            /// </summary>
            public DateTime FHMASTERDATE { get; set; }
            /// <summary>
            /// 日计划明细数量
            /// </summary>
            public decimal FHQTY { get; set; }
            /// <summary>
            /// 齐套数
            /// </summary>
            public decimal FCOMPLETECOUNT { get; set; }
            /// <summary>
            /// 生产订单工单ID
            /// </summary>
            public long FPRDMOMAINID { get; set; }
            /// <summary>
            /// 子表ID
            /// </summary>
            public int FENTRYID { get; set; }
            /// <summary>
            /// 单位用料
            /// </summary>
            public decimal FNeedQty { get; set; }
            /// <summary>
            /// 物料ID
            /// </summary>
            public string FMATERIALID { get; set; }
            /// <summary>
            /// 提前天数
            /// </summary>
            public int FFIXLEADTIME { get; set; }
            /// <summary>
            ///最大包装
            /// </summary>
            public decimal FMAXPOQTY { get; set; }
            /// <summary>
            /// 最小包装量
            /// </summary>
            public decimal FMINPOQTY { get; set; }
            /// <summary>
            /// 物料编码
            /// </summary>
            public string FNumber { get; set; }
            /// <summary>
            /// 实际需求
            /// </summary>
            public decimal NeedQty { get; set; }
 
            /// <summary>
            /// 库存组织
            /// </summary>
            public long FStockOrgId { get; set; }
            //库存组织名称
            public string FStockOrgName { get; set; }
            /// <summary>
            /// jit物料分类
            /// </summary>
            public string FJITmaterialGroup { get; set; }
            /// <summary>
            /// JIT物料需求供货周期
            /// </summary>
            public string FJITMaterielDemand { get; set; }
            /// <summary>
            /// JIT安全库存
            /// </summary>
            public string FJITSafeStock { get; set; }
 
            /// <summary>
            /// 物料属性
            /// </summary>
            public string FErpClsID { get; set; }
            /// <summary>
            /// 需求单号(销售订单号)
            /// </summary>
            public string FXQD { get; set; }
            /// <summary>
            /// 日计划工单单号
            /// </summary>
            public string FDAYPLANBILLNO { get; set; }
            /// <summary>
            /// 生产车间编码
            /// </summary>
            public string FWORKSHOPNUMBER { get; set; }
 
 
        }
        #endregion
 
        #region 采购订单物料库存
        public class PurchaseInventory
        {
            /// <summary>
            /// 采购FID
            /// </summary>
            public long FID { get; set; }
            //采购订单单号
            public string FBillNo { get; set; }
            /// <summary>
            /// 采购子表标识
            /// </summary>
            public long FENTRYID { get; set; }
            /// <summary>
            /// 供应商id
            /// </summary>
            public long FSUPPLIERID { get; set; }
            /// <summary>
            /// 供应商名称
            /// </summary>
            public string FNUMBER { get; set; }
            /// <summary>
            /// 物料ID
            /// </summary>
            public string FMATERIALID { get; set; }
            /// <summary>
            /// 物料编码
            /// </summary>
            public string FMATERIALNUMBER { get; set; }
 
            /// <summary>
            /// 采购数量
            /// </summary>
            public decimal FQTY { get; set; }
 
            /// <summary>
            /// 采购组织
            /// </summary>
            public long FStockOrgId { get; set; }
            /// <summary>
            /// 采购组织名称
            /// </summary>
            public string FStockOrgName { get; set; }
            /// <summary>
            /// 组织编码
            /// </summary>
            public string FORGNumber { get; set; }
            /// <summary>
            /// 提前期
            /// </summary>
            public int FFIXLEADTIME { get; set; }
 
            /// <summary>
            /// 需求单号
            /// </summary>
            public string FXQD { get; set; }
            /// <summary>
            /// 采购订单上的创建人
            /// </summary>
            public string FCREATORID { get; set; }
            /// <summary>
            /// 采购订单上的创建人名称
            /// </summary>
            public string FName { get; set; }
            /// <summary>
            /// 采购订单上的采购日期
            /// </summary>
            public DateTime FDate { get; set; }
            /// <summary>
            /// 采购订单上的交货日期
            /// </summary>
            public DateTime FDeliveryDate { get; set; }
            /// <summary>
            /// 采购订单表头摘要
            /// </summary>
            public string F_QIMB_NOTE { get; set; }
            /// <summary>
            /// 采购订单表体备注
            /// </summary>
            public string FNOTE { get; set; }
            //采购部门
            public string FPURCHASEDEPTNUMBER { get; set; }
 
            /// <summary>
            /// 收料但是没入库部分 需要优先去扣除
            /// </summary>
            public decimal FReceiveNotInQty { get; set; }
            /// <summary>
            /// 采购订单数量
            /// </summary>
            public decimal FPURCHASEQTY { get; set; }
            /// <summary>
            /// 采购订单关联数量
            /// </summary>
            public decimal FJOINQTY { get; set; }
 
            /// <summary>
            /// 收料单数量
            /// </summary>
            public decimal FReceiveQty { get; set; }
        }
        #endregion
 
        #region 提料计划临时储存
        public class PODemandPlanTemp
        {
            /// <summary>
            /// 日计划工单主ID
            /// </summary>
            public long FID { get; set; }
            /// <summary>
            /// 日计划工单编号
            /// </summary>
            public string FBILLNO { get; set; }
            /// <summary>
            /// 日计划明细日期
            /// </summary>
            public DateTime FHMASTERDATE { get; set; }
            /// <summary>
            /// 日计划明细数量
            /// </summary>
            public decimal FHQTY { get; set; }
            /// <summary>
            /// 生产订单工单ID
            /// </summary>
            public long FPRDMOMAINID { get; set; }
            /// <summary>
            /// 子表ID
            /// </summary>
            public int FENTRYID { get; set; }
            /// <summary>
            /// 数量
            /// </summary>
            public decimal FQty { get; set; }
            /// <summary>
            /// 物料ID
            /// </summary>
            public string FMATERIALID { get; set; }
            /// <summary>
            /// 物料编码
            /// </summary>
            public string FNumber { get; set; }
 
            /// <summary>
            /// 采购FID
            /// </summary>
            public long PurchseFID { get; set; }
            /// <summary>
            /// 采购订单单号
            /// </summary>
            public string PurchseFBillNo { get; set; }
            /// <summary>
            /// 采购子表标识
            /// </summary>
            public long PurchseFentryID { get; set; }
            /// <summary>
            /// 供应商id
            /// </summary>
            public long FSUPPLIERID { get; set; }
            /// <summary>
            /// 供应商名称
            /// </summary>
            public string PurchseFNUMBER { get; set; }
 
            /// <summary>
            /// 日计划日期
            /// </summary>
            public DateTime OLDDATE { get; set; }
 
            /// <summary>
            /// 采购订单数量
            /// </summary>
            public decimal PurchseFqty { get; set; }
 
            /// <summary>
            /// 提前期
            /// </summary>
            public double FFIXLEADTIME { get; set; }
 
            /// <summary>
            /// 采购组织
            /// </summary>
            public long FStockOrgId { get; set; }
            /// <summary>
            /// 采购组织名称
            /// </summary>
            public string FStockOrgName { get; set; }
            /// <summary>
            /// 组织编码
            /// </summary>
            public string FORGNumber { get; set; }
 
            /// <summary>
            /// 物料属性
            /// </summary>
            public string FErpClsID { get; set; }
 
            /// <summary>
            /// 需求单号
            /// </summary>
            public string FXQD { get; set; }
            /// <summary>
            /// 采购订单上的创建人
            /// </summary>
            public string FCREATORID { get; set; }
            /// <summary>
            /// 采购订单上的创建人名称
            /// </summary>
            public string FName { get; set; }
            /// <summary>
            /// 采购订单上的采购日期
            /// </summary>
            public DateTime FDate { get; set; }
            /// <summary>
            /// 采购订单上的交货日期
            /// </summary>
            public DateTime FDeliveryDate { get; set; }
            /// <summary>
            /// 采购订单表头摘要
            /// </summary>
            public string F_QIMB_NOTE { get; set; }
            /// <summary>
            /// 采购订单表体备注
            /// </summary>
            public string FNOTE { get; set; }
 
            /// <summary>
            /// 采购部门
            /// </summary>
            public string FPURCHASEDEPTNUMBER { get; set; }
            /// <summary>
            /// 日计划工单单号
            /// </summary>
            public string FDAYPLANBILLNO { get; set; }
            /// <summary>
            /// 生产车间编码
            /// </summary>
            public string FWORKSHOPNUMBER { get; set; }
            /// <summary>
            /// 采购订单数量
            /// </summary>
            public decimal FPURCHASEQTY { get; set; }
            /// <summary>
            /// 采购订单关联数量
            /// </summary>
            public decimal FJOINQTY { get; set; }
        }
        #endregion
 
        [Route("JIT_DayPlanPlatFormBill/JIT_TLYS")]
        [HttpGet]
        public object JIT_TLYS(string sWhere, string user,string HTLType)
        {
            try
            {
                omdelMian = JsonConvert.DeserializeObject<Sc_WorkBillSortBillMain>(sWhere);
 
                string fProWorkShopId = omdelMian.HWorkShopID.ToString();
                var fPrdOrgId = omdelMian.HProdORGID;
                string sqlName = "";//AIS20210811135644
                string WMS_CampanyName = "";    //客户名称
                //客户制定
                string sErr = "";
                if (oSystemParameter.ShowBill(ref sErr))
                {
                    if (oSystemParameter.omodel.WMS_CampanyName == "帅威")
                    {
                        sqlName = "AIS20230129011339";
                        WMS_CampanyName = "帅威";
                    }
                    else if (oSystemParameter.omodel.WMS_CampanyName == "凯贝奈特")
                    {
                        sqlName = "AIS20210820164804";
                        WMS_CampanyName = "凯贝奈特";
                    }
                    else if (oSystemParameter.omodel.WMS_CampanyName == "添康科技")
                    {
                        sqlName = "AIS20240809105013";
                        WMS_CampanyName = "添康科技";
                    }
                    else if (oSystemParameter.omodel.WMS_CampanyName == "宝工")
                    {
                        sqlName = "AIS20250102123554";
                        WMS_CampanyName = "宝工";
                    }
                    else
                    {
                        sqlName = "AIS20210811135644";
                    }
 
                    if (WMS_CampanyName == "宝工")
                    {
                        objJsonResult = (json)JIT_MOMaterLack(fProWorkShopId, fPrdOrgId, user);
                    }
                    else if (HTLType == "缺料")
                    {
                        if (WMS_CampanyName == "帅威" || WMS_CampanyName == "凯贝奈特" || WMS_CampanyName == "添康科技")
                        {
                            objJsonResult = (json)JIT_QL(fProWorkShopId, fPrdOrgId, user, sqlName);
                        }
                        else
                        {
                            objJsonResult = (json)JIT_MOMaterReady(fProWorkShopId, fPrdOrgId, user);
                        }
                    }
                    else if (HTLType == "生产用料清单")
                    {
                        objJsonResult = (json)JIT_PPBOM(fProWorkShopId, fPrdOrgId, user, sqlName);
                    }
 
                    return objJsonResult;
                }
                else
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "获取系统参数失败! " + sErr;
                    objJsonResult.data = null;
                    return objJsonResult;
                }
            }
            catch (Exception e)
            {
                LogService.Write("操作失败:" + e.Message.ToString());
                oCN.RollBack();//事务回滚
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.Message.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
 
        /// <summary>
        /// 通过缺料情况算提料
        /// </summary>
        /// <returns></returns>
        public object JIT_QL(string HWorkShopID,int? HProdORGID,string user,string sqlName) {
            try
            {
 
                oCN.BeginTran();
 
                DataSet DaSet = oCN.RunProcReturn($"exec h_p_JIT_MOMaterReady {HWorkShopID},{HProdORGID},1", "JIT_MOMaterReadysBill");
 
                if (DaSet.Tables[0].Rows[0][0].ToString() != "1")
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "没有数据,请先齐套分析!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                //Stopwatch sw = new Stopwatch();
                //sw.Start();//开始计时
                //提料计划预处理 清理提料计划单数据 更新采购订单提料计划数量
                //               string sql = string.Format(@"
                // /*dialect*/
                //exec [提料计划预处理] 
                //");
                //               DBServiceHelper.Execute(Context, sql);
                ////LogHelper.Info("[提料计划准备阶段]提料计划预处理sql:" + sql);
                //采购订单数据
                string sql = $@"exec h_p_JIT_MOMaterReady {HWorkShopID},{HProdORGID},2";
                DataSet ds = oCN.RunProcReturn(sql, "t_PUR_POOrderEntry");
                List<PurchaseInventory> PurchaseInventory = ds.ToModelList<PurchaseInventory>();
                ////LogHelper.Info("[提料计划准备阶段]可用采购订单数据sql:" + sql);
                sql = string.Format($@"exec h_p_JIT_MOMaterReady {HWorkShopID},{HProdORGID},3");
                ////LogHelper.Info("[提料计划准备阶段]需要提料数据sql:" + sql);
                ds = oCN.RunProcReturn( sql, "JIT_MOMaterReadysBill");
                List<DayPlanPpbom> DayPlanPpbom = ds.ToModelList<DayPlanPpbom>();
                //物料+库存组织分类
                var MaterialIDList = DayPlanPpbom.GroupBy(p => new { p.FMATERIALID, p.FNumber,p.FStockOrgName, p.FStockOrgId }).Select(x => new PODemandPlanTemp { FMATERIALID = x.Key.FMATERIALID, FNumber=x.Key.FNumber, FStockOrgId = x.Key.FStockOrgId , FStockOrgName =x.Key.FStockOrgName }).ToList();
                //提料计划数据集临时存储集合
                List<PODemandPlanTemp> PODemandPlanTemp = new List<PODemandPlanTemp>();
                //sql集合 更新采购订单占用的提料计划数量
                List<string> sqlList = new List<string>();
 
                //LogService.Write("1");
                string Error = "";
                foreach (var item in MaterialIDList)
                {
                    //当前物料没有采购订单时 直接跳出
                    List<PurchaseInventory> _PurchaseInventory = PurchaseInventory.Where(x => x.FMATERIALID == item.FMATERIALID && x.FStockOrgId == item.FStockOrgId && x.FQTY > 0).OrderBy(x => x.FENTRYID).ToList();
                    if (_PurchaseInventory.Count == 0)
                    {
                        Error+="[提料计划开始]当前物料无采购信息:" + item.FNumber + " 库存组织:" + item.FStockOrgName + "      ";
                        continue;
                    }
 
                    //LogService.Write("1.1");
 
                    ////LogHelper.Info(item.FMATERIALID.ToString());
                    //当前物料和库存组织对应的需进行提料计划的数据    
                    List<DayPlanPpbom> _DayPlanPpbom = DayPlanPpbom.Where(x => x.FMATERIALID == item.FMATERIALID && x.FStockOrgId == item.FStockOrgId).ToList();
                    decimal FMINPOQTY = _DayPlanPpbom.FirstOrDefault().FMINPOQTY;//最小起订量
                    double FFIXLEADTIME = _DayPlanPpbom.FirstOrDefault().FFIXLEADTIME;//提前期
                    //double FFIXLEADTIME = 3;//提前期(2022-1-26 提前期改为3天 乃永刚反馈)
                    string FJITmaterialGroup = _DayPlanPpbom.FirstOrDefault().FJITmaterialGroup;//jit物料分类
                    string FJITMaterielDemand = _DayPlanPpbom.FirstOrDefault().FJITMaterielDemand; //JIT物料需求供货周期
                    string FJITSafeStock = _DayPlanPpbom.FirstOrDefault().FJITSafeStock; //JIT安全库存
                    decimal NeedQty = 0;
                    DateTime DATE = _DayPlanPpbom.FirstOrDefault().FHMASTERDATE;//第一个订货起始日期
                    int i = 0;
                    //记录在最小采购量需求下的日计划明细FentyrID
 
                    //LogService.Write("1.2");
 
                    List<int> FEntryIdList = new List<int>();
                    foreach (var _item in _DayPlanPpbom)
                    {
                        i++;
                        _PurchaseInventory = PurchaseInventory.Where(x => x.FMATERIALID == item.FMATERIALID && x.FStockOrgId == item.FStockOrgId && x.FQTY > 0).OrderBy(x => x.FENTRYID).ToList();
                        if (_PurchaseInventory.Count == 0)
                        {
                            break;
                        }
 
                        //LogService.Write("1.2.1");
 
                        if (NeedQty == 0)
                        {
                            DATE = Convert.ToDateTime(_item.FHMASTERDATE).AddDays(-FFIXLEADTIME);
                        }
                        FEntryIdList.Add(_item.FENTRYID);
                        NeedQty += _item.NeedQty;
                        //LogService.Write(FJITmaterialGroup);
                        //LogService.Write(FEntryIdList.Count);
                        //LogService.Write(Convert.ToDouble(FJITMaterielDemand));
                        //LogService.Write(_DayPlanPpbom.Count);
                        //LogService.Write(i);
                        if ((FJITmaterialGroup == "总量控制规格类" || FJITmaterialGroup == "订单专用个性类") && FEntryIdList.Count < Convert.ToDouble(FJITMaterielDemand) && i < _DayPlanPpbom.Count) //订单专用个性类
                        {
                            continue;
                        }
 
                        //LogService.Write("1.2.2");
 
                        foreach (var Purchase in _PurchaseInventory)
                        {
                            if (Purchase.FQTY >= NeedQty)
                            {
                                foreach (int id in FEntryIdList)
                                {
                                    var DayPlanPpbomls = DayPlanPpbom.Where(c => c.FENTRYID == id && c.FMATERIALID == _item.FMATERIALID).FirstOrDefault();
                                    PODemandPlanTemp.Add(new PODemandPlanTemp
                                    {
                                        FID = DayPlanPpbomls.FID,
                                        FHMASTERDATE = DATE,
                                        FQty = DayPlanPpbomls.NeedQty,
                                        FBILLNO = DayPlanPpbomls.FBILLNO,
                                        FENTRYID = DayPlanPpbomls.FENTRYID,
                                        FMATERIALID = DayPlanPpbomls.FMATERIALID,
                                        FNumber = DayPlanPpbomls.FNumber,
                                        OLDDATE = DayPlanPpbomls.FHMASTERDATE,
                                        FFIXLEADTIME = FFIXLEADTIME,
                                        FErpClsID = DayPlanPpbomls.FErpClsID,
 
                                        PurchseFID = Purchase.FID,
                                        PurchseFentryID = Purchase.FENTRYID,
                                        FSUPPLIERID = Purchase.FSUPPLIERID,
                                        PurchseFNUMBER = Purchase.FNUMBER,
                                        PurchseFBillNo = Purchase.FBillNo,
                                        PurchseFqty = Purchase.FQTY,
                                        FStockOrgId = Purchase.FStockOrgId, //采购组织
                                        FORGNumber = Purchase.FORGNumber,
 
                                        FXQD = _item.FXQD,
                                        FCREATORID = Purchase.FCREATORID,
                                        FName = Purchase.FName,
                                        FDate = Purchase.FDate,
                                        FDeliveryDate = Purchase.FDeliveryDate,
                                        F_QIMB_NOTE = Purchase.F_QIMB_NOTE,
                                        FNOTE = Purchase.FNOTE,
                                        FPURCHASEQTY = Purchase.FPURCHASEQTY,
                                        FJOINQTY = Purchase.FJOINQTY,
                                        FDAYPLANBILLNO = _item.FDAYPLANBILLNO
                                    });
                                    //扣除日计划明细已被分配的数量
                                    DayPlanPpbomls.NeedQty = 0;
                                }
 
                                //LogService.Write("1.2.3");
 
                                FEntryIdList.Clear();
                                //更新采购订单
                                //sqlList.Add($"/*dialect*/ update t_PUR_POOrderEntry set FPODemandPlanCount  =isnull(FPODemandPlanCount,0)+  '{NeedQty}' where FENTRYID = {Purchase.FENTRYID}");
                                //扣除当前行对应采购订单数量
                                var ls = PurchaseInventory.Where(c => c.FENTRYID == Purchase.FENTRYID).FirstOrDefault();
                                ls.FQTY -= NeedQty;
                                break;
                            }
                            else
                            {
                                //更新总需求数量
                                NeedQty = NeedQty - Purchase.FQTY;
                                //采购订单数量
                                decimal _NeedQty = Purchase.FQTY;
                                List<int> mmm = new List<int>();
                                foreach (int id in FEntryIdList)
                                {
                                    var DayPlanPpbomls = DayPlanPpbom.Where(c => c.FENTRYID == id && c.FMATERIALID == _item.FMATERIALID).FirstOrDefault();
                                    decimal Qty = DayPlanPpbomls.NeedQty;//订单数量
                                  
                                    if (Qty > _NeedQty)
                                        Qty = _NeedQty; //订单数量>采购订单数量 取采购订单
 
                                    _NeedQty = _NeedQty - Qty;
                                    PODemandPlanTemp.Add(new PODemandPlanTemp
                                    {
                                        FID = DayPlanPpbomls.FID,
                                        FHMASTERDATE = DATE,
                                        FQty = Qty,
                                        FBILLNO = DayPlanPpbomls.FBILLNO,
                                        FENTRYID = DayPlanPpbomls.FENTRYID,
                                        FMATERIALID = DayPlanPpbomls.FMATERIALID,
                                        FNumber = DayPlanPpbomls.FNumber,
                                        OLDDATE = DayPlanPpbomls.FHMASTERDATE,
                                        FFIXLEADTIME = FFIXLEADTIME,
                                        FErpClsID = DayPlanPpbomls.FErpClsID,
 
                                        PurchseFID = Purchase.FID,
                                        PurchseFentryID = Purchase.FENTRYID,
                                        FSUPPLIERID = Purchase.FSUPPLIERID,
                                        PurchseFNUMBER = Purchase.FNUMBER,
                                        PurchseFBillNo = Purchase.FBillNo,
                                        PurchseFqty = Purchase.FQTY,
                                        FStockOrgId = Purchase.FStockOrgId, //采购组织
                                        FORGNumber = Purchase.FORGNumber,
 
                                        FPURCHASEDEPTNUMBER = Purchase.FPURCHASEDEPTNUMBER,
                                        FXQD = _item.FXQD,
                                        FCREATORID = Purchase.FCREATORID,
                                        FName = Purchase.FName,
                                        FDate = Purchase.FDate,
                                        FDeliveryDate = Purchase.FDeliveryDate,
                                        F_QIMB_NOTE = Purchase.F_QIMB_NOTE,
                                        FNOTE = Purchase.FNOTE,
                                        FPURCHASEQTY = Purchase.FPURCHASEQTY,
                                        FJOINQTY = Purchase.FJOINQTY,
                                        FDAYPLANBILLNO = _item.FDAYPLANBILLNO
                                    });
                                    //更新计划数量(剩余需要排的) 继续去计算下一个采购订单
                                    DayPlanPpbomls.NeedQty -= Qty;
                                    //更新采购订单
                                    //sqlList.Add($"/*dialect*/ update t_PUR_POOrderEntry set FPODemandPlanCount = isnull(FPODemandPlanCount,0)+ '{Qty}' where FENTRYID = {Purchase.FENTRYID}");
                                    //更新Model
                                    var ls = PurchaseInventory.Where(c => c.FENTRYID == Purchase.FENTRYID).FirstOrDefault();
                                    ls.FQTY -= Qty;
                                    if (_NeedQty <= 0)
                                    {
                                        foreach (var mm in mmm)
                                        {
                                            FEntryIdList.Remove(mm);
                                        }
                                        break;
                                    }
                                    mmm.Add(id);
                                }
                            }
                        }
 
                        //LogService.Write("1.2.4");
 
                        NeedQty = 0;
 
                    }
                }
 
                //var PODemandPlanList222 = PODemandPlanTemp.GroupBy(p => new PODemandPlanTemp { PurchseFNUMBER = p.PurchseFNUMBER, FHMASTERDATE = p.FHMASTERDATE }).Select(x => new PODemandPlanTemp { PurchseFNUMBER = x.Key.PurchseFNUMBER, FHMASTERDATE = x.Key.FHMASTERDATE }).ToList();
                var PODemandPlanList = PODemandPlanTemp.GroupBy(p => new { p.PurchseFNUMBER, p.FHMASTERDATE }).Select(x => new PODemandPlanTemp { PurchseFNUMBER = x.Key.PurchseFNUMBER, FHMASTERDATE = x.Key.FHMASTERDATE }).ToList();
                //LogHelper.Info($"提料计划,数据准备完成,保存到Model实体,总行数:{PODemandPlanTemp.Count}");
                int tlmmm = 0;
                JArray FinalyResult = new JArray();
 
                //LogService.Write("2");
 
                foreach (var item in PODemandPlanList)
                {
                    tlmmm++;
 
                    DateTime date = item.FHMASTERDATE;
                    string PurchseFNUMBER = item.PurchseFNUMBER;
                    //JObject model = new JObject();
                    //model.Add("FHDate", date);
                    //model.Add("FDeliveryDate", date.AddDays(-3));//供应商预计发货日期
                    //model.Add("FSettleCurrId", new JObject() { ["Fnumber"] = "PRE001" });
                    //model.Add("FSupplierID", new JObject() { ["Fnumber"] = PurchseFNUMBER });
 
                    var HInterID = DBUtility.ClsPub.CreateBillID("4608", ref DBUtility.ClsPub.sExeReturnInfo);
                    var HBillNo = DBUtility.ClsPub.CreateBillCode("4608", ref DBUtility.ClsPub.sExeReturnInfo, true);
 
                    var dataUser = oCN.RunProcReturn("select Czymc from gy_czygl where Czybm = '" + user + "'", "gy_czygl");
                    string HMaker = dataUser.Tables[0].Rows.Count == 0 ? "" : dataUser.Tables[0].Rows[0][0].ToString();//制单人
                    string HUpDater = dataUser.Tables[0].Rows.Count == 0 ? "" : dataUser.Tables[0].Rows[0][0].ToString();//修改人
                   
 
                    var dataOrg = oCN.RunProcReturn(@"select HItemID from Xt_ORGANIZATIONS o
                    inner join  "+ sqlName + @"..T_ORG_ORGANIZATIONS fo on o.HNumber=fo.FNUMBER
                    where FNUMBER='" + PODemandPlanTemp[0].FORGNumber + "'  and HItemID ='" + HProdORGID + "'", "Xt_ORGANIZATIONS");
                    long HPURCHASEORGID = dataOrg.Tables[0].Rows.Count == 0 ? 0 : long.Parse(dataOrg.Tables[0].Rows[0]["HItemID"].ToString()); //采购组织
 
                    var dataSup = oCN.RunProcReturn(@"select * from Gy_Supplier p
                    inner join  " + sqlName + @"..t_BD_Supplier fp on p.HNumber=fp.FNUMBER and p.HUSEORGID=fp.FUSEORGID
                    where FNUMBER='" + item.PurchseFNUMBER + "' and HUSEORGID ='" + HProdORGID + "'", "Gy_Supplier");
                    long HSupplierID = dataSup.Tables[0].Rows.Count == 0 ? 0 : long.Parse(dataSup.Tables[0].Rows[0]["HItemID"].ToString()); //供应商
 
                    long HSettleCurrId = 1;//货币 默认本地人民币
 
                    //主表
                    oCN.RunProc("insert into JIT_Cg_PODemandPlanBillMain(HInterID,HBillNo,HYear,HPeriod,HBillType" +
                                ",HBillSubType,HDate,HBillStatus,HMaker,HMakeDate" +
                                ",HSubORGID ,HAddress,HPURCHASEORGID,HSupplierID ,HSettleCurrId" +
                                ",HRemark,HExplanation,HUpDater,HUpDateDate)" +
                               $"values({HInterID}, '{HBillNo}', {DateTime.Now.Year}, {DateTime.Now.Month}, '4608'" +
                               $", '4608','{date}',1, '{HMaker}',GETDATE()," +
                               $"{HPURCHASEORGID},'',{HPURCHASEORGID}, {HSupplierID}, {HSettleCurrId}" +
                               $",'','','{HUpDater}',getdate())");
 
                    JArray Fentity = new JArray();
                    List<PODemandPlanTemp> _PODemandPlanList = PODemandPlanTemp.Where(x => x.FHMASTERDATE == date && x.PurchseFNUMBER == PurchseFNUMBER).ToList();
                    //LogService.Write("测试listmodel:" + _PODemandPlanList[0].FORGNumber.ToString());
                    int i = 0;
                    foreach (var _item in _PODemandPlanList)
                    {
                        i++;
                        //if (!model.ToString().Contains("FHPURCHASEORGID"))
                        //    model.Add("FHPURCHASEORGID", new JObject() { ["Fnumber"] = _item.FORGNumber });
                        //JObject FentityModel = new JObject();
                        //FentityModel.Add("FHPURCHASEORGID", new JObject() { ["Fnumber"] = _item.FORGNumber });//采购组织
                        //FentityModel.Add("FHMaterID", new JObject() { ["Fnumber"] = _item.FNumber });//物料
                        //FentityModel.Add("FHQty", _item.FQty);//数量
                        //FentityModel.Add("FHSourceInterID", _item.FID);//日计划工单FID
                        //FentityModel.Add("FHSourceEntryID", _item.FENTRYID);//日计划工单FENTRYID
                        //FentityModel.Add("FHSourceBillNo", _item.FBILLNO);//日计划工单单号
                        //FentityModel.Add("FHSourceBillType", "");//日计划工单类型
                        //FentityModel.Add("FDayPlanDate", _item.OLDDATE);//日计划工单类型
                        //FentityModel.Add("FHRelationQty", _item.PurchseFqty);//关联数量
                        //FentityModel.Add("FFIXLEADTIME", _item.FFIXLEADTIME);//提前期
                        //FentityModel.Add("FPURCHASEORGID", new JObject() { ["Fnumber"] = _item.FORGNumber });//采购组织
                        //FentityModel.Add("FHPOOrderInterID", _item.PurchseFID);// 采购订单内码:FHPOOrderInterID
                        //FentityModel.Add("FHPOOrderEntryID", _item.PurchseFentryID); //采购订单子内码:FHPOOrderEntryID
                        //FentityModel.Add("FHPOOrderBillNo", _item.PurchseFBillNo); //采购订单号:FHPOOrderBillNo
                        //FentityModel.Add("FERPCLSID", _item.FErpClsID); //发料方式
                        //FentityModel.Add("FUnitID", new JObject() { ["Fnumber"] = "Pcs" }); //发料方式
                        //Fentity.Add(FentityModel);
 
 
                        var dataSet = oCN.RunProcReturn(@"select m.* from Gy_Material m
                        inner join  " + sqlName + @"..T_BD_MATERIAL fm on m.HNumber = fm.FNUMBER and m.HUSEORGID=fm.FUSEORGID
                        where FNUMBER='" + _item.FNumber + "'  and HUSEORGID ='" + HProdORGID + "'", "Gy_Material");
                        string HMaterID = "0"; //物料
                        string HMaterModel = ""; //物料代码
                        string HMaterName = ""; //物料名称
                        if (dataSet.Tables[0].Rows.Count != 0)
                        {
                            HMaterID = dataSet.Tables[0].Rows[0]["HItemID"].ToString(); //物料
                            HMaterModel = dataSet.Tables[0].Rows[0]["HNumber"].ToString(); //物料代码
                            HMaterName = dataSet.Tables[0].Rows[0]["HName"].ToString(); //物料名称
                        }
 
                        decimal HQty = _item.FQty; //数量
                        long HSourceInterID = _item.FID; //日计划工单FID
                        long HSourceEntryID = _item.FENTRYID;//日计划工单FENTRYID
                        string HSourceBillNo = _item.FBILLNO; //生产订单号
                        string HSourceBillType = ""; //日计划工单类型
                        DateTime HDayPlanDate = _item.OLDDATE; // 工单生产日期
                        decimal HRelationQty = _item.PurchseFqty; // 关联数量
                        double HFixleadTime = _item.FFIXLEADTIME; // 提前期
 
                        dataOrg = oCN.RunProcReturn(@"select HItemID from Xt_ORGANIZATIONS o
                    inner join  " + sqlName + @"..T_ORG_ORGANIZATIONS fo on o.HNumber=fo.FNUMBER
                    where FNUMBER='" + _item.FORGNumber + "'  and HItemID ='" + HProdORGID + "'", "Xt_ORGANIZATIONS");
                        long HPURCHASEORGIDSub = dataOrg.Tables[0].Rows.Count == 0 ? 0 : long.Parse(dataOrg.Tables[0].Rows[0]["HItemID"].ToString()); // 采购组织
                        long HPOOrderInterID = _item.PurchseFID; // 采购订单内码
                        long HPOOrderEntryID = _item.PurchseFentryID; // 采购订单子内码
                        string HPOOrderBillNo = _item.PurchseFBillNo; // 采购订单号
                        string HErpClsID = _item.FErpClsID; // 物料属性
                        long HUnitID = 10101; // 计量单位  先按照本地来  默认 Pcs
                        string HSeOrderBillNo = _item.FXQD; // 销售订单号   需求单号
                        string HOrderEmpID = _item.FCREATORID; // 采购员  
                        DateTime HPOOrderBillDate = _item.FDate; // 采购订单单据日期  
                        DateTime HPOOrderBillDeliveryDate = _item.FDeliveryDate; // 采购订单交货日期  
                        string HPOOrderBillRemark = _item.F_QIMB_NOTE; // 采购订单摘要  
                        string HPOOrderBillNote = _item.FNOTE; // 采购订单表体备注  
                        string HDayPlanBillNo = _item.FDAYPLANBILLNO; // 日计划工单号  
 
                        dataSet = oCN.RunProcReturn(@"select HItemID from Gy_Department d
                        inner join  " + sqlName + @"..T_BD_DEPARTMENT fd on d.HNumber = fd.FNUMBER
                        where FNUMBER='" + _item.FWORKSHOPNUMBER + "'  and HUSEORGID ='" + HProdORGID + "'", "Gy_Department");
                        HWorkShopID = dataSet.Tables[0].Rows.Count == 0 ? "0" : dataSet.Tables[0].Rows[0][0].ToString(); // 生产车间  
 
                        dataSet = oCN.RunProcReturn(@"select HItemID from Gy_Department d
                        inner join  " + sqlName + @"..T_BD_DEPARTMENT fd on d.HNumber = fd.FNUMBER
                        where FNUMBER='" + _item.FPURCHASEDEPTNUMBER + "'  and HUSEORGID ='" + HProdORGID + "'", "Gy_Department");
                        string HPurchaseDeptID = dataSet.Tables[0].Rows.Count == 0 ? "0" : dataSet.Tables[0].Rows[0][0].ToString(); // 采购部门  
 
                        decimal HPURCHASEQTY = _item.FPURCHASEQTY; // 采购订单数量  
                        decimal HJoinQty = _item.FJOINQTY; // 采购订单关联数量  
 
                        oCN.RunProc("insert into JIT_Cg_PODemandPlanBillSub(HInterID,HEntryID,HLaterReason,HMaterID,HMaterName" +
                          ", HMaterModel, HUnitID, HErpClsID, HQty, HRemark" +
                          ", HPURCHASEORGID, HStatus, HFixleadTime, HDayPlanBillNo, HSourceInterID" +
                          ", HSourceEntryID, HSourceBillNo, HSourceBillType, HWorkShopID, HDayPlanDate" +
                          ", HRelationQty1, HPOOrderInterID, HPOOrderEntryID, HPOOrderBillNo, HPOOrderBillSEQ" +
                          ", HWWOrderInterID, HWWOrderEntryID, HWWOrderBillNo, HPurchaseDeptID, HCloseTypeSub" +
                          ", HCloseMan, HEntryCloseDate, HSendQty, HReciveQty, HCloseStatus" +
                          ", HRemoveQty, HSeOrderBillNo, HUnReciveQty, HPOOrderBillDate, HPOOrderBillDeliveryDate" +
                          ", HPOOrderBillRemark, HPOOrderBillNote)" +
                          $"values({HInterID}, {i}, '', {(HMaterID == null ? "0" : HMaterID)}, '{HMaterName}'" +
                          $", '{HMaterModel}', {HUnitID}, '{HErpClsID}', {HQty}, ''" +
                          $", {HPURCHASEORGIDSub}, '', {HFixleadTime}, '{HDayPlanBillNo}', {HSourceInterID}" +
                          $", {HSourceEntryID}, '{HSourceBillNo}', '{HSourceBillType}', {HWorkShopID}, '{HDayPlanDate}'" +
                          $", {HRelationQty}, {HPOOrderInterID},{HPOOrderEntryID}, '{HPOOrderBillNo}',0" +
                          $",0,0, '',{HPurchaseDeptID}, '0'" +
                          $", '','',0,0, '0'" +
                          $",0, '{HSeOrderBillNo}',0, '{HPOOrderBillDate}', '{HPOOrderBillDeliveryDate}'" +
                          $", '{HPOOrderBillRemark}', '{HPOOrderBillNote}')");
 
                    }
                    //model.Add("FEntity", Fentity);
                    //FinalyResult.Add(model);
                    //    if ((tlmmm >= 20 || tlmmm == PODemandPlanList.Count) && (tlmmm % 20 == 0 || tlmmm == PODemandPlanList.Count))
                    //    {
                    //        //LogHelper.Info("提料计划新增批量执行,记录循环的当前条数" + tlmmm);
                    //        JObject jsonRoot = new JObject()
                    //        {
                    //            ["Creator"] = "",
                    //            ["NeedUpDateFields"] = new JArray(),
                    //            ["NeedReturnFields"] = new JArray(),
                    //            ["IsDeleteEntry"] = "false",
                    //            ["SubSystemId"] = "",
                    //            ["IsVerifyBaseDataField"] = "false",
                    //            ["Model"] = FinalyResult
                    //        };
                    //        CloudClient cloudClient = new CloudClient("http://localhost//k3cloud/");
                    //        var result = cloudClient.BatchSave("paez_PODemandPlan", jsonRoot.ToString());
                    //        JObject saveObj = JObject.Parse(result);
                    //        string saveIsSuc = saveObj["Result"]["ResponseStatus"]["IsSuccess"].ToString().ToUpper();
                    //        if (saveIsSuc != "TRUE")
                    //        {
                    //            //LogHelper.Error(jsonRoot.ToString());
                    //        }
                    //        FinalyResult = new JArray();
                    //    }
                    //    tlmmm++;
                }
 
                //LogService.Write("3");
                if (Error != "")
                {
                    oCN.Commit();
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "运算成功!" + Error;
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                else if (tlmmm == PODemandPlanList.Count && tlmmm != 0)
                {
                    oCN.Commit();
                    objJsonResult.code = "1";
                    objJsonResult.count = 1;
                    objJsonResult.Message = "运算成功!" + Error;
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                else
                {
                    oCN.RollBack();//事务回滚
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "运算失败!" + Error;
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                ////sw.Stop();//结束计时
                //////LogHelper.Info("提料计划执行完成,运行总时长:" + sw.Elapsed);
                //DBServiceHelper.ExecuteBatch(Context, sqlList);
 
                //objJsonResult.code = "1";
                //objJsonResult.count = 1;
                //objJsonResult.Message = "提料运算成功!";
                //objJsonResult.data = null;
                //return objJsonResult;
            }
            catch (Exception e)
            {
                LogService.Write("操作失败:" + e.Message.ToString());
                oCN.RollBack();//事务回滚
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.Message.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
 
        }
 
        /// <summary>
        /// 通过生产用料清单 算缺料情况
        /// </summary>
        /// <returns></returns>
        public object JIT_PPBOM(string fProWorkShopId,int? fPrdOrgId,string user,string sqlName) {
 
            try
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();//开始计时
                           //提料计划预处理 清理提料计划单数据 更新采购订单提料计划数量 并且查询出需要进行运算的数据
 
                oCN.BeginTran();  //开始事务
 
                ds = oCN.RunProcReturn($"exec h_p_PROC_JIT_TLPLANYCL '{fProWorkShopId}','{fPrdOrgId}'", "h_p_PROC_JIT_TLPLANYCL");
                List<DayPlanPpbom> DayPlanPpbom = ds.ToModelList<DayPlanPpbom>();
 
                if (DayPlanPpbom.Count == 0)
                {
                    oCN.RollBack();//回滚事务
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "无数据运算!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                //采购订单数据 (剩余收料数量)
 
                //t2.FXQD  t2.FSTOCKINQTY,t2.FReceiveQty 本地没有这些字段
                string sql = string.Format(@"
select * from h_v_jit_POOrderList where FQTY>0 and FCloseStatus in('A') 
and FMRPCLOSESTATUS in('A') and FBillTypeID in('83d822ca3e374b4ab01e5dd46a0062bd','6d01d059713d42a28bb976c90a121142') and FStockOrgId = '{0}'", fPrdOrgId);
 
                ds = oCN.RunProcReturn(sql, "h_v_jit_POOrderList");
 
                if (ds.Tables[0].Rows.Count == 0)
                {
                    oCN.RollBack();//回滚事务
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "查无采购订单数据!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                List<PurchaseInventory> PurchaseInventory = ds.ToModelList<PurchaseInventory>();
                //物料+库存组织分类
                var MaterialIDList = DayPlanPpbom.GroupBy(p => new { p.FMATERIALID, p.FStockOrgId }).Select(x => new PODemandPlanTemp { FMATERIALID = x.Key.FMATERIALID, FStockOrgId = x.Key.FStockOrgId }).ToList();
 
                //提料计划数据集临时存储集合
                List<PODemandPlanTemp> PODemandPlanTemp = new List<PODemandPlanTemp>();
                //sql集合 更新采购订单占用的提料计划数量
                List<string> sqlList = new List<string>();
 
                foreach (var item in MaterialIDList)
                {
                    //this.View.Session["ProcessRateValue"] = Convert.ToInt32((Convert.ToDecimal(75) / MaterialIDList.Count) * i);
                    //当前物料和库存组织对应的需进行提料计划的数据    
                    List<DayPlanPpbom> _DayPlanPpbom = DayPlanPpbom.Where(x => x.FMATERIALID == item.FMATERIALID && x.FStockOrgId == item.FStockOrgId).ToList();
                    decimal NeedQty = 0;
                    foreach (var _item in _DayPlanPpbom)
                    {
                        //查询有没有可以用于提料的采购订单数据
                        var _PurchaseInventory = PurchaseInventory.Where(x => x.FMATERIALID == item.FMATERIALID && x.FStockOrgId == item.FStockOrgId && x.FQTY > 0).OrderBy(x => x.FENTRYID).ToList();
                        if (_PurchaseInventory.Count == 0)
                        {
                            //无采购订单直接下一个物料
                            sql = $"INSERT INTO JIT_TLPLANERROR(HROGID,HUSERID,HWORKSHOPID,HDAYPLANID,HDAYPLANENTRYID,HMATERIALID,HQTY,HTYPE) VALUES({fPrdOrgId},{user},{fProWorkShopId},{_item.FID},{_item.FENTRYID},{_item.FMATERIALID},{_item.NeedQty},0) ";
                            sqlList.Add(sql);
                            break;
                        }
                        //需求数量
                        NeedQty = _item.NeedQty;
                        //增加一个销售订单号匹配的逻辑 优先循环
                        var PurchaseInventoryBySalOrder = _PurchaseInventory.Where(x => x.FXQD == _item.FXQD).OrderBy(x => x.FENTRYID).ToList();
                        if (PurchaseInventoryBySalOrder.Count > 0)
                        {
                            foreach (var Purchase in PurchaseInventoryBySalOrder)
                            {
                                double _FFIXLEADTIME = Purchase.FFIXLEADTIME;//提前期
                                DateTime _DATE = Convert.ToDateTime(_item.FHMASTERDATE).AddDays(-_FFIXLEADTIME);
                                if (Purchase.FQTY >= NeedQty)
                                {
                                    PODemandPlanTemp.Add(new PODemandPlanTemp
                                    {
                                        FID = _item.FID,
                                        FHMASTERDATE = _DATE,
                                        FQty = NeedQty,
                                        FBILLNO = _item.FBILLNO,
                                        FENTRYID = _item.FENTRYID,
                                        FMATERIALID = _item.FMATERIALID,
                                        FNumber = _item.FNumber,
                                        OLDDATE = _item.FHMASTERDATE,
                                        FFIXLEADTIME = _FFIXLEADTIME,
                                        FErpClsID = _item.FErpClsID,
                                        FWORKSHOPNUMBER = _item.FWORKSHOPNUMBER,
                                        FDAYPLANBILLNO = _item.FDAYPLANBILLNO,
 
                                        PurchseFentryID = Purchase.FENTRYID,
                                        FSUPPLIERID = Purchase.FSUPPLIERID,
                                        PurchseFNUMBER = Purchase.FNUMBER,
                                        PurchseFBillNo = Purchase.FBillNo,
                                        PurchseFqty = Purchase.FQTY,
                                        FStockOrgId = Purchase.FStockOrgId, //采购组织
                                        FORGNumber = Purchase.FORGNumber,
                                        FPURCHASEDEPTNUMBER = Purchase.FPURCHASEDEPTNUMBER,
 
                                        FXQD = _item.FXQD,
                                        FCREATORID = Purchase.FCREATORID,
                                        FName = Purchase.FName,
                                        FDate = Purchase.FDate,
                                        FDeliveryDate = Purchase.FDeliveryDate,
                                        F_QIMB_NOTE = Purchase.F_QIMB_NOTE,
                                        FNOTE = Purchase.FNOTE,
                                        FPURCHASEQTY = Purchase.FPURCHASEQTY,
                                        FJOINQTY = Purchase.FJOINQTY
 
                                    });
                                    //扣除日计划明细已被分配的数量
                                    _item.NeedQty = 0;
                                    //扣除当前行对应采购订单数量
                                    Purchase.FQTY -= NeedQty;
                                    //更新采购订单
                                    //sqlList.Add($"/*dialect*/ update t_PUR_POOrderEntry set FPODemandPlanCount  =isnull(FPODemandPlanCount,0)+  '{NeedQty}' where FENTRYID = {Purchase.FENTRYID}");
                                    //需求数量变为0
                                    NeedQty = 0;
                                    break;
                                }
                                else//采购订单数据不能满足订单所需数量
                                {
                                    //采购订单数量
                                    decimal _NeedQty = Purchase.FQTY;
                                    PODemandPlanTemp.Add(new PODemandPlanTemp
                                    {
                                        FID = _item.FID,
                                        FHMASTERDATE = _DATE,
                                        FQty = _NeedQty,
                                        FBILLNO = _item.FBILLNO,
                                        FENTRYID = _item.FENTRYID,
                                        FMATERIALID = _item.FMATERIALID,
                                        FNumber = _item.FNumber,
                                        OLDDATE = _item.FHMASTERDATE,
                                        FFIXLEADTIME = _FFIXLEADTIME,
                                        FErpClsID = _item.FErpClsID,
                                        FWORKSHOPNUMBER = _item.FWORKSHOPNUMBER,
                                        FDAYPLANBILLNO = _item.FDAYPLANBILLNO,
 
                                        PurchseFentryID = Purchase.FENTRYID,
                                        FSUPPLIERID = Purchase.FSUPPLIERID,
                                        PurchseFNUMBER = Purchase.FNUMBER,
                                        PurchseFBillNo = Purchase.FBillNo,
                                        PurchseFqty = Purchase.FQTY,
                                        FStockOrgId = Purchase.FStockOrgId, //采购组织
                                        FORGNumber = Purchase.FORGNumber,
                                        FPURCHASEDEPTNUMBER = Purchase.FPURCHASEDEPTNUMBER,
 
                                        FXQD = _item.FXQD,
                                        FCREATORID = Purchase.FCREATORID,
                                        FName = Purchase.FName,
                                        FDate = Purchase.FDate,
                                        FDeliveryDate = Purchase.FDeliveryDate,
                                        F_QIMB_NOTE = Purchase.F_QIMB_NOTE,
                                        FNOTE = Purchase.FNOTE,
                                        FPURCHASEQTY = Purchase.FPURCHASEQTY,
                                        FJOINQTY = Purchase.FJOINQTY
                                    });
                                    //更新采购订单
                                    //sqlList.Add($"/*dialect*/ update t_PUR_POOrderEntry set FPODemandPlanCount = isnull(FPODemandPlanCount,0)+ '{Purchase.FQTY}' where FENTRYID = {Purchase.FENTRYID}");
                                    //更新订单需求数量
                                    NeedQty = NeedQty - Purchase.FQTY;
                                    //扣除日计划明细已被分配的数量
                                    _item.NeedQty -= _NeedQty;
                                    //扣除当前行对应采购订单数量
                                    Purchase.FQTY = 0;
                                }
                            }
                        }
                        if (NeedQty == 0)
                            continue;
                        var PurchaseInventoryElse = _PurchaseInventory.Where(x => x.FXQD != _item.FXQD).OrderBy(x => x.FENTRYID).ToList();
                        foreach (var Purchase in PurchaseInventoryElse)
                        {
                            double _FFIXLEADTIME = Purchase.FFIXLEADTIME;//提前期
                            DateTime _DATE = Convert.ToDateTime(_item.FHMASTERDATE).AddDays(-_FFIXLEADTIME);
                            if (Purchase.FQTY >= NeedQty)
                            {
                                PODemandPlanTemp.Add(new PODemandPlanTemp
                                {
                                    FID = _item.FID,
                                    FHMASTERDATE = _DATE,
                                    FQty = _item.NeedQty,
                                    FBILLNO = _item.FBILLNO,
                                    FENTRYID = _item.FENTRYID,
                                    FMATERIALID = _item.FMATERIALID,
                                    FNumber = _item.FNumber,
                                    OLDDATE = _item.FHMASTERDATE,
                                    FFIXLEADTIME = _FFIXLEADTIME,
                                    FErpClsID = _item.FErpClsID,
                                    FWORKSHOPNUMBER = _item.FWORKSHOPNUMBER,
                                    FDAYPLANBILLNO = _item.FDAYPLANBILLNO,
 
                                    PurchseFentryID = Purchase.FENTRYID,
                                    FSUPPLIERID = Purchase.FSUPPLIERID,
                                    PurchseFNUMBER = Purchase.FNUMBER,
                                    PurchseFBillNo = Purchase.FBillNo,
                                    PurchseFqty = Purchase.FQTY,
                                    FStockOrgId = Purchase.FStockOrgId, //采购组织
                                    FORGNumber = Purchase.FORGNumber,
                                    FPURCHASEDEPTNUMBER = Purchase.FPURCHASEDEPTNUMBER,
 
                                    FXQD = _item.FXQD,
                                    FCREATORID = Purchase.FCREATORID,
                                    FName = Purchase.FName,
                                    FDate = Purchase.FDate,
                                    FDeliveryDate = Purchase.FDeliveryDate,
                                    F_QIMB_NOTE = Purchase.F_QIMB_NOTE,
                                    FNOTE = Purchase.FNOTE,
                                    FPURCHASEQTY = Purchase.FPURCHASEQTY,
                                    FJOINQTY = Purchase.FJOINQTY
                                });
                                //更新采购订单
                                //sqlList.Add($"/*dialect*/ update t_PUR_POOrderEntry set FPODemandPlanCount  =isnull(FPODemandPlanCount,0)+  '{NeedQty}' where FENTRYID = {Purchase.FENTRYID}");
                                //扣除日计划明细已被分配的数量
                                _item.NeedQty = 0;
                                //扣除当前行对应采购订单数量
                                Purchase.FQTY -= NeedQty;
                                //需求数量变为0
                                NeedQty = 0;
                                break;
                            }
                            else//采购订单数据不能满足订单所需数量
                            {
                                //更新总需求数量
                                NeedQty = NeedQty - Purchase.FQTY;
                                //采购订单数量
                                decimal _NeedQty = Purchase.FQTY;
                                PODemandPlanTemp.Add(new PODemandPlanTemp
                                {
                                    FID = _item.FID,
                                    FHMASTERDATE = _DATE,
                                    FQty = _NeedQty,
                                    FBILLNO = _item.FBILLNO,
                                    FENTRYID = _item.FENTRYID,
                                    FMATERIALID = _item.FMATERIALID,
                                    FNumber = _item.FNumber,
                                    OLDDATE = _item.FHMASTERDATE,
                                    FFIXLEADTIME = _FFIXLEADTIME,
                                    FErpClsID = _item.FErpClsID,
                                    FWORKSHOPNUMBER = _item.FWORKSHOPNUMBER,
                                    FDAYPLANBILLNO = _item.FDAYPLANBILLNO,
 
                                    PurchseFentryID = Purchase.FENTRYID,
                                    FSUPPLIERID = Purchase.FSUPPLIERID,
                                    PurchseFNUMBER = Purchase.FNUMBER,
                                    PurchseFBillNo = Purchase.FBillNo,
                                    PurchseFqty = Purchase.FQTY,
                                    FStockOrgId = Purchase.FStockOrgId, //采购组织
                                    FORGNumber = Purchase.FORGNumber,
                                    FPURCHASEDEPTNUMBER = Purchase.FPURCHASEDEPTNUMBER,
 
                                    FXQD = _item.FXQD,
                                    FCREATORID = Purchase.FCREATORID,
                                    FName = Purchase.FName,
                                    FDate = Purchase.FDate,
                                    FDeliveryDate = Purchase.FDeliveryDate,
                                    F_QIMB_NOTE = Purchase.F_QIMB_NOTE,
                                    FNOTE = Purchase.FNOTE,
                                    FPURCHASEQTY = Purchase.FPURCHASEQTY,
                                    FJOINQTY = Purchase.FJOINQTY
                                });
                                //更新采购订单
                                //sqlList.Add($"/*dialect*/ update t_PUR_POOrderEntry set FPODemandPlanCount = isnull(FPODemandPlanCount,0)+ '{Purchase.FQTY}' where FENTRYID = {Purchase.FENTRYID}");
                                //扣除日计划明细已被分配的数量
                                _item.NeedQty -= _NeedQty;
                                //扣除当前行对应采购订单数量
                                Purchase.FQTY = 0;
                            }
                        }
                        if (NeedQty > 0)
                        {
                            sql = $"INSERT INTO JIT_TLPLANERROR(HROGID,HUSERID,HWORKSHOPID,HDAYPLANID,HDAYPLANENTRYID,HMATERIALID,HQTY,HTYPE,HERRORTYPE) VALUES({fPrdOrgId},{user},{fProWorkShopId},{_item.FID},{_item.FENTRYID},{_item.FMATERIALID},{NeedQty},0,1) ";
                            sqlList.Add(sql);
                        }
                    }
                }
 
                //供应商,提料日期,生产车间,采购员 分组
                var PODemandPlanList = PODemandPlanTemp.GroupBy(p => new { p.PurchseFNUMBER, p.FHMASTERDATE, p.FWORKSHOPNUMBER, p.FCREATORID }).Select(x => new PODemandPlanTemp { PurchseFNUMBER = x.Key.PurchseFNUMBER, FHMASTERDATE = x.Key.FHMASTERDATE, FWORKSHOPNUMBER = x.Key.FWORKSHOPNUMBER, FCREATORID = x.Key.FCREATORID }).ToList();
 
                LogService.Write("提料计划重算 ,数据准备完成,保存到Model实体 用时:" + sw.Elapsed + "总行数:" + PODemandPlanTemp.Count);
 
                int tlmmm = 0;
                JArray FinalyResult = new JArray();
                foreach (var item in PODemandPlanList)
                {
                    tlmmm++;
 
                    DateTime date = item.FHMASTERDATE;
                    long HSettleCurrId = 1;//货币 默认本地人民币
 
                    var dataSup = oCN.RunProcReturn(@"select * from Gy_Supplier p
                    inner join  " + sqlName + @"..t_BD_Supplier fp on p.HNumber=fp.FNUMBER and p.HUSEORGID=fp.FUSEORGID
                    where FNUMBER='" + item.PurchseFNUMBER + "' and HUSEORGID ='" + fPrdOrgId + "'", "Gy_Supplier");
                    long HSupplierID = dataSup.Tables[0].Rows.Count == 0 ? 0 : long.Parse(dataSup.Tables[0].Rows[0]["HItemID"].ToString()); //供应商
 
                    var dataUser = oCN.RunProcReturn("select Czymc from gy_czygl where Czybm = '" + user + "'", "gy_czygl");
                    string HMaker = dataUser.Tables[0].Rows.Count == 0 ? "" : dataUser.Tables[0].Rows[0][0].ToString();//制单人
                    string HUpDater = dataUser.Tables[0].Rows.Count == 0 ? "" : dataUser.Tables[0].Rows[0][0].ToString();//修改人
 
                    var dataOrg = oCN.RunProcReturn(@"select HItemID from Xt_ORGANIZATIONS o
                    inner join  " + sqlName + @"..T_ORG_ORGANIZATIONS fo on o.HNumber=fo.FNUMBER
                    where FNUMBER='" + PODemandPlanTemp[0].FORGNumber + "'  and HItemID ='" + fPrdOrgId + "'", "Xt_ORGANIZATIONS");
                    long HPURCHASEORGID = dataOrg.Tables[0].Rows.Count == 0 ? 0 : long.Parse(dataOrg.Tables[0].Rows[0]["HItemID"].ToString()); //采购组织
 
                    string PurchseFNUMBER = item.PurchseFNUMBER;
                    string FWorkshopNumber = item.FWORKSHOPNUMBER;
                    string FCreatorID = item.FCREATORID;
 
                    var HInterID = DBUtility.ClsPub.CreateBillID("4608", ref DBUtility.ClsPub.sExeReturnInfo);
                    var HBillNo = DBUtility.ClsPub.CreateBillCode("4608", ref DBUtility.ClsPub.sExeReturnInfo, true);
                    //主表
                    oCN.RunProc("insert into JIT_Cg_PODemandPlanBillMain(HInterID,HBillNo,HYear,HPeriod,HBillType" +
                                ",HBillSubType,HDate,HBillStatus,HMaker,HMakeDate" +
                                ",HSubORGID ,HAddress,HPURCHASEORGID,HSupplierID ,HSettleCurrId" +
                                ",HRemark,HExplanation,HUpDater,HUpDateDate)" +
                               $"values({HInterID}, '{HBillNo}', {DateTime.Now.Year}, {DateTime.Now.Month}, '4608'" +
                               $", '4608','{date}',1, '{HMaker}',GETDATE()," +
                               $"{HPURCHASEORGID},'',{HPURCHASEORGID}, {HSupplierID}, {HSettleCurrId}" +
                               $",'','','{HUpDater}',getdate())");
 
                    List<PODemandPlanTemp> _PODemandPlanList = PODemandPlanTemp.Where(x => x.FHMASTERDATE == date && x.PurchseFNUMBER == PurchseFNUMBER && x.FWORKSHOPNUMBER == FWorkshopNumber && x.FCREATORID == FCreatorID).ToList();
                    int i = 0;
                    foreach (var _item in _PODemandPlanList)
                    {
                        i++;
 
                        var dataSet = oCN.RunProcReturn(@"select m.* from Gy_Material m
                        inner join  " + sqlName + @"..T_BD_MATERIAL fm on m.HNumber = fm.FNUMBER and m.HUSEORGID=fm.FUSEORGID
                        where FNUMBER='" + _item.FNumber + "'  and HUSEORGID ='" + fPrdOrgId + "'", "Gy_Material");
                        string HMaterID = "0"; //物料
                        string HMaterModel = ""; //物料代码
                        string HMaterName = ""; //物料名称
                        if (dataSet.Tables[0].Rows.Count != 0)
                        {
                            HMaterID = dataSet.Tables[0].Rows[0]["HItemID"].ToString(); //物料
                            HMaterModel = dataSet.Tables[0].Rows[0]["HNumber"].ToString(); //物料代码
                            HMaterName = dataSet.Tables[0].Rows[0]["HName"].ToString(); //物料名称
                        }
 
                        decimal HQty = _item.FQty; //数量
                        long HSourceInterID = _item.FID; //日计划工单FID
                        long HSourceEntryID = _item.FENTRYID;//日计划工单FENTRYID
                        string HSourceBillNo = _item.FBILLNO; //生产订单号
                        string HSourceBillType = ""; //日计划工单类型
                        DateTime HDayPlanDate = _item.OLDDATE; // 工单生产日期
                        decimal HRelationQty = _item.PurchseFqty; // 关联数量
                        double HFixleadTime = _item.FFIXLEADTIME; // 提前期
 
                        dataOrg = oCN.RunProcReturn(@"select HItemID from Xt_ORGANIZATIONS o
                    inner join  " + sqlName + @"..T_ORG_ORGANIZATIONS fo on o.HNumber=fo.FNUMBER
                    where FNUMBER='" + _item.FORGNumber + "'  and HItemID ='" + fPrdOrgId + "'", "Xt_ORGANIZATIONS");
                        long HPURCHASEORGIDSub = dataOrg.Tables[0].Rows.Count == 0 ? 0 : long.Parse(dataOrg.Tables[0].Rows[0]["HItemID"].ToString()); // 采购组织
                        long HPOOrderInterID = _item.PurchseFID; // 采购订单内码
                        long HPOOrderEntryID = _item.PurchseFentryID; // 采购订单子内码
                        string HPOOrderBillNo = _item.PurchseFBillNo; // 采购订单号
                        string HErpClsID = _item.FErpClsID; // 物料属性
                        long HUnitID = 10101; // 计量单位  先按照本地来  默认 Pcs
                        string HSeOrderBillNo = _item.FXQD; // 销售订单号   需求单号
                        string HOrderEmpID = _item.FCREATORID; // 采购员  
                        DateTime HPOOrderBillDate = _item.FDate; // 采购订单单据日期  
                        DateTime HPOOrderBillDeliveryDate = _item.FDeliveryDate; // 采购订单交货日期  
                        string HPOOrderBillRemark = _item.F_QIMB_NOTE; // 采购订单摘要  
                        string HPOOrderBillNote = _item.FNOTE; // 采购订单表体备注  
                        string HDayPlanBillNo = _item.FDAYPLANBILLNO; // 日计划工单号  
 
                        dataSet = oCN.RunProcReturn(@"select HItemID from Gy_Department d
                        inner join  " + sqlName + @"..T_BD_DEPARTMENT fd on d.HNumber = fd.FNUMBER
                        where FNUMBER='" + _item.FWORKSHOPNUMBER + "'  and HUSEORGID ='" + fPrdOrgId + "'", "Gy_Department");
                        string HWorkShopID = dataSet.Tables[0].Rows.Count == 0 ? "0" : dataSet.Tables[0].Rows[0][0].ToString(); // 生产车间  
 
                        dataSet = oCN.RunProcReturn(@"select HItemID from Gy_Department d
                        inner join  " + sqlName + @"..T_BD_DEPARTMENT fd on d.HNumber = fd.FNUMBER
                        where FNUMBER='" + _item.FPURCHASEDEPTNUMBER + "'  and HUSEORGID ='" + fPrdOrgId + "'", "Gy_Department");
                        string HPurchaseDeptID = dataSet.Tables[0].Rows.Count == 0 ? "0" : dataSet.Tables[0].Rows[0][0].ToString(); // 采购部门  
 
                        decimal HPURCHASEQTY = _item.FPURCHASEQTY; // 采购订单数量  
                        decimal HJoinQty = _item.FJOINQTY; // 采购订单关联数量  
 
                        oCN.RunProc("insert into JIT_Cg_PODemandPlanBillSub(HInterID,HEntryID,HLaterReason,HMaterID,HMaterName" +
                           ", HMaterModel, HUnitID, HErpClsID, HQty, HRemark" +
                           ", HPURCHASEORGID, HStatus, HFixleadTime, HDayPlanBillNo, HSourceInterID" +
                           ", HSourceEntryID, HSourceBillNo, HSourceBillType, HWorkShopID, HDayPlanDate" +
                           ", HRelationQty1, HPOOrderInterID, HPOOrderEntryID, HPOOrderBillNo, HPOOrderBillSEQ" +
                           ", HWWOrderInterID, HWWOrderEntryID, HWWOrderBillNo, HPurchaseDeptID, HCloseTypeSub" +
                           ", HCloseMan, HEntryCloseDate, HSendQty, HReciveQty, HCloseStatus" +
                           ", HRemoveQty, HSeOrderBillNo, HUnReciveQty, HPOOrderBillDate, HPOOrderBillDeliveryDate" +
                           ", HPOOrderBillRemark, HPOOrderBillNote)" +
                           $"values({HInterID}, {i}, '', {(HMaterID == null ? "0" : HMaterID)}, '{HMaterName}'" +
                           $", '{HMaterModel}', {HUnitID}, '{HErpClsID}', {HQty}, ''" +
                           $", {HPURCHASEORGIDSub}, '', {HFixleadTime}, '{HDayPlanBillNo}', {HSourceInterID}" +
                           $", {HSourceEntryID}, '{HSourceBillNo}', '{HSourceBillType}', {HWorkShopID}, '{HDayPlanDate}'" +
                           $", {HRelationQty}, {HPOOrderInterID},{HPOOrderEntryID}, '{HPOOrderBillNo}',0" +
                           $",0,0, '',{HPurchaseDeptID}, '0'" +
                           $", '','',0,0, '0'" +
                           $",0, '{HSeOrderBillNo}',0, '{HPOOrderBillDate}', '{HPOOrderBillDeliveryDate}'" +
                           $", '{HPOOrderBillRemark}', '{HPOOrderBillNote}')");
                    }
                }
 
                if (tlmmm == PODemandPlanList.Count)
                {
                    oCN.Commit();
                    objJsonResult.code = "1";
                    objJsonResult.count = 1;
                    objJsonResult.Message = "运算成功!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                else
                {
                    oCN.RollBack();//事务回滚
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "运算失败!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
            }
            catch (Exception e)
            {
                LogService.Write("操作失败:" + e.Message.ToString());
                oCN.RollBack();//事务回滚
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.Message.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
 
        /// <summary>
        /// 通过欠料表   算提料 宝工
        /// </summary>
        /// <returns></returns>
        public object JIT_MOMaterLack(string HWorkShopID, int? HProdORGID, string user)
        {
            try
            {
                ds = oCN.RunProcReturn("exec h_p_JIT_PODemandPlanBill_MOMaterLack " + HWorkShopID.ToString() + ",'" + user + "'," + HProdORGID.ToString(), "h_p_JIT_PODemandPlanBill_MOMaterLack");
                if (ds == null || ds.Tables[0].Rows.Count == 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "提料运算发生错误!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                else if (DBUtility.ClsPub.isLong(ds.Tables[0].Rows[0]["HBack"]) == 1)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = DBUtility.ClsPub.isStrNull(ds.Tables[0].Rows[0]["HRemark"]);
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                else
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 1;
                    objJsonResult.Message = DBUtility.ClsPub.isStrNull(ds.Tables[0].Rows[0]["HRemark"]);    //运算成功
                    objJsonResult.data = null;
                    return objJsonResult;
                }
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "提料运算失败!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
 
        /// <summary>
        /// 通过齐套表   算提料
        /// </summary>
        /// <returns></returns>
        public object JIT_MOMaterReady(string HWorkShopID, int? HProdORGID, string user)
        {
            try
            {
                ds = oCN.RunProcReturn("exec h_p_JIT_PODemandPlanBill_MOMaterReady " + HWorkShopID.ToString() + ",'" + user + "'," + HProdORGID.ToString(), "h_p_JIT_PODemandPlanBill_MOMaterReady");
                if (ds == null || ds.Tables[0].Rows.Count == 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "提料运算发生错误!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                else if (DBUtility.ClsPub.isLong(ds.Tables[0].Rows[0]["HBack"]) == 1)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = DBUtility.ClsPub.isStrNull(ds.Tables[0].Rows[0]["HRemark"]);
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                else
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 1;
                    objJsonResult.Message = DBUtility.ClsPub.isStrNull(ds.Tables[0].Rows[0]["HRemark"]);    //运算成功
                    objJsonResult.data = null;
                    return objJsonResult;
                }
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "提料运算失败!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
 
        #endregion
 
        #region 生产日计划平台 锁定
        [Route("JIT_DayPlanPlatFormBill/JIT_DayPlanPlatFormBillHLockedDay")]
        [HttpGet]
        public object JIT_DayPlanPlatFormBillHLockedDay(int HLockedDay,int HWorkShopID)
        {
            try
            {
                oCN.RunProc("update b set HLockedSub=0 from Sc_WorkBillSortBillMain a join Sc_WorkBillSortBillSub b on a.HInterID = b.HInterID " +
              $" where a.HWorkShopID={HWorkShopID}");
 
                oCN.RunProc("update b set HLockedSub=1 from Sc_WorkBillSortBillMain a join Sc_WorkBillSortBillSub b on a.HInterID = b.HInterID " +
                $" where  HMasterDate between  DATEADD(day, -1, getdate()) " +
                $"and DATEADD(day,{(HLockedDay - 1)},getdate())  and a.HWorkShopID={HWorkShopID}");
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = null;
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 生产日计划平台 解锁
        [Route("JIT_DayPlanPlatFormBill/JIT_DayPlanPlatFormBillHUnlockDay")]
        [HttpGet]
        public object JIT_DayPlanPlatFormBillHUnlockDay(int HWorkShopID)
        {
            try
            {
                oCN.RunProc("update b set HLockedSub=0 from Sc_WorkBillSortBillMain a join Sc_WorkBillSortBillSub b on a.HInterID = b.HInterID " +
              $" where a.HWorkShopID={HWorkShopID}");
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = null;
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 生产日计划平台 锁定工单
        [Route("JIT_DayPlanPlatFormBill/JIT_DayPlanPlatFormBillHLockedOrder")]
        [HttpGet]
        public object JIT_DayPlanPlatFormBillHLockedOrder(string HInterIDs)
        {
            try
            {
                oCN.RunProc($"update Sc_WorkBillSortBillMain set HLockOrder = 1 where HInterID in ({HInterIDs})");
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = null;
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 生产日计划平台 解锁工单
        [Route("JIT_DayPlanPlatFormBill/JIT_DayPlanPlatFormBillHUnlockOrder")]
        [HttpGet]
        public object JIT_DayPlanPlatFormBillHUnlockOrder(string HInterIDs)
        {
            try
            {
                oCN.RunProc($"update Sc_WorkBillSortBillMain set HLockOrder = 0 where HInterID in ({HInterIDs})");
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = null;
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 生产日计划平台 生产订单查询
        [Route("JIT_DayPlanPlatFormBill/JIT_ICMOBillList")]
        [HttpGet]
        public object JIT_ICMOBillList(string hmainid)
        {
            try
            {
                var list = hmainid.Split(',');
                List<DataTable> listdt = new List<DataTable>();
                DataTable dtable = new DataTable("dt");
                for (int i = 0; i < list.Length; i++)
                {
                    var listEvery = list[i].Split('_');
                   
                    ds = oCN.RunProcReturn($"exec h_p_ICMOBillList_PrimarySubTable '{listEvery[0]}','{listEvery[1]}'", "h_p_ICMOBillList_PrimarySubTable");
 
                    var dt = oCN.RunProcReturn($"select * from  h_v_JIT_Sc_WorkBillSortBillList where 源单主内码 in({ds.Tables[0].Rows[0]["源单主内码"].ToString()}) and  源单子内码 in({ds.Tables[0].Rows[0]["源单子内码"].ToString()})", "h_v_JIT_Sc_WorkBillSortBillList");
                    if (dt.Tables[0].Rows.Count > 0)
                    {
                        objJsonResult.code = "0";
                        objJsonResult.count = 0;
                        objJsonResult.Message = "生产明细行重复,重复的生产订单号:" + dt.Tables[0].Rows[i]["生产订单号"].ToString() + ",明细行号:" + dt.Tables[0].Rows[i]["生产订单明细行号"].ToString();
                        objJsonResult.data = null;
                        return objJsonResult;
                    }
                    if (i == 0)
                    {
                        //添加列名
                        for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                        {
                            dtable.Columns.Add(ds.Tables[0].Columns[j].ToString());
                        }
                    }
                    listdt.Add(ds.Tables[0]);
                }
 
                //获取集合数据
                for (int i = 0; i < listdt.Count; i++)
                {
                    DataRow row = dtable.NewRow();
                    for (int j = 0; j < listdt[i].Columns.Count; j++)
                    {
                        if (listdt[i].Columns[j].ColumnName == "计划数量")
                        {
                            row[j] = double.Parse(listdt[i].Rows[0][j].ToString()).ToString();
                        }
                        else
                        {
                            row[j] = listdt[i].Rows[0][j].ToString();
                        }
                    }
                    dtable.Rows.Add(row);
                }
 
                //添加动态日期
                for (int j = 1; j <= 31; j++)
                {
                    dtable.Columns.Add(DateTime.Now.AddDays(j - 1).ToString("yyyy-MM-dd"), typeof(Int32));
                }
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = dtable;
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 生产日计划平台 数据准备 设置任务单相关信息
        [Route("JIT_DayPlanPlatFormBill/ReadyData")]
        [HttpGet]
        public object ReadyData(string SWhere)
        {
            try
            {
                var list = SWhere.Split(',');
                DataTable dt = new DataTable("date");
                dt.Columns.Add("HICMOInterID", typeof(string));
                dt.Columns.Add("HICMOEntryID", typeof(string));
                dt.Columns.Add("小时产能", typeof(string));
                dt.Columns.Add("生产周期", typeof(decimal));
                dt.Columns.Add("开工余量", typeof(decimal));
                dt.Columns.Add("最迟开工日期", typeof(DateTime));
                dt.Columns.Add("最迟完工日期", typeof(DateTime));
                dt.Columns.Add("订单需求数量", typeof(decimal));
                dt.Columns.Add("订单交货期", typeof(DateTime));
 
                for (int i = 0; i < list.Length; i++)
                {
                    string HICMOInterID = list[i].Split(';')[0].ToString();
                    string HICMOEntryID = list[i].Split(';')[1].ToString();
                    string HSourceID = list[i].Split(';')[2].ToString();
 
                    Thread.Sleep(100);
                    ds = oCN.RunProcReturn("exec h_p_Sc_GetInfoByICMOBillNo " + HICMOInterID+","+ HICMOEntryID+","+ HSourceID, "h_p_Sc_GetInfoByICMOBillNo");
                    if (ds == null || ds.Tables[0].Rows.Count == 0)
                    {
                        
                    }
                    else
                    {
                        DataRow dr = dt.NewRow();
                        dr["小时产能"] = DBUtility.ClsPub.isSingle(ds.Tables[0].Rows[0]["产能"]);
                        dr["生产周期"] = DBUtility.ClsPub.isSingle(ds.Tables[0].Rows[0]["生产周期"]);
                        dr["开工余量"] = DBUtility.ClsPub.isSingle(ds.Tables[0].Rows[0]["开工余量"]);
                        dr["最迟开工日期"] = DBUtility.ClsPub.isDate(ds.Tables[0].Rows[0]["最迟开工日期"]);
                        dr["最迟完工日期"] = DBUtility.ClsPub.isDate(ds.Tables[0].Rows[0]["最迟完工日期"]);
                        dr["订单需求数量"] = DBUtility.ClsPub.isSingle(ds.Tables[0].Rows[0]["订单需求数"]);
                        dr["订单交货期"] = DBUtility.ClsPub.isDate(ds.Tables[0].Rows[0]["订单交货期"]);
                        dr["HICMOInterID"] = DBUtility.ClsPub.isSingle(ds.Tables[0].Rows[0]["HICMOInterID"]);
                        dr["HICMOEntryID"] = DBUtility.ClsPub.isSingle(ds.Tables[0].Rows[0]["HICMOEntryID"]);
                        dt.Rows.Add(dr);
                    }
                }
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = dt;
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region  缺料分析报表
        public class MaterialShorAnalysis
        {
            public int? HORGID;
            public DateTime HBEGINDATE;
            public DateTime HENDDATE;
        }
        [Route("JIT_DayPlanPlatFormBill/MaterialShorAnalysisReport")]
        [HttpGet]
        public object MaterialShorAnalysisReport(string sWhere)
        {
            try
            {
                MaterialShorAnalysis Report = JsonConvert.DeserializeObject<MaterialShorAnalysis>(sWhere);
 
                ds = oCN.RunProcReturn($"exec h_p_JIT_MaterialShorAnalysisReportList {Report.HORGID},'{Report.HBEGINDATE}','{Report.HENDDATE}' ", "h_p_JIT_PODemandPlanBill_ReportList");
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = ds.Tables[0];
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 根据物料ID获取工艺路线 列表
        [Route("JIT_DayPlanPlatFormBill/GetRoutingListByMater")]
        [HttpGet]
        public object GetRoutingListByMater(int HMaterID, string user)
        {
            try
            {
                List<object> columnNameList = new List<object>();
 
                int IsHavingPermissions = 1;
 
                //判断是否有工艺路线编辑权限
                if (!DBUtility.ClsPub.Security_Log("Gy_RoutingBill_Edit", 1, false, user))
                {
                    IsHavingPermissions = 0;
                }
 
                ds = oCN.RunProcReturn("select * from  h_v_JIT_GetRoutingList_Mater where HMaterID = " + HMaterID , "h_v_JIT_GetRoutingList_Mater");
 
                if (ds == null || ds.Tables[0].Rows.Count == 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "当前物料没有维护工艺路线!请联系计划部进行维护";
                    objJsonResult.data = ds.Tables[0];
                    objJsonResult.IsHavingPermissions = IsHavingPermissions;
                    return objJsonResult;
                }
                else
                {
                    //添加列名
                    foreach (DataColumn col in ds.Tables[0].Columns)
                    {
                        Type dataType = col.DataType;
                        string ColmString = "{\"ColmCols\":\"" + col.ColumnName + "\",\"ColmType\":\"" + dataType.Name + "\"}";
                        columnNameList.Add(JsonConvert.DeserializeObject(ColmString));//获取到DataColumn列对象的列名
                    }
 
                    objJsonResult.code = "1";
                    objJsonResult.count = 1;
                    objJsonResult.Message = "Sucess!";
                    objJsonResult.data = ds.Tables[0];
                    objJsonResult.list = columnNameList;
                    objJsonResult.IsHavingPermissions = IsHavingPermissions;
                    return objJsonResult;
                }
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 生产日计划平台 根据车间添加未排产生产订单
        [Route("JIT_DayPlanPlatFormBill/JIT_ICMOBillListByDept")]
        [HttpGet]
        public object JIT_ICMOBillListByDept(string HDeptID)
        {
            try
            {
                //获取显示系统参数
                string sReturn = "";
                oSystemParameter.ShowBill(ref sReturn);
 
                //查询选择车间中未排产过的生产订单信息(添康科技--生产订单状态为下达)
                ds = oCN.RunProcReturn($"exec h_p_JIT_ICMOBillListByDept '{HDeptID}'", "h_p_JIT_ICMOBillListByDept");
 
                if (ds.Tables[0].Rows.Count > 0 && ds != null)
                {
                    if (oSystemParameter.omodel.WMS_CampanyName == "添康科技") //系统参数  客户定制化名称     空白为通用
                    {
                        //数据表格添加动态日期
                        for (int j = 1; j <= 180; j++)
                        {
                            ds.Tables[0].Columns.Add(DateTime.Now.AddDays(j - 1).ToString("yyyy-MM-dd"), typeof(Int32));
                        }
                    }
                    else
                    {
                        //数据表格添加动态日期
                        for (int j = 1; j <= 31; j++)
                        {
                            ds.Tables[0].Columns.Add(DateTime.Now.AddDays(j - 1).ToString("yyyy-MM-dd"), typeof(Int32));
                        }
                    }                   
 
                    objJsonResult.code = "1";
                    objJsonResult.count = 1;
                    objJsonResult.Message = "Sucess!";
                    objJsonResult.data = ds.Tables[0];
                    return objJsonResult;
                }
                else
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "查无数据,当前所选车间下暂无未排产且订单状态为下达的生产订单信息!";
                    objJsonResult.data = "";
                    return objJsonResult;
                }
               
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 生产日计划平台 获取完工日期
        [Route("JIT_DayPlanPlatFormBill/GetICMOCompletionDate")]
        [HttpGet]
        public object GetICMOCompletionDate(string HDeptID)
        {
            try
            {
                //更新日计划工单的完工日期
                oCN.RunProc($"exec h_p_JIT_GetICMOCompletionDate '{HDeptID}'");
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "获取完工日期成功!";
                objJsonResult.data = null;
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 生产日计划平台 获取最早开工日期
        [Route("JIT_DayPlanPlatFormBill/GetICMOEarlyDate")]
        [HttpGet]
        public object GetICMOEarlyDate(string HDeptID)
        {
            try
            {
                //更新生产订单的最早开工日期
                oCN.RunProc($"exec h_p_JIT_GetICMOEarlyDate '{HDeptID}'");
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "获取最早开工日期成功!";
                objJsonResult.data = null;
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 通过物料匹配产品器具清单
        [Route("JIT_DayPlanPlatFormBill/GetMouldByMater")]
        [HttpGet]
        public object GetMouldByMater(string HMaterID,string HSourceID,string HPCDate)
        {
            try
            {
                ds = oCN.RunProcReturn("exec h_p_Gy_MaterialMouldByMater " + HMaterID + "," + HSourceID + ",'" + HPCDate + "'", "h_p_Gy_MaterialMouldByMater");               
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = ds.Tables[0];
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 通过资源匹配资源器具清单
        [Route("JIT_DayPlanPlatFormBill/GetMouldBySource")]
        [HttpGet]
        public object GetMouldBySource(string HSourceID, string HMouldID)
        {
            try
            {
                ds = oCN.RunProcReturn("select * from h_v_Gy_SourceMouldBillMainList where HSourceID = " + HSourceID + " and HMouldID = " + HMouldID, "h_v_Gy_SourceMouldBillMainList");
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = ds.Tables[0];
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 排产后将器具占用时间写入数据库
        [Route("JIT_DayPlanPlatFormBill/AddMouldOccupancyTime")]
        [HttpGet]
        public object AddMouldOccupancyTime(string HMouldID, string HSourceID, string HICMOInterID, string HICMOEntryID, string HICMOBillNo, string HMouldPCTime)
        {
            try
            {
                ds = oCN.RunProcReturn("exec h_p_JIT_AddMouldOccupancyTime " + HMouldID + "," + HSourceID + "," + HICMOInterID + "," + HICMOEntryID + ",'" + HICMOBillNo  + "','" + HMouldPCTime + "'", "h_p_JIT_AddMouldOccupancyTime");
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = "";
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 通过主资源匹配子资源
        [Route("JIT_DayPlanPlatFormBill/GetChildSource")]
        [HttpGet]
        public object GetChildSource(string HSourceID)
        {
            try
            {
                ds = oCN.RunProcReturn("select HItemID 子资源ID,HNumber 子资源代码,HName 子资源名称,HCubicleQty 子资源工位数 from Gy_Source with(nolock) where HParentID = " + HSourceID + " order by HName asc", "Gy_Source");
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = ds.Tables[0];
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 判断物料是否可以放在同一资源上一起生产
        [Route("JIT_DayPlanPlatFormBill/GetSourceByMater")]
        [HttpGet]
        public object GetSourceByMater(string HMaterID)
        {
            try
            {
                ds = oCN.RunProcReturn("exec h_p_Sc_ICMOGetWorkSource_TK " + HMaterID + ",'',''", "h_p_Sc_ICMOGetWorkSource_TK");
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = ds.Tables[0];
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        #region 工序负荷分析汇总报表 查询
        /// <summary>
        /// 返回项目阶段列表
        ///参数:string sql。
        ///返回值:object。
        /// </summary>
        [Route("JIT_DayPlanPlatFormBill/JIT_FuHeFenXiReport")]
        [HttpGet]
        public object JIT_FuHeFenXiReport(string sWhere, string user)
        {
            try
            {
 
                //查看权限
                if (!DBUtility.ClsPub.Security_Log("JIT_FuHeFenXiReport", 1, false, user))
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "无查看权限!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
 
                List<object> columnNameList = new List<object>();
                string sql = "exec h_p_JIT_FuHeFenXiReport   '" + sWhere + "','" + user + "'";
 
                ds = oCN.RunProcReturn(sql, "h_p_JIT_FuHeFenXiReport");
 
                //添加列名
                foreach (DataColumn col in ds.Tables[0].Columns)
                {
                    Type dataType = col.DataType;
                    string ColmString = "{\"ColmCols\":\"" + col.ColumnName + "\",\"ColmType\":\"" + dataType.Name + "\"}";
                    columnNameList.Add(JsonConvert.DeserializeObject(ColmString));//获取到DataColumn列对象的列名
                }
 
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "Sucess!";
                objJsonResult.data = ds.Tables[0];
                objJsonResult.list = columnNameList;
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
 
        
 
    }
}