ShipmentApiService.java 32.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
package com.huaheng.api.general.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaheng.api.general.domain.ShipmentDomain;
import com.huaheng.common.constant.HttpConstant;
import com.huaheng.common.constant.QuantityConstant;
import com.huaheng.common.exception.service.ServiceException;
import com.huaheng.common.utils.StringUtils;
import com.huaheng.common.utils.restful.RestUtil;
import com.huaheng.common.utils.security.ShiroUtils;
import com.huaheng.framework.web.domain.AjaxResult;
import com.huaheng.pc.config.address.service.AddressService;
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.customer.service.CustomerServiceImpl;
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.shipmentType.domain.ShipmentType;
import com.huaheng.pc.config.shipmentType.service.ShipmentTypeService;
import com.huaheng.pc.config.station.domain.Station;
import com.huaheng.pc.config.station.service.StationService;
import com.huaheng.pc.config.warehouse.service.WarehouseService;
import com.huaheng.pc.inventory.inventoryDetail.domain.InventoryDetail;
import com.huaheng.pc.inventory.inventoryDetail.service.InventoryDetailService;
import com.huaheng.pc.inventory.inventoryTransaction.domain.InventoryTransaction;
import com.huaheng.pc.inventory.inventoryTransaction.service.InventoryTransactionService;
import com.huaheng.pc.monitor.apilog.service.IApiLogService;
import com.huaheng.pc.rgv.service.RgvService;
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.shipmentDetailHistory.domain.ShipmentDetailHistory;
import com.huaheng.pc.shipment.shipmentDetailHistory.service.ShipmentDetailHistoryService;
import com.huaheng.pc.shipment.shipmentHeader.domain.ShipmentHeader;
import com.huaheng.pc.shipment.shipmentHeader.service.ShipmentHeaderService;
import com.huaheng.pc.shipment.shipmentHeaderHistory.domain.ShipmentHeaderHistory;
import com.huaheng.pc.shipment.shipmentHeaderHistory.service.ShipmentHeaderHistoryService;
import com.huaheng.pc.task.taskHeader.domain.ShipmentTaskCreateModel;
import com.huaheng.pc.task.taskHeader.domain.TaskHeader;
import com.huaheng.pc.task.taskHeader.service.ShipmentTaskService;
import com.huaheng.pc.task.taskHeader.service.TaskHeaderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author ricard
 * @time 19/11/11
 */


@Component
@Transactional
public class ShipmentApiService {

    @Resource
    private StationService stationService;
    @Resource
    private AddressService addressService;
    @Autowired
    private LocationService locationService;
    @Autowired
    private ContainerService containerService;
    @Autowired
    private ShipmentHeaderService shipmentHeaderService;

    @Autowired
    private ShipmentDetailService shipmentDetailService;

    @Autowired
    private WarehouseService warehouseService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private CustomerServiceImpl customerService;

    @Autowired
    private ShipmentTypeService shipmentTypeService;

    @Autowired
    private MaterialService materialService;

    @Resource
    private ShipmentHeaderHistoryService shipmentHeaderHistoryService;

    @Resource
    private ShipmentDetailHistoryService shipmentDetailHistoryService;
    @Resource
    private ShipmentContainerHeaderService shipmentContainerHeaderService;
    @Resource
    ShipmentTaskService shipmentTaskService;

    @Resource
    private InventoryDetailService inventoryDetailService;
    @Resource
    private TaskHeaderService taskHeaderService;

    @Resource
    private InventoryTransactionService inventoryTransactionService;
    @Resource
    private ShipmentApiService shipmentApiService;

    @Resource
    private IApiLogService apiLogService;

    @Resource
    private RgvService rgvService;

    /**
     * 出库单下发
     *
     * @param shipmentDomain
     * @return
     */
    @Transactional
    public AjaxResult shipment(ShipmentDomain shipmentDomain) {

        //1、判断出库主单和子单列是否为空
        ShipmentHeader shipmentHeader = shipmentDomain.getShipmentHeader();
        List<ShipmentDetail> shipmentDetails = shipmentDomain.getShipmentDetails();
        if (shipmentHeader == null) {
            return AjaxResult.error("出库主单为空");
        }
        if (shipmentDetails == null || shipmentDetails.size() < 1) {
            return AjaxResult.error("出库子单为空");
        }

        //2、检查出库主单的合法性
        AjaxResult ajaxResult = checkShipmentHeader(shipmentHeader);
        if (ajaxResult.hasErr()) {
            return AjaxResult.error(ajaxResult.getMsg());
        }
        //3、检查出库明细的合法性
        AjaxResult result = checkShipmentDetail(shipmentDetails);
        if (result.hasErr()) {
            return AjaxResult.error(result.getMsg());
        }

        //4、保存出库主表
        BigDecimal totalQty = new BigDecimal(0);
        for (ShipmentDetail item : shipmentDetails) {
            totalQty = totalQty.add(item.getQty());
        }

        shipmentHeader.setTotalLines(shipmentDetails.size());
        shipmentHeader.setTotalQty(totalQty);
        shipmentHeader.setCreatedBy(QuantityConstant.PLATFORM_MES);
        if (StringUtils.isNotEmpty(shipmentHeader.getShipmentNote())) {
            shipmentHeader.setShipmentNote(shipmentHeader.getShipmentNote());
        }
        if (StringUtils.isNotEmpty(shipmentHeader.getLine())) {
            shipmentHeader.setLine(shipmentHeader.getLine());
        }
        String stack = shipmentHeader.getStack();
        List<String> stackList = Arrays.asList(stack.split(","));
        if (StringUtils.isEmpty(stack)) {
            return AjaxResult.error("出库栈口不能为空");
        }
        //匹配出没有执行任务的栈口
        List<TaskHeader> taskHeaderList = taskHeaderService.list(new LambdaQueryWrapper<TaskHeader>()
                .isNotNull(TaskHeader::getPort)
                .ne(TaskHeader::getStatus, 100));
        List<String> taskPorts = taskHeaderList.stream().map(TaskHeader::getPort).distinct().collect(Collectors.toList());
        List<Station> stationList = stationService.list(new LambdaQueryWrapper<Station>()
                .notIn(StringUtils.isNotEmpty(taskPorts), Station::getCode, taskPorts).in(Station::getCode, stackList));
        List<String> ports = stationList.stream().map(Station::getCode).collect(Collectors.toList());
        if (ports.isEmpty()) {
            return AjaxResult.error("没有空闲出库口");
        }
        String port = ports.get(0);
        //玻布仓分配栈口
        if (StringUtils.isNotEmpty(shipmentHeader.getLineNumber())) {
            //匹配出库口
            port = matchPort(ports, shipmentHeader.getLineNumber());
            if (StringUtils.isBlank(port)) {
                //如果有多个栈口,排除已经执行过的栈口
                AjaxResult result1 = rgvService.excludeStack(ports, port, "shipment");
                if (result1.hasErr()) {
                    return AjaxResult.error(result1.getMsg());
                }
                port = result1.getMsg();
            }

        }
        shipmentHeader.setStack(port);
        shipmentHeader.setWarehouseCode("CS0001");
        shipmentHeader.setCompanyCode("BHF");
        //String shipmentCode = shipmentHeaderService.createCode(shipmentHeader.getShipmentType());
        shipmentHeader.setCode(shipmentHeader.getReferCode());
        shipmentHeader.setFirstStatus(QuantityConstant.SHIPMENT_HEADER_BUILD);//新建
        shipmentHeader.setLastStatus(QuantityConstant.SHIPMENT_HEADER_BUILD);//新建

        if (!shipmentHeaderService.save(shipmentHeader)) {
            throw new ServiceException("保存出库主表失败");
        }


        //5、保存出库子表
        addDetail(shipmentHeader, shipmentDetails, port);


        //自动组盘
        AjaxResult result2 = shipmentContainerHeaderService.autoCombination(shipmentHeader.getCode());
        if (result2.hasErr()) {
            throw new ServiceException("MES下发出库组盘时失败:" + result2.getMsg());
        }

        //生成任务
        List<ShipmentContainerHeader> shipmentContainerHeaders = shipmentContainerHeaderService.list(new LambdaQueryWrapper<ShipmentContainerHeader>()
                .eq(ShipmentContainerHeader::getStatus, QuantityConstant.SHIPMENT_CONTAINER_BUILD));

        for (ShipmentContainerHeader item : shipmentContainerHeaders) {
            ShipmentTaskCreateModel shipmentTask = new ShipmentTaskCreateModel();
            shipmentTask.setShipmentContainerHeaderIds(item.getId());
            AjaxResult ajaxResults = shipmentTaskService.createTaskFromShipmentContainers(shipmentTask);
            if (ajaxResults.hasErr()) {
                throw new ServiceException("任务生成失败");
            }
        }

        //点位不等于空,调用MES的RGV接口
        if (StringUtils.isNotEmpty(shipmentHeader.getLine())) {
            AjaxResult result3 = rgvService.sendRgv(shipmentHeader.getLine(), port, "RGV出库,发送点位", "shipment", "", shipmentHeader.getCode());
            if (result3.hasErr()) {
                throw new ServiceException("发送RGV接口失败:" + result3.getMsg());
            }
        }

        //出库单明细的出库数量必须等于预出库数量
        List<ShipmentDetail> list = shipmentDetailService.list(new LambdaQueryWrapper<ShipmentDetail>().eq(ShipmentDetail::getShipmentCode, shipmentHeader.getCode()));
        for (ShipmentDetail shipmentDetail : list) {
            if (!shipmentDetail.getQty().equals(shipmentDetail.getTaskQty())) {
                throw new ServiceException(shipmentDetail.getMaterialCode() + "," + shipmentDetail.getMaterialName() + ",库存不够,任务要出:" + shipmentDetail.getQty());
            }
        }

        /* 6.step回传出库单和出库明细单 */
//        ShipmentDomain shipment = new ShipmentDomain();
//        shipment.setShipmentHeader(shipmentHeader);
//        shipment.setShipmentDetails(shipmentDetailList);
        return AjaxResult.success();
    }


    //匹配出库口
    private String matchPort(List<String> ports, String lineNumber) {
        String port = ports.get(0);
        if (ports.contains("P1014") && ports.contains("P1011")) {
            if (ports.size() > 1 && StringUtils.isNotEmpty(lineNumber)) {
                if (lineNumber.equals("SJ01") || lineNumber.equals("SJ02") || lineNumber.equals("SJ03")) {
                    port = "P1014";
                } else if (lineNumber.equals("SJ04") || lineNumber.equals("SJ05")) {
                    port = "P1011";
                } else {
                    port = "";
                }
            }
        }
        return port;
    }

    private void addDetail(ShipmentHeader shipmentHeader, List<ShipmentDetail> shipmentDetails, String port) {
        int count = 0;
        shipmentHeader = shipmentHeaderService.getOne(new LambdaQueryWrapper<ShipmentHeader>().eq(ShipmentHeader::getCode, shipmentHeader.getCode()));
        //List<ShipmentDetail> shipmentDetailList = new ArrayList<>();
        for (ShipmentDetail shipmentDetail : shipmentDetails) {
            shipmentDetail.setShipmentId(shipmentHeader.getId());
            shipmentDetail.setShipmentCode(shipmentHeader.getCode());
            shipmentDetail.setInventorySts(QuantityConstant.GOOD);
            shipmentDetail.setPort(port);
            if (StringUtils.isNotEmpty((shipmentDetail.getBatch()))) {
                shipmentDetail.setBatch(shipmentDetail.getBatch());
            }
            if (StringUtils.isNotEmpty((shipmentDetail.getLabelCode()))) {
                shipmentDetail.setLabelCode(shipmentDetail.getLabelCode());
            }
            if (StringUtils.isNotEmpty((shipmentDetail.getCustomerCode()))) {
                shipmentDetail.setCustomerCode(shipmentDetail.getCustomerCode());
            }
            if (StringUtils.isNotEmpty((shipmentDetail.getPo()))) {
                shipmentDetail.setPo(shipmentDetail.getPo());
            }
            if (shipmentDetail.getProductionDate() != null) {
                shipmentDetail.setProductionDate(shipmentDetail.getProductionDate());
            }
            shipmentDetail.setDoubleSided(shipmentDetail.getDoubleSided());
            shipmentDetail.setManage(shipmentDetail.getManage());
            shipmentDetail.setWarehouseCode("CS0001");
            shipmentDetail.setCompanyCode("BHF");
            Material material = materialService.getOne(new LambdaQueryWrapper<Material>().eq(Material::getCode, shipmentDetail.getMaterialCode()));
            shipmentDetail.setMaterialName(material.getName());
            shipmentDetail.setMaterialSpec(material.getSpec());
            shipmentDetail.setMaterialUnit(material.getUnit());
            shipmentDetail.setMaterialCode(material.getCode());
            if (!shipmentDetailService.save(shipmentDetail)) {
                throw new ServiceException("保存入库明细失败");
            }
            //shipmentDetailList.add(shipmentDetail);


            //双面,分配库存的标签给他们两个,指定出库
            if (shipmentDetail.getDoubleSided() == 1) {
                count++;
                if (count > 1) {
                    throw new ServiceException("双面只能有一个");
                }
                List<InventoryDetail> inventoryDetailList = inventoryDetailService.list(new LambdaQueryWrapper<InventoryDetail>()
                        .eq(InventoryDetail::getMaterialCode, shipmentDetail.getMaterialCode()));
                shipmentDetail.setLabelCode(inventoryDetailList.get(0).getLabelCode());
                shipmentDetailService.updateById(shipmentDetail);

                ShipmentDetail newShipmentDetail = new ShipmentDetail();
                BeanUtils.copyProperties(shipmentDetail, newShipmentDetail, "id");
                newShipmentDetail.setQty(new BigDecimal(1));
                newShipmentDetail.setIsNew("双面出库新增出库明细");
                newShipmentDetail.setLabelCode(inventoryDetailList.get(1).getLabelCode());
                if (!shipmentDetailService.save(newShipmentDetail)) {
                    throw new ServiceException("保存双面入库明细失败");
                }
            }
        }
    }


    /**
     * 检查出库主单的合法性
     *
     * @param shipmentHeader
     * @return
     */
    public AjaxResult checkShipmentHeader(ShipmentHeader shipmentHeader) {
        if (StringUtils.isEmpty(shipmentHeader.getReferCode()) || StringUtils.isEmpty(shipmentHeader.getShipmentType())) {
            return AjaxResult.error("出库单号或出库单类型为空");
        }

        //2、判断出库类型
        if (shipmentTypeService.getOne(new LambdaQueryWrapper<ShipmentType>().eq(ShipmentType::getCode, shipmentHeader.getShipmentType())) == null) {
            return AjaxResult.error("wms没有此出库类型");
        }

        //3、检查上游单号是否存在
        if (shipmentHeaderService.getOne(new LambdaQueryWrapper<ShipmentHeader>().eq(ShipmentHeader::getReferCode, shipmentHeader.getReferCode())) != null) {
            return AjaxResult.error("该单据已存在:" + shipmentHeader.getReferCode());
        }
        return AjaxResult.success(shipmentHeader);
    }


    /**
     * 检查出库子单的合法性
     *
     * @param shipmentDetails
     * @return
     */
    public AjaxResult checkShipmentDetail(List<ShipmentDetail> shipmentDetails) {
        for (ShipmentDetail shipmentDetail : shipmentDetails) {
            //判断必填字段是否为空且总数量不能为0
            if (shipmentDetail.getMaterialCode() == null || new BigDecimal(0).compareTo(shipmentDetail.getQty() != null ?
                    shipmentDetail.getQty() : new BigDecimal(0)) == 0) {
                return AjaxResult.error("出库明细字段有误,MaterialCode或qty");
            }
            //检查物料
            String materialCode = shipmentDetail.getMaterialCode();
            if (StringUtils.isEmpty(materialCode)) {
                return AjaxResult.error("物料为空");
            }
            if (materialService.getOne(new LambdaQueryWrapper<Material>().eq(Material::getCode, materialCode)) == null) {
                return AjaxResult.error("WMS不存在此物料:", materialCode);
            }

            //如果带标签号,判断标签号相同的库存是否足够
            if (StringUtils.isNotEmpty(shipmentDetail.getLabelCode())) {
                AjaxResult result1 = judgingLabelInventory(materialCode, shipmentDetail);
                if (result1.hasErr()) {
                    return AjaxResult.error(result1.getMsg());
                }
            }

            //判断库存是否足够
            AjaxResult result2 = judgingInventory(materialCode, shipmentDetail);
            if (result2.hasErr()) {
                return AjaxResult.error(result2.getMsg());
            }
        }

        //物料号相同的出库单合并qty
        List<ShipmentDetail> newShipmentDetailList = mergeShipmentDetails(shipmentDetails);
        for (ShipmentDetail shipmentDetail : newShipmentDetailList) {
            //判断库存是否足够
            AjaxResult result2 = judgingInventory(shipmentDetail.getMaterialCode(), shipmentDetail);
            if (result2.hasErr()) {
                return AjaxResult.error(result2.getMsg());
            }
        }

        return AjaxResult.success();
    }


    //物料号相同的出库单合并qty
    public static List<ShipmentDetail> mergeShipmentDetails(List<ShipmentDetail> shipmentDetails) {
        Map<String, BigDecimal> materialCodeQtyMap = new HashMap<>();
        List<ShipmentDetail> mergedShipmentDetails = new ArrayList<>();

        // 统计相同MaterialCode的qty总和
        for (ShipmentDetail shipmentDetail : shipmentDetails) {
            String materialCode = shipmentDetail.getMaterialCode();
            BigDecimal qty = shipmentDetail.getQty();

            BigDecimal oldQty = materialCodeQtyMap.get(materialCode);
            if (oldQty != null) {
                qty = qty.add(oldQty);
            }
            materialCodeQtyMap.put(materialCode, qty);
        }

        // 合并ShipmentDetail并添加到结果集中
        for (Map.Entry<String, BigDecimal> entry : materialCodeQtyMap.entrySet()) {
            ShipmentDetail mergedShipmentDetail = new ShipmentDetail();
            mergedShipmentDetail.setMaterialCode(entry.getKey());
            mergedShipmentDetail.setQty(entry.getValue());
            mergedShipmentDetails.add(mergedShipmentDetail);
        }

        return mergedShipmentDetails;
    }

    //判断标签库存
    private AjaxResult judgingLabelInventory(String materialCode, ShipmentDetail shipmentDetail) {
        List<InventoryDetail> labelCodeinventoryDetailList = inventoryDetailService.list(new LambdaQueryWrapper<InventoryDetail>()
                .eq(InventoryDetail::getLabelCode, shipmentDetail.getLabelCode()));
        if (labelCodeinventoryDetailList.isEmpty()) {
            return AjaxResult.error("WMS库存中没有此标签条码:", shipmentDetail.getLabelCode());
        }
        //排除掉有任务的库存
        List<InventoryDetail> newInventoryDetailList = excludeLock(labelCodeinventoryDetailList);

        for (InventoryDetail inventoryDetail : newInventoryDetailList) {
            BigDecimal inventoryQty = inventoryDetail.getQty().subtract(inventoryDetail.getTaskQty());
            if (inventoryQty.compareTo(shipmentDetail.getQty()) < 0) {
                return AjaxResult.error("该标签库存不够" + shipmentDetail.getLabelCode() + ":需求为:" + shipmentDetail.getQty()
                        + ",库存剩余" + inventoryQty
                        + ",物料名称:" + shipmentDetail.getMaterialName()
                        + ",物料编码:" + shipmentDetail.getMaterialCode());
            }
        }
        return AjaxResult.success();
    }


    //判断库存
    public AjaxResult judgingInventory(String materialCode, ShipmentDetail shipmentDetail) {
        List<InventoryDetail> inventoryDetailList = inventoryDetailService.list(new LambdaQueryWrapper<InventoryDetail>()
                .eq(InventoryDetail::getMaterialCode, materialCode));
        if (inventoryDetailList.isEmpty()) {
            return AjaxResult.error("WMS库存中没有此物料库存:", materialCode);
        }
        //排除掉有任务的库存
        List<InventoryDetail> newInventoryDetailList2 = excludeLock(inventoryDetailList);

        //判断双面库存
        if (shipmentDetail.getDoubleSided() == 1) {
            if (newInventoryDetailList2.size() < 2) {
                return AjaxResult.error("双面库存不足:", materialCode);
            }
        }
        //和出库单明细物料相同的库存
        BigDecimal totalQty = new BigDecimal(0);
        for (InventoryDetail inventoryDetail : newInventoryDetailList2) {
            BigDecimal inventoryQty = inventoryDetail.getQty().subtract(inventoryDetail.getTaskQty());
            totalQty = totalQty.add(inventoryQty);
        }
        if (totalQty.compareTo(shipmentDetail.getQty()) < 0) {
            return AjaxResult.error("该物料库存不足或该托盘已有任务:需求为:" + shipmentDetail.getQty()
                    + ",库存剩余" + totalQty
                    + ",物料名称:" + shipmentDetail.getMaterialName()
                    + ",物料编码:" + shipmentDetail.getMaterialCode());
        }
        return AjaxResult.success();
    }


    private List<InventoryDetail> exclude(List<InventoryDetail> inventoryDetailList) {
        List<InventoryDetail> removeList = new ArrayList<>();
        ArrayList<String> lockContainerCode = new ArrayList<>();

        List<String> containerCodes = inventoryDetailList.stream().map(InventoryDetail::getContainerCode).distinct().collect(Collectors.toList());
        for (String containerCode : containerCodes) {
            Container container = containerService.getOne(new LambdaQueryWrapper<Container>()
                    .eq(Container::getStatus, QuantityConstant.STATUS_LOCATION_LOCK)
                    .eq(Container::getCode, containerCode));
            if (container != null) {
                lockContainerCode.add(containerCode);
            }
        }
        for (InventoryDetail inventoryDetail : inventoryDetailList) {
            for (String str : lockContainerCode) {
                if (inventoryDetail.getContainerCode().contains(str)) {
                    removeList.add(inventoryDetail);
                }
            }
        }
        inventoryDetailList.removeAll(removeList);
        return inventoryDetailList;
    }


    private List<InventoryDetail> excludeLock(List<InventoryDetail> inventoryDetailList) {
        List<String> lockContainerCodes = containerService.list(new LambdaQueryWrapper<Container>()
                        .eq(Container::getStatus, QuantityConstant.STATUS_LOCATION_LOCK))
                .stream().map(Container::getCode).collect(Collectors.toList());
        List<InventoryDetail> remainingList = new ArrayList<>();
        for (InventoryDetail inventoryDetail : inventoryDetailList) {
            if (!lockContainerCodes.contains(inventoryDetail.getContainerCode())) {
                remainingList.add(inventoryDetail);
            }
        }
        return remainingList;
    }

    @Transactional
    public AjaxResult remove(List<String> shipmentCodeList) {
        LambdaQueryWrapper<ShipmentHeader> headerQueryWrapper;
        for (String shipmentCode : shipmentCodeList) {
            headerQueryWrapper = Wrappers.lambdaQuery();
            headerQueryWrapper.eq(ShipmentHeader::getCode, shipmentCode);
            ShipmentHeader shipmentHeader = shipmentHeaderService.getOne(headerQueryWrapper);
            if (shipmentHeader == null) {
                return AjaxResult.success("");
            }
            if ((shipmentHeader.getFirstStatus() >= QuantityConstant.SHIPMENT_HEADER_RETURN && shipmentHeader.getLastStatus() >= QuantityConstant.SHIPMENT_HEADER_RETURN) ||
                    (shipmentHeader.getFirstStatus() < QuantityConstant.SHIPMENT_HEADER_POOL & shipmentHeader.getLastStatus() < QuantityConstant.SHIPMENT_HEADER_POOL)) {
                ShipmentHeaderHistory shipmentHeaderHistory = new ShipmentHeaderHistory();
                List<ShipmentDetailHistory> shipmentDetailHistoryList = new ArrayList<>();
                //查询入库单明细
                LambdaQueryWrapper<ShipmentDetail> lambdaQueryWrapper = Wrappers.lambdaQuery();
                lambdaQueryWrapper.eq(ShipmentDetail::getShipmentCode, shipmentCode);
                List<ShipmentDetail> list = shipmentDetailService.list(lambdaQueryWrapper);

                //复制到入库历史实体
                com.huaheng.common.utils.bean.BeanUtils.copyBeanProp(shipmentHeaderHistory, shipmentHeader);
                for (ShipmentDetail shipmentDetail : list) {
                    ShipmentDetailHistory shipmentDetailHistory = new ShipmentDetailHistory();
                    com.huaheng.common.utils.bean.BeanUtils.copyBeanProp(shipmentDetailHistory, shipmentDetail);
                    shipmentDetailHistoryList.add(shipmentDetailHistory);
                }


                shipmentHeaderHistory.setLastUpdatedBy(ShiroUtils.getName());
                if (!shipmentHeaderService.removeById(shipmentHeader.getId())) {
                    throw new ServiceException("删除头表失败");
                }
                if (!shipmentHeaderHistoryService.save(shipmentHeaderHistory)) {
                    throw new ServiceException("新增历史出库单失败");
                }
                // 当存在明细时删除
                if (list.size() != 0) {
                    //删除入库明细
                    List<Integer> shipmentDetailIds = new ArrayList<>();
                    for (int i = 0; i < shipmentDetailHistoryList.size(); i++) {
                        shipmentDetailHistoryList.get(i).setLastUpdatedBy(ShiroUtils.getName());
                        shipmentDetailHistoryList.get(i).setShipmentId(shipmentHeaderHistory.getId());
                        shipmentDetailIds.add(shipmentDetailHistoryList.get(i).getId());
                    }
                    if (!shipmentDetailService.removeByIds(shipmentDetailIds)) {
                        throw new ServiceException("删除明细表失败");
                    }
                    if (!shipmentDetailHistoryService.saveBatch(shipmentDetailHistoryList)) {
                        throw new ServiceException("新增明细失败");
                    }
                }
            } else {
                return AjaxResult.success("出库单没有完成,无法删除");
            }
        }
        return AjaxResult.success("删除成功");
    }

    public AjaxResult search(String shipmentCode, String companyCode, String warehouseCode) {
        if (companyCode == null) {
            return AjaxResult.error("货主编码不能为空");
        }
        if (warehouseCode == null) {
            return AjaxResult.error("仓库编码不能为空");
        }
        ShipmentDomain shipmentDomain = new ShipmentDomain();
        LambdaQueryWrapper<ShipmentHeader> headerLambdaQuery = Wrappers.lambdaQuery();
        LambdaQueryWrapper<ShipmentDetail> detailLambdaQuery = Wrappers.lambdaQuery();
        headerLambdaQuery.eq(ShipmentHeader::getWarehouseCode, warehouseCode)
                .eq(ShipmentHeader::getCompanyCode, companyCode)
                .eq(ShipmentHeader::getCode, shipmentCode);
        detailLambdaQuery.eq(ShipmentDetail::getWarehouseCode, warehouseCode)
                .eq(ShipmentDetail::getCompanyCode, companyCode)
                .eq(ShipmentDetail::getShipmentCode, shipmentCode);
        ShipmentHeader shipmentHeader = shipmentHeaderService.getOne(headerLambdaQuery);
        List<ShipmentDetail> shipmentDetailList = shipmentDetailService.list(detailLambdaQuery);
        shipmentDomain.setShipmentHeader(shipmentHeader);
        shipmentDomain.setShipmentDetails(shipmentDetailList);
        return AjaxResult.success("查询成功", shipmentDomain);
    }


    public AjaxResult shipmentBack(ShipmentHeader shipmentHeader) {
        String warehouseCode = "CS0001";
        String url = addressService.selectAddress(QuantityConstant.ADDRESS_MES_SHIPMENT);
        //List<ShipmentDetail> shipmentDetailList = shipmentDetailService.list(new LambdaQueryWrapper<ShipmentDetail>().eq(ShipmentDetail::getShipmentId, shipmentHeader.getId()));
        List<InventoryTransaction> inventoryTransactionList = inventoryTransactionService.list(new LambdaQueryWrapper<InventoryTransaction>()
                .eq(InventoryTransaction::getTransactionType, 20)
                .eq(InventoryTransaction::getBillCode, shipmentHeader.getCode()));

        //处理库存交易
        List<InventoryTransaction> inventoryTransactions = processInventoryTransactionList(inventoryTransactionList);
        List<ShipmentDetail> shipmentDetailList = new ArrayList<>();
        for (InventoryTransaction it : inventoryTransactions) {
            ShipmentDetail sd = new ShipmentDetail();
            sd.setId(it.getBillDetailId());
            sd.setBatch(it.getBatch());
            sd.setDoubleSided(it.getDoubleSided());
            sd.setLabelCode(it.getLabelCode());
            sd.setManage(it.getManage());
            sd.setMaterialName(it.getMaterialName());
            sd.setMaterialUnit(it.getMaterialUnit());
            sd.setMaterialCode(it.getMaterialCode());
            sd.setMaterialSpec(it.getMaterialSpec());
            sd.setQty(it.getTaskQty());
            sd.setShipmentCode(shipmentHeader.getCode());
            sd.setShipmentId(shipmentHeader.getId());
            sd.setContainerCode(it.getContainerCode());
            shipmentDetailList.add(sd);
        }
        //替换出库明细部分值
        ShipmentDomain shipmentDomain = new ShipmentDomain();
        shipmentDomain.setShipmentHeader(shipmentHeader);
        shipmentDomain.setShipmentDetails(shipmentDetailList);
        String jsonParam = JSON.toJSONString(shipmentDomain);
        ResponseEntity<JSONObject> result = RestUtil.request_post(url, warehouseCode, jsonParam, "出库回传MES");
        if (result != null && result.getBody() != null) {
            String code = result.getBody().getString("RequestStatus");
            String msg = result.getBody().getString("Msg");
            if (!HttpConstant.isMesSuccess(Integer.parseInt(code))) {
                return AjaxResult.error(msg);
            }
        } else {
            throw new ServiceException("接口地址错误或返回为空");
        }

        return AjaxResult.success();
    }

    public List<InventoryTransaction> processInventoryTransactionList(List<InventoryTransaction> inventoryTransactionList) {
        // 新建一个HashMap用于存储labelCode相同的库存交易对象
        Map<String, InventoryTransaction> itMap = new HashMap<>();

        // 循环遍历 库存交易List
        for (InventoryTransaction inventoryTransaction : inventoryTransactionList) {
            // 如果taskQty为负数,则改为正数
            if (inventoryTransaction.getTaskQty().compareTo(BigDecimal.ZERO) < 0) {
                inventoryTransaction.setTaskQty(inventoryTransaction.getTaskQty().abs());
            }

            // 如果itMap中已存在标签条码相同的,库存交易对象,则将taskQty相加
            if (itMap.containsKey(inventoryTransaction.getLabelCode())) {
                InventoryTransaction existingInventoryTransaction = itMap.get(inventoryTransaction.getLabelCode());
                existingInventoryTransaction.setTaskQty(existingInventoryTransaction.getTaskQty().add(inventoryTransaction.getTaskQty()));
            } else {
                // 如果itMap中不存在该labelCode的库存交易对象,则将该对象存入map中
                itMap.put(inventoryTransaction.getLabelCode(), inventoryTransaction);
            }
        }

        // 将map中的所有库存交易对象转为List并返回
        return new ArrayList<>(itMap.values());
    }

}