ZarshService.java 93.7 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
package com.huaheng.pc.sap.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaheng.api.general.service.BasicDataApiService;
import com.huaheng.api.sap.domain.ZarDomain;
import com.huaheng.api.sap.service.ZarApiService;
import com.huaheng.api.utils.SAPUtils;
import com.huaheng.api.wcs.service.warecellAllocation.WarecellAllocationService;
import com.huaheng.common.constant.QuantityConstant;
import com.huaheng.common.exception.service.ServiceException;
import com.huaheng.common.utils.DateUtils;
import com.huaheng.common.utils.StringUtils;
import com.huaheng.common.utils.security.ShiroUtils;
import com.huaheng.framework.aspectj.lang.annotation.ProcessTrack;
import com.huaheng.framework.aspectj.lang.constant.ProcessCode;
import com.huaheng.framework.web.domain.AjaxResult;
import com.huaheng.framework.web.service.ConfigService;
import com.huaheng.pc.config.container.domain.Container;
import com.huaheng.pc.config.container.service.ContainerService;
import com.huaheng.pc.config.location.domain.Location;
import com.huaheng.pc.config.location.service.AcsLocationStatusService;
import com.huaheng.pc.config.location.service.LocationService;
import com.huaheng.pc.config.material.domain.Material;
import com.huaheng.pc.config.material.domain.MaterialDiameter;
import com.huaheng.pc.config.material.service.MaterialDiameterService;
import com.huaheng.pc.config.material.service.MaterialService;
import com.huaheng.pc.config.station.domain.Station;
import com.huaheng.pc.config.station.service.StationService;
import com.huaheng.pc.config.zone.domain.Zone;
import com.huaheng.pc.config.zone.service.ZoneService;
import com.huaheng.pc.inventory.inventoryDetail.domain.InventoryDetail;
import com.huaheng.pc.inventory.inventoryDetail.service.InventoryDetailService;
import com.huaheng.pc.inventory.inventoryHeader.service.InventoryHeaderService;
import com.huaheng.pc.receipt.receiptContainerHeader.domain.ReceiptContainerHeader;
import com.huaheng.pc.receipt.receiptContainerHeader.service.ReceiptContainerHeaderService;
import com.huaheng.pc.receipt.receiptHeader.service.ReceiptHeaderService;
import com.huaheng.pc.sap.domain.SAPTaskDomain;
import com.huaheng.pc.sap.domain.Zarsh;
import com.huaheng.pc.sap.domain.Zarsi;
import com.huaheng.pc.sap.mapper.ZarshMapper;
import com.huaheng.pc.shipment.shipmentContainerHeader.service.ShipmentContainerHeaderService;
import com.huaheng.pc.shipment.shipmentHeader.service.ShipmentHeaderService;
import com.huaheng.pc.task.agvTask.domain.AgvTask;
import com.huaheng.pc.task.agvTask.service.AgvTaskService;
import com.huaheng.pc.task.taskDetail.domain.TaskDetail;
import com.huaheng.pc.task.taskDetail.service.TaskDetailService;
import com.huaheng.pc.task.taskHeader.domain.TaskHeader;
import com.huaheng.pc.task.taskHeader.service.ReceiptTaskService;
import com.huaheng.pc.task.taskHeader.service.TaskHeaderService;
import com.huaheng.pc.task.taskHeader.service.WorkTaskEmptyContainerService;
import com.huaheng.pc.task.taskHeader.service.WorkTaskService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * Created by Enzo Cotter on 2022/5/11.
 *
 * @author zhouhong
 */
@Service
public class ZarshService extends ServiceImpl<ZarshMapper, Zarsh> {
    @Resource
    private ZarsiService zarsiService;
    @Resource
    private ReceiptContainerHeaderService receiptContainerHeaderService;
    @Resource
    private ShipmentContainerHeaderService shipmentContainerHeaderService;
    @Resource
    private ReceiptHeaderService receiptHeaderService;
    @Resource
    private ShipmentHeaderService shipmentHeaderService;
    @Resource
    private TaskHeaderService taskHeaderService;
    @Resource
    private ContainerService containerService;
    @Resource
    private BackSapStatusService backSapStatusService;
    @Resource
    private ZoneService zoneService;
    @Resource
    private StationService stationService;
    @Resource
    private LocationService locationService;
    @Resource
    private TaskDetailService taskDetailService;
    @Resource
    private WorkTaskService workTaskService;
    @Resource
    private WorkTaskEmptyContainerService workTaskEmptyContainerService;
    @Resource
    private ZarshService zarshService;
    @Resource
    private ZarApiService zarApiService;
    @Resource
    private ReceiptTaskService receiptTaskService;
    @Resource
    private InventoryDetailService inventoryDetailService;
    @Resource
    private MaterialService materialService;
    @Resource
    private MaterialDiameterService materialDiameterService;
    @Resource
    private BasicDataApiService basicDataApiService;
    @Resource
    private WarecellAllocationService warecellAllocationService;
    @Resource
    private AgvTaskService agvTaskService;
    @Resource
    private InventoryHeaderService inventoryHeaderService;
    @Resource
    private LockSapUniqueIdService lockSapUniqueIdService;
    @Resource
    private ZarshLocationService zarshLocationService;
    @Resource
    private ZarshAddService zarshAddService;
    @Resource
    private ConfigService configService;
    @Resource
    private AcsLocationStatusService acsLocationStatusService;
    @Resource
    private IStationBlocker stationBlocker;


    public Zarsh checkZarshByUniqueId(String uniqueId) {
        LambdaQueryWrapper<Zarsh> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(Zarsh::getUniqueId, uniqueId);
        lambdaQueryWrapper.last("limit 1");
        Zarsh zarsh = this.getOne(lambdaQueryWrapper);
        if (zarsh != null) {
            return zarsh;
        }
        return null;
    }

    public boolean saveZarsh(Zarsh zarsh) {
        Date date = new Date();
        String uniqueId = UUID.randomUUID().toString();
        zarsh.setUniqueId(uniqueId);
        zarsh.setCreated(date);
        zarsh.setCreateBy("wms");
        zarsh.setLastUpdatedBy("wms");
        zarsh.setLastUpdated(date);
        return this.save(zarsh);
    }

    public boolean editZarsh(Zarsh zarsh) {
        Date date = new Date();
        zarsh.setLastUpdatedBy("wms");
        zarsh.setLastUpdated(date);
        return this.updateById(zarsh);
    }

    public void removeByZarshId(String uniqueId, Integer id) {
        LambdaQueryWrapper<Zarsh> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(StringUtils.isNotEmpty(uniqueId), Zarsh::getUniqueId, uniqueId);
        queryWrapper.eq(StringUtils.isNotNull(id), Zarsh::getId, id);
        queryWrapper.last("limit 1");
        Zarsh zarsh = this.getOne(queryWrapper);
        if (zarsh != null) {
            LambdaQueryWrapper<Zarsi> query = Wrappers.lambdaQuery();
            query.eq(Zarsi::getUniqueId, zarsh.getUniqueId());
            List<Zarsi> list = zarsiService.list(query);
            List<Integer> ids = list.stream().map(detail -> detail.getId()).collect(toList());
            if (ids.size() > 0) {
                zarsiService.removeByIds(ids);
            }
            this.removeById(zarsh.getId());
        }

    }

    public Zarsh getZarshByUnique(String uniqueId) {
        LambdaQueryWrapper<Zarsh> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(StringUtils.isNotEmpty(uniqueId), Zarsh::getUniqueId, uniqueId);
        queryWrapper.last("limit 1");
        Zarsh zarsh = this.getOne(queryWrapper);
        return zarsh;
    }

    public AjaxResult saveSapDataByApi(ZarDomain zarDomain) {
        // 用主表UniqueId查找子表zarsi信息
        List<Zarsi> zarsiList = zarDomain.getZarsiList();
        Zarsh zarsh = zarDomain.getZarsh();
        /**
         * 任务取消
         */
        if (StringUtils.isNotEmpty(zarsh.getCFlag()) && zarsh.getCFlag().equals("D")) {
            // 取消
            return zarApiService.cancelTaskBySap(zarsh);
        }
        Zarsh zarsh1 = zarshService.checkZarshByUniqueId(zarsh.getUniqueId());
        if (zarsh1 != null) {
            return AjaxResult.error("单据已存在,请不要重复下发");
        }
        return zarshService.createTaskBySAP(zarsiList, zarsh);

    }

    /**
     * pltype 入库已wms托盘表为准,出库已sap为准
     *
     * @param zarsiList
     * @param zarsh
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult createTaskBySAP(List<Zarsi> zarsiList, Zarsh zarsh) {
        String zoneCode = SAPUtils.getZoneCode(zarsh);
        String area = zoneService.getZoneAreaByCode(zoneCode);
        String port = null;
        String inOrOut = "";
        if (StringUtils.isNotEmpty(area)) {
            switch (zarsh.getMFlag()) {
                case "2":
                case "B":
                case "M":
                    inOrOut = "IN";
                    port = zarsh.getFromPos();
                    if (zarsh.getLgnum().equals("PLC")) {
                        Container container = containerService.getContainerByCode(zarsh.getDrumId(), QuantityConstant.WAREHOUSECODE);
                        if (container != null) {
                            if (container.getPlType() == 0) {
                                throw new ServiceException("配料仓不能入库卷状托盘:" + zarsh.getDrumId());
                            }
                        }
                    }
                    String crnIn = zarsh.getCrnIn();
                    if (StringUtils.isNotEmpty(crnIn)) {
                        if (crnIn.equals("A") || crnIn.equals("a") || crnIn.equals("B") || crnIn.equals("b") || crnIn.equals("C") || crnIn.equals("c")) {
                            crnIn = crnIn.toUpperCase();
                            zarsh.setCrnIn(crnIn);
                        } else {
                            zarsh.setCrnIn("");
                        }
                    }
                    if(zoneCode.equals("E")){
                        Container container = containerService.getContainerByCode(zarsh.getDrumId(), QuantityConstant.WAREHOUSECODE);
                        if(container != null){
                            if(container.getPlType() == 0){
                                throw new ServiceException("卷托盘不能入到配料仓");
                            }
                        }
                    }

                    break;
                case "1":
                case "3":
                    inOrOut = "OUT";
                    port = zarsh.getToPos();
                    if (StringUtils.isNotEmpty(zarsh.getLocation()) && zarsh.getLocation().equals(port)) {
                        throw new ServiceException("出库终点和库位不能一样:" + port + ":" + zarsh.getLocation());
                    }
                    if(zoneCode.equals("E")){
                        Container container = containerService.getContainerByCode(zarsh.getDrumId(), QuantityConstant.WAREHOUSECODE);
                        if(container != null){
                            if(container.getPlType() == 0){
                                throw new ServiceException("卷托盘不能出到配料仓");
                            }
                        }
                    }
                    break;
                default:
            }
            if (StringUtils.isEmpty(port)) {
                throw new ServiceException("指定:" + zarsh.getMFlag() + " 站台不存在");
            }
            Station station = stationService.getStationBySAPCode(port);
            if (StringUtils.isNull(station)) {
                throw new ServiceException("指定:" + zarsh.getMFlag() + " 站台未找到:" + port);
            }
            if(station.getTwoWay() > 0){
                if(stationBlocker.isBlock(station.getCode(), inOrOut)){
                    throw new ServiceException(station.getCode().concat("站台开启双向限制,不能同时出入库。"));
                }
            }
            if(station.getCode().equals("P4005")){
                Container container = containerService.getContainerByCode(zarsh.getDrumId(), QuantityConstant.WAREHOUSECODE);
                if(container != null){
                    if(container.getPlType() == 0){
                        throw new ServiceException("卷托盘不能出到配料仓");
                    }
                }
            }
        }

        /**
         * 1:整盘 / 等待组盘
         * 2:空托
         */
        Integer billType = zarsh.getInKind();
        String type = zarsh.getMFlag();
        String uniqueId = zarsh.getUniqueId();
        SAPTaskDomain domain = new SAPTaskDomain();
        domain.setZarsh(zarsh);
        domain.setZarsiList(zarsiList);
        if (!zarshService.save(zarsh)) {
            throw new ServiceException("保存主表数据失败");
        }
        if (!zarsiService.saveBatchs(zarsiList, zarsh)) {
            throw new ServiceException("保存子表数据失败");
        }

        // 站台单向检测

        // 商片仓2061只能出空托,和入库,2058只能出库
        switch (billType) {
            case 1:
                createHavingTask(domain);
                break;
            case 0:
                createEmptyTask(domain);
                break;
            default:
                throw new ServiceException("inKind不支持的业务类型");
        }
        backSapStatusService.addBackSapStatus(uniqueId, zoneCode, null, type, "1", null, null);
        return AjaxResult.success("添加任务成功");
    }

    /**
     * SAP无货指令
     *
     * @param domain
     */
    public void createEmptyTask(SAPTaskDomain domain) {
        Zarsh zarsh = domain.getZarsh();
        String formPort = zarsh.getFromPos();
        String toPort = zarsh.getToPos();
        String type = zarsh.getMFlag();
        Integer containerType = zarsh.getPlType();
        String containerCode = zarsh.getDrumId();
        String locationCode = zarsh.getLocation();
        String uniqueId = zarsh.getUniqueId();
        String crnIn = zarsh.getCrnIn();
        String zoneCode = SAPUtils.getZoneCode(zarsh);
        List<Zarsi> zarsiList = domain.getZarsiList();

        // 入库站台属性
        switch (type) {
            // 入库
            case "2":
            case "B":
                LambdaQueryWrapper<Station> lambdaQuery1 = Wrappers.lambdaQuery();
                lambdaQuery1.eq(Station::getByName, formPort);
                Station inStation = stationService.getOne(lambdaQuery1);
                if (inStation == null) {
                    throw new ServiceException(toPort + "站台异常,未找到站台");
                }
                if (inStation.getType().equals("2")) {
                    throw new ServiceException(formPort + ":出库站台不能入库");
                }
                // 站台是否需要扫托盘码判断
                zarshService.checkStationContainer(inStation, containerCode);

                String area = SAPUtils.getArea(zarsh);
                // 判断有无空闲库位分配
                AjaxResult checkAjax = zarshLocationService.checkEmptyLocationCount(zarsh, area);
                if (checkAjax.hasErr()) {
                    throw new ServiceException(checkAjax.getMsg());
                }
                //查看该托盘是否存在任务,或者在库内的变成虚拟托盘
                checkContainerInWarehouse(zarsh.getDrumId());
                // 判断站台属性
                switch (inStation.getDefineProperty()) {
                    // AGV站台类型
                    case 1:
                        if (StringUtils.isEmpty(toPort)) {
                            // 获取 AGV立库交互站台
                            createReceiptAGVTask(zarsh, zarsiList, inStation.getCode());
                        } else {
                            createStation2Station(zarsh, zarsiList, inStation.getCode());
                        }
                        break;
                    // 立库AGV交互站台类型
                    case 2:
                    // 立库站台类型
                    case 0:
                        AjaxResult ajaxResult = workTaskService.createEmptyIn(containerCode, null, area, inStation.getCode(), uniqueId, null);
                        if (ajaxResult.hasErr()) {
                            throw new ServiceException(ajaxResult.getMsg());
                        }
                        break;
                    // 二期与维修房AGV站台类型
                    case 3:
                        String fromPoint = null;
                        String toPoint = null;
                        Station station = stationService.getStationBySAPCode(zarsh.getFromPos());
                        if (station != null) {
                            fromPoint = station.getCode();
                        }
                        if (StringUtils.isNotEmpty(zarsh.getToPos())) {
                            Station toStation = stationService.getStationBySAPCode(zarsh.getToPos());
                            toPoint = toStation.getCode();
                        }
                        createCSStation2Station(zarsh, zarsiList, fromPoint, toPoint);
                        break;
                    // 配料仓
                    case 4:
                        // 配料仓站台到入库到中间仓
                        // 判断仓库不是本仓库,就要生成过站;是本仓库直接生成空托入库任务
                        //叠卜房空托自动入库中间仓,查询中间仓空库位,到了预警值则入库配料仓
                        if ((formPort.equals("2E07") || formPort.equals("2E09")) && zoneCode.equals("E")) {
                            // 提前判断P4004存在多少空托盘入库任务避免通道堵塞,如果超过3个,则不再换站
                            LambdaQueryWrapper<TaskHeader> query = Wrappers.lambdaQuery();
                            query.eq(TaskHeader::getTaskType, QuantityConstant.TASK_TYPE_EMPTYRECEIPT)
                                    .eq(TaskHeader::getZoneCode, "D")
                                    .eq(TaskHeader::getPort, "P4004")
                                    .lt(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_COMPLETED);
                            int count = taskHeaderService.count(query);
                            if (count >= 4){
                                AjaxResult ajaxResult1 = workTaskService.createEmptyIn(containerCode, null, area, inStation.getCode(), uniqueId, zarsh.getToPos());
                                if (ajaxResult1.hasErr()) {
                                    throw new ServiceException(ajaxResult1.getMsg());
                                }
                                return;
                            }

                            String emptyD = configService.getKey("empty_d");
                            Integer emptyD_real = locationService.getLocaitonNumByArea("D");
                            if (emptyD_real.intValue() > Integer.parseInt(emptyD)) {
                                zarshAddService.createMoveTask(containerCode, inStation.getZoneCode(), zarsh.getFromPos(), "3E20", uniqueId);
                                zarsh.setCustomerCode(zarsh.getLgnum());
                                zarsh.setLgnum("PPC");
                                zarshService.updateById(zarsh);
                            } else {
                                AjaxResult ajaxResult1 = workTaskService.createEmptyIn(containerCode, null, area, inStation.getCode(), uniqueId, zarsh.getToPos());
                                if (ajaxResult1.hasErr()) {
                                    throw new ServiceException(ajaxResult1.getMsg());
                                }
                            }
                            break;
                        }
                        if (zoneCode.equals("D") && inStation.getZoneCode().equals("E")) {
                            zarshAddService.createMoveTask(containerCode, inStation.getZoneCode(), zarsh.getFromPos(), "3E20", uniqueId);
                        } else {
                            // 不能跨区域
//                        String fromArea = inStation.getAreaByWcs();
                            AjaxResult ajaxResult1 = workTaskService.createEmptyIn(containerCode, null, area, inStation.getCode(), uniqueId, zarsh.getToPos());
                            if (ajaxResult1.hasErr()) {
                                throw new ServiceException(ajaxResult1.getMsg());
                            }
                        }
                        break;
                    default:
                }
                break;
            // 出库
            case "1":
            case "3":
                LambdaQueryWrapper<Station> lambdaQuery2 = Wrappers.lambdaQuery();
                lambdaQuery2.eq(Station::getByName, toPort);
                //终点站
                Station finalStation = stationService.getOne(lambdaQuery2);
                //枢纽站
                Station hubStation = finalStation;
                if (hubStation == null) {
                    throw new ServiceException(toPort + "站台异常,未找到站台");
                }
                Integer defineProperty = hubStation.getDefineProperty();

                boolean P7flag = toPort.contains("P7");
                if(P7flag &&  containerType.intValue() == 1){
                    throw new ServiceException(toPort+":站台不能呼叫片类型托盘");
                }

                // 判断库区
                Location location1 = locationService.getLocationByCode(locationCode, QuantityConstant.WAREHOUSECODE);
                if (location1 != null) {
                    zoneCode = location1.getZoneCode();
                }
                if (StringUtils.isEmpty(zoneCode)) {
                    zoneCode = SAPUtils.getZoneCode(zarsh);
                }
                // 获取库区
                if (zoneCode.contains("X")) {
                    createShipmentAGVTask(zarsh, zarsiList, hubStation.getCode());
                } else {
                    // 区域移库 映射站台 SAP任务下发的是移入库区的站台 通过移入站台获取到 出库的站台
                    if (1 == defineProperty || 3 == defineProperty) {
                        //获取枢纽站Code
                        String port = getLKAGVPort(zoneCode, hubStation.getLayer(), null, QuantityConstant.SHIPMENT_STATION_TYPE, hubStation.getOutSlicePalletArea(),
                                hubStation.getOutRollPalletArea(), hubStation.getRangeStation());
                        if (StringUtils.isEmpty(port)) {
                            throw new ServiceException("立库AGV交互站台未配置请先配置立库AGV交互站台");
                        }
                        hubStation = stationService.getStaionByCode(port);
                    }
                    String shipmentStationCode = hubStation.getCode();
                    String areaByWcs = hubStation.getAreaByWcs();
                    Station station2 = stationService.getOne(new LambdaQueryWrapper<Station>().eq(Station::getCode, shipmentStationCode));
                    if (station2 == null) {
                        throw new ServiceException(shipmentStationCode + "站台异常,未找到站台");
                    }
                    List<String> roadWays = station2.getRoadways();
                    if (!SAPUtils.getZoneCode(zarsh).equals(hubStation.getZoneCode())) {
                        throw new ServiceException(toPort + ":出库站台与仓库号不匹配 " + zarsh.getLgnum());
                    }
                    // 根据 SAP containerType 来获取托盘类型
                    String palletCode = null;
                    if (StringUtils.isNotEmpty(locationCode)) {
                        Location location = locationService.getLocationByCode(locationCode, QuantityConstant.WAREHOUSECODE);
                        if (location != null) {
                            palletCode = location.getContainerCode();
                        }
                    } else {
                        palletCode = containerService.getEmptyContainerList(zoneCode, roadWays, areaByWcs, containerType);
                    }
                    if (StringUtils.isEmpty(palletCode)) {
                        throw new ServiceException(containerType + "容器类型未匹配成功");
                    }
                    Container container = containerService.getContainerByCode(palletCode, QuantityConstant.WAREHOUSECODE);
                    if (container == null) {
                        throw new ServiceException(palletCode + "容器异常,未找到容器");
                    }
                    AjaxResult emptyOut = workTaskService.createEmptyOut(container.getCode(), container.getLocationCode(), shipmentStationCode,
                            QuantityConstant.WAREHOUSECODE, uniqueId, finalStation.getCode(),null);
                    if (emptyOut.hasErr()) {
                        throw new ServiceException(emptyOut.getMsg());
                    }
                }

                break;
            case "M":
                Station station = stationService.getStationBySAPCode(formPort);
                if (StringUtils.isNull(station)) {
                    throw new ServiceException("SAP站台编码不存在" + formPort);
                }
                Station toPosStation = stationService.getStationBySAPCode(toPort);
                if (StringUtils.isNull(toPosStation)) {
                    throw new ServiceException("SAP站台编码不存在" + formPort);
                }
                switch (station.getDefineProperty().intValue()) {
                    case 0:
                        // 配料仓站台到站台任务
//                        zarshAddService.createMoveTask(containerCode, zoneCode, formPort, toPort, uniqueId);
                        break;
                    case 1:
                        createStation2Station(zarsh, zarsiList, station.getCode());
                        break;
                    case 3:
                        createCSStation2Station(zarsh, zarsiList, station.getCode(), toPosStation.getCode());
                        break;
                    case 4:
                        // 配料仓站台到站台任务
                        zarshAddService.createMoveTask(containerCode, zoneCode, formPort, toPort, uniqueId);
                        break;
                    default:
                }
                break;
            default:
                throw new ServiceException("MFlag不支持的业务类型");
        }
    }

    /**
     * SAP有货指令
     *
     * @param domain
     */
    public void createHavingTask(SAPTaskDomain domain) {
        Zarsh zarsh = domain.getZarsh();
        String crnIn = zarsh.getCrnIn();
        String formPort = zarsh.getFromPos();
        String toPort = zarsh.getToPos();
        String type = zarsh.getMFlag();
        String zoneCode = null;
        String containerCode = zarsh.getDrumId();
        String locationCode = zarsh.getLocation();
        Integer containerType = zarsh.getPlType();
        String uniqueId = zarsh.getUniqueId();
        List<Zarsi> zarsiList = domain.getZarsiList();

        // 校验或添加物料
        checkMaterialCode(zarsiList);

        // 校验判断 有料方法 一定需要托盘号

        switch (type) {
            // 入库
            case "2":
            case "B":
                Station station = stationService.getStationBySAPCode(formPort);
                if (station == null) {
                    throw new ServiceException("站台未找到!" + formPort);
                }
                if (station.getType().equals("2")) {
                    throw new ServiceException(formPort + ":出库站台不能入库");
                }
                // 校验是否为入库站台
                checkReceiptPort(station);
                zarshService.checkStationContainer(station, containerCode);

                if (StringUtils.isNotNull(zarsiList)) {
                    switch (SAPUtils.getZoneCode(zarsh)) {
                        case "A":
                            if (zarsiList.size() > 1) {
                                throw new ServiceException("玻璃仓入库明细数量限制为1条!");
                            }
                            break;
                        case "C":
                            if (zarsiList.size() > 2) {
                                throw new ServiceException("铜箔仓入库明细数量限制为2条!");
                            }
                            break;
                        default:
                    }
                }
                // 标志是否有 容器编码
                int containerFlag = 0;
                Container container = null;
                if (StringUtils.isNotEmpty(containerCode)) {
                    container = containerService.getContainerByCode(containerCode, QuantityConstant.WAREHOUSECODE);
                    if (container != null) {
                        containerFlag = 1;

                        TaskHeader task = taskHeaderService.checkTaskByContainerCode(containerCode);
                        if (task != null) {
                            if (task.getInternalTaskType().intValue() == 100) {
                                throw new ServiceException("有货入库,该容器已存在未完成的入库任务,请不要重复下发" + containerCode);
                            } else if (task.getInternalTaskType().intValue() == 200) {
                                throw new ServiceException(
                                        "有货入库,该容器已存在未完成的出库任务,出库任务未完成,请到WCS中未完成任务查看是否有改任务,任务状态是否是响应接出站台请求,如果是直接手动强制完成该任务即可恢复正常,同时告知电气或WCS;" + containerCode);
                            } else {
                                throw new ServiceException("有货入库,该容器已存在未完成的任务" + containerCode);
                            }

                        }
                        AgvTask agvTask = taskHeaderService.checkAgvTaskByContainerCode(containerCode);
                        if (agvTask != null) {
                            throw new ServiceException("有货入库,该容器已存在未完成的agv任务,请不要重复下发" + containerCode);
                        }
                        // 不是出库入库或agv任务
                        if (QuantityConstant.STATUS_LOCATION_LOCK.equals(container.getStatus())) {
                            // 没有任务直接解锁
                            containerService.updateLocationCodeAndStatus(containerCode, "", QuantityConstant.STATUS_LOCATION_EMPTY, QuantityConstant.WAREHOUSECODE);
                        }
                        if (StringUtils.isNotEmpty(container.getLocationCode())) {
                            AjaxResult ajaxResult = inventoryHeaderService.removeInventoryByContainer(containerCode);
                            if (ajaxResult.hasErr()) {
                                throw new ServiceException(ajaxResult.getMsg());
                            }
                        }
                        List<InventoryDetail> inventoryDetails =
                                inventoryDetailService.list(new LambdaQueryWrapper<InventoryDetail>().eq(InventoryDetail::getContainerCode, container.getCode()));
                        if (!inventoryDetails.isEmpty()) {
                            AjaxResult ajaxResult = inventoryHeaderService.removeInventoryByContainer(containerCode);
                            if (ajaxResult.hasErr()) {
                                throw new ServiceException(ajaxResult.getMsg());
                            }
                        }
                    }
                }
                // 入库站台编码
                String formPortCode = station.getCode();
                // 入库站台属性
                Integer defineProperty = station.getDefineProperty();
                String area = SAPUtils.getArea(zarsh);
                // 判断有无空闲库位分配
                AjaxResult checkAjax = zarshLocationService.checkEmptyLocationCount(zarsh, area);
                if (checkAjax.hasErr()) {
                    throw new ServiceException(checkAjax.getMsg());
                }
                switch (containerFlag) {
                    // 无托盘
                    case 0:
                        // agv站台
                        if (defineProperty == 1) {
                            // 创建agv任务
                            AgvTask agvTask = createReceiptAGVTask(zarsh, zarsiList, formPortCode);
                        }
                        // 生成入库单 用于AGV调用组盘接口
                        receiptHeaderService.saveReceiptHeaderBySap(uniqueId, zarsh, zarsiList);
                        break;
                    // 有托盘
                    case 1:
                        //清除入库组盘
                        LambdaQueryWrapper<ReceiptContainerHeader> lambdaQuery = Wrappers.lambdaQuery();
                        lambdaQuery.eq(ReceiptContainerHeader::getContainerCode,containerCode)
                                .eq(ReceiptContainerHeader::getStatus,0);
                        List<ReceiptContainerHeader> list = receiptContainerHeaderService.list(lambdaQuery);
                        if(!list.isEmpty()){
                            receiptContainerHeaderService.cancelByIds(list.stream().map(ReceiptContainerHeader::getId).collect(toList()));
                        }
                        // 判断 from_pos 来源
                        domain.setFormPort(formPortCode);
                        // 立库agv交互点入库
                        // 指定去那边
                        if ((defineProperty == 2) || defineProperty == 0) {
                            createSAPReceiptTask(uniqueId, zarsh, zarsiList);
                        }
                        // agv站台入库
                        if (defineProperty == 1) {
                            createReceiptAGVTask(zarsh, zarsiList, formPortCode);
                        }
                        if(defineProperty == 3){
                            if(StringUtils.isEmpty(zarsh.getToPos())){
                                toPort = QuantityConstant.H1001;
                            }
                            createCSStation2Station(zarsh, zarsiList, formPortCode, toPort);
                        }
                        if (defineProperty == 4) {
                            zoneCode = SAPUtils.getZoneCode(zarsh);
                            // 配料仓站台到入库到中间仓,或者入库到
                            // 判断仓库不是本仓库,就要生成过站;是本仓库直接生成空托入库任务
                            if (zoneCode.equals("D")) {
                                zarshAddService.createMoveTask(containerCode, zoneCode, zarsh.getFromPos(), "3E20", uniqueId);
                            } else {
                                // 不能跨区域,入库到本仓库
                                // String fromArea = inStation.getAreaByWcs();
                                createSAPReceiptTask(uniqueId, zarsh, zarsiList);
                            }
                        }
                        break;
                    default:
                        throw new IllegalStateException("Unexpected value: " + containerFlag);
                }
                break;
            case "M":
                Station formPortStation = stationService.getStationBySAPCode(formPort);
                if (StringUtils.isNull(formPortStation)) {
                    throw new ServiceException("SAP站台编码不存在" + formPort);
                }
                Station toPosStation = stationService.getStationBySAPCode(toPort);
                if (StringUtils.isNull(toPosStation)) {
                    throw new ServiceException("SAP站台编码不存在" + formPort);
                }
                switch (formPortStation.getDefineProperty().intValue()) {
                    case 0:
                        // 配料仓站台到站台任务
//                        zarshAddService.createMoveTask(containerCode, SAPUtils.getZoneCode(zarsh), formPort, toPort, uniqueId);
                        break;
                    case 1:
                        createStation2Station(zarsh, zarsiList, formPortStation.getCode());
                        break;
                    case 3:
                        createCSStation2Station(zarsh, zarsiList, formPortStation.getCode(), toPosStation.getCode());
                        break;
                    case 4:
                        // 配料仓站台到站台任务
                        zarshAddService.createMoveTask(containerCode, SAPUtils.getZoneCode(zarsh), formPort, toPort, uniqueId);
                        break;
                    default:
                }
                break;
            // 出库
            case "1":
            case "3":
                // 校验P7出库站台 不能入库片托盘
                boolean P7flag = toPort.contains("P7");
                if(P7flag &&  containerType.intValue() == 1){
                    throw new ServiceException(toPort+":站台不能呼叫片类型托盘");
                }
                Station stationLocation = stationService.getStaionByCode(locationCode);
                if (stationLocation != null) {
                    Station toStation = stationService.getStationBySAPCode(toPort);
                    if (toStation == null) {
                        throw new ServiceException("站台未找到!" + formPort);
                    }
                    defineProperty = stationLocation.getDefineProperty();
                    switch (defineProperty) {
                        case 1:
                            createStation2Station(zarsh, zarsiList, stationLocation.getCode());
                            break;
                        case 3:
                            createCSStation2Station(zarsh, zarsiList, stationLocation.getCode(), toStation.getCode());
                            break;
                        default:
                    }
                    break;
                }
                // 判断库区
                Location location = locationService.getLocationByCode(locationCode, QuantityConstant.WAREHOUSECODE);
                if (location == null) {
                    Station station1 = stationService.getStaionByCode(locationCode);
                    if (station1 == null) {
                        throw new ServiceException("SAP数据异常 locationCode 值不存在");
                    }
                    zoneCode = station1.getZoneCode();
                } else {
                    zoneCode = location.getZoneCode();
                }
                if(!location.getStatus().equals(QuantityConstant.STATUS_LOCATION_EMPTY)){
                    throw new ServiceException("库位被锁定无法出库");
                }
                zoneCode = location.getZoneCode();
                Station toStation = stationService.getStationBySAPCode(toPort);
                if (toStation == null) {
                    throw new ServiceException("站台未找到!" + toPort);
                }

                // 出库站台编码
                String toPortCode1 = toStation.getCode();
                Integer defineProperty1 = toStation.getDefineProperty();
                if (StringUtils.isEmpty(locationCode)) {
                    throw new ServiceException("SAP数据异常 locationCode 值为空");
                }
                // 边线库区
                if (zoneCode.contains("X")) {
                    // 先生成AGV任务
                    switch (defineProperty1) {
                        case 1:
                            createShipmentAGVTask(zarsh, zarsiList, toPortCode1);
                            break;
                        case 2:
                            createShipmentAGVTask(zarsh, zarsiList, toPortCode1);
                            // 临时托盘生成 入库单
                            if (!location.getContainerCode().contains("TP")) {
                                receiptHeaderService.saveReceiptHeaderBySap(uniqueId, zarsh, zarsiList);
                            }
                            break;
                        case 3:
                            String fromPoint = null;
                            String toPoint = null;
                            Station locationStation = stationService.getStationBySAPCode(locationCode);
                            fromPoint = locationStation.getCode();
                            toPoint = toStation.getCode();
                            createCSStation2Station(zarsh, zarsiList, fromPoint, toPoint);
                            break;
                        default:
                            throw new ServiceException("SAP数据异常");
                    }
                } else {
                    // 校验是否为出库站台
                    checkShipmentPort(toStation);
                    // 生成立库任务
                    switch (defineProperty1) {
                        case 1:
                            // 获取立库AGV交互站台
                            String port = getLKAGVPort(zoneCode, toStation.getLayer(), location.getRoadway(), QuantityConstant.SHIPMENT_STATION_TYPE, 0, 0,
                                    toStation.getRangeStation());
                            createSAPShipmentTask(zarsh, zarsiList, port);
                            break;
                        case 3:
                            if(toStation.getZoneCode().equals("BX")){
                                toPortCode1 = "P2058";
                            }
                            createSAPShipmentTask(zarsh, zarsiList, toPortCode1);
                            break;
                        case 4:
                            // 有货,从中间仓出库到配料台,先生成出库任务,再生成过站任务
                            if (zoneCode.equals("D")) {
                                //验证配料台是否跨区域
                                if (toStation.getArea() == 5 && toStation.getAreaByWcs().equals("C")) {
                                    throw new ServiceException("暂不支持中间仓到配料仓C区域的跨区域任务:中间仓到配料台任务");
                                }
                                String port1 = "P4005";
                                createSAPShipmentTask(zarsh, zarsiList, port1);
                            } else {
                                createSAPShipmentTask(zarsh, zarsiList, toPortCode1);
                            }
                            break;
                        default:
                            createSAPShipmentTask(zarsh, zarsiList, toPortCode1);
                    }
                }
            default:
        }
    }

    private void checkMaterialCode(List<Zarsi> zarsiList) {
        Set<String> materialCodes = zarsiList.stream().map(Zarsi::getMatnr).collect(Collectors.toSet());
        for (String materialCode : materialCodes) {
            Material material = materialService.getMaterialByCode(materialCode, QuantityConstant.WAREHOUSECODE);
            if (StringUtils.isNull(material)) {
                material = new Material();
                material.setCode(materialCode);
                material.setName(materialCode);
                basicDataApiService.material(material);
            }
        }

    }

    /**
     * 根据sap创建入库任务
     */
    @ProcessTrack(taskName = "创建入库任务", processCode = ProcessCode.RECEIPT_TASK_CODE)
    public synchronized TaskHeader createSAPReceiptTask(String uniqueId, Zarsh zarsh, List<Zarsi> zarsiList) {
        String warehouseCode = QuantityConstant.WAREHOUSECODE;
        Integer priority = 10;
        String containerCode = zarsh.getDrumId();
        String port = zarsh.getFromPos();
        Station station = stationService.getStationBySAPCode(port);
        if (station != null) {
            port = station.getCode();
            priority = station.getPriority();
        }
        String zoneCode = SAPUtils.getZoneCode(zarsh);

        if (!zoneCode.equals(station.getZoneCode())) {
            throw new ServiceException("入库任务 站台:" + port + " 不在" + zarsh.getLgnum() + "仓库范围内");
        }
        Container container = containerService.getContainerByCode(containerCode, warehouseCode);
        if (StringUtils.isNull(container)) {
            throw new ServiceException("托盘不存在!");
        }
        if (container.getStatus().equals(QuantityConstant.STATUS_CONTAINER_LOCK)) {
            throw new ServiceException("托盘已经锁定!");
        }

        containerService.updateStatus(container.getCode(), QuantityConstant.STATUS_LOCATION_LOCK, warehouseCode);

        // 创建任务头
        TaskHeader task = new TaskHeader();
        task.setTaskType(QuantityConstant.TASK_TYPE_WHOLERECEIPT);
        task.setUniqueIds(uniqueId);
        task.setZoneCode(zoneCode);
        task.setInternalTaskType(QuantityConstant.TASK_INTENERTYPE_RECEIPT);
        task.setAllocationHeadId(0);
        task.setWarehouseCode(warehouseCode);
        task.setAssignedUser(ShiroUtils.getLoginName() == null ? QuantityConstant.PLATFORM_WCS : ShiroUtils.getLoginName());
        task.setConfirmedBy(ShiroUtils.getLoginName() == null ? QuantityConstant.PLATFORM_WCS : ShiroUtils.getLoginName());
        task.setPort(port);
        task.setStatus(QuantityConstant.TASK_STATUS_BUILD);
        task.setContainerCode(container.getCode());
        task.setCompanyCode(QuantityConstant.COMPANYCODE);
        task.setCreatedBy(QuantityConstant.PLATFORM_SAP);
        task.setCreated(DateUtils.getNowDate());
        task.setPriority(priority);
        if (StringUtils.isNotEmpty(zarsh.getHFlag())) {
            task.setHFlag(Integer.parseInt(zarsh.getHFlag()));
        }
        if (StringUtils.isNotEmpty(zarsh.getRlFlag())) {
            task.setRlFlag(Integer.parseInt(zarsh.getRlFlag()));
        }
        task.setCrnIn(zarsh.getCrnIn());
        if (!taskHeaderService.save(task)) {
            throw new ServiceException("生成任务失败");
        }
        List<TaskDetail> taskDetailList = new ArrayList<>();
        for (Zarsi zarsi : zarsiList) {
            String materialCode = zarsi.getMatnr();
            Material material = materialService.getMaterialByCode(materialCode, warehouseCode);
            if (material == null) {
                material = new Material();
                material.setCode(materialCode);
                material.setName(materialCode);
                basicDataApiService.material(material);
            }
            TaskDetail taskDetail = new TaskDetail();
            taskDetail.setTaskId(task.getId());
            taskDetail.setTaskType(task.getTaskType());
            taskDetail.setInternalTaskType(QuantityConstant.TASK_INTENERTYPE_RECEIPT);
            taskDetail.setWarehouseCode(task.getWarehouseCode());
            taskDetail.setAllocationId(0);
            taskDetail.setCompanyCode(task.getCompanyCode());
            taskDetail.setMaterialCode(material.getCode());
            taskDetail.setMaterialName(material.getName());
            taskDetail.setMaterialSpec(material.getSpec());
            taskDetail.setMaterialUnit(material.getUnit());
            taskDetail.setInventorySts(QuantityConstant.GOOD);
            taskDetail.setBillCode(QuantityConstant.EMPTY_STRING);
            taskDetail.setContainerDetailNumber(zarsi.getPosnr());
            taskDetail.setBillDetailId(0);
            taskDetail.setLot(zarsi.getWjffh());
            taskDetail.setManufactureDate(zarsi.getPdate());
            // 查找上游号
            taskDetail.setReferenceCode(uniqueId);
            taskDetail.setQty(zarsi.getVerme());
            taskDetail.setContainerCode(task.getContainerCode());
            taskDetail.setFromLocation(task.getFromLocation());
            taskDetail.setRollNumber(zarsi.getCharg());
            taskDetail.setCreatedBy(QuantityConstant.PLATFORM_SAP);
            taskDetail.setCreated(DateUtils.getNowDate());
            taskDetailList.add(taskDetail);
        }
        taskDetailService.saveBatch(taskDetailList);
        return task;
    }

    /**
     * 根据sap创建出库任务
     */
    public void createSAPShipmentTask(Zarsh zarsh, List<Zarsi> zarsiList, String allocationStationCode) {
        String warehouseCode = QuantityConstant.WAREHOUSECODE;
        String locationCode = zarsh.getLocation();
        String uniqueId = zarsh.getUniqueId();
        Station toPortStation = stationService.getStationBySAPCode(zarsh.getToPos());
        Integer priority = 10;
        Location location = locationService.getLocationByCode(locationCode, warehouseCode);
        if (StringUtils.isNull(location)) {
            throw new ServiceException("库位禁用或不存在!");
        }
        Station station = stationService.getStaionByCode(allocationStationCode);
        String zoneCode = SAPUtils.getZoneCode(zarsh);
        if (!zoneCode.equals(station.getZoneCode())) {
            throw new ServiceException("出库任务 站台:" + allocationStationCode + " 不在" + zarsh.getLgnum() + "仓库范围内");
        }
        if (station != null) {
            priority = station.getPriority();
        }
        if (StringUtils.isEmpty(location.getContainerCode())) {
            throw new ServiceException("库位容器不存在 请联系现场人员是否通过WMS出库!");
        }
        Container container = containerService.getContainerByCode(location.getContainerCode(), warehouseCode);
        if (StringUtils.isNull(container)) {
            throw new ServiceException("托盘不存在!");
        }
        if (container.getStatus().equals(QuantityConstant.STATUS_CONTAINER_LOCK)) {
            TaskHeader task = taskHeaderService.checkTaskByContainerCode(location.getContainerCode());
            if (task != null) {
                if (task.getInternalTaskType().intValue() == 100) {
                    throw new ServiceException("该容器已存在未完成的入库任务:" + location.getContainerCode());
                } else if (task.getInternalTaskType().intValue() == 200) {
                    throw new ServiceException("该容器已存在未完成的出库任务,请不要重复下发;" + location.getContainerCode());
                } else {
                    throw new ServiceException("该容器已存在未完成的任务" + location.getContainerCode());
                }

            }
            AgvTask agvTask = taskHeaderService.checkAgvTaskByContainerCode(location.getContainerCode());
            if (agvTask != null) {
                throw new ServiceException("该容器已存在未完成的agv任务" + location.getContainerCode());
            }
            throw new ServiceException("托盘已经锁定!");
        }

        containerService.updateStatus(container.getCode(), QuantityConstant.STATUS_LOCATION_LOCK, warehouseCode);
        locationService.updateStatus(location.getCode(), QuantityConstant.STATUS_LOCATION_LOCK, warehouseCode);

        List<InventoryDetail> inventoryDetails =
                inventoryDetailService.list(new LambdaQueryWrapper<InventoryDetail>().eq(InventoryDetail::getLocationCode, locationCode));

        TaskHeader task = new TaskHeader();
        task.setAllocationHeadId(0);
        task.setInternalTaskType(QuantityConstant.TASK_INTENERTYPE_SHIPMENT);
        task.setWarehouseCode(warehouseCode);
        task.setZoneCode(location.getZoneCode());
        task.setCompanyCode(QuantityConstant.COMPANYCODE);
        task.setStatus(QuantityConstant.TASK_STATUS_BUILD);
        task.setTaskType(QuantityConstant.TASK_TYPE_WHOLESHIPMENT);
        task.setFromLocation(locationCode);
        task.setCrnIn(zarsh.getCrnIn());
        task.setContainerCode(container.getCode());
        task.setPort(allocationStationCode);
        task.setToPort(toPortStation.getCode());
        task.setSendTo(0);
        task.setUniqueIds(uniqueId);
        task.setCreatedBy(QuantityConstant.PLATFORM_SAP);
        task.setPriority(priority);
        // 剪切线检验库位和站台的限制
        locationService.checkPreLocationByCode(locationCode, allocationStationCode, task.getZoneCode());
        taskHeaderService.save(task);

        List<Zarsi> zarsis = zarsiList.stream().filter(e -> "X".equals(e.getUseFlag())).collect(toList());
        List<String> lots = zarsis.stream().map(Zarsi::getCharg).collect(toList());
        Map<String, Zarsi> maps = new HashMap<>();
        for (Zarsi zarsi : zarsiList) {
            String charg = zarsi.getCharg();
            maps.put(charg, zarsi);
        }
        List<TaskDetail> taskDetailList = new ArrayList<>();
        for (InventoryDetail inventoryDetail : inventoryDetails) {
            TaskDetail taskDetail = new TaskDetail();

            taskDetail.setTaskId(task.getId());
            taskDetail.setInternalTaskType(task.getInternalTaskType());
            taskDetail.setWarehouseCode(task.getWarehouseCode());
            taskDetail.setCompanyCode(task.getCompanyCode());
            taskDetail.setTaskType(task.getTaskType());
            taskDetail.setToInventoryId(inventoryDetail.getId());
            taskDetail.setFromInventoryId(inventoryDetail.getId());
            taskDetail.setAllocationId(0);
            taskDetail.setBillCode(QuantityConstant.EMPTY_STRING);
            taskDetail.setMaterialCode(inventoryDetail.getMaterialCode());
            taskDetail.setMaterialName(inventoryDetail.getMaterialName());
            taskDetail.setMaterialSpec(inventoryDetail.getMaterialSpec());
            taskDetail.setMaterialUnit(inventoryDetail.getMaterialUnit());
            taskDetail.setLevel(inventoryDetail.getLevel());
            taskDetail.setQty(inventoryDetail.getQty());
            taskDetail.setContainerCode(task.getContainerCode());
            taskDetail.setFromLocation(task.getFromLocation());
            taskDetail.setLot(inventoryDetail.getLot());
            taskDetail.setBatch(inventoryDetail.getBatch());
            taskDetail.setProjectNo(inventoryDetail.getProjectNo());
            taskDetail.setStatus(QuantityConstant.TASK_STATUS_BUILD);
            taskDetail.setWaveId(0);
            taskDetail.setInventorySts(inventoryDetail.getInventorySts());
            taskDetail.setReferenceCode(inventoryDetail.getReferCode());
            taskDetail.setRollNumber(inventoryDetail.getRollNumber());
            taskDetail.setContainerDetailNumber(inventoryDetail.getContainerDetailNumber());
            taskDetailList.add(taskDetail);
            inventoryDetail.setTaskQty(inventoryDetail.getQty());
            if ("P2076".equals(allocationStationCode)) {
                taskDetailList.remove(taskDetail);
            }
            //
            Zarsi zarsi = maps.get(inventoryDetail.getRollNumber());
            if (StringUtils.isNotNull(zarsi)) {
                zarsi.setPosnr(inventoryDetail.getContainerDetailNumber());
                zarsiService.updateById(zarsi);
            }
        }
        if (inventoryDetails == null || inventoryDetails.size() == 0) {
            throw new ServiceException(locationCode + "库位没库存!");
        }
        inventoryDetailService.updateBatchById(inventoryDetails);
        if(!"P2076".equals(station.getCode())){
            taskDetailService.saveBatch(taskDetailList);
        }

    }

    public AgvTask createReceiptAGVTask(Zarsh zarsh, List<Zarsi> zarsiList, String allocationStationCode) {
        Station station = stationService.getStaionByCode(allocationStationCode);
        if (station == null) {
            throw new ServiceException(allocationStationCode + "站台异常,未找到站台");
        }
        int layer = station.getLayer();
        // 来源点位
        String fromPoint = station.getCode();
        String taskTypes = QuantityConstant.RECEIPT_AGV;
        // 来源点位
        String toPoint = "";
        // 小车优先级别
        Integer priority = station.getPriority();
        String toPos = zarsh.getToPos();
        // 去向位置 如果找不到去向位置 就在后面分配库位 或者 分配立库交互站台 根据 库区类型来
        if (StringUtils.isNotEmpty(toPos)) {
            Station toPointStation = stationService.getStationBySAPCode(toPos);
            toPoint = toPointStation.getCode();
        }
        boolean flag = true;
        switch (fromPoint){
            case "P31202":
            case "P31182":
            case "P31152":
                if(zarsh.getInKind().intValue() == 0 && zarsh.getLgnum().equals("XBK")){
                    flag = false;
                }
                break;
            default:
        }

        String zoneCode = station.getZoneCode();
        String containerCode = zarsh.getDrumId();
        Integer pointType = -1;
        Container container = containerService.getContainerByCode(containerCode, QuantityConstant.WAREHOUSECODE);
        // 没有托盘创建虚拟托盘
        if (container == null) {
            containerCode = containerService.createContainerByZone("LS");
            container = containerService.getContainerByCode(containerCode, QuantityConstant.WAREHOUSECODE);
        }

        TaskHeader task = taskHeaderService.checkTaskByContainerCode(containerCode);
        if (task != null) {
            if (task.getInternalTaskType().intValue() == 100) {
                throw new ServiceException("入库,该容器已存在未完成的立库入库任务,请不要重复下发" + containerCode);
            } else if (task.getInternalTaskType().intValue() == 200) {
                throw new ServiceException("入库,该容器已存在未完成的立库出库任务,出库任务未完成,请到WCS中未完成任务查看是否有改任务,任务状态是否是响应接出站台请求,如果是直接手动强制完成该任务即可恢复正常,同时告知电气或WCS;" + containerCode);
            } else {
                throw new ServiceException("入库,该容器已存在未完成的任务" + containerCode);
            }
        }
        AgvTask agvTask1 = taskHeaderService.checkAgvTaskByContainerCode(containerCode);
        if (agvTask1 != null) {
            throw new ServiceException("入库,该容器已存在未完成的agv任务,请不要重复下发" + containerCode);
        }
        // 不是出库入库
        if (QuantityConstant.STATUS_LOCATION_LOCK.equals(container.getStatus())) {
            // 没有任务直接解锁
            containerService.updateLocationCodeAndStatus(containerCode, "", QuantityConstant.STATUS_LOCATION_EMPTY, QuantityConstant.WAREHOUSECODE);
//                            throw new ServiceException("容器状态为锁定" + containerCode);
        }
        if (StringUtils.isNotNull(container.getPlType())) {
            if (container.getPlType() == 0) {
                pointType = 1;
            }
            if (container.getPlType() == 1 || container.getPlType() == 2 || container.getPlType() == 5) {
                pointType = 2;
            }
        }
        if (StringUtils.isNotEmpty(container.getLocationCode())) {
//            throw new ServiceException("容器在库位" + container.getLocationCode() + "上!");
            AjaxResult ajaxResult = inventoryHeaderService.removeInventoryByContainer(containerCode);
            if (ajaxResult.hasErr()) {
                throw new ServiceException(ajaxResult.getMsg());
            }
        }
        int unCompleteTask = agvTaskService.getUnCompleteTask(containerCode);
        if (unCompleteTask > 0) {
            throw new ServiceException(containerCode + "容器存在未完成的AGV任务!");
        }

        AgvTask agvTask = new AgvTask();
        agvTask.setLayer(layer);
        agvTask.setIsEmpty(zarsh.getInKind());
        agvTask.setFromPoint(fromPoint);
        agvTask.setToPoint(toPoint);
        agvTask.setTaskLevel(priority);
        agvTask.setZoneCode(zoneCode);
        // AGV任务类型都为配送
        agvTask.setTaskType(QuantityConstant.PEISONG_AGV);
        agvTask.setTaskTypes(taskTypes);
        agvTask.setPalletNo(containerCode);
        agvTask.setUniqueId(zarsh.getUniqueId());
        agvTask.setCreatedBy(QuantityConstant.PLATFORM_SAP);
        agvTask.setCreated(DateUtils.getNowDate());
        agvTask.setPointType(pointType);
        // 添加上布物料直径
        if (zarsiList != null && zarsiList.size() == 1) {
            agvTask.setLot(zarsiList.get(0).getCharg());
            MaterialDiameter materialDiameter =
                    materialDiameterService.getOne(new LambdaQueryWrapper<MaterialDiameter>().eq(MaterialDiameter::getLot, agvTask.getLot()));
            if (materialDiameter != null) {
                agvTask.setMaterialDiameter(materialDiameter.getDiameter());
            }
        }
        agvTaskService.save(agvTask);
        containerService.updateStatus(containerCode, QuantityConstant.STATUS_CONTAINER_LOCK, QuantityConstant.WAREHOUSECODE);
        if (StringUtils.isEmpty(agvTask.getToPoint()) && flag) {

            if (agvTask.getFromPoint().equals(QuantityConstant.H1001)) {
                agvTask.setToPoint(QuantityConstant.P31071);
                agvTaskService.updateById(agvTask);
                return agvTask;
            }

            Zone zone = zoneService.getZoneByCode(SAPUtils.getZoneCode(zarsh));
            if (zone != null) {
                String userDef8 = zone.getUserDef8();
                if (StringUtils.isNotEmpty(userDef8)) {
                    warecellAllocationService.agvWarecellAllocation(agvTask);
                } else {
                    // 根据库区 楼层 巷道 获取终点站台
                    String port = getLKAGVPort(SAPUtils.getZoneCode(zarsh), layer, null, QuantityConstant.RECEIPT_STATION_TYPE, station.getOutSlicePalletArea(),
                            station.getOutRollPalletArea(), station.getRangeStation());
                    agvTask.setToPoint(port);
                    agvTaskService.updateById(agvTask);
                }
            }
        }else{
            String locationCode = warecellAllocationService.verticalWarehouseAllocation(agvTask);
            if(StringUtils.isEmpty(locationCode)){
                throw new ServiceException("边线库没有空闲库位可分配");
            }
            agvTask.setToPoint("TEMP");
            agvTaskService.updateById(agvTask);
        }
        return agvTask;
    }

    /**
     * @param
     */
    public void createAgvRelay(AgvTask agvTask, String toport) {
        // 输送线-》固定点
        AgvTask agvTask2 = new AgvTask();
        agvTask2.setIsEmpty(agvTask.getIsEmpty());
        agvTask2.setTaskTypes(QuantityConstant.RECEIPT_AGV);
        agvTask2.setTaskType(agvTask.getTaskType());
        agvTask2.setUniqueId(agvTask.getUniqueId());
        agvTask2.setPalletNo(agvTask.getPalletNo());
        agvTask2.setZoneCode("DX");
        agvTask2.setPointType(agvTask.getPointType());
        agvTask2.setFromPoint(agvTask.getToPoint());
        agvTask2.setLot(agvTask.getLot());
        agvTask2.setToPoint("P001");
        agvTaskService.save(agvTask2);
        // 固定点-》立库口
        AgvTask agvTask3 = new AgvTask();
        agvTask3.setIsEmpty(agvTask.getIsEmpty());
        agvTask3.setTaskTypes(QuantityConstant.RECEIPT_AGV);
        agvTask3.setTaskType(agvTask.getTaskType());
        agvTask3.setUniqueId(agvTask.getUniqueId());
        agvTask3.setPalletNo(agvTask.getPalletNo());
        agvTask3.setZoneCode("B");
        agvTask3.setPointType(agvTask.getPointType());
        agvTask3.setFromPoint(agvTask2.getToPoint());
        agvTask3.setLot(agvTask.getLot());
        agvTask3.setToPoint(toport);
        agvTaskService.save(agvTask3);
    }

    public AgvTask createShipmentAGVTask(Zarsh zarsh, List<Zarsi> zarsiList, String allocationStationCode) {
        String zoneCode = null;
        String locationCode = zarsh.getLocation();
        Station station = stationService.getStaionByCode(allocationStationCode);
        if (station == null) {
            throw new ServiceException(allocationStationCode + "站台异常,未找到站台");
        }
        int layer = station.getLayer();
        int priority = station.getPriority();
        // 校验站台是否可以直接使用
        if (StringUtils.isEmpty(locationCode)) {
            List<String> roadways = new ArrayList<>();
            roadways.add("0");
            zoneCode = SAPUtils.getZoneCode(zarsh);
            String palletCode = containerService.getEmptyContainerList(zoneCode, roadways, null, zarsh.getPlType());
            if (StringUtils.isEmpty(palletCode)) {
                throw new ServiceException(zoneCode + " AGV缓存区没有空容器可以出");
            }
            Container container1 = containerService.getContainerByCode(palletCode, QuantityConstant.WAREHOUSECODE);
            locationCode = container1.getLocationCode();
        }
        Location location = locationService.getLocationByCode(locationCode, QuantityConstant.WAREHOUSECODE);
        if (location == null) {
            throw new ServiceException(locationCode + " 系统内未找到改库位");
        }
        Integer acsStatus = acsLocationStatusService.getAcsLocationStatusByCode(locationCode);
        if (acsStatus != null && acsStatus == 2) {
            throw new ServiceException(locationCode + " ACS系统显示该库位为空,请到线边库查看是否有货");
        }
        Container container = containerService.getContainerByCode(location.getContainerCode(), QuantityConstant.WAREHOUSECODE);
        if (container == null) {
            throw new ServiceException(locationCode + " 系统内未找到改库位");
        }
        if (zarsh.getInKind() == 0) {
            if (!container.getStatus().equals(QuantityConstant.STATUS_CONTAINER_EMPTY)) {
                throw new ServiceException(locationCode + " 容器状态不为空");
            }
        }
        int pointType = -1;
        if (StringUtils.isNotNull(container.getPlType())) {
            if (container.getPlType() == 0) {
                pointType = 3;
            }
            if (container.getPlType() == 1 || container.getPlType() == 2 || container.getPlType() == 5) {
                pointType = 0;
            }
        }
        String fromPoint = locationCode;
        String taskTypes = QuantityConstant.SHIPMENT_AGV;
        String toPoint = station.getCode();
        if (layer == 2 && location.getZoneCode().equals("A")) {
            if ("2".equals(location.getRoadway())) {
                toPoint = "P1040";
            }
            if ("1".equals(location.getRoadway())) {
                toPoint = "P1039";
            }
        }

        AgvTask agvTask = new AgvTask();
        agvTask.setLayer(layer);
        agvTask.setIsEmpty(zarsh.getInKind());
        agvTask.setFromPoint(fromPoint);
        agvTask.setToPoint(toPoint);
        agvTask.setZoneCode(location.getZoneCode());
        agvTask.setTaskLevel(priority);
        // AGV任务类型都为配送
        agvTask.setTaskType(QuantityConstant.PEISONG_AGV);
        agvTask.setTaskTypes(taskTypes);
        agvTask.setPalletNo(location.getContainerCode());
        agvTask.setUniqueId(zarsh.getUniqueId());
        agvTask.setCreatedBy(QuantityConstant.PLATFORM_SAP);
        agvTask.setCreated(DateUtils.getNowDate());
        agvTask.setPointType(pointType);
        if (zarsiList.size() == 1) {
            agvTask.setLot(zarsiList.get(0).getCharg());
            MaterialDiameter materialDiameter =
                    materialDiameterService.getOne(new LambdaQueryWrapper<MaterialDiameter>().eq(MaterialDiameter::getLot, agvTask.getLot()));
            if (materialDiameter != null) {
                agvTask.setMaterialDiameter(materialDiameter.getDiameter());
            }
        }
        agvTaskService.save(agvTask);
        List<Zarsi> zarsis = zarsiList.stream().filter(e -> "X".equals(e.getUseFlag())).collect(toList());
        if (zarsis.isEmpty()) {
            if ("B".equals(SAPUtils.getZoneCode(zarsh))) {
                throw new ServiceException("没有USE_FLAG使用标识");
            }
        }
        List<String> lots = zarsis.stream().map(Zarsi::getCharg).collect(toList());
        Map<String, Zarsi> maps = new HashMap<>();
        for (Zarsi zarsi : zarsiList) {
            String charg = zarsi.getCharg();
            maps.put(charg, zarsi);
        }
        List<InventoryDetail> inventoryDetails =
                inventoryDetailService.list(new LambdaQueryWrapper<InventoryDetail>().eq(InventoryDetail::getLocationCode, locationCode));
        for (InventoryDetail inventoryDetail : inventoryDetails) {
            if (!lots.contains(inventoryDetail.getRollNumber())) {
                continue;
            }
            Zarsi zarsi = maps.get(inventoryDetail.getRollNumber());
            if (StringUtils.isNotNull(zarsi)) {
                zarsi.setPosnr(inventoryDetail.getContainerDetailNumber());
                zarsiService.updateById(zarsi);
            }
        }

        containerService.updateStatus(container.getCode(), QuantityConstant.STATUS_CONTAINER_LOCK, QuantityConstant.WAREHOUSECODE);
        locationService.updateStatus(locationCode, QuantityConstant.STATUS_CONTAINER_LOCK, QuantityConstant.WAREHOUSECODE);
        return agvTask;
    }

    public AgvTask createStation2Station(Zarsh zarsh, List<Zarsi> zarsiList, String allocationStationCode) {
        Station station = stationService.getStaionByCode(allocationStationCode);
        if (station == null) {
            throw new ServiceException(allocationStationCode + "站台异常,未找到站台");
        }
        int layer = station.getLayer();
        int pointType = -1;
        if (StringUtils.isNotNull(zarsh.getInKind())) {
            if (zarsh.getInKind() == 0) {
                pointType = 3;
            }
            if (zarsh.getInKind() == 1) {
                pointType = 0;
            }
        }
        Station station1 = stationService.getStationBySAPCode(zarsh.getToPos());
        if (station1 == null) {
            throw new ServiceException("终点站台未找到" + zarsh.getToPos());
        }
        if (station.getArea() == 3) {
            Integer fromStatus = acsLocationStatusService.getAcsLocationStatusByCode(station.getCode());
            if (fromStatus != null && fromStatus == 2) {
                throw new ServiceException("起点站台ACS状态无货物" + allocationStationCode);
            }
            Integer toStatus = acsLocationStatusService.getAcsLocationStatusByCode(station1.getCode());
            if (toStatus != null && toStatus == 1) {
                throw new ServiceException("终点站台ACS状态有物" + zarsh.getToPos());
            }
        }
        String fromPoint = station.getCode();
        String taskTypes = QuantityConstant.STATION_2_STATION_AGV;
        String toPoint = station1.getCode();

        AgvTask agvTask = new AgvTask();
        agvTask.setLayer(layer);
        agvTask.setIsEmpty(zarsh.getInKind());
        agvTask.setFromPoint(fromPoint);
        agvTask.setToPoint(toPoint);
        agvTask.setZoneCode(station.getZoneCode());
        // AGV任务类型都为配送
        agvTask.setTaskType(QuantityConstant.PEISONG_AGV);
        agvTask.setTaskTypes(taskTypes);
        agvTask.setUniqueId(zarsh.getUniqueId());
        agvTask.setCreatedBy(QuantityConstant.PLATFORM_SAP);
        agvTask.setCreated(DateUtils.getNowDate());
        agvTask.setPointType(pointType);
        if (StringUtils.isNotNull(zarsiList) && zarsiList.size() == 1) {
            agvTask.setLot(zarsiList.get(0).getCharg());
            MaterialDiameter materialDiameter =
                    materialDiameterService.getOne(new LambdaQueryWrapper<MaterialDiameter>().eq(MaterialDiameter::getLot, agvTask.getLot()));
            if (materialDiameter != null) {
                agvTask.setMaterialDiameter(materialDiameter.getDiameter());
            }
        }
        agvTaskService.save(agvTask);
        return agvTask;
    }

    public AgvTask createCSStation2Station(Zarsh zarsh, List<Zarsi> zarsiList, String fromPoint, String toPoint) {
        AgvTask agvTask = new AgvTask();
        Station fromStation = stationService.getStaionByCode(fromPoint);
        Station toStation = stationService.getStaionByCode(toPoint);
        if (toStation != null) {
            if (fromStation.getDefineProperty().intValue() != toStation.getDefineProperty().intValue()) {
                // 创建去向地址位置H1001
                agvTask.setToPoint(QuantityConstant.H1001);
                /**
                 * 去向地址位H1001都是taskType 400
                 */
                agvTask.setTaskType("400");
            } else {
                agvTask.setToPoint(toStation.getCode());
                agvTask.setTaskType("300");
            }
        } else {
            agvTask.setToPoint(QuantityConstant.H1001);
            agvTask.setTaskType("400");
        }

        agvTask.setZoneCode(QuantityConstant.AGV_ZONE);
        agvTask.setFromPoint(fromStation.getCode());
        agvTask.setTaskLevel(10);
        agvTask.setPalletNo(zarsh.getDrumId());
        agvTask.setIsEmpty(zarsh.getInKind());
        agvTask.setUniqueId(zarsh.getUniqueId());
        agvTask.setState(1);
        agvTask.setStopPoint(zarsh.getPassPos());
        boolean save = agvTaskService.save(agvTask);
        if (!save) {
            throw new ServiceException("生成AGV任务失败");
        }
        return agvTask;
    }

    public String getLKAGVPort(String toZoneCode, int layer, String roadWay, int inOut, int outSlicePalletArea, int outRollPalletArea, int range) {
        List<Integer> inOuts = new ArrayList<>();
        switch (inOut) {
            case 1:
                inOuts.add(1);
                inOuts.add(3);
                break;
            case 2:
                inOuts.add(2);
                inOuts.add(3);
                break;
        }
        String realZoneCode = toZoneCode;
        if (toZoneCode.contains("X")) {
            toZoneCode = toZoneCode.replace("X", "");
        }
        Zone toZone = zoneService.getZoneByCode(toZoneCode);
        String getPortType = null;
        if (toZone != null) {
            getPortType = toZone.getUserDef2();
        }
        List<Station> list = stationService.list(new LambdaQueryWrapper<Station>().eq(Station::getZoneCode, toZoneCode)
                .eq(Station::getDefineProperty, QuantityConstant.LK_AGV_PORT).eq(Station::getLayer, layer)
                .eq(StringUtils.isEmpty(getPortType) || !QuantityConstant.OUTSIDE_PORT.equals(getPortType), Station::getRangeStation, range)
                .le(QuantityConstant.OUTSIDE_PORT.equals(getPortType), Station::getRangeStation, range)
                .eq(outSlicePalletArea > 0, Station::getOutSlicePalletArea, outSlicePalletArea)
                .eq(outRollPalletArea > 0, Station::getOutRollPalletArea, outRollPalletArea).in(Station::getType, inOuts)
                .like(StringUtils.isNotEmpty(roadWay), Station::getRoadWay, roadWay));
        List<String> stationCodes = list.stream().map(Station::getCode).collect(toList());

        if (stationCodes.isEmpty()) {
            throw new ServiceException("该库区没有配置AGV 立库站台请前往配置");
        }

        if("A".equals(realZoneCode) && inOut == 1){
            LambdaQueryWrapper<AgvTask> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.in(AgvTask::getToPoint,stationCodes)
                    .eq(AgvTask::getState,10);
            List<AgvTask> agvTaskList = agvTaskService.list(queryWrapper);
            if(!agvTaskList.isEmpty()){
                Map<String,Integer> map = new HashMap<>();
                map.put("P1039",0);
                map.put("P1040",0);
                for (AgvTask agvTask : agvTaskList) {
                    String toPoint = agvTask.getToPoint();
                    Integer toPointNum = map.get(toPoint);
                    toPointNum += 1;
                    map.put(toPoint,toPointNum);
                }
                Integer valueP1039 = map.get("P1039");
                Integer valueP1040 = map.get("P1040");
                String port = valueP1039 > valueP1040 ? "P1040" : "P1039";
                return port;
            }
        }

        LambdaQueryWrapper<TaskHeader> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(TaskHeader::getZoneCode, toZoneCode).in(TaskHeader::getPort, stationCodes)
                .in(TaskHeader::getTaskType, 100, 200, 300, 400, 500, 600, 1100, 1200).le(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_ARRIVED_STATION);
        List<TaskHeader> list1 = taskHeaderService.list(queryWrapper);

        if (list1.isEmpty()) {
            return stationCodes.get(0);
        }
        Map<String, Integer> map = new HashMap<>();
        for (String stationCode : stationCodes) {
            map.put(stationCode, 0);
        }
        for (TaskHeader taskHeader : list1) {
            String port = taskHeader.getPort();
            if (map.containsKey(port)) {
                int num = map.get(port);
                num++;
                map.put(port, num);
            }
        }
        List<Map.Entry<String, Integer>> list2 = new ArrayList(map.entrySet());
        Collections.sort(list2, (o1, o2) -> (o1.getValue() - o2.getValue()));
        List<String> ports = list2.stream().map(Map.Entry::getKey).collect(toList());
        if(ports.isEmpty()){
            throw new ServiceException("没有可用站台");
        }
        String s = ports.get(0);
        return s;
    }

    public void checkStationContainer(Station station, String containerCode) {
        String formPort = station.getByName();
        switch (station.getForceContainer()) {
            case 1:
                if (StringUtils.isNotEmpty(containerCode)) {

                    Container container = containerService.getContainerByCode(containerCode, QuantityConstant.WAREHOUSECODE);
                    if (container == null) {
                        throw new ServiceException(formPort + "入库站台站点容器号 不存在系统" + containerCode);
                    }
                } else {
                    throw new ServiceException(formPort + "入库站台站点容器号 不能为空");
                }
                break;
            case 2:
                // 该站台不能
                Container container = containerService.getContainerByCode(containerCode, QuantityConstant.WAREHOUSECODE);
                if (container != null) {
                    throw new ServiceException("组盘站点不需要输入托盘号!!");
                }
                break;
            default:
        }
    }

    public void checkReceiptPort(Station receiptStation) {
        if (receiptStation == null) {
            throw new ServiceException("入库站台不能为空");
        }
        switch (receiptStation.getType()) {
            case "1":
            case "3":
            case "0":
                break;
            default:
                throw new ServiceException("入库站台类型不匹配");
        }
    }

    public void checkShipmentPort(Station shipmentStation) {
        if (shipmentStation == null) {
            throw new ServiceException("出库站台不能为空");
        }
        switch (shipmentStation.getType()) {
            case "2":
            case "3":
            case "0":
                break;
            default:
                throw new ServiceException("出库站台类型不匹配");
        }
    }

    /**
     * 1、去向为站台
     * 2、去向为库位
     *
     * @return
     */
    public int agvToPointChooseStationOrLocation(Zarsh zarsh) {

        // 1.校验库区是否存在
        String zoneCode = SAPUtils.getZoneCode(zarsh);
        // 2.校验库区为边线区还是立库区
        Zone zone = zoneService.getZoneByCode(zoneCode);
        if (zone == null) {
            return 0;
        }
        if (StringUtils.isNotEmpty(zone.getUserDef1())) {
            switch (zone.getUserDef1()) {
                case "1":
                case "2":
                    break;
                default:
            }
        }
        // 3.校验边线库区是否存在库位
        return 0;

    }

    /**
     * 配料仓外观仓检查不能跨区任务
     *
     * @param fromPos
     * @param toPos
     * @param lgnum
     * @param mFlag
     * @param locationCode
     * @param inkind
     */
    public void checkACCross(String fromPos, String toPos, String lgnum, String mFlag, String locationCode, Integer inkind, String crnIn) {
        String areaByFrom = null;
        String areaByTo = null;
        if (lgnum.equals("PLC")) {
            switch (mFlag) {
                case "2":
                case "B":
//                    String value = configService.getKey("online_F");
//                    if (lgnum.equals("WJC") && value.equals("0")) {
//                        // 配置了不上线外观仓,不需要判断
//                        return;
//                    }
                    if (inkind == 0) {
                        // 空托盘不需要校验出库区域
                        return;
                    }
                    // 入库
                    if (StringUtils.isEmpty(fromPos)) {
                        throw new ServiceException("配料外观仓入库任务,起点站台为空");
                    }
                    if (StringUtils.isEmpty(crnIn)) {
//                        return;
                        throw new ServiceException("配料外观仓入库任务,出库区域(直通入库作业)为空或不是ABC");
                    }

                    Station stationFrom = stationService.getStationBySAPCode(fromPos);
                    if (stationFrom == null) {
                        throw new ServiceException("配料外观仓入库任务,起点站台找不到" + fromPos);
                    }

//                    Station stationTo = stationService.getStationBySAPCode(toPos);
//                    if (stationTo == null) {
//                        throw new ServiceException("配料外观仓入库任务,终点站台找不到" + toPos);
//                    }
                    areaByFrom = stationFrom.getAreaByWcs();
                    areaByTo = crnIn;
                    if (StringUtils.isNotEmpty(areaByFrom) && StringUtils.isNotEmpty(areaByTo)) {
                        if (areaByFrom.equals("A") && areaByTo.equals("C")) {
                            throw new ServiceException("配料外观仓入库任务,起点和终点站台跨区,不能生成任务");
                        } else if (areaByFrom.equals("C") && areaByTo.equals("A")) {
                            throw new ServiceException("配料外观仓入库任务,起点和终点站台跨区,不能生成任务");
                        }
                    }
                    break;
                case "1":
                case "3":
                    // 出库
                    if (inkind == 1) {
                        if (StringUtils.isEmpty(toPos)) {
                            throw new ServiceException("配料外观仓出库任务,终点站台为空");
                        }
                        if (StringUtils.isEmpty(locationCode)) {
                            throw new ServiceException("配料外观仓出库任务,库位不能为空");
                        }
                        Station stationTo1 = stationService.getStationBySAPCode(toPos);
                        if (stationTo1 == null) {
                            throw new ServiceException("配料外观仓出库任务,终点站台找不到" + fromPos);
                        }
                        Location location1 = locationService.getLocationByCode(locationCode, QuantityConstant.WAREHOUSECODE);
                        if (location1 == null) {
                            throw new ServiceException("配料外观仓出库任务,库位找不到" + locationCode);
                        }
                        String areaByto = stationTo1.getAreaByWcs();
                        String areaByfrom = location1.getAreaByWcs();
                        if (StringUtils.isNotEmpty(areaByfrom) && StringUtils.isNotEmpty(areaByto)) {
                            if (areaByfrom.equals("A") && areaByto.equals("C")) {
                                throw new ServiceException("配料外观仓出库任务,起点和终点站台跨区,生成任务失败");
                            } else if (areaByfrom.equals("C") && areaByto.equals("A")) {
                                throw new ServiceException("配料外观仓出库任务,起点和终点站台跨区,生成任务失败");
                            }
                        }
                    }
                    break;
                case "M":
                    if (StringUtils.isEmpty(fromPos)) {
                        throw new ServiceException("配料外观仓换站任务,起点站台为空");
                    }
                    if (StringUtils.isEmpty(toPos)) {
                        throw new ServiceException("配料外观仓换站任务,出库站台为空");
                    }
                    Station stationFrom1 = stationService.getStationBySAPCode(fromPos);
                    if (stationFrom1 == null) {
                        throw new ServiceException("配料外观仓换站任务,起点站台找不到" + fromPos);
                    }

                    Station stationTo1 = stationService.getStationBySAPCode(toPos);
                    if (stationTo1 == null) {
                        throw new ServiceException("配料外观仓换站任务,终点站台找不到" + toPos);
                    }
                    areaByFrom = stationFrom1.getAreaByWcs();
                    areaByTo = stationTo1.getAreaByWcs();
                    if (StringUtils.isNotEmpty(areaByFrom) && StringUtils.isNotEmpty(areaByTo)) {
                        if (areaByFrom.equals("A") && areaByTo.equals("C")) {
                            throw new ServiceException("配料外观仓换站任务,起点和终点站台跨区,不能生成任务");
                        } else if (areaByFrom.equals("C") && areaByTo.equals("A")) {
                            throw new ServiceException("配料外观仓换站任务,起点和终点站台跨区,不能生成任务");
                        }
                    }
                    break;

            }
        }
    }

    public AgvTask createReceiptAGVTask(Zarsh zarsh, String allocationStationCode) {
        int layer = 2;
        // 来源点位
        String fromPoint = allocationStationCode;
        String taskTypes = QuantityConstant.RECEIPT_AGV;
        // 来源点位
        String toPoint = "";
        // 小车优先级别
        Integer priority = 888;
        String toPos = zarsh.getToPos();
        // 去向位置 如果找不到去向位置 就在后面分配库位 或者 分配立库交互站台 根据 库区类型来
        if (StringUtils.isNotEmpty(toPos)) {
            Station toPointStation = stationService.getStationBySAPCode(toPos);
            toPoint = toPointStation.getCode();
        }

        String zoneCode = "DX";
        String containerCode = zarsh.getDrumId();
        Integer pointType = -1;
        Container container = containerService.getContainerByCode(containerCode, QuantityConstant.WAREHOUSECODE);
        // 没有托盘创建虚拟托盘
        if (container == null) {
            containerCode = containerService.createContainerByZone("LS");
            container = containerService.getContainerByCode(containerCode, QuantityConstant.WAREHOUSECODE);
        }
        TaskHeader task = taskHeaderService.checkTaskByContainerCode(containerCode);
        if (task != null) {
            if (task.getInternalTaskType().intValue() == 100) {
                throw new ServiceException("入库,该容器已存在未完成的立库入库任务,请不要重复下发" + containerCode);
            } else if (task.getInternalTaskType().intValue() == 200) {
                throw new ServiceException("入库,该容器已存在未完成的立库出库任务,出库任务未完成,请到WCS中未完成任务查看是否有改任务,任务状态是否是响应接出站台请求,如果是直接手动强制完成该任务即可恢复正常,同时告知电气或WCS;" + containerCode);
            } else {
                throw new ServiceException("入库,该容器已存在未完成的任务" + containerCode);
            }
        }
        AgvTask agvTask1 = taskHeaderService.checkAgvTaskByContainerCode(containerCode);
        if (agvTask1 != null) {
            throw new ServiceException("入库,该容器已存在未完成的agv任务,请不要重复下发" + containerCode);
        }
        // 不是出库入库
        if (QuantityConstant.STATUS_LOCATION_LOCK.equals(container.getStatus())) {
            // 没有任务直接解锁
            containerService.updateLocationCodeAndStatus(containerCode, "", QuantityConstant.STATUS_LOCATION_EMPTY, QuantityConstant.WAREHOUSECODE);
        }
        if (StringUtils.isNotNull(container.getPlType())) {
            if (container.getPlType() == 0) {
                pointType = 1;
            }
            if (container.getPlType() == 1) {
                pointType = 2;
            }
            if (container.getPlType() == 2) {
                pointType = 2;
            }
        }
        if (StringUtils.isNotEmpty(container.getLocationCode())) {
            AjaxResult ajaxResult = inventoryHeaderService.removeInventoryByContainer(containerCode);
            if (ajaxResult.hasErr()) {
                throw new ServiceException(ajaxResult.getMsg());
            }
        }
        int unCompleteTask = agvTaskService.getUnCompleteTask(containerCode);
        if (unCompleteTask > 0) {
            throw new ServiceException(containerCode + "容器存在未完成的AGV任务!");
        }

        AgvTask agvTask = new AgvTask();
        agvTask.setLayer(layer);
        agvTask.setIsEmpty(zarsh.getInKind());
        agvTask.setFromPoint(allocationStationCode);
        agvTask.setToPoint(toPoint);
        agvTask.setTaskLevel(priority);
        agvTask.setZoneCode(zoneCode);
        // AGV任务类型都为配送
        agvTask.setTaskType(QuantityConstant.PEISONG_AGV);
        agvTask.setTaskTypes(taskTypes);
        agvTask.setPalletNo(containerCode);
        agvTask.setUniqueId(zarsh.getUniqueId());
        agvTask.setCreatedBy(QuantityConstant.PLATFORM_SAP);
        agvTask.setCreated(DateUtils.getNowDate());
        agvTask.setPointType(pointType);
        agvTaskService.save(agvTask);
        containerService.updateStatus(containerCode, QuantityConstant.STATUS_CONTAINER_LOCK, QuantityConstant.WAREHOUSECODE);
        if (StringUtils.isEmpty(agvTask.getToPoint())) {

            if (agvTask.getFromPoint().equals(QuantityConstant.H1001)) {
                agvTask.setToPoint(QuantityConstant.P31071);
                agvTaskService.updateById(agvTask);
                return agvTask;
            }

            Zone zone = zoneService.getZoneByCode(SAPUtils.getZoneCode(zarsh));
            if (zone != null) {
                String userDef8 = zone.getUserDef8();
                if (StringUtils.isNotEmpty(userDef8)) {
                    warecellAllocationService.agvWarecellAllocation(agvTask);
                } else {
                    // 根据库区 楼层 巷道 获取终点站台
                    String port = getLKAGVPort(SAPUtils.getZoneCode(zarsh), layer, null, QuantityConstant.RECEIPT_STATION_TYPE, 0, 0, 0);
                    agvTask.setToPoint(port);
                    agvTaskService.updateById(agvTask);
                }
            }
        }
        return agvTask;
    }

    public void checkContainerInWarehouse(String containerCode) {
        if (StringUtils.isNotEmpty(containerCode)) {
            Container container = containerService.getContainerByCode(containerCode, QuantityConstant.WAREHOUSECODE);
            if (container == null) {
                return;
            }
            TaskHeader task = taskHeaderService.checkTaskByContainerCode(containerCode);
            if (task != null) {
                if (task.getInternalTaskType().intValue() == 100) {
                    throw new ServiceException("该容器已存在未完成的入库任务,请不要重复下发" + containerCode);
                } else if (task.getInternalTaskType().intValue() == 200) {
                    throw new ServiceException(
                            "该容器已存在未完成的出库任务,出库任务未完成,请到WCS中未完成任务查看是否有改任务,任务状态是否是响应接出站台请求,如果是直接手动强制完成该任务即可恢复正常,同时告知电气或WCS;" + containerCode);
                } else {
                    throw new ServiceException("该容器已存在未完成的工作任务" + containerCode);
                }

            }
            AgvTask agvTask = taskHeaderService.checkAgvTaskByContainerCode(containerCode);
            if (agvTask != null) {
                throw new ServiceException("该容器已存在未完成的agv任务,请不要重复下发" + containerCode);
            }
            // 不是出库入库或agv任务
            if (QuantityConstant.STATUS_LOCATION_LOCK.equals(container.getStatus())) {
                // 没有任务直接解锁
                containerService.updateLocationCodeAndStatus(containerCode, "", QuantityConstant.STATUS_LOCATION_EMPTY, QuantityConstant.WAREHOUSECODE);
            }
            if (StringUtils.isNotEmpty(container.getLocationCode())) {
                AjaxResult ajaxResult = inventoryHeaderService.removeInventoryByContainer(containerCode);
                if (ajaxResult.hasErr()) {
                    throw new ServiceException(ajaxResult.getMsg());
                }
            }
            List<InventoryDetail> inventoryDetails =
                    inventoryDetailService.list(new LambdaQueryWrapper<InventoryDetail>().eq(InventoryDetail::getContainerCode, container.getCode()));
            if (!inventoryDetails.isEmpty()) {
                AjaxResult ajaxResult = inventoryHeaderService.removeInventoryByContainer(containerCode);
                if (ajaxResult.hasErr()) {
                    throw new ServiceException(ajaxResult.getMsg());
                }
            }
        }

    }

    public int truncateTable(int days) {
        String preweek = DateUtils.getNowPreDays("yyyy-MM-dd HH:mm:ss", days);
        LambdaQueryWrapper<Zarsh> lambda = new LambdaQueryWrapper<>();
        lambda.lt(Zarsh::getCreated, preweek);
        this.remove(lambda);
        return 1;
    }
}