ERPServiceImpl.java 106 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
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.ExtK3CloudApi;
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.service.BasicDataApiService;
import com.huaheng.common.constant.QuantityConstant;
import com.huaheng.common.exception.service.ServiceException;
import com.huaheng.common.utils.DateUtils;
import com.huaheng.framework.aspectj.ApiLogAspect;
import com.huaheng.framework.aspectj.lang.annotation.ApiLogger;
import com.huaheng.framework.web.domain.AjaxResult;

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.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.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.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.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.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ERPServiceImpl implements ERPService {

    @Resource
    private ContainerService containerService;
    @Resource
    private ContainerTypeService containerTypeService;
    @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;


    @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() {
        K3CloudApi api = new ExtK3CloudApi();
        QueryParam param = new QueryParam()
                .setFormId("BD_Department")
                .setFieldKeys("FDEPTID,FNumber,FName,FParentID,FIsStock")
                .setFilterString("fdocumentStatus=\'C\' and FUseOrgId.FNumber='102' and FForbidStatus=\'A\'")
                .setOrderString("FDEPTID ASC");
        List<ERPDept> datas = null;
        try {
            datas = api.executeBillQuery(param, ERPDept.class);
        } 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() {
        K3CloudApi api = new ExtK3CloudApi();
        QueryParam param = new QueryParam()
                .setFormId("BD_Empinfo")
                .setFieldKeys("FID,FName,FNumber,FPostDept,FCreateDate,FModifyDate")
                .setFilterString("fdocumentStatus=\'C\' and FUseOrgId.FNumber='102' and FForbidStatus=\'A\'")
                .setOrderString("FID ASC")
                .setLimit(0);
        List<ERPUser> datas = null;
        try {
            datas = api.executeBillQuery(param, ERPUser.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

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

        System.out.println("a");
        for (User user : userList) {
            basicDataApiService.user(user);
        }
    }
    /**
     * 同步客户数据
     */
    @Override
    public void customer() {
        K3CloudApi api = new ExtK3CloudApi();
        QueryParam param = new QueryParam()
                .setFormId("BD_Customer")
                .setFieldKeys("FCUSTID,FName,FNumber,FCOUNTRY,FPROVINCIAL,FCreateDate,FModifyDate")
                .setFilterString("fdocumentStatus=\'C\' and FUseOrgId.FNumber='102' and FForbidStatus=\'A\'")
                .setOrderString("FModifyDate DESC")
                .setLimit(0);
        List<ERPCustmer> datas = null;
        try {
            datas = api.executeBillQuery(param, ERPCustmer.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

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

        LambdaQueryWrapper<Customer> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Customer::getEnable,true);
        //获取本地 客户集合
        List<Customer> list = customerService.list(queryWrapper);

        //客户id
        List<String> idList = list.stream().map(t -> t.getCode()).collect(Collectors.toList());
        //erp客户id
        List<String> erpIdList = userList.stream().map(t -> t.getCode()).collect(Collectors.toList());

        //新增客户id集合
        List<String> addList = new ArrayList<>();

        //判断id
        for (String erpId : erpIdList) {
            if(!idList.contains(erpId)){
                addList.add(erpId);
            }
        }
        //
        List<Customer> userList1 = new ArrayList<>();
        //对比 修改 保存 客户属性
        for (Customer user1 : userList) {
            user1.setWarehouseCode("CS0001");
            user1.setCompanyCode("JY");
            user1.setCreatedBy("ERP系统");
            userList1.add(user1);
        }
        if(userList1.size()>0){
            customerService.truncateTable();
        }
        customerService.saveOrUpdateBatch(userList1);
    }

    @Override
    public void material() {
        K3CloudApi api = new ExtK3CloudApi();
        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("fdocumentStatus=\'C\' and FUseOrgId.FNumber='102' and FForbidStatus=\'A\' and FMaterialGroup.Fnumber like '2%'")
                .setStartRow(0)
                .setLimit(0);
        List<ERPMaterial> datas = null;
        try {
            datas = api.executeBillQuery(param, ERPMaterial.class);
        } 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);

        Gson gson = new Gson();
        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);
            addMaterialList.add(material1);
        }
        if(datas.size()>0){
            materialService.truncateTable();
        }
        materialService.insertBatch(addMaterialList);
    }

    @Override
    public void proPackaging() {
        K3CloudApi api = new ExtK3CloudApi();
        QueryParam param = new QueryParam()
                .setFormId("CH_ProPackaging")
                .setFieldKeys("FNumber,FName,FDescription,FPrice,FPieceBox,F_CH_Pallet,F_CH_Boxs")
                .setFilterString("fdocumentStatus=\'C\' and FUseOrgId.FNumber='101' and FForbidStatus=\'A\'")
                .setOrderString("FID ASC")
                .setLimit(0);
        List<ProPackaging> datas = null;
        try {
            datas = api.executeBillQuery(param, ProPackaging.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(datas.size()>0){
            proPackagingService.truncateTable();
        }
        proPackagingService.insertBatch(datas);
    }

    @Override
    public void productSize() {
        //基本物料数据获取器
        K3CloudApi api = new ExtK3CloudApi();
        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("fdocumentStatus=\'C\' and FForbidStatus=\'A\'  and FUseOrgId.FNumber='100'")
                .setStartRow(0)
                .setLimit(0);
        List<ProductSize> datas = null;
        try {
            datas = api.executeBillQuery(param, ProductSize.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(datas.size()>0){
            productSizeService.truncateTable();
        }
        productSizeService.insertBatch(datas);
    }

    @Override
    public void stock() {
        K3CloudApi api = new ExtK3CloudApi();
        QueryParam param = new QueryParam()
                .setFormId("BD_STOCK")
                .setFieldKeys("fStockId,fName,fNumber,fisOpenLocation,FUseOrgId.FNumber")
                .setFilterString("fdocumentStatus=\'C\' and FUseOrgId.FNumber='102' and FForbidStatus=\'A\'")
                .setOrderString("fStockId ASC")
                .setLimit(0);
        List<Stock> stocks = null;
        try {
            stocks = api.executeBillQuery(param, Stock.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(stocks.size()>0){
            stockService.truncateTable();
        }
        stockService.insertBatch(stocks);
    }

    @Override
    public void flexValues() {
        K3CloudApi api = new ExtK3CloudApi();
        QueryParam param = new QueryParam()
                .setFormId("bd_flexvalues")
                .setFieldKeys("fid,fName,fNumber,fflexValueNumber,fflexValueName,FUseOrgId.FNumber,FEntity_FEntryId")
                .setFilterString("fdocumentStatus=\'C\' and FUseOrgId.FNumber='101' and FForbidStatus=\'A\'")
                .setOrderString("FEntity_FEntryId ASC")
                .setLimit(0);
        List<FlexValues> flexValues = null;
        try {
            flexValues = api.executeBillQuery(param, FlexValues.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(flexValues.size()>0){
            flexValuesService.truncateTable();
        }
        flexValuesService.insertBatch(flexValues);
    }

    @Override
    public void unit() {
        K3CloudApi api = new ExtK3CloudApi();
        QueryParam param = new QueryParam()
                .setFormId("bd_unit")
                .setFieldKeys("fName,fNumber")
                .setFilterString("FDocumentStatus=\'C\' and FForbidStatus=\'A\'")
                .setOrderString("funitid ASC")
                .setLimit(0);
        List<Unit> units = null;
        try {
            units = api.executeBillQuery(param, Unit.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

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

    @Override
    public void bosAssistantDetail() {
        //基本物料数据获取器
        K3CloudApi api = new ExtK3CloudApi();
        QueryParam param = new QueryParam()
                .setFormId("BOS_ASSISTANTDATA_DETAIL")
                .setFieldKeys("Fid.Fnumber,FdataValue,FNUMBER,fdocumentStatus,FisSysPreset,Fdescription")
                .setFilterString("fdocumentStatus=\'C\' and FForbidStatus=\'A\' and FId.FNumber in (\'level\',\'colour\',\'QTCKLX\',\'QTRKLX\',\'SCLLLX\')")
                .setStartRow(0)
                .setLimit(0);
        List<BosAssistantDetail> datas = null;
        try {
            datas = api.executeBillQuery(param, BosAssistantDetail.class);
        } 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 void productSchedule() {
        K3CloudApi api = new ExtK3CloudApi();
        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("fdocumentStatus=\'C\' and FForbidStatus=\'A\' and F_CH_IsClose=0 and FCreateOrgId.Fnumber='100'")
                .setOrderString("FCreateDate DESC")
                .setStartRow(0)
                .setLimit(0);
        List<ProductScheduleHeader> datas = null;
        try {
            datas = api.executeBillQuery(param, ProductScheduleHeader.class);
        } 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("fdocumentStatus=\'C\' and FForbidStatus=\'A\' and F_CH_IsClose=0 and FCreateOrgId.Fnumber='100'")
                .setOrderString("FCreateDate DESC")
                .setStartRow(0)
                .setLimit(0);
        List<ProductScheduleDetail> detailDatas = null;
        try {
            detailDatas = api.executeBillQuery(detailParam, ProductScheduleDetail.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(detailDatas.size()>0){
            productScheduleDetailService.truncateTable();
        }
        productScheduleDetailService.insertBatch(detailDatas);
    }



    @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() {
        AjaxResult ajaxResult = AjaxResult.success("出库列表已更新为最新状态!!");
        boolean result = false;
        String warehouseCode = "CS0001";
        String companyCode = "JY";
        K3CloudApi api = new ExtK3CloudApi();
        QueryParam param = new QueryParam()
                .setFormId("STK_OutStockApply")
                .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")
                .setFilterString("fdocumentStatus=\'C\' and FCloseStatus='A' and FStockOrgId.FNumber='102'")
                .setOrderString("FApproveDate DESC");
        List<ShipmentRequests> datas = null;
        try {
            datas = api.executeBillQuery(param, ShipmentRequests.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<ShipmentRequest> transfer = ShipmentRequests.transfer(datas);
        if(transfer.size()==0){
            return AjaxResult.error("没有找到出库申请单");
        }

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

        List<Integer> integers = shipmentHeaderService.list(queryWrapper2).stream().map(ShipmentHeader::getReferId).collect(Collectors.toList());

        List<ShipmentRequest> collect = transfer.stream()
                .filter(s -> !integers.contains(s.getId())).collect(Collectors.toList());
        for (ShipmentRequest req : collect) {
            //其他出库类型
            String code = shipmentHeaderService.createCode("SO");
            ShipmentHeader shipmentHeader = new ShipmentHeader();
            shipmentHeader.setWarehouseCode(warehouseCode);
            shipmentHeader.setCompanyCode(companyCode);
            shipmentHeader.setCode(code);
            shipmentHeader.setShipmentType("SO");
            shipmentHeader.setReferId(req.getId());//申请单内部号
            shipmentHeader.setReferCodeType(req.getBillTypeId());//申请单类型
            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系统");
            if (StringUtils.isNotEmpty(req.getReceiver())) {
                shipmentHeader.setCarrierCode(req.getReceiver());
            }
            result = shipmentHeaderService.save(shipmentHeader);
            if(!result){
                throw new ServiceException("出库单保存失败!");
            }
            List<ShipmentRequestEntity> entity = req.getEntity();
            List<ShipmentDetail> shipmentDetailList = new ArrayList<ShipmentDetail>();
            for (ShipmentRequestEntity reqEntity : entity) {
                ShipmentDetail shipmentDetail = new ShipmentDetail();
                shipmentDetail.setShipmentId(shipmentHeader.getId());
                shipmentDetail.setReferId(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()));
                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
        ExtK3CloudApi api = new ExtK3CloudApi();
        OperatorResult operatorResult = null;
        ApiLog log = null;
        Gson gson = new Gson();
        String body = gson.toJson(param);
        HttpHeaders headers = new HttpHeaders();
        String msg = "WMS请求发送成功,接收返回内容是空的";
        try {
            log = ApiLogAspect.initApiLog("post", QuantityConstant.URL+"STK_OutStockApply",
                    body, headers, QuantityConstant.DEFAULT_WAREHOUSE);
            operatorResult = api.pushOperator("STK_OutStockApply", "DoNothingPushOut", param);
            RepoStatus results = operatorResult.getResult().getResponseStatus();
            if(!results.isIsSuccess()){
                ArrayList<RepoError> errors = results.getErrors();
                msg = JSON.toJSONString(errors);
                throw new ServiceException(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);
        ExtK3CloudApi api = new ExtK3CloudApi();
        try {
            log = ApiLogAspect.initApiLog("post", QuantityConstant.URL+"STK_MisDelivery",
                    body, headers, QuantityConstant.DEFAULT_WAREHOUSE);
            operatorResult = api.pushOperator("STK_MisDelivery", "", param);
            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)
    public AjaxResult downLoadDeliveryNotice() {
        AjaxResult ajaxResult = AjaxResult.error("下载失败");
        boolean result = false;
        String warehouseCode = "CS0001";
        String companyCode = "JY";
        K3CloudApi api = new ExtK3CloudApi();
        QueryParam param = new QueryParam()
                .setFormId("SAL_DELIVERYNOTICE")
                .setFieldKeys("FId,FBillNo,FSOEntryId,FBillTypeID.FNumber,F_CH_LoadRemark,FreceiveAddress,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")
                .setFilterString("fdocumentStatus=\'C\' and FDeliveryOrgID.FNumber='102'")
                .setOrderString("FApproveDate DESC");
        List<DeliveryNotices> datas = null;
        try {
            datas = api.executeBillQuery(param, DeliveryNotices.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

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

        List<Integer> integers = shipmentHeaderService.list(queryWrapper2).stream().map(ShipmentHeader::getReferId).collect(Collectors.toList());
        deliveryNoticeList = deliveryNoticeList.stream()
                .filter(s -> !integers.contains(s.getId())).collect(Collectors.toList());

        for (DeliveryNotice deliveryNotice : deliveryNoticeList) {
            String code = shipmentHeaderService.createCode("DN");
            ShipmentHeader shipmentHeader = new ShipmentHeader();
            shipmentHeader.setWarehouseCode(warehouseCode);
            shipmentHeader.setCompanyCode(companyCode);
            shipmentHeader.setCode(code);
            shipmentHeader.setShipmentType("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.getNote());
            shipmentHeader.setPriority(100);
            shipmentHeader.setFirstStatus(0);
            shipmentHeader.setLastStatus(0);
            shipmentHeader.setCreatedBy("ERP系统");
            shipmentHeader.setDriverName(deliveryNotice.getDriver());
            shipmentHeader.setDriverTel(deliveryNotice.getLinkPhone());
            result = shipmentHeaderService.save(shipmentHeader);
            if(!result){
                throw new ServiceException("出库单保存失败!");
            }
            List<DeliveryNoticeEntity> entity = deliveryNotice.getEntity();
            List<ShipmentDetail> shipmentDetailList = new ArrayList<ShipmentDetail>();
            for (int i = 0; i < entity.size(); i++) {
                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()));
                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<Integer> soEntryIds = list.stream().map(ReceiptDetail::getSoEntryId).collect(Collectors.toList());
        if(soEntryIds.size() == 0 ){
            return AjaxResult.error("找不到关联发货通知单 soEntryId");
        }

        LambdaQueryWrapper<ShipmentDetail> queryWrapper4 = Wrappers.lambdaQuery();
        queryWrapper4.in(ShipmentDetail::getSoEntryId,soEntryIds);
        //发货通知明细
        List<ShipmentDetail> list2 = shipmentDetailService.list(queryWrapper4);
        Map<String, ShipmentDetail> maps = list2.stream().collect(Collectors.toMap(ShipmentDetail::getMaterialCode,a->a));
        Integer shipmentId = list2.get(0).getShipmentId();

        LambdaQueryWrapper<ShipmentHeader> queryWrapper5 = Wrappers.lambdaQuery();
        queryWrapper5.eq(ShipmentHeader::getId,shipmentId);
        //获取发货通知单
        ShipmentHeader noticeShipment = shipmentHeaderService.getOne(queryWrapper5);

        //entrys
        List<PushTransferEntity> entrys = new ArrayList<>();
        //Parameters
        PushTransfer parameters = new PushTransfer();
        //ExtOperateParam
        ExtOperateParam param = new ExtOperateParam();
        //直接调拨单明细
        LambdaQueryWrapper<ReceiptDetail> queryWrapper2 = Wrappers.lambdaQuery();
        queryWrapper2.eq(ReceiptDetail::getReceiptId,receiptId);
        List<ReceiptDetail> receiptDetailList = receiptDetailService.list(queryWrapper2);


        for (ReceiptDetail receiptDetail : receiptDetailList) {
            PushTransferEntity entity = new PushTransferEntity();
            entity.setEntryId(noticeShipment.getReferId()+"");
            entity.setNoteEntry("");
            entity.setSrcStockId(srcStockId);
            entity.setSrcStockLocId(srcStockLocId);
            entity.setDestStockId(destStockId);
            entity.setDestStockLocId(destStockLocId);
            entity.setActQty(receiptDetail.getQty().intValue());
            if(maps.get(receiptDetail.getMaterialCode()) != null){
                ShipmentDetail shipmentDetail = maps.get(receiptDetail.getMaterialCode());
                entity.setHtzDetail(shipmentDetail.getFHTZDetail());
                entity.setSoEntryId(shipmentDetail.getSoEntryId()+"");
                entrys.add(entity);
                receiptDetail.setFHTZDetail(shipmentDetail.getFHTZDetail());
                receiptDetail.setSoEntryId(shipmentDetail.getSoEntryId());
            }
        }

        parameters.setSrcBillNo(noticeShipment.getReferCode());
        System.out.println(receiptDetailList);
        parameters.setEntrys(entrys);
        param.setParameters(parameters);
        param.setNumbers(noticeShipment.getReferCode());
        Gson gson2 = new Gson();
        System.out.println(gson2.toJson(param));
        ExtK3CloudApi api = new ExtK3CloudApi();
        OperatorResult operatorResult = null;
        ApiLog log = null;
        HttpHeaders headers = new HttpHeaders();
        try {
            log = ApiLogAspect.initApiLog("post", QuantityConstant.URL+"SAL_DELIVERYNOTICE",
                    gson2.toJson(param), headers, QuantityConstant.DEFAULT_WAREHOUSE);
            operatorResult = api.pushOperator("SAL_DELIVERYNOTICE",
                    "DoNothing_PushTransferRin", param);
            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);
                directId = success.getId();
                directCode = success.getNumber();
                //修改直接调拨单明细
                receiptDetailService.updateBatchById(receiptDetailList);
                //修改直接调拨单referId referCode
                receiptHeader.setReferId(Integer.valueOf(directId));
                receiptHeader.setReferCode(directCode);
                receiptHeader.setFirstStatus(QuantityConstant.RECEIPT_HEADER_RETURN);
                receiptHeader.setLastStatus(QuantityConstant.RECEIPT_HEADER_RETURN);
                receiptHeaderService.updateById(receiptHeader);
                msg = "回传成功";
                //更新直接调拨单 状态
//            receiptHeaderService.updateReceiptStatus(receiptHeader.getId());
            } 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)
    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+"】找不到或被删除!!");
        }
        //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);
        //
        List<String> fHTZDetails = shipmentDetailList.stream().map(ShipmentDetail::getFHTZDetail).collect(Collectors.toList());
        LambdaQueryWrapper<ReceiptDetail> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.in(ReceiptDetail::getFHTZDetail,fHTZDetails);
        //获取直接调拨单明细
        List<ReceiptDetail> details = receiptDetailService.list(queryWrapper1);
        if(details.size()==0){
            throw new ServiceException("销售出库单回传【异常】:" +
                    "没有找打对应调拨单明细");
        }
        Integer receiptId = details.get(0).getReceiptId();

        Map<String, String> maps = details.stream().collect(Collectors.toMap(ReceiptDetail::getMaterialCode,
                ReceiptDetail::getFHTZDetail));

        LambdaQueryWrapper<ReceiptHeader> queryWrapper2 = Wrappers.lambdaQuery();
        queryWrapper2.eq(ReceiptHeader::getId,receiptId);
        //获取直接调拨单
        ReceiptHeader directReceipt = receiptHeaderService.getOne(queryWrapper2);

        for (ShipmentDetail shipmentDetail : shipmentDetailList) {
            PushTransferEntity entity = new PushTransferEntity();
            entity.setActQty(shipmentDetail.getQty().intValue());
            if(maps.get(shipmentDetail.getMaterialCode()) != null){
                entity.setHtzDetail(maps.get(shipmentDetail.getMaterialCode()));
                shipmentDetail.setFHTZDetail(maps.get(shipmentDetail.getMaterialCode()));
                entrys.add(entity);
            }
        }

        parameters.setSrcBillNo(directReceipt.getReferCode());
        parameters.setEntrys(entrys);
        param.setParameters(parameters);
        param.setNumbers(directReceipt.getReferCode());
        Gson gson2 = new Gson();
        String body = gson2.toJson(param);
        ApiLog log = null;
        HttpHeaders headers = new HttpHeaders();
        ExtK3CloudApi api = new ExtK3CloudApi();
        OperatorResult operatorResult = null;
        String msg = "WMS请求发送成功,接收返回内容是空的";
        try {
            log = ApiLogAspect.initApiLog("post", QuantityConstant.URL+"STK_TransferDirect",
                    body, headers, QuantityConstant.DEFAULT_WAREHOUSE);
            operatorResult = api.pushOperator("STK_TransferDirect", "DoNothing_TransferPushSaleOut", param);
            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);
                shipmentDetailService.updateBatchById(shipmentDetailList);
                shipmentHeader.setReferId(Integer.valueOf(success.getId()));
                shipmentHeader.setReferCode(success.getNumber());
                shipmentHeader.setLastStatus(900);
                shipmentHeader.setFirstStatus(900);
                shipmentHeaderService.updateById(shipmentHeader);
            }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() {
        AjaxResult ajaxResult = AjaxResult.success("出库列表已更新为最新状态!!");
        boolean result = false;
        String warehouseCode = "CS0001";
        String companyCode = "JY";
        K3CloudApi api = new ExtK3CloudApi();
        QueryParam param = new QueryParam()
                .setFormId("SAL_RETURNNOTICE")
                .setFieldKeys("FId,FBillNo,FDate,FBillTypeID.FNumber,FRetorgId.FNumber,FReceiveCusContact,FDescription,FReturnReason,FownerTypeIdHead,Fdate,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")
                .setFilterString("fdocumentStatus=\'C\' and FCloseStatus='A' and FRetorgId.FNumber='102'")
                .setOrderString("FApproveDate DESC");
        List<ReturnNotices> datas = null;
        try {
            datas = api.executeBillQuery(param, ReturnNotices.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<ReturnNotice> transfer = ReturnNotices.transfer(datas);
        if(transfer.size()==0){
            return AjaxResult.error("没有找到出库申请单");
        }

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

        List<Integer> integers = receiptHeaderService.list(queryWrapper2).stream().map(ReceiptHeader::getReferId).collect(Collectors.toList());

        List<ReturnNotice> collect = transfer.stream()
                .filter(s -> !integers.contains(s.getId())).collect(Collectors.toList());
        for (ReturnNotice req : collect) {
            //其他出库类型
            String code = receiptHeaderService.createCode("RN");
            ReceiptHeader receiptHeader = new ReceiptHeader();
            receiptHeader.setWarehouseCode(warehouseCode);
            receiptHeader.setCompanyCode(companyCode);
            receiptHeader.setCode(code);
            receiptHeader.setReceiptType("RN");
            receiptHeader.setReferId(req.getId());//申请单内部号
            receiptHeader.setReferType(req.getBillTypeId());//申请单类型
            receiptHeader.setReferCode(req.getBillNo());//申请编码
            receiptHeader.setTotalQty(BigDecimal.ZERO);
            receiptHeader.setReceiptNote(req.getDescription());
            receiptHeader.setTotalLines(0);
            receiptHeader.setFirstStatus(0);
            receiptHeader.setLastStatus(0);
            receiptHeader.setCreatedBy("ERP系统");

            result = receiptHeaderService.save(receiptHeader);
            if(!result){
                throw new ServiceException("出库单保存失败!");
            }
            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.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.setTotalLines(receiptHeader.getTotalLines() + 1);
                receiptHeader.setTotalQty(receiptHeader.getTotalQty().add(receiptDetail.getQty()));
                receiptHeaderService.updateById(receiptHeader);
            }
        }
        return ajaxResult;
    }

    @Override
    public AjaxResult pushReturnNotice(PushModel pushModel) {
        AjaxResult ajaxResult = AjaxResult.success("回传成功");
        boolean result = false;
        int shipmentId = pushModel.getHeaderId();
        ShipmentHeader shipmentHeader = shipmentHeaderService.getById(shipmentId);
        if(shipmentHeader==null){
            throw new ServiceException("下推失败,找不到出库单内码 receiptId:【"+shipmentId+"】找不到或被删除!!");
        }
        //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);

        List<String> fHTZDetails = shipmentDetailList.stream().map(ShipmentDetail::getFHTZDetail).collect(Collectors.toList());
        LambdaQueryWrapper<ReceiptDetail> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.in(ReceiptDetail::getFHTZDetail,fHTZDetails);
        //获取退货通知单明细
        List<ReceiptDetail> details = receiptDetailService.list(queryWrapper1);
        if(details.size()==0){
            throw new ServiceException("回传销售退货单【异常】:没有找到入库单明细");
        }
        Map<String, String> maps = details.stream().collect(Collectors.toMap(ReceiptDetail::getMaterialCode, ReceiptDetail::getFHTZDetail));
        Integer receiptId = details.get(0).getReceiptId();

        LambdaQueryWrapper<ReceiptHeader> queryWrapper2 = Wrappers.lambdaQuery();
        queryWrapper2.eq(ReceiptHeader::getId,receiptId);
        //获取退货通知单
        ReceiptHeader returnReceipt = receiptHeaderService.getOne(queryWrapper2);

        for (ShipmentDetail shipmentDetail : shipmentDetailList) {
            PushTransferEntity entity = new PushTransferEntity();
            entity.setActQty(shipmentDetail.getQty().intValue());
            entity.setNoteEntry("");
            entity.setSrcStockId(pushModel.getSrcStockId());
            entity.setSrcStockLocId(pushModel.getDestStockLocId());
            if(maps.get(shipmentDetail.getMaterialCode()) != null){
                entity.setHtzDetail(maps.get(shipmentDetail.getMaterialCode()));
                shipmentDetail.setFHTZDetail(maps.get(shipmentDetail.getMaterialCode()));
                entrys.add(entity);
            }
        }
        parameters.setSargetBillTypeNum("66fba68dd04b499e8860966f2ee60117");
        parameters.setSrcBillNo(returnReceipt.getReferCode());
        parameters.setEntrys(entrys);

        param.setParameters(parameters);
        param.setNumbers(returnReceipt.getReferCode());
        Gson gson2 = new Gson();
        System.out.println(gson2.toJson(param));
        ExtK3CloudApi api = new ExtK3CloudApi();
        OperatorResult operatorResult = null;
        try {
            operatorResult = api.pushOperator("SAL_RETURNNOTICE", "DoNothingPushOut", param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        RepoStatus results = operatorResult.getResult().getResponseStatus();
        boolean isSuccess = results.isIsSuccess();
        String id = "";
        String code = "";

        if(isSuccess){
            ArrayList<SuccessEntity> successEntitys = results.getSuccessEntitys();
            SuccessEntity success = successEntitys.get(0);
            //更新 销售退货单明细
            shipmentDetailService.updateBatchById(shipmentDetailList);
            //更新 销售退货单
            shipmentHeader.setReferId(Integer.valueOf(success.getId()));
            shipmentHeader.setReferCode(success.getNumber());
            shipmentHeader.setLastStatus(900);
            shipmentHeader.setFirstStatus(900);
            shipmentHeaderService.updateById(shipmentHeader);
        }else{
            ArrayList<RepoError> errors = results.getErrors();
            String errorMsg = "";
            for (RepoError error : errors) {
                Gson gson = new Gson();
                errorMsg += gson.toJson(error);
            }
            throw new ServiceException(errorMsg);
        }
        return ajaxResult;
    }

    @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 "JS" :
                //直接调拨单回传
                pushModel.setSrcStockId(QuantityConstant.SRC_STOCK_ID);//
                pushModel.setDestStockId(QuantityConstant.DEST_STOCK_ID);
                ajaxResult = pushDirectTransfer(pushModel);
                break;
//            case "ZJDB01_01User" : //直接调拨单 下推
//                ajaxResult = pushSalesDelivery(pushModel);
//                break;
            case "SR" : //退货通知单 下推 销售退货单
                pushModel.setSrcStockId(QuantityConstant.SRC_STOCK_ID);
                ajaxResult = pushReturnNotice(pushModel);
                break;
            case "QTCKD01_SYS" : //出库申请单 下推 其他出库单
                pushModel.setSrcStockId(QuantityConstant.SRC_STOCK_ID_BH);//
                ajaxResult = pushShipmentRequest(pushModel);
                break;
            case "QTRKD01_SYS" : //其他出库单 下推 其他入库单
                pushModel.setSrcStockId(QuantityConstant.SRC_STOCK_ID);//
                pushModel.setDestStockId(QuantityConstant.DEST_STOCK_ID);
                ajaxResult = pushOtherBilling(pushModel);
                break;
            case "SC" :  //生产入库单
                ajaxResult = receiptMethod(pushModel.getHeaderId());
                break;
            case "SP" : //销售出库回传
                ajaxResult = pushSalesDelivery(pushModel);
                break;
            default :
                throw new ServiceException("该类型没有下推规则");
        }
        return ajaxResult;
    }

    /**
     * 回传入库单数据
     * @param receiptHeader 任务头
     */
    @Transactional
    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 = param(receiptHeader,receiptHeader.getReferType());
            ExtSaveParam saveParam = new ExtSaveParam<>(receiptData);

            K3CloudApi api = new ExtK3CloudApi();
            //返回结果
            SaveResult spInStock = null;
            Gson gson = new Gson();
            System.out.println(gson.toJson(saveParam));
            ApiLog log = null;
            String body = gson.toJson(saveParam);
            HttpHeaders headers = new HttpHeaders();
            try {
                if (SingleReceipt.class.isAssignableFrom(receiptData.getClass())) {
                    formId = "SP_InStock";
                    spInStock = api.save(formId, saveParam, InvokeMode.Syn);
                    log = ApiLogAspect.initApiLog("post", QuantityConstant.URL+"SP_InStock",
                            body, headers, QuantityConstant.DEFAULT_WAREHOUSE);
                } else if (OtherReceipt.class.isAssignableFrom(receiptData.getClass())) {
                    formId = "STK_MISCELLANEOUS";
                    spInStock = api.save(formId, saveParam, InvokeMode.Syn);
                    log = ApiLogAspect.initApiLog("post", QuantityConstant.URL+"STK_MISCELLANEOUS",
                            body, 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> receiptDetails = receiptDetailService.list(queryWrapper);
                    for (ReceiptDetail receiptDetail : receiptDetails) {
                        receiptDetail.setReferId(referId);
                        receiptDetail.setReferCode(referCode);
                        receiptDetailService.updateById(receiptDetail);
                    }
                    receiptHeader.setReferId(referId);
                    receiptHeader.setReferCode(referCode);
                    receiptHeaderService.updateById(receiptHeader);
                    //修改回传后状态
                    editReceiveStatus(receiptHeader.getId());
                    //更新 入库单明细状态
                    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 = "";
            //回传器
            SaveParam<Object> saveParam = null;
            //获取回传出库信息
            receiptData = param(shipmentHeader,shipmentHeader.getReferCodeType());
            //回传model
            saveParam = new ExtSaveParam<>(receiptData);

            K3CloudApi api = new ExtK3CloudApi();
            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;
            try {
                spInStock = api.save(formId,saveParam,InvokeMode.Syn);
            } catch (Exception e) {
                e.printStackTrace();
            }
            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 回传入库信息
     */
    private Object param(ReceiptHeader receiptHeader,String billType){
        Object returnReceipt;
        switch (billType) {
            //简单生产入库单
            case QuantityConstant.BILL_TYPE_RECEIPT_SINGLE:
                returnReceipt = buildSingleReceiptHead(receiptHeader);
                break;
            //其他生产入库单
            case QuantityConstant.BILL_TYPE_RECEIPT_OTHER:
                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<ReceiptBillEntity> receiptInfos = getReceiptEntities(details);

        //设置回传入库明细集
        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.BILL_TYPE_SHIPMENT_OTHER:
                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);

        // 传入物料判断是否添加辅助属性
        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, "colour");
        ConvertObj color= ConvertObjFactory.newInstance(colorValue);
        //等级
        String levelDetail = detail.getLevel();
        String levelValue = getBosAssistantNumber(levelDetail, "level");
        ConvertObj level = ConvertObjFactory.newInstance(levelValue);
        //尺寸
        ConvertObj productSize = ConvertObjFactory.newInstance(detail.getProductSize());

        auxProperty.setColor(color);
        auxProperty.setLevel(level);
        auxProperty.setProPackaging(proPackaging);
        auxProperty.setProductSize(productSize);
        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("CK005"));
        //仓位
        StockLoc location = new StockLoc();
        location.setLocation(ConvertObjFactory.newInstance("1101T"));
        billEntity.setStockLocId(location);
        //批号
        billEntity.setLotId(ConvertObjFactory.newInstance(detail.getBatch()));
        //货主类型
        billEntity.setOwnerType("BD_OwnerOrg");
        //货主
        billEntity.setOwnerId(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //库存状态
        billEntity.setStockstatusId(ConvertObjFactory.newInstance("KCZT01_SYS"));
        //保管者类型
        billEntity.setKeeperType("BD_KeeperOrg");
        //保管者
        billEntity.setKeeperId(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //库存组织
        billEntity.setOrgId(ConvertObjFactory.newInstance(QuantityConstant.JY));


        //other attr
        //默认生产车间
        //就一个可选测试
        billEntity.setWorkShopId1(ConvertObjFactory.newInstance("BM000340"));
        //箱数
        billEntity.setBox(detail.getQty().intValue());
        //生产编号
        billEntity.setProductNo(detail.getBatch());
        //基本单位实收数量
        billEntity.setBaseRealQty(detail.getQty());

        //实收数量
        billEntity.setRealQty(detail.getQty());
        //重量
        BigDecimal pieceWeight = material.getPieceWeight();
        billEntity.setWeight(pieceWeight.multiply(detail.getQty()));
        //箱数
        billEntity.setBox(detail.getBox());
        return billEntity;
    }


    private String getBosAssistantNumber(String dataValue, String id) {
        LambdaQueryWrapper<BosAssistantDetail> bosAssistantDetailLambdaQueryWrapper = Wrappers.lambdaQuery();
        bosAssistantDetailLambdaQueryWrapper.eq(BosAssistantDetail::getId, id)
                .eq(BosAssistantDetail::getDataValue, dataValue);
        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<InventoryHistoryDetail> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.eq(InventoryHistoryDetail::getMaterialCode,detail.getMaterialCode())
                .eq(StringUtils.isNotEmpty(detail.getProductSchedule()),InventoryHistoryDetail::getProductSchedule,detail.getProductSchedule())
                .eq(StringUtils.isNotEmpty(detail.getLevel()),InventoryHistoryDetail::getLevel,detail.getLevel())
                .eq(StringUtils.isNotEmpty(detail.getColor()),InventoryHistoryDetail::getColor,detail.getColor())
                .eq(StringUtils.isNotEmpty(detail.getProPackaging()),InventoryHistoryDetail::getProPackaing,detail.getProPackaging())
                .eq(StringUtils.isNotEmpty(detail.getProductSize()),InventoryHistoryDetail::getProductSize,detail.getProductSize())
                .gt(InventoryHistoryDetail::getTaskQty,0)
                .eq(InventoryHistoryDetail::getBatch,detail.getBatch());
        List<InventoryHistoryDetail> list = inventoryHistoryDetailService.list(queryWrapper1);
        InventoryHistoryDetail inventoryHistoryDetail = list.get(0);
        InventoryHistoryHeader inventoryHeader = inventoryHistoryHeaderService.getById(inventoryHistoryDetail.getInventoryHistoryHeaderId());

        AuxProperty auxProperty = new AuxProperty();
        ConvertObj proPackaging= ConvertObjFactory.newInstance(inventoryHistoryDetail.getProPackaing());
        ConvertObj productScheduleHeader = ConvertObjFactory.newInstance(inventoryHistoryDetail.getProductSchedule());
        ConvertObj color= ConvertObjFactory.newInstance(inventoryHistoryDetail.getColor());
        ConvertObj level = ConvertObjFactory.newInstance(inventoryHistoryDetail.getLevel());
        ConvertObj productSize = ConvertObjFactory.newInstance(inventoryHistoryDetail.getProductSize());
        auxProperty.setColor(color);
        auxProperty.setLevel(level);
        auxProperty.setProPackaging(proPackaging);
        auxProperty.setProductSize(productSize);
        auxProperty.setProductSchedule(productScheduleHeader);

        //base attr
        //物料编码
        billEntity.setMaterialId(ConvertObjFactory.newInstance(detail.getMaterialCode()));
        //辅助属性
        billEntity.setAuxProperty(auxProperty);
        //单位
        billEntity.setUnitId(ConvertObjFactory.newInstance(inventoryHistoryDetail.getMaterialUnit()));
        //收货仓库
        billEntity.setStockId(ConvertObjFactory.newInstance("Ck002"));
        //批号
        billEntity.setLot(ConvertObjFactory.newInstance(inventoryHistoryDetail.getBatch()));
        //货主类型
        billEntity.setOwnerTypeId("BD_OwnerOrg");
        //货主
        billEntity.setOwnerId(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //库存状态
        billEntity.setStockStatusId(ConvertObjFactory.newInstance("KCZT01_SYS"));
        //保管者类型
        billEntity.setKeeperTypeId("BD_KeeperOrg");
        //保管者
        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("BD_OwnerOrg");
        //产品货主
        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.getReceiptType()));
        //库存组织
        otherReceipt.setStockOrgId(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //货主
        otherReceipt.setOwnerIdHead(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //供应商
        otherReceipt.setSupplierId(ConvertObjFactory.newInstance("001.0001"));
        //部门
        otherReceipt.setDeptId(ConvertObjFactory.newInstance("102.BM000279"));
        //仓管员
        otherReceipt.setStockId(ConvertObjFactory.newInstance("102.YG2021054"));
        //本位币
        otherReceipt.setBaseCurrId(ConvertObjFactory.newInstance("PRE001"));
        //其他入库类型
        otherReceipt.setQtrklx(ConvertObjFactory.newInstance(receiptHeader.getInType()));
        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(new Date());

//        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("CK005"));
        //仓管员
        singleReceipt.setDescription("666");
        //本位币.
        singleReceipt.setBaseCurrId(ConvertObjFactory.newInstance("PRE001"));
        return singleReceipt;

    }

    public Object buildSingleShipmentHead(ShipmentHeader shipmentHeader){
        SingleShipment singleShipment = new SingleShipment();
        //单据类型
        singleShipment.setBillType(ConvertObjFactory.newInstance(shipmentHeader.getShipmentType()));
        //时间
        singleShipment.setDate(new Date());
        //入库组织
        singleShipment.setStockOrgId(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //本位币.
        singleShipment.setBaseCurrId(ConvertObjFactory.newInstance("PRE001"));
        //货主类型
        singleShipment.setOwnerTypeIdHead("BD_OwnerOrg");
        //货主
        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("CK005"));


        //other
        //生产车间
        singleShipment.setWorkShopId(ConvertObjFactory.newInstance("BM000340"));
        //业务类型
        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("GENERAL");
        //日期
        otherShipment.setDate(new Date());
        //部门
        otherShipment.setDeptId(ConvertObjFactory.newInstance("102.BM000279"));
        //仓管员
        otherShipment.setStockerId(ConvertObjFactory.newInstance("102.YG2021054"));
        //货主类型
        otherShipment.setOwnerTypeIdHead("BD_OwnerOrg");
        //货主
        otherShipment.setOwnerIdHead(ConvertObjFactory.newInstance(QuantityConstant.JY));
        //本位币
        otherShipment.setBaseCurrId(ConvertObjFactory.newInstance("PRE001"));

        //other
        //其他入库类型
        otherShipment.setQtcklx(ConvertObjFactory.newInstance(shipmentHeader.getQtcklx()));
        // 客户
        otherShipment.setCustId(ConvertObjFactory.newInstance(shipmentHeader.getCustomerCode()));
        //供应商
        otherShipment.setSupplierId(ConvertObjFactory.newInstance("001.0001"));
        //收货人信息
        otherShipment.setReceive("receive");
        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("CS0001");
        shipmentContainerHeader.setLocationCode(locationCode);
        shipmentContainerHeader.setCompanyCode("JY");
        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("赋码系统");
        shipmentContainerHeader.setLastUpdatedBy("赋码系统");
        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(new BigDecimal(1));
            shipmentContainerDetail.setBatch(batch);
            shipmentContainerDetail.setShipmentCode(shipmentDetail.getShipmentCode());
            shipmentContainerDetail.setBoxCode(inventoryDetail.getBoxCode());
            shipmentContainerDetail.setShipmentType("SC");
            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);
    }


    @Transactional(rollbackFor = Exception.class)
    Boolean agvTaskAndReceiptQcStream(String position, ReceiptHeader receiptHeader,String warehouseCode){
        //生成AGV取放货任务
        AgvTask agvTask = new AgvTask();
        agvTask.setTaskType(QuantityConstant.AGV_TYPE_TAKE_AND_RELEASE);
        agvTask.setStatus(QuantityConstant.AGV_TASK_STATUS_BUILD);
        agvTask.setWarehouseCode(warehouseCode);
        agvTask.setPriority(10);
        agvTask.setFromPort(position);
        agvTask.setToPort("质检点位");
        agvTask.setCreatedBy("赋码系统");
        Boolean result = agvTaskService.save(agvTask);
        if(!result) {
            throw new ServiceException("生成AGV任务失败");
        }
        //生成入库质检单
        receiptHeaderService.check(receiptHeader.getId());
        return Boolean.TRUE;
    }




}