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

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

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.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.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.service.ReceiptContainerHeaderService;
import com.huaheng.pc.receipt.receiptHeader.domain.ReceiptHeader;
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.domain.ShipmentContainerHeader;
import com.huaheng.pc.shipment.shipmentContainerHeader.service.ShipmentContainerHeaderService;
import com.huaheng.pc.shipment.shipmentHeader.domain.ShipmentHeader;
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;

/**
 * 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;

    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("单据已存在,请不要重复下发");
        }
        boolean tag = lockSapUniqueIdService.checkStationUniqueId(zarsh);
        if (tag) {
            return AjaxResult.error("站台有未成功的任务,请确认该站台入库任务后解锁站台");
        }
        return zarshService.createTaskBySAP(zarsiList, zarsh);
        /*
         * try {
         * zarshService.createTaskBySAP(zarsiList, zarsh);
         * } catch (Ex
         * ception e) {
         * e.printStackTrace();
         * backSapStatusService.addBackSapStatus(zarsh.getUniqueId(), zarsh.getLgnum(), null, zarsh.getMFlag(), "C",
         * null, e.getMessage());
         * return AjaxResult.error(e.getMessage());
         * }
         */
//        return AjaxResult.success("添加任务成功");
    }

    // 入库
    public TaskHeader receiptBySap(List<Zarsi> zarsiList, Zarsh zarsh) {
        TaskHeader taskHeader = null;
        // 空托盘入库
        if (zarsiList == null || zarsiList.size() == 0) {
            String area = zoneService.getZoneAreaByCode(zarsh.getLgnum());
            // SAP创建 空容器号的入库任务
            AjaxResult result = workTaskEmptyContainerService.createEmptyIn(zarsh.getDrumId(), "", area, zarsh.getFromPos(), zarsh.getCrnIn());
            if (result.hasErr()) {
                throw new ServiceException(result.getMsg());
            }
            Integer taskId = (Integer)result.getData();
            taskHeader = taskHeaderService.getById(taskId);
            taskHeader.setUniqueIds(zarsh.getUniqueId());
            taskHeaderService.updateById(taskHeader);
            // 调用sap的api,传递任务状态
            backSapStatusService.addBackSapStatus(zarsh.getUniqueId(), zarsh.getLgnum(), null, "1", "1", null, null);
            return null;
        }
        // 保存入库信息
        ReceiptHeader receiptHeader = null;
        for (Zarsi zarsi : zarsiList) {
            if (zarsi.getVerme() == null || zarsi.getVerme().compareTo(BigDecimal.ZERO) == 0) {
                throw new ServiceException("入库数量不能为0");
            }
        }
        AjaxResult ajaxResult = receiptHeaderService.saveReceiptBySap(zarsh, zarsiList);
        if (ajaxResult != null && ajaxResult.hasErr()) {
            throw new ServiceException(ajaxResult.getMsg());
        }
        receiptHeader = (ReceiptHeader)ajaxResult.getData();
        // 调用sap的api,传递任务状态
        backSapStatusService.addBackSapStatus(zarsh.getUniqueId(), zarsh.getLgnum(), null, "1", "1", null, null);
        // 如果是玻璃布2楼入库,机台到立库,站台机台,线边库到立库,站台立库口,机台到线边库

        Container container = containerService.getContainerByCode(zarsh.getDrumId(), QuantityConstant.WAREHOUSECODE);
        // 指定一个托盘生成任务
        if (StringUtils.isEmpty(zarsh.getDrumId()) || container == null) {
            if (zarsh.getLgnum().contains("A")) {
                Container container1 = containerService.createContainerByZoneNoTrasa("A");
                zarsh.setDrumId(container1.getCode());
                container = container1;
                // 创建临时托盘
            }
        }
        // 判断有没有托盘号,有则生成组盘
        if (StringUtils.isNotEmpty(zarsh.getDrumId()) && container != null) {
            // 保存组盘,生成任务信息
            // 设置wcs固定登录缓存,调用公共组盘接口
            ShiroUtils.setUserByWcsZone("SAP", QuantityConstant.WAREHOUSECODE, receiptHeader.getZoneCode());

            AjaxResult ajaxResult_receiptcontainerH = receiptContainerHeaderService.saveContainerByReceiptHeaderId(receiptHeader.getId(), zarsh.getDrumId());
            if (ajaxResult_receiptcontainerH != null && ajaxResult_receiptcontainerH.hasErr()) {
                throw new ServiceException(ajaxResult_receiptcontainerH.getMsg());
            }
//            AjaxResult ajaxResult_receiptcontainer =
//                receiptContainerHeaderService.saveReceiptContainerBySap(receiptHeader, zarsh.getDrumId(), zarsh.getFromPos(), zarsh.getToPos());
//            if (ajaxResult_receiptcontainer != null && ajaxResult_receiptcontainer.hasErr()) {
//                throw new ServiceException(ajaxResult_receiptcontainer.getMsg());
//            }
        }
        return taskHeader;
    }

    // 出库
    public TaskHeader shipmentBySap(List<Zarsi> zarsiList, Zarsh zarsh) {
        TaskHeader taskHeader = null;
        // 空托盘出库
        if (zarsiList == null || zarsiList.size() == 0) {
            // 获取对应库区编码 zarsh.getLgnum() --> F
            List<Location> list = containerService.getEmptyContainerInLocation(zarsh.getLgnum(), "", "", QuantityConstant.WAREHOUSECODE);
            List<String> emptyContainerCodeList = list.stream().map(t -> t.getContainerCode()).collect(toList());
            List<String> removeContainerList = new ArrayList<>();
            for (String containerCode : emptyContainerCodeList) {
                Container container = containerService.getContainerByCode(containerCode, QuantityConstant.WAREHOUSECODE);
                if (container.getStatus().equals(QuantityConstant.STATUS_CONTAINER_LOCK)) {
                    removeContainerList.add(containerCode);
                }
            }
            emptyContainerCodeList.removeAll(removeContainerList);

            if (emptyContainerCodeList == null || emptyContainerCodeList.isEmpty()) {
                throw new ServiceException("库内没有找到空容器");
            }
            // 自动匹配空容器出库
            Container container = null;
            if (StringUtils.isNotEmpty(zarsh.getDrumId())) {
                container = containerService.getContainerByCode(zarsh.getDrumId(), QuantityConstant.WAREHOUSECODE);
            } else {
                container = containerService.getContainerByCode(emptyContainerCodeList.get(0), QuantityConstant.WAREHOUSECODE);
            }
            if (container == null) {
                throw new ServiceException("请检查容器码:" + zarsh.getDrumId() + "是否正确!");
            }
            // 创建空容器出库任务
            AjaxResult result = workTaskService.createEmptyOut(container.getCode(), container.getLocationCode(), zarsh.getToPos(), QuantityConstant.WAREHOUSECODE,
                zarsh.getUniqueId());

            if (result.hasErr()) {
                throw new ServiceException(result.getMsg());
            }
            // 调用sap的api,传递任务状态
            backSapStatusService.addBackSapStatus(zarsh.getUniqueId(), zarsh.getLgnum(), null, "2", "1", null, null);
            return taskHeader;
        }
        // 有料出库
        // 保存出库信息
        ShipmentHeader shipmentHeader = null;
        AjaxResult ajaxResult = shipmentHeaderService.saveShipmentBySap(zarsh, zarsiList);
        if (ajaxResult != null && ajaxResult.hasErr()) {
            throw new ServiceException(ajaxResult.getMsg());
        }
        shipmentHeader = (ShipmentHeader)ajaxResult.getData();
        // 调用sap的api,传递任务状态
        backSapStatusService.addBackSapStatus(zarsh.getUniqueId(), zarsh.getLgnum(), null, "2", "1", null, null);
        // 判断有没有库位号,有则生成组盘
        if (StringUtils.isNotEmpty(zarsh.getLocation())) {
            // 保存组盘信息
            ShipmentContainerHeader shipmentContainerHeader = null;
            AjaxResult result = shipmentContainerHeaderService.saveShipmentContainerBySap(shipmentHeader, zarsh);
            if (result != null && result.hasErr()) {
                throw new ServiceException(result.getMsg());
            }
            shipmentContainerHeader = (ShipmentContainerHeader)result.getData();
            // 创建任务表数据
            AjaxResult ajaxResult_taskheader = taskHeaderService.saveTaskBySapLK(shipmentContainerHeader);
            // 生成任务成功之后在修改 组盘状态
            if (ajaxResult_taskheader.hasErr()) {
                throw new ServiceException("生成任务失败");
            }
        }
        return taskHeader;
    }

    @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;
        if (StringUtils.isNotEmpty(area)) {
            switch (zarsh.getMFlag()) {
                case "2":
                case "B":
                    port = zarsh.getFromPos();
                    break;
                case "1":
                case "3":
                    port = zarsh.getToPos();
                    if (StringUtils.isNotEmpty(zarsh.getLocation()) && zarsh.getLocation().equals(port)) {
                        throw new ServiceException("出库终点和库位不能一样:" + port + ":" + zarsh.getLocation());
                    }
                    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);
            }
        }

        /**
         * 1:整盘 / 等待组盘
         * 2:空托
         */
        Integer billType = zarsh.getInKind();
        String type = zarsh.getMFlag();
        String uniqueId = zarsh.getUniqueId();
        SAPTaskDomain domain = new SAPTaskDomain();
        domain.setZarsh(zarsh);
        domain.setZarsiList(zarsiList);
        zarsh.setCreateBy(QuantityConstant.PLATFORM_SAP);
        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.checkLocationByZarsh(zarsh, area);
                if (checkAjax.hasErr()) {
                    throw new ServiceException(checkAjax.getMsg());
                }
                // 判断站台属性是否为AGV站台
                if (inStation.getDefineProperty() == 1) {
                    if (StringUtils.isEmpty(toPort)) {
                        // 获取 AGV立库交互站台
                        createReceiptAGVTask(zarsh, zarsiList, inStation.getCode());
                    } else {
                        createStation2Station(zarsh, zarsiList, inStation.getCode());
                    }
                } else {
                    AjaxResult ajaxResult = workTaskService.createEmptyIn(containerCode, null, area, inStation.getCode(), uniqueId);
                    if (ajaxResult.hasErr()) {
                        throw new ServiceException(ajaxResult.getMsg());
                    }
                }

                break;
            // 出库
            case "1":
            case "3":
                LambdaQueryWrapper<Station> lambdaQuery2 = Wrappers.lambdaQuery();
                lambdaQuery2.eq(Station::getByName, toPort);
                Station outStation = stationService.getOne(lambdaQuery2);
                if (outStation == null) {
                    throw new ServiceException(toPort + "站台异常,未找到站台");
                }
                Integer defineProperty = outStation.getDefineProperty();
                // 判断库区
                if (StringUtils.isNotEmpty(zarsh.getCrnIn())) {
                    zoneCode = zarsh.getCrnIn();
                } else {
                    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, outStation.getCode());
                } else {
                    // 区域移库 映射站台 SAP任务下发的是移入库区的站台 通过移入站台获取到 出库的站台
                    if (1 == defineProperty) {
                        String port = getLKAGVPort(zoneCode, outStation.getLayer(), null, QuantityConstant.SHIPMENT_STATION_TYPE, outStation.getOutSlicePalletArea(),
                            outStation.getOutRollPalletArea(), outStation.getRangeStation());
                        if (StringUtils.isEmpty(port)) {
                            throw new ServiceException("立库AGV交互站台未配置请先配置立库AGV交互站台");
                        }
                        outStation = stationService.getStaionByCode(port);
                    }
                    String shipmentStationCode = null;
                    if (StringUtils.isEmpty(outStation.getByPassPort())) {
                        shipmentStationCode = outStation.getCode();
                    } else {
                        shipmentStationCode = outStation.getCode();
                    }
                    String areaByWcs = outStation.getAreaByWcs();
                    Station station2 = stationService.getOne(new LambdaQueryWrapper<Station>().eq(Station::getCode, shipmentStationCode));
                    if (station2 == null) {
                        throw new ServiceException(shipmentStationCode + "站台异常,未找到站台");
                    }
                    String roadWay = station2.getRoadWay();
                    String[] split = roadWay.split(",");
                    List<String> roadWays = Arrays.asList(split);

                    if (!SAPUtils.getZoneCode(zarsh).equals(outStation.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, outStation.getCode());
                    if (emptyOut.hasErr()) {
                        throw new ServiceException(emptyOut.getMsg());
                    }
                }

                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();
        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.checkLocationByZarsh(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);
                            if (StringUtils.isEmpty(crnIn)) {
                                // 获取分配agv任务去向的站台
                                String toPoint = agvTask.getToPoint();
                                zarsh.setFromPos(toPoint);
                                receiptHeaderService.saveReceiptHeaderBySap(uniqueId, zarsh, zarsiList);
                            }
                            break;
                        }
                        // 生成入库单 用于AGV调用组盘接口
                        receiptHeaderService.saveReceiptHeaderBySap(uniqueId, zarsh, zarsiList);
                        break;
                    // 有托盘
                    case 1:
                        // 判断 from_pos 来源
                        domain.setFormPort(formPortCode);
                        // 立库agv交互点入库
                        // 指定去那边
                        if ((defineProperty == 2 && StringUtils.isEmpty(zarsh.getCrnIn())) || defineProperty == 0) {
                            createSAPReceiptTask(uniqueId, zarsh, zarsiList);
                        }
                        // agv站台入库
                        if (defineProperty == 1 || (defineProperty == 2 && StringUtils.isNotEmpty(zarsh.getCrnIn()))) {
                            createReceiptAGVTask(zarsh, zarsiList, formPortCode);
                        }
                        break;
                    default:
                        throw new IllegalStateException("Unexpected value: " + containerFlag);
                }
                break;
            // 出库
            case "1":
            case "3":
                Station stationLocation = stationService.getStationBySAPCode(locationCode);
                if (stationLocation != null) {
                    Station toStation = stationService.getStationBySAPCode(toPort);
                    if (toStation == null) {
                        throw new ServiceException("站台未找到!" + formPort);
                    }
                    createStation2Station(zarsh, zarsiList, toStation.getCode());
                    break;
                }
                // 判断库区
                Location location = locationService.getLocationByCode(locationCode, QuantityConstant.WAREHOUSECODE);
                if (location == null) {
                    throw new ServiceException("SAP库位为空请检查数据" + zarsh.getLocation());
                }
                zoneCode = location.getZoneCode();
                Station toStation = stationService.getStationBySAPCode(toPort);
                if (toStation == null) {
                    throw new ServiceException("站台未找到!" + toPort);
                }
                // 校验是否为出库站台
                checkShipmentPort(toStation);
                // 出库站台编码
                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;
                        default:
                            throw new ServiceException("SAP数据异常");
                    }
                } else {
                    // 生成立库任务
                    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;
                        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 void 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 = receiptTaskService.getLocationByH(task.getPort(), task);
        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.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);

    }

    /**
     * 根据sap创建出库任务
     */
    public void createSAPShipmentTask(Zarsh zarsh, List<Zarsi> zarsiList, String allocationStationCode) {
        String warehouseCode = QuantityConstant.WAREHOUSECODE;
        String locationCode = zarsh.getLocation();
        String uniqueId = zarsh.getUniqueId();
        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.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());
        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<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 (!lots.contains(inventoryDetail.getRollNumber())) {
                if ("B".equals(location.getZoneCode())) {
                    taskDetailList.remove(taskDetail);
                }
                continue;
            }
            //
            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);
        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();
        }

        String zoneCode = station.getZoneCode();
        String containerCode = zarsh.getDrumId();
        Integer pointType = -1;
        Container container = null;
        if (StringUtils.isEmpty(containerCode)) {
            containerCode = containerService.createContainerByZone(zoneCode);
        }
        container = containerService.getContainerByCode(containerCode, QuantityConstant.WAREHOUSECODE);
        // 没有托盘创建虚拟托盘
        if (container == null) {
            containerCode = containerService.createContainerByZone(zoneCode);
            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) {
                pointType = 2;
            }
            if (container.getPlType() == 2) {
                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())) {
            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);
                }
            }
        }
        if (station.getIsRelay() == 2) {
            toPoint = agvTask.getToPoint();
            agvTask.setToPoint("P003");
            agvTask.setZoneCode(QuantityConstant.AGV_ZONE);
            agvTaskService.updateById(agvTask);
            createAgvRelay(agvTask, toPoint);
        }
        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 + " 系统内未找到改库位");
        }
        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) {
                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) {
        String locationCode = zarsh.getLocation();
        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(locationCode);
        String fromPoint = station1.getCode();
        String taskTypes = QuantityConstant.STATION_2_STATION_AGV;
        String toPoint = station.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 (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 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;
        }
        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 立库站台请前往配置");
        }

        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) {
            if (map.containsKey(taskHeader)) {
                int num = map.get(taskHeader.getPort());
                num++;
                map.put(taskHeader.getPort(), num);
            } else {
                map.put(taskHeader.getPort(), 1);
            }
        }
        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());
        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);
                    }
                    if (station.getArea() == 4 || station.getArea() == 5) {
                        if (!container.getArea().equals("4") && !container.getArea().equals("5")) {
                            throw new ServiceException(":容器和站台不匹配:" + formPort + ":" + containerCode);
                        }
                    } else {
                        if (!station.getArea().toString().equals(container.getArea())) {
                            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;

    }

}