TaskHeaderService.java 83.2 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
package com.huaheng.pc.task.taskHeader.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaheng.api.SSP.service.OrderAssignApiService;
import com.huaheng.api.acs.service.AcsService;
import com.huaheng.api.wcs.domain.WcsTask;
import com.huaheng.api.wcs.service.taskAssignService.TaskAssignService;
import com.huaheng.common.constant.HttpConstant;
import com.huaheng.common.constant.QuantityConstant;
import com.huaheng.common.exception.service.Assert;
import com.huaheng.common.exception.service.ServiceException;
import com.huaheng.common.support.Convert;
import com.huaheng.common.utils.DateUtils;
import com.huaheng.common.utils.StringUtils;
import com.huaheng.common.utils.Wrappers;
import com.huaheng.common.utils.restful.RestUtil;
import com.huaheng.common.utils.security.ShiroUtils;
import com.huaheng.framework.web.domain.AjaxResult;
import com.huaheng.framework.web.service.ConfigService;
import com.huaheng.pc.config.address.service.AddressService;
import com.huaheng.pc.config.company.domain.Company;
import com.huaheng.pc.config.company.service.CompanyService;
import com.huaheng.pc.config.container.domain.Container;
import com.huaheng.pc.config.container.service.ContainerService;
import com.huaheng.pc.config.containerType.domain.ContainerType;
import com.huaheng.pc.config.containerType.service.ContainerTypeService;
import com.huaheng.pc.config.cycleCountPreference.domain.CycleCountPreference;
import com.huaheng.pc.config.cycleCountPreference.service.CycleCountPreferenceService;
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.service.MaterialService;
import com.huaheng.pc.config.station.domain.Station;
import com.huaheng.pc.config.station.service.StationService;
import com.huaheng.pc.inventory.cycleCountDetail.domain.CycleCountDetail;
import com.huaheng.pc.inventory.cycleCountDetail.service.CycleCountDetailService;
import com.huaheng.pc.inventory.inventoryDetail.domain.InventoryDetail;
import com.huaheng.pc.inventory.inventoryDetail.service.InventoryDetailService;
import com.huaheng.pc.inventory.inventoryHeader.domain.InventoryHeader;
import com.huaheng.pc.inventory.inventoryHeader.service.InventoryHeaderService;
import com.huaheng.pc.receipt.receiptContainerDetail.domain.ReceiptContainerDetail;
import com.huaheng.pc.receipt.receiptContainerDetail.service.ReceiptContainerDetailService;
import com.huaheng.pc.receipt.receiptContainerHeader.domain.ReceiptContainerHeader;
import com.huaheng.pc.receipt.receiptContainerHeader.service.ReceiptContainerHeaderService;
import com.huaheng.pc.receipt.receiptDetail.domain.ReceiptDetail;
import com.huaheng.pc.receipt.receiptDetail.service.ReceiptDetailService;
import com.huaheng.pc.receipt.receiptHeader.domain.ReceiptHeader;
import com.huaheng.pc.receipt.receiptHeader.service.ReceiptHeaderService;
import com.huaheng.pc.receipt.receiving.service.ReceivingService;
import com.huaheng.pc.shipment.lockingWorkOrder.domain.LockingWorkOrder;
import com.huaheng.pc.shipment.lockingWorkOrder.service.LockingWorkOrderService;
import com.huaheng.pc.shipment.shipmentContainerDetail.domain.ShipmentContainerDetail;
import com.huaheng.pc.shipment.shipmentContainerDetail.service.ShipmentContainerDetailService;
import com.huaheng.pc.shipment.shipmentContainerHeader.domain.ShipmentContainerHeader;
import com.huaheng.pc.shipment.shipmentContainerHeader.service.ShipmentContainerHeaderService;
import com.huaheng.pc.shipment.shipmentDetail.domain.ShipmentDetail;
import com.huaheng.pc.shipment.shipmentDetail.service.ShipmentDetailService;
import com.huaheng.pc.shipment.shipmentHeader.domain.ShipmentHeader;
import com.huaheng.pc.shipment.shipmentHeader.service.ShipmentHeaderService;
import com.huaheng.pc.task.taskDetail.domain.TaskDetail;
import com.huaheng.pc.task.taskDetail.service.TaskDetailService;
import com.huaheng.pc.task.taskHeader.domain.MobileTask;
import com.huaheng.pc.task.taskHeader.domain.ShipmentTaskCreateModel;
import com.huaheng.pc.task.taskHeader.domain.TaskHeader;
import com.huaheng.pc.task.taskHeader.mapper.TaskHeaderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

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

@Service
public class TaskHeaderService  extends ServiceImpl<TaskHeaderMapper, TaskHeader> {

    @Resource
    private ShipmentContainerHeaderService shipmentContainerHeaderService;
    @Autowired
    private AddressService addressService;
    @Resource
    private LocationService locationService;
    @Resource
    private ContainerService containerService;
    @Resource
    private ContainerTypeService containerTypeService;
    @Resource
    private TaskDetailService taskDetailService;
    @Resource
    private TaskHeaderService taskHeaderService;
    @Resource
    private InventoryHeaderService inventoryHeaderService;
    @Resource
    private InventoryDetailService inventoryDetailService;
    @Resource
    private ReceiptContainerDetailService receiptContainerDetailService;
    @Resource
    private CycleCountDetailService cycleCountDetailService;
    @Resource
    private CycleCountPreferenceService cycleCountPreferenceService;
    @Resource
    private CycleCountTaskService cycleCountTaskService;
    @Resource
    private ReceiptContainerHeaderService receiptContainerHeaderService;
    @Resource
    private TaskHeaderMapper taskHeaderMapper;
    @Autowired
    private TaskAssignService taskAssignService;
    @Resource
    private ReceiptTaskService receiptTaskService;
    @Resource
    private ShipmentTaskService shipmentTaskService;
    @Resource
    private WorkTaskService workTaskService;
    @Resource
    private TransferTaskService transferTaskService;
    @Resource
    private ReceivingService receivingService;
    @Resource
    private ConfigService configService;
    @Resource
    private BackInvokeService backInvokeService;
    @Resource
    private LockingWorkOrderService lockingWorkOrderService;
    @Resource
    private ShipmentHeaderService shipmentHeaderService;
    @Resource
    private ShipmentDetailService shipmentDetailService;
    @Resource
    private MaterialService materialService;
    @Resource
    private ShipmentContainerDetailService shipmentContainerDetailService;
    @Resource
    private AcsService acsService;
    @Resource
    private OrderAssignApiService orderAssignApiService;
    @Resource
    private StationService stationService;
    @Resource
    private CompanyService companyService;
    @Resource
    private ReceiptHeaderService receiptHeaderService;
    @Resource
    private ReceiptDetailService receiptDetailService;

    public TaskHeader selectFirstEntity(TaskHeader condition) {
        LambdaQueryWrapper<TaskHeader> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(condition.getContainerCode()),TaskHeader::getContainerCode, condition.getContainerCode());
        lambdaQueryWrapper.eq(StringUtils.isNotNull(condition.getStatus()),TaskHeader::getStatus, condition.getStatus());
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(condition.getWarehouseCode()),TaskHeader::getWarehouseCode, condition.getWarehouseCode());
        lambdaQueryWrapper.orderByDesc(TaskHeader::getId);
        lambdaQueryWrapper.last("limit 1");
        return this.getOne(lambdaQueryWrapper);
    }
    public TaskHeader selectByUser(TaskHeader condition) {
        LambdaQueryWrapper<TaskHeader> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(condition.getContainerCode()),TaskHeader::getContainerCode, condition.getContainerCode());
        lambdaQueryWrapper.lt(StringUtils.isNotNull(condition.getStatus()),TaskHeader::getStatus, condition.getStatus());
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(condition.getWarehouseCode()),TaskHeader::getWarehouseCode, condition.getWarehouseCode());
        lambdaQueryWrapper.last("limit 1");
        return this.getOne(lambdaQueryWrapper);
    }

    public List<TaskHeader> getTasksStatus(Short lastStatus) {
        return taskHeaderMapper.getTasksStatus(lastStatus);
    }


    /**
     * 查询容器有无任务
     */
    public Integer UncompleteCount(String ContainerCode) {
        return taskHeaderMapper.UncompleteCount(ContainerCode, ShiroUtils.getWarehouseCode());
    }

    /**
     * 查询容器有无任务
     */
    public Integer UncompleteCount(String ContainerCode,String warehouseCode) {
        return taskHeaderMapper.UncompleteCount(ContainerCode, warehouseCode);
    }


    /**
     * 盘点任务首选项
     *
     * @param taskHeaderList
     * @return
     */
    public List<TaskHeader> preferenceRealize(List<TaskHeader> taskHeaderList) {
        //盘点任务头,默认不显示库位,容器。
        List<TaskHeader> taskHeaders = new ArrayList<>();
        for (TaskHeader item : taskHeaderList) {
            //盘点明细
            CycleCountDetail cycleCountDetailtemp = new CycleCountDetail();
            cycleCountDetailtemp.setWarehouseCode(item.getWarehouseCode());
            cycleCountDetailtemp.setCycleCountHeadCode(item.getReferenceCode());
            cycleCountDetailtemp.setId(item.getAllocationHeadId());  //明细ID
            LambdaQueryWrapper<CycleCountDetail> detailLambdaQueryWrapper = Wrappers.lambdaQuery(cycleCountDetailtemp);
            CycleCountDetail cycleCountDetail = cycleCountDetailService.getOne(detailLambdaQueryWrapper);
            if (StringUtils.isNull(cycleCountDetail)) {
                throw new SecurityException("没有找到子任务对应的盘点明细!");
            }
            //找盘点首选项
            CycleCountPreference cycleCountPreferenceTemp = new CycleCountPreference();
            cycleCountPreferenceTemp.setCode(cycleCountDetail.getPreferenceCode());
            cycleCountPreferenceTemp.setWarehouseCode(cycleCountDetail.getWarehouseCode());
            LambdaQueryWrapper<CycleCountPreference> preferenceLambdaQueryWrapper = Wrappers.lambdaQuery(cycleCountPreferenceTemp);
            CycleCountPreference cycleCountPreference = cycleCountPreferenceService.getOne(preferenceLambdaQueryWrapper);
            if (StringUtils.isNull(cycleCountPreference)) {
                throw new SecurityException("没有找到盘点首选项!");
            }
            //根据首选项判断数据
            if (!cycleCountPreference.getPromptLocation()) {
                //库位
                item.setFromLocation("");
                item.setToLocation("");
            }
            if (!cycleCountPreference.getPromptLpn()) {
                //容器
                item.setContainerCode("");
            }
            taskHeaders.add(item);
        }
        return taskHeaders;
    }

    /**
     * 取消任务
     */
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult cancelTask(Integer[] taskIds) {
        for (int taskId : taskIds) {
            TaskHeader taskHeader = taskHeaderService.getById(taskId);
            if (taskHeader == null) {
                return AjaxResult.error("任务" + taskId + "未找到,操作中止");
            }
            if (taskHeader.getStatus() > QuantityConstant.TASK_STATUS_RELEASE) {
                return AjaxResult.error("存在任务" + taskHeader.getId() + "已下发或执行,操作中止");
            }
            int preTaskNo = taskId;
            LambdaQueryWrapper<TaskHeader> taskHeaderLambdaQueryWrapper = Wrappers.lambdaQuery();
            taskHeaderLambdaQueryWrapper.eq(TaskHeader::getPreTaskNo, preTaskNo);
            TaskHeader preTaskHeader = taskHeaderService.getOne(taskHeaderLambdaQueryWrapper);
            if (preTaskHeader != null) {
                return AjaxResult.error("取消任务失败, 有前置任务" + preTaskHeader.getId());
            }
            //查出任务明细
            TaskDetail taskDetail1 = new TaskDetail();
            taskDetail1.setTaskId(taskHeader.getId());
            taskDetail1.setWarehouseCode(taskHeader.getWarehouseCode());
            taskDetail1.setCompanyCode(taskHeader.getCompanyCode());
            LambdaQueryWrapper<TaskDetail> td = Wrappers.lambdaQuery(taskDetail1);
            List<TaskDetail> taskDetailList = taskDetailService.list(td);
            TaskDetail taskDetail = null;
            if (taskDetailList != null && taskDetailList.size() > 0) {
                taskDetail = taskDetailList.get(0);
                if (taskDetail == null) {
                    throw new ServiceException("任务明细条目错误");
                }
            }
            //删除子任务
            LambdaQueryWrapper<TaskDetail> lambdaQueryWrapper = Wrappers.lambdaQuery();
            lambdaQueryWrapper.eq(TaskDetail::getTaskId, taskHeader.getId());
            taskDetailService.remove(lambdaQueryWrapper);
            //删除主任务
            taskHeaderService.removeById(taskHeader.getId());
            //盘点取消任务,恢复明细状态为1
            int taskType = taskHeader.getTaskType().intValue();
            switch (taskType) {
                case QuantityConstant.TASK_TYPE_WHOLERECEIPT:
                case QuantityConstant.TASK_TYPE_SUPPLEMENTRECEIPT:
                    receiptContainerHeaderService.cancelReceipt(taskHeader.getAllocationHeadId());
                    LambdaQueryWrapper<ReceiptContainerHeader> lambda = Wrappers.lambdaQuery();
                    lambda.eq(ReceiptContainerHeader::getContainerCode, taskHeader.getContainerCode())
                            .ne(ReceiptContainerHeader::getStatus, QuantityConstant.RECEIPT_CONTAINER_FINISHED)
                            .eq(ReceiptContainerHeader::getWarehouseCode, ShiroUtils.getWarehouseCode());
                    lambda.last("limit 1");
                    ReceiptContainerHeader receiptContainerHeader = receiptContainerHeaderService.getOne(lambda);
                    String value = configService.getKey(QuantityConstant.RULE_TASK_LOCATION,ShiroUtils.getWarehouseCode());
                    int taskLocationRule = Integer.parseInt(value);
                    if (taskLocationRule == QuantityConstant.RULE_TASK_NOT_LOCATION) {
                        receiptContainerHeader.setToLocation("");
                        receiptContainerHeaderService.update(receiptContainerHeader, lambda);
                    }
                    LambdaQueryWrapper<ReceiptContainerDetail> receiptContainerDetailLambdaQueryWrapper = Wrappers.lambdaQuery();
                    receiptContainerDetailLambdaQueryWrapper.eq(ReceiptContainerDetail::getReceiptContainerId, receiptContainerHeader.getId());
                    List<ReceiptContainerDetail> receiptContainerDetailList = receiptContainerDetailService.list(receiptContainerDetailLambdaQueryWrapper);
                    for (ReceiptContainerDetail receiptContainerDetail : receiptContainerDetailList) {
                        LambdaQueryWrapper<ReceiptContainerDetail> receiptContainerDetailLambdaQueryWrapper1 = Wrappers.lambdaQuery();
                        receiptContainerDetailLambdaQueryWrapper1.eq(ReceiptContainerDetail::getId, receiptContainerDetail.getId());
                        receiptContainerDetail.setLocationCode("");
                        receiptContainerDetailService.update(receiptContainerDetail, receiptContainerDetailLambdaQueryWrapper1);
                    }
                    break;
                case QuantityConstant.TASK_TYPE_WHOLESHIPMENT:
                case QuantityConstant.TASK_TYPE_SORTINGSHIPMENT:
                    ShipmentContainerHeader shipmentContainerHeader = new ShipmentContainerHeader();
                    shipmentContainerHeader.setId(taskHeader.getAllocationHeadId());
                    shipmentContainerHeader.setStatus(QuantityConstant.SHIPMENT_CONTAINER_BUILD);
                    shipmentContainerHeaderService.updateById(shipmentContainerHeader);
                    List<ShipmentContainerDetail> shipmentContainerDetails = shipmentContainerDetailService.selectByShippingContainerId(taskHeader.getAllocationHeadId());
                    for (ShipmentContainerDetail shipmentContainerDetail : shipmentContainerDetails) {
                        shipmentContainerDetail.setStatus(QuantityConstant.SHIPMENT_CONTAINER_BUILD);
                    }
                    shipmentContainerDetailService.updateBatchById(shipmentContainerDetails);
                    break;
                case QuantityConstant.TASK_TYPE_CYCLECOUNT:
                    CycleCountDetail cycleCountDetail = new CycleCountDetail();
                    cycleCountDetail.setCompanyCode(taskDetail.getCompanyCode());
                    cycleCountDetail.setWarehouseCode(taskDetail.getWarehouseCode());
                    cycleCountDetail.setLocationCode(taskDetail.getFromLocation());
                    cycleCountDetail.setContainerCode(taskDetail.getContainerCode());
                    cycleCountDetail.setCycleCountHeadCode(taskDetail.getBillCode());//盘点单Code
                    cycleCountDetail.setId(taskDetail.getBillDetailId());//盘点细单ID
                    LambdaQueryWrapper<CycleCountDetail> lam = Wrappers.lambdaQuery(cycleCountDetail);
                    List<CycleCountDetail> cycleCountDetailList = cycleCountDetailService.list(lam);//
                    for (CycleCountDetail item : cycleCountDetailList) {
                        item.setTaskHeaderId(null);
                        item.setTaskHeaderId(null);
                        item.setLastUpdated(new Date());
                        item.setLastUpdatedBy(ShiroUtils.getLoginName());
                        item.setEnableStatus(1);
                        cycleCountDetailService.saveOrUpdate(item);
                    }
                    break;
                default:
                    break;
            }
            cancelLocationAndContainerStatus(taskHeader);
        }
        return AjaxResult.success("取消任务成功!");
    }

    private void cancelLocationAndContainerStatus(TaskHeader taskHeader) {
        if (taskHeader.getFromLocation() != null) {
            //更新托盘、库位状态
            locationService.updateStatus(taskHeader.getFromLocation(), QuantityConstant.STATUS_LOCATION_EMPTY);
        }
        if (taskHeader.getToLocation() != null) {
            //更新托盘、库位状态
            locationService.updateStatus(taskHeader.getToLocation(), QuantityConstant.STATUS_LOCATION_EMPTY);
        }
        LambdaQueryWrapper<InventoryHeader> inventoryHeaderLambdaQueryWrapper = Wrappers.lambdaQuery();
        inventoryHeaderLambdaQueryWrapper.eq(InventoryHeader::getContainerCode, taskHeader.getContainerCode());
        InventoryHeader inventoryHeader = inventoryHeaderService.getOne(inventoryHeaderLambdaQueryWrapper);
        Container container = containerService.getContainerByCode(taskHeader.getContainerCode());
        String lastStatus = container.getLastStatus();
        container.setStatus(QuantityConstant.STATUS_CONTAINER_EMPTY);
        if(StringUtils.isNotEmpty(lastStatus)) {
            container.setStatus(lastStatus);     //解决空托盘组移库问题
        }
        if (inventoryHeader != null) {
            if (QuantityConstant.STATUS_CONTAINER_SOME.equals(inventoryHeader.getContainerStatus())) {
                container.setStatus(QuantityConstant.STATUS_CONTAINER_SOME);
            }
        }
        container.setLastStatus(QuantityConstant.EMPTY_STRING);
        container.setLocationCode(taskHeader.getFromLocation());
        containerService.updateById(container);
    }

    /**
     * 下发WCS执行任务
     * 执行任务
     */
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult<TaskHeader> sendTaskToWcs(Integer[] taskIds) {
        TaskHeader task = null;
        for (Integer taskId : taskIds) {

            task = taskHeaderService.getById(taskId);

            if (task.getStatus() >= QuantityConstant.TASK_STATUS_RELEASE) {
                return AjaxResult.error("任务" + taskId + "已经下发,请不要重复下发,操作中止");
            }

            // 给wcs传递任务
            AjaxResult ajaxResult =null;
            String station=task.getPort();
            switch (task.getZoneCode()){
                case "LK":
                    //立库考虑双伸位问题,外部库位挡住内部库位
                    if(task.getWarehouseCode().equals(QuantityConstant.WAREHOUSE_KS)&&100!=(task.getTaskType()) && 500!=task.getTaskType()) {
                        transferTaskService.doubletransfer(task);
                    }
                    ajaxResult=taskAssignService.wcsTaskAssign(task);
                    if (ajaxResult != null && ajaxResult.hasErr()) {
                        return AjaxResult.error(ajaxResult.getMsg());
                    }
                    task=this.updateTaskRelease(task);
                    break;
                case QuantityConstant.ZONECODE_XC:
                    ajaxResult=taskAssignService.wcsTaskAssign(task);
                    if (ajaxResult != null && ajaxResult.hasErr()) {
                        return AjaxResult.error(ajaxResult.getMsg());
                    }
                    task=this.updateTaskRelease(task);
                    break;
                case "AGV":
                    if(task.getWarehouseCode().equals(QuantityConstant.WAREHOUSE_KS)){
                        if(StringUtils.isEmpty(station)){
                            return AjaxResult.error("AGV任务需要选择站台");
                        }
                        AjaxResult ajaxResult1=acsService.TaskModel(station, task.getId());
                        if(ajaxResult1.hasErr()){
                            return ajaxResult1;
                        }
                        //task=this.updateTaskRelease(task);
                        if(task.getType().intValue() == 900){
                            this.completeTask(task);
                        }
                    }
                    break;
                case "QG":
                    orderAssignApiService.taskAssign(task);
                    task=this.updateTaskRelease(task);
                    break;
            }

        }
        return AjaxResult.success("执行下发任务成功", task);
    }

    public TaskHeader updateTaskRelease(TaskHeader task){
            //修改任务头表
            task.setId(task.getId());
            task.setStatus(QuantityConstant.TASK_STATUS_RELEASE);
            task.setStartPickDateTime(new Date());   //生成时间
            task.setLastUpdated(new Date());
            task.setLastUpdatedBy(ShiroUtils.getLoginName());
            taskHeaderService.saveOrUpdate(task);
            //修改任务明细状态
            LambdaQueryWrapper<TaskDetail> lambdaWrapper = Wrappers.lambdaQuery();
            lambdaWrapper.eq(TaskDetail::getTaskId, task.getId());
            List<TaskDetail> taskDetailList = taskDetailService.list(lambdaWrapper);
            List<TaskDetail> taskDetails = new ArrayList<>();
            for (TaskDetail item : taskDetailList) {
                item.setStatus(QuantityConstant.TASK_STATUS_RELEASE);
                item.setLastUpdated(new Date());
                item.setLastUpdatedBy(ShiroUtils.getLoginName());
                item.setProcessStamp("100");
                taskDetails.add(item);
                //盘点执行修改盘点单据状态为10
                if (task.getTaskType().equals(QuantityConstant.TASK_TYPE_CYCLECOUNT)) {
                    cycleCountDetailService.updataDetailStatus(item.getBillDetailId(), QuantityConstant.CYCLECOUNT_STATUS_EXECUTING);
                }
            }
            if (taskDetails != null && taskDetails.size() > 0) {
                if (!taskDetailService.saveOrUpdateBatch(taskDetails)) {
                    throw new ServiceException("更新任务明细失败");
                }
            }

        return task;
    }

    /**空容器入库*/
    @Transactional
    public AjaxResult createEmptyIn(String containerCode) {
        // 校验托盘
        Container container = new Container();
        String warehouseCode = "CS0001";
        container = containerService.getContainerByCode(containerCode,warehouseCode);
        if(container==null) {
            return AjaxResult.error("容器不存在");
        }
        if (StringUtils.isNotEmpty(container.getLocationCode()))  {
            return AjaxResult.error("容器已在库位[" + container.getLocationCode() + "]上");
        }

        //判断托盘是否已经存在任务
        Integer taskCount = taskHeaderMapper.UncompleteCount(containerCode,warehouseCode);
        if (taskCount != null && taskCount.intValue() > 0)  {
            return AjaxResult.error("容器已存在任务");
        }

        LambdaQueryWrapper<Location> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Location::getWarehouseCode, "CS0001");
        queryWrapper.eq(Location::getStatus,QuantityConstant.STATUS_LOCATION_EMPTY);
        queryWrapper.eq(Location::getRoadway, 3);
        queryWrapper.eq(Location::getZoneCode,"LK");
        queryWrapper.eq(Location::getContainerCode,"").or().isNull(Location::getContainerCode);
        queryWrapper.orderByAsc(Location::getIColumn,Location::getIRow);
        queryWrapper.last("limit 1");
        Location location=locationService.getOne(queryWrapper);

        if(location == null){
            return AjaxResult.error("LK库位已用完");
        }
        //创建任务
        TaskHeader task = new TaskHeader();
        task.setWarehouseCode(QuantityConstant.WAREHOUSE_CS);
        task.setCompanyCode(QuantityConstant.COMPANY_CS);
        //这里默认一个0
        task.setPriority(0);
        task.setTaskType(QuantityConstant.TASK_TYPE_EMPTYRECEIPT);
        task.setInternalTaskType(QuantityConstant.TASK_INTENERTYPE_RECEIPT);
        task.setContainerCode(containerCode);
        task.setStatus(1);
        task.setZoneCode(QuantityConstant.ZONE_CODE_TYPE_LK);
        task.setRoadway("3");
        task.setToLocation(location.getCode());
        task.setCreated(new Date());
        task.setCreatedBy("ck");
        task.setCreated(new Date());
        save(task);

        container.setLocationCode(location.getCode());
        containerService.updateById(container);
        location.setContainerCode(container.getCode());
        location.setStatus(QuantityConstant.STATUS_LOCATION_LOCK);
        locationService.updateById(location);
        return AjaxResult.success(task.getId());
    }

    /**
     * WMS完成任务
     */
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult completeTaskByWMS(Integer[] taskIds, String[] weightConvert) {
        AjaxResult  ajaxResult = null;
        for (int i = 0; i < taskIds.length; i++) {
            TaskHeader task = taskHeaderService.getById(taskIds[i]);

            if (task == null) {
                return AjaxResult.error("任务" + taskIds[i] + "未找到,执行中止");
            }
            //如果已完成则不管
            if (task.getStatus().equals(QuantityConstant.TASK_STATUS_COMPLETED)) {
                return AjaxResult.success("任务(" + taskIds[i] + ")任务已经是完成的!");
            }
            //整盘入库,空托入库库位自动分配
            //整盘入库手动完成分配库位,已分配则略过
//            if (task.getTaskType().equals(QuantityConstant.TASK_TYPE_WHOLERECEIPT)
//                    || task.getTaskType().equals(QuantityConstant.TASK_TYPE_EMPTYRECEIPT)) {
//                if (StringUtils.isEmpty(task.getToLocation())) {
            //自动分配库位
//                    AjaxResult ajaxResult = this.setLocationCode(task.getId(), 0);
//                    task.setToLocation((String) ajaxResult.getData());
//                }
//            }
            //如果没有库位不能完成
            if (StringUtils.isEmpty(task.getFromLocation()) && StringUtils.isEmpty(task.getToLocation())) {
                return AjaxResult.error("任务" + task.getId() + "没有库位,执行中止");
            }
            // 获取需要解锁的数据
//            List<LockingWorkOrder> list = lockingWorkOrderService.getLockingWorkOrders(task);
            ajaxResult = this.completeTask(task);
            // 任务完成后进行解锁操作 锁定工作令
//            lockingWorkOrderService.deleteLockingWorkOrders(list);
            if(!ajaxResult.hasErr()){
                backInvokeService.invokeBack(Integer.valueOf(task.getId()));
            }
        }
        return ajaxResult;
    }

    /**
     * 完成任务
     *
     * @param task
     */
    public AjaxResult completeTask(TaskHeader task) {
        int taskType = task.getTaskType().intValue();
        AjaxResult ajaxResult = null;
        //区分任务类型
        switch (taskType) {
            //整盘入库、补充入库
            case QuantityConstant.TASK_TYPE_WHOLERECEIPT:
            case QuantityConstant.TASK_TYPE_SUPPLEMENTRECEIPT:
//                long tim1= System.currentTimeMillis();
                ajaxResult = receiptTaskService.completeReceiptTask(task);
//                long tim2= System.currentTimeMillis();
//                long tim3= tim2-tim1;
//                System.out.println("TaskHeaderServiceImpl.completeTask=="+tim3);
                combineInventory(task);
                break;
            //整盘出库、分拣出库
            case QuantityConstant.TASK_TYPE_WHOLESHIPMENT:
            case QuantityConstant.TASK_TYPE_SORTINGSHIPMENT:
                ajaxResult = shipmentTaskService.completeShipmentTask(task);
                combineInventory(task);
                break;
            //空托入库
            case QuantityConstant.TASK_TYPE_EMPTYRECEIPT:
                ajaxResult = workTaskService.completeEmptyIn(task);
                break;
            //空托出库
            case QuantityConstant.TASK_TYPE_EMPTYSHIPMENT:
                ajaxResult =  workTaskService.completeEmptyOut(task);
                break;
            case QuantityConstant.TASK_TYPE_CYCLECOUNT:
                ajaxResult = cycleCountTaskService.completeCycleCountTask(task);
                break;
            case QuantityConstant.TASK_TYPE_TRANSFER:
                ajaxResult = transferTaskService.completeTransferTask(task);
                break;
            case QuantityConstant.TASK_TYPE_VIEW:
                ajaxResult = workTaskService.completeCheckOutTask(task);
                break;
            case QuantityConstant.TASK_TYPE_MANY_EMPTYRECEIPT:
                ajaxResult = workTaskService.completeManyEmptyIn(task);
                break;
            case QuantityConstant.TASK_TYPE_MANY_EMPTYSHIPMENT:
                ajaxResult = workTaskService.completeManyEmptyOut(task);
                break;
            default:
                throw new ServiceException("不支持的任务类型");
        }
        String containerCode = task.getContainerCode();
        String warehouseCode = task.getWarehouseCode();
        Container container = containerService.getContainerByCode(containerCode, warehouseCode);
        if(container != null) {
            int useCount = container.getUseCount();
            useCount++;
            container.setUseCount(useCount);
            containerService.updateById(container);
        }
        //物料 任务总数
        String materialCode = task.getMaterialCode();
        Material material = materialService.getMaterialByCode(materialCode, warehouseCode);
        if (material != null){
            int useCount = material.getUseCount();
            useCount++;
            material.setUseCount(useCount);
            materialService.updateById(material);
        }
        return ajaxResult;
    }

    /**
     * 根据库位完成任务
     *
     * @param locationCode
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult completeTask(String locationCode) {
        LambdaQueryWrapper<TaskHeader> taskQueryWrapper = Wrappers.lambdaQuery();
        taskQueryWrapper.eq(TaskHeader::getToLocation, locationCode)
                .lt(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_COMPLETED);
        List<TaskHeader> list = this.list(taskQueryWrapper);
        if (list.isEmpty()) {
            throw new ServiceException("库位(" + locationCode + ")没有任务!");
        } else if (list.get(0).getStatus().equals(QuantityConstant.TASK_STATUS_COMPLETED)) {
            //如果已完成则不管
            throw new ServiceException("库位(" + locationCode + ")任务已经完成!");
        }
        TaskHeader taskHeader = list.get(0);
        int taskType = taskHeader.getTaskType().intValue();
        if (taskType == QuantityConstant.TASK_TYPE_WHOLERECEIPT
                || taskType == QuantityConstant.TASK_TYPE_SUPPLEMENTRECEIPT) {
            //入库任务
            return receiptTaskService.completeReceiptTask(taskHeader);
        } else {
            throw new ServiceException("库位(" + locationCode + ")的任务不是上架,不能完成!");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public AjaxResult createReplenishTask(String containerCode, Integer taskStatus) {
        LambdaQueryWrapper<ReceiptContainerHeader> headerQueryWrapper = Wrappers.lambdaQuery();
        headerQueryWrapper.eq(ReceiptContainerHeader::getContainerCode, containerCode)
                .eq(ReceiptContainerHeader::getStatus, QuantityConstant.RECEIPT_CONTAINER_BUILD);

        List<ReceiptContainerHeader> receiptContainerHeaderList = receiptContainerHeaderService.list(headerQueryWrapper);
        if (receiptContainerHeaderList.isEmpty()) {
            throw new ServiceException("该容器没有任务!");
        }
        if (receiptContainerHeaderList.size() > 1) {
            throw new ServiceException("该容器存在多条任务");
        }
        if (receiptContainerHeaderList.get(0).getWarehouseCode() != ShiroUtils.getWarehouseCode()) {
            throw new ServiceException("容器不在当前仓库!");
        }
        LambdaQueryWrapper<ReceiptContainerDetail> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(ReceiptContainerDetail::getReceiptContainerId, receiptContainerHeaderList.get(0).getId());
        List<ReceiptContainerDetail> containerDetailList = receiptContainerDetailService.list(lambdaQueryWrapper);
        ReceiptContainerHeader containerHeader = receiptContainerHeaderList.get(0);
        if (containerDetailList.isEmpty()) {
            throw new ServiceException("没有组盘明细,请先组盘!");
        }
        if (containerHeader.getStatus().equals(QuantityConstant.TASK_STATUS_BUILD)) {
            if (containerHeader.getStatus().intValue() != taskStatus.intValue()) {
                containerHeader.setStatus(taskStatus);
                receiptContainerHeaderService.updateById(containerHeader);
            }
        }
        List<Integer> ids = new ArrayList<>();
        ids.add(containerHeader.getId());
        receiptTaskService.createReceiptTask(ids);
        return AjaxResult.success("成功!");
    }

    /**
     * 移动端根据容器编码获取盘点任务
     *
     * @param containerCode 容器编码
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public List<MobileTask> mobileFindTransferTask(String containerCode) {
        /* 查询该容器未完成的盘点任务明细*/
        LambdaQueryWrapper<TaskDetail> detailLambdaQueryWrapper = Wrappers.lambdaQuery();
        detailLambdaQueryWrapper.eq(TaskDetail::getContainerCode, containerCode)
                .eq(TaskDetail::getTaskType, QuantityConstant.TASK_TYPE_CYCLECOUNT)
                .ne(TaskDetail::getStatus, QuantityConstant.TASK_STATUS_COMPLETED);
        List<TaskDetail> taskDetailList = taskDetailService.list(detailLambdaQueryWrapper);

        /* 获取任务明细中的任务头id*/
        List<Integer> headerIdList = taskDetailList.stream().map(TaskDetail::getTaskId).collect(Collectors.toList());
        List<MobileTask> mobileTasks = new ArrayList<>();

        /* 遍历id查询出盘点任务*/
        for (Integer id : headerIdList) {
            TaskHeader taskHeader = taskHeaderService.getById(id);
            MobileTask mobileTask = new MobileTask();
            mobileTask.setTaskHeader(taskHeader);
            LambdaQueryWrapper<TaskDetail> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(TaskDetail::getTaskId, id)
                    .eq(TaskDetail::getContainerCode, containerCode);
            List<TaskDetail> taskDetails = taskDetailService.list(queryWrapper);
            mobileTask.setTaskDetail(taskDetails);
            mobileTasks.add(mobileTask);
        }
        return mobileTasks;
    }

    /**
     * 容器收货上架
     *
     * @param containerCode
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult createQuickTask(String containerCode) {
        LambdaQueryWrapper<ReceiptContainerHeader> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ReceiptContainerHeader::getContainerCode, containerCode)
                .eq(ReceiptContainerHeader::getStatus, QuantityConstant.RECEIPT_CONTAINER_BUILD)
                .eq(ReceiptContainerHeader::getWarehouseCode, ShiroUtils.getWarehouseCode());
        ReceiptContainerHeader receiptContainerHeader = receiptContainerHeaderService.getOne(queryWrapper);
        if (receiptContainerHeader == null) {
            throw new ServiceException("该容器没有任务!");
        }
        if (receiptContainerHeader.getWarehouseCode() != ShiroUtils.getWarehouseCode()){
            throw new ServiceException("容器不在当前仓库!");
        }

        //pda快速入库,校验托盘是否已经在库位上
        LambdaQueryWrapper<Location> query1 = Wrappers.lambdaQuery();
        query1.eq(Location::getContainerCode, containerCode)
                .last("limit 1");
        Location lc = locationService.getOne(query1);
        if(lc != null){
            throw new ServiceException("托盘已经在库位" + lc.getCode() + "请检查托盘是否编码重复?");
        }
        //pda快速入库,校验托盘是否已经有库存
      /*  LambdaQueryWrapper<InventoryHeader> query = Wrappers.lambdaQuery();
        query.eq(InventoryHeader::getContainerCode, containerCode)
                .last("limit 1");
        if(inventoryHeaderService.getOne(query) != null){
            throw new ServiceException("该容器已有库存数据,请检查是否托盘编码重复?");
        }
*/

        LambdaQueryWrapper<ReceiptContainerDetail> containerDetailQueryWrapper = Wrappers.lambdaQuery();
        containerDetailQueryWrapper.eq(ReceiptContainerDetail::getReceiptContainerId, receiptContainerHeader.getId())
                .eq(ReceiptContainerDetail::getStatus, QuantityConstant.RECEIPT_CONTAINER_BUILD)
                .eq(ReceiptContainerDetail::getContainerCode, containerCode);
        List<ReceiptContainerDetail> containerDetailList = receiptContainerDetailService.list(containerDetailQueryWrapper);
        if (containerDetailList.isEmpty()) {
            throw new SecurityException("没有组盘明细,请先组盘");
        }
        if (receiptContainerHeader.getStatus() == QuantityConstant.RECEIPT_HEADER_BUILD.shortValue()) {
            String ids = String.valueOf(receiptContainerHeader.getId());
            if (StringUtils.isEmpty(ids)) {
                return AjaxResult.error("id不能为空");
            }
            List<Integer> idList = Arrays.asList(Convert.toIntArray(ids));
            if (StringUtils.isEmpty(ids)) {
                return AjaxResult.error("id不能为空");
            }

            Integer maxId = idList.stream().max(Comparator.comparing(Integer::intValue)).orElse(null);

            LambdaQueryWrapper<ReceiptContainerHeader> lambda = Wrappers.lambdaQuery();
            lambda.select(ReceiptContainerHeader::getId)
                    .lt(ReceiptContainerHeader::getStatus, 10)
                    .le(ReceiptContainerHeader::getId, maxId);
            return receiptTaskService.createReceiptTask(idList);
        }
        return AjaxResult.error("生成入库任务失败");
    }

    @Transactional(rollbackFor = Exception.class)
    public void combineInventory(TaskHeader task) {
        String warehouseCode = task.getWarehouseCode();
        LambdaQueryWrapper<InventoryHeader> inventoryHeaderErapper = Wrappers.lambdaQuery();
        inventoryHeaderErapper.eq(InventoryHeader::getWarehouseCode, warehouseCode)
                .eq(InventoryHeader::getLocationCode, task.getToLocation())
                .eq(InventoryHeader::getContainerCode, task.getContainerCode());
        inventoryHeaderErapper.last("limit 1");
        InventoryHeader header = inventoryHeaderService.getOne(inventoryHeaderErapper);
        if (header != null) {
            LambdaQueryWrapper<InventoryDetail> inventory = Wrappers.lambdaQuery();
            inventory.eq(InventoryDetail::getWarehouseCode, warehouseCode)
                    .eq(InventoryDetail::getLocationCode, task.getToLocation())
                    .eq(InventoryDetail::getContainerCode, task.getContainerCode());
            List<InventoryDetail> inventoryDetailList = inventoryDetailService.list(inventory);
            for (int i = 0; i < inventoryDetailList.size() - 1; i++) {
                for (int j = inventoryDetailList.size() - 1; j > i; j--) {
                    InventoryDetail inventoryDetail = inventoryDetailList.get(i);
                    InventoryDetail inventoryDetail2 = inventoryDetailList.get(j);
                    if (inventoryDetail.getMaterialCode().equals(inventoryDetail2.getMaterialCode())
                            && inventoryDetail.getBatch().equals(inventoryDetail2.getBatch())
                            && inventoryDetail.getLot().equals(inventoryDetail2.getLot())
                            && inventoryDetail.getProjectNo().equals(inventoryDetail2.getProjectNo())) {
                        BigDecimal totalQty = inventoryDetailList.get(i).getQty().add(inventoryDetailList.get(j).getQty());
                        inventoryDetailList.get(i).setQty(totalQty);
                        LambdaQueryWrapper<InventoryDetail> wrapper = Wrappers.lambdaQuery();
                        wrapper.eq(InventoryDetail::getId, inventoryDetailList.get(i).getId());
                        inventoryDetailService.update(inventoryDetailList.get(i), wrapper);
                        LambdaQueryWrapper<InventoryDetail> wrapper2 = Wrappers.lambdaQuery();
                        wrapper2.eq(InventoryDetail::getId, inventoryDetailList.get(j).getId());
                        inventoryDetailService.remove(wrapper2);
                        inventoryDetailList.remove(j);
                    }
                }
            }
            BigDecimal totalQty = new BigDecimal(0);
            int totalLines = 0;
            for (InventoryDetail inventoryDetail : inventoryDetailList) {
                totalQty = totalQty.add(inventoryDetail.getQty());
                totalLines++;
            }
            header.setTotalQty(totalQty);
            header.setTotalLines(totalLines);
            header.setContainerStatus(QuantityConstant.STATUS_CONTAINER_SOME);
            LambdaQueryWrapper<InventoryHeader> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(InventoryHeader::getId, header.getId());
            inventoryHeaderService.update(header, wrapper);
        }
    }

    /**
     * 移动端创建入库任务
     *
     * @param containerCode  容器编码
     * @param sourceLocation 目的库位
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult mobileCreateReceiptTask(String containerCode, String sourceLocation) {
        LambdaQueryWrapper<ReceiptContainerHeader> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ReceiptContainerHeader::getContainerCode, containerCode)
                .eq(ReceiptContainerHeader::getStatus, 0);
        ReceiptContainerHeader receiptContainerHeader = receiptContainerHeaderService.getOne(queryWrapper);
        if (receiptContainerHeader == null) {
            throw new ServiceException("该容器没有任务!");
        }
        if (receiptContainerHeader.getWarehouseCode().equals(ShiroUtils.getWarehouseCode())) {
            throw new ServiceException("容器不在当前仓库!");
        }
        List<Integer> idList = new ArrayList<>();
        idList.add(receiptContainerHeader.getId());
        receiptTaskService.createReceiptTask(idList);

        return AjaxResult.success(receiptContainerHeader);
    }

    /**
     * 自动空托出库
     */
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult createAutoEmptyOut(String warehouseCode) {
        /*先查询容器表,选中空托盘,再查询库存核实*/
        //该容器中有库位信息,并且状态是空
        List<Location> locationsList = locationService.selectContainerEmpty(warehouseCode);
        if (locationsList.size() == 0) {
            throw new ServiceException("立库中没有空容器!");
        }
        //根据入库顺序正序排列取第一个
        Location location = locationsList.get(0);
        //反查库位
        Container containerTmp = new Container();
        containerTmp.setWarehouseCode(location.getWarehouseCode());
        containerTmp.setCode(location.getContainerCode());
        LambdaQueryWrapper<Container> containerLambda = Wrappers.lambdaQuery(containerTmp);
        Container container = containerService.getOne(containerLambda);
        if (container == null) {
            throw new ServiceException("选中的库位容器错误,请确认库位和容器!");
        }
        //生成空容器出库任务
        inventoryHeaderService.createEmptyOut(container.getCode(), location.getCode());
        return AjaxResult.success("空容器出库任务已下发!", container.getCode());
    }

    /**
     * 自动分配库位
     *
     * @param taskId 任务号
     * @param high   1是高库位,否则低库位
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult setLocationCode(Integer taskId, Integer high) {
        TaskHeader taskHeader = this.getById(taskId);
        if (taskHeader == null) {
            throw new ServiceException("找不到id为" + taskId + "的任务!");
        }
        if (StringUtils.isNotEmpty(taskHeader.getToLocation())) {
            return AjaxResult.success("任务已经有目的库位,不需要再分配");
        }

        LambdaQueryWrapper<Location> locationLambdaQueryWrapper = Wrappers.lambdaQuery();
        locationLambdaQueryWrapper.eq(Location::getWarehouseCode, ShiroUtils.getWarehouseCode())
                .eq(Location::getContainerCode, "")
                .eq(Location::getStatus, QuantityConstant.STATUS_LOCATION_EMPTY)
                .eq(Location::getDeleted, false);

        List<Location> locations = locationService.list(locationLambdaQueryWrapper);
        if (locations.size() == 0) {
            throw new ServiceException("没有空闲库位!");
        }
        //随机取库位
        Random rand = new Random();
        Location location = locations.get(rand.nextInt(locations.size()));
        if (location == null) {
            throw new ServiceException("库位分配错误!");
        }
        //锁定库位
        locationService.updateStatus(location.getCode(), QuantityConstant.STATUS_LOCATION_LOCK);
        //给组盘分配库位

        int internalTaskType = taskHeader.getInternalTaskType();
        if (internalTaskType == QuantityConstant.TASK_TYPE_WHOLERECEIPT || internalTaskType == QuantityConstant.TASK_TYPE_SUPPLEMENTRECEIPT) {
            ReceiptContainerHeader receiptContainerHeader = new ReceiptContainerHeader();
            receiptContainerHeader.setId(taskHeader.getAllocationHeadId());
            receiptContainerHeader.setToLocation(location.getCode());
            LambdaQueryWrapper<ReceiptContainerHeader> receiptContainerHeaderlLambdaQueryWrapper = Wrappers.lambdaQuery(receiptContainerHeader);
            receiptContainerHeaderService.update(receiptContainerHeader, receiptContainerHeaderlLambdaQueryWrapper);
            //给子任务分配库位
            TaskDetail condition = new TaskDetail();
            condition.setWarehouseCode(ShiroUtils.getWarehouseCode());
            condition.setTaskId(taskHeader.getId());
            LambdaQueryWrapper<TaskDetail> taskDetailLambdaQueryWrapper = Wrappers.lambdaQuery(condition);
            List<TaskDetail> taskDetailList = taskDetailService.list(taskDetailLambdaQueryWrapper);
            if (taskDetailList != null && taskDetailList.size() > 0) {
                for (TaskDetail taskDetail : taskDetailList) {
                    if (taskDetail != null) {
                        taskDetail.setToLocation(location.getCode());
                        taskDetailService.update(taskDetail, taskDetailLambdaQueryWrapper);
                    }
                }
            }
        }
        //给任务分配库位
        taskHeader.setToLocation(location.getCode());
        LambdaQueryWrapper<TaskHeader> taskHeaderLambdaQueryWrapper = Wrappers.lambdaQuery(taskHeader);
        this.update(taskHeader, taskHeaderLambdaQueryWrapper);
        return AjaxResult.success("生成库位成功", location.getCode());

    }

    public int getUncompleteTaskInNear(Location location) {
        Location location1 = locationService.getNear(location);
        if (location1 == null) {
            return 0;
        }
        String locationCode = location1.getCode();
        LambdaQueryWrapper<TaskHeader> taskHeaderLambdaQueryWrapper = Wrappers.lambdaQuery();
        taskHeaderLambdaQueryWrapper.eq(TaskHeader::getToLocation, locationCode)
                .lt(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_COMPLETED);
        List<TaskHeader> taskHeaderList = taskHeaderService.list(taskHeaderLambdaQueryWrapper);
        if (taskHeaderList == null || taskHeaderList.size() == 0) {
            taskHeaderLambdaQueryWrapper = Wrappers.lambdaQuery();
            taskHeaderLambdaQueryWrapper.eq(TaskHeader::getFromLocation, locationCode)
                    .lt(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_COMPLETED);
            taskHeaderList = taskHeaderService.list(taskHeaderLambdaQueryWrapper);
            if (taskHeaderList == null || taskHeaderList.size() == 0) {
                return 0;
            }
        }
        return taskHeaderList.size();
    }

    public List<TaskHeader> remoteList() {
        LambdaQueryWrapper<TaskHeader> wrapper = Wrappers.lambdaQuery();
        wrapper.ge(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_RELEASE)
                .lt(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_COMPLETED);
        return list(wrapper);
    }

    public List<TaskHeader> getUnCompleteTaskList()  {
        LambdaQueryWrapper<TaskHeader> taskHeaderLambdaQueryWrapper = Wrappers.lambdaQuery();
        taskHeaderLambdaQueryWrapper.lt(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_COMPLETED);
        List<TaskHeader> taskHeaderList = taskHeaderService.list(taskHeaderLambdaQueryWrapper);
        return taskHeaderList;
    }

    public boolean prioritymax(String ids) {
        String[] idArray = Convert.toStrArray(ids);
        LambdaQueryWrapper<TaskHeader> wrapper = Wrappers.lambdaQuery();
        wrapper.orderByDesc(TaskHeader::getPriority).ne(TaskHeader::getStatus,
                QuantityConstant.TASK_STATUS_COMPLETED);//.last("limit 1");
        List<TaskHeader> taskHeaders = baseMapper.selectList(wrapper);
        if(taskHeaders.size()<1)
        {
            return false;
        }
        int priority = taskHeaders.get(0).getPriority() + 1;
        boolean result = false;
        for (String s : idArray) {
            for (int x = 0; x < taskHeaders.size(); x++) {
                if (s.equals(String.valueOf(taskHeaders.get(x).getId()))) {
                    result = setPriority(s, priority);
                    if(result) {
                        TaskHeader taskHeader = new TaskHeader();
                        taskHeader.setId(Integer.parseInt(s));
                        taskHeader.setPriority(priority);
                        updateById(taskHeader);
                        //4、发送数据
                    }
                    result = true;
                }
            }

        }
        return result;
    }


    public boolean prioritymin(String ids) {
        String[] idArray = Convert.toStrArray(ids);
        String a = "";
        LambdaQueryWrapper<TaskHeader> wrapper = Wrappers.lambdaQuery();
        wrapper.orderByAsc(TaskHeader::getPriority).ne(TaskHeader::getStatus,
                QuantityConstant.TASK_STATUS_COMPLETED);//.last("limit 1");
        List<TaskHeader> taskHeaders = baseMapper.selectList(wrapper);
        boolean result = false;
        if(taskHeaders.size()<1)
        {
            return result;
        }
        int i = taskHeaders.get(0).getPriority() - 1;
        for (String s : idArray) {
            for (int x = 0; x < taskHeaders.size(); x++) {
                if (s.equals("" + taskHeaders.get(x).getId())) {
                    result = setPriority(s,i);
                    if(result){
                        TaskHeader taskHeader = new TaskHeader();
                        taskHeader.setId(Integer.parseInt(s));
                        taskHeader.setPriority(i);
                        updateById(taskHeader);
                    }
                }
            }
        }
        return result;
    }

    public TaskHeader getTaskHeaderByLocation(String locationCode) {
        TaskHeader taskHeader = null;
        LambdaQueryWrapper<TaskHeader> taskHeaderLambdaQueryWrapper = Wrappers.lambdaQuery();
        taskHeaderLambdaQueryWrapper.eq(TaskHeader::getFromLocation, locationCode)
                .lt(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_COMPLETED);
        taskHeader = getOne(taskHeaderLambdaQueryWrapper);
        if(taskHeader == null) {
            taskHeaderLambdaQueryWrapper = Wrappers.lambdaQuery();
            taskHeaderLambdaQueryWrapper.eq(TaskHeader::getToLocation, locationCode)
                    .lt(TaskHeader::getStatus, QuantityConstant.TASK_STATUS_COMPLETED);
            taskHeader = getOne(taskHeaderLambdaQueryWrapper);
        }
        return taskHeader;
    }

    private boolean setPriority(String id, int priority) {
        TaskHeader taskHeader = taskHeaderService.getById(id);
        String warehouseCode = taskHeader.getWarehouseCode();
        String containerCode = taskHeader.getContainerCode();
        Container container = containerService.getContainerByCode(containerCode, warehouseCode);
        ContainerType containerType = containerTypeService.getContainerTypeByCode(
                container.getContainerType(), warehouseCode);
        String url = addressService.selectAddress(QuantityConstant.ADDRESS_WCS_TASK_PRIORITY_CHANGE, warehouseCode
                , containerType.getArea());
        WcsTask wcsTask = new WcsTask();
        wcsTask.setTaskNo(id);
        wcsTask.setPriority(priority);
        String jsonParam = JSON.toJSONString(wcsTask);
        System.out.println(jsonParam);
        ResponseEntity<JSONObject> result = RestUtil.request_post(url, warehouseCode, jsonParam);
        if (result != null && result.getBody() != null) {
            String code = result.getBody().getString("code");
            String msg = result.getBody().getString("msg");
            if (HttpConstant.isSuccess(Integer.parseInt(code))) {
                return false;
            }
        } else {
            throw new ServiceException("接口地址错误或返回为空");
        }
        String data = result.getBody().getString("data");
        AjaxResult ajaxResult = JSON.parseObject(data, AjaxResult.class);
        if (HttpConstant.isSuccess(ajaxResult.getCode())) {
            return false;
        }
        return true;
    }
    public TaskHeader createTaskByReceipt(ReceiptContainerHeader receiptContainerHeader){

        TaskHeader task = new TaskHeader();
        task.setAllocationHeadId(receiptContainerHeader.getId());
        task.setInternalTaskType(QuantityConstant.TASK_INTENERTYPE_RECEIPT);
        task.setWarehouseCode(receiptContainerHeader.getWarehouseCode());
        task.setCompanyCode(receiptContainerHeader.getCompanyCode());
        task.setStatus(QuantityConstant.TASK_STATUS_BUILD);
        task.setTaskType(receiptContainerHeader.getTaskType());
        task.setFromLocation(receiptContainerHeader.getFromLocation());
        if(receiptContainerHeader.getToLocation() != null){
            task.setToLocation(receiptContainerHeader.getToLocation());
        }
       /* Location location = locationService.getLocationByCode(
                task.getToLocation(), ShiroUtils.getWarehouseCode());
        if(location != null) {
            task.setZoneCode(location.getZoneCode());
        }*/
        task.setContainerCode(receiptContainerHeader.getContainerCode());
        Container container = containerService.getContainerByCode(
                task.getContainerCode());
        if(container != null) {
            task.setZoneCode(container.getZoneCode());
        }

        task.setRecvDock(receiptContainerHeader.getRecvDock());
        //东厂默认分配站台 KS0001 LK
        if(container.getWarehouseCode().equals("KS0001")&&container.getZoneCode().equals(QuantityConstant.ZONE_CODE_TYPE_LK)){
            Station station = stationService.getOne(
                    new LambdaQueryWrapper<Station>()
                            .eq(Station::getWarehouseCode, "KS0001")
                            .eq(Station::getArea, 5)
                            .eq(Station::getRoadway,1)
                            .last("limit 1"));
            if (station != null) {
                task.setPort(station.getCode());
            }
        }else {
            task.setPort(receiptContainerHeader.getPort());
        }
        return task;

    }

    public void handleBack(Integer taskId){
        backInvokeService.invokeBack(taskId);
    }

    @Transactional(rollbackFor = Exception.class)
    public AjaxResult shipmentrelax(String[] ids){
        for(String t:ids) {
             List<InventoryDetail> inventoryDetails = inventoryDetailService.list(new LambdaQueryWrapper<InventoryDetail>()
                     .eq(InventoryDetail::getInventoryHeaderId,Integer.valueOf(t)));

            ShipmentHeader shipmentHeader = new ShipmentHeader();
            String code = shipmentHeaderService.createCode("PO");
            shipmentHeader.setUWarehouseCode("");
            shipmentHeader.setCompanyCode(ShiroUtils.getCompanyCode());
            shipmentHeader.setWarehouseCode(ShiroUtils.getWarehouseCode());
            shipmentHeader.setShipmentType("PO");
            shipmentHeader.setStation("102");
            shipmentHeader.setRemark("");
            shipmentHeader.setSourceCode("");
            shipmentHeader.setEnable(1);
            shipmentHeader.setCode(code);
            shipmentHeader.setId(null);
            shipmentHeader.setCreated(new Date());
            shipmentHeader.setCreatedBy("ck");
            shipmentHeaderService.save(shipmentHeader);
            BigDecimal bigDecimal = new BigDecimal(0);
            ShipmentDetail shipmentDetail = new ShipmentDetail();
            for (InventoryDetail i : inventoryDetails) {
                Material material = materialService.getMaterialByCode(i.getMaterialCode());
                if (material == null) {
                    Material material1 = new Material();
                    material1.setId(null);
                    material1.setCode(i.getMaterialCode());
                    material1.setName(i.getMaterialCode());
                    material1.setWarehouseCode(ShiroUtils.getWarehouseCode());
                    material1.setDeleted(false);
                    material1.setCompanyCode(ShiroUtils.getCompanyCode());
                    material1.setCreated(new Date());
                    material1.setType("");
                    material1.setBarcode("");
                    material1.setLastUpdated(new Date());
                    material1.setLastUpdatedBy("ck");
                    material1.setCreatedBy("ck");
                    materialService.save(material1);
                    shipmentDetail.setMaterialName(material1.getName());
                    shipmentDetail.setMaterialId(material1.getId());
                } else {
                    shipmentDetail.setMaterialName(material.getName());
                    shipmentDetail.setMaterialCode(material.getCode());
                }
                shipmentDetail.setShipmentId(shipmentHeader.getId());
                shipmentDetail.setShipmentCode(code);
                shipmentDetail.setCompanyId(2);
                shipmentDetail.setCompanyCode(ShiroUtils.getCompanyCode());
                shipmentDetail.setWarehouseId(1);
                shipmentDetail.setWarehouseCode(ShiroUtils.getWarehouseCode());
                shipmentDetail.setMaterialCode(i.getMaterialCode());
                shipmentDetail.setQty(i.getQty());
                shipmentDetail.setInventorySts(QuantityConstant.GOOD);
                shipmentDetail.setMoCode(i.getMoCode());
                shipmentDetailService.save(shipmentDetail);
                bigDecimal = bigDecimal.add(i.getQty());
            }
            shipmentHeader.setTotalLines(inventoryDetails.size());
            shipmentHeader.setTotalQty(bigDecimal);
            shipmentHeaderService.updateById(shipmentHeader);
        }
        return AjaxResult.success();
    }

    @Transactional
    public AjaxResult createTransferTask(String sourceLocation, Integer companyId, String companyCode) {
        Location location = locationService.getLocationByCode(sourceLocation,"CS0001");
        if(location==null){
            return AjaxResult.error("源库位:"+sourceLocation+"未找到");
        }
        if(!location.getStatus().equals("empty")){
            return AjaxResult.error("源库位:"+sourceLocation+"状态非空闲");
        }
        if(StringUtils.isEmpty(location.getContainerCode())){
            return AjaxResult.error("源库位:"+sourceLocation+"不存在托盘");
        }
        if(!location.getZoneCode().equals("LK")){
            return AjaxResult.error("该库位:"+sourceLocation+"不是立库库位");
        }

        if(location.getZoneCode().equals("LK")){
            TaskHeader task =new TaskHeader();
            task.setContainerCode(location.getContainerCode());
            task.setStatus(10);
            task =transferTaskService.selectFirstEntity(task);
            if(task!=null){
                return AjaxResult.error(location.getContainerCode()+"该容器已有任务");
            }
        }
        //这里增加组盘校验,如果此托盘存在未完成的组盘数据,则不能移库
        //校验入库组盘
        int count1 = inventoryHeaderService.getUncompleteReceiptContainer(sourceLocation,"CS0001");
        if(count1>0){
            return AjaxResult.error("源库位:"+sourceLocation+"存在入库组盘,不能移库");
        }
        int count2 = inventoryHeaderService.getUncompleteShipmentContainer(sourceLocation,"CS0001");
        if(count2>0){
            return AjaxResult.error("源库位:"+sourceLocation+"存在出库组盘,不能移库");
        }
        Location loc=null;
        int line;
        int layer=(int)(Math.random()*10);
        if (location.getContainerCode().startsWith("L")||location.getContainerCode().startsWith("B")) {
            if(location.getIColumn()<=8){
                line=(int)(Math.random()*9+8);
            }else {
                line=(int)(Math.random()*8);
            }
            loc = locationService.getLocationFarAway(3, line,layer);
        }
        if(loc ==null){
            if(location.getContainerCode().startsWith("S")){
                loc = locationService.getLocationOfRule(2);
            }else if(location.getContainerCode().startsWith("M")){
                loc = locationService.getLocationOfRule(1);
            }else {
                loc = locationService.getLocationOfRule(3);
            }
        }
        if(loc == null){
            return AjaxResult.error("立库库位已用完,无法移库");
        }
        List<InventoryDetail> list = inventoryDetailService.list(new LambdaQueryWrapper<InventoryDetail>()
                .eq(InventoryDetail::getContainerCode, location.getContainerCode())
                .eq(InventoryDetail::getLocationCode, location.getCode())
                .eq(InventoryDetail::getZoneCode, location.getZoneCode())
                .eq(InventoryDetail::getWarehouseCode, location.getWarehouseCode()));
        //移库前记录 容器状态
        Container container = containerService.getContainerByCode(location.getContainerCode(), location.getWarehouseCode());
        container.setLastStatus(container.getStatus());
        containerService.updateById(container);

        TaskHeader task = new TaskHeader();
        task.setWarehouseId(1);
        task.setWarehouseCode("CS0001");
        task.setCompanyId(2);//获取第一个货主
        task.setCompanyCode(QuantityConstant.COMPANY_CS);
        //这里默认一个0
        task.setPriority(0);
        task.setTaskType(QuantityConstant.TASK_TYPE_TRANSFER);
        task.setRoadway(loc.getRoadway());
        //对移库来说,这个没啥用
        task.setPort(null);
        task.setZoneCode(location.getZoneCode());
        task.setContainerCode(location.getContainerCode());
        task.setStatus(1);
        task.setCreated(new Date());
        task.setFromLocation(sourceLocation);
        task.setToLocation(loc.getCode());
        task.setCreated(new Date());
        task.setCreatedBy("ck");
        save(task);
        List<TaskDetail> taskDetails = new ArrayList<>();
        for (InventoryDetail inventoryDetail : list) {
            TaskDetail taskDetail =new TaskDetail();
            taskDetail.setTaskId(task.getId());
            taskDetail.setWarehouseCode(task.getWarehouseCode());
            taskDetail.setCompanyCode(task.getCompanyCode());
            taskDetail.setMaterialCode(inventoryDetail.getMaterialCode());
            taskDetail.setMaterialName(inventoryDetail.getMaterialName());
            taskDetail.setAllocationId(inventoryDetail.getId());
            taskDetail.setQty(inventoryDetail.getQty());
            taskDetail.setContainerCode(task.getContainerCode());
            taskDetail.setFromLocation(sourceLocation);
            taskDetail.setToLocation(loc.getCode());
            taskDetail.setTaskType(QuantityConstant.TASK_TYPE_TRANSFER);
            taskDetail.setStatus(task.getStatus());
            taskDetail.setLastUpdatedBy("ck");
            taskDetail.setProjectNo(inventoryDetail.getProjectNo());
            taskDetails.add(taskDetail);
        }
        boolean b = taskDetailService.saveBatch(taskDetails);
        if(!b){
            throw new ServiceException("保存库位失败");
        }
        //更新货位状态为预定
        location.setStatus("lock");
        loc.setStatus("lock");
        loc.setUserDef1("0");
        locationService.updateById(location);
        locationService.updateById(loc);
        return AjaxResult.success(task);
    }




    public AjaxResult createTransferTasks(String sourceLocation, String targetLocation) {
        String warehouseCode = QuantityConstant.WAREHOUSE_CS;
        Location temp1 = new Location();
        temp1.setCode(sourceLocation);
        Location location = locationService.selectFirstEntity(temp1);
        Location temp2 = new Location();
        temp2.setCode(targetLocation);
        Location location2 = locationService.selectFirstEntity(temp2);

        if(location==null){
            return AjaxResult.error("源库位:"+sourceLocation+"未找到");
        }
        if(!location.getStatus().equals("empty")){
            return AjaxResult.error("源库位:"+sourceLocation+"状态非空闲");
        }
        if(StringUtils.isEmpty(location.getContainerCode())){
            return AjaxResult.error("源库位:"+sourceLocation+"不存在托盘");
        }

        if(StringUtils.isNotEmpty(location2.getContainerCode())){
            return AjaxResult.error("目标库位:"+targetLocation+" 已有托盘 " + location2.getContainerCode());
        }

        if(!location.getZoneCode().equals("LK")){
            return AjaxResult.error("该库位:"+sourceLocation+"不是立库库位");
        }

        if(location.getZoneCode().equals("LK")){
            TaskHeader task =new TaskHeader();
            task.setContainerCode(location.getContainerCode());
            task.setStatus(0);
            task =transferTaskService.selectFirstEntity(task);
            if(task!=null){
                return AjaxResult.error(location.getContainerCode()+"该容器已有任务");
            }
        }
        //这里增加组盘校验,如果此托盘存在未完成的组盘数据,则不能移库
        //校验入库组盘
        int count1 = inventoryHeaderService.getUncompleteReceiptContainer(sourceLocation,warehouseCode);
        if(count1>0){
            return AjaxResult.error("源库位:"+sourceLocation+"存在入库组盘,不能移库");
        }
        int count2 = inventoryHeaderService.getUncompleteShipmentContainer(sourceLocation,warehouseCode);
        if(count2>0){
            return AjaxResult.error("源库位:"+sourceLocation+"存在出库组盘,不能移库");
        }
        List<InventoryDetail> list = inventoryDetailService.list(new LambdaQueryWrapper<InventoryDetail>()
                .eq(InventoryDetail::getContainerCode, location.getContainerCode())
                .eq(InventoryDetail::getLocationCode, location.getCode())
                .eq(InventoryDetail::getZoneCode, location.getZoneCode())
                .eq(InventoryDetail::getWarehouseCode, location.getWarehouseCode()));

        TaskHeader task = new TaskHeader();
        task.setWarehouseCode(warehouseCode);
        task.setCompanyCode(QuantityConstant.COMPANY_CS);
        //这里默认一个0
        task.setPriority(0);
        task.setTaskType(QuantityConstant.TASK_TYPE_TRANSFER);
        //对移库来说,这个没啥用
        task.setPort(null);
        task.setRoadway(location.getRoadway());
        task.setZoneCode(location.getZoneCode());
        task.setContainerCode(location.getContainerCode());
        task.setStatus(1);
        task.setFromLocation(sourceLocation);
        task.setToLocation(targetLocation);
        task.setCreated(new Date());
        task.setCreatedBy("ck");
        save(task);
        List<TaskDetail> taskDetails = new ArrayList<>();
        for (InventoryDetail inventoryDetail : list) {
            TaskDetail taskDetail =new TaskDetail();
            taskDetail.setTaskId(task.getId());
            taskDetail.setWarehouseCode(task.getWarehouseCode());
            taskDetail.setCompanyCode(task.getCompanyCode());
            taskDetail.setMaterialCode(inventoryDetail.getMaterialCode());
            taskDetail.setMaterialName(inventoryDetail.getMaterialName());
            taskDetail.setAllocationId(inventoryDetail.getId());
            taskDetail.setQty(inventoryDetail.getQty());
            taskDetail.setContainerCode(task.getContainerCode());
            taskDetail.setFromLocation(sourceLocation);
            taskDetail.setToLocation(targetLocation);
            taskDetail.setTaskType(QuantityConstant.TASK_TYPE_TRANSFER);
            taskDetail.setStatus(task.getStatus());
            taskDetail.setLastUpdatedBy("ck");
            taskDetail.setProjectNo(inventoryDetail.getProjectNo());
            taskDetails.add(taskDetail);
        }
        boolean b = taskDetailService.saveBatch(taskDetails);
        if(!b){
            throw new ServiceException("保存库位失败");
        }
        //更新货位状态为预定
        location.setStatus(QuantityConstant.STATUS_LOCATION_LOCK);
        location2.setStatus(QuantityConstant.STATUS_LOCATION_LOCK);
        location2.setUserDef1("0");
        locationService.updateById(location);
        locationService.updateById(location2);
        return AjaxResult.success(task);
    }

    public List<TaskHeader> autoCompleteDX() {
        return taskHeaderMapper.autoCompleteDX();
    }

    //补充入库
    public AjaxResult replenIn(String containerCode) {
        Container container = new Container();
        container.setCode(containerCode);
        container = containerService.selectFirstEntity(container);
        Assert.notNull(container,"容器输入错误");
        Assert.notNull(container.getLocationCode(),"容器不在库位上");


        TaskHeader task4 =new TaskHeader();
        task4.setContainerCode(container.getCode());
        task4.setStatus(10);
        task4 =taskHeaderService.selectFirstEntity(task4);
        if(task4!=null){
            throw new ServiceException("该容器已有任务,且已下发");
        }

        TaskHeader task2 =new TaskHeader();
        task2.setContainerCode(container.getCode());
        task2.setStatus(20);
        task2 =taskHeaderService.selectFirstEntity(task2);
        if(task2!=null){
            throw new ServiceException("该容器已有任务,且已下发");
        }

        TaskHeader task3 =new TaskHeader();
        task3.setContainerCode(container.getCode());
        task3.setStatus(30);
        task3 =taskHeaderService.selectFirstEntity(task3);
        if(task3!=null){
            throw new ServiceException("该容器已有任务,且已下发");
        }

        TaskHeader condition =new TaskHeader();
        condition.setContainerCode(container.getCode());
        condition.setStatus(1);
        condition =this.selectFirstEntity(condition);
        if(condition!=null && condition.getType().intValue()>200){
            throw new ServiceException("该容器已有其他任务,无法组盘");
        }

        TaskHeader task1 =new TaskHeader();
        task1.setStatus(100);
        task1.setContainerCode(container.getCode());
        task1 = this.selectByUser(task1);

        if(task1!= null && !task1.getCreatedBy().equals(ShiroUtils.getLoginName())){
            throw new ServiceException("该容器已被其他操作员使用");
        }


        Location location = new Location();
        location.setCode(container.getLocationCode());
        location = locationService.selectFirstEntity(location);
        Assert.notNull(location,"容器绑定的库位不存在");
        if(QuantityConstant.STATUS_LOCATION_LOCK.equals(location.getStatus())){
            throw new ServiceException("库位已锁定");}

        ReceiptContainerHeader receiptContainerHeader = new ReceiptContainerHeader();
//        receiptContainerHeader.setZoneCode(location.getZoneCode());
        receiptContainerHeader.setContainerCode(container.getCode());
        receiptContainerHeader.setToLocation(location.getCode());
        receiptContainerHeader.setWarehouseCode(location.getWarehouseCode());
        receiptContainerHeader.setCompanyCode(container.getCompanyCode());
        receiptContainerHeader.setTaskType(QuantityConstant.TASK_TYPE_SUPPLEMENTRECEIPT);
        receiptContainerHeader.setStatus(QuantityConstant.TASK_STATUS_RELEASE);
        receiptContainerHeader.setCreated(new Date());
        receiptContainerHeader.setCreatedBy(ShiroUtils.getLoginName());

        Assert.update(receiptContainerHeaderService.save(receiptContainerHeader),"生成任务失败");


        //写入任务主表
        TaskHeader task = new TaskHeader();
//        task.set(container.getGoodsShlfNo());
        task.setZoneCode(location.getZoneCode());
        task.setWarehouseCode(location.getWarehouseCode());
        task.setCompanyCode(container.getCompanyCode());
        task.setPriority(10);
        task.setTaskType(QuantityConstant.TASK_TYPE_SUPPLEMENTRECEIPT);
        task.setAllocationHeadId(receiptContainerHeader.getId());
        task.setContainerCode(containerCode);
        task.setRoadway(location.getRoadway());
        task.setFromLocation(location.getCode());
        task.setToLocation(location.getCode());
        task.setStatus(1);
        task.setCreated(new Date());
        task.setCreatedBy(ShiroUtils.getLoginName());
        Assert.update(this.save(task),"生成任务失败");
        //锁定库位状态
        locationService.updateStatus(location.getCode(),"lock");
        return AjaxResult.success(task.getId());
    }


    @Transactional
    public AjaxResult createEmptyOutByInventoryClear(String containerCode) throws Exception {
        Container temp3 = new Container();
        temp3.setCode(containerCode);
        temp3.setWarehouseCode(ShiroUtils.getWarehouseCode());
        Container container = containerService.selectFirstEntity(temp3);
        if(container==null){
            return AjaxResult.error("托盘不存在");
        }

        Location loc = new Location();
        loc.setCode(container.getLocationCode());
        loc = locationService.selectFirstEntity(loc);
        if(loc==null){
            return AjaxResult.error("源货位不存在");
        }
        if(StringUtils.isEmpty(loc.getContainerCode())){
            return AjaxResult.error("源货位没有托盘");
        }
        if(!loc.getStatus().equals("empty")){
            return AjaxResult.error("源货位非空闲");
        }
        if(!loc.getZoneCode().equals(QuantityConstant.ZONECODE_LK) && !loc.getZoneCode().equals(QuantityConstant.ZONECODE_XC)){
            return AjaxResult.error("非立库无法空托出库");
        }
        //更新货位状态
        loc.setStatus("lock");
        locationService.updateById(loc);


        //创建任务
        TaskHeader task = new TaskHeader();
        task.setWarehouseCode(ShiroUtils.getWarehouseCode());
        task.setCompanyCode(container.getCompanyCode());
        //这里默认一个0
        task.setPriority(0);
        task.setTaskType(QuantityConstant.TASK_TYPE_EMPTYSHIPMENT);
        task.setPort("1");
        task.setZoneCode(loc.getZoneCode());
        task.setContainerCode(containerCode);
        task.setStatus(1);
        task.setFromLocation(loc.getCode());
//        task.setDestinationLocation(loc.getCode());
        task.setCreated(DateUtils.getNowDate());
        task.setCreatedBy(ShiroUtils.getLoginName());
        save(task);
        AjaxResult ajaxResult = taskHeaderService.sendTaskToWcs(Convert.toIntArray(task.getId().toString()));
        return AjaxResult.success("成功");
    }

    public List<TaskDetail> selectList(String goodsShelfNo,String shelf,String station) {
        String warehouseCode=ShiroUtils.getWarehouseCode();
        String shelfNo=goodsShelfNo.substring(1,5);
        List<String> companyCodeList=ShiroUtils.getCompanyCodeList();
        return taskHeaderMapper.selectLists(shelfNo,warehouseCode,companyCodeList,shelf,station);
    }
    public List<TaskDetail> selectList(String goodsShelfNo,String station) {
        String warehouseCode=ShiroUtils.getWarehouseCode();
        String shelfNo=goodsShelfNo.substring(1,5);
        List<String> companyCodeList=ShiroUtils.getCompanyCodeList();
        return taskHeaderMapper.selectList1(shelfNo,warehouseCode,companyCodeList,station);
    }

    public List<TaskDetail> selectTaskList(String station) {
        String warehouseCode=ShiroUtils.getWarehouseCode();
        List<String> companyCodeList=ShiroUtils.getCompanyCodeList();
        return taskHeaderMapper.selectTaskLists(warehouseCode,companyCodeList,station);
    }

    public ModelMap deliveryReport(Integer[] ids, ModelMap mmap) {
        List<TaskDetail> list=new ArrayList<TaskDetail>();
        for(Integer id:ids){
            if(id!=null) {
                List<TaskDetail> taskDetails = taskDetailService.list(new LambdaQueryWrapper<TaskDetail>().eq(TaskDetail::getTaskId, id));
                for(TaskDetail item: taskDetails) {
                    Material material =materialService.getMaterialByCode(item.getMaterialCode(),ShiroUtils.getWarehouseCode());
                    // 截取规格型号、名称过长的打印字段
                    if (StringUtils.isNotEmpty(material.getSpec()) && material.getSpec().length() >= 20){
                        String tmep = material.getSpec().substring(0, 20);
                        item.setMaterialSpec(tmep);
                    }else {
                        item.setMaterialSpec(material.getSpec());
                    }
                    if (StringUtils.isNotEmpty(material.getName()) && material.getName().length() >= 18){
                        String temp = material.getName().substring(0, 18);
                        item.setMaterialName(temp);
                    }else {
                        item.setMaterialName(material.getName());
                    }
                    item.setUserDef1(material.getBarcode());
                    Company company= companyService.getOne(new LambdaQueryWrapper<Company>().eq(Company::getCode,item.getCompanyCode()).eq(Company::getWarehouseCode,ShiroUtils.getWarehouseCode()));
                    item.setCompanyName(company.getName());
                    //出库类型
                    if(item.getInternalTaskType()==200){
                        ShipmentHeader shipmentHeader = shipmentHeaderService.getById(item.getBillId());
                        ShipmentDetail shipmentDetail=shipmentDetailService.getById(item.getBillDetailId());
                        if (shipmentHeader != null){
                            item.setBillCode(shipmentHeader.getCode());
                            item.setReferenceCode(shipmentHeader.getSourceCode());
                        }
                        if (shipmentDetail != null){
                            if (StringUtils.isEmpty(shipmentDetail.getMaterialUnit())){
                                item.setQyUnit(String.valueOf(item.getQty().setScale(2, BigDecimal.ROUND_HALF_UP)));
                            }else{
                                item.setQyUnit((item.getQty().setScale(2,BigDecimal.ROUND_HALF_UP))+"/"+shipmentDetail.getMaterialUnit());
                            }
                          //  item.setMoCode(shipmentDetail.getMoCode());
                        }else {
                            item.setQyUnit(String.valueOf(item.getQty().setScale(2, BigDecimal.ROUND_HALF_UP)));
                        }
                        if(item.getBillCode().substring(0,2).equals("SO")){
                           // item.setMoCode(item.getSourceCode());
                        }
                    }else {
                        //入库单
                        ReceiptHeader receiptHeader = receiptHeaderService.getById(item.getBillId());
                        ReceiptDetail receiptDetail=receiptDetailService.getById(item.getBillDetailId());
                        if (receiptDetail != null){
                            if (StringUtils.isEmpty(receiptDetail.getMaterialUnit())){
                                item.setQyUnit(String.valueOf(item.getQty().setScale(2,BigDecimal.ROUND_HALF_UP)));
                            }else{
                                item.setQyUnit((item.getQty().setScale(2,BigDecimal.ROUND_HALF_UP))+"/"+receiptDetail.getMaterialUnit());
                            }

                            //item.setMoCode(receiptDetail.getMoCode());
                        }else {
                            item.setQyUnit(String.valueOf(item.getQty().setScale(2,BigDecimal.ROUND_HALF_UP)));
                        }
                        if (receiptHeader != null){
                            item.setBillCode(receiptHeader.getCode());
                            item.setReferenceCode(receiptHeader.getReferCode());
                        }
                        if(item.getBillCode().substring(0,2).equals("SR")){
                           // item.setMoCode(item.getSourceCode());
                        }
                    }
                }
                list.addAll(taskDetails);
            }
            mmap.put("taskReport", list);
        }
        return mmap;
    }
}