ERPServiceImpl.java 155 KB
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
package com.huaheng.api.erp.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.gson.Gson;
import com.huaheng.api.erp.ExtOperateParam;
import com.huaheng.api.erp.ExtSaveParam;
import com.huaheng.api.erp.domain.*;
import com.huaheng.api.erp.domain.notice.*;
import com.huaheng.api.erp.domain.push.PushModel;
import com.huaheng.api.erp.domain.push.PushTransfer;
import com.huaheng.api.erp.domain.push.PushTransferEntity;
import com.huaheng.api.erp.domain.sale.*;
import com.huaheng.api.erp.domain.convert.DirectConvert;
import com.huaheng.api.erp.domain.convert.DirectConvertEntity;
import com.huaheng.api.erp.domain.convert.DirectConverts;
import com.huaheng.api.general.domain.ReceiptDomain;
import com.huaheng.api.general.service.BasicDataApiService;
import com.huaheng.common.constant.HttpConstant;
import com.huaheng.common.constant.QuantityConstant;
import com.huaheng.common.exception.service.ServiceException;
import com.huaheng.common.utils.DateUtils;
import com.huaheng.common.utils.bean.BeanUtils;
import com.huaheng.common.utils.http.OkHttpUtils;
import com.huaheng.framework.aspectj.ApiLogAspect;
import com.huaheng.framework.aspectj.lang.annotation.ApiLogger;
import com.huaheng.framework.aspectj.lang.annotation.ProcessTrack;
import com.huaheng.framework.aspectj.lang.constant.ProcessCode;
import com.huaheng.framework.web.domain.AjaxResult;
import com.huaheng.common.constant.Res;

import com.huaheng.framework.web.service.ConfigService;
import com.huaheng.pc.config.address.service.AddressService;
import com.huaheng.pc.config.bosAssistantDetail.domain.BosAssistantDetail;
import com.huaheng.pc.config.bosAssistantDetail.service.IBosAssistantDetailService;
import com.huaheng.pc.config.container.domain.Container;
import com.huaheng.pc.config.container.service.ContainerService;
import com.huaheng.pc.config.containerType.domain.ContainerType;
import com.huaheng.pc.config.containerType.service.ContainerTypeService;
import com.huaheng.pc.config.customer.domain.Customer;
import com.huaheng.pc.config.customer.service.CustomerServiceImpl;
import com.huaheng.pc.config.flexValues.domain.FlexValues;
import com.huaheng.pc.config.flexValues.service.IFlexValuesService;
import com.huaheng.pc.config.location.domain.Location;
import com.huaheng.pc.config.location.service.LocationService;
import com.huaheng.pc.config.locationType.domain.LocationType;
import com.huaheng.pc.config.locationType.service.LocationTypeService;
import com.huaheng.pc.config.material.domain.Material;
import com.huaheng.pc.config.material.service.MaterialService;
import com.huaheng.pc.config.materialType.domain.MaterialType;
import com.huaheng.pc.config.materialType.service.MaterialTypeService;
import com.huaheng.pc.config.productScheduleDetail.domain.ProductScheduleDetail;
import com.huaheng.pc.config.productScheduleDetail.service.IProductScheduleDetailService;
import com.huaheng.pc.config.productScheduleHeader.domain.ProductScheduleHeader;
import com.huaheng.pc.config.productScheduleHeader.service.IProductScheduleHeaderService;
import com.huaheng.pc.config.productSize.domain.ProductSize;
import com.huaheng.pc.config.productSize.service.IProductSizeService;
import com.huaheng.pc.config.proPackaging.domain.ProPackaging;
import com.huaheng.pc.config.proPackaging.service.IProPackagingService;
import com.huaheng.pc.config.station.service.StationService;
import com.huaheng.pc.config.stock.domain.Stock;
import com.huaheng.pc.config.stock.service.IStockService;
import com.huaheng.pc.config.unit.domain.Unit;
import com.huaheng.pc.config.unit.service.IUnitService;
import com.huaheng.pc.config.zone.domain.Zone;
import com.huaheng.pc.config.zone.service.ZoneService;
import com.huaheng.pc.config.zone.service.ZoneService;
import com.huaheng.pc.inventory.InventoryHistoryDetail.domain.InventoryHistoryDetail;
import com.huaheng.pc.inventory.InventoryHistoryDetail.service.IInventoryHistoryDetailService;
import com.huaheng.pc.inventory.inventoryDetail.domain.InventoryDetail;
import com.huaheng.pc.inventory.inventoryDetail.service.InventoryDetailService;
import com.huaheng.pc.inventory.inventoryHeader.domain.InventoryHeader;
import com.huaheng.pc.inventory.inventoryHeader.service.InventoryHeaderService;
import com.huaheng.pc.inventory.inventoryHistoryHeader.domain.InventoryHistoryHeader;
import com.huaheng.pc.inventory.inventoryHistoryHeader.service.IInventoryHistoryHeaderService;
import com.huaheng.pc.monitor.apilog.domain.ApiLog;
import com.huaheng.pc.receipt.receiptContainerDetail.domain.ReceiptContainerDetail;
import com.huaheng.pc.receipt.receiptContainerDetail.service.ReceiptContainerDetailService;
import com.huaheng.pc.receipt.receiptContainerHeader.domain.ReceiptContainerHeader;
import com.huaheng.pc.receipt.receiptContainerHeader.service.ReceiptContainerHeaderService;
import com.huaheng.pc.receipt.receiptDetail.domain.ReceiptDetail;
import com.huaheng.pc.receipt.receiptDetail.service.ReceiptDetailService;
import com.huaheng.pc.receipt.receiptHeader.domain.ReceiptHeader;
import com.huaheng.pc.receipt.receiptHeader.service.ReceiptHeaderService;
import com.huaheng.pc.referenceCode.domain.ReferenceCode;
import com.huaheng.pc.referenceCode.service.IReferenceCodeService;
import com.huaheng.pc.shipment.shipmentContainerDetail.domain.ShipmentContainerDetail;
import com.huaheng.pc.shipment.shipmentContainerDetail.service.ShipmentContainerDetailService;
import com.huaheng.pc.shipment.shipmentContainerHeader.domain.ShipmentContainerHeader;
import com.huaheng.pc.shipment.shipmentContainerHeader.service.ShipmentContainerHeaderService;
import com.huaheng.pc.shipment.shipmentDetail.domain.ShipmentDetail;
import com.huaheng.pc.shipment.shipmentDetail.service.ShipmentDetailService;
import com.huaheng.pc.shipment.shipmentHeader.domain.ShipmentHeader;
import com.huaheng.pc.shipment.shipmentHeader.service.ShipmentHeaderService;
import com.huaheng.pc.system.config.domain.Config;
import com.huaheng.pc.system.dept.domain.Dept;
import com.huaheng.pc.system.dept.service.DeptServiceImpl;
import com.huaheng.pc.system.user.domain.User;
import com.huaheng.pc.system.user.service.UserServiceImpl;
import com.huaheng.pc.task.taskHeader.service.ReceiptTaskService;
import com.huaheng.pc.task.taskHeader.service.ShipmentTaskService;
import com.huaheng.pc.task.taskHeader.service.TaskHeaderService;
import com.kingdee.bos.webapi.sdk.*;
import org.apache.regexp.RE;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.huaheng.pc.task.agvTask.domain.AgvTask;
import com.huaheng.pc.task.agvTask.service.AgvTaskService;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ERPServiceImpl  implements ERPService  {

    @Resource
    private ContainerService containerService;
    @Resource
    private ContainerTypeService containerTypeService;
    @Resource
    private ERPServiceImpl erpService;
    @Resource
    private ReceiptContainerHeaderService receiptContainerHeaderService;
    @Resource
    private ReceiptContainerDetailService receiptContainerDetailService;
    @Resource
    private ReceiptHeaderService receiptHeaderService;
    @Resource
    private ReceiptDetailService receiptDetailService;
    @Resource
    private ReceiptTaskService receiptTaskService;
    @Resource
    private MaterialService materialService;
    @Resource
    private AgvTaskService agvTaskService;

    @Resource
    private ShipmentHeaderService shipmentHeaderService;
    @Resource
    private InventoryHeaderService inventoryHeaderService;
    @Resource
    private InventoryDetailService inventoryDetailService;
    @Resource
    private ShipmentContainerHeaderService shipmentContainerHeaderService;
    @Resource
    private StationService stationService;
    @Resource
    private TaskHeaderService taskHeaderService;
    @Resource
    private CustomerServiceImpl customerService;
    @Resource
    private ShipmentTaskService shipmentTaskService;
    @Resource
    private ShipmentDetailService shipmentDetailService;
    @Resource
    private ShipmentContainerDetailService shipmentContainerDetailService;
    @Resource
    private DeptServiceImpl deptService;
    @Resource
    private BasicDataApiService basicDataApiService;
    @Resource
    private IStockService stockService;
    @Resource
    private UserServiceImpl userService;
    @Resource
    private IFlexValuesService flexValuesService;
    @Resource
    private IUnitService unitService;
    @Resource
    private IProPackagingService proPackagingService;
    @Resource
    private IBosAssistantDetailService bosAssistantDetailService;
    @Resource
    private IProductSizeService productSizeService;
    @Resource
    private IProductScheduleDetailService productScheduleDetailService;
    @Resource
    private IProductScheduleHeaderService productScheduleHeaderService;
    @Resource
    private MaterialTypeService materialTypeService;
    @Resource
    private IInventoryHistoryDetailService inventoryHistoryDetailService;
    @Resource
    private IInventoryHistoryHeaderService inventoryHistoryHeaderService;
    @Resource
    private ZoneService zoneService;
    @Resource
    private LocationService locationService;
    @Resource
    private IReferenceCodeService referenceCodeService;
    @Resource
    private ConfigService configService;
    @Resource
    private AddressService addressService;


    @Override
    public AjaxResult selectOtherReceipt() {
        LambdaQueryWrapper<ReceiptHeader> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ReceiptHeader::getReceiptType,QuantityConstant.RECEIPT_BILL_TYPE_OR);
        queryWrapper.eq(ReceiptHeader::getDeleted,true);
        queryWrapper.eq(ReceiptHeader::getOrderFinish,false);
        queryWrapper.orderByAsc(ReceiptHeader::getCreated);
        List<ReceiptHeader> list = receiptHeaderService.list(queryWrapper);
        if(list.size() == 0){
            return AjaxResult.error("没有找到其他入库单");
        }
        ReceiptHeader receiptHeader = list.get(0);
        List<ReceiptDetail> receiptDetailList = receiptDetailService.list(
                new LambdaQueryWrapper<ReceiptDetail>()
                .eq(ReceiptDetail::getReceiptId, receiptHeader.getId()));

        ReceiptDomain domain = new ReceiptDomain();
        domain.setReceiptHeader(receiptHeader);
        domain.setReceiptDetails(receiptDetailList);
        return AjaxResult.success(domain);
    }

    @Override
    public void common() {
        dept();
        user();
        customer();
        material();
        proPackaging();
        productSize();
        stock();
        flexValues();
        unit();
        bosAssistantDetail();
        productSchedule();
    }

    @Override
    public void downloadBill() {
        downloadReturnNotice();      // 退货入库单
        downLoadDeliveryNotice();    // 销售出库单
        downloadShipmentRequest();   // 其他出库单
    }

    /**
     * 同步部门数据
     */
    @Override
    public void dept() {
        String key = configService.getKey(QuantityConstant.DEPT_FILTERSTRING);
        if(StringUtils.isEmpty(key)){
            return;
        }

        QueryParam param = new QueryParam()
                .setFormId("BD_Department")
                .setFieldKeys("FDEPTID,FNumber,FName,FParentID,FIsStock")
                .setFilterString(key)
                .setOrderString("FDEPTID ASC");

        Gson gson = new Gson();
        Object[] objects = new Object[]{param.toJson()};
        ErpSaveObject erpSaveObject = new ErpSaveObject();
        erpSaveObject.setParameters(objects);
        String body = gson.toJson(erpSaveObject);

        String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_QUERY,
                QuantityConstant.DEFAULT_WAREHOUSE, "");
        System.out.println(body);
        String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
        if(StringUtils.isEmpty(sessionId)){
            throw new ServiceException("sessionId不能为空");
        }
        String okResult = OkHttpUtils.bodypost(url, body, sessionId);
        if(StringUtils.isEmpty(okResult)) {
            throw new ServiceException("接口地址错误或返回为空");
        }
        String fieldKeys = param.getFieldKeys();
        List<ERPDept> datas = null;
        try {
            datas = loadDataList(fieldKeys, ERPDept.class, okResult);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //erp 部门集合
        List<Dept> depts = new ArrayList<>();
        for (ERPDept data : datas) {
            Dept dept = new Dept();
            dept.setDeptName(data.getName());
            dept.setId(data.getDeptId());
            dept.setCode(data.getNumber());
            dept.setParentId(data.getParentId());
            dept.setIsStock(data.getIsStock());
            depts.add(dept);
        }

        Set<String> collect = depts.stream().map(Dept::getCode).collect(Collectors.toSet());
        do{
            Iterator<Dept> iterator = depts.iterator();
            //迭代erp 部门
            while (iterator.hasNext()){
                //获取部门
                Dept dept = iterator.next();
                //获取部门编码
                String code = dept.getCode();
                //查询是否有该部门
                Dept dept1 = deptService.selectDepts(code);
                //没有 新增 有就修改
                if(dept1 == null){
                    //判断erp部门有没有父部门id 有else查找父部门 没有就开新的分支
                    Integer parentId = dept.getParentId();
                    if(parentId==0){
                        dept.setId(null);
                        dept.setParentId(0);
                        dept.setAncestors("0");
                        dept.setOrderNum("0");
                        boolean save = deptService.save(dept);
                        if(save){
                            collect.remove(code);
                        }
                        //减少下次循环的次数
                        iterator.remove();
                    }else{
                        //获取父部门判断是否为null
                        Dept parentDept = deptService.getById(parentId);
                        //判断 为null 进入下次循环
                        if(parentDept!=null){
                            dept.setAncestors(parentDept.getAncestors() + "," + parentDept.getId());
                            //显示排序 序号
                            int orderNum = Integer.valueOf(parentDept.getOrderNum()) + 1;
                            dept.setOrderNum(""+orderNum);
                            dept.setId(null);
                            boolean save = deptService.save(dept);
                            if(save){
                                collect.remove(code);
                            }
                            iterator.remove();
                        }
                    }
                }else{
                    //修改 部门名称
                    dept1.setDeptName(dept.getDeptName());
                    //修改父部门
                    dept1.setParentId(dept.getParentId());
                    dept1.setIsStock(dept.getIsStock());
                    //查询修改后 部门是否存在
                    Dept superDept = deptService.selectDeptById(dept1.getParentId());
                    if(superDept!=null){
                        dept1.setAncestors(superDept.getAncestors() + "," + dept.getParentId());
                        dept1.setOrderNum(Integer.valueOf(superDept.getOrderNum())+1+"");
                    }else {
                        //大于0 表示该部门 父部门发生改变 父部门还没有录入跳过 进入下次循环
                        if(dept1.getParentId()>0){
                            continue;
                        }
                        dept1.setAncestors("0");
                        dept1.setOrderNum("0");
                    }
                    boolean save = deptService.updateById(dept1);
                    if(save){
                        collect.remove(code);
                    }
                    iterator.remove();
                }
            }
        }while (collect.size()>0);
    }


    /**
     * 同步用户数据
     */
    @Override
    public void user() {
        String key = configService.getKey(QuantityConstant.USER_FILTERSTRING);
        if(StringUtils.isEmpty(key)){
            return;
        }

        QueryParam param = new QueryParam()
                .setFormId("BD_Empinfo")
                .setFieldKeys("FID,FName,FNumber,FPostDept,FCreateDate,FModifyDate")
                .setFilterString(key)
                .setOrderString("FID ASC")
                .setLimit(0);

        Gson gson = new Gson();
        Object[] objects = new Object[]{param.toJson()};
        ErpSaveObject erpSaveObject = new ErpSaveObject();
        erpSaveObject.setParameters(objects);
        String body = gson.toJson(erpSaveObject);

        String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_QUERY,
                QuantityConstant.DEFAULT_WAREHOUSE, "");
        System.out.println(body);
        String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
        if(StringUtils.isEmpty(sessionId)){
            throw new ServiceException("sessionId不能为空");
        }
        String okResult = OkHttpUtils.bodypost(url, body, sessionId);
        if(StringUtils.isEmpty(okResult)) {
            throw new ServiceException("接口地址错误或返回为空");
        }
        String fieldKeys = param.getFieldKeys();
        List<ERPUser> datas = null;
        try {
            datas = loadDataList(fieldKeys, ERPUser.class, okResult);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //通过json获取员工对象集合 获取key相同的数据
        String jsonStr = gson.toJson(datas);
        //erp 员工集合
        List<User> userList = Arrays.asList(gson.fromJson(jsonStr, User[].class));

        for (User user : userList) {
            basicDataApiService.user(user);
        }
    }
    /**
     * 同步客户数据
     */
    @Override
    public void customer() {
        String key = configService.getKey(QuantityConstant.CUSTOMER_FILTERSTRING);
        if(StringUtils.isEmpty(key)){
            return;
        }

        QueryParam param = new QueryParam()
                .setFormId("BD_Customer")
                .setFieldKeys("FCUSTID,FName,FNumber,FCOUNTRY,FPROVINCIAL,FCreateDate,FModifyDate")
                .setFilterString(key)
                .setOrderString("FModifyDate DESC")
                .setLimit(0);

        Gson gson = new Gson();
        Object[] objects = new Object[]{param.toJson()};
        ErpSaveObject erpSaveObject = new ErpSaveObject();
        erpSaveObject.setParameters(objects);
        String body = gson.toJson(erpSaveObject);

        String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_QUERY,
                QuantityConstant.DEFAULT_WAREHOUSE, "");
        System.out.println(body);
        String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
        if(StringUtils.isEmpty(sessionId)){
            throw new ServiceException("sessionId不能为空");
        }
        String okResult = OkHttpUtils.bodypost(url, body, sessionId);
        if(StringUtils.isEmpty(okResult)) {
            throw new ServiceException("接口地址错误或返回为空");
        }
        String fieldKeys = param.getFieldKeys();

        List<ERPCustmer> datas = null;
        try {
            datas = loadDataList(fieldKeys, ERPCustmer.class, okResult);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //通过json获取客户对象集合 获取key相同的数据
        String jsonStr = gson.toJson(datas);
        //erp 客户集合
        List<Customer> userList = Arrays.asList(gson.fromJson(jsonStr, Customer[].class));

        for (Customer user1 : userList) {
            user1.setWarehouseCode("CS0001");
            user1.setCompanyCode("JY");
            user1.setCreatedBy("ERP系统");
        }
        if(userList.size()>0){
            customerService.truncateTable();
        }
        customerService.insertBatch(userList);
    }

    @Override
    public void material() {
        String key = configService.getKey(QuantityConstant.MATERIAL_FILTERSTRING);
        if(StringUtils.isEmpty(key)){
            return;
        }

        QueryParam param = new QueryParam()
                .setFormId("BD_MATERIAL")
                .setFieldKeys("FMATERIALID,FCREATEORGID,FNUMBER,fUseOrgId,FName,FSpecification,F_CH_Square,F_CH_PieceWeight,FIsBatchManage,FIsEnable1,FAuxPropertyId,FCreateDate,FMODIFYDATE,F_CH_Brand")
                .setOrderString("FCREATEDATE ASC")
                .setFilterString(key)
                .setStartRow(0)
                .setLimit(0);

        Gson gson = new Gson();
        Object[] objects = new Object[]{param.toJson()};
        ErpSaveObject erpSaveObject = new ErpSaveObject();
        erpSaveObject.setParameters(objects);
        String body = gson.toJson(erpSaveObject);

        String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_QUERY,
                QuantityConstant.DEFAULT_WAREHOUSE, "");
        System.out.println(body);
        String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
        if(StringUtils.isEmpty(sessionId)){
            throw new ServiceException("sessionId不能为空");
        }
        String okResult = OkHttpUtils.bodypost(url, body, sessionId);
        if(StringUtils.isEmpty(okResult)) {
            throw new ServiceException("接口地址错误或返回为空");
        }
        String fieldKeys = param.getFieldKeys();

        List<ERPMaterial> datas = null;
        try {
            datas = loadDataList(fieldKeys, ERPMaterial.class, okResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<ERPMaterial> newDatas= new ArrayList<>();
        ERPMaterial erpMaterial = null;
        //去重 erp物料数据
        for (ERPMaterial data : datas) {
            //material为null 或者materialId 实例化erp物料对象
            if(erpMaterial != null ){
                if(!erpMaterial.getNumber().equals(data.getNumber())){
                    newDatas.add(erpMaterial);
                }
            }
            if(erpMaterial == null || !erpMaterial.getNumber().equals(data.getNumber())){
                erpMaterial = new ERPMaterial();
                erpMaterial.setMaterialId(data.getMaterialId());
                erpMaterial.setNumber(data.getNumber());
                erpMaterial.setName(data.getName());
                erpMaterial.setSpecification(data.getSpecification());
                erpMaterial.setPieceWeight(data.getPieceWeight());
                erpMaterial.setSquare(data.getSquare());
                if(com.huaheng.common.utils.StringUtils.isNotNull(data.getIsBatchManage())){
                    erpMaterial.setIsBatchManage(data.getIsBatchManage());
                }
                erpMaterial.setCreateDate(data.getCreateDate());
                erpMaterial.setModifyDate(data.getModifyDate());
            }
            if(com.huaheng.common.utils.StringUtils.isNotNull(data.isColor())){
                erpMaterial.setColor(data.isColor());
            }
            if(com.huaheng.common.utils.StringUtils.isNotNull(data.isCustProductSize())){
                erpMaterial.setCustProductSize(data.isCustProductSize());
            }
            if(com.huaheng.common.utils.StringUtils.isNotNull(data.isLevel())){
                erpMaterial.setLevel(data.isLevel());
            }
            if(com.huaheng.common.utils.StringUtils.isNotNull(data.isProPackaging())){
                erpMaterial.setProPackaging(data.isProPackaging());
            }
            if(com.huaheng.common.utils.StringUtils.isNotNull(data.isProductSchedule())){
                erpMaterial.setProductSchedule(data.isProductSchedule());
            }
        }
        newDatas.add(erpMaterial);

        String jsonStr = gson.toJson(newDatas);
        //erp 物料集合
        List<Material> materialList = Arrays.asList(gson.fromJson(jsonStr, Material[].class));

        //新增集合
        List<Material> addMaterialList = new ArrayList<>();
        //设置保存
        for (Material material1 : materialList) {
            material1.setCreatedBy("ERP系统");
            material1.setCompanyCode("JY");
            material1.setWarehouseCode("CS0001");
            material1.setDaysToExpire(0);
            material1.setTrackSerialNum(0);
            material1.setAutoGenSerialNum(0);
            material1.setMinShelfLifeDays(0);
            material1.setEnable(true);
            material1.setVersion(0);
            material1.setUnit("1001");//默认单位为 1001 块
            material1.setDeleted(false);
            material1.setIsMix(true);

            LambdaQueryWrapper<MaterialType> queryWrapper = Wrappers.lambdaQuery();
            String spec = material1.getSpec().trim();
            if(StringUtils.isNotEmpty(spec)){
                queryWrapper.like(StringUtils.isNotEmpty(spec),MaterialType::getName, spec);
                MaterialType one = materialTypeService.getOne(queryWrapper);
                if (one!=null)
                {
                    material1.setType(one.getCode());
                }
            }

            addMaterialList.add(material1);
        }
        if(datas.size()>0){
            materialService.truncateTable();
        }
        materialService.insertBatch(addMaterialList);
    }

    @Override
    public void proPackaging() {
        String key = configService.getKey(QuantityConstant.PROPACKAGING_FILTERSTRING);
        if(StringUtils.isEmpty(key)){
            return;
        }

        QueryParam param = new QueryParam()
                .setFormId("CH_ProPackaging")
                .setFieldKeys("FNumber,FName,FDescription,FPrice,FPieceBox,F_CH_Pallet,F_CH_Boxs")
                .setFilterString(key)
                .setOrderString("FID ASC")
                .setLimit(0);

        Gson gson = new Gson();
        Object[] objects = new Object[]{param.toJson()};
        ErpSaveObject erpSaveObject = new ErpSaveObject();
        erpSaveObject.setParameters(objects);
        String body = gson.toJson(erpSaveObject);

        String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_QUERY,
                QuantityConstant.DEFAULT_WAREHOUSE, "");
        System.out.println(body);
        String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
        if(StringUtils.isEmpty(sessionId)){
            throw new ServiceException("sessionId不能为空");
        }
        String okResult = OkHttpUtils.bodypost(url, body, sessionId);
        if(StringUtils.isEmpty(okResult)) {
            throw new ServiceException("接口地址错误或返回为空");
        }
        String fieldKeys = param.getFieldKeys();
        List<ProPackaging> datas = null;
        try {
            datas = loadDataList(fieldKeys, ProPackaging.class, okResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(datas.size()>0){
            proPackagingService.truncateTable();
        }
        proPackagingService.insertBatch(datas);
    }

    @Override
    public void productSize() {
        String key = configService.getKey(QuantityConstant.PRODUCTSIZE_FILTERSTRING);
        if(StringUtils.isEmpty(key)){
            return;
        }

        QueryParam param = new QueryParam()
                .setFormId("CH_CustProductSize")
                .setFieldKeys("Fnumber,FSize,fname,fdocumentStatus,fcreateDate,FUnitArea,fmodifyDate,F_CH_longSide,F_CH_shortSide,FforbidStatus,FcreateOrgId.Fnumber,FuseOrgId.Fnumber,F_CH_group,Fdescription")
                .setFilterString(key)
                .setStartRow(0)
                .setLimit(0);

        Gson gson = new Gson();
        Object[] objects = new Object[]{param.toJson()};
        ErpSaveObject erpSaveObject = new ErpSaveObject();
        erpSaveObject.setParameters(objects);
        String body = gson.toJson(erpSaveObject);

        String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_QUERY,
                QuantityConstant.DEFAULT_WAREHOUSE, "");
        System.out.println(body);
        String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
        if(StringUtils.isEmpty(sessionId)){
            throw new ServiceException("sessionId不能为空");
        }
        String okResult = OkHttpUtils.bodypost(url, body, sessionId);
        if(StringUtils.isEmpty(okResult)) {
            throw new ServiceException("接口地址错误或返回为空");
        }
        String fieldKeys = param.getFieldKeys();

        List<ProductSize> datas = null;
        try {
            datas = loadDataList(fieldKeys, ProductSize.class, okResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(datas.size()>0){
            productSizeService.truncateTable();
        }
        productSizeService.insertBatch(datas);
    }

    @Override
    public void stock() {
        String key = configService.getKey(QuantityConstant.STOCK_FILTERSTRING);
        if(StringUtils.isEmpty(key)){
            return;
        }

        QueryParam param = new QueryParam()
                .setFormId("BD_STOCK")
                .setFieldKeys("fStockId,fName,fNumber,fisOpenLocation,FUseOrgId.FNumber")
                .setFilterString(key)
                .setOrderString("fStockId ASC")
                .setLimit(0);

        Gson gson = new Gson();
        Object[] objects = new Object[]{param.toJson()};
        ErpSaveObject erpSaveObject = new ErpSaveObject();
        erpSaveObject.setParameters(objects);
        String body = gson.toJson(erpSaveObject);

        String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_QUERY,
                QuantityConstant.DEFAULT_WAREHOUSE, "");
        System.out.println(body);
        String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
        if(StringUtils.isEmpty(sessionId)){
            throw new ServiceException("sessionId不能为空");
        }
        String okResult = OkHttpUtils.bodypost(url, body, sessionId);
        if(StringUtils.isEmpty(okResult)) {
            throw new ServiceException("接口地址错误或返回为空");
        }
        String fieldKeys = param.getFieldKeys();

        List<Stock> stocks = null;
        try {
            stocks = loadDataList(fieldKeys, Stock.class, okResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(stocks.size()>0){
            stockService.truncateTable();
        }
        stockService.insertBatch(stocks);
    }

    @Override
    public void flexValues() {
        String key = configService.getKey(QuantityConstant.FLEXVALUES_FILTERSTRING);
        if(StringUtils.isEmpty(key)){
            return;
        }

        QueryParam param = new QueryParam()
                .setFormId("bd_flexvalues")
                .setFieldKeys("fid,fName,fNumber,fflexValueNumber,fflexValueName,FUseOrgId.FNumber,FEntity_FEntryId")
                .setFilterString(key)
                .setOrderString("FEntity_FEntryId ASC")
                .setLimit(0);

        Gson gson = new Gson();
        Object[] objects = new Object[]{param.toJson()};
        ErpSaveObject erpSaveObject = new ErpSaveObject();
        erpSaveObject.setParameters(objects);
        String body = gson.toJson(erpSaveObject);

        String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_QUERY,
                QuantityConstant.DEFAULT_WAREHOUSE, "");
        System.out.println(body);
        String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
        if(StringUtils.isEmpty(sessionId)){
            throw new ServiceException("sessionId不能为空");
        }
        String okResult = OkHttpUtils.bodypost(url, body, sessionId);
        if(StringUtils.isEmpty(okResult)) {
            throw new ServiceException("接口地址错误或返回为空");
        }
        String fieldKeys = param.getFieldKeys();

        List<FlexValues> flexValues = null;
        try {
            flexValues = loadDataList(fieldKeys, FlexValues.class, okResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(flexValues.size()>0){
            flexValuesService.truncateTable();
        }
        flexValuesService.insertBatch(flexValues);
    }

    @Override
    public void unit() {
        String key = configService.getKey(QuantityConstant.UNIT_FILTERSTRING);
        if(StringUtils.isEmpty(key)){
            return;
        }

        QueryParam param = new QueryParam()
                .setFormId("bd_unit")
                .setFieldKeys("fName,fNumber")
                .setFilterString(key)
                .setOrderString("funitid ASC")
                .setLimit(0);

        Gson gson = new Gson();
        Object[] objects = new Object[]{param.toJson()};
        ErpSaveObject erpSaveObject = new ErpSaveObject();
        erpSaveObject.setParameters(objects);
        String body = gson.toJson(erpSaveObject);

        String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_QUERY,
                QuantityConstant.DEFAULT_WAREHOUSE, "");
        System.out.println(body);
        String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
        if(StringUtils.isEmpty(sessionId)){
            throw new ServiceException("sessionId不能为空");
        }
        String okResult = OkHttpUtils.bodypost(url, body, sessionId);
        if(StringUtils.isEmpty(okResult)) {
            throw new ServiceException("接口地址错误或返回为空");
        }
        String fieldKeys = param.getFieldKeys();

        List<Unit> units = null;
        try {
            units = loadDataList(fieldKeys, Unit.class, okResult);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(units.size()>0){
            unitService.truncateTable();
        }
        unitService.insertBatch(units);
    }

    @Override
    public void bosAssistantDetail() {
        String key = configService.getKey(QuantityConstant.BOSASSISTANTDETAIL_FILTERSTRING);
        if(StringUtils.isEmpty(key)){
            return;
        }

        QueryParam param = new QueryParam()
                .setFormId("BOS_ASSISTANTDATA_DETAIL")
                .setFieldKeys("Fid.Fnumber,FdataValue,FNUMBER,fdocumentStatus,FisSysPreset,Fdescription")
                .setFilterString(key)
                .setStartRow(0)
                .setLimit(0);

        Gson gson = new Gson();
        Object[] objects = new Object[]{param.toJson()};
        ErpSaveObject erpSaveObject = new ErpSaveObject();
        erpSaveObject.setParameters(objects);
        String body = gson.toJson(erpSaveObject);

        String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_QUERY,
                QuantityConstant.DEFAULT_WAREHOUSE, "");
        System.out.println(body);
        String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
        if(StringUtils.isEmpty(sessionId)){
            throw new ServiceException("sessionId不能为空");
        }
        String okResult = OkHttpUtils.bodypost(url, body, sessionId);
        if(StringUtils.isEmpty(okResult)) {
            throw new ServiceException("接口地址错误或返回为空");
        }
        String fieldKeys = param.getFieldKeys();

        //基本物料数据获取器
        List<BosAssistantDetail> datas = null;
        try {
            datas = loadDataList(fieldKeys, BosAssistantDetail.class, okResult);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Set<String> set = new HashSet<>();
        //去重
        List<BosAssistantDetail> newdates = new ArrayList<>();
        for (BosAssistantDetail data : datas) {
            String number = data.getNumber()+ data.getId();
            if(set.contains(number)){
                continue;
            }
            newdates.add(data);
            set.add(number);
        }
        //清楚
        if(newdates.size()>0){
            bosAssistantDetailService.truncateTable();
        }
        bosAssistantDetailService.insertBatch(newdates);
    }

    @Override
    public AjaxResult productSchedule() {
        String key = configService.getKey(QuantityConstant.PRODUCTSCHEDULEHEADER_FILTERSTRING);
        if(StringUtils.isEmpty(key)) {
            return AjaxResult.error(QuantityConstant.PRODUCTSCHEDULEHEADER_FILTERSTRING+"参数不存在,请先配置后使用。");
        }
        String key1 = configService.getKey(QuantityConstant.PRODUCTSCHEDULEDETAIL_FILTERSTRING);
        if(StringUtils.isEmpty(key1)) {
            return AjaxResult.error(QuantityConstant.PRODUCTSCHEDULEDETAIL_FILTERSTRING+"参数不存在,请先配置后使用。");
        }

        QueryParam param = new QueryParam()
                .setFormId("CH_ProductSchedule")
                .setFieldKeys("FNumber,FName,FDocumentStatus,F_CH_Date,F_CH_Customer.FNumber,FCreateDate,FModifyDate,F_CH_IsClose,F_PKMX_DateNew,F_PKMX_CustOutDate,F_CH_Dept.FNumber")
                .setFilterString(key)
                .setOrderString("FCreateDate DESC")
                .setStartRow(0)
                .setLimit(0);

        Gson gson = new Gson();
        Object[] objects = new Object[]{param.toJson()};
        ErpSaveObject erpSaveObject = new ErpSaveObject();
        erpSaveObject.setParameters(objects);
        String body = gson.toJson(erpSaveObject);

        String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_QUERY,
                QuantityConstant.DEFAULT_WAREHOUSE, "");
        System.out.println(body);
        String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
        if(StringUtils.isEmpty(sessionId)){
            throw new ServiceException("sessionId不能为空");
        }
        String okResult = OkHttpUtils.bodypost(url, body, sessionId);
        if(StringUtils.isEmpty(okResult)) {
            throw new ServiceException("接口地址错误或返回为空");
        }
        String fieldKeys = param.getFieldKeys();

        List<ProductScheduleHeader> datas = null;
        try {
            datas = loadDataList(fieldKeys, ProductScheduleHeader.class, okResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(datas.size()>0){
            productScheduleHeaderService.truncateTable();
        }
        productScheduleHeaderService.insertBatch(datas);

        QueryParam detailParam = new QueryParam()
                .setFormId("CH_ProductSchedule")
                .setFieldKeys("fid,FNumber,FmaterialId.FNumber,F_CH_Assistant.FNumber,F_CH_Size.FNumber,F_CH_Packaging.FNumber,F_CH_NoOrderNum,F_CH_NoInNum,F_CH_StockID.FNumber,F_CH_FLot,F_CH_area,F_CH_UnitArea,F_CH_FBillNo,F_CH_AssistQty1,F_CH_UnitWeight,F_CH_Weight,F_CH_Remark2")
                .setFilterString(key1)
                .setOrderString("FCreateDate DESC")
                .setStartRow(0)
                .setLimit(0);

         objects = new Object[]{param.toJson()};
         erpSaveObject = new ErpSaveObject();
        erpSaveObject.setParameters(objects);
         body = gson.toJson(erpSaveObject);

         url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_QUERY,
                QuantityConstant.DEFAULT_WAREHOUSE, "");
        System.out.println(body);
        okResult = OkHttpUtils.bodypost(url, body, sessionId);
        if(StringUtils.isEmpty(okResult)) {
            throw new ServiceException("接口地址错误或返回为空");
        }
        fieldKeys = param.getFieldKeys();

        List<ProductScheduleDetail> detailDatas = null;
        try {
            detailDatas = loadDataList(fieldKeys, ProductScheduleDetail.class, okResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(detailDatas.size()>0){
            productScheduleDetailService.truncateTable();
        }
        productScheduleDetailService.insertBatch(detailDatas);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult backERPBill() {
        LambdaQueryWrapper<ReceiptHeader> receiptHeaderLambdaQueryWrapper = Wrappers.lambdaQuery();
        receiptHeaderLambdaQueryWrapper.eq(ReceiptHeader::getLastStatus, QuantityConstant.RECEIPT_HEADER_POSTING)
                                        .ne(ReceiptHeader::getReceiptType, QuantityConstant.RECEIPT_BILL_TYPE_SC);
        List<ReceiptHeader> receiptHeaderList = receiptHeaderService.list(receiptHeaderLambdaQueryWrapper);
        for(ReceiptHeader receiptHeader : receiptHeaderList) {
            try {
                String qty = configService.getKey(QuantityConstant.ERP_RETURN_QTY);
                if (receiptHeader.getReturnQty()>Integer.valueOf(qty))
                {
                    continue;
                }
                PushModel model = new PushModel();
                model.setHeaderId(receiptHeader.getId());
                model.setReferType(receiptHeader.getReceiptType());
                AjaxResult push = erpService.push(model);
                if (push.getCode() != 200)
                {
                    receiptHeader.setReturnMessage(push.getMsg());
                    receiptHeader.setReturnQty(receiptHeader.getReturnQty()+1);
                    receiptHeaderService.updateById(receiptHeader);
                }
            } catch (Exception e) {
                receiptHeader.setReturnMessage(e.getMessage());
                receiptHeader.setReturnQty(receiptHeader.getReturnQty()+1);
                receiptHeaderService.updateById(receiptHeader);
                e.printStackTrace();
            }
        }

        LambdaQueryWrapper<ShipmentHeader> shipmentHeaderLambdaQueryWrapper = Wrappers.lambdaQuery();
        shipmentHeaderLambdaQueryWrapper.eq(ShipmentHeader::getLastStatus, QuantityConstant.SHIPMENT_HEADER_COMPLETED);
        List<ShipmentHeader> shipmentHeaderList = shipmentHeaderService.list(shipmentHeaderLambdaQueryWrapper);
        for(ShipmentHeader shipmentHeader : shipmentHeaderList) {
            try {
                String qty = configService.getKey(QuantityConstant.ERP_RETURN_QTY);
                if (shipmentHeader.getReturnQty()>Integer.valueOf(qty))
                {
                    continue;
                }
                PushModel model = new PushModel();
                model.setHeaderId(shipmentHeader.getId());
                model.setReferType(shipmentHeader.getShipmentType());
                AjaxResult push = erpService.push(model);
                if (push.getCode() != 200)
                {
                    shipmentHeader.setReturnMessage(push.getMsg());
                    shipmentHeader.setReturnQty(shipmentHeader.getReturnQty()+1);
                    shipmentHeaderService.updateById(shipmentHeader);
                }
            }   catch (Exception e) {
                shipmentHeader.setReturnMessage(e.getMessage());
                shipmentHeader.setReturnQty(shipmentHeader.getReturnQty()+1);
                shipmentHeaderService.updateById(shipmentHeader);
                e.printStackTrace();
            }
        }

        return AjaxResult.success("回传成功");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult receiptMethod(int receiptHeaderId){
        ReceiptHeader header = receiptHeaderService.getById(receiptHeaderId);
        return receiptMethod(header);
    }

    //下载 出库申请单(内部领用) 出库申请单->其他出库单
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult downloadShipmentRequest() {
        String key = configService.getKey(QuantityConstant.SHIPMENTREQUEST_FILTERSTRING);
        if(StringUtils.isEmpty(key)){
            return AjaxResult.error("过滤参数不能为空");
        }
        String currentSQL = " and FDate >= '";
        String before_bill_date = configService.getKey(QuantityConstant.BEFORE_BILL_DATE_NUM).trim();
        if(StringUtils.isEmpty(before_bill_date)){
            before_bill_date = "-30";
        }
        Integer num = Integer.parseInt(before_bill_date);
        /*获取当前日期 指定天数的时间。*/
        String presetDate = DateUtils.getPresetDate(DateUtils.getNowDate(), DateUtils.YYYY_MM_DD_HH_MM_SS, num);
        if(presetDate==null){
            currentSQL = "";
        }else{
            currentSQL += presetDate+"'";
        }
        key += currentSQL;
        AjaxResult ajaxResult = AjaxResult.success("出库列表已更新为最新状态!!");
        boolean result = false;
        String warehouseCode = "CS0001";
        String companyCode = "JY";

        ErpRequest erpRequest = new ErpRequest();
        ErpParam erpParam =  new ErpParam();
        erpParam.setFormId("STK_OutStockApply"); //销售退货单
        erpParam.setFieldKeys("FId,FBillNo,FBillTypeId.FNumber,FEntity_FEntryID,FStockOrgId1.FNumber,FStockOrgId.FNumber,FDate,FCustId.FNumber,FDeptId.FNumber,FPickerId.FNumber,FOwnerTypeIdHead,FNote,F_CH_LockType,F_CH_ContainerNo,F_CH_QTCKLX.FNumber,F_CH_QTCKBillType.FNumber,F_CH_Receiver,F_CH_Supplier.FNumber,F_CH_Applicant,F_CH_CK.FNumber,FMaterialId.FNumber,FUnitID.FNumber,FQty,FBaseUnitId.FNumber,FStockOrgIdEntry.FNumber,FStockId.FNumber,FLot.FNumber,FOwnerTypeId,FOwnerId.FNumber,FStockStatusId.FNumber,F_CH_ISLOCK,FAuxpropID.FF100008.FNumber,FAuxpropID.FF100007.FNumber,FAuxpropID.FF100003.FNumber,FAuxpropID.FF100002.FNumber,FAuxpropID.FF100001.FNumber,F_CH_Weight");
        erpParam.setFilterString(key);
        erpParam.setOrderString("FApproveDate DESC");
        erpRequest.setData(erpParam);
        String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_QUERY, warehouseCode, "");
        String jsonParam = JSON.toJSONString(erpRequest);
        System.out.println(jsonParam);
        String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
        if(StringUtils.isEmpty(sessionId)){
            throw new ServiceException("sessionId不能为空");
        }
        String okResult = OkHttpUtils.bodypost(url, jsonParam, sessionId);
        String fieldKeys = erpParam.getFieldKeys();

        List<ShipmentRequests> datas = null;
        try {
            datas = loadDataList(fieldKeys, ShipmentRequests.class, okResult);
        } catch (Exception e) {
            e.printStackTrace();
        }

        List<ShipmentRequest> transfer = ShipmentRequests.transfer(datas);
        if(transfer.size()==0){
            return AjaxResult.error("没有找到出库申请单");
        }

        LambdaQueryWrapper<ReferenceCode> queryWrapper2 = Wrappers.lambdaQuery();
        queryWrapper2.isNotNull(ReferenceCode::getBillno)
                .eq(ReferenceCode::getTypeName,QuantityConstant.BILL_TYPE_NAME_SO)
                .ne(ReferenceCode::getBillno,"");

        List<String> billNos = referenceCodeService.list(queryWrapper2).stream().distinct().map(ReferenceCode::getBillno).collect(Collectors.toList());

        List<ShipmentRequest> collect = transfer.stream()
                .filter(s -> !billNos.contains(s.getBillNo())).collect(Collectors.toList());

        for (ShipmentRequest req : collect) {
            //其他出库类型
            String code = shipmentHeaderService.createCode(QuantityConstant.SHIPMENT_BILL_TYPE_OS);
            ShipmentHeader shipmentHeader = new ShipmentHeader();
            shipmentHeader.setWarehouseCode(warehouseCode);
            shipmentHeader.setCompanyCode(companyCode);
            shipmentHeader.setCode(code);
            shipmentHeader.setShipmentType(QuantityConstant.SHIPMENT_BILL_TYPE_OS);
            shipmentHeader.setReferCode(req.getBillNo());//申请编码
            shipmentHeader.setCustomerCode(req.getCustId());
            shipmentHeader.setTotalQty(BigDecimal.ZERO);
            shipmentHeader.setTotalWeight(BigDecimal.ZERO);
            shipmentHeader.setShipmentNote(req.getNote());
            shipmentHeader.setTotalLines(0);
            shipmentHeader.setPriority(100);
            shipmentHeader.setFirstStatus(0);
            shipmentHeader.setLastStatus(0);
            shipmentHeader.setCreatedBy("ERP系统");
            shipmentHeader.setOrderQty(BigDecimal.ZERO);
            if (StringUtils.isNotEmpty(req.getReceiver())) {
                shipmentHeader.setCarrierCode(req.getReceiver());
            }
            result = shipmentHeaderService.save(shipmentHeader);
            if(!result){
                throw new ServiceException("出库单保存失败!");
            }
            ReferenceCode ref = new ReferenceCode();
            ref.setReferType(shipmentHeader.getReferCodeType());
            ref.setReferType(req.getBillTypeId());
            ref.setBillno(req.getBillNo());
            ref.setCreated(DateUtils.getNowDate());
            ref.setCreatedBy(QuantityConstant.PLATFORM_ERP);
            ref.setTypeName(QuantityConstant.BILL_TYPE_NAME_SO);
            referenceCodeService.save(ref);
            List<ShipmentRequestEntity> entity = req.getEntity();
            List<ShipmentDetail> shipmentDetailList = new ArrayList<ShipmentDetail>();
            for (ShipmentRequestEntity reqEntity : entity) {
                ShipmentDetail shipmentDetail = new ShipmentDetail();
                shipmentDetail.setShipmentId(shipmentHeader.getId());
                shipmentDetail.setFHTZDetail(reqEntity.getEntryId()+"");
                shipmentDetail.setWarehouseCode(warehouseCode);
                shipmentDetail.setCompanyCode(companyCode);
                shipmentDetail.setShipmentCode(code);
                LambdaQueryWrapper<Material> queryWrapper1 = Wrappers.lambdaQuery();
                queryWrapper1.eq(Material::getCode, reqEntity.getMaterialId());
                Material material = materialService.getOne(queryWrapper1);
                shipmentDetail.setMaterialCode(reqEntity.getMaterialId());
                shipmentDetail.setMaterialName(material.getName());
                shipmentDetail.setMaterialSpec(material.getSpec());
                shipmentDetail.setMaterialUnit(reqEntity.getBaseUnitId());

                shipmentDetail.setQty(reqEntity.getQty());
                shipmentDetail.setTaskQty(BigDecimal.ZERO);
                shipmentDetail.setBatch(reqEntity.getLot());
                shipmentDetail.setInventorySts("good");
                shipmentDetail.setStatus(0);
                shipmentDetail.setWaveId(0);
                shipmentDetail.setCreated(DateUtils.getNowDate());
                shipmentDetail.setProcessStamp(0 + "");
                shipmentDetail.setProductSize(reqEntity.getF100008());
                shipmentDetail.setProductSchedule(reqEntity.getF100007());
                shipmentDetail.setProPackaging(reqEntity.getF100003());
                shipmentDetail.setColor(reqEntity.getF100002());
                shipmentDetail.setLevel(reqEntity.getF100001());
                result  = shipmentDetailService.save(shipmentDetail);
                if(result){
                    shipmentHeader.setTotalWeight(shipmentHeader.getTotalWeight().add(reqEntity.getWeight()));
                    shipmentDetailList.add(shipmentDetail);
                }
                shipmentHeader.setStockId(reqEntity.getStockId());
                shipmentHeader.setTotalLines(shipmentHeader.getTotalLines() + 1);
                shipmentHeader.setTotalQty(shipmentHeader.getTotalQty().add(shipmentDetail.getQty()));
                shipmentHeader.setOrderQty(shipmentHeader.getOrderQty().add(shipmentDetail.getQty()));
                shipmentHeaderService.updateById(shipmentHeader);
            }
        }
        return ajaxResult;
    }

    //其他出库单
    @Override
    public AjaxResult pushShipmentRequest(PushModel pushModel) {
        AjaxResult ajaxResult = AjaxResult.error("下载失败");
        boolean result = false;
        int shipmentId = pushModel.getHeaderId();
        String srcStockId = pushModel.getSrcStockId();
        String srcStockLocId = pushModel.getSrcStockLocId();
        ShipmentHeader shipmentHeader = shipmentHeaderService.getById(shipmentId);
        if(shipmentHeader==null){
            throw new ServiceException("下推失败,找不到出库单内码 shipmentId:【"+shipmentId+"】找不到或被删除!!");
        }
        Stock srcStock = stockService.getById(srcStockId);
        if(srcStock==null){
            throw new ServiceException("下推失败,找不到源仓库内码 srcStockId:【"+srcStockId+"】找不到或被删除!!");
        }
        //entrys
        List<PushTransferEntity> entrys = new ArrayList<>();
        //Parameters
        PushTransfer parameters = new PushTransfer();
        //ExtOperateParam
        ExtOperateParam param = new ExtOperateParam();
        LambdaQueryWrapper<ShipmentDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ShipmentDetail::getShipmentId,shipmentId);
        List<ShipmentDetail> shipmentDetailList = shipmentDetailService.list(queryWrapper);

        for (int i = 0; i < shipmentDetailList.size(); i++) {
            PushTransferEntity entity = new PushTransferEntity();
            ShipmentDetail shipmentDetail = shipmentDetailList.get(i);
            entity.setHtzDetail(shipmentDetail.getFHTZDetail());//来自 出库申请单明细的referId
            entity.setNoteEntry("");
            entity.setSrcStockId(srcStockId);
            entity.setSrcStockLocId(srcStockLocId);
            entity.setActQty(shipmentDetail.getQty().intValue());
            entrys.add(entity);
        }
        parameters.setSargetBillTypeNum("54533291F9A44D38809F70000499BEE9");
        parameters.setSrcBillNo(shipmentHeader.getReferCode());//来自出库申请单的referCode
        parameters.setEntrys(entrys);
        param.setParameters(parameters);
        param.setNumbers(shipmentHeader.getReferCode());//来自出库申请单的referCode

        OperatorResult operatorResult = null;
        ApiLog log = null;
        Gson gson = new Gson();
        HttpHeaders headers = new HttpHeaders();
        String msg = "WMS请求发送成功,接收返回内容是空的";
        try {
            String formId = "STK_OutStockApply";
            String type = "DoNothingPushOut";
            String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_POST,
                    QuantityConstant.DEFAULT_WAREHOUSE, "");
            ErpPushParam erpPushParam = new ErpPushParam();
            erpPushParam.setType(type);
            erpPushParam.setFormId(formId);
            erpPushParam.setData(param);

            Object[] objects = new Object[]{formId, type, param.toJson()};
            ErpSaveObject erpSaveObject = new ErpSaveObject();
            erpSaveObject.setParameters(objects);

            String body = gson.toJson(erpSaveObject);
            System.out.println(body);
            String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
            if(StringUtils.isEmpty(sessionId)){
                throw new ServiceException("sessionId不能为空");
            }
            log = ApiLogAspect.initApiLog("post", QuantityConstant.URL+"STK_OutStockApply",
                    body, headers, QuantityConstant.DEFAULT_WAREHOUSE);
            String okResult = OkHttpUtils.bodypost(url, body, sessionId);
            operatorResult = JSON.parseObject(okResult, OperatorResult.class);
            RepoStatus results = operatorResult.getResult().getResponseStatus();
            if(!results.isIsSuccess()){
                ArrayList<RepoError> errors = results.getErrors();
                msg = JSON.toJSONString(errors);
                return AjaxResult.error(msg);
            }else{
                SuccessEntity success = results.getSuccessEntitys().get(0);
                String id = success.getId();
                String number = success.getNumber();
                shipmentHeader.setReferId(Integer.parseInt(id));
                shipmentHeader.setReferCode(number);
                shipmentHeader.setFirstStatus(900);
                shipmentHeader.setLastStatus(900);
                shipmentHeaderService.updateById(shipmentHeader);
                msg = JSON.toJSONString(results.getSuccessEntitys());

            }
        }catch (Exception e) {
            e.printStackTrace();
            ApiLogAspect.setApiLogException(log, e);
        } finally {
            ApiLogAspect.finishApiLog(log, headers, msg);
        }
        return AjaxResult.success("回传成功");
    }

    private AjaxResult pushOtherBilling(PushModel pushModel){
        AjaxResult ajaxResult = AjaxResult.error("WMS请求发送成功,接收返回内容是空的");
        String msg = "WMS请求发送成功,接收返回内容是空的";
        HttpHeaders headers = new HttpHeaders();
        ApiLog log = null;
        OperatorResult operatorResult = null;

        Gson gson = new Gson();
        int headerId = pushModel.getHeaderId();
        ReceiptHeader receiptHeader = receiptHeaderService.getById(headerId);
        String srcStockId = pushModel.getSrcStockId();
        String srcStockLocId = pushModel.getSrcStockLocId();
        String destStockId = pushModel.getDestStockId();
        String destStockLocId = pushModel.getDestStockLocId();
        if(headerId==0){
            return AjaxResult.error("入库单id:【"+headerId+"】为空。");
        }
        if(receiptHeader==null){
            return AjaxResult.error("入库单id:【"+headerId+"】不存在。");
        }
        List<PushTransferEntity> entrys = new ArrayList<>();
        PushTransfer parameters = new PushTransfer();
        ExtOperateParam param = new ExtOperateParam();

        LambdaQueryWrapper<ReceiptDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ReceiptDetail::getReceiptId,receiptHeader.getId());
        List<ReceiptDetail> receiptDetailList = receiptDetailService.list(queryWrapper);

        for (int i = 0; i < receiptDetailList.size(); i++) {
            PushTransferEntity entity = new PushTransferEntity();
            ReceiptDetail receiptDetail = receiptDetailList.get(i);
            entity.setHtzDetail(receiptDetail.getReferId()+"");
            entity.setNoteEntry("");
            entity.setSrcStockId(srcStockId);
            entity.setSrcStockLocId(srcStockLocId);
            entity.setActQty(receiptDetail.getQty().intValue());
            entrys.add(entity);
        }
        parameters.setSargetBillTypeNum("54533291F9A44D38809F70000499BEE9");
        parameters.setSrcBillNo(receiptHeader.getReferCode());
        parameters.setEntrys(entrys);
        param.setParameters(parameters);
        param.setNumbers(receiptHeader.getReferCode());
//        String body = gson.toJson(param);
        try {
//            operatorResult = api.pushOperator("STK_MisDelivery", "", param);
            String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_POST,
                    QuantityConstant.DEFAULT_WAREHOUSE, "");
            String formId = "STK_MisDelivery";
            String type = "";
            Object[] objects = new Object[]{formId, type, param.toJson()};
            ErpSaveObject erpSaveObject = new ErpSaveObject();
            erpSaveObject.setParameters(objects);
            String body = gson.toJson(erpSaveObject);
            System.out.println(body);
            String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
            if(StringUtils.isEmpty(sessionId)){
                throw new ServiceException("sessionId不能为空");
            }
            log = ApiLogAspect.initApiLog("post", QuantityConstant.URL+"STK_MisDelivery",
                    body, headers, QuantityConstant.DEFAULT_WAREHOUSE);
            String okResult = OkHttpUtils.bodypost(url, body, sessionId);
            operatorResult = JSON.parseObject(okResult, OperatorResult.class);
            RepoStatus results = operatorResult.getResult().getResponseStatus();
            if(!results.isIsSuccess()){
                ArrayList<RepoError> errors = results.getErrors();
                msg = JSON.toJSONString(errors);
                throw new ServiceException(msg);
            }
        }catch (Exception e) {
            e.printStackTrace();
            ApiLogAspect.setApiLogException(log, e);
        } finally {
            ApiLogAspect.finishApiLog(log, headers, msg);
        }
        return AjaxResult.success("回传成功");
    }

    /*
    下载发货通知单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @ProcessTrack(taskName = "出库单据创建", processCode = ProcessCode.SHIPMENT_BILL_CODE)
    public AjaxResult downLoadDeliveryNotice() {
        String key = configService.getKey(QuantityConstant.DEILVERYNOTICE_FILTERSTRING);
        if(StringUtils.isEmpty(key)){
            return AjaxResult.error("过滤参数不能为空");
        }
        String currentSQL = " and FDate >= '";
        String before_bill_date = configService.getKey(QuantityConstant.BEFORE_BILL_DATE_NUM).trim();
        if(StringUtils.isEmpty(before_bill_date)){
            before_bill_date = "-30";
        }
        Integer num = Integer.parseInt(before_bill_date);
        /*获取当前日期 指定天数的时间。*/
        String presetDate = DateUtils.getPresetDate(DateUtils.getNowDate(), DateUtils.YYYY_MM_DD_HH_MM_SS, num);
        if(presetDate==null){
            currentSQL = "";
        }else{
            currentSQL += presetDate+"'";
        }
        key += currentSQL;
        AjaxResult ajaxResult = AjaxResult.error("下载失败");
        boolean result = false;
        String warehouseCode = "CS0001";
        String companyCode = "JY";

        ErpRequest erpRequest = new ErpRequest();
        ErpParam erpParam =  new ErpParam();
        erpParam.setFormId("SAL_DELIVERYNOTICE"); //销售退货单
        erpParam.setFieldKeys("FId,FBillNo,FSOEntryId,FBillTypeID.FNumber,F_CH_LoadRemark,FreceiveAddress,F_CH_Address,F_CH_CKSPY.FNumber,Fnote,FReceiverContactID.FNumber,FownerTypeIdHead,Fdate,FsaleOrgId.FNumber,FCustomerID.FNumber,FEntity_FEntryId,F_CH_Driver,F_CH_Receiver,F_CH_LoadRemark,F_CH_CKSPY,F_CH_IsLoadFee,FReceiverContactID.FNAME,FReceiveAddress,FAuxpropID.FF100008.FNumber,FAuxpropID.FF100007.FNumber,FAuxpropID.FF100003.FNumber,FAuxpropID.FF100002.FNumber,FAuxpropID.FF100001.FNumber,F_CH_Slice,F_CH_BoxQty,FIsFree,Flot.FNumber,FbaseUnitId.FNumber,FnoteEntry,FstockId.FNumber,Fqty,FunitId.FNumber,FmateriaModel,FMaterialID.FNumber,FMaterialName,F_CH_Weight");
        erpParam.setFilterString(key);
        erpParam.setOrderString("FApproveDate DESC");
        erpRequest.setData(erpParam);
        String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_QUERY, warehouseCode, "");
        String jsonParam = JSON.toJSONString(erpRequest);
        System.out.println(jsonParam);
        String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
        if(StringUtils.isEmpty(sessionId)){
            throw new ServiceException("sessionId不能为空");
        }
        String okResult = OkHttpUtils.bodypost(url, jsonParam, sessionId);
        String fieldKeys = erpParam.getFieldKeys();
        List<DeliveryNotices> datas = null;
        try {
            datas = loadDataList(fieldKeys, DeliveryNotices.class, okResult);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (datas==null)
        {
            return AjaxResult.error("拉取上游获取的订单为null");
        }

        List<DeliveryNotice> deliveryNoticeList = DeliveryNotices.transfer(datas);
        if(deliveryNoticeList.size()==0){
            return AjaxResult.success("更新成功");
        }else{
            result = true;
        }
        LambdaQueryWrapper<ReferenceCode> queryWrapper2 = Wrappers.lambdaQuery();
        queryWrapper2.isNotNull(ReferenceCode::getBillno)
                .eq(ReferenceCode::getTypeName,QuantityConstant.BILL_TYPE_NAME_DN)
                .ne(ReferenceCode::getBillno,"");

        List<String> billNos = referenceCodeService.list(queryWrapper2).stream().distinct().map(ReferenceCode::getBillno).collect(Collectors.toList());

        List<DeliveryNotice> collect = deliveryNoticeList.stream()
                .filter(s -> !billNos.contains(s.getBillNo())).collect(Collectors.toList());

        for (DeliveryNotice deliveryNotice : collect) {


            String driver = deliveryNotice.getDriver();
            String[] arr = driver.split("/");
            if (arr.length != 4)
            {
                return AjaxResult.error("切割信息错误 司机信息不全");
            }
            String code = shipmentHeaderService.createCode(QuantityConstant.SHIPMENT_BILL_TYPE_DN);
            ShipmentHeader shipmentHeader = new ShipmentHeader();
            shipmentHeader.setWarehouseCode(warehouseCode);
            shipmentHeader.setCompanyCode(companyCode);
            shipmentHeader.setCode(code);
            shipmentHeader.setShipmentType(QuantityConstant.SHIPMENT_BILL_TYPE_DN);
            shipmentHeader.setReferId(deliveryNotice.getId());
            shipmentHeader.setReferCode(deliveryNotice.getBillNo());
            shipmentHeader.setReferCodeType(deliveryNotice.getBillTypeId());
            shipmentHeader.setTotalQty(BigDecimal.ZERO);
            shipmentHeader.setTotalWeight(BigDecimal.ZERO);
            shipmentHeader.setTotalLines(0);
            //装车备注
            shipmentHeader.setShipmentNote(deliveryNotice.getLoadRemark());
            shipmentHeader.setPriority(100);
            shipmentHeader.setDriverName(arr[1]);
            shipmentHeader.setDriverTel(arr[3]);
            shipmentHeader.setPlateNumber(arr[0]);
            shipmentHeader.setIdentity(Long.valueOf(arr[2]));
            shipmentHeader.setFirstStatus(0);
            shipmentHeader.setLastStatus(0);
            shipmentHeader.setCreatedBy("ERP系统");
            shipmentHeader.setCreated(new Date());
            shipmentHeader.setLastUpdated(new Date());
            shipmentHeader.setOrderQty(BigDecimal.ZERO);
            LambdaQueryWrapper<Customer> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(Customer::getCode,deliveryNotice.getCustomerId());
            queryWrapper.eq(Customer::getWarehouseCode,QuantityConstant.DEFAULT_WAREHOUSE);
            Customer customer = customerService.getOne(queryWrapper);
            if(customer!=null){
                shipmentHeader.setCustomerCode(customer.getCode());
                shipmentHeader.setCustomerName(customer.getName());
            }
//            shipmentHeader.setDriverName(deliveryNotice.getDriver());
//            shipmentHeader.setDriverTel(deliveryNotice.getLinkPhone());
            result = shipmentHeaderService.save(shipmentHeader);
            if(!result){
                throw new ServiceException("出库单保存失败!");
            }
            ReferenceCode ref = new ReferenceCode();
            ref.setReferType(shipmentHeader.getReferCodeType());
            ref.setReferType(deliveryNotice.getBillTypeId());
            ref.setBillno(deliveryNotice.getBillNo());
            ref.setCreated(DateUtils.getNowDate());
            ref.setCreatedBy(QuantityConstant.PLATFORM_ERP);
            ref.setTypeName(QuantityConstant.BILL_TYPE_NAME_DN);
            referenceCodeService.save(ref);
            List<DeliveryNoticeEntity> entity = deliveryNotice.getEntity();
            List<ShipmentDetail> shipmentDetailList = new ArrayList<ShipmentDetail>();
            for (int i = 0; i < entity.size(); i++) {
                Material material = materialService.getMaterialByCode(entity.get(i).getMaterialId());
                if (material==null)
                {
                    continue;
                }
                DeliveryNoticeEntity deliveryNoticeEntity = entity.get(i);
                ShipmentDetail shipmentDetail = new ShipmentDetail();
                shipmentDetail.setReferId(deliveryNoticeEntity.getEntryId());//上游订单明细id
                shipmentDetail.setReferCode(shipmentHeader.getReferCode());//上游订单编号
                shipmentDetail.setShipmentId(shipmentHeader.getId());
                shipmentDetail.setWarehouseCode(warehouseCode);
                shipmentDetail.setCompanyCode(companyCode);
                shipmentDetail.setShipmentCode(code);
                shipmentDetail.setFHTZDetail(i+1+""+shipmentHeader.getReferId());
                shipmentDetail.setSoEntryId(deliveryNoticeEntity.getSoEntryId());

                shipmentDetail.setMaterialCode(deliveryNoticeEntity.getMaterialId());
                shipmentDetail.setMaterialName(deliveryNoticeEntity.getMaterialName());
                shipmentDetail.setMaterialSpec(deliveryNoticeEntity.getMateriaModel());
                shipmentDetail.setMaterialUnit(deliveryNoticeEntity.getBaseUnitId());

                shipmentDetail.setQty(deliveryNoticeEntity.getQty());
                shipmentDetail.setTaskQty(BigDecimal.ZERO);
                shipmentDetail.setBatch(deliveryNoticeEntity.getLot());
                shipmentDetail.setInventorySts("good");
                shipmentDetail.setStatus(0);
                shipmentDetail.setWaveId(0);
                shipmentDetail.setCreated(DateUtils.getNowDate());
                shipmentDetail.setProcessStamp(0 + "");
                shipmentDetail.setProductSize(deliveryNoticeEntity.getF100008());
                shipmentDetail.setProductSchedule(deliveryNoticeEntity.getF100007());
                shipmentDetail.setProPackaging(deliveryNoticeEntity.getF100003());
                shipmentDetail.setColor(deliveryNoticeEntity.getF100002());
                shipmentDetail.setLevel(deliveryNoticeEntity.getF100001());
                result  = shipmentDetailService.save(shipmentDetail);
                if(result){
                    shipmentHeader.setTotalWeight(shipmentHeader.getTotalWeight().add(deliveryNoticeEntity.getWeight()));
                    shipmentDetailList.add(shipmentDetail);
                }
                shipmentHeader.setTotalLines(shipmentHeader.getTotalLines() + 1);
                shipmentHeader.setTotalQty(shipmentHeader.getTotalQty().add(shipmentDetail.getQty()));
                shipmentHeader.setOrderQty(shipmentHeader.getOrderQty().add(shipmentDetail.getQty()));
                result = shipmentHeaderService.updateById(shipmentHeader);
            }
        }
        if(result){
            ajaxResult.setCode(200);
            ajaxResult.setMsg("下载成功");
        }
        return ajaxResult;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult pushDirectTransfer(PushModel pushModel) {
        AjaxResult ajaxResult = AjaxResult.success("回传成功");
        String msg = "WMS请求发送成功,接收返回内容是空的";
        boolean result = false;
        int receiptId = pushModel.getHeaderId();
        String srcStockId = pushModel.getSrcStockId();
        String srcStockLocId = pushModel.getSrcStockLocId();
        String destStockId = pushModel.getDestStockId();
        String destStockLocId = pushModel.getDestStockLocId();
        ReceiptHeader receiptHeader = receiptHeaderService.getById(receiptId);
        if(receiptHeader==null){
            throw new ServiceException("下推失败,找不到入库单内码 receiptId:【"+receiptId+"】找不到或被删除!!");
        }
        Stock srcStock = stockService.getById(srcStockId);
        if(srcStock==null){
            throw new ServiceException("下推失败,找不到源仓库内码 srcStockId:【"+srcStockId+"】找不到或被删除!!");
        }
        Stock destStock = stockService.getById(destStockId);
        if(destStock==null){
            throw new ServiceException("下推失败,找不到目标仓库内码 destStock:【"+destStockId+"】找不到或被删除!!");
        }
        LambdaQueryWrapper<ReceiptDetail> queryWrapper3 = Wrappers.lambdaQuery();
        queryWrapper3.eq(ReceiptDetail::getReceiptId,receiptHeader.getId());
        List<ReceiptDetail> list = receiptDetailService.list(queryWrapper3);
        List<String> FHTZDetails = list.stream().map(ReceiptDetail::getFHTZDetail).collect(Collectors.toList());
        if(FHTZDetails.size() == 0 ){
            return AjaxResult.error("找不到关联发货通知单 FHTZDetails");
        }

        ShipmentHeader noticeShipment = shipmentHeaderService.getOne(new LambdaQueryWrapper<ShipmentHeader>()
                .eq(ShipmentHeader::getCode, receiptHeader.getShipmentCode()));
        List<ShipmentHeader> shipmentHeaders = shipmentHeaderService.list(new LambdaQueryWrapper<ShipmentHeader>()
                .eq(ShipmentHeader::getReferCode, noticeShipment.getReferCode()));
        List<Integer> ids = shipmentHeaders.stream().map(ShipmentHeader::getId).collect(Collectors.toList());
        List<ShipmentDetail> shipmentDetails = shipmentDetailService.list(new LambdaQueryWrapper<ShipmentDetail>()
                .in(ShipmentDetail::getShipmentId, ids));

        //发货通知单 数量
        Map<String,BigDecimal> k3BillData = new HashMap<>();
        for (ShipmentDetail shipmentDetail : shipmentDetails) {
            if(k3BillData.containsKey(shipmentDetail.getFHTZDetail())){
                k3BillData.put(shipmentDetail.getFHTZDetail(),k3BillData.get(shipmentDetail.getFHTZDetail()).add(shipmentDetail.getQty()));
            }else{
                k3BillData.put(shipmentDetail.getFHTZDetail(),shipmentDetail.getQty());
            }
        }

        List<String> codes = shipmentHeaders.stream().map(ShipmentHeader::getCode).collect(Collectors.toList());
        //所有发货通知单对应的直接调拨单。
        List<ReceiptHeader> receiptHeaders = receiptHeaderService.list(new LambdaQueryWrapper<ReceiptHeader>()
                .in(ReceiptHeader::getShipmentCode, codes));
        for (ReceiptHeader header : receiptHeaders) {
            if(header.getFirstStatus()==800 && header.getLastStatus()==800){
                continue;
            }else{
                return AjaxResult.error("直接调拨单回传:未全部为回传状态,不可回传。");
            }
        }
        List<ReceiptDetail> receiptDetails = receiptDetailService.list(new LambdaQueryWrapper<ReceiptDetail>()
                .in(ReceiptDetail::getReceiptId, receiptHeaders.stream().map(ReceiptHeader::getId).collect(Collectors.toList())));


        Map<String,BigDecimal> zjdbData = new HashMap<>();
        for (ReceiptDetail receiptDetail : receiptDetails) {
            if(zjdbData.containsKey(receiptDetail.getFHTZDetail())){
                zjdbData.put(receiptDetail.getFHTZDetail(),zjdbData.get(receiptDetail.getFHTZDetail()).add(receiptDetail.getQty()));
            }else{
                zjdbData.put(receiptDetail.getFHTZDetail(),receiptDetail.getQty());
            }
        }
        boolean equals = zjdbData.equals(k3BillData);
        if(!equals){
            return AjaxResult.error("回传:调拨单数量和发货通知单数量不匹配,请检查数据。");
        }

        //entrys
        List<PushTransferEntity> entrys = new ArrayList<>();
        //Parameters
        PushTransfer parameters = new PushTransfer();
        //ExtOperateParam
        ExtOperateParam param = new ExtOperateParam();

        Set<String> sets = new HashSet<>();
        for (ReceiptDetail receiptDetail : receiptDetails) {
            PushTransferEntity entity = new PushTransferEntity();
            if(sets.contains(receiptDetail.getFHTZDetail())){
                continue;
            }
            sets.add(receiptDetail.getFHTZDetail());
            entity.setEntryId(noticeShipment.getReferId()+"");
            entity.setNoteEntry("");
            entity.setSrcStockId(srcStockId);
            entity.setSrcStockLocId(srcStockLocId);
            entity.setDestStockId(destStockId);
            entity.setDestStockLocId(destStockLocId);
            entity.setActQty(zjdbData.get(receiptDetail.getFHTZDetail()).intValue());
            entity.setHtzDetail(receiptDetail.getFHTZDetail());
            entity.setSoEntryId(receiptDetail.getSoEntryId()+"");
            entrys.add(entity);
        }

        parameters.setSrcBillNo(noticeShipment.getReferCode());
        parameters.setEntrys(entrys);
        param.setParameters(parameters);
        param.setNumbers(noticeShipment.getReferCode());
        Gson gson2 = new Gson();
        System.out.println(gson2.toJson(param));

        OperatorResult operatorResult = null;
        ApiLog log = null;
        HttpHeaders headers = new HttpHeaders();
        try {
//            operatorResult = api.pushOperator(QuantityConstant.SAL_DELIVERYNOTICE,
//                    QuantityConstant.DoNothing_PushTransferRin, param);
            String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_POST,
                    QuantityConstant.DEFAULT_WAREHOUSE, "");
            String formId = QuantityConstant.SAL_DELIVERYNOTICE;
            String type = QuantityConstant.DoNothing_PushTransferRin;
            Object[] objects = new Object[]{formId, type, param.toJson()};
            ErpSaveObject erpSaveObject = new ErpSaveObject();
            erpSaveObject.setParameters(objects);
            Gson gson = new Gson();
            String body = gson.toJson(erpSaveObject);
            System.out.println(body);
            String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
            if(StringUtils.isEmpty(sessionId)) {
                throw new ServiceException("sessionId不能为空");
            }
            log = ApiLogAspect.initApiLog("post", QuantityConstant.URL+QuantityConstant.SAL_DELIVERYNOTICE,
                    body, headers, QuantityConstant.DEFAULT_WAREHOUSE);
            String okResult = OkHttpUtils.bodypost(url, body, sessionId);
            operatorResult = JSON.parseObject(okResult, OperatorResult.class);
            RepoStatus results = operatorResult.getResult().getResponseStatus();
            boolean isSuccess = results.isIsSuccess();
            String directId = "";
            String directCode = "";

            if(isSuccess){
                ArrayList<SuccessEntity> successEntitys = results.getSuccessEntitys();
                SuccessEntity success = successEntitys.get(0);
                for (ReceiptHeader header : receiptHeaders) {
                    directId = success.getId();
                    directCode = success.getNumber();
                    //修改直接调拨单referId referCode
                    header.setReferId(Integer.valueOf(directId));
                    header.setReferCode(directCode);
                    header.setFirstStatus(QuantityConstant.RECEIPT_HEADER_RETURN);
                    header.setLastStatus(QuantityConstant.RECEIPT_HEADER_RETURN);
                    receiptHeaderService.updateById(header);

                    noticeShipment.setFirstStatus(QuantityConstant.RECEIPT_HEADER_RETURN);
                    noticeShipment.setLastStatus(QuantityConstant.RECEIPT_HEADER_RETURN);
                    shipmentHeaderService.updateById(noticeShipment);
                }
                msg = "回传成功";
                //更新直接调拨单 状态
            } else {
                ArrayList<RepoError> errors = results.getErrors();
                msg = JSONArray.toJSONString(errors);
                return AjaxResult.error(msg);
            }
        }catch (Exception e) {
            e.printStackTrace();
            ApiLogAspect.setApiLogException(log, e);
        } finally {
            ApiLogAspect.finishApiLog(log, headers, msg);
        }
        return ajaxResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ProcessTrack(taskName = "出库单据回传" , processCode = ProcessCode.SHIPMENT_BILL_CODE)
    public AjaxResult pushSalesDelivery(PushModel pushModel) {
        /**
         * 1.先获取需要推送的表单id receiptId
         * 2.通过表单id 查询明细 receiptCode
         * 3.构建下推 销售出库单实体
         * 4.发送下推() 接收返回参数 erp销售出库单id billNo update
         */
        AjaxResult ajaxResult = AjaxResult.success("回传成功");
        boolean result = false;
        int shipmentId = pushModel.getHeaderId();
        ShipmentHeader shipmentHeader = shipmentHeaderService.getById(shipmentId);
        if(shipmentHeader==null){
            throw new ServiceException("下推失败,找不到出库单内码 shipmentId:【"+shipmentId+"】找不到或被删除!!");
        }

        LambdaQueryWrapper<ShipmentDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ShipmentDetail::getShipmentId,shipmentId);
        //销售出库单明细
        List<ShipmentDetail> shipmentDetailList = shipmentDetailService.list(queryWrapper);
        List<String> fHTZDetails = shipmentDetailList.stream().map(ShipmentDetail::getFHTZDetail).collect(Collectors.toList());
        String fhtz = fHTZDetails.get(0);
        List<ReceiptDetail> receiptDetails = receiptDetailService.list(new LambdaQueryWrapper<ReceiptDetail>()
                .eq(ReceiptDetail::getFHTZDetail, fhtz));

        ReceiptHeader directReceipt = receiptHeaderService.getById(receiptDetails.get(0).getReceiptId());

        //获取该订单 直接调拨单所有的FHTZDetail
        List<ReceiptHeader> receiptHeaders = receiptHeaderService.list(new LambdaQueryWrapper<ReceiptHeader>()
                .eq(ReceiptHeader::getReferCode, directReceipt.getReferCode()));
        List<Integer> ids = receiptHeaders.stream().map(ReceiptHeader::getId).collect(Collectors.toList());
        List<ReceiptDetail> detailList = receiptDetailService.list(new LambdaQueryWrapper<ReceiptDetail>()
                .in(ReceiptDetail::getReceiptId, ids));
        List<String> fhtzs = detailList.stream().distinct().map(ReceiptDetail::getFHTZDetail).collect(Collectors.toList());
        //获取直接调拨单 订单数量
        Map<String,BigDecimal> map = new HashMap<>();
        for (ReceiptDetail receiptDetail : detailList) {
            if(map.containsKey(receiptDetail.getFHTZDetail())){
                map.put(receiptDetail.getFHTZDetail(),map.get(receiptDetail.getFHTZDetail()).add(receiptDetail.getQty()));
            }else{
                map.put(receiptDetail.getFHTZDetail(),receiptDetail.getQty());
            }
        }
        //获取销售出库单 订单数量
        List<ShipmentDetail> shipmentDetails = shipmentDetailService.list(new LambdaQueryWrapper<ShipmentDetail>()
                .in(ShipmentDetail::getFHTZDetail, fhtzs));
        List<Integer> ids2 = shipmentDetails.stream().distinct().map(ShipmentDetail::getShipmentId).collect(Collectors.toList());
        List<ShipmentHeader> shipmentHeaders = shipmentHeaderService.list(new LambdaQueryWrapper<ShipmentHeader>()
                .in(ShipmentHeader::getId, ids2));
        List<ShipmentHeader> shipmentHeaderList = new ArrayList<>();
        for (ShipmentHeader header : shipmentHeaders) {
            if((header.getFirstStatus()==500||header.getFirstStatus()==900) && (header.getLastStatus()==500||header.getLastStatus()==900)){
                if(header.getShipmentType().equals(QuantityConstant.SHIPMENT_BILL_TYPE_SP)){
                    shipmentHeaderList.add(header);
                }
                continue;
            }else{
                return AjaxResult.error("销售出库回传:未全部为回传状态,不可回传。");
            }
        }
        List<Integer> ids3 = shipmentHeaderList.stream().distinct().map(ShipmentHeader::getId).collect(Collectors.toList());

        Map<String,BigDecimal> map1 = new HashMap<>();
        for (ShipmentDetail shipmentDetail : shipmentDetails) {
            if(ids3.contains(shipmentDetail.getShipmentId())){
                //用于拆单情况
                if(map1.containsKey(shipmentDetail.getFHTZDetail())){
                    map1.put(shipmentDetail.getFHTZDetail(),map1.get(shipmentDetail.getFHTZDetail()).add(shipmentDetail.getQty()));
                }else{
                    map1.put(shipmentDetail.getFHTZDetail(),shipmentDetail.getQty());
                }
            }
        }
        //比较
        boolean equals = map1.equals(map);
        if(!equals){
            return AjaxResult.error("销售出库回传:销售出库单数量和直接调拨单数量不匹配,请检查数据。");
        }
        Set<String> sets = new HashSet<>();
        //entrys
        List<PushTransferEntity> entrys = new ArrayList<>();
        //Parameters
        PushTransfer parameters = new PushTransfer();
        //ExtOperateParam
        ExtOperateParam param = new ExtOperateParam();
        for (ShipmentDetail shipmentDetail : shipmentDetailList) {
            PushTransferEntity entity = new PushTransferEntity();
            if(sets.contains(shipmentDetail.getFHTZDetail())){
                continue;
            }
            entity.setActQty(map1.get(shipmentDetail.getFHTZDetail()).intValue());
            entity.setHtzDetail(shipmentDetail.getFHTZDetail());
            entrys.add(entity);
        }
        parameters.setSrcBillNo(directReceipt.getReferCode());
        parameters.setEntrys(entrys);
        param.setParameters(parameters);
        param.setNumbers(directReceipt.getReferCode());
        Gson gson2 = new Gson();
        ApiLog log = null;
        HttpHeaders headers = new HttpHeaders();
        OperatorResult operatorResult = null;
        String msg = "WMS请求发送成功,接收返回内容是空的";
        try {
            String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_POST,
                    QuantityConstant.DEFAULT_WAREHOUSE, "");
            String formId = "STK_TransferDirect";
            String type = "DoNothing_TransferPushSaleOut";
            Object[] objects = new Object[]{formId, type, param.toJson()};
            ErpSaveObject erpSaveObject = new ErpSaveObject();
            erpSaveObject.setParameters(objects);
            Gson gson = new Gson();
            String body = gson.toJson(erpSaveObject);
            System.out.println(body);
            String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
            if(StringUtils.isEmpty(sessionId)) {
                throw new ServiceException("sessionId不能为空");
            }
            log = ApiLogAspect.initApiLog("post", QuantityConstant.URL+"STK_TransferDirect",
                    body, headers, QuantityConstant.DEFAULT_WAREHOUSE);
//            operatorResult = api.pushOperator("STK_TransferDirect", "DoNothing_TransferPushSaleOut", param);
            String okResult = OkHttpUtils.bodypost(url, body, sessionId);
            operatorResult = JSON.parseObject(okResult, OperatorResult.class);
            RepoStatus results = operatorResult.getResult().getResponseStatus();
            boolean isSuccess = results.isIsSuccess();
            msg = JSON.toJSONString(results.getSuccessEntitys());
            if(isSuccess){
                ArrayList<SuccessEntity> successEntitys = results.getSuccessEntitys();
                SuccessEntity success = successEntitys.get(0);
                for (ShipmentHeader header : shipmentHeaderList) {
                    header.setReferId(Integer.valueOf(success.getId()));
                    header.setReferCode(success.getNumber());
                    header.setLastStatus(900);
                    header.setFirstStatus(900);
                    shipmentHeaderService.updateById(header);
                }
            }else{
                ArrayList<RepoError> errors = results.getErrors();
                msg = JSON.toJSONString(errors);
                return AjaxResult.error(msg);
//                throw new ServiceException(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ApiLogAspect.setApiLogException(log, e);
        } finally {
            ApiLogAspect.finishApiLog(log, headers, msg);
        }
        return AjaxResult.success("回传成功");
    }


    /*
     ** 下载退货通知单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult downloadReturnNotice() {

        String key = configService.getKey(QuantityConstant.RETURNNOTICE_FILTERSTRING);
        if(StringUtils.isEmpty(key)){
            return AjaxResult.error("过滤参数不能为空");
        }
        String currentSQL = " and FDate >= '";
        String before_bill_date = configService.getKey(QuantityConstant.BEFORE_BILL_DATE_NUM).trim();
        if(StringUtils.isEmpty(before_bill_date)){
            before_bill_date = "-30";
        }
        Integer num = Integer.parseInt(before_bill_date);
        /*获取当前日期 指定天数的时间。*/
        String presetDate = DateUtils.getPresetDate(DateUtils.getNowDate(), DateUtils.YYYY_MM_DD_HH_MM_SS, num);
        if(presetDate==null){
            currentSQL = "";
        }else{
            currentSQL += presetDate+"'";
        }
        key += currentSQL;
        AjaxResult ajaxResult = AjaxResult.success("出库列表已更新为最新状态!!");
        boolean result = false;
        String warehouseCode = "CS0001";
        String companyCode = "JY";
        ErpRequest erpRequest = new ErpRequest();
        ErpParam erpParam =  new ErpParam();
            erpParam.setFormId("SAL_RETURNNOTICE"); //销售退货单
        erpParam.setFieldKeys("FId,FBillNo,FDate,FBillTypeID.FNumber,FRetorgId.FNumber,FReceiveCusContact,FDescription,FReturnReason,FownerTypeIdHead,FsaleOrgId.FNumber,FretcustId.FNumber,FEntity_FEntryId,FLinkPhone,FLinkMan,FReceiveAddress,FAuxpropID.FF100008.FNumber,FAuxpropID.FF100007.FNumber,FAuxpropID.FF100003.FNumber,FAuxpropID.FF100002.FNumber,FAuxpropID.FF100001.FNumber,F_CH_pieces,F_CH_box,Flot.FNumber,FaseUnitId.FNumber,FstockId.FNumber,FunitId.FNumber,FMaterialModel,FMaterialID.FNumber,FMaterialName,Fqty,F_CH_Weight,F_CH_BillType,FdeliveryDate,FIsFree");
        erpParam.setFilterString(key);
        erpRequest.setData(erpParam);
        String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_QUERY, warehouseCode, "");
        String jsonParam = JSON.toJSONString(erpRequest);
        System.out.println(jsonParam);
        String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
        if(StringUtils.isEmpty(sessionId)){
            return AjaxResult.error("sessionId不能为空");
        }
        String okResult = OkHttpUtils.bodypost(url, jsonParam, sessionId);
        String fieldKeys = erpParam.getFieldKeys();
        List<ReturnNotices> returnNotices  = null;
        try {
            returnNotices = loadDataList(fieldKeys, ReturnNotices.class, okResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<ReturnNotice> transfer;
        System.out.println("returnNotices:" + returnNotices);
        transfer = ReturnNotices.transfer(returnNotices);
        if(transfer.size()==0){
            return AjaxResult.error("没有找到退货通知单");
        }

        LambdaQueryWrapper<ReferenceCode> queryWrapper2 = Wrappers.lambdaQuery();
        queryWrapper2.isNotNull(ReferenceCode::getBillno)
                .ne(ReferenceCode::getBillno,"");

        List<String> billNos = referenceCodeService.list(queryWrapper2).stream().distinct().map(ReferenceCode::getBillno).collect(Collectors.toList());

        List<ReturnNotice> collect = transfer.stream()
                .filter(s -> !billNos.contains(s.getBillNo())).collect(Collectors.toList());
        if(collect!=null && collect.size() == 0){
            return ajaxResult;
        }
        //检查排产订单是否存在
        ReturnNoticeEntity returnNoticeEntity = collect.get(0).getEntity().get(0);
        String productSchedule = returnNoticeEntity.getF100007();
        ProductScheduleHeader productScheduleHeader = productScheduleHeaderService.getOne(new LambdaQueryWrapper<ProductScheduleHeader>()
                .eq(ProductScheduleHeader::getNumber, productSchedule));
        if(productScheduleHeader==null){
            return AjaxResult.error("数据库中 【"+productSchedule+"】排产订单不存在,请先更新排产订单。");
        }
        for (ReturnNotice req : collect) {
            String code = receiptHeaderService.createCode(QuantityConstant.RECEIPT_BILL_TYPE_SR);
            ReceiptHeader receiptHeader = new ReceiptHeader();
            receiptHeader.setWarehouseCode(warehouseCode);
            receiptHeader.setCompanyCode(companyCode);
            receiptHeader.setCode(code);
            receiptHeader.setReceiptType(QuantityConstant.RECEIPT_BILL_TYPE_SR);
            receiptHeader.setReferId(req.getId());//申请单内部号
            receiptHeader.setReferType(req.getBillTypeId());//申请单类型
            receiptHeader.setReferCode(req.getBillNo());//申请编码
            receiptHeader.setReferCodeAssist(req.getBillNo());
            receiptHeader.setTotalQty(BigDecimal.ZERO);
            receiptHeader.setReceiptNote(req.getDescription());
            receiptHeader.setTotalLines(0);
            receiptHeader.setFirstStatus(0);
            receiptHeader.setLastStatus(0);
            receiptHeader.setCreatedBy("ERP系统");
            receiptHeader.setOrderQty(BigDecimal.ZERO);

            result = receiptHeaderService.save(receiptHeader);
            if(!result){
                throw new ServiceException("出库单保存失败!");
            }
            ReferenceCode ref = new ReferenceCode();
            ref.setReferType(receiptHeader.getReferType());
            ref.setReferType(req.getBillTypeId());
            ref.setBillno(req.getBillNo());
            ref.setCreated(DateUtils.getNowDate());
            ref.setCreatedBy(QuantityConstant.PLATFORM_ERP);
            ref.setTypeName(QuantityConstant.BILL_TYPE_NAME_RN);
            referenceCodeService.save(ref);
            List<ReturnNoticeEntity> entity = req.getEntity();
            List<ReceiptDetail> receiptDetailList = new ArrayList<ReceiptDetail>();
            for (int i = 0; i < entity.size(); i++) {
                ReturnNoticeEntity reqEntity = entity.get(i);
                ReceiptDetail receiptDetail = new ReceiptDetail();
                receiptDetail.setReceiptId(receiptHeader.getId());
                receiptDetail.setWarehouseCode(warehouseCode);
                receiptDetail.setCompanyCode(companyCode);
                receiptDetail.setReferId(reqEntity.getEntryId());
                receiptDetail.setReceiptCode(code);
                LambdaQueryWrapper<Material> queryWrapper1 = Wrappers.lambdaQuery();
                queryWrapper1.eq(Material::getCode, reqEntity.getMaterialId());
                Material material = materialService.getOne(queryWrapper1);
                receiptDetail.setMaterialCode(reqEntity.getMaterialId());
                receiptDetail.setMaterialName(material.getName());
                receiptDetail.setMaterialSpec(material.getSpec());
                receiptDetail.setMaterialUnit(reqEntity.getAseUnitId());
                receiptDetail.setFHTZDetail(""+reqEntity.getEntryId());

                receiptDetail.setQty(reqEntity.getQty());
                receiptDetail.setBox(reqEntity.getBox());
                receiptDetail.setTaskQty(BigDecimal.ZERO);
                receiptDetail.setBatch(reqEntity.getLot());
                receiptDetail.setInventorySts("good");
                receiptDetail.setStatus(0);
                receiptDetail.setQcCheck("1");
                receiptDetail.setCreated(DateUtils.getNowDate());
                receiptDetail.setProcessStamp(0 + "");
                receiptDetail.setProductSize(reqEntity.getF100008());
                receiptDetail.setProductSchedule(reqEntity.getF100007());
                receiptDetail.setProPackaging(reqEntity.getF100003());
                receiptDetail.setColor(reqEntity.getF100002());
                receiptDetail.setLevel(reqEntity.getF100001());
                result  = receiptDetailService.save(receiptDetail);
                if(result){
                    receiptDetailList.add(receiptDetail);
                }
                receiptHeader.setOrderCode(reqEntity.getF100007());
                receiptHeader.setTotalLines(receiptHeader.getTotalLines() + 1);
                receiptHeader.setTotalQty(receiptHeader.getTotalQty().add(receiptDetail.getQty()));
                receiptHeader.setOrderQty(receiptHeader.getOrderQty().add(receiptDetail.getQty()));
                receiptHeaderService.updateById(receiptHeader);
            }
        }
        return ajaxResult;
    }


    @Override
    public AjaxResult pushReturnNotice(PushModel pushModel) {
        AjaxResult ajaxResult = AjaxResult.success("回传成功");
        boolean result = false;
        int receiptId = pushModel.getHeaderId();
        ReceiptHeader receiptHeader = receiptHeaderService.getById(receiptId);
        if(receiptHeader==null){
            throw new ServiceException("回传失败,找不到退销售退货单内码 receiptId:【"+receiptId+"】找不到或被删除!!");
        }
        //entrys
        List<PushTransferEntity> entrys = new ArrayList<>();
        //Parameters
        PushTransfer parameters = new PushTransfer();
        //ExtOperateParam
        ExtOperateParam param = new ExtOperateParam();
        LambdaQueryWrapper<ReceiptDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ReceiptDetail::getReceiptId,receiptId);
        //销售退货单明细
        List<ReceiptDetail> receiptDetailList = receiptDetailService.list(queryWrapper);

        for (ReceiptDetail receiptDetail : receiptDetailList) {
            PushTransferEntity entity = new PushTransferEntity();
            entity.setActQty(receiptDetail.getTaskQty().subtract(receiptDetail.getBackQty()).intValue());
            entity.setNoteEntry(pushModel.getRemakes());
            entity.setSrcStockId(pushModel.getSrcStockId());
            entity.setSrcStockLocId(pushModel.getDestStockLocId());
            entity.setHtzDetail(receiptDetail.getFHTZDetail());
            entrys.add(entity);
            receiptDetail.setBackQty(receiptDetail.getTaskQty());
        }
        parameters.setSargetBillTypeNum("66fba68dd04b499e8860966f2ee60117");
        parameters.setSrcBillNo(receiptHeader.getReferCode());
        parameters.setEntrys(entrys);


        param.setParameters(parameters);
        param.setNumbers(receiptHeader.getReferCode());
        Gson gson2 = new Gson();
        System.out.println(gson2.toJson(param));
        OperatorResult operatorResult = null;
        ApiLog log = null;
        HttpHeaders headers = new HttpHeaders();


//        String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_POST,
//                QuantityConstant.DEFAULT_WAREHOUSE, "");
//        System.out.println(body);
//        String okResult = OkHttpUtils.bodypost(url, body);

        String msg = "WMS请求发送成功,接收返回内容是空的";
        try {
            String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_POST,
                    QuantityConstant.DEFAULT_WAREHOUSE, "");
            String formId = QuantityConstant.SAL_RETURNNOTICE;
            String type = QuantityConstant.DoNothingPushOut;
            Object[] objects = new Object[]{formId, type, param.toJson()};
            ErpSaveObject erpSaveObject = new ErpSaveObject();
            erpSaveObject.setParameters(objects);
            Gson gson = new Gson();
            String body = gson.toJson(erpSaveObject);
            System.out.println(body);
            String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
            if(StringUtils.isEmpty(sessionId)) {
                throw new ServiceException("sessionId不能为空");
            }
            log = ApiLogAspect.initApiLog("post", QuantityConstant.URL+QuantityConstant.SAL_RETURNNOTICE,
                    body, headers, QuantityConstant.DEFAULT_WAREHOUSE);
//            operatorResult = api.pushOperator(QuantityConstant.SAL_RETURNNOTICE,
//                    QuantityConstant.DoNothingPushOut, param);
            String okResult = OkHttpUtils.bodypost(url, body, sessionId);
            operatorResult = JSON.parseObject(okResult, OperatorResult.class);
            RepoStatus results = operatorResult.getResult().getResponseStatus();
            msg = JSON.toJSONString(results.getSuccessEntitys());
            boolean isSuccess = results.isIsSuccess();
            String id = "";
            String code = "";

            if(isSuccess){
                ArrayList<SuccessEntity> successEntitys = results.getSuccessEntitys();
                SuccessEntity success = successEntitys.get(0);
                //更新 销售退货单明细
                receiptDetailService.updateBatchById(receiptDetailList);
                //更新 销售退货单
                receiptHeader.setReferId(Integer.valueOf(success.getId()));
                receiptHeader.setReferCode(success.getNumber());
                receiptHeader.setLastStatus(900);
                receiptHeader.setFirstStatus(900);
                receiptHeaderService.updateById(receiptHeader);
            }else{
                ArrayList<RepoError> errors = results.getErrors();
                msg = JSON.toJSONString(errors);
                return AjaxResult.error(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ApiLogAspect.setApiLogException(log, e);
        } finally {
            ApiLogAspect.finishApiLog(log, headers, msg);
        }
        return ajaxResult;
    }

    /**
     * 不用了
     * @param pushModel
     * @return
     */
    @Override
    public AjaxResult backK3Adjust(PushModel pushModel) {
        int headerId = pushModel.getHeaderId();
        ReceiptHeader receiptHeader = receiptHeaderService.getById(headerId);
        if(receiptHeader==null){
            return AjaxResult.error("入库单为空");
        }
        String msg = "WMS请求发送成功,接收返回内容是空的";
        if(receiptHeader.getFirstStatus() == 190 && receiptHeader.getLastStatus() == 190){
            List<ReceiptDetail> receiptDetails = receiptDetailService.findByReceiptId(headerId);
            K3AdjustHeader k3AdjustHeader = createK3AdjustHeader(receiptHeader);
            k3AdjustHeader = createK3AdjustDetail(k3AdjustHeader,receiptDetails);
            //回传标识
            String formId = "";
            ExtSaveParam saveParam = new ExtSaveParam<>(k3AdjustHeader);
            //返回结果
            SaveResult spInStock = null;
            ApiLog log = null;
            Gson gson = new Gson();

            HttpHeaders headers = new HttpHeaders();

            String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_SAVE, QuantityConstant.DEFAULT_WAREHOUSE, "");
            String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
            if(StringUtils.isEmpty(sessionId)){
                throw new ServiceException("sessionId不能为空");
            }

            ErpSaveObject request = new ErpSaveObject();
            request.setParameters(new Object[]{"STK_TransferDirect",saveParam});
            String json = gson.toJson(request);

            try {
                formId = "STK_TransferDirect";

                String respResult = OkHttpUtils.bodypost(url, json, sessionId);
                spInStock = gson.fromJson(respResult, SaveResult.class);

                log = ApiLogAspect.initApiLog("post", QuantityConstant.URL+formId,
                        json, headers, QuantityConstant.DEFAULT_WAREHOUSE);
                if (spInStock.getResult().getResponseStatus().isIsSuccess()) {
                    SuccessEntity success = spInStock.getResult().
                            getResponseStatus().getSuccessEntitys().get(0);
                    Integer referId = Integer.valueOf(success.getId());
                    String referCode = success.getNumber();
                    //更新 入库单明细状态
                    LambdaQueryWrapper<ReceiptDetail> queryWrapper = Wrappers.lambdaQuery();
                    queryWrapper.eq(ReceiptDetail::getReceiptId, receiptHeader.getId());
                    List<ReceiptDetail> receiptDetailss = receiptDetailService.list(queryWrapper);
                    for (ReceiptDetail receiptDetail : receiptDetailss) {
                        receiptDetail.setReferId(referId);
                        receiptDetail.setReferCode(referCode);
                        receiptDetail.setTaskQty(receiptDetail.getQty());
                        receiptDetailService.updateById(receiptDetail);
                    }
                    receiptHeader.setReferId(referId);
                    receiptHeader.setReferCode(referCode);
                    receiptHeaderService.updateById(receiptHeader);
                    //修改回传后状态
                    editReceiveStatus(receiptHeader.getId());
                    receiptHeader = receiptHeaderService.getById(receiptHeader.getId());
                    receiptDetailService.updateReceiptHeader(receiptHeader);
                    //更新 入库单明细状态
                    msg = "回传成功";
                    return AjaxResult.success("回传成功");
                } else {
                    ArrayList<RepoError> errors = spInStock.getResult().getResponseStatus().getErrors();
                    msg = JSON.toJSONString(errors);
                    return AjaxResult.error(msg);
                }
            }catch (Exception e) {
                e.printStackTrace();
                ApiLogAspect.setApiLogException(log, e);
            } finally {
                ApiLogAspect.finishApiLog(log, headers, msg);
            }
        }
        return AjaxResult.success("回传成功");
    }

    @Override
    public AjaxResult innerLoginERP() {
        ErpLogin erpLogin = new ErpLogin();
        erpLogin.setAcctID(QuantityConstant.ERP_AcctID);
        erpLogin.setAppID(QuantityConstant.ERP_AppID);
        erpLogin.setAppSec(QuantityConstant.ERP_AppSec);
        erpLogin.setUserName(QuantityConstant.ERP_UserName);
        erpLogin.setPassword(QuantityConstant.ERP_PASSWORD);
        erpLogin.setLCID(QuantityConstant.ERP_LCID);
        String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_LOGIN,
                QuantityConstant.DEFAULT_WAREHOUSE, "");
        String jsonParam = JSON.toJSONString(erpLogin);
        String result = OkHttpUtils.bodypost(url, jsonParam);
        ERPLoginResult erpLoginResult = JSON.parseObject(result, ERPLoginResult.class);
        String sessionId = erpLoginResult.getKDSVCSessionId();
        Config config1 = new Config();
        config1.setConfigKey(QuantityConstant.ERP_SESSION_ID);
        Config config = configService.selectConfigList(config1).get(0);
        config.setConfigValue(sessionId);
        int ret = configService.updateConfig(config);
        return AjaxResult.success();
    }

    private K3AdjustHeader createK3AdjustHeader(ReceiptHeader receiptHeader){
        K3AdjustHeader k3header = new K3AdjustHeader();

        k3header.setFBillTypeID(ConvertObjFactory.newInstance(Res.string().getKey("ADJUSTHEADER_TYPE")));
        k3header.setFTransferDirect(QuantityConstant.DEFAULT_STOCKDIRECT);
        k3header.setFTransferBizType(Res.string().getKey("TRANSFER_BIZ_TYPE"));
        k3header.setFStockOrgId(ConvertObjFactory.newInstance(QuantityConstant.JY));
        k3header.setFOwnerTypeIdHead(QuantityConstant.DEFAULT_OWNERTYPE);
        k3header.setFOwnerIdHead(ConvertObjFactory.newInstance(QuantityConstant.JY));
        k3header.setFDate(DateUtils.getNowDate());
        k3header.setFBaseCurrId(ConvertObjFactory.newInstance(QuantityConstant.DEFAULT_BASECURRID));
        k3header.setF_CH_IsLoadFee(false);

        return k3header;
    }
    private K3AdjustHeader createK3AdjustDetail(K3AdjustHeader k3AdjustHeader, List<ReceiptDetail> receiptDetails) {

        List<K3AdjustDetail> details = new ArrayList<>();
        for (ReceiptDetail receiptDetail : receiptDetails) {
            K3AdjustDetail k3AdjustDetail = new K3AdjustDetail();
            k3AdjustDetail.setFMaterialId(ConvertObjFactory.newInstance(receiptDetail.getMaterialCode()));
            AuxProperty auxProperty = new AuxProperty();
            auxProperty.setLevel(ConvertObjFactory.newInstance(receiptDetail.getLevel()));
            auxProperty.setColor(ConvertObjFactory.newInstance(receiptDetail.getColor()));
            auxProperty.setProPackaging(ConvertObjFactory.newInstance(receiptDetail.getProPackaging()));
            auxProperty.setProductSchedule(ConvertObjFactory.newInstance(receiptDetail.getProductSchedule()));
            auxProperty.setProductSize(ConvertObjFactory.newInstance(receiptDetail.getProductSize()));
            K3Location location = new K3Location();
            location.setLocation(ConvertObjFactory.newInstance(QuantityConstant.DEFAULT_STOCKLOC));

            k3AdjustDetail.setFAuxPropId(auxProperty);
            k3AdjustDetail.setFSrcStockLocId(location);

            k3AdjustDetail.setFDestStockId(ConvertObjFactory.newInstance(Res.string().getKey("DAMANGE_CODE")));
            k3AdjustDetail.setFSrcStockId(ConvertObjFactory.newInstance(QuantityConstant.DEFAULT_STOCK));
            k3AdjustDetail.setFSrcStockStatusId(ConvertObjFactory.newInstance(QuantityConstant.DEFAULT_STOCKSTATUS));
            k3AdjustDetail.setFUnitID(ConvertObjFactory.newInstance("1001"));
            k3AdjustDetail.setFBaseUnitId(ConvertObjFactory.newInstance("1001"));
            k3AdjustDetail.setFOwnerTypeOutId(QuantityConstant.DEFAULT_OWNERTYPE);
            k3AdjustDetail.setFOwnerTypeId(QuantityConstant.DEFAULT_OWNERTYPE);
            k3AdjustDetail.setFOwnerId(ConvertObjFactory.newInstance(QuantityConstant.JY));
            k3AdjustDetail.setFKeeperTypeId(QuantityConstant.DEFAULT_KEEPER);
            k3AdjustDetail.setFKeeperId(ConvertObjFactory.newInstance(QuantityConstant.JY));
            k3AdjustDetail.setFKeeperTypeOutId(QuantityConstant.DEFAULT_KEEPER);
            k3AdjustDetail.setFKeeperOutId(ConvertObjFactory.newInstance(QuantityConstant.JY));

            k3AdjustDetail.setFQty(receiptDetail.getQty());
            k3AdjustDetail.setFLot(ConvertObjFactory.newInstance(receiptDetail.getBatch()));

            details.add(k3AdjustDetail);
        }
        k3AdjustHeader.setFBillEntry(details);
        return k3AdjustHeader;
    }

    @Override
    public AjaxResult push(PushModel pushModel) {
        AjaxResult ajaxResult = null;
        String referType = pushModel.getReferType();
        if(pushModel.getReferType()==null || "".equals(pushModel.getReferType())){
            ajaxResult = AjaxResult.error("上游订单类型不能空");
        }
        switch(referType){
            case QuantityConstant.SHIPMENT_BILL_TYPE_JS :
                //直接调拨单回传
                pushModel.setSrcStockId(Res.string().getKey("SRC_STOCK_ID"));//
                pushModel.setDestStockId(Res.string().getKey("DEST_STOCK_ID"));
                ajaxResult = pushDirectTransfer(pushModel);
                break;
            case QuantityConstant.RECEIPT_BILL_TYPE_SR : //销售退货单 回传
                pushModel.setSrcStockId(Res.string().getKey("SRC_STOCK_ID"));
                ajaxResult = pushReturnNotice(pushModel);
                break;
            case QuantityConstant.SHIPMENT_BILL_TYPE_OS : //其他出库单 回传
                ShipmentHeader shipmentHeader = shipmentHeaderService.getById(pushModel.getHeaderId());
                if(shipmentHeader.getReferCode()==null){
                    ajaxResult = shipmentMethod(pushModel.getHeaderId()+"");
                }else{
                    pushModel.setSrcStockId(Res.string().getKey("SRC_STOCK_ID"));//
                    ajaxResult = pushShipmentRequest(pushModel);
                }



                break;
            case QuantityConstant.RECEIPT_BILL_TYPE_OR:  //其它入库单
            case QuantityConstant.RECEIPT_BILL_TYPE_SC :  //生产入库单
                ajaxResult = receiptMethod(pushModel.getHeaderId());
                break;
            case QuantityConstant.SHIPMENT_BILL_TYPE_SP : //销售出库回传
                ajaxResult = pushSalesDelivery(pushModel);
                break;
            default :
                throw new ServiceException("该类型没有下推规则");
        }
        if(ajaxResult.hasErr()) {
            String message = ajaxResult.getMsg();
            if(message.contains("会话信息已丢失")) {
                erpService.innerLoginERP();
            }
        }
        return ajaxResult;
    }

    /**
     * 回传入库单数据
     * @param receiptHeader 任务头
     */
    @Transactional
    @ProcessTrack(taskName = "入库单据回传", processCode = ProcessCode.RECEIPT_BILL_CODE)
    public AjaxResult receiptMethod(ReceiptHeader receiptHeader){
        if(receiptHeader==null){
            return AjaxResult.error("入库单为空");
        }
        String msg = "WMS请求发送成功,接收返回内容是空的";
        if(receiptHeader.getFirstStatus() == 800 &&
                receiptHeader.getLastStatus() == 800){
            //入库数据
            Object receiptData;
            //回传标识
            String formId = "";
            //获取回传入库信息
            receiptData = erpService.param(receiptHeader,receiptHeader.getReceiptType());
            ExtSaveParam saveParam = new ExtSaveParam<>(receiptData);

            //返回结果
            SaveResult spInStock = null;
            Gson gson = new Gson();
            ApiLog log = null;
            String body = null;
            HttpHeaders headers = new HttpHeaders();

            try {
                if (SingleReceipt.class.isAssignableFrom(receiptData.getClass())) {
                    String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_SAVE,
                            QuantityConstant.DEFAULT_WAREHOUSE, "");
                    String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
                    if(StringUtils.isEmpty(sessionId)){
                        return AjaxResult.error("sessionId不能为空");
                    }
                    formId = QuantityConstant.SP_InStock;
                    Object[] objects = new Object[]{formId, saveParam.toJson()};
                    ErpSaveObject erpSaveObject = new ErpSaveObject();
                    erpSaveObject.setParameters(objects);
                    body = gson.toJson(erpSaveObject);
                    log = ApiLogAspect.initApiLog("post", QuantityConstant.URL+QuantityConstant.SP_InStock,
                            body, headers, QuantityConstant.DEFAULT_WAREHOUSE);
                    String okResult = OkHttpUtils.bodypost(url, body, sessionId);
                    spInStock = JSON.parseObject(okResult, SaveResult.class);
                } else if (OtherReceipt.class.isAssignableFrom(receiptData.getClass())) {
                    String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_SAVE,
                            QuantityConstant.DEFAULT_WAREHOUSE, "");
                    String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
                    if(StringUtils.isEmpty(sessionId)){
                        return AjaxResult.error("sessionId不能为空");
                    }
                    formId = QuantityConstant.STK_MISCELLANEOUS;
                    Object[] objects = new Object[]{formId, saveParam.toJson()};
                    ErpSaveObject erpSaveObject = new ErpSaveObject();
                    erpSaveObject.setParameters(objects);
                    body = gson.toJson(erpSaveObject);
                    log = ApiLogAspect.initApiLog("post", QuantityConstant.URL+QuantityConstant.STK_MISCELLANEOUS,
                            body, headers, QuantityConstant.DEFAULT_WAREHOUSE);
                    String okResult = OkHttpUtils.bodypost(url, body, sessionId);
                    spInStock = JSON.parseObject(okResult, SaveResult.class);
                }

                if (spInStock.getResult().getResponseStatus().isIsSuccess()) {
                    SuccessEntity success = spInStock.getResult().
                            getResponseStatus().getSuccessEntitys().get(0);
                    Integer referId = Integer.valueOf(success.getId());
                    String referCode = success.getNumber();
                    //更新 入库单明细状态
                    LambdaQueryWrapper<ReceiptDetail> queryWrapper = Wrappers.lambdaQuery();
                    queryWrapper.eq(ReceiptDetail::getReceiptId, receiptHeader.getId());
                    List<ReceiptDetail> receiptDetails = receiptDetailService.list(queryWrapper);
                    for (ReceiptDetail receiptDetail : receiptDetails) {
                        receiptDetail.setReferId(referId);
                        receiptDetail.setReferCode(referCode);
                        receiptDetail.setQty(receiptDetail.getTaskQty());
                        receiptDetailService.updateById(receiptDetail);
                    }
                    receiptHeader.setReferId(referId);
                    receiptHeader.setReferCode(referCode);
                    receiptHeaderService.updateById(receiptHeader);
                    //修改回传后状态
                    editReceiveStatus(receiptHeader.getId());
                    receiptHeader = receiptHeaderService.getById(receiptHeader.getId());
                    receiptDetailService.updateReceiptHeader(receiptHeader);
                    //更新 入库单明细状态
                    msg = "回传成功";
                    return AjaxResult.success("回传成功");
                } else {
                    ArrayList<RepoError> errors = spInStock.getResult().getResponseStatus().getErrors();
                    String errorStr = "";
                    for (RepoError error : errors) {
                        errorStr = error.getFieldName() + "==" + error.getMessage() + "==";
                    }
                    msg = errorStr;
                    return AjaxResult.error(errorStr);
                }
            }catch (Exception e) {
                e.printStackTrace();
                ApiLogAspect.setApiLogException(log, e);
            } finally {
                ApiLogAspect.finishApiLog(log, headers, msg);
            }
        }
        return AjaxResult.success("回传成功");
    }

    private AjaxResult editReceiveStatus(Integer id) {
        ReceiptHeader receiptHeader = new ReceiptHeader();
        receiptHeader.setId(id);
        receiptHeader.setFirstStatus(900);
        receiptHeader.setLastStatus(900);
        if (!receiptHeaderService.updateById(receiptHeader)) {
            throw new ServiceException("更新头表状态失败");
        } else {
            LambdaQueryWrapper<ReceiptDetail> lambdaQueryWrapper = Wrappers.lambdaQuery();
            lambdaQueryWrapper.eq(ReceiptDetail::getReceiptId, id);
            List<ReceiptDetail> receiptDetails = receiptDetailService.list(lambdaQueryWrapper);
            for (ReceiptDetail receiptDetail : receiptDetails) {
                receiptDetail.setProcessStamp("900");
            }
            if (!receiptDetailService.updateBatchById(receiptDetails)) {
                throw new ServiceException("更新明细失败");
            }
        }
        return AjaxResult.success("");
    }

    private AjaxResult editShipmentStatus(Integer id) {
        ShipmentHeader shipmentHeader = new ShipmentHeader();
        shipmentHeader.setId(id);
        shipmentHeader.setFirstStatus(900);
        shipmentHeader.setLastStatus(900);
        if (!shipmentHeaderService.updateById(shipmentHeader)) {
            throw new ServiceException("更新头表状态失败");
        } else {
            LambdaQueryWrapper<ShipmentDetail> lambdaQueryWrapper = Wrappers.lambdaQuery();
            lambdaQueryWrapper.eq(ShipmentDetail::getShipmentId, id);
            List<ShipmentDetail> shipmentDetails = shipmentDetailService.list(lambdaQueryWrapper);
            for (ShipmentDetail shipmentDetail : shipmentDetails) {
                shipmentDetail.setProcessStamp("900");
            }
            if (!shipmentDetailService.updateBatchById(shipmentDetails)) {
                throw new ServiceException("更新明细失败");
            }
        }
        return AjaxResult.success("");
    }

    @Override
    public AjaxResult shipmentMethod(String shipmentHeaderId){
        ShipmentHeader header = shipmentHeaderService.getById(shipmentHeaderId);
        return shipmentMethod(header);
    }
    /**
     * 回传出库单数据
     * @param shipmentHeader 任务头
     */
    @Transactional
    public AjaxResult shipmentMethod(ShipmentHeader shipmentHeader){
        if(shipmentHeader==null){
            return AjaxResult.error("出库单为空");
        }
        if(shipmentHeader.getFirstStatus()==500 && shipmentHeader.getLastStatus()==500){
            //入库数据
            Object receiptData;
            //回传标识
            String formId = "";
            //回传器
            ExtSaveParam<Object> saveParam = null;
            //获取回传出库信息
            receiptData = param(shipmentHeader,shipmentHeader.getShipmentType());

            if(SingleShipment.class.isAssignableFrom(receiptData.getClass())){
                formId = "SP_PickMtrl";
                saveParam = new ExtSaveParam<>(receiptData);
            }else if(OtherShipment.class.isAssignableFrom(receiptData.getClass())){
                formId = "STK_MisDelivery";
                saveParam = new ExtSaveParam<>(receiptData);
            }
            //返回结果
            SaveResult spInStock = null;
            Object[] objects = new Object[]{formId, saveParam.toJson()};
            ErpSaveObject erpSaveObject = new ErpSaveObject();
            erpSaveObject.setParameters(objects);
            Gson gson = new Gson();
            String body = gson.toJson(erpSaveObject);
            String url = addressService.selectAddress(QuantityConstant.ERP_K3CLOUD_SAVE,
                    QuantityConstant.DEFAULT_WAREHOUSE, "");
            String sessionId = configService.getKey(QuantityConstant.ERP_SESSION_ID);
            if(StringUtils.isEmpty(sessionId)){
                return AjaxResult.error("sessionId不能为空");
            }
            String okResult = OkHttpUtils.bodypost(url, body, sessionId);
            spInStock = JSON.parseObject(okResult, SaveResult.class);

            if(spInStock.getResult().getResponseStatus().isIsSuccess()){
                SuccessEntity success = spInStock.getResult().getResponseStatus().getSuccessEntitys().get(0);
                Integer referId = Integer.valueOf(success.getId());
                String referCode = success.getNumber();
                //更新 出库单明细状态
                LambdaQueryWrapper<ShipmentDetail> queryWrapper = Wrappers.lambdaQuery();
                queryWrapper.eq(ShipmentDetail::getShipmentId,shipmentHeader.getId());
                List<ShipmentDetail> shipmentDetails = shipmentDetailService.list(queryWrapper);
                for (ShipmentDetail shipmentDetail : shipmentDetails) {
                    shipmentDetail.setReferId(referId);
                    shipmentDetail.setReferCode(referCode);
                    shipmentDetailService.updateById(shipmentDetail);
                }
                shipmentHeader.setReferId(referId);
                shipmentHeader.setReferCode(referCode);
                shipmentHeaderService.updateById(shipmentHeader);
                //修改回传后状态
                editShipmentStatus(shipmentHeader.getId());
                return AjaxResult.success("回传成功");
            }else{
                ArrayList<RepoError> errors = spInStock.getResult().getResponseStatus().getErrors();
                String errorStr = "";
                for (RepoError error : errors) {
                    errorStr = error.getFieldName()+"=="+error.getMessage()+"==";
                }
                return AjaxResult.error(errorStr);
            }
        }
        return AjaxResult.error("出库单数据问题");
    }

    /**
     * 判断入库单类型返回 回传入库信息
     * @param receiptHeader 入库头
     * @param billType 单据类型
     * @return 回传入库信息
     */
    @Transactional
    public Object param(ReceiptHeader receiptHeader, String billType){
        Object returnReceipt;
        switch (billType) {
            //简单生产入库单
            case QuantityConstant.RECEIPT_BILL_TYPE_SC:
                returnReceipt = buildSingleReceiptHead(receiptHeader);
                break;
            //其他生产入库单
            case QuantityConstant.RECEIPT_BILL_TYPE_OR:
                returnReceipt = buildOtherReceiptHead(receiptHeader);
                break;
            default:
                throw new ServiceException("不支持的任务类型");
        }
        //获取入库单数据
        LambdaQueryWrapper<ReceiptDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ReceiptDetail::getReceiptId,receiptHeader.getId());
        //入库明细集合
        List<ReceiptDetail> details = receiptDetailService.list(queryWrapper);

        List<ReceiptDetail> receiptDetails = new ArrayList<>();
        details.forEach(it->{
            ReceiptDetail d = new ReceiptDetail();
            BeanUtils.copyBeanProp(d, it);
            receiptDetails.add(d);
        });

        receiptDetails.stream()
                .forEach(detail -> detail.setReturnedQty(
                        detail.getReturnedQty().add(detail.getQty().subtract(detail.getReturnedQty()))
                ));
        //已回传数=已回传数+单据数量-已回传数量
        receiptDetailService.updateBatchById(receiptDetails);


        details.forEach(detail -> detail.setQty(detail.getQty().subtract(detail.getReturnedQty())));

        //回传入库明细集
        List<ReceiptBillEntity> receiptInfos = getReceiptEntities(details);
        //TODO 这里修改数量为单据数减去已回传数

        //设置回传入库明细集
        Class<?> receiptCls = returnReceipt.getClass();

        if(OtherReceipt.class.isAssignableFrom(receiptCls)){
            OtherReceipt otherReceipt = (OtherReceipt)returnReceipt;
            otherReceipt.setEntity(receiptInfos);
            //重新赋值给 returnReceipt
            returnReceipt = otherReceipt;
        }else if(SingleReceipt.class.isAssignableFrom(receiptCls)){
            SingleReceipt singleReceipt = (SingleReceipt)returnReceipt;
            singleReceipt.setEntity(receiptInfos);
            //重新赋值给 returnReceipt
            returnReceipt = singleReceipt;
        }
        return returnReceipt;
    }

    /**
     * 获取
     * 判断出库单类型返回 回传出库信息
     * @param shipmentHeader 出库头
     * @param billType 单据类型
     * @return 回传出库信息
     */
    private Object param(ShipmentHeader shipmentHeader,String billType){
        Object returnShipment;
        switch (billType) {
            //简单生产退料单
            case QuantityConstant.BILL_TYPE_SHIPMENT_SINGLE:
                returnShipment = buildSingleShipmentHead(shipmentHeader);
                break;
            //其他生产退料单
            case QuantityConstant.SHIPMENT_BILL_TYPE_OS:
                returnShipment = buildOtherShipmentHead(shipmentHeader);
                break;
            default:
                throw new ServiceException("不支持的任务类型");
        }
        //获取退料单数据
        LambdaQueryWrapper<ShipmentDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ShipmentDetail::getShipmentId,shipmentHeader.getId());
        //出库明细集合
        List<ShipmentDetail> details = shipmentDetailService.list(queryWrapper);

        //回传出库明细集
        List<ShipmentBillEntity> billEntities = getShipmentEntities(details);

        //设置回传出库明细集
        Class<?> receiptCls = returnShipment.getClass();
        if(OtherShipment.class.isAssignableFrom(receiptCls)){
            OtherShipment otherShipment = (OtherShipment)returnShipment;
            otherShipment.setEntity(billEntities);
            //重新赋值给 returnShipment
            returnShipment = otherShipment;
        }else if(SingleShipment.class.isAssignableFrom(receiptCls)){
            SingleShipment singleShipment = (SingleShipment)returnShipment;
            singleShipment.setEntity(billEntities);
            //重新赋值给 returnShipment
            returnShipment = singleShipment;
        }
        return returnShipment;
    }

    /**
     * 获取回传入库明细数据 通过入库单明细集
     * @param details 入库单明细集
     */
    public List<ReceiptBillEntity> getReceiptEntities(List<ReceiptDetail> details){
        List<ReceiptBillEntity> billEntities = new ArrayList<>();
        if(details.size()>0){
            for (ReceiptDetail detail : details) {
                ReceiptBillEntity entity = getEntity(detail);
                billEntities.add(entity);
            }
        }
        return billEntities;
    }
    /**
     * 获取回传出库明细数据 通过出库单明细集
     * @param details 出库单明细集
     */
    public List<ShipmentBillEntity> getShipmentEntities(List<ShipmentDetail> details){
        List<ShipmentBillEntity> billEntities = new ArrayList<>();
        if(details.size()>0){
            for (ShipmentDetail detail : details) {
                ShipmentBillEntity entity = getEntity(detail);
                billEntities.add(entity);
            }
        }
        return billEntities;
    }



    /**
     * 通过参数入库明细单 获取单据体
     * @param detail 入库明细单
     * @return 返回 BillEntity 单据体
     */
    public ReceiptBillEntity getEntity(ReceiptDetail detail){
        ReceiptBillEntity billEntity = new ReceiptBillEntity();
        //设值辅助属性
        LambdaQueryWrapper<Material> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.eq(Material::getCode,detail.getMaterialCode());
        Material material = materialService.getOne(queryWrapper1);

        ReceiptHeader receiptHeader = receiptHeaderService.getById(detail.getReceiptId());

        // 传入物料判断是否添加辅助属性
        AuxProperty auxProperty = new AuxProperty();
        //包装
        String packageingDetail = detail.getProPackaging();
        ConvertObj proPackaging= ConvertObjFactory.newInstance(packageingDetail);
        //排产订单
        ConvertObj productScheduleHeader = ConvertObjFactory.newInstance(detail.getProductSchedule());
        //色号
        String colorDetail = detail.getColor();
        String colorValue = getBosAssistantNumber(colorDetail, QuantityConstant.MATERIAL_COLOUR);
        ConvertObj color= ConvertObjFactory.newInstance(colorValue);
        //等级
        String levelDetail = detail.getLevel();
        String levelValue = getBosAssistantNumber(levelDetail, QuantityConstant.MATERIAL_LEVEL);
        ConvertObj level = ConvertObjFactory.newInstance(levelValue);
        //尺寸
        ConvertObj productSize = ConvertObjFactory.newInstance(detail.getProductSize());
        //辅助属性判断与录入
        if(material.getIsCustProductSize()){
            auxProperty.setProductSchedule(productSize);
        }
        if(material.getIsColor()){
            auxProperty.setColor(color);
        }
        if(material.getIsLevel()){
            auxProperty.setLevel(level);
        }
        if(material.getIsProPackaging()){
            auxProperty.setProPackaging(proPackaging);
        }
        if(material.getIsProductSchedule()){
            auxProperty.setProductSchedule(productScheduleHeader);
        }

        //base attr
        //物料编码
        billEntity.setMaterial(ConvertObjFactory.newInstance(detail.getMaterialCode()));
        //辅助属性
        billEntity.setProperty(auxProperty);
        //单位
        billEntity.setUnit(ConvertObjFactory.newInstance(detail.getMaterialUnit()));
        //收货仓库
//        String stockId = detail.getStockId();
        billEntity.setStockId(ConvertObjFactory.newInstance(Res.string().getKey("DEFAULT_STOCK")));
        //仓位
        StockLoc location = new StockLoc();
        location.setLocation(ConvertObjFactory.newInstance(QuantityConstant.DEFAULT_STOCKLOC));
        billEntity.setStockLocId(location);
        //批号
        billEntity.setLotId(ConvertObjFactory.newInstance(detail.getBatch()));
        //货主类型
        billEntity.setOwnerType(QuantityConstant.DEFAULT_OWNERTYPE);
        //货主
        billEntity.setOwnerId(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //库存状态
        billEntity.setStockstatusId(ConvertObjFactory.newInstance(QuantityConstant.DEFAULT_STOCKSTATUS));
        //保管者类型
        billEntity.setKeeperType(QuantityConstant.DEFAULT_KEEPER);
        //保管者
        billEntity.setKeeperId(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //库存组织
        billEntity.setOrgId(ConvertObjFactory.newInstance(QuantityConstant.JY));

        //other attr
        //默认生产车间
        //就一个可选测试
        billEntity.setWorkShopId1(ConvertObjFactory.newInstance(Res.string().getKey("DEFAULT_WORKSHOP")));
        //箱数
        billEntity.setBox(detail.getQty().intValue());
        //生产编号
        billEntity.setProductNo(detail.getBatch());

        if(receiptHeader.getReceiptType().equals(QuantityConstant.RECEIPT_TYPE_PRODUCTON)) {
            //基本单位实收数量
            billEntity.setBaseRealQty(detail.getTaskQty());
            //实收数量(简单生产人库单)
            billEntity.setRealQty(detail.getTaskQty());
        } else {
            billEntity.setBaseRealQty(detail.getQty());
            billEntity.setRealQty(detail.getQty());
        }
        //重量
        BigDecimal pieceWeight = material.getPieceWeight();
        billEntity.setWeight(pieceWeight.multiply(detail.getQty()));
        //箱数
        billEntity.setBox(detail.getBox());
        //实收数量(其他人库单)
        billEntity.setQty(detail.getQty());
        return billEntity;
    }


    private String getBosAssistantNumber(String number1, String id) {
        LambdaQueryWrapper<BosAssistantDetail> bosAssistantDetailLambdaQueryWrapper = Wrappers.lambdaQuery();
        bosAssistantDetailLambdaQueryWrapper.eq(BosAssistantDetail::getId, id)
                .eq(BosAssistantDetail::getNumber, number1);
        BosAssistantDetail bosAssistantDetail = bosAssistantDetailService.getOne(
                bosAssistantDetailLambdaQueryWrapper);
        if(bosAssistantDetail == null) {
            throw new ServiceException("没有找到对应详情");
        }
        String number = bosAssistantDetail.getNumber();
        return number;
    }
    /**
     * 通过参数出库明细单 获取单据体
     * @param detail 出库明细单
     * @return 返回 BillEntity 单据体
     */
    public ShipmentBillEntity getEntity(ShipmentDetail detail){
        ShipmentBillEntity billEntity = new ShipmentBillEntity();
        //设值辅助属性
        LambdaQueryWrapper<Material> queryWrapper2 = Wrappers.lambdaQuery();
        queryWrapper2.eq(Material::getCode,detail.getMaterialCode());
//        Material material = materialService.getOne(queryWrapper2);
        LambdaQueryWrapper<InventoryDetail> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.eq(InventoryDetail::getMaterialCode,detail.getMaterialCode())
                .eq(StringUtils.isNotEmpty(detail.getProductSchedule()),InventoryDetail::getProductSchedule,detail.getProductSchedule())
                .eq(StringUtils.isNotEmpty(detail.getLevel()),InventoryDetail::getLevel,detail.getLevel())
                .eq(StringUtils.isNotEmpty(detail.getColor()),InventoryDetail::getColor,detail.getColor())
                .eq(StringUtils.isNotEmpty(detail.getProPackaging()),InventoryDetail::getProPackaging,detail.getProPackaging())
                .eq(StringUtils.isNotEmpty(detail.getProductSize()),InventoryDetail::getProductSize,detail.getProductSize())
                .eq(InventoryDetail::getBatch,detail.getBatch());
        List<InventoryDetail> list = inventoryDetailService.list(queryWrapper1);
        InventoryDetail inventoryHistoryDetail = list.get(0);
        InventoryHistoryHeader inventoryHeader = inventoryHistoryHeaderService.getById(inventoryHistoryDetail.getInventoryHeaderId());
        Material material = materialService.getMaterialByCode(detail.getMaterialCode(), QuantityConstant.DEFAULT_WAREHOUSE);
        AuxProperty auxProperty = new AuxProperty();
        ConvertObj proPackaging= ConvertObjFactory.newInstance(inventoryHistoryDetail.getProPackaging());
        ConvertObj productScheduleHeader = ConvertObjFactory.newInstance(inventoryHistoryDetail.getProductSchedule());
        ConvertObj color= ConvertObjFactory.newInstance(inventoryHistoryDetail.getColor());
        ConvertObj level = ConvertObjFactory.newInstance(inventoryHistoryDetail.getLevel());
        ConvertObj productSize = ConvertObjFactory.newInstance(inventoryHistoryDetail.getProductSize());
        //判断辅助属性与录入
        if(material.getIsColor()){
            auxProperty.setColor(color);
        }
        if(material.getIsLevel()){
            auxProperty.setLevel(level);
        }
        if(material.getIsProductSchedule()){
            auxProperty.setProductSchedule(productScheduleHeader);
        }
        if(material.getIsProPackaging()){
            auxProperty.setProPackaging(proPackaging);
        }
        if(material.getIsCustProductSize()){
            auxProperty.setProductSize(productSize);
        }

        //base attr
        //物料编码
        billEntity.setMaterialId(ConvertObjFactory.newInstance(detail.getMaterialCode()));
        //辅助属性
        billEntity.setAuxProperty(auxProperty);
        //单位
        billEntity.setUnitId(ConvertObjFactory.newInstance(inventoryHistoryDetail.getMaterialUnit()));
        //收货仓库
        billEntity.setStockId(ConvertObjFactory.newInstance(Res.string().getKey("DEFAULT_STOCK")));
        StockLoc location = new StockLoc();
        location.setLocation(ConvertObjFactory.newInstance(QuantityConstant.DEFAULT_STOCKLOC));
        billEntity.setStockLocId(location);
        //批号
        billEntity.setLot(ConvertObjFactory.newInstance(inventoryHistoryDetail.getBatch()));
        //货主类型
        billEntity.setOwnerTypeId(QuantityConstant.DEFAULT_OWNERTYPE);
        //货主
        billEntity.setOwnerId(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //库存状态
        billEntity.setStockStatusId(ConvertObjFactory.newInstance(QuantityConstant.DEFAULT_STOCKSTATUS));
        //保管者类型
        billEntity.setKeeperTypeId(QuantityConstant.DEFAULT_KEEPER);
        //保管者
        billEntity.setKeeperId(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //库存组织
        billEntity.setOrgId(ConvertObjFactory.newInstance(QuantityConstant.JY));


        //other attr
        //基本单位数量
        billEntity.setActualQty(detail.getQty());
        //实发数量(基本单位)
        billEntity.setBaseQty(detail.getQty());
        //实发数量
        billEntity.setQty(detail.getQty());
        //实发数量
        billEntity.setBaseActualQty(detail.getQty());
        //库存单位实发数量
        billEntity.setStockActualQty(detail.getQty());
        //批号
        billEntity.setLot(ConvertObjFactory.newInstance(inventoryHistoryDetail.getBatch()));
        //生产编号影响成本
        billEntity.setIsAffectCost(false);
        //库存单位
        billEntity.setStockUnitId(ConvertObjFactory.newInstance(inventoryHistoryDetail.getMaterialUnit()));
        //基本单位
        billEntity.setBaseUnitId(ConvertObjFactory.newInstance(inventoryHistoryDetail.getMaterialUnit()));
        //产品货主类型
        billEntity.setParentOwnerTypeId(QuantityConstant.DEFAULT_OWNERTYPE);
        //产品货主
        billEntity.setParentOwnerId(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //生产领料类型
        billEntity.setSclllx(ConvertObjFactory.newInstance(detail.getSclllx()));
        return billEntity;
    }

    /**
     * 构建其他入库头信息
     * @param receiptHeader 入库头
     * @return object对象
     */
    public Object buildOtherReceiptHead(ReceiptHeader receiptHeader){
        OtherReceipt otherReceipt = new OtherReceipt();
        //单据类型
        otherReceipt.setBillTypeId(ConvertObjFactory.newInstance(receiptHeader.getReferType()));
        //库存组织
        otherReceipt.setStockOrgId(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //货主
        otherReceipt.setOwnerIdHead(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //供应商
        otherReceipt.setSupplierId(ConvertObjFactory.newInstance(receiptHeader.getSupplierCode()));
        //部门
        otherReceipt.setDeptId(ConvertObjFactory.newInstance(receiptHeader.getUserDef1()));
//        仓管员
//        otherReceipt.setStockId(ConvertObjFactory.newInstance("102.YG2021054"));
        //本位币
        otherReceipt.setBaseCurrId(ConvertObjFactory.newInstance(QuantityConstant.DEFAULT_BASECURRID));
        //其他入库类型
        otherReceipt.setQtrklx(ConvertObjFactory.newInstance(receiptHeader.getInType()));
        //客户
        otherReceipt.setCustomer(ConvertObjFactory.newInstance(receiptHeader.getUserDef2()));
        return otherReceipt;
    }

    /**
     * 构建简单入库头信息
     * @param receiptHeader 入库头
     * @return object对象
     */
    public Object buildSingleReceiptHead(ReceiptHeader receiptHeader){

        SingleReceipt singleReceipt = new SingleReceipt();
        //单据类型
        singleReceipt.setBillType(ConvertObjFactory.newInstance(receiptHeader.getReferType()));
        //生产组织
        singleReceipt.setProdOrgId(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //货主
        singleReceipt.setOwnerId0(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //入库组织
        singleReceipt.setStockOrgId(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //时间
        singleReceipt.setDate(DateUtils.getNowDate());

//        String loginName = receiptHeader.getCreatedBy();
//        LambdaQueryWrapper<User> queryWrapper2 = Wrappers.lambdaQuery();
//        queryWrapper2.eq(User::getLoginName,loginName);
//        User stock = userService.getOne(queryWrapper2);

        //获取仓管员编码
//        String number = stock.getNumber();
        singleReceipt.setStockId(ConvertObjFactory.newInstance(Res.string().getKey("DEFAULT_STOCKER")));
        //备注
        singleReceipt.setDescription("");
        //本位币.
        singleReceipt.setBaseCurrId(ConvertObjFactory.newInstance(QuantityConstant.DEFAULT_BASECURRID));
        return singleReceipt;

    }

    public Object buildSingleShipmentHead(ShipmentHeader shipmentHeader){
        SingleShipment singleShipment = new SingleShipment();
        //单据类型
        singleShipment.setBillType(ConvertObjFactory.newInstance(shipmentHeader.getShipmentType()));
        //时间
        singleShipment.setDate(DateUtils.getNowDate());
        //入库组织
        singleShipment.setStockOrgId(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //本位币.
        singleShipment.setBaseCurrId(ConvertObjFactory.newInstance(QuantityConstant.DEFAULT_BASECURRID));
        //货主类型
        singleShipment.setOwnerTypeIdHead(QuantityConstant.DEFAULT_OWNERTYPE);
        //货主
        singleShipment.setOwnerId0(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //生产组织
        singleShipment.setProdOrgId(ConvertObjFactory.newInstance(QuantityConstant.JY));

//        String loginName = shipmentHeader.getCreatedBy();
//        LambdaQueryWrapper<User> queryWrapper2 = Wrappers.lambdaQuery();
//        queryWrapper2.eq(User::getLoginName,loginName);
//        User stock = userService.getOne(queryWrapper2);
//        String number = stock.getNumber();
        //仓管员
        singleShipment.setStockId(ConvertObjFactory.newInstance(Res.string().getKey("DEFAULT_STOCK")));


        //other
        //生产车间
        singleShipment.setWorkShopId(ConvertObjFactory.newInstance(Res.string().getKey("DEFAULT_WORKSHOP")));
        //业务类型
        singleShipment.setBizType("NORMAL");
        return singleShipment;
    }

    public Object buildOtherShipmentHead(ShipmentHeader shipmentHeader){
        OtherShipment otherShipment = new OtherShipment();
        //base
        //单据类型
        otherShipment.setBillTypeId(ConvertObjFactory.newInstance(shipmentHeader.getReferCodeType()));
        //库存组织
        otherShipment.setStockOrgId(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //库存方向
        otherShipment.setStockDirect(QuantityConstant.DEFAULT_STOCKDIRECT);
        //日期
        otherShipment.setDate(DateUtils.getNowDate());
        //部门
        if(shipmentHeader.getUserDef1() == null || StringUtils.isEmpty(shipmentHeader.getUserDef1())){
            String defDeptCode = configService.getKey(QuantityConstant.QT_DEF_DEPT);
            shipmentHeader.setUserDef1(defDeptCode);
        }
        otherShipment.setDeptId(ConvertObjFactory.newInstance(shipmentHeader.getUserDef1()));
        //仓管员
        otherShipment.setStockerId(ConvertObjFactory.newInstance(Res.string().getKey("DEFAULT_STOCKER")));
        //货主类型
        otherShipment.setOwnerTypeIdHead(QuantityConstant.DEFAULT_OWNERTYPE);
        //货主
        otherShipment.setOwnerIdHead(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //本位币
        otherShipment.setBaseCurrId(ConvertObjFactory.newInstance(QuantityConstant.DEFAULT_BASECURRID));

        //other
        //其他入库类型
        otherShipment.setQtcklx(ConvertObjFactory.newInstance(shipmentHeader.getQtcklx()));
        // 客户
        otherShipment.setCustId(ConvertObjFactory.newInstance(shipmentHeader.getCustomerCode()));
        //供应商
        otherShipment.setSupplierId(ConvertObjFactory.newInstance(""));
        //收货人信息
        otherShipment.setReceive(shipmentHeader.getShipmentNote());
        return otherShipment;
    }

    /**
     * 递归进行组盘 当出库单明细 的请求数量等于出库数量时,
     * 结束递归
     * 当请求数量小于
     * @param shipmentContainer
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    protected ERPShipmentContainer addERPCombination(ERPShipmentContainer shipmentContainer){
        BigDecimal shipQty = shipmentContainer.getShipQty();
        BigDecimal requestQty = shipmentContainer.getRequestQty();
        String orderCode = shipmentContainer.getOrderCode();
        ShipmentDetail shipmentDetail = shipmentContainer.getShipmentDetail();
        List<String> containers = shipmentContainer.getContainers();//该订单项目的所有物料托盘
        String color = shipmentContainer.getMaterialInfo().getColor();
        String level = shipmentContainer.getMaterialInfo().getLevel();
        int stack = shipmentContainer.getMaterialInfo().getStack();
        String batch = shipmentContainer.getMaterialInfo().getBatch();
        String materialCode = shipmentContainer.getMaterialInfo().getMaterialCode();

        String containerCode1 = containers.get(containers.size() - 1);
        Container container = containerService.getContainerByCode(containerCode1, "CS0001");
        String containerCode = container.getCode();
        String locationCode = container.getLocationCode();

        ShipmentContainerHeader shipmentContainerHeader = new ShipmentContainerHeader();
        shipmentContainerHeader.setWarehouseCode(QuantityConstant.DEFAULT_WAREHOUSE);
        shipmentContainerHeader.setLocationCode(locationCode);
        shipmentContainerHeader.setCompanyCode(QuantityConstant.DEFAULT_COMPANY);
        shipmentContainerHeader.setContainerCode(containerCode);
        shipmentContainerHeader.setColor(color);//色号
        shipmentContainerHeader.setLevel(level);//等级
        shipmentContainerHeader.setOrderCode(orderCode);//订单编号
        shipmentContainerHeader.setBatch(batch);//批次
        shipmentContainerHeader.setMaterialCode(materialCode);//物料编码
        shipmentContainerHeader.setTaskType(QuantityConstant.TASK_TYPE_SORTINGSHIPMENT);
        shipmentContainerHeader.setStatus(QuantityConstant.SHIPMENT_CONTAINER_BUILD);
        shipmentContainerHeader.setStack(stack);//设置垛型
        shipmentContainerHeader.setCreatedBy(QuantityConstant.PLATFORM_CODING);
        shipmentContainerHeader.setLastUpdatedBy(QuantityConstant.PLATFORM_CODING);
        boolean result = shipmentContainerHeaderService.save(shipmentContainerHeader);
        if(!result){
            throw new ServiceException("保存出库组盘头失败");
        }
        //出库阻盘头完成
        containers.remove(containerCode1);//删除该托盘号

        List<InventoryDetail> inventoryList = inventoryDetailService.getInventoryList(containerCode, "CS0001");
        for (InventoryDetail inventoryDetail : inventoryList) {
            ShipmentContainerDetail shipmentContainerDetail = new ShipmentContainerDetail();
            String chipCode1 = inventoryDetail.getChipCode1();
            String chipCode2 = inventoryDetail.getChipCode2();
            shipmentContainerDetail.setInventoryId(inventoryDetail.getId());//设置库存明细id 用于取消配盘
            shipmentContainerDetail.setWarehouseCode(QuantityConstant.DEFAULT_WAREHOUSE);
            shipmentContainerDetail.setContainerCode(containerCode);
            shipmentContainerDetail.setLocationCode(inventoryDetail.getLocationCode());
            shipmentContainerDetail.setCompanyCode(QuantityConstant.DEFAULT_COMPANY);
            shipmentContainerDetail.setTaskType(QuantityConstant.TASK_TYPE_WHOLERECEIPT);
            shipmentContainerDetail.setChipCode1(chipCode1);
            shipmentContainerDetail.setChipCode2(chipCode2);
            shipmentContainerDetail.setMaterialCode(inventoryDetail.getMaterialCode());
            shipmentContainerDetail.setMaterialName(inventoryDetail.getMaterialName());
            shipmentContainerDetail.setMaterialSpec(inventoryDetail.getMaterialSpec());
            shipmentContainerDetail.setMaterialUnit(inventoryDetail.getMaterialUnit());
            shipmentContainerDetail.setLevel(level);
            shipmentContainerDetail.setColor(color);
            shipmentContainerDetail.setQty(BigDecimal.ONE);
            shipmentContainerDetail.setBatch(batch);
            shipmentContainerDetail.setShipmentCode(shipmentDetail.getShipmentCode());
            shipmentContainerDetail.setBoxCode(inventoryDetail.getBoxCode());
            shipmentContainerDetail.setShipmentType(QuantityConstant.RECEIPT_TYPE_PRODUCTON);
            shipmentContainerDetail.setInventorySts(QuantityConstant.QUALITY_GOOD);
            shipmentContainerDetail.setCreatedBy(QuantityConstant.PLATFORM_CODING);
            shipmentContainerDetail.setLastUpdatedBy(QuantityConstant.PLATFORM_CODING);
            shipmentContainerDetail.setBoxPosition(Integer.valueOf(inventoryDetail.getBoxPosition()));
            shipmentContainerDetail.setShipmentId(shipmentDetail.getShipmentId());
            shipmentContainerDetail.setShipmentDetailId(shipmentDetail.getId());
            shipmentContainerDetail.setShippingContainerId(shipmentContainerHeader.getId());

            inventoryDetail.setTaskQty(inventoryDetail.getTaskQty().add(BigDecimal.ONE));
            requestQty = requestQty.add(BigDecimal.ONE);//组盘加一
            result = shipmentContainerDetailService.save(shipmentContainerDetail);
            if(!result){
                throw new ServiceException("保存出库组盘明细失败");
            }
            //更新库存任务数量
            result = inventoryDetailService.updateById(inventoryDetail);
            if(!result) {
                throw new ServiceException("保存出库组盘明细失败");
            }
            if(requestQty.compareTo(shipQty)==0){
                shipmentContainer.setHavInventory(true);
                break;
            }
        }
        result = shipmentTaskService.createPickingTask(shipmentContainerHeader.getId(), QuantityConstant.DEFAULT_WAREHOUSE);
        if(!result){
            throw new ServiceException("保存出库任务失败");
        }
        //出
        if(shipmentContainer.getHavInventory()){
            shipmentContainer.setRequestQty(requestQty);
            shipmentDetail.setStatus(QuantityConstant.SHIPMENT_HEADER_GROUPDISK);
            shipmentDetail.setProcessStamp(QuantityConstant.SHIPMENT_HEADER_GROUPDISK+"");
            result = shipmentDetailService.updateById(shipmentDetail);

            if(!result){
                throw new ServiceException("保存出库单明细失败");
            }
            return null;//结束
        }
        shipmentContainer.setRequestQty(requestQty);
        shipmentContainer.setContainers(containers);
        return addERPCombination(shipmentContainer);
    }


    protected <T> List<T> loadDataList(String fieldKeys, Class type, String json) throws InstantiationException, IllegalAccessException, InvocationTargetException {
        List<T> rets = new ArrayList();
        List rows = JSON.parseObject(json, rets.getClass());
        Method[] pes = type.getMethods();
        String[] fields = fieldKeys.split(",");

        for (int i = 0; i < fields.length; i++) {
            String field = fields[i];
            /* 去掉最后一个 _ 前面的字符 */
            field = BeanUtils.cutBeforeStr(field, "_");
            /* 去掉F */
            field = BeanUtils.cutHeader(field);
            //这里是发货通知单 辅助属性 格式加的验证
            //FAuxpropID.FF100001.FNumber 等级
            String str = field;
            int first = str.indexOf(".");
            if(first!=-1){
                str = str.substring(0,first);
                str = str.toUpperCase();
                if("AUXPROPID".equals(str)){
                    int last = field.lastIndexOf(".");
                    field = field.substring(first+1,last);
                    /* 去掉F */
                    field = BeanUtils.cutHeader(field);
                }
            }

            /* 去掉.后面的字符*/
            fields[i] = BeanUtils.convertToFormat(field);
        }
        Method[] setPes = this.getMethodsByFields(pes, "set", fields);
        Method[] getPes = this.getMethodsByFields(pes, "get", fields);
        Iterator var12 = rows.iterator();

        while(var12.hasNext()) {
            List<Object> darray = (List)var12.next();
            T ret = (T) type.newInstance();

            for(int i = 0; i < fields.length; ++i) {
                if (setPes[i] != null && getPes[i] != null) {
                    Object v = this.convertToDest(getPes[i].getReturnType(), darray.get(i));
                    if (v != null) {
                        setPes[i].invoke(ret, v);
                    }
                }
            }
            rets.add(ret);
        }
        return rets;
    }

    Method[] getMethodsByFields(Method[] pes, String pre, String[] fields) {
        Method[] rets = new Method[fields.length];

        for(int i = 0; i < fields.length; ++i) {
            for(int j = 0; j < pes.length; ++j) {
                String name = pes[j].getName().toLowerCase();
                String preName = pre + fields[i].toLowerCase();
                if (name.equals(preName)) {
                    rets[i] = pes[j];
                }
            }
        }

        return rets;
    }

    Object convertToDest(Type type, Object val) {
        if (val == null) {
            return null;
        } else if (type.getTypeName().equals(String.class.getTypeName())) {
            return val.toString();
        } else if (!type.getTypeName().equals(Integer.TYPE.getTypeName()) && !type.getTypeName().equals(Short.TYPE.getTypeName()) && !type.getTypeName().equals(Long.TYPE.getTypeName())) {
            if (type.getTypeName().equals(BigDecimal.class.getTypeName())) {
                return new BigDecimal(val.toString());
            } else if (type.getTypeName().equals(Date.class.getTypeName())) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

                try {
                    return sdf.parse(val.toString());
                } catch (ParseException var5) {
                    var5.printStackTrace();
                    return null;
                }
            } else {
                return val;
            }
        } else {
            String v = val.toString();
            if (v.toString().indexOf(".") > -1) {
                v = v.substring(0, v.toString().indexOf("."));
            }

            return new Integer(v.toString());
        }
    }
}