package com.prolog.eis.service.page.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.codingapi.tx.annotation.TxTransaction;
import com.prolog.cs.basic.item.model.vo.ItemBarCodeVO;
import com.prolog.eis.aspect.RedissonLock;
import com.prolog.eis.constants.base.BaseTaskTypeConstants;
import com.prolog.eis.constants.base.ContainerTaskStatusConstants;
import com.prolog.eis.constants.base.ContainerTaskTypeConstants;
import com.prolog.eis.constants.cfg.LocationCfgConstants;
import com.prolog.eis.constants.redisKey.RedisKey;
import com.prolog.eis.dao.container.MergeContainerTaskHisMapper;
import com.prolog.eis.dao.out.BizOutboundTaskDetailDismantleGridMapper;
import com.prolog.eis.dao.out.ContainerStoreChangeMapper;
import com.prolog.eis.dao.out.OrderLogMapper;
import com.prolog.eis.dao.statistics.EfficiencyStatisticsMapper;
import com.prolog.eis.dto.item.ItemSyncVO;
import com.prolog.eis.dto.outbound.SupervisionCodeDto;
import com.prolog.eis.dto.page.*;
import com.prolog.eis.dto.wms.*;
import com.prolog.eis.enums.base.BaseStatusEnum;
import com.prolog.eis.enums.base.BaseTypeEnum;
import com.prolog.eis.enums.base.LayerEnum;
import com.prolog.eis.enums.wms.WmsCarryTaskInCode;
import com.prolog.eis.model.container.*;
import com.prolog.eis.model.out.*;
import com.prolog.eis.model.outbound.BizOutboundTask;
import com.prolog.eis.model.outbound.BizOutboundTaskDetail;
import com.prolog.eis.model.outbound.OrderLog;
import com.prolog.eis.model.outbound.PrintTask;
import com.prolog.eis.model.shelves.AllotmentTaskRecord;
import com.prolog.eis.model.shelves.AllotmentTaskRecordHis;
import com.prolog.eis.model.shelves.GridInfo;
import com.prolog.eis.model.statistics.EfficiencyStatistics;
import com.prolog.eis.router.vo.ContainerLocationVo;
import com.prolog.eis.service.container.EmptyContainerTaskService;
import com.prolog.eis.service.container.MergeContainerTaskService;
import com.prolog.eis.service.out.*;
import com.prolog.eis.service.page.PdaService;
import com.prolog.eis.service.route.RouteInterfaceService;
import com.prolog.eis.service.shelves.*;
import com.prolog.eis.service.wms.WmsContainerStatusUpdateService;
import com.prolog.eis.service.wms.WmsTaskFinishBackService;
import com.prolog.eis.utils.MapUtils;
import com.prolog.framework.authority.core.dto.UserDTO;
import com.prolog.framework.authority.user.UserTemplate;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.PrologException;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.Restrictions;
import com.prolog.framework.utils.AssertUtils;
import com.prolog.upcloud.base.inventory.model.BatchNumberSync;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @desc:
 * @author: zhangJie
 * @date: 2023/9/1 10:42
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PdaServiceImpl implements PdaService {

    private final ContainerTaskDismantleService containerTaskDismantleService;
    private final ContainerTaskService containerTaskService;
    private final ContainerInfoService containerInfoService;
    private final ContainerInfoDetailService containerInfoDetailService;
    private final ContainerStoreChangeService containerStoreChangeService;
    private final BizOutboundTaskService bizOutboundTaskService;
    private final BizOutboundTaskDetailService bizOutboundTaskDetailService;
    private final EmptyContainerTaskService emptyContainerTaskService;
    private final RouteInterfaceService routeFeignService;
    private final LocationCfgService locationCfgService;
    private final ItemService itemService;
    private final InventoryService inventoryService;
    private final WmsTaskFinishBackService wmsTaskFinishBackService;
    private final GridInfoService gridInfoService;
    private final PrintTaskService printTaskService;
    private final BizOutboundTaskDetailDismantleService bizOutboundTaskDetailDismantleService;
    private final BizOutboundTaskDismantleSupplyService outboundTaskDismantleSupplyService;
    private final MergeContainerTaskService mergeContainerTaskService;
    private final ContainerStoreChangeMapper containerStoreChangeMapper;
    private final MergeContainerTaskHisMapper mergeContainerTaskHisMapper;
    private final UserTemplate userTemplate;
    private final BizOutboundTaskDetailItemService outboundTaskDetailItemService;
    private final BizOutboundTaskDetailItemHisService outboundTaskDetailItemHisService;
    private final WmsContainerStatusUpdateService wmsContainerStatusUpdateService;
    private final StationCfgService stationCfgService;
    private final OrderLogMapper orderLogMapper;
    private final AllotmentTaskRecordService allotmentTaskRecordService;
    private final AllotmentTaskRecordHisService allotmentTaskRecordHisService;
    private final RedisTemplate redisTemplate;
    private final BizOutboundTaskDetailDismantleGridMapper outboundTaskDetailDismantleGridMapper;
    private final EfficiencyStatisticsMapper efficiencyStatisticsMapper;
    @Value("${wms.warehouseId}")
    private String warehouseId;
    @Value("${wms.enterpriseId}")
    private String enterpriseId;

    @Override
    public List<DismantlePickingListDto> dismantlePickingTaskList(String containerNo) throws Exception {
        List<ContainerTask> dismantlePickingTask = containerTaskDismantleService.findDismantlePickingList(containerNo);
        if (CollectionUtils.isEmpty(dismantlePickingTask)) {
            return null;
        }
        List<DismantlePickingListDto> resultList = new ArrayList<>();
        final List<String> itemIds = dismantlePickingTask.stream().map(ContainerTask::getItemId).collect(Collectors.toList());
        final List<ItemSyncVO> itemInfoList = itemService.queryItemMst(itemIds);
        dismantlePickingTask.forEach(item -> {
            ItemSyncVO itemInfo = itemInfoList.stream().filter(info -> StrUtil.equals(info.getItemId(), item.getItemId())).findFirst().orElse(null);
            resultList.add(DismantlePickingListDto.builder()
                    .containerSubNo(item.getContainerSubNo())
                    .containerNo(item.getContainerNo())
                    .goodsName(itemInfo.getItemName())
                    .qty(item.getQty())
                    .id(item.getId())
                    .eisWaveNo(item.getEisWaveNo())
                    .isBindGrid(item.getIsBindGrid())
                    .build());
        });
        return resultList;
    }

    @Override
    public DismantlePickingDetailDto dismantlePickingTaskDetail(String containerSubNo, String eisWaveNo) throws Exception {
        ContainerTask dismantlePickingTask = containerTaskDismantleService.findDismantlePickingDetail(containerSubNo, eisWaveNo);
        if (Objects.isNull(dismantlePickingTask)) {
            return null;
        }
        ItemSyncVO itemInfo = itemService.queryItemMst(Arrays.asList(dismantlePickingTask.getItemId())).stream().findFirst().orElseThrow(() -> new PrologException("未查询到商品信息"));
        BatchNumberSync batchNumberSync = inventoryService.getBatchNumberSync(Arrays.asList(dismantlePickingTask.getLotId())).stream().findFirst().orElseThrow(() -> new PrologException("未查询到批次信息"));
        return DismantlePickingDetailDto.builder()
                .goodsName(itemInfo.getItemName())
                .goodsCode(itemInfo.getPieceBarcode())
                .locationNo(dismantlePickingTask.getContainerSubNo())
                .lotNo(batchNumberSync.getManufacturerLotNum())
                .id(dismantlePickingTask.getId())
                .dismantleQty(dismantlePickingTask.getQty())
                .containerSubNo(dismantlePickingTask.getContainerSubNo())
                .qty(dismantlePickingTask.getQty())
                .pickQty(itemInfo.getUomList().get(0).getConversionRate())
                .pieceQty(BigDecimal.ZERO)
                .itemId(dismantlePickingTask.getItemId())
                .lotId(dismantlePickingTask.getLotId())
                .eisWaveNo(dismantlePickingTask.getEisWaveNo())
                .isBindGrid(dismantlePickingTask.getIsBindGrid())
                .build();
    }


    /**
     * 拆零拣选 以货格containerSubNo的维度进行拣选确认
     * 一个货格或一个托盘可能对应多个订单
     *
     * @param req
     * @throws Exception
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    @RedissonLock(prefixKey = RedisKey.DISMANTLE_PICKING_CONFIRM, key = "#req.containerSubNo")
    public void dismantlePickingConfirm(DismantleConfirmReqDto req) throws Exception {
        //1 根据货格或者托盘查询所有订单容器任务
        List<ContainerTaskDismantle> containerTaskDismantleList = containerTaskDismantleService.findDismantleContainerTask(req.getContainerSubNo());
        AssertUtils.isNotTrue(CollectionUtils.isEmpty(containerTaskDismantleList), "没有查询到任务");
        List<Integer> collect = containerTaskDismantleList.stream().map(ContainerTaskDismantle::getContainerTaskId).collect(Collectors.toList());
        Criteria containerTaskCri = new Criteria(ContainerTask.class);
        containerTaskCri.restrictionBuilder().in(ContainerTask::getId, collect).build();
        List<ContainerTask> containerTaskList = containerTaskService.findByCriteria(containerTaskCri);
        AssertUtils.isNotTrue(CollectionUtils.isEmpty(containerTaskList), "没有查询到任务");

        String containerNoStr = containerTaskList.get(0).getContainerNo();
        List<ContainerLocationVo> containerLocationVoList = routeFeignService.findLocationByContainerList(Arrays.asList(containerNoStr));
        if (CollectionUtils.isEmpty(containerLocationVoList)) {
            throw new PrologException(String.format("容器%s未查询到点位信息", containerNoStr));
        }
        Criteria criteria3 = new Criteria(StationCfg.class);
        criteria3.restrictionBuilder().in(StationCfg::getStationType, Arrays.asList(90, 92)).build();
        List<String> stationAreaList = stationCfgService.findByCriteria(criteria3).stream().map(StationCfg::getAreaNo).collect(Collectors.toList());
        ContainerLocationVo containerLocationVo = containerLocationVoList.get(0);
        if (!stationAreaList.contains(containerLocationVo.getCurrentArea())) {
            throw new PrologException(String.format("容器%s未到位无法确认", containerNoStr));
        }

        List<Integer> outboundIds = containerTaskList.stream().map(ContainerTask::getOutboundId).collect(Collectors.toList());
        Criteria outboundCriteria = new Criteria(BizOutboundTask.class);
        outboundCriteria.restrictionBuilder().in(BizOutboundTask::getId, outboundIds).build();
        List<BizOutboundTask> bizOutboundTaskList = bizOutboundTaskService.findByCriteria(outboundCriteria);
        Assert.notEmpty(bizOutboundTaskList, "未查询到对应出库单信息");

        //过滤当前波次的订单
        bizOutboundTaskList = bizOutboundTaskList.stream().filter(item -> StrUtil.equals(item.getEisWaveNo(), req.getEisWaveNo())).collect(Collectors.toList());
        Assert.notEmpty(bizOutboundTaskList, "未查询到对应出库单信息");

        final List<Integer> outboundId = bizOutboundTaskList.stream().map(BizOutboundTask::getId).collect(Collectors.toList());
        containerTaskList = containerTaskList.stream().filter(item -> outboundId.contains(item.getOutboundId())).collect(Collectors.toList());

        final List<Integer> outboundDetailIds = containerTaskList.stream().map(ContainerTask::getOutboundDetailId).collect(Collectors.toList());

        //2 查出对应的拆零任务
        Criteria outboundDismantleCriteria = new Criteria(BizOutboundTaskDetailDismantle.class);
        outboundDismantleCriteria.restrictionBuilder().in(BizOutboundTaskDetailDismantle::getOutboundDetailId, outboundDetailIds).eq(BizOutboundTaskDetailDismantle::getType, 2).build();
        List<BizOutboundTaskDetailDismantle> outboundTaskDetailDismantles = bizOutboundTaskDetailDismantleService.findByCriteria(outboundDismantleCriteria);
        Assert.notEmpty(outboundTaskDetailDismantles, "没有查询到任务");

        //3 校验拣选数量不能大于计划数量
        BigDecimal planQty = containerTaskDismantleList.stream().map(ContainerTaskDismantle::getPlanQty).reduce(BigDecimal.ZERO, BigDecimal::add);
        AssertUtils.isNotTrue(req.getQty().compareTo(planQty) > 0, "拣选数量不能大于计划数量");

        ContainerInfoDetail containerInfoDetail = containerInfoDetailService.findOneByMap(MapUtils.put(ContainerInfoDetail::getContainerSubNo, req.getContainerSubNo()).getMap());
        ContainerInfo containerInfo = containerInfoService.findOneByMap(MapUtils.put(ContainerInfo::getContainerNo, containerInfoDetail.getContainerNo()).getMap());
        if (!Objects.equals(containerInfo.getTaskType(), BaseTaskTypeConstants.DISMANTLE_OUTBOUND_END_TYPE)) {
            throw new PrologException(String.format("容器%s未到位无法确认", containerNoStr));
        }
        AssertUtils.isNotTrue(Objects.isNull(containerInfoDetail), "容器库存未查到");
        LocationCfg locationCfg = locationCfgService.findOneByMap(MapUtils.put(LocationCfg::getType, containerInfo.getAGVLCode()).put(LocationCfg::getWmsAreaNo, WmsCarryTaskInCode.AGVL.getCode()).getMap());
        AssertUtils.isNotNull(locationCfg, "拆零区未配置");

        //4 遍历订单进行处理
        Criteria outboundDetailCriteria = new Criteria(BizOutboundTaskDetail.class);
        outboundDetailCriteria.restrictionBuilder().in(BizOutboundTask::getId, outboundDetailIds).build();
        List<BizOutboundTaskDetail> bizOutboundTaskDetailList = bizOutboundTaskDetailService.findByCriteria(outboundDetailCriteria);

        BigDecimal sumQty = req.getQty();
        List<WmsTaskFinishDto> wmsTaskFinishDtoList = new ArrayList<>();
        //总拣库存扣减
        Set<String> cotnainerSet = this.inventoryDeduction(sumQty, containerInfoDetail);

        for (ContainerTask containerTask : containerTaskList) {
            //根据容器任务找对应拆零任务
            ContainerTaskDismantle containerTaskDismantle = containerTaskDismantleList.stream().filter(item -> NumberUtil.equals(item.getContainerTaskId(), containerTask.getId())).findFirst().orElseThrow(() -> new PrologException("未找到对应拆零任务"));
            containerTaskDismantle.setStatus(3);
            //根据容器任务找对应出库任务详情
            BizOutboundTaskDetail bizOutboundTaskDetail = bizOutboundTaskDetailList.stream()
                    .filter(item -> NumberUtil.equals(item.getId(), containerTask.getOutboundDetailId())).findFirst().orElseThrow(() -> new PrologException("未找到对应出库任务详情"));
            BizOutboundTaskDetailDismantle outboundTaskDetailDismantle = outboundTaskDetailDismantles.stream()
                    .filter(item -> NumberUtil.equals(item.getOutboundDetailId(), bizOutboundTaskDetail.getId())).findFirst().orElseThrow(() -> new PrologException("未找到对应出库拆零任务详情"));
            BizOutboundTask outboundTask = bizOutboundTaskList.stream()
                    .filter(x -> NumberUtil.equals(x.getId(), containerTask.getOutboundId())).findFirst().orElseThrow(() -> new PrologException("未找到对应出库任务"));

            if (sumQty.compareTo(containerTaskDismantle.getPlanQty()) >= 0) {
                //满足此订单库存扣减
                containerTaskDismantle.setActQty(containerTaskDismantle.getActQty().add(containerTaskDismantle.getPlanQty()));
                sumQty = sumQty.subtract(containerTaskDismantle.getPlanQty());
                WmsTaskFinishDto wmsTaskFinishDto = taskFinishBack(outboundTask, bizOutboundTaskDetail, containerTask.getContainerNo(), BigDecimal.ZERO, containerTaskDismantle.getPlanQty(), 0);
                wmsTaskFinishDtoList.add(wmsTaskFinishDto);
            } else {
                //不满足此订单库存扣减
                if (sumQty.compareTo(BigDecimal.ZERO) > 0) {
                    containerTaskDismantle.setActQty(containerTaskDismantle.getActQty().add(sumQty));
                    WmsTaskFinishDto wmsTaskFinishDto = taskFinishBack(outboundTask, bizOutboundTaskDetail, containerTask.getContainerNo(), containerTaskDismantle.getPlanQty().subtract(sumQty), sumQty, 0);
                    wmsTaskFinishDtoList.add(wmsTaskFinishDto);
                    sumQty = sumQty.subtract(containerTaskDismantle.getPlanQty());
                } else {
                    WmsTaskFinishDto wmsTaskFinishDto = taskFinishBack(outboundTask, bizOutboundTaskDetail, containerTask.getContainerNo(), containerTaskDismantle.getPlanQty(), BigDecimal.ZERO, 0);
                    wmsTaskFinishDtoList.add(wmsTaskFinishDto);
                }
            }
            containerTaskDismantleService.update(containerTaskDismantle);

            //修改拆零详情表状态为已经拣选，判断当前拆零详情所有拆零任务是否全部拣选，全部拣选才修改
            final List<Integer> detailContainerTaskIds = containerTaskService.findByMap(MapUtils.
                            put(ContainerTask::getOutboundDetailId, outboundTaskDetailDismantle.getOutboundDetailId()).getMap())
                    .stream().map(ContainerTask::getId).collect(Collectors.toList());
            Criteria criteria2 = new Criteria(ContainerTaskDismantle.class);
            criteria2.restrictionBuilder().in(ContainerTaskDismantle::getContainerTaskId, detailContainerTaskIds)
                    .eq(ContainerTaskDismantle::getType, 2).lt(ContainerTaskDismantle::getStatus, 3).build();
            final long count = containerTaskDismantleService.findByCriteria(criteria2).stream().count();
            if (count == 0) {
                outboundTaskDetailDismantle.setStatus(12);
            }
            bizOutboundTaskDetailDismantleService.update(outboundTaskDetailDismantle);

            Criteria criteria1 = new Criteria(ContainerTaskDismantle.class);
            criteria1.restrictionBuilder().eq(ContainerTaskDismantle::getContainerTaskId, containerTask.getId()).eq(ContainerTaskDismantle::getType, 1).build();
            List<ContainerTaskDismantle> containerTaskDismantleList1 = containerTaskDismantleService.findByCriteria(criteria1);
            if (CollectionUtils.isEmpty(containerTaskDismantleList1) || containerTaskDismantleList1.get(0).getStatus() >= 3) {
                //任务完成改状态
                containerTask.setStatus(ContainerTaskStatusConstants.CARRY_RUNNING);
                containerTask.setUpdateTime(LocalDateTime.now());
                containerTaskService.update(containerTask);
                containerTaskService.containerTaskToHis(containerTask);
            }
        }
        Assert.isTrue(CollectionUtils.isNotEmpty(wmsTaskFinishDtoList), "未找到需要返回的容器");
        //调用WMS作业完成回告
        this.wmsTaskFinishBack(wmsTaskFinishDtoList, bizOutboundTaskList, bizOutboundTaskDetailList, outboundTaskDetailDismantles);

        List<ContainerTask> dismantlePickingTask = containerTaskDismantleService.findDismantlePickingList(containerInfoDetail.getContainerNo());
        if (CollectionUtils.isEmpty(dismantlePickingTask) && CollectionUtil.isNotEmpty(cotnainerSet)) {
            // TODO: 2023/10/12 到位完成处理
            Criteria criteria = new Criteria(ContainerInfo.class);
            criteria.setRestriction(Restrictions.eq("containerNo", containerInfoDetail.getContainerNo()));
            containerInfoService.updateByMap(MapUtils.put(ContainerInfo::getTaskType, ContainerTaskTypeConstants.OUTBOUND_RETURN).getMap(), criteria);
        }

        Criteria efficiencyCriteria = Criteria.forClass(EfficiencyStatistics.class);
        efficiencyCriteria.restrictionBuilder().eq(EfficiencyStatistics::getContainerNo, containerInfo.getContainerNo())
                .isnull(EfficiencyStatistics::getLeaveTime).build();
        efficiencyStatisticsMapper.updateMapByCriteria(com.prolog.framework.utils.MapUtils.put("leave_time", new Date()).getMap(), efficiencyCriteria);
    }

    /**
     * 总拣库存扣减
     *
     * @param sumPickQty
     * @param containerInfoDetail
     * @throws Exception
     */
    private Set<String> inventoryDeduction(BigDecimal sumPickQty, ContainerInfoDetail containerInfoDetail) throws Exception {
        Set<String> cotnainerSet = new TreeSet<>();
        containerStoreChangeService.saveStoreChange(containerInfoDetail, sumPickQty, containerInfoDetail.getQty().subtract(sumPickQty), 20, "拣选出库");

        //判断是否拣选成空，托盘拣空去叠盘机，货架不管拣空直接回库
        if (sumPickQty.compareTo(containerInfoDetail.getQty()) == 0) {
            if (StrUtil.equals(containerInfoDetail.getContainerNo(), containerInfoDetail.getContainerSubNo())) {
                emptyContainerTaskService.save(containerInfoDetail.getContainerNo(), LayerEnum.TWO, WmsCarryTaskInCode.AGVL);
                wmsContainerStatusUpdateService.execute(WmsContainerStatusUpdateDto.builder()
                        .containerCode(containerInfoDetail.getContainerNo())
                        .warehouseId("901884530611326976")
                        .enterpriseId("900356013474058240").build());
            } else {
                cotnainerSet.add(containerInfoDetail.getContainerSubNo());
            }
            containerInfoDetailService.deleteById(containerInfoDetail.getId());
        } else {
            //更新库存
            containerInfoDetail.setQty(containerInfoDetail.getQty().subtract(sumPickQty));
            containerInfoDetail.setUpdateTime(LocalDateTime.now());
            if (!containerInfoDetail.getContainerNo().equals(containerInfoDetail.getContainerSubNo())) {
                containerInfoDetail.setVolume(containerInfoDetail.getSingleVolume().multiply(containerInfoDetail.getQty()));
            }
            containerInfoDetailService.update(containerInfoDetail);
            cotnainerSet.add(containerInfoDetail.getContainerSubNo());
        }
        return cotnainerSet;
    }

    /**
     * 回告WMS作业完成确定
     *
     * @param wmsTaskFinishDtoList
     * @param bizOutboundTaskList
     * @param bizOutboundTaskDetailList
     * @param outboundTaskDetailDismantles
     * @throws Exception
     */
    private void wmsTaskFinishBack(List<WmsTaskFinishDto> wmsTaskFinishDtoList, List<BizOutboundTask> bizOutboundTaskList, List<BizOutboundTaskDetail> bizOutboundTaskDetailList, List<BizOutboundTaskDetailDismantle> outboundTaskDetailDismantles) throws Exception {
        RestMessage<JSONObject> restMessage = wmsTaskFinishBackService.execute(wmsTaskFinishDtoList);
        WmsTaskFinishResDto wmsTaskFinishResDto = JSON.parseObject(restMessage.getData().toString(), WmsTaskFinishResDto.class);
        if (CollectionUtils.isNotEmpty(wmsTaskFinishResDto.getFlg())) {
            for (WmsTaskFinishDto messageDatum : wmsTaskFinishResDto.getFlg()) {
                if (BigDecimal.ZERO.compareTo(new BigDecimal(messageDatum.getLackQty())) != 0) {
                    BizOutboundTask outboundTask = bizOutboundTaskList.stream().filter(item -> messageDatum.getBillNo().equals(item.getBillNo()))
                            .findFirst().orElseThrow(() -> new PrologException(String.format("未找到对应的出库单%s", messageDatum.getBillNo())));

                    BizOutboundTaskDetail bizOutboundTaskDetail = bizOutboundTaskDetailList.stream()
                            .filter(item -> messageDatum.getTaskLineId().equals(item.getSeqNo())).findFirst().orElseThrow(() -> new PrologException("未找到对应出库任务详情"));
                    BizOutboundTaskDetailDismantle outboundTaskDetailDismantle = outboundTaskDetailDismantles.stream()
                            .filter(item -> NumberUtil.equals(item.getOutboundDetailId(), bizOutboundTaskDetail.getId())).findFirst().orElseThrow(() -> new PrologException("未找到对应出库拆零任务详情"));

                    if (messageDatum.getFlg() == 0) {
                        outboundTask.setLackState(1);
                        outboundTask.setUpdateTime(LocalDateTime.now());
                        bizOutboundTaskService.update(outboundTask);

                        outboundTaskDetailDismantle.setLackQty(new BigDecimal(messageDatum.getLackQty()));
                        outboundTaskDetailDismantle.setLackState(messageDatum.getFlg());

                        bizOutboundTaskDetail.setLackState(messageDatum.getFlg());
                        bizOutboundTaskDetail.setLackQty(new BigDecimal(messageDatum.getLackQty()));
                    } else {
                        if (bizOutboundTaskDetail.getLackState() != 0) {
                            bizOutboundTaskDetail.setLackState(messageDatum.getFlg());
                            outboundTaskDetailDismantle.setLackState(messageDatum.getFlg());
                        }
                        saveSupplyRecord(bizOutboundTaskDetail, 2, new BigDecimal(messageDatum.getLackQty()));
                        outboundTaskDetailDismantle.setSupplyQty(outboundTaskDetailDismantle.getSupplyQty().add(new BigDecimal(messageDatum.getLackQty())));
                        outboundTaskDetailDismantle.setOfferShowQty(outboundTaskDetailDismantle.getOfferShowQty().add(new BigDecimal(messageDatum.getLackQty())));
                        bizOutboundTaskDetail.setSupplyQty(bizOutboundTaskDetail.getSupplyQty().add(new BigDecimal(messageDatum.getLackQty())));
                    }
                    bizOutboundTaskDetailService.update(bizOutboundTaskDetail);
                }
            }
        }
    }

    private void saveSupplyRecord(BizOutboundTaskDetail outboundTaskDetail, Integer type, BigDecimal supplyQty) {
        BizOutboundTaskDismantleSupply outboundTaskDismantleSupply = new BizOutboundTaskDismantleSupply();
        outboundTaskDismantleSupply.setOutboundId(outboundTaskDetail.getOutboundId());
        outboundTaskDismantleSupply.setOutboundDetailId(outboundTaskDetail.getId());
        outboundTaskDismantleSupply.setType(type);
        outboundTaskDismantleSupply.setCreateTime(new Date());
        outboundTaskDismantleSupply.setItemId(outboundTaskDetail.getItemId());
        outboundTaskDismantleSupply.setLotId(outboundTaskDetail.getLotId());
        outboundTaskDismantleSupply.setOwnerId(outboundTaskDetail.getOwnerId());
        outboundTaskDismantleSupply.setPackId(outboundTaskDetail.getPackId());
        outboundTaskDismantleSupply.setSupplyQty(supplyQty);
        outboundTaskDismantleSupplyService.save(outboundTaskDismantleSupply);
    }

    private WmsTaskFinishDto taskFinishBack(BizOutboundTask bizOutboundTask, BizOutboundTaskDetail
            bizOutboundTaskDetail, String containerNo, BigDecimal lackQty, BigDecimal qty, Integer isLfz) throws Exception {
        return WmsTaskFinishDto.builder().msgId(StrUtil.uuid()).billNo(bizOutboundTask.getBillNo()).containerNo(containerNo)
                .businessType(bizOutboundTask.getBusinessType()).workType(bizOutboundTask.getWorkType()).warehouseId(bizOutboundTask.getWmsWarehouseId())
                .taskId(bizOutboundTask.getUpperSystemTaskId()).taskLineId(bizOutboundTaskDetail.getSeqNo()).itemId(bizOutboundTaskDetail.getItemId())
                .lotId(bizOutboundTaskDetail.getLotId()).ownerId(bizOutboundTaskDetail.getOwnerId()).packId(bizOutboundTaskDetail.getPackId())
                .employeeId(getUserId()).inventoryQty(qty).wmsLocationCode(bizOutboundTask.getWmsLocationCode())
                .lackQty(lackQty.toString()).isLack(lackQty.compareTo(BigDecimal.ZERO) == 0 ? 1 : 0).isLfz(isLfz)
                .build();
    }

    public String getUserId() {
        final UserDTO userDTO = userTemplate.getUserDTO();
        if (null != userDTO) {
            log.info("----->获取用户信息:{}", JSONUtil.toJsonStr(userDTO));
            return userDTO.getUserBizModel().getEmployeeNo();
        }
        throw new PrologException("获取用户信息为空");
    }

    public UserDTO getUserInfo() {
        final UserDTO userDTO = userTemplate.getUserDTO();
        if (null != userDTO) {
            log.info("----->获取用户信息:{}", JSONUtil.toJsonStr(userDTO));
            return userDTO;
        }
        throw new PrologException("获取用户信息为空");
    }

    @Override
    public List<DismantleFullDetailDto> dismantleFullDetail(String containerNo) throws Exception {
        List<ContainerTask> containerTasks = containerTaskDismantleService.dismantleFullDetail(containerNo);
        if (CollectionUtils.isEmpty(containerTasks)) {
            return null;
        }
        List<DismantleFullDetailDto> result = new ArrayList<>();
        final List<String> itemIds = containerTasks.stream().map(ContainerTask::getItemId).collect(Collectors.toList());
        final List<Integer> outboundIds = containerTasks.stream().map(ContainerTask::getOutboundId).collect(Collectors.toList());
        final List<ItemSyncVO> itemInfoList = itemService.queryItemMst(itemIds);
        final List<String> lotIds = containerTasks.stream().map(ContainerTask::getLotId).collect(Collectors.toList());
        List<BatchNumberSync> batchNumberSyncs = inventoryService.getBatchNumberSync(lotIds);
        Criteria criteria = new Criteria(BizOutboundTask.class);
        criteria.restrictionBuilder().in(BizOutboundTask::getId, outboundIds).build();
        List<BizOutboundTask> bizOutboundTaskList = bizOutboundTaskService.findByCriteria(criteria);
        ContainerInfo containerInfo = containerInfoService.findOneByMap(MapUtils.put(ContainerInfo::getContainerNo, containerNo).getMap());
        for (ContainerTask containerTask : containerTasks) {
            ContainerInfoDetail containerInfoDetail = containerInfoDetailService.findOneByMap(MapUtils.put(ContainerInfoDetail::getContainerSubNo, containerTask.getContainerSubNo()).getMap());
            ItemSyncVO itemInfo = itemInfoList.stream().filter(info -> StrUtil.equals(info.getItemId(), containerTask.getItemId())).findFirst().orElseThrow(() -> new PrologException("未查询到商品信息"));
            BatchNumberSync batchNumberSync = batchNumberSyncs.stream().filter(info -> StrUtil.equals(info.getBatchId(), containerTask.getLotId())).findFirst().orElseThrow(() -> new PrologException("未查询到批次信息"));
            BizOutboundTask outboundTask = bizOutboundTaskList.stream().filter(info -> NumberUtil.equals(info.getId(), containerTask.getOutboundId())).findFirst().orElseThrow(() -> new PrologException("未查询到出库单信息"));
            result.add(DismantleFullDetailDto.builder()
                    .goodsName(itemInfo.getItemName())
                    .goodsCode(itemInfo.getItemCode())
                    .lotNo(batchNumberSync.getManufacturerLotNum())
                    .billNo(outboundTask.getBillNo())
                    .locationNo(containerInfo.getSource())
                    .id(containerTask.getId())
                    .dismantleQty(BigDecimal.ZERO)
                    .qty(containerTask.getQty())
                    .pickQty(itemInfo.getUomList().get(0).getConversionRate())
                    .pieceQty(containerTask.getQty().divide(itemInfo.getUomList().get(0).getConversionRate()))
                    .itemId(containerTask.getItemId())
                    .lotId(containerTask.getLotId())
                    .containerQty(containerInfoDetail.getQty())
                    .businessType(outboundTask.getBusinessType())
                    .containerSubNo(containerTask.getContainerSubNo())
                    .containerNo(containerTask.getContainerNo())
                    .goodsSpec(itemInfo.getSpecification())
                    .superviseflag(itemInfo.getItemHealthSuperviseflag())
                    .build());
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @TxTransaction(rollbackFor = Exception.class)
    public void dismantleFullConfirm(DismantleConfirmReqDto req) throws Exception {
        ContainerTask containerTask = containerTaskService.findById(req.getId());
        AssertUtils.isNotNull(containerTask, "没有查询到任务");
        ContainerTaskDismantle containerTaskDismantle = containerTaskDismantleService.findOneByMap(MapUtils.put(ContainerTaskDismantle::getContainerTaskId, req.getId()).put(ContainerTaskDismantle::getType, 1).getMap());
        AssertUtils.isNotNull(containerTaskDismantle, "没有查询到任务");
        String containerNo = containerTask.getContainerNo();
        List<ContainerLocationVo> containerLocationVoList = routeFeignService.findLocationByContainerList(Arrays.asList(containerNo));
        if (CollectionUtils.isEmpty(containerLocationVoList)) {
            throw new PrologException(String.format("容器%s未查询到点位信息", containerNo));
        }
        StationCfg stationCfg = stationCfgService.findByMap(MapUtils.put(StationCfg::getStationType, 91).getMap()).stream().findFirst().orElseThrow(() -> new PrologException("拆零总拣站台未配置"));
        ContainerLocationVo containerLocationVo = containerLocationVoList.get(0);
        if (!StrUtil.equals(containerLocationVo.getCurrentArea(), stationCfg.getAreaNo())) {
            throw new PrologException(String.format("容器%s未到位无法确认", containerNo));
        }
        containerTaskDismantle.setStatus(3);
        AssertUtils.isNotTrue(req.getQty().compareTo(containerTaskDismantle.getPlanQty()) > 0, "拣选数量不能大于计划数量");
        ContainerInfo containerInfo = containerInfoService.findOneByMap(MapUtils.put(ContainerInfo::getContainerNo, containerTask.getContainerNo()).getMap());
        if (!Objects.equals(containerInfo.getTaskType(), BaseTaskTypeConstants.DISMANTLE_OUTBOUND_END_TYPE)) {
            throw new PrologException(String.format("容器%s未到位无法确认", containerNo));
        }
        ContainerInfoDetail containerInfoDetail = containerInfoDetailService.findOneByMap(MapUtils.put(ContainerInfoDetail::getContainerSubNo, containerTask.getContainerSubNo()).getMap());
        AssertUtils.isNotTrue(Objects.isNull(containerInfo) || Objects.isNull(containerInfoDetail), "容器库存未查到");
        BizOutboundTask bizOutboundTask = bizOutboundTaskService.findById(containerTask.getOutboundId());
        AssertUtils.isNotNull(bizOutboundTask, "未查询到对应出库单信息");
        BizOutboundTaskDetail bizOutboundTaskDetail = bizOutboundTaskDetailService.findById(containerTask.getOutboundDetailId());
        AssertUtils.isNotNull(bizOutboundTaskDetail, "未查询到对应出库单信息");
        BizOutboundTaskDetailDismantle bizOutboundTaskDetailDismantle = bizOutboundTaskDetailDismantleService.findByMap(MapUtils.put(BizOutboundTaskDetailDismantle::getOutboundId, bizOutboundTask.getId()).put(BizOutboundTaskDetailDismantle::getOutboundDetailId, bizOutboundTaskDetail.getId()).put(BizOutboundTaskDetailDismantle::getType, 1).getMap()).stream().findFirst().orElseThrow(() -> new PrologException("未查询到零发整任务"));
        LocationCfg locationCfg = locationCfgService.findOneByMap(MapUtils.put(LocationCfg::getType, containerInfo.getAGVLCode()).put(LocationCfg::getWmsAreaNo, WmsCarryTaskInCode.AGVL.getCode()).getMap());
        AssertUtils.isNotNull(locationCfg, "拆零区未配置");
        AssertUtils.isNotTrue(req.getSuperviseflag() == 1 && CollectionUtils.isEmpty(req.getDrugSupervisionCode()), "药监码不能为空");
        AssertUtils.isNotTrue(req.getSuperviseflag() == 1 && req.getDrugSupervisionCode().size() != req.getPieceQty().intValue(), "药监码数量和实物数量不一致");
        if (req.getSuperviseflag() == 1) {
            List<String> list = Convert.toList(String.class, bizOutboundTaskDetailDismantle.getDrugSupervisionCode());
            req.getDrugSupervisionCode().addAll(list);
            int size = req.getDrugSupervisionCode().size();
            long count = req.getDrugSupervisionCode().stream().distinct().count();
            AssertUtils.isNotTrue(size != count, "监管码不能重复");
            List<BizOutboundTaskDetailDismantle> bizOutboundTaskDetailDismantleList = bizOutboundTaskDetailDismantleService.findByMap(MapUtils.put(BizOutboundTaskDetailDismantle::getOutboundId, bizOutboundTaskDetailDismantle.getOutboundId()).getMap()).stream().filter(item -> !Objects.equals(item.getId(), bizOutboundTaskDetailDismantle.getId())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(bizOutboundTaskDetailDismantleList)) {
                List<String> codeList = new ArrayList<>();
                for (BizOutboundTaskDetailDismantle outboundTaskDetailDismantle : bizOutboundTaskDetailDismantleList) {
                    if (StrUtil.isNotBlank(outboundTaskDetailDismantle.getDrugSupervisionCode())) {
                        codeList.addAll(Convert.toList(String.class, outboundTaskDetailDismantle.getDrugSupervisionCode()));
                    }
                }
                codeList.addAll(req.getDrugSupervisionCode());
                size = codeList.size();
                count = codeList.stream().distinct().count();
                AssertUtils.isNotTrue(size != count, "监管码不能重复");
            }
            bizOutboundTaskDetailDismantle.setDrugSupervisionCode(StrUtil.join(",", req.getDrugSupervisionCode()));
        }
        //2 扣减库存
        BigDecimal qty = req.getPickQty().multiply(req.getPieceQty());
        BigDecimal remainQry = containerInfoDetail.getQty().subtract(qty);
        //需补货的数量
        BigDecimal supplyQty = containerTaskDismantle.getPlanQty().subtract(qty);
        containerStoreChangeService.saveStoreChange(containerInfoDetail, qty.subtract(containerInfoDetail.getQty()), remainQry, Integer.valueOf(bizOutboundTask.getWorkType()), "拣选出库");
        if (remainQry.compareTo(BigDecimal.ZERO) == 0 && StrUtil.equals(containerTask.getContainerNo(), containerTask.getContainerSubNo())) {
            //拣成空托 搬到叠盘机删库存
            emptyContainerTaskService.save(containerTask.getContainerNo(), LayerEnum.TWO, WmsCarryTaskInCode.AGVL);
            wmsContainerStatusUpdateService.execute(WmsContainerStatusUpdateDto.builder()
                    .containerCode(containerTask.getContainerNo())
                    .enterpriseId(bizOutboundTask.getEnterpriseId())
                    .warehouseId(bizOutboundTask.getWmsWarehouseId())
                    .build());
        } else {
            if (remainQry.compareTo(BigDecimal.ZERO) == 0) {
                containerInfoDetailService.deleteById(containerInfoDetail.getId());
//                final List<ContainerInfoDetail> containerInfoDetailList = containerInfoDetailService.findByMap(MapUtils.put(ContainerInfoDetail::getContainerNo, containerInfo.getContainerNo()).getMap());
//                if (CollectionUtils.isEmpty(containerInfoDetailList)) {
//                    containerInfoService.deleteById(containerInfo.getId());
//                }
            } else {
                containerInfoDetail.setQty(remainQry);
                containerInfoDetail.setUpdateTime(LocalDateTime.now());
                if (supplyQty.compareTo(BigDecimal.ZERO) > 0) {
                    //如果需要补货，计算库存是否有剩余数量，有余量并且小于补货数量，锁定全部库存，大于库存数量锁定数量为补货数量
                    containerInfoDetail.setLockQty(supplyQty.compareTo(containerInfoDetail.getQty()) > 0 ? containerInfoDetail.getQty() : supplyQty);
                }
                if (!containerInfoDetail.getContainerNo().equals(containerInfoDetail.getContainerSubNo())) {
                    containerInfoDetail.setVolume(containerInfoDetail.getSingleVolume().multiply(containerInfoDetail.getQty()));
                }
                containerInfoDetailService.update(containerInfoDetail);

            }
            List<ContainerTask> containerTasks = containerTaskDismantleService.dismantleFullDetail(containerTask.getContainerNo());
            long count = containerTasks.stream().filter(item -> !Objects.equals(item.getId(), containerTask.getId())).count();
            if (count == 0) {
                // TODO: 2023/10/12 到位完成处理
                Criteria criteria = new Criteria(ContainerInfo.class);
                criteria.setRestriction(Restrictions.eq("containerNo", containerInfoDetail.getContainerNo()));
                containerInfoService.updateByMap(com.prolog.framework.utils.MapUtils.put("taskType", ContainerTaskTypeConstants.OUTBOUND_RETURN).getMap(), criteria);
            }

//            plgRouteFeignService.updateWorkStatus(containerInfoDetail.getContainerNo());
        }

        //4 记录实际出库数量
        if (supplyQty.compareTo(BigDecimal.ZERO) > 0) {
            WmsTaskFinishDto wmsTaskFinishDto = taskFinishBack(bizOutboundTask, bizOutboundTaskDetail, containerTask.getContainerNo(), supplyQty, qty, 1);
            RestMessage<JSONObject> restMessage = wmsTaskFinishBackService.execute(Arrays.asList(wmsTaskFinishDto));
            WmsTaskFinishResDto wmsTaskFinishResDto = JSON.parseObject(restMessage.getData().toString(), WmsTaskFinishResDto.class);
            Assert.isTrue(CollectionUtils.isNotEmpty(wmsTaskFinishResDto.getFlg()), "任务回传失败");
            WmsTaskFinishDto data = wmsTaskFinishResDto.getFlg().get(0);
            if (data.getFlg() == 0) {
                bizOutboundTask.setLackState(1);
                bizOutboundTask.setUpdateTime(LocalDateTime.now());
                bizOutboundTaskService.update(bizOutboundTask);
                bizOutboundTaskDetail.setLackState(data.getFlg());
                bizOutboundTaskDetail.setLackQty(bizOutboundTaskDetail.getLackQty().add(supplyQty));
                bizOutboundTaskDetailDismantle.setLackState(data.getFlg());
                bizOutboundTaskDetailDismantle.setLackQty(bizOutboundTaskDetailDismantle.getLackQty().add(supplyQty));
            } else {
                if (bizOutboundTaskDetail.getLackState() != 0) {
                    bizOutboundTaskDetailDismantle.setLackState(data.getFlg());
                    bizOutboundTaskDetail.setLackState(data.getFlg());
                }
                saveSupplyRecord(bizOutboundTaskDetail, 1, supplyQty);
                bizOutboundTaskDetailDismantle.setSupplyQty(bizOutboundTaskDetailDismantle.getSupplyQty().add(supplyQty));
                bizOutboundTaskDetail.setSupplyQty(bizOutboundTaskDetail.getSupplyQty().add(supplyQty));
            }
            containerTaskDismantle.setActQty(containerTaskDismantle.getActQty().add(qty));
            containerTaskDismantleService.update(containerTaskDismantle);

        } else {
            containerTaskDismantle.setActQty(containerTaskDismantle.getActQty().add(containerTaskDismantle.getPlanQty()));
            containerTaskDismantleService.update(containerTaskDismantle);
            WmsTaskFinishDto wmsTaskFinishDto = taskFinishBack(bizOutboundTask, bizOutboundTaskDetail, containerTask.getContainerNo(), BigDecimal.ZERO, containerTaskDismantle.getPlanQty(), 1);
            wmsTaskFinishBackService.execute(Arrays.asList(wmsTaskFinishDto));
        }

        bizOutboundTaskDetailService.update(bizOutboundTaskDetail);

        List<BizOutboundTaskDetailDismantle> outboundTaskDetailDismantleList = bizOutboundTaskDetailDismantleService.findByMap(MapUtils.put(BizOutboundTaskDetailDismantle::getOutboundId, bizOutboundTask.getId()).getMap());

        //修改零发整详情表状态为已经拣选，判断当前零发整详情所有零发整任务是否全部拣选，全部拣选才修改
        final List<Integer> detailContainerTaskIds = containerTaskService.findByMap(MapUtils.put(ContainerTask::getOutboundDetailId, bizOutboundTaskDetailDismantle.getOutboundDetailId()).getMap()).stream().map(ContainerTask::getId).collect(Collectors.toList());
        Criteria criteria2 = new Criteria(ContainerTaskDismantle.class);
        criteria2.restrictionBuilder().in(ContainerTaskDismantle::getContainerTaskId, detailContainerTaskIds).eq(ContainerTaskDismantle::getType, 1).lt(ContainerTaskDismantle::getStatus, 3).build();
        final long count2 = containerTaskDismantleService.findByCriteria(criteria2).stream().count();
        if (count2 == 0) {
            bizOutboundTaskDetailDismantle.setStatus(12);

            WmsOfferBackDetailDto wmsOfferBackDetailDto = WmsOfferBackDetailDto.builder()
                    .taskLineId(bizOutboundTaskDetail.getSeqNo())
                    .itemId(bizOutboundTaskDetail.getItemId())
                    .lotId(bizOutboundTaskDetail.getLotId())
                    .ownerId(bizOutboundTaskDetail.getOwnerId())
                    .packId(bizOutboundTaskDetail.getPackId())
                    .qty(bizOutboundTaskDetailDismantle.getOfferQty())
                    .drugSupervisionCode(Convert.toList(String.class, bizOutboundTaskDetailDismantle.getDrugSupervisionCode()))
                    .build();

            bizOutboundTaskDetailDismantle.setExtend2(JSONUtil.toJsonStr(wmsOfferBackDetailDto));

            final List<BizOutboundTaskDismantleSupply> supplyList = outboundTaskDismantleSupplyService.findByMap(MapUtils.put(BizOutboundTaskDismantleSupply::getOutboundId, bizOutboundTask.getId()).put(BizOutboundTaskDismantleSupply::getType, 1).getMap());
            if (CollectionUtils.isEmpty(supplyList)) {
                //保存打印信息
//                //判断此订单是否有拆零
                long count = outboundTaskDetailDismantleList.stream().filter(item -> item.getType() == 2).count();
                if (count > 0) {
                    PrintTask printTask = new PrintTask();
                    printTask.setType(7);
                    printTask.setPrintCount(0);
                    printTask.setGridNo(null);
                    printTask.setCreateTime(new Date());
                    printTask.setStatus(0);
                    printTask.setWmsOutTaskId(bizOutboundTask.getId());
                    printTask.setPrintData(bizOutboundTask.getBillNo());
                    printTask.setExtend1(getUserInfo().getUsername());
                    printTaskService.save(printTask);
                }
            }
        }

        bizOutboundTaskDetailDismantleService.update(bizOutboundTaskDetailDismantle);

        long count = outboundTaskDetailDismantleList.stream().filter(item -> StrUtil.isBlank(item.getExtend2())).count();
        final List<BizOutboundTaskDismantleSupply> supplyList = outboundTaskDismantleSupplyService.findByMap(MapUtils.put(BizOutboundTaskDismantleSupply::getOutboundId, bizOutboundTask.getId()).getMap());
        if (count == 0 && CollectionUtils.isEmpty(supplyList)) {
            List<WmsOfferBackDetailDto> wmsOfferBackDetailDtos = new ArrayList<>();
            for (BizOutboundTaskDetailDismantle temp : outboundTaskDetailDismantleList) {
                WmsOfferBackDetailDto bean = JSONUtil.toBean(temp.getExtend2(), WmsOfferBackDetailDto.class);
                wmsOfferBackDetailDtos.add(bean);
            }
            //组装回告数据
            WmsOfferBackDto wmsOfferBackDto = WmsOfferBackDto.builder()
                    .taskId(bizOutboundTask.getUpperSystemTaskId())
                    .billNo(bizOutboundTask.getBillNo())
                    .enterpriseId(bizOutboundTask.getEnterpriseId())
                    .warehouseId(bizOutboundTask.getWmsWarehouseId())
                    .employeeId(getUserId())
                    .subList(wmsOfferBackDetailDtos)
                    .build();
            //保存打印信息
            PrintTask printTask = new PrintTask();
            printTask.setPrintCount(0);
            printTask.setGridNo(null);
            printTask.setCreateTime(new Date());
            printTask.setStatus(0);
            printTask.setWmsOutTaskId(bizOutboundTask.getId());
            printTask.setType(3);
            printTask.setPrintData(JSONUtil.toJsonStr(wmsOfferBackDto));
            printTaskService.save(printTask);
        }

        Criteria criteria1 = new Criteria(ContainerTaskDismantle.class);
        criteria1.restrictionBuilder().eq(ContainerTaskDismantle::getContainerTaskId, containerTask.getId()).eq(ContainerTaskDismantle::getType, 2).build();
        List<ContainerTaskDismantle> containerTaskDismantleList1 = containerTaskDismantleService.findByCriteria(criteria1);
        if (CollectionUtils.isEmpty(containerTaskDismantleList1) || containerTaskDismantleList1.get(0).getStatus() >= 3) {
            containerTask.setStatus(3);
            containerTask.setUpdateTime(LocalDateTime.now());
            containerTaskService.update(containerTask);

            containerTaskService.containerTaskToHis(containerTask);
            outboundToHis(bizOutboundTask);
        }
    }

    private void outboundToHis(BizOutboundTask bizOutboundTask) {
        List<BizOutboundTaskDetailDismantle> outboundTaskDetailDismantles = bizOutboundTaskDetailDismantleService.findByMap(MapUtils.put(BizOutboundTaskDetailDismantle::getOutboundId, bizOutboundTask.getId()).getMap());
        for (BizOutboundTaskDetailDismantle taskDetailDismantle : outboundTaskDetailDismantles) {
            if (taskDetailDismantle.getType() == 1 && taskDetailDismantle.getStatus() < 12) {
                return;
            }
            if (taskDetailDismantle.getType() == 2 && taskDetailDismantle.getStatus() != 20) {
                return;
            }
        }
        bizOutboundTaskService.outboundToHis(bizOutboundTask);
    }


    @Override
    public PackOrderInfoDto packOrder(String gridNo) {
        final GridInfo gridInfo = gridInfoService.findOneByMap(MapUtils.put(GridInfo::getGridNo, gridNo).getMap());
        AssertUtils.isNotNull(gridInfo, "对应格口信息未配置");
        if (gridInfo.getOrderId() == null) {
            log.warn("格口：{}订单已完成或没有订单", gridInfo.getOrderId());
            return null;
        }
        final BizOutboundTask outboundTask = bizOutboundTaskService.findById(Integer.valueOf(gridInfo.getOrderId()));
        AssertUtils.isNotTrue(Objects.isNull(outboundTask), "此格口没有订单或已完成");
        AssertUtils.isNotNull(outboundTask, "未找到格口订单信息");

        int state = outboundTask.getLackState() == 1 && gridInfo.getLastFlag() == 1 ? 5 : gridInfo.getFallGrid() == 1 ? 4 : 3;
        return PackOrderInfoDto.builder()
                .companyName(outboundTask.getCompanyName())
                .billNo(outboundTask.getBillNo())
                .gridNo(gridNo)
                .status(state)
                .id(outboundTask.getId())
                .build();
    }

    @Override
    public void unpacking(UnpackingDto req) {
        //已打印次数
//        long count = printTaskService.findCountByMap(MapUtils.put(PrintTask::getWmsOutTaskId, req.getId()).put(PrintTask::getType, 1).getMap());
//        AssertUtils.isNotTrue(req.getNum() < count, String.format("拆包数量不能小于%s", count));
        BizOutboundTask outboundTask = bizOutboundTaskService.findById(req.getId());
        outboundTask.setBillCount(req.getNum());
        bizOutboundTaskService.update(outboundTask);
        GridInfo gridInfo = gridInfoService.findOneByMap(MapUtils.put(GridInfo::getGridNo, req.getGridNo()).getMap());
        if (Objects.isNull(gridInfo.getOrderId()) || !Objects.equals(gridInfo.getOrderId(), req.getId())) {
            throw new PrologException(String.format("订单%s没有绑定格口%s", outboundTask.getBillNo(), gridInfo.getGridNo()));
        }
        WmsApplePrintDto wmsApplePrintDto = new WmsApplePrintDto();
        wmsApplePrintDto.setWarehouseId(outboundTask.getWmsWarehouseId());
        wmsApplePrintDto.setTaskId(outboundTask.getUpperSystemTaskId());
        wmsApplePrintDto.setBillNo(outboundTask.getBillNo());
        wmsApplePrintDto.setEnterpriseId(outboundTask.getEnterpriseId());
        wmsApplePrintDto.setGridNo(gridInfo.getGridNo());
        wmsApplePrintDto.setLabelCount(req.getNum());
        wmsApplePrintDto.setPackFlag(1);
        PrintTask printTask = new PrintTask();
        printTask.setType(10);
        printTask.setPrintCount(0);
        printTask.setGridNo(null);
        printTask.setPrintData(JSONUtil.toJsonStr(wmsApplePrintDto));
        printTask.setCreateTime(new Date());
        printTask.setStatus(0);
        printTask.setWmsOutTaskId(req.getId());
        printTaskService.save(printTask);
    }


    @Override
    public void tagPrint(Integer id, String gridNo) {
//        long count = printTaskService.findCountByMap(MapUtils.put(PrintTask::getWmsOutTaskId, id).put(PrintTask::getType, 1).getMap());
        BizOutboundTask outboundTask = bizOutboundTaskService.findById(id);
//        AssertUtils.isNotTrue(count + 1 > outboundTask.getBillCount(), "打印失败：已超过打印次数");
        if (outboundTask.getLackState() == 1) {
            //打印异常标签
            PrintTask printTask = new PrintTask();
            printTask.setType(6);
            printTask.setPrintCount(0);
            printTask.setGridNo(null);
            printTask.setCreateTime(new Date());
            printTask.setStatus(0);
            printTask.setWmsOutTaskId(id);
            printTaskService.save(printTask);
        } else {
            GridInfo gridInfo = gridInfoService.findOneByMap(MapUtils.put(GridInfo::getGridNo, gridNo).getMap());
            if (Objects.isNull(gridInfo.getOrderId()) || !Objects.equals(gridInfo.getOrderId(), id)) {
                throw new PrologException(String.format("订单%s没有绑定格口%s", outboundTask.getBillNo(), gridInfo.getGridNo()));
            }
            PrintTask printTask = new PrintTask();
            printTask.setPrintCount(0);
            printTask.setGridNo(gridInfo.getGridNo());
            printTask.setCreateTime(new Date());
            printTask.setStatus(0);
            printTask.setWmsOutTaskId(id);
            printTask.setType(1);
            printTaskService.save(printTask);
        }
    }

    @Override
    public PackOrderRespDto packOrderDetail(PackOrderDetailReqDto req, int flag) throws Exception {
        GridInfo gridInfo = gridInfoService.findOneByMap(MapUtils.put(GridInfo::getGridNo, req.getGridNo()).getMap());
        BizOutboundTask outboundTask = bizOutboundTaskService.findById(req.getId());
        if (Objects.isNull(gridInfo) || Objects.isNull(gridInfo.getOrderId()) || !Objects.equals(gridInfo.getOrderId(), req.getId())) {
            throw new PrologException(String.format("格口号%s未绑定订单%s", req.getGridNo(), outboundTask.getBillNo()));
        }
        PackOrderRespDto result = new PackOrderRespDto();
        List<PackOrderDetailRespDto> packOrderDetail = new ArrayList<>();
        //订单绑定的最后一个格口才显示物料
        if (gridInfo.getLastFlag() == 1) {
            List<BizOutboundTaskDetailItem> outboundTaskDetailItems = outboundTaskDetailItemService.findByMap(MapUtils.put(BizOutboundTaskDetailItem::getOutboundId, req.getId()).getMap());
            for (BizOutboundTaskDetailItem outboundTaskDetailItem : outboundTaskDetailItems) {
                packOrderDetail.add(PackOrderDetailRespDto.builder()
                        .billNo(outboundTask.getBillNo())
                        .itemId(outboundTaskDetailItem.getItemId())
                        .lotId(outboundTaskDetailItem.getLotId())
                        .status(6)
                        .planQty(outboundTaskDetailItem.getPlanQty())
                        .build());

            }
        }
        List<PackOrderDetailRespDto> packOrderDetail1 = bizOutboundTaskDetailService.findPackOrderDetail(req.getId(), req.getGridNo());
        if (gridInfo.getLastFlag() == 1) {
            List<Integer> detailId = new ArrayList<>();
            List<PackOrderDetailRespDto> packOrderDetailLast = bizOutboundTaskDetailService.findPackOrderDetailLast(req.getId());
            for (PackOrderDetailRespDto entity : packOrderDetail1) {
                PackOrderDetailRespDto packOrder = packOrderDetailLast.stream().filter(item -> StrUtil.equals(item.getItemId(), entity.getItemId()) && StrUtil.equals(item.getLotId(), entity.getLotId())).findFirst().orElse(null);
                if (Objects.nonNull(packOrder)) {
                    entity.setPlanQty(entity.getPlanQty().add(packOrder.getPlanQty()));
                    detailId.add(packOrder.getOutboundDetailId());
                }
            }
            if (CollectionUtils.isNotEmpty(detailId)) {
                packOrderDetailLast = packOrderDetailLast.stream().filter(item -> !detailId.contains(item.getOutboundDetailId())).collect(Collectors.toList());
            }
            packOrderDetail.addAll(packOrderDetailLast);
        }
        packOrderDetail.addAll(packOrderDetail1);
        if (StrUtil.isNotBlank(req.getCode()) && flag == 1) {
            ItemBarCodeVO itemBarCodeVO = itemService.queryItemByBarCode(req.getCode());
            packOrderDetail = packOrderDetail.stream().filter(item -> StrUtil.equals(item.getItemId(), itemBarCodeVO.getItemId())).collect(Collectors.toList());
        }
        result.setBtnFlag(flag == 1 ? 2 : gridInfo.getScanFinish());
        if (CollectionUtils.isEmpty(packOrderDetail)) {
            return result;
        }


        List<ItemSyncVO> itemInfoList = itemService.queryItemMst(packOrderDetail.stream().map(PackOrderDetailRespDto::getItemId).collect(Collectors.toList()));
        List<BatchNumberSync> batchNumberList = inventoryService.getBatchNumberSync(packOrderDetail.stream().map(PackOrderDetailRespDto::getLotId).collect(Collectors.toList()));
        packOrderDetail.forEach(item -> {
            if (gridInfo.getScanFinish() == 0) {
                int state = Objects.nonNull(item.getStatus()) ? item.getStatus() : item.getOfferQty().compareTo(item.getPlanQty()) >= 0 ? 4 : 3;
                item.setStatus(state);
            } else if (gridInfo.getScanFinish() == 1) {
                int state = Objects.nonNull(item.getStatus()) ? item.getStatus() : item.getOfferQty().compareTo(item.getPlanQty()) >= 0 ? 4 : 5;
                item.setStatus(state);
                if (state == 5) {
                    item.setLackQty(item.getPlanQty().subtract(item.getOfferQty()));
                }
            }
            ItemSyncVO itemInfo = itemInfoList.stream().filter(inner -> StrUtil.equals(inner.getItemId(), item.getItemId())).findFirst().orElseThrow(() -> new PrologException("未查询到商品信息"));
            BatchNumberSync batchNumber = batchNumberList.stream().filter(inner -> StrUtil.equals(inner.getBatchId(), item.getLotId())).findFirst().orElseThrow(() -> new PrologException("未查询到商品批次信息"));
            item.setItemName(itemInfo.getItemName());
            item.setBarcode(itemInfo.getPieceBarcode());
            item.setLotNo(batchNumber.getBatchNum());
        });
        result.setList(packOrderDetail);
        return result;
    }

    @Override
    @Transactional
    public List<PackOrderCheckRespDto> checkOrder(Integer id, String gridNo) throws Exception {
        BizOutboundTask outboundTask = bizOutboundTaskService.findById(id);
        GridInfo gridInfo = gridInfoService.findOneByMap(MapUtils.put(GridInfo::getGridNo, gridNo).getMap());
        if (Objects.isNull(gridInfo) || Objects.isNull(gridInfo.getOrderId()) || !Objects.equals(gridInfo.getOrderId(), id)) {
            throw new PrologException(String.format("格口号%s未绑定订单%s", gridNo, outboundTask.getBillNo()));
        }
        if (gridInfo.getLastFlag() != 1) {
            return null;
        }
        Criteria criteria = new Criteria(BizOutboundTaskDetailDismantle.class);
        criteria.restrictionBuilder().eq(BizOutboundTaskDetailDismantle::getOutboundId, id).eq(BizOutboundTaskDetailDismantle::getType, 2).lt(BizOutboundTaskDetailDismantle::getStatus, 12).build();
        List<BizOutboundTaskDetailDismantle> listDis = bizOutboundTaskDetailDismantleService.findByCriteria(criteria);
        if (CollectionUtils.isNotEmpty(listDis)) {
            throw new PrologException("当前订单还有未拣货的商品");
        }
        //判断订单是否已复核
        if (outboundTask.getStatus() < BaseStatusEnum.STATUS_OFFER.getCode()) {
            //获取未复核的详情
            criteria = new Criteria(BizOutboundTaskDetailDismantle.class);
            criteria.restrictionBuilder().eq(BizOutboundTaskDetailDismantle::getOutboundId, id).eq(BizOutboundTaskDetailDismantle::getType, 2).lt(BizOutboundTaskDetailDismantle::getStatus, BaseStatusEnum.STATUS_OFFER.getCode()).build();
            List<BizOutboundTaskDetailDismantle> outboundTaskDetailDismantleList = bizOutboundTaskDetailDismantleService.findByCriteria(criteria);
            //查询未复核的商品是否需要填写药监码
            List<String> itemIds = outboundTaskDetailDismantleList.stream().map(BizOutboundTaskDetailDismantle::getItemId).collect(Collectors.toList());
            List<String> lotIds = outboundTaskDetailDismantleList.stream().map(BizOutboundTaskDetailDismantle::getLotId).collect(Collectors.toList());
            List<ItemSyncVO> itemList = itemService.queryItemMst(itemIds);
            List<ItemSyncVO> list = itemList.stream().filter(item -> item.getItemHealthSuperviseflag() == 1).collect(Collectors.toList());
            if (list.size() == 0) {
                doOfferBack(outboundTask);
                return null;
            }
            List<BatchNumberSync> batchNumberSync = inventoryService.getBatchNumberSync(lotIds);
            List<PackOrderCheckRespDto> resultList = new ArrayList<>();
            for (ItemSyncVO itemSyncVO : list) {
                List<BizOutboundTaskDetailDismantle> collect = outboundTaskDetailDismantleList.stream().filter(item -> StrUtil.equals(item.getItemId(), itemSyncVO.getItemId())).collect(Collectors.toList());
                for (BizOutboundTaskDetailDismantle outboundTaskDetailDismantle : collect) {
                    BatchNumberSync batchNumberSync1 = batchNumberSync.stream().filter(item -> StrUtil.equals(item.getBatchId(), outboundTaskDetailDismantle.getLotId())).findFirst().get();
                    resultList.add(PackOrderCheckRespDto.builder()
                            .outboundId(id)
                            .outboundDetailDismantleId(outboundTaskDetailDismantle.getId())
                            .outboundDetailId(outboundTaskDetailDismantle.getOutboundDetailId())
                            .itemId(itemSyncVO.getItemId())
                            .lotId(outboundTaskDetailDismantle.getLotId())
                            .itemName(itemSyncVO.getItemName())
                            .lotNo(batchNumberSync1.getManufacturerLotNum())
                            .qty(outboundTaskDetailDismantle.getPlanQty().subtract(outboundTaskDetailDismantle.getOfferQty()).subtract(outboundTaskDetailDismantle.getOfferShowQty()).subtract(outboundTaskDetailDismantle.getLackQty()))
                            .build());
                }
            }
            return resultList;
        }
        return null;
    }

    private void doOfferBack(BizOutboundTask outboundTask) {
        outboundTask.setStatus(BaseStatusEnum.STATUS_OFFER.getCode());
        outboundTask.setUpdateTime(LocalDateTime.now());
        bizOutboundTaskService.update(outboundTask);

        List<BizOutboundTaskDetailDismantle> outboundTaskDetailDismantleList = bizOutboundTaskDetailDismantleService.findByMap(MapUtils.put(BizOutboundTaskDetailDismantle::getOutboundId, outboundTask.getId()).getMap());
        for (BizOutboundTaskDetailDismantle outboundTaskDetailDismantle : outboundTaskDetailDismantleList) {
            if (StrUtil.isBlank(outboundTaskDetailDismantle.getExtend2())) {
                BizOutboundTaskDetail outboundTaskDetail = bizOutboundTaskDetailService.findById(outboundTaskDetailDismantle.getOutboundDetailId());
                WmsOfferBackDetailDto wmsOfferBackDetailDto = WmsOfferBackDetailDto.builder()
                        .taskLineId(outboundTaskDetail.getSeqNo())
                        .itemId(outboundTaskDetail.getItemId())
                        .lotId(outboundTaskDetail.getLotId())
                        .ownerId(outboundTaskDetail.getOwnerId())
                        .packId(outboundTaskDetail.getPackId())
                        .qty(outboundTaskDetailDismantle.getPlanQty().subtract(outboundTaskDetailDismantle.getOfferShowQty()).subtract(outboundTaskDetailDismantle.getLackQty()))
                        .drugSupervisionCode(Convert.toList(String.class, outboundTaskDetailDismantle.getDrugSupervisionCode()))
                        .build();
                outboundTaskDetailDismantle.setExtend2(JSONUtil.toJsonStr(wmsOfferBackDetailDto));
                bizOutboundTaskDetailDismantleService.update(outboundTaskDetailDismantle);
            }
        }

        List<WmsOfferBackDetailDto> wmsOfferBackDetailDtos = new ArrayList<>();
        for (BizOutboundTaskDetailDismantle bizOutboundTaskDetail : outboundTaskDetailDismantleList) {
            WmsOfferBackDetailDto bean = JSONUtil.toBean(bizOutboundTaskDetail.getExtend2(), WmsOfferBackDetailDto.class);
            wmsOfferBackDetailDtos.add(bean);
        }
        //组装回告数据
        WmsOfferBackDto wmsOfferBackDto = WmsOfferBackDto.builder()
                .taskId(outboundTask.getUpperSystemTaskId())
                .billNo(outboundTask.getBillNo())
                .enterpriseId(outboundTask.getEnterpriseId())
                .warehouseId(outboundTask.getWmsWarehouseId())
                .employeeId(getUserId())
                .subList(wmsOfferBackDetailDtos)
                .build();
        //保存打印信息
        PrintTask printTask = new PrintTask();
        printTask.setPrintCount(0);
        printTask.setGridNo(null);
        printTask.setCreateTime(new Date());
        printTask.setUpdateTime(new Date());
        printTask.setStatus(0);
        printTask.setWmsOutTaskId(outboundTask.getId());
        printTask.setType(3);
        printTask.setPrintData(JSONUtil.toJsonStr(wmsOfferBackDto));
        printTaskService.save(printTask);
    }

    @Override
    public String itemSuperviseCheck(PackOrderItemSuperviseDto req) {
        if (CollectionUtil.isEmpty(req.getList())) {
            throw new PrologException("请采集药监码");
        }
        List<PackOrderItemSuperviseDetailDto> list = req.getList();
        for (PackOrderItemSuperviseDetailDto item : list) {
            if (CollectionUtil.isEmpty(item.getCodeList())) {
                throw new PrologException("请采集药监码");
            }
        }
        //药监码无品批信息
        List<String> codeNotLot = new ArrayList<>();
        //药监码与品批不一致
        List<String> codeLotDis = new ArrayList<>();
        for (PackOrderItemSuperviseDetailDto item : list) {
            int size = item.getCodeList().size();
            long count = item.getCodeList().stream().distinct().count();
            AssertUtils.isNotTrue(size != count, "监管码不能重复");
            BizOutboundTaskDetailDismantle bizOutboundTaskDetailDismantle = bizOutboundTaskDetailDismantleService.findById(item.getOutboundDetailDismantleId());
            BigDecimal subtract = bizOutboundTaskDetailDismantle.getPlanQty().subtract(bizOutboundTaskDetailDismantle.getOfferQty()).subtract(bizOutboundTaskDetailDismantle.getLackQty()).subtract(bizOutboundTaskDetailDismantle.getOfferShowQty());
            if (subtract.compareTo(new BigDecimal(size)) > 0) {
                throw new PrologException("请采集对应数量的药监码");
            }
            List<SupervisionCodeDto> supervisionCodeList = bizOutboundTaskDetailService.findSupervisionCode(item.getCodeList());
            if (CollectionUtils.isEmpty(supervisionCodeList)) {
                codeNotLot.addAll(item.getCodeList());
                continue;
            }
            if (supervisionCodeList.size() < size) {
                List<String> collect = supervisionCodeList.stream().map(SupervisionCodeDto::getCode).collect(Collectors.toList());
                List<String> drugSupervisionCode = item.getCodeList();
                List<String> collect1 = drugSupervisionCode.stream().filter(inner -> !collect.contains(inner)).collect(Collectors.toList());
                codeNotLot.addAll(collect1);
            }
            BizOutboundTaskDetail outboundTaskDetail = bizOutboundTaskDetailService.findById(item.getOutboundDetailId());
            List<String> collect = supervisionCodeList.stream().filter(inner -> !StrUtil.equals(inner.getItemId(), outboundTaskDetail.getItemId()) ||
                    !StrUtil.equals(inner.getLotId(), outboundTaskDetail.getLotId())).map(SupervisionCodeDto::getCode).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                codeLotDis.addAll(collect);
            }
        }
        String msg = "";
        if (CollectionUtils.isNotEmpty(codeNotLot)) {
            msg += "药监码" + StrUtil.join(",", codeNotLot) + "无品批信息 ";
        }
        if (CollectionUtils.isNotEmpty(codeLotDis)) {
            msg += "药监码" + StrUtil.join(",", codeLotDis) + "与实际品批信息不一致 ";
        }
        if (StrUtil.isBlank(msg)) {
            return null;
        }
        return msg;
    }

    @Override
    @Transactional
    public void itemSupervise(PackOrderItemSuperviseDto req) throws Exception {
        if (CollectionUtil.isEmpty(req.getList())) {
            throw new PrologException("请采集药监码");
        }
        List<PackOrderItemSuperviseDetailDto> list = req.getList();
        for (PackOrderItemSuperviseDetailDto item : list) {
            if (CollectionUtil.isEmpty(item.getCodeList())) {
                throw new PrologException("请采集药监码");
            }
        }
        for (PackOrderItemSuperviseDetailDto item : list) {
            BizOutboundTaskDetailDismantle bizOutboundTaskDetailDismantle = bizOutboundTaskDetailDismantleService.findById(item.getOutboundDetailDismantleId());
            if (bizOutboundTaskDetailDismantle.getStatus() >= BaseStatusEnum.STATUS_OFFER.getCode()) {
                throw new PrologException(String.format("物料%s已复核，请勿重复复核", bizOutboundTaskDetailDismantle.getItemId()));
            }
            //校验此次监管码与已采集的监管码是否有重复
            List<String> codeList = Convert.toList(String.class, bizOutboundTaskDetailDismantle.getDrugSupervisionCode());
            codeList.addAll(item.getCodeList());
            int size = codeList.size();
            long count = codeList.stream().distinct().count();
            AssertUtils.isNotTrue(size != count, String.format("物料%s监管码有重复", bizOutboundTaskDetailDismantle.getItemId()));
            bizOutboundTaskDetailDismantle.setDrugSupervisionCode(StrUtil.join(",", codeList));
            bizOutboundTaskDetailDismantle.setOfferQty(bizOutboundTaskDetailDismantle.getOfferQty().add(new BigDecimal(item.getCodeList().size())));
            //判断此订单详情是否复核完成
            if ((bizOutboundTaskDetailDismantle.getPlanQty()
                    .subtract(bizOutboundTaskDetailDismantle.getLackQty())
                    .subtract(bizOutboundTaskDetailDismantle.getOfferShowQty())
                    .subtract(bizOutboundTaskDetailDismantle.getOfferQty())).compareTo(BigDecimal.ZERO) == 0) {
                //复核完成
                //修改订单详情状态为已复核
                BizOutboundTaskDetail outboundTaskDetail = bizOutboundTaskDetailService.findById(item.getOutboundDetailId());
                outboundTaskDetail.setStatus(BaseStatusEnum.STATUS_OFFER.getCode());
                outboundTaskDetail.setUpdateTime(LocalDateTime.now());
                bizOutboundTaskDetailService.update(outboundTaskDetail);
                // 组装回告消息
                WmsOfferBackDetailDto wmsOfferBackDetailDto = WmsOfferBackDetailDto.builder()
                        .taskLineId(outboundTaskDetail.getSeqNo())
                        .itemId(outboundTaskDetail.getItemId())
                        .lotId(outboundTaskDetail.getLotId())
                        .ownerId(outboundTaskDetail.getOwnerId())
                        .packId(outboundTaskDetail.getPackId())
                        .qty(bizOutboundTaskDetailDismantle.getOfferQty())
                        .drugSupervisionCode(Convert.toList(String.class, bizOutboundTaskDetailDismantle.getDrugSupervisionCode()))
                        .build();
                bizOutboundTaskDetailDismantle.setExtend2(JSONUtil.toJsonStr(wmsOfferBackDetailDto));
                //修改状态为已复核
                bizOutboundTaskDetailDismantle.setStatus(BaseStatusEnum.STATUS_OFFER.getCode());
                bizOutboundTaskDetailDismantleService.update(bizOutboundTaskDetailDismantle);
                //判断订单是否复核完成
                List<BizOutboundTaskDetailDismantle> outboundTaskDetailDismantleList = bizOutboundTaskDetailDismantleService.findByMap(MapUtils.put(BizOutboundTaskDetailDismantle::getOutboundId, req.getOutboundId()).put(BizOutboundTaskDetailDismantle::getType, 2).getMap());
                List<BizOutboundTaskDetailDismantle> collect = outboundTaskDetailDismantleList.stream().filter(inner -> inner.getStatus() < BaseStatusEnum.STATUS_OFFER.getCode()).collect(Collectors.toList());
                boolean offerFinish = CollectionUtil.isEmpty(collect);
                if (CollectionUtil.isNotEmpty(collect)) {
                    List<String> itemIds = collect.stream().map(BizOutboundTaskDetailDismantle::getItemId).collect(Collectors.toList());
                    List<ItemSyncVO> itemList = itemService.queryItemMst(itemIds);
                    long count1 = itemList.stream().filter(inner -> inner.getItemHealthSuperviseflag() == 1).count();
                    offerFinish = count1 == 0;
                }
                if (offerFinish) {
                    BizOutboundTask bizOutboundTask = bizOutboundTaskService.findById(req.getOutboundId());
                    doOfferBack(bizOutboundTask);
                }
            } else {
                bizOutboundTaskDetailDismantleService.update(bizOutboundTaskDetailDismantle);
            }
        }
    }

    @Override
    public void handOfferScan(PackOrderDetailReqDto req) throws Exception {
        ItemBarCodeVO itemBarCodeVO = itemService.queryItemByBarCode(req.getCode());
        BizOutboundTaskDetail bizOutboundTaskDetail = bizOutboundTaskDetailService.findByMap(MapUtils.put(BizOutboundTaskDetail::getOutboundId, req.getId()).put(BizOutboundTaskDetail::getItemId, itemBarCodeVO.getItemId()).getMap()).stream().findFirst().orElseThrow(() -> new PrologException(String.format("订单id %s,商品id %s 未查询到对应的订单详情", req.getId(), itemBarCodeVO.getItemId())));
        BizOutboundTaskDetailDismantle outboundTaskDetailDismantle = bizOutboundTaskDetailDismantleService.findByMap(MapUtils.put(BizOutboundTaskDetailDismantle::getOutboundId, req.getId())
                        .put(BizOutboundTaskDetailDismantle::getOutboundDetailId, bizOutboundTaskDetail.getId())
                        .put(BizOutboundTaskDetailDismantle::getType, 2).getMap())
                .stream().findFirst().orElseThrow(() -> new PrologException(String.format("订单id %s,商品id %s 未查询到对应的订单拆零详情", req.getId(), itemBarCodeVO.getItemId())));
        List<BizOutboundTaskDetailDismantleGrid> outboundTaskDetailDismantleGridList = outboundTaskDetailDismantleGridMapper.findByMap(MapUtils.put(BizOutboundTaskDetailDismantleGrid::getOutboundDetailDismantleId, outboundTaskDetailDismantle.getId())
                .put(BizOutboundTaskDetailDismantleGrid::getGridNo, req.getGridNo()).getMap(), BizOutboundTaskDetailDismantleGrid.class);
        BigDecimal totalOfferQty = outboundTaskDetailDismantleGridList.stream().map(BizOutboundTaskDetailDismantleGrid::getHandOfferQty).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalQty = outboundTaskDetailDismantleGridList.stream().map(BizOutboundTaskDetailDismantleGrid::getQty).reduce(BigDecimal.ZERO, BigDecimal::add);
        if (totalQty.compareTo(totalOfferQty) <= 0) {
            throw new PrologException("已全部复核完成，请勿重复复核");
        }
        BizOutboundTaskDetailDismantleGrid outboundTaskDetailDismantleGrid = outboundTaskDetailDismantleGridList.get(0);
        outboundTaskDetailDismantleGrid.setHandOfferQty(outboundTaskDetailDismantleGrid.getHandOfferQty().add(BigDecimal.ONE));
        outboundTaskDetailDismantleGridMapper.update(outboundTaskDetailDismantleGrid);
    }

    @Override
    @Transactional
    public void packOrderFinish(Integer id, String gridNo) {
        BizOutboundTask outboundTask = bizOutboundTaskService.findById(id);
        GridInfo gridInfo = gridInfoService.findOneByMap(MapUtils.put(GridInfo::getGridNo, gridNo).getMap());
        if (Objects.isNull(gridInfo) || Objects.isNull(gridInfo.getOrderId()) || !Objects.equals(gridInfo.getOrderId(), id)) {
            throw new PrologException(String.format("格口号%s未绑定订单%s", gridNo, outboundTask.getBillNo()));
        }
        gridInfo.setScanFinish(1);
        gridInfo.setUpdateTime(new Date());
        gridInfoService.update(gridInfo);
//        orderFinish(id);
    }

    @Override
    @Transactional
    public void packOrderLack(Integer id) {
        //打印异常标签
        PrintTask printTask = new PrintTask();
        printTask.setType(6);
        printTask.setPrintCount(0);
        printTask.setGridNo(null);
        printTask.setCreateTime(new Date());
        printTask.setStatus(0);
        printTask.setWmsOutTaskId(id);
        printTaskService.save(printTask);
        orderFinish(id);
    }

    private void orderFinish(Integer id) {
        //修改出库单相关所有表状态为完成
        BizOutboundTask outboundTask = bizOutboundTaskService.findById(id);
        List<BizOutboundTaskDetailDismantle> outboundTaskDetailDismantleList = bizOutboundTaskDetailDismantleService.findByMap(MapUtils.put(BizOutboundTaskDetailDismantle::getOutboundId, id).getMap());
        List<BizOutboundTaskDetailDismantle> collect = outboundTaskDetailDismantleList.stream().filter(item -> item.getType() == 1).collect(Collectors.toList());
        //修改此订单拆零已全部完成
        List<BizOutboundTaskDetailDismantle> collect2 = outboundTaskDetailDismantleList.stream().filter(item -> item.getType() == 2).collect(Collectors.toList());
        Criteria criteria = new Criteria(BizOutboundTaskDetailDismantle.class);
        criteria.restrictionBuilder().in(BizOutboundTaskDetailDismantle::getId, collect2.stream().map(BizOutboundTaskDetailDismantle::getId).collect(Collectors.toList())).build();
        bizOutboundTaskDetailDismantleService.updateMapByCriteria(MapUtils.put(BizOutboundTaskDetailDismantle::getStatus, 20).put(BizOutboundTaskDetailDismantle::getUpdateTime, LocalDateTime.now()).getMap(), criteria);
        //判断零发整是否完成
        long count = collect.stream().filter(item -> item.getStatus() < 12).count();
        if (count == 0) {
            bizOutboundTaskService.outboundToHis(outboundTask);
        }
        List<BizOutboundTaskDetailItem> outboundTaskDetailItems = outboundTaskDetailItemService.findByMap(MapUtils.put(BizOutboundTaskDetailItem::getOutboundId, id).getMap());
        for (BizOutboundTaskDetailItem outboundTaskDetailItem : outboundTaskDetailItems) {
            BizOutboundTaskDetailItemHis outboundTaskDetailItemHis = new BizOutboundTaskDetailItemHis();
            BeanUtils.copyProperties(outboundTaskDetailItem, outboundTaskDetailItemHis);
            outboundTaskDetailItemHisService.save(outboundTaskDetailItemHis);
            outboundTaskDetailItemService.deleteById(outboundTaskDetailItem.getId());
        }
        List<GridInfo> gridInfoList = gridInfoService.findByMap(MapUtils.put(GridInfo::getOrderId, id).getMap());
        String gridNos = "";
        for (GridInfo gridInfo : gridInfoList) {
            gridNos += gridInfo.getGridNo() + ",";
            gridInfo.setOrderId(null);
            gridInfo.setApplyVolume(BigDecimal.ZERO);
            gridInfo.setSupplyFlag(0);
            gridInfo.setFallGrid(0);
            gridInfo.setBillFlag(0);
            gridInfo.setLastFlag(0);
            gridInfo.setScanFinish(0);
            gridInfoService.update(gridInfo);
            redisTemplate.delete(RedisKey.GRID_BIND_KEY + gridInfo.getGridNo());
        }
        orderLogMapper.save(OrderLog.builder()
                .orderId(outboundTask.getId().toString())
                .orderNo(outboundTask.getBillNo())
                .type("格口释放")
                .remark("释放的格口：" + gridNos)
                .createTime(new Date())
                .build());
    }

    @Override
    @Transactional
    public void packOrderGridFinish(Integer id, String gridNo) {
        BizOutboundTask outboundTask = bizOutboundTaskService.findById(id);
        GridInfo gridInfo = gridInfoService.findOneByMap(MapUtils.put(GridInfo::getGridNo, gridNo).getMap());
        if (Objects.isNull(gridInfo) || Objects.isNull(gridInfo.getOrderId()) || !Objects.equals(gridInfo.getOrderId(), id)) {
            throw new PrologException(String.format("格口号%s未绑定订单%s", gridNo, outboundTask.getBillNo()));
        }
        outboundTask.setLackState(0);
        outboundTask.setUpdateTime(LocalDateTime.now());
        bizOutboundTaskService.update(outboundTask);
        Criteria criteria = new Criteria(BizOutboundTaskDetail.class);
        criteria.restrictionBuilder().eq(BizOutboundTaskDetail::getOutboundId, id).build();
        bizOutboundTaskDetailService.updateMapByCriteria(MapUtils.put(BizOutboundTaskDetail::getLackState, -1).put(BizOutboundTaskDetail::getUpdateTime, LocalDateTime.now()).getMap(),
                criteria);

        WmsApplePrintDto wmsApplePrintDto = new WmsApplePrintDto();
        wmsApplePrintDto.setWarehouseId(outboundTask.getWmsWarehouseId());
        wmsApplePrintDto.setTaskId(outboundTask.getUpperSystemTaskId());
        wmsApplePrintDto.setBillNo(outboundTask.getBillNo());
        wmsApplePrintDto.setEnterpriseId(outboundTask.getEnterpriseId());
        wmsApplePrintDto.setGridNo(gridInfo.getGridNo());
        wmsApplePrintDto.setLabelCount(1);
        wmsApplePrintDto.setPackFlag(Objects.isNull(outboundTask.getBillCount()) || outboundTask.getBillCount() <= 1 ? 0 : 1);
        PrintTask printTask = new PrintTask();
        printTask.setType(10);
        printTask.setPrintCount(0);
        printTask.setGridNo(null);
        printTask.setPrintData(JSONUtil.toJsonStr(wmsApplePrintDto));
        printTask.setCreateTime(new Date());
        printTask.setStatus(0);
        printTask.setWmsOutTaskId(id);
        printTaskService.save(printTask);

        List<AllotmentTaskRecord> allotmentTaskRecordList = allotmentTaskRecordService.findByMap(MapUtils.put(AllotmentTaskRecord::getOutboundId, id).getMap());
        if (CollectionUtils.isNotEmpty(allotmentTaskRecordList)) {
            List<AllotmentTaskRecordHis> hisList = new ArrayList<>();
            AllotmentTaskRecordHis allotmentTaskRecordHis = null;
            for (AllotmentTaskRecord record : allotmentTaskRecordList) {
                allotmentTaskRecordHis = new AllotmentTaskRecordHis();
                com.prolog.framework.beans.BeanUtils.copyProperties(record, allotmentTaskRecordHis);
                hisList.add(allotmentTaskRecordHis);
            }
            allotmentTaskRecordHisService.saveBatch(hisList);
            allotmentTaskRecordService.deleteByMap(MapUtils.put(AllotmentTaskRecord::getOutboundId, id).getMap());
        }
        orderFinish(id);
    }

    @Override
    public void targetMergeContainerScan(String sourceContainerNo, String targetContainerNo) {
        Criteria criteria = new Criteria(MergeContainerTask.class);
        criteria.restrictionBuilder().in(MergeContainerTask::getContainerNo, Arrays.asList(sourceContainerNo, targetContainerNo)).build();
        List<MergeContainerTask> mergeContainerTaskList = mergeContainerTaskService.findByCriteria(criteria);
        AssertUtils.isNotNull(mergeContainerTaskList, "容器不存在合托任务");
        AssertUtils.isNotTrue(mergeContainerTaskList.size() != 2, "容器不存在合托任务");
        AssertUtils.isNotTrue(!StrUtil.equals(mergeContainerTaskList.get(0).getBillNo(), mergeContainerTaskList.get(1).getBillNo()), "合托容器任务不一致");
        AssertUtils.isNotTrue(Arrays.asList(0, 3).contains(mergeContainerTaskList.get(0).getStatus()), "此容器合托任务未开始或已完成");
        AssertUtils.isNotTrue(Arrays.asList(0, 3).contains(mergeContainerTaskList.get(1).getStatus()), "此容器合托任务未开始或已完成");
        Criteria containerInfoCri = new Criteria(ContainerInfo.class);
        containerInfoCri.restrictionBuilder().in(ContainerInfo::getContainerNo, Arrays.asList(sourceContainerNo, targetContainerNo)).build();
        List<ContainerInfo> containerInfoList = containerInfoService.findByCriteria(containerInfoCri);
        AssertUtils.isNotTrue(CollectionUtils.isEmpty(containerInfoList) || containerInfoList.size() != 2, "容器库存不存在");
    }

    @Override
    public MergeContainerListRespDto sourceMergeContainerScan(String containerNo) throws Exception {
        MergeContainerTask mergeContainerTask = mergeContainerTaskService.findByMap(MapUtils.put(MergeContainerTask::getContainerNo, containerNo).getMap()).stream().findFirst().orElseThrow(() -> new PrologException("没有此容器的合托任务"));
        AssertUtils.isNotTrue(Arrays.asList(0, 3).contains(mergeContainerTask.getStatus()), "此容器合托任务未开始或已完成");
        ContainerInfoDetail containerInfoDetail = containerInfoDetailService.findByMap(MapUtils.put(ContainerInfoDetail::getContainerNo, containerNo).getMap()).stream().findFirst().orElseThrow(() -> new PrologException("容器库存不存在"));
        ItemSyncVO itemInfo = itemService.queryItemMst(Arrays.asList(containerInfoDetail.getItemId())).stream().findFirst().orElseThrow(() -> new PrologException("未查询到商品信息"));
        BatchNumberSync batchNumberSync = inventoryService.getBatchNumberSync(Arrays.asList(containerInfoDetail.getLotId())).stream().findFirst().orElseThrow(() -> new PrologException("未查询到批次信息"));
        return MergeContainerListRespDto.builder()
                .barCode(itemInfo.getPieceBarcode())
                .containerNo(containerNo)
                .itemName(itemInfo.getItemName())
                .billNo(mergeContainerTask.getBillNo())
                .lotNo(batchNumberSync.getManufacturerLotNum())
                .qty(containerInfoDetail.getQty())
                .build();
    }

    @Override
    public MergeContainerDetailDto mergeContainerDetail(String containerNo) throws Exception {
        MergeContainerTask mergeContainerTask = mergeContainerTaskService.findByMap(MapUtils.put(MergeContainerTask::getContainerNo, containerNo).getMap()).stream().findFirst().orElseThrow(() -> new PrologException("没有此容器的合托任务"));
        ContainerInfoDetail containerInfoDetail = containerInfoDetailService.findByMap(MapUtils.put(ContainerInfoDetail::getContainerNo, containerNo).getMap()).stream().findFirst().orElseThrow(() -> new PrologException("容器库存不存在"));
        ItemSyncVO itemInfo = itemService.queryItemMst(Arrays.asList(containerInfoDetail.getItemId())).stream().findFirst().orElseThrow(() -> new PrologException("未查询到商品信息"));
        BatchNumberSync batchNumberSync = inventoryService.getBatchNumberSync(Arrays.asList(containerInfoDetail.getLotId())).stream().findFirst().orElseThrow(() -> new PrologException("未查询到批次信息"));
//        BigDecimal[] bigDecimals = containerInfoDetail.getQty().divideAndRemainder(itemInfo.getUomList().get(0).getConversionRate());
        return MergeContainerDetailDto.builder()
                .containerNo(containerNo)
                .spec(itemInfo.getSpecification())
                .taskType("合托出库")
                .itemName(itemInfo.getItemName())
                .barCode(itemInfo.getPieceBarcode())
                .billNo(mergeContainerTask.getBillNo())
                .id(mergeContainerTask.getId())
                .itemQty(BigDecimal.ZERO)
                .packQty(itemInfo.getUomList().get(0).getConversionRate())
                .lotNo(batchNumberSync.getManufacturerLotNum())
                .scatteredQty(BigDecimal.ZERO)
                .qty(BigDecimal.ZERO)
                .storeQty(containerInfoDetail.getQty())
                .build();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @TxTransaction(rollbackFor = Exception.class)
    public void mergeContainerBack(String containerNo) throws Exception {
        MergeContainerTask mergeContainerTask = mergeContainerTaskService.findByMap(MapUtils.put(MergeContainerTask::getContainerNo, containerNo).getMap()).stream().findFirst().orElseThrow(() -> new PrologException("没有此容器的合托任务"));
        ContainerInfoDetail containerInfoDetail = containerInfoDetailService.findByMap(MapUtils.put(ContainerInfoDetail::getContainerNo, containerNo).getMap()).stream().findFirst().orElseThrow(() -> new PrologException("容器库存不存在"));
        ContainerInfo containerInfo = containerInfoService.findByMap(MapUtils.put(ContainerInfo::getContainerNo, containerNo).getMap()).stream().findFirst().orElseThrow(() -> new PrologException("容器库存不存在"));
        AssertUtils.isNotTrue(Arrays.asList(0, 3).contains(mergeContainerTask.getStatus()), "当前任务状态不支持回库");

        //修改库存状态为回库中
        containerInfo.setTaskType(ContainerTaskTypeConstants.RETURN);
        containerInfo.setUpdateTime(LocalDateTime.now());
        containerInfoService.update(containerInfo);

        //修改合托任务为已回库转历史
        mergeContainerTask.setStatus(3);
        mergeContainerTask.setUpdateTime(LocalDateTime.now());
        mergeContainerTaskService.update(mergeContainerTask);
        MergeContainerTaskHis mergeContainerTaskHis = new MergeContainerTaskHis();
        BeanUtils.copyProperties(mergeContainerTask, mergeContainerTaskHis);
        mergeContainerTaskHisMapper.save(mergeContainerTaskHis);
        mergeContainerTaskService.deleteById(mergeContainerTask.getId());

        //删除容器任务
        containerTaskService.deleteByMap(MapUtils.put(ContainerTask::getContainerNo, containerNo).put(ContainerTask::getTaskType, 77).getMap());

        //判断容器回库还是去碟盘机
        if (containerInfoDetail.getQty().compareTo(BigDecimal.ZERO) == 0) {
            //去碟盘机
            emptyContainerTaskService.save(containerNo, LayerEnum.TWO, WmsCarryTaskInCode.AGVL);
            wmsContainerStatusUpdateService.execute(WmsContainerStatusUpdateDto.builder()
                    .containerCode(containerNo)
                    .enterpriseId(enterpriseId)
                    .warehouseId(warehouseId)
                    .build());
        } else {
            //回库
            LocationCfg locationCfg = locationCfgService.findOneByMap(MapUtils.put(LocationCfg::getType, LocationCfgConstants.AGVL_TP).put(LocationCfg::getWmsAreaNo, WmsCarryTaskInCode.AGVL.getCode()).getMap());
            routeFeignService.createCarryTask(containerNo, null, null, null, locationCfg.getAreaNo(), null,
                    String.valueOf(BaseTaskTypeConstants.IN_TYPE), 1, "合托回库", null);
        }

    }

    @Override
    @Transactional
    public void mergeContainerConfirm(MergeContainerConfirmDto req) {
        MergeContainerTask sourceMergeContainerTask = mergeContainerTaskService.findByMap(MapUtils.put(MergeContainerTask::getContainerNo, req.getSourceContainerNo()).getMap()).stream().findFirst().orElseThrow(() -> new PrologException("容器合托任务不在"));
        MergeContainerTask targetMergeContainerTask = mergeContainerTaskService.findByMap(MapUtils.put(MergeContainerTask::getContainerNo, req.getTargetContainerNo()).getMap()).stream().findFirst().orElseThrow(() -> new PrologException("容器合托任务不在"));
        AssertUtils.isTrue(StrUtil.equals(sourceMergeContainerTask.getBillNo(), targetMergeContainerTask.getBillNo()), "当前合托容器不是同一合托任务");
        AssertUtils.isNotTrue(sourceMergeContainerTask.getStatus() != 1 || targetMergeContainerTask.getStatus() != 1, "容器任务还未开始或已完成");
        Criteria criteria = new Criteria(ContainerInfoDetail.class);
        criteria.restrictionBuilder().in(ContainerInfoDetail::getContainerNo, Arrays.asList(sourceMergeContainerTask.getContainerNo(), targetMergeContainerTask.getContainerNo())).build();
        List<ContainerInfoDetail> containerInfoDetailList = containerInfoDetailService.findByCriteria(criteria);
//        BigDecimal total = containerInfoDetailList.stream().map(ContainerInfoDetail::getQty).reduce(BigDecimal.ZERO, BigDecimal::add);
//        AssertUtils.isNotTrue(req.getQty().compareTo(BigDecimal.ZERO) <= 0 || req.getQty().compareTo(total) > 0, "数量不能小于0和大于容器库存总数");

        ContainerInfoDetail targetContainerInfo = containerInfoDetailList.stream().filter(item -> StrUtil.equals(item.getContainerNo(), targetMergeContainerTask.getContainerNo())).findFirst().get();
        ContainerInfoDetail sourceContainerInfo = containerInfoDetailList.stream().filter(item -> StrUtil.equals(item.getContainerNo(), sourceMergeContainerTask.getContainerNo())).findFirst().get();

        AssertUtils.isNotTrue(req.getQty().compareTo(sourceContainerInfo.getQty()) > 0, "合并数量不能大于原库存数量");

        //记录库存流水
        List<ContainerStoreChange> changeList = new ArrayList<>();
        ContainerStoreChange containerChange = new ContainerStoreChange();
        containerChange.setTaskType(BaseTypeEnum.MERGE_TYPE.getCode());
        containerChange.setContainerNo(targetContainerInfo.getContainerNo());
        containerChange.setContainerSubNo(targetContainerInfo.getContainerNo());
        containerChange.setSoureQty(targetContainerInfo.getQty());
        containerChange.setChangeQty(req.getQty());
        containerChange.setTargetQty(req.getQty().add(targetContainerInfo.getQty()));
        containerChange.setUpperSystemId(null);
        containerChange.setItemId(targetContainerInfo.getItemId());
        containerChange.setLotId(targetContainerInfo.getLotId());
        containerChange.setPackId(targetContainerInfo.getPackId());
        containerChange.setRemark("合托增加");
        containerChange.setOwnerId(targetContainerInfo.getOwnerId());
        containerChange.setCreateTime(LocalDateTime.now());
        changeList.add(containerChange);
        ContainerStoreChange containerChange1 = new ContainerStoreChange();
        containerChange1.setTaskType(BaseTypeEnum.MERGE_TYPE.getCode());
        containerChange1.setContainerNo(sourceContainerInfo.getContainerNo());
        containerChange1.setContainerSubNo(sourceContainerInfo.getContainerNo());
        containerChange1.setSoureQty(sourceContainerInfo.getQty());
        containerChange1.setTargetQty(req.getQty().negate());
        containerChange1.setChangeQty((sourceContainerInfo.getQty().subtract(req.getQty())).negate());
        containerChange1.setUpperSystemId(null);
        containerChange1.setItemId(sourceContainerInfo.getItemId());
        containerChange1.setLotId(sourceContainerInfo.getLotId());
        containerChange1.setPackId(sourceContainerInfo.getPackId());
        containerChange1.setRemark("合托减少");
        containerChange1.setOwnerId(sourceContainerInfo.getOwnerId());
        containerChange1.setCreateTime(LocalDateTime.now());
        changeList.add(containerChange1);
        containerStoreChangeMapper.saveBatch(changeList);
        //修改托盘库存
        targetContainerInfo.setQty(targetContainerInfo.getQty().add(req.getQty()));
        targetContainerInfo.setUpdateTime(LocalDateTime.now());
        sourceContainerInfo.setQty(sourceContainerInfo.getQty().subtract(req.getQty()));
        sourceContainerInfo.setUpdateTime(LocalDateTime.now());
        containerInfoDetailService.update(targetContainerInfo);
        containerInfoDetailService.update(sourceContainerInfo);
        //修改任务状态
        sourceMergeContainerTask.setStatus(2);
        sourceMergeContainerTask.setUpdateTime(LocalDateTime.now());
        targetMergeContainerTask.setStatus(2);
        targetMergeContainerTask.setUpdateTime(LocalDateTime.now());
        mergeContainerTaskService.update(targetMergeContainerTask);
        mergeContainerTaskService.update(sourceMergeContainerTask);

    }
}
