package com.junmp.v2.print.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.junmp.jyzb.api.bean.dto.printDto.*;
import com.junmp.jyzb.api.bean.query.LogDetailReq;
import com.junmp.jyzb.api.bean.query.LogSummaryReq;
import com.junmp.jyzb.api.bean.query.inAndOutRecordReq.*;
import com.junmp.jyzb.api.bean.req.PrintReq.*;
import com.junmp.jyzb.api.exception.JYZBAppException;
import com.junmp.jyzb.api.exception.enums.CabinetV2ExceptionEnum;
import com.junmp.jyzb.api.exception.enums.JyzbV2ExceptionEnum;
import com.junmp.jyzb.cache.GenerateEpc2Cache;
import com.junmp.jyzb.cache.OutInRecordRedisCache;
import com.junmp.jyzb.entity.*;
import com.junmp.jyzb.mapper.*;
import com.junmp.jyzb.service.*;
import com.junmp.jyzb.utils.DateTimeUtil;
import com.junmp.v2.channel.service.ChannelService;
import com.junmp.v2.common.util.BeanPlusUtil;
import com.junmp.v2.print.RFID.GenerateEpcNum;
import com.junmp.v2.print.service.PrintService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <pre>
 *
 * 描述：
 * 版本：1.0.0
 * 日期：2024/9/4 下午1:30
 * 作者：xuzc@junmp.com.cn
 * <br>修改记录
 * <br>修改日期 修改人 修改内容
 *
 * </pre>
 */
@Service
public class PrintServiceImpl implements PrintService
{
    @Resource
    private SupplierService supplierService;

    @Resource
    private EquipmentSizeService equipmentSizeService;

    @Resource
    private EquipmentTypeService equipmentTypeService;

    @Resource
    private SupplierTypeService supplierTypeService;

    @Resource
    private OrderMainMapper orderMainMapper;

    @Resource
    private InventoryService inventoryService;

    @Resource
    private WarehouseInventoryService warehouseInventoryService;

    @Resource
    private InventorySummaryService inventorySummaryService;

    @Resource
    private InventoryMapper inventoryMapper;

    @Resource
    private LogDetailService logDetailService;

    @Resource
    private InventoryBoxMarkMapper inventoryBoxMarkMapper;

    @Resource
    private InventoryBoxMarkService inventoryBoxMarkService;

    @Resource
    private InventorySummaryMapper inventorySummaryMapper;

    @Resource
    GenerateEpc2Cache generateEpc2Cache;

    @Resource
    private PrintEpcsService printEpcsService;

    @Resource
    private OrderDetailService orderDetailService;

    @Resource
    private ShelfService shelfService;

    @Resource
    private WarehouseService warehouseService;

    @Resource
    private PrintEpcsMapper printEpcsMapper;

    @Resource
    private ChannelService channelService;

    @Resource
    private LogSummaryService logSummaryService;

    @Resource
    private PolicemanService policemanService;

    @Resource
    private OutInRecordRedisCache outInRecordRedisCache;

    @Resource
    private OrderMainService orderMainService;

    @Override
    public PrintGenericDto<PrintSupplierDto> GetAllSupplier()
    {
        List<Supplier> suppliers = supplierService.list();

        if (suppliers == null || suppliers.size() <= 0){
            return new PrintGenericDto<>(0, new ArrayList<>());
        }

        List<PrintSupplierDto> dtos = new ArrayList<>();

        for (Supplier supplier : suppliers){
            dtos.add(new PrintSupplierDto(supplier.getId(), supplier.getCode(), supplier.getName()));
        }

        return new PrintGenericDto<>(dtos.size(), dtos);
    }

    @Override
    public List<PrintEquipmentInfoDto> GetAllEquipments()
    {
        LambdaQueryWrapper<EquipmentType> typeQuery = new LambdaQueryWrapper();
        typeQuery.eq(EquipmentType::getType, 1);

        List<EquipmentType> types = equipmentTypeService.list(typeQuery);
        List<EquipmentSize> sizes = equipmentSizeService.list();
        List<Supplier> suppliers = supplierService.list();

        Map<String, List<String>> map = supplierTypeService.list().stream()
                .collect(Collectors.groupingBy(SupplierType :: getTypeId, Collectors.mapping(SupplierType :: getSupplierId, Collectors.toList())));

        List<PrintEquipmentInfoDto> rs = new ArrayList<>();

        for (EquipmentType type : types) {
            List<String> parentIds =  Arrays.asList(type.getParentIds().split(","));
            List<String> mapSupplierIds = new ArrayList<>();

            for(String parentId : parentIds){
                if(map.containsKey(parentId)){
                    mapSupplierIds.addAll(map.get(parentId));
                }
            }

            List<PrintEquipmentSupplierDto> aaa= suppliers.stream()
                    .filter(s -> mapSupplierIds.contains(s.getId()))
                    .map(s -> new PrintEquipmentSupplierDto(s.getId(), s.getName()))
                    .collect(Collectors.toList());

            rs.add(
                    new PrintEquipmentInfoDto(
                            type.getId(),
                            type.getName(),
                            suppliers.stream()
                                    .filter(s -> mapSupplierIds.contains(s.getId()))
                                    .map(s ->
                                            new PrintEquipmentSupplierDto(
                                                    s.getId(),
                                                    s.getName()))
                                    .collect(Collectors.toList()),
                            sizes.stream()
                                    .filter(s -> s.getTypeId().equals(type.getId()))
                                    .map(s ->
                                            new PrintEquipmentSizeDto(
                                                    s.getId(),
                                                    s.getName(),
                                                    s.getCode()))
                                    .collect(Collectors.toList())
                    )
            );
        }

        return rs;
    }

    @Override
    public PrintEquipmentInfoDto GetEquInfoById(GetEquInfoByIdReq req)
    {
        EquipmentType type = equipmentTypeService.getOne(new LambdaQueryWrapper<EquipmentType>().eq(EquipmentType::getId, req.getId()));

        if(type != null){
            List<EquipmentSize> sizes = equipmentSizeService.list(new LambdaQueryWrapper<EquipmentSize>().eq(EquipmentSize::getTypeId, req.getId()));

            List<String> supplierIds = supplierTypeService
                    .list(new LambdaQueryWrapper<SupplierType>().in(SupplierType::getTypeId, Arrays.asList(type.getParentIds().split(","))))
                    .stream().map(SupplierType::getSupplierId).collect(Collectors.toList());

            List<Supplier> suppliers = supplierService.list(new LambdaQueryWrapper<Supplier>().in(Supplier::getId, supplierIds));

            return new PrintEquipmentInfoDto(
                    type.getId(),
                    type.getName(),
                    suppliers.stream()
                            .map(s -> new PrintEquipmentSupplierDto(s.getId(), s.getName()))
                            .collect(Collectors.toList()),
                    sizes.stream()
                            .map(s -> new PrintEquipmentSizeDto(s.getId(), s.getName(), s.getCode(), s.getPrice()))
                            .collect(Collectors.toList()));
        }else {
            return new PrintEquipmentInfoDto();
        }
    }



//    @Override
//    public GetPrintOrderDto GetPrintOrder(GetPrintOrderReq req) {
//        if (ObjectUtil.isNull(req.getSize()) || req.getSize()==0){
//            req.setSize(50);
//        }
//        int size=orderMainMapper.getPrintOrderCount();
//        List<GetPrintOrderDto.PrintOrderDto> printOrderDtoList= orderMainMapper.getPrintOrderList();
//
//        GetPrintOrderDto getPrintOrderDto = new GetPrintOrderDto();
//        getPrintOrderDto.setRecord(printOrderDtoList);
//        getPrintOrderDto.setTotal(size);
//        return getPrintOrderDto;
//    }


    /**
     * 删除epc
     * @param req
     * @return
     */
    @Override
    @Transactional
    public Boolean DeleteInventory(EpcInvReq req) {


        if (ObjectUtil.isEmpty(req.getEpc())){
            throw new JYZBAppException(JyzbV2ExceptionEnum.EPC_ERROR);
        }
        List<String> epcList=new ArrayList<>();
        epcList.add(req.getEpc());

        List<Inventory> invEpcList = inventoryMapper.getInvEpcList(null, epcList, null, null);
        if (CollectionUtil.isEmpty(invEpcList)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.INVEOTORY_INFO_ERROR,"无效epc");
        }
        Inventory inventory = invEpcList.get(0);
        List<LogDetail> list = logDetailService.list(new LambdaQueryWrapper<LogDetail>().eq(LogDetail::getEpc, inventory.getEpc()));
        if (CollectionUtil.isNotEmpty(list)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.INVEOTORY_INFO_ERROR,"存在出入库记录，删除失败");
        }
        InventorySummary invSum = inventorySummaryService.getOne(new LambdaQueryWrapper<InventorySummary>()
                .eq(InventorySummary::getOrgId, inventory.getOrgId())
                .eq(InventorySummary::getLocationId, inventory.getLocationId())
                .eq(InventorySummary::getTypeId, inventory.getTypeId())
                .eq(InventorySummary::getSizeId, inventory.getSizeId())
                .eq(InventorySummary::getUnitPrice, inventory.getPrice())
                .eq(InventorySummary::getProperty, inventory.getProperty()));
        if (ObjectUtil.isNotNull(invSum) && inventory.getLocationState().equals("in")){
            invSum.setNumber(invSum.getNumber()-1);
            invSum.setStockNumber(invSum.getBrokenNumber()-1);
        } else if (ObjectUtil.isNotNull(invSum) && inventory.getLocationState().equals("out")) {
            invSum.setNumber(invSum.getNumber()-1);
            invSum.setOutboundNumber(invSum.getOutboundNumber()-1);
        }
        boolean result;
        if (invSum.getNumber()==0 && invSum.getStockNumber()==0 && invSum.getOutboundNumber()==0
                && invSum.getBrokenNumber()==0 && invSum.getDestructionNumber()==0) {
            result=inventorySummaryService.removeById(invSum);
        }else {
            result=inventorySummaryService.updateById(invSum);
        }
        boolean remove1 = inventoryService.removeById(inventory);
        boolean remove2 = warehouseInventoryService.remove(new LambdaQueryWrapper<WarehouseInventory>().eq(WarehouseInventory::getEpc, inventory.getEpc()));
        return result && remove2 && remove1;
    }

    /**
     * 直接报废箱标EPC（包括箱内物资）
     * @param req
     * @return
     */
    @Override
    @Transactional
    public Boolean DeleteInventoryByEpcList(EpcInvReq req) {

        if (ObjectUtil.isEmpty(req.getEpc())){
            throw new JYZBAppException(JyzbV2ExceptionEnum.EPC_ERROR);
        }
        List<InventoryBoxMark> list = inventoryBoxMarkService.list(new LambdaQueryWrapper<InventoryBoxMark>().eq(InventoryBoxMark::getEpc, req.getEpc()));
        if (CollectionUtil.isEmpty(list)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.INVEOTORY_INFO_ERROR,"无效epc");
        }
        InventoryBoxMark inventoryBoxMark = list.get(0);
        List<Inventory> invList = inventoryService.list(new LambdaQueryWrapper<Inventory>().eq(Inventory::getBoxMarkId, inventoryBoxMark.getId()));
        if (CollectionUtil.isEmpty(invList)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.INVEOTORY_INFO_ERROR,"无效epc");
        }
        List<String> epcList = invList.stream().map(Inventory::getEpc).collect(Collectors.toList());
        List<LogDetail> logDetaiList = logDetailService.list(new LambdaQueryWrapper<LogDetail>().in(LogDetail::getEpc, epcList));
        if (CollectionUtil.isNotEmpty(logDetaiList)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.INVEOTORY_INFO_ERROR,"epc存在出入库记录，不能进行删除");
        }
        //根据invList获取库存汇总并且进行删除
        Map<String,Object[]> searchMap=new HashMap<>();
        for (Inventory inventory:invList){
            String key=inventory.getOrgId()+inventory.getLocationId()+inventory.getTypeId()+inventory.getSizeId()+inventory.getPrice()+inventory.getProperty();
            if (searchMap.containsKey(key)){
                Object[] objects = searchMap.get(key);
                if (inventory.getLocationState().equals("in")){
                    objects[6]=(Integer)objects[6]+1;
                }else {
                    objects[7]=(Integer)objects[7]+1;
                }

                searchMap.put(key,objects);
            }else {
                Object[] item;
                if (inventory.getLocationState().equals("in")) {
                    item=new Object[]{inventory.getOrgId(),inventory.getCabinetId(),inventory.getTypeId(),inventory.getSizeId(),inventory.getPrice(),inventory.getProperty(),1,0};
                }else {
                    item=new Object[]{inventory.getOrgId(),inventory.getCabinetId(),inventory.getTypeId(),inventory.getSizeId(),inventory.getPrice(),inventory.getProperty(),0,1};
                }
                searchMap.put(key,item);
            }
        }
        List<InventorySummary> inventorySummaryList = inventorySummaryMapper.selectSum(new ArrayList<>(searchMap.values()));
        List<InventorySummary> delInvSumList=new ArrayList<>();
        for (InventorySummary oldSum:inventorySummaryList) {
            String key= oldSum.getOrgId()+oldSum.getLocationId()+oldSum.getTypeId()+oldSum.getSizeId()+oldSum.getUnitPrice()+oldSum.getProperty();
            Object[] objects = searchMap.get(key);
            oldSum.setOutboundNumber(oldSum.getOutboundNumber()-(Integer) objects[7]);
            oldSum.setStockNumber(oldSum.getStockNumber()-(Integer) objects[6]);
            oldSum.setNumber(oldSum.getStockNumber()-(Integer) objects[6]-(Integer) objects[7]);
            oldSum.setPrice(oldSum.getUnitPrice().multiply(BigDecimal.valueOf(oldSum.getNumber())));
            if (oldSum.getNumber() == 0 && oldSum.getStockNumber() == 0 && oldSum.getOutboundNumber() == 0
                    && oldSum.getBrokenNumber()==0 && oldSum.getDestructionNumber() == 0) {
                delInvSumList.add(oldSum);
                inventorySummaryList.remove(oldSum);
            }
        }
        boolean result=true;
        boolean result1=true;
        if (CollectionUtil.isNotEmpty(delInvSumList)){
            result=inventorySummaryService.removeBatchByIds(delInvSumList);
        }
        if (CollectionUtil.isNotEmpty(inventorySummaryList)){
            result1=inventorySummaryService.updateBatchById(inventorySummaryList);
        }
        boolean remove1 = inventoryService.removeBatchByIds(invList);
        boolean remove2 = warehouseInventoryService.remove(new LambdaQueryWrapper<WarehouseInventory>().in(WarehouseInventory::getEpc, epcList));
        return result && result1 && remove1 && remove2;
    }

    /**
     * 通过箱标epc获取件标详细信息
     * @param req
     * @return
     */
    @Override
    public List<GetInvListByBoxMarkEpcDto> GetInventoryListByBoxMarkEpc(EpcInvReq req) {

        if (ObjectUtil.isEmpty(req.getEpc())){
            throw new JYZBAppException(JyzbV2ExceptionEnum.EPC_ERROR);
        }
        List<GetInvListByBoxMarkEpcDto> dtoList=inventoryMapper.GetInventoryListByBoxMarkEpc(req);
        return CollectionUtil.isNotEmpty(dtoList)?dtoList:new ArrayList<>();
    }

    /**
     * 获取箱标
     * @param req
     * @return
     */
    @Override
    public List<GetBoxMarkDto> GetBoxMarkList(GetBoxMarkReq req) {
        if (StrUtil.isEmpty(req.getWarehouseId())){
            req.setWarehouseId(null);
        }
        List<GetBoxMarkDto> dtoList = inventoryBoxMarkMapper.GetBoxMarkList(req);
        System.out.println("dtoList = " + dtoList);
        return dtoList;
    }


    /**
     * 获取打印单据
     * @param req
     * @return
     */
    @Override
    public GetPrintOrderDto GetPrintOrder(GetPrintOrderReq req) {

        if (ObjectUtil.isNull(req.getSize()) || req.getSize()==0){
            req.setSize(50);
        }
        if (ObjectUtil.isNull(req.getPage()) || req.getPage()==0){
            req.setPage(1);
        }
        //获取需要打印的列表
        int size=orderMainMapper.GetPrintOrderCount(req);
        List<GetPrintOrderDto.PrintOrderDto> dtoList=orderMainMapper.GetPrintOrder(req,(req.getPage()-1)*req.getSize(),req.getSize());
        //将供应商单独进行处理
        for (GetPrintOrderDto.PrintOrderDto printOrderDto:dtoList){
            List<GetPrintOrderDto.PrintOrderDto.SuppliersDto> suppliersDtoList=new ArrayList<>();
            GetPrintOrderDto.PrintOrderDto.SuppliersDto suppliersDto = new GetPrintOrderDto.PrintOrderDto.SuppliersDto();
            suppliersDto.setId(printOrderDto.getSupplierId());
            suppliersDto.setCode(printOrderDto.getSupplierCode());
            suppliersDto.setName(printOrderDto.getSupplierName());
            suppliersDtoList.add(suppliersDto);
            printOrderDto.setSuppilers(suppliersDtoList);
        }
        GetPrintOrderDto getPrintOrderDto = new GetPrintOrderDto();
        getPrintOrderDto.setTotal(size);
        getPrintOrderDto.setRecord(dtoList);
        return getPrintOrderDto;
    }

    /**
     * 生成epc
     * @param req
     * @return
     */
    @Override
    public List<GenerateIntTagEpcDto> GenerateIntTagEpc(GenerateIntTagEpcReq req) {


        if (ObjectUtil.isEmpty(req.getSupplierCode()) || ObjectUtil.isEmpty(req.getSizeCode()) ||
                ObjectUtil.isEmpty(req.getEquCode()) || ObjectUtil.isNull(req.getQuantity()) ||
                ObjectUtil.isEmpty(req.getProductTime()) || ObjectUtil.isNull(req.getWarrantyCycle())){
            throw new JYZBAppException(JyzbV2ExceptionEnum.PARAM_ERROR);
        }

        EquipmentType type = equipmentTypeService.getOne(new LambdaQueryWrapper<EquipmentType>().eq(EquipmentType::getCode, req.getEquCode()).eq(EquipmentType::getType,1));
        if (ObjectUtil.isNull(type)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"无效的物资代码");
        }
        EquipmentSize size = equipmentSizeService.getOne(new LambdaQueryWrapper<EquipmentSize>().eq(EquipmentSize::getCode, req.getSizeCode()).eq(EquipmentSize::getTypeId, type.getId()));
        if (ObjectUtil.isNull(size) ){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"无效的号型代码");
        }
        if (req.getQuantity()<=0){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"无效的装备数量");
        }
        if (req.getQuantity()>4095){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"装备数量不正确，应小于4095");
        }
        if (req.getWarrantyCycle()<0){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"无效的质保周期");
        }
        Supplier supplier = supplierService.getOne(new LambdaQueryWrapper<Supplier>().eq(Supplier::getCode, req.getSupplierCode()));
        if (ObjectUtil.isNull(supplier)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"无效的供应商代码");
        }
        if (ObjectUtil.isEmpty(req.getLabelType())){
            req.setLabelType("件标");
        }
        int time = Integer.parseInt(DateTimeUtil.TimeDateToString(req.getProductTime(), "yyyyMMdd"));
        List<GenerateIntTagEpcDto> epcs=new ArrayList<>();
        List<GenerateEpcNum.GenEpcInfo> genEpcInfos=new ArrayList<>();
        if (req.getLabelType().equals("箱标")) {
            Integer epcBoxNum=0;
            //箱标
            if (ObjectUtil.isNull(req.getOneBoxNum()) || req.getOneBoxNum() <=0){
                throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"无效的箱内装备数量");
            }
            String key = DateTimeUtil.TimeDateToString(DateTimeUtil.getCurrentDateTime(),"yyyyMMdd") + "BoxNo";
            String value = generateEpc2Cache.get(key);
            epcBoxNum=ObjectUtil.isNull(value)?1:Integer.parseInt(value)+1;
            generateEpc2Cache.put(key,String.valueOf(epcBoxNum),(long)(10 * 60 * 60));
            genEpcInfos = GenerateEpcNum.GenBoxMarkEpcs((byte) 1, req.getEquCode(), req.getSupplierCode(), req.getSizeCode(), time, req.getOneBoxNum(), epcBoxNum,req.getQuantity());

        }else {
            //件标
            genEpcInfos = GenerateEpcNum.GenEpcs((byte) 1, req.getEquCode(), req.getSupplierCode(), req.getSizeCode(),time, req.getQuantity(),0);

        }
        epcs = genEpcInfos.stream().map(genEpcInfo -> {
            return new GenerateIntTagEpcDto(genEpcInfo.getEpc(),genEpcInfo.getNum());
        }).collect(Collectors.toList());
        if (epcs.size()!=req.getQuantity()){
           throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"生成失败");
        }
        return epcs;

    }

    /**
     * 拆箱还原epc inbox状态(多个epc,箱标限定）
     * @param req
     * @return
     */
    @Override
    @Transactional
    public Boolean UnpackRangeInventory(EpcInvReq req) {

        if (ObjectUtil.isEmpty(req.getEpc())){
            throw new JYZBAppException(JyzbV2ExceptionEnum.EPC_ERROR);
        }
        InventoryBoxMark one = inventoryBoxMarkService.getOne(new LambdaQueryWrapper<InventoryBoxMark>().eq(InventoryBoxMark::getEpc, req.getEpc()));
        if (ObjectUtil.isNull(one)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.INVEOTORY_INFO_ERROR,"无效的epc");
        }
        List<Inventory> list = inventoryService.list(new LambdaQueryWrapper<Inventory>().eq(Inventory::getBoxMarkId, one.getId()));
        if (CollectionUtil.isEmpty(list)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"无对应物资，更新失败");
        }else {
            if (list.stream().anyMatch(inventory -> inventory.getLocationState().equals("out"))){
                throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"物资状态不是在库，更新失败");

            }
            list.forEach(inventory -> {inventory.setBoxMarkId("");inventory.setIsInBox(0);});
        }
        boolean result1 = inventoryBoxMarkService.removeById(one);
        boolean result2 = inventoryService.updateBatchById(list);
        return result1 && result2;
    }


    /**
     * 检查epc是否已被实例化过
     * @param req
     * @return
     */
    @Override
    public Boolean CheckEpcIsInstantiation(EpcInvReq req) {

        if (ObjectUtil.isEmpty(req.getEpc())){
            throw new JYZBAppException(JyzbV2ExceptionEnum.EPC_ERROR);
        }
        //查询库存是否存在装备
        Inventory inventory = inventoryService.getOne(new LambdaQueryWrapper<Inventory>().eq(Inventory::getEpc, req.getEpc()));
        PrintEpcs printEpcs = printEpcsService.getOne(new LambdaQueryWrapper<PrintEpcs>()
                .eq(PrintEpcs::getEpc, req.getEpc())
                .ne(PrintEpcs::getCurrentState, 0));
        //查询采购打印是否已经生成epc
        if (ObjectUtil.isNotNull(inventory) || ObjectUtil.isNotNull(printEpcs)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"标签已绑定过装备");
        }
        return true;
    }


    /**
     * 根据采购单信息生成EPC
     * @param req
     * @return
     */
    @Override
    @Transactional
    public Boolean GenerateExtTagEpc(GenerateExtTagEpcReq req) {
        Integer totalNum =(Integer) outInRecordRedisCache.get(req.getDetailId());
        if (ObjectUtil.isNull(totalNum))
            totalNum=0;
        if ((ObjectUtil.isEmpty(req.getSupplierId()) && ObjectUtil.isEmpty(req.getSupplierCode())) ||
                ObjectUtil.isEmpty(req.getSupplierName()) || ObjectUtil.isEmpty(req.getDetailId()) ||
                ObjectUtil.isEmpty(req.getSizeCode()) || ObjectUtil.isEmpty(req.getEquCode()) ||
                ObjectUtil.isNull(req.getQuantity()) || ObjectUtil.isEmpty(req.getProductTime()) ||
                ObjectUtil.isNull(req.getRepairCycle()) || ObjectUtil.isNull(req.getWarrantyCycle())){
            throw new JYZBAppException(JyzbV2ExceptionEnum.PARAM_ERROR);
        }

        Boolean result;
        EquipmentType type = equipmentTypeService.getOne(new LambdaQueryWrapper<EquipmentType>().eq(EquipmentType::getCode, req.getEquCode()).eq(EquipmentType::getType,1));
        if (ObjectUtil.isNull(type)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"无效的物资代码");
        }
        EquipmentSize size = equipmentSizeService.getOne(new LambdaQueryWrapper<EquipmentSize>().eq(EquipmentSize::getCode, req.getSizeCode()).eq(EquipmentSize::getTypeId, type.getId()));
        if (ObjectUtil.isNull(size) ){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"无效的号型代码");
        }
        if (req.getQuantity()<=0){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"无效的装备数量");
        }
        if (req.getQuantity()>4095){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"装备数量不正确，应小于4095");
        }
        if (req.getWarrantyCycle()<0){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"无效的质保周期");
        }
        Supplier supplier=null;
        if (ObjectUtil.isNotEmpty(req.getSupplierId())){
            supplier=supplierService.getById(req.getSupplierId());
        }else {

            supplier = supplierService.getOne(new LambdaQueryWrapper<Supplier>().eq(Supplier::getCode, req.getSupplierCode()));
        }
        if (ObjectUtil.isNull(supplier)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"无效的供应商代码");
        }
        if (!supplier.getName().equals(req.getSupplierName())){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"无效的供应商名称");
        }
        if (!supplier.getId().equals(req.getSupplierId())){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"无效的供应商id");
        }
        OrderDetail orderDetail = orderDetailService.getById(req.getDetailId());
        if (ObjectUtil.isNull(orderDetail)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"无效的子单据id");
        }
        if (req.getWarrantyCycle()<0 || req.getRepairCycle()<=0){
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"无效的质保期或者维保期");
        }
        Shelf shelf=null;
        if (ObjectUtil.isNotEmpty(req.getShelfId())){
            shelf=shelfService.getById(req.getShelfId());
        }
        int time = Integer.parseInt(DateTimeUtil.TimeDateToString(req.getProductTime(), "yyyyMMdd"));

        List<GenerateEpcNum.GenEpcInfo> genEpcInfos = GenerateEpcNum.GenEpcs((byte) 1, req.getEquCode(), req.getSupplierCode(), req.getSizeCode(), time, req.getQuantity(),totalNum);


        if (genEpcInfos.size()==req.getQuantity()){
            List<PrintEpcs> addList=new ArrayList<>();
            for (GenerateEpcNum.GenEpcInfo genEpcInfo:genEpcInfos) {
                PrintEpcs printEpcs = new PrintEpcs();
                printEpcs.setEpc(genEpcInfo.getEpc());
                printEpcs.setNum(genEpcInfo.getNum());
                printEpcs.setCreateTime(DateTimeUtil.getCurrentDateTime());
                printEpcs.setCurrentState(0);
                printEpcs.setOrderDetailId(req.getDetailId());
                printEpcs.setPrice(req.getPrice());
                printEpcs.setProductTime(req.getProductTime());
                printEpcs.setRepairCycle(req.getRepairCycle());
                printEpcs.setWarrantyCycle(req.getWarrantyCycle());
                printEpcs.setSupplierId(req.getSupplierId());
                printEpcs.setUseDirection(0);
                printEpcs.setUseTime(req.getUseTime());
                printEpcs.setSupplierName(req.getSupplierName());
                if (ObjectUtil.isNotNull(shelf)){
                    printEpcs.setShelfId(shelf.getShelfId());
                    printEpcs.setShelfRow(req.getShelfRow());
                    printEpcs.setShelfRange(req.getShelfRange());
                    printEpcs.setShelfColumn(req.getShelfColumn());
                }
                if (totalNum<genEpcInfo.getNum()){
                    totalNum=genEpcInfo.getNum();
                }
                addList.add(printEpcs);
            }
            if (totalNum<orderDetail.getPlanNum()){
                outInRecordRedisCache.put(req.getDetailId(),totalNum);
            }else {
                outInRecordRedisCache.remove(req.getDetailId());
            }
            result = printEpcsService.saveBatch(addList);
        }else {
            throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"操作失败");
        }
        return result;
    }

    /**
     * 导入旧箱标数据（旧时间戳epc）
     * @param req
     * @return
     */
    @Override
    public ImportOldBoxMarkDto ImportOldBoxMark(ImportOldBoxMarkReq req) {
        if (CollectionUtil.isEmpty(req.getDataList()) || req.getDataList().size()<=0){
            throw new JYZBAppException(CabinetV2ExceptionEnum.IMPORT_BOX_MARK_ERROR,"请求参数为空");
        }

        List<ImportOldBoxMarkDto.SuccessDto> successDtoList=new ArrayList<>();
        List<ImportOldBoxMarkDto.FailDto> failDtoList=new ArrayList<>();

        List<String> allEpcList=new ArrayList<>();
        List<String> allBoxMarkEpcList=new ArrayList<>();
        for (ImportOldBoxMarkReq.OldBoxMarkReq markReq:req.getDataList()){
            //全部查询出来并且一一进行比对
            allBoxMarkEpcList.add(markReq.getBoxMarkEpc());
            List<String> epcs = JSONObject.parseArray(ObjectUtil.isEmpty(markReq.getEpcListJosn()) ?"[]":markReq.getEpcListJosn(), String.class);
            allEpcList.addAll(epcs);
        }
        if (CollectionUtil.isEmpty(allEpcList)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.IMPORT_BOX_MARK_ERROR,"epc不能为空");
        }
        List<Inventory> invList = inventoryMapper.getInvWithCode(allEpcList);
        List<InventoryBoxMark> boxMarkList = inventoryBoxMarkService.list(new LambdaQueryWrapper<InventoryBoxMark>()
                .in(InventoryBoxMark::getEpc, allBoxMarkEpcList));
        List<String> existBoxMarkEpcList=new ArrayList<>();
        if (CollectionUtil.isNotEmpty(boxMarkList)){
            existBoxMarkEpcList = boxMarkList.stream().map(InventoryBoxMark::getEpc).collect(Collectors.toList());
        }

        List<InventoryBoxMark> addBoxMarkList=new ArrayList<>();
        List<Inventory> updateInventoryList=new ArrayList<>();
        for (ImportOldBoxMarkReq.OldBoxMarkReq markReq:req.getDataList()){
            //如果存在直接报错
            if (CollectionUtil.isNotEmpty(existBoxMarkEpcList) && existBoxMarkEpcList.contains(markReq.getBoxMarkEpc())){
                ImportOldBoxMarkDto.FailDto failDto = new ImportOldBoxMarkDto.FailDto();
                failDto.setEpc(markReq.getBoxMarkEpc());
                failDto.setMessage("该箱标已录入");
                failDtoList.add(failDto);
                continue;
            }


            List<String> epcs = JSONObject.parseArray(ObjectUtil.isEmpty(markReq.getEpcListJosn()) ?"[]":markReq.getEpcListJosn(), String.class);
            List<Inventory> inventoryList = countCommonElements(invList, epcs);
            if (inventoryList.size() == 0 || inventoryList.size() != epcs.size()){
                ImportOldBoxMarkDto.FailDto failDto = new ImportOldBoxMarkDto.FailDto();
                failDto.setEpc(markReq.getBoxMarkEpc());
                failDto.setMessage("箱内物资数量错误");
                failDtoList.add(failDto);
                continue;
            }

            boolean flag=false;
            for (Inventory inventory:inventoryList){
                if (ObjectUtil.isEmpty(inventory.getBoxMarkId())){
                    ImportOldBoxMarkDto.FailDto failDto = new ImportOldBoxMarkDto.FailDto();
                    failDto.setEpc(markReq.getBoxMarkEpc());
                    failDto.setMessage("箱内物资状态异常");
                    failDtoList.add(failDto);
                    flag=true;
                    break;
                }
            }
            if (flag){
                continue;
            }

            //获取第一个物资，并进行创建箱标
            Inventory inventory = inventoryList.get(0);
            GenerateIntTagEpcReq generateIntTagEpcReq = new GenerateIntTagEpcReq();
            generateIntTagEpcReq.setLabelType("箱标");
            generateIntTagEpcReq.setProductTime(inventory.getProductionDate());
            generateIntTagEpcReq.setEquCode(inventory.getEquCode());
            generateIntTagEpcReq.setSizeCode(inventory.getSizeCode());
            generateIntTagEpcReq.setSupplierCode(inventory.getSupplierCode());
            generateIntTagEpcReq.setQuantity(1);
            generateIntTagEpcReq.setWarrantyCycle(inventory.getWarrantyPeriod());
            generateIntTagEpcReq.setOneBoxNum(inventoryList.size());

            List<GenerateIntTagEpcDto> list= this.GenerateIntTagEpc(generateIntTagEpcReq);
            if (CollectionUtil.isEmpty(list)){
                ImportOldBoxMarkDto.FailDto failDto = new ImportOldBoxMarkDto.FailDto();
                failDto.setEpc(markReq.getBoxMarkEpc());
                failDto.setMessage("箱标创建失败");
                failDtoList.add(failDto);
                continue;
            }

            String newBoxMarkEpc = list.get(0).getEpc();
            //创建一个boxMark信息
            InventoryBoxMark inventoryBoxMark = createBoxMark(newBoxMarkEpc,markReq.getBoxMarkEpc(),inventoryList.size(),
                    inventory.getTypeId(),inventory.getSizeId(),inventory.getSupplierId(),inventory.getLocationId(),0,2);
            addBoxMarkList.add(inventoryBoxMark);

            inventoryList.forEach(inventory1 -> inventory1.setBoxMarkId(inventoryBoxMark.getId()));
            updateInventoryList.addAll(inventoryList);

            ImportOldBoxMarkDto.SuccessDto successDto = new ImportOldBoxMarkDto.SuccessDto();
            successDto.setEpc(markReq.getBoxMarkEpc());
            successDto.setMessage("");
            successDtoList.add(successDto);

        }
        if (CollectionUtil.isNotEmpty(addBoxMarkList)){
            inventoryBoxMarkService.saveBatch(addBoxMarkList);
        }
        if (CollectionUtil.isNotEmpty(updateInventoryList)){
            inventoryService.updateBatchById(updateInventoryList);
        }
        ImportOldBoxMarkDto importOldBoxMarkDto = new ImportOldBoxMarkDto();
        importOldBoxMarkDto.setSuccessList(successDtoList);
        importOldBoxMarkDto.setFailList(failDtoList);
        return importOldBoxMarkDto;
    }

    /**
     * 获取需要打印的重装箱箱标
     * @param req
     * @return
     */
    @Override
    public List<GetNeedPrintBoxMarkDto> GetNeedPrintBoxMarkList(GetNeedPrintBoxMarkReq req) {
        List<GetNeedPrintBoxMarkDto> dtoList=inventoryBoxMarkMapper.selectNeedPrintListByOrgId(req.getOrgId());
        if (CollectionUtil.isEmpty(dtoList)){
            return new ArrayList<>();
        }else {
            //将epc进行重新处理
            for (GetNeedPrintBoxMarkDto dto:dtoList){
                if (ObjectUtil.isNotNull(dto.getEpcJson())){

                    String epcJson = dto.getEpcJson();
                    List<String> epcList = Arrays.asList(epcJson.split(","));
                    dto.setEpcList(epcList);
                }
            }
            return dtoList;
        }
    }

    /**
     * 装箱操作(内部版，箱标限定)
     * @param req
     * @return
     */
    @Override
    @Transactional
    public Boolean BoxingInventory(BoxingInventoryReq req) {

        if (ObjectUtil.isEmpty(req.getBoxMarkEpc())){
            throw new JYZBAppException(JyzbV2ExceptionEnum.BOXMARKEPC_ERROR);
        }

        InventoryBoxMark boxMark = inventoryBoxMarkService.getById(req.getBoxMarkEpc());
        if (ObjectUtil.isNotNull(boxMark)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.BOXING_INVENTORY_ERROR,"箱标epc已存在");
        }
        if (CollectionUtil.isEmpty(req.getInvList()) || req.getInvList().size()<=0){
            throw new JYZBAppException(CabinetV2ExceptionEnum.BOXING_INVENTORY_ERROR,"invList不能为空");
        }
        BoxingInventoryReq.InvReq invReq = req.getInvList().get(0);
        String boxSizeId=invReq.getSizeId();
        String boxEquId=invReq.getEquId();
        String boxSupplierId=invReq.getSupplierId();
        String boxWarehouseId=invReq.getWarehouseId();

        //创建一个新的箱标信息
        InventoryBoxMark newBoxMark = createBoxMark(req.getBoxMarkEpc(), null, req.getInvList().size(), boxEquId, boxSizeId, boxSupplierId, boxWarehouseId, 0, 1);
        inventoryBoxMarkService.save(newBoxMark);

        List<String> epcList=new ArrayList<>();
        List<String> epcReqList=new ArrayList<>();
        Map<String,Long> warehouseOrgMap=new HashMap<>();
//        Map<String,String> warehouseIdMap=new HashMap<>();
        List<String> warehouseIdsList=new ArrayList<>();
        Map<String,String> warehouseIdToNameMap=new HashMap<>();
        for (int i=0;i<req.getInvList().size();i++){
            BoxingInventoryReq.InvReq invInfo = req.getInvList().get(i);
            //将装备添加箱标信息
            if (invInfo.getIsUnboxingLabel()){
                epcList.add(invInfo.getEpc());
                req.getInvList().remove(invInfo);
                i--;
            }else {
                //创建新物资
                //首先需要判断一下库存中是否存在epc，如果存在则直接报错
                epcReqList.add(invInfo.getEpc());
                if (!warehouseIdsList.contains(invReq.getWarehouseId())){
                    warehouseIdsList.add(invReq.getWarehouseId());
                }
            }
        }
        //修改拆箱标签
        if (CollectionUtil.isNotEmpty(epcList)){
            List<Inventory> list = inventoryService.list(new LambdaQueryWrapper<Inventory>().in(Inventory::getEpc, epcList));
            List<String> collect = list.stream().map(Inventory::getEpc).collect(Collectors.toList());
            if (CollectionUtil.isEmpty(list)){
                throw new JYZBAppException(CabinetV2ExceptionEnum.BOXING_INVENTORY_ERROR,"无效拆箱标签");
            }else {
                for (Inventory inventory:list){
                    if (!collect.contains(inventory.getEpc())){
                        throw new JYZBAppException(CabinetV2ExceptionEnum.BOXING_INVENTORY_ERROR,"无效拆箱标签");
                    }else {
                        inventory.setBoxMarkId(newBoxMark.getId());
                    }
                }
                inventoryService.updateBatchById(list);
            }

        }
        if (CollectionUtil.isNotEmpty(epcReqList)){
            List<Inventory> list = inventoryService.list(new LambdaQueryWrapper<Inventory>().in(Inventory::getEpc, epcReqList));
            if (CollectionUtil.isNotEmpty(list)){
                List<String> collect = list.stream().map(Inventory::getEpc).collect(Collectors.toList());
                String joinEpc = String.join(",", collect);
                throw new JYZBAppException(CabinetV2ExceptionEnum.BOXING_INVENTORY_ERROR,"生成库存失败，库存内已存在此EPC"+joinEpc);
            }
        }

        List<Inventory> addInventoryList=new ArrayList<>();
        if (CollectionUtil.isNotEmpty(req.getInvList())){
            List<Warehouse> list = warehouseService.list(new LambdaQueryWrapper<Warehouse>().in(Warehouse::getId, warehouseIdsList));

            for (Warehouse warehouse:list){
                if (!warehouseOrgMap.containsKey(warehouse.getId())){
                    warehouseOrgMap.put(warehouse.getId(),warehouse.getOrgIdInt());
                }
                if (!warehouseIdToNameMap.containsKey(warehouse.getId())){
                    warehouseIdToNameMap.put(warehouse.getId(),warehouse.getName());

                }
            }


            List<String> epcs=new ArrayList<>();
            for (BoxingInventoryReq.InvReq inv:req.getInvList()){
                //创建新的装备，并且根据新的装备添加库存汇总数据

                Inventory inventory = createInventoryInfo(newBoxMark.getId(),inv.getWarehouseId(),inv.getEquId(),inv.getSizeId(),
                        warehouseOrgMap.get(inv.getWarehouseId()),inv.getProductTime(),inv.getRepairCycle(),inv.getWarrantyCycle(),
                        inv.getEpc(),inv.getSupplierId(),inv.getShelfId(),inv.getShelfColumn(),inv.getShelfRange(),inv.getShelfRange(),1,1);



                addInventoryList.add(inventory);
                epcs.add(inv.getEpc());
            }
            boolean b = inventoryService.saveBatch(addInventoryList);
            //插了之后查询想要的数据进行返回
            addInventoryList=inventoryMapper.getInvNamesByEpcs(epcs);
            //还得创建warehouseInventory的数据
            List<WarehouseInventory> addWareInvList = createWareInvList(addInventoryList);

            if (CollectionUtil.isNotEmpty(addWareInvList)){
                warehouseInventoryService.saveBatch(addWareInvList);
            }

            addInvAndSumInfo(addInventoryList);

        }

        return true;
    }


    /**
     * 装箱操作(用户版，箱标限定)
     * @param req
     * @return
     */
    @Override
    public Boolean BoxingInventoryNormalVersion(BoxingInventoryReq req) {


        if (ObjectUtil.isEmpty(req.getBoxMarkEpc())){
            throw new JYZBAppException(JyzbV2ExceptionEnum.BOXMARKEPC_ERROR);
        }
        Policeman policeman=null;
        if (ObjectUtil.isNotEmpty(req.getPoliceId()) || !StrUtil.isEmpty(req.getPoliceId()) || !req.getPoliceId().isEmpty()){
            policeman = policemanService.getById(req.getPoliceId());
        }
        //获取箱标
        InventoryBoxMark boxMark = inventoryBoxMarkService.getById(req.getBoxMarkEpc());
        if (ObjectUtil.isNotNull(boxMark)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.BOXING_INVENTORY_ERROR,"箱标epc已存在");
        }
        if (CollectionUtil.isEmpty(req.getInvList()) || req.getInvList().size()<=0){
            throw new JYZBAppException(CabinetV2ExceptionEnum.BOXING_INVENTORY_ERROR,"invList不能为空");
        }
        BoxingInventoryReq.InvReq invReq = req.getInvList().get(0);
        String boxSizeId=invReq.getSizeId();
        String boxEquId=invReq.getEquId();
        String boxSupplierId=invReq.getSupplierId();
        String boxWarehouseId=invReq.getWarehouseId();

        //创建一个新的箱标信息
        InventoryBoxMark newBoxMark = createBoxMark(req.getBoxMarkEpc(), null, req.getInvList().size(), boxEquId, boxSizeId, boxSupplierId, boxWarehouseId, 0, 1);
        inventoryBoxMarkService.save(newBoxMark);

        //装箱设置箱标的epc列表
        List<String> epcList=new ArrayList<>();

        List<String> epcReqList=new ArrayList<>();
        Boolean flag=false;
        for (int i=0;i<req.getInvList().size();i++){
            BoxingInventoryReq.InvReq invInfo = req.getInvList().get(i);
            //将装备添加箱标信息（装箱）
            if (ObjectUtil.isNotNull(invInfo.getIsUnboxingLabel()) && invInfo.getIsUnboxingLabel()){
                epcList.add(invInfo.getEpc());
                req.getInvList().remove(invInfo);
                flag=true;
                i--;
            }else {
                //创建新物资，不直接存入库存，调用rabbitmq本地处理方法进行处理
                //首先需要判断一下库存中是否存在epc，如果存在则直接报错
                epcReqList.add(invInfo.getEpc());
            }
        }
        List<Inventory> list1 = inventoryService.list(new LambdaQueryWrapper<Inventory>().eq(Inventory::getInstantiationState, 1).in(Inventory::getEpc, epcReqList));
        if (CollectionUtil.isNotEmpty(list1)){
            for (Inventory inventory:list1) {
                epcReqList.remove(inventory.getEpc());
                epcList.add(inventory.getEpc());
            }
        }
        //修改装箱标签
        if (CollectionUtil.isNotEmpty(epcList)){
            List<Inventory> list =new ArrayList<>();
            if (CollectionUtil.isNotEmpty(list1) && !flag){
                list.addAll(list1);
            }else {
                list= inventoryService.list(new LambdaQueryWrapper<Inventory>().in(Inventory::getEpc, epcList));
            }

            List<String> collect = list.stream().map(Inventory::getEpc).collect(Collectors.toList());
            if (CollectionUtil.isEmpty(list)){
                throw new JYZBAppException(CabinetV2ExceptionEnum.BOXING_INVENTORY_ERROR,"无效拆箱标签");
            }else {
                for (Inventory inventory:list){
                    if (!collect.contains(inventory.getEpc())){
                        throw new JYZBAppException(CabinetV2ExceptionEnum.BOXING_INVENTORY_ERROR,"无效拆箱标签");
                    }else {
                        inventory.setBoxMarkId(newBoxMark.getId());
                    }
                }
                inventoryService.updateBatchById(list);
            }

        }
        //处理生成采购epcList，并进行处理后续出入库记录，以及汇总信息
        List<PrintEpcs> list=new ArrayList<>();
        if (CollectionUtil.isNotEmpty(epcReqList)){
            list=printEpcsMapper.getList(epcReqList);

            if (CollectionUtil.isNotEmpty(list)){
                List<String> noExitEpcList=new ArrayList<>();
                List<String> collect = list.stream().map(PrintEpcs::getEpc).collect(Collectors.toList());
                for (String epc:epcReqList) {
                    if (!collect.contains(epc)){
                        noExitEpcList.add(epc);
                    }
                }
                if (CollectionUtil.isNotEmpty(noExitEpcList)){
                    String joinEpc = String.join(",", noExitEpcList);
                    throw new JYZBAppException(CabinetV2ExceptionEnum.BOXING_INVENTORY_ERROR,"无效打印标签"+joinEpc);
                }
                list.forEach(printEpcs -> printEpcs.setCurrentState(2));
            }
        }
        //同一处理采购epc，如果单子记账了就不管了
        //根据detail进行分类，如果单子已经记账，删除
        //存入调用本地返回上报结果方法进行处理（先获取一下redis中存入的东西之后再今天添加跟新之后再调用结果方法因为redis是替换不是追加）
        if (CollectionUtil.isNotEmpty(list)){

            //这个printEpcsListMap 中的key为orderDetailId，value则是采购生成的epc信息
            Map<String,List<PrintEpcs>> printEpcsListMap=new HashMap<>();
            for (int i=0;i<list.size();i++) {
                PrintEpcs printEpcs = list.get(i);
                if (!printEpcsListMap.containsKey(printEpcs.getOrderDetailId())){
                    List<PrintEpcs> printEpcsList=new ArrayList<>();
                    printEpcsList.add(printEpcs);
                    printEpcsListMap.put(printEpcs.getOrderDetailId(),printEpcsList);
                }else {
                    List<PrintEpcs> printEpcsList = printEpcsListMap.get(printEpcs.getOrderDetailId());
                    printEpcsList.add(printEpcs);
                    printEpcsListMap.put(printEpcs.getOrderDetailId(),printEpcsList);
                }
            }
            List<String> orderDetailIdsList = new ArrayList<>(printEpcsListMap.keySet());
            //获取一个detail的详细信息但是带了order信息的东西
            List<OrderInfoDto> orderInfoList=orderMainMapper.getInfoByOrderDetailIds(orderDetailIdsList);

            //orderMainReqMap的key是主单据id，value是单据信息
            Map<String,OrderReq> orderMainReqMap=new HashMap<>();


            //处理出入库调用接口
            Map<String,SummaryLogReq> orderLogReqMap=new HashMap<>();


            if (orderInfoList.size()>0){
                //为了获取不重复的主单据id，为了直接获取主单局的具体采购信息
                //orderInvMap的key是主单据id，value是存入的采购装备信息列表
                Map<String,List<Inventory>> orderInvMap=new HashMap<>();
                List<String> orderIdList = orderInfoList.stream().map(OrderInfoDto::getOrderId).distinct().collect(Collectors.toList());
                for (String orderId:orderIdList){
                    List<Inventory> objects = outInRecordRedisCache.addInventory("addInvRecord:" + orderId);
                    if (CollectionUtil.isNotEmpty(objects)){
                        orderInvMap.put(orderId,objects);
                    }
                }
                for (OrderInfoDto infoDto:orderInfoList) {

                    //操作单据
                    if (!orderMainReqMap.containsKey(infoDto.getOrderId())){
                        OrderReq orderReq = new OrderReq();
                        orderReq.setId(infoDto.getOrderId());
                        orderReq.setBussinessType("purchase");
                        orderReq.setOrgId(infoDto.getOrgId());
                        orderReq.setOrgName(infoDto.getOrgName());
                        orderReq.setOrderState("finished");
                        List<PrintEpcs> printEpcsList = printEpcsListMap.get(infoDto.getId());
                        //存放orderDetail列表
                        List<DetailOrderReq> detailList=new ArrayList<>();

                        if (CollectionUtil.isNotEmpty(printEpcsList)){

                            Integer actualNum = ObjectUtil.isNotNull(infoDto.getActualNum())?infoDto.getActualNum():0;
                            DetailOrderReq detailOrderReq = new DetailOrderReq();
                            detailOrderReq.setId(infoDto.getId());
                            detailOrderReq.setOrderType("finished");
                            detailOrderReq.setActualNum(actualNum+printEpcsList.size());


                            Map<String,Object> valueMap=new HashMap<>();
                            valueMap = createDetailInvInfo(valueMap, printEpcsList, detailList, detailOrderReq, infoDto, newBoxMark);
                            Object detailList1 = valueMap.get("detailList");
                            detailList = ((List<?>) detailList1).stream()
                                    .filter(DetailOrderReq.class::isInstance)
                                    .map(DetailOrderReq.class::cast)
                                    .collect(Collectors.toList());
                            Object collect1 = valueMap.get("collect");
                            List<PurchaseEqsReq> collect = ((List<?>) collect1).stream()
                                    .filter(PurchaseEqsReq.class::isInstance)
                                    .map(PurchaseEqsReq.class::cast)
                                    .collect(Collectors.toList());

                            List<Inventory> inventoryList = orderInvMap.get(infoDto.getOrderId());
                            if (CollectionUtil.isNotEmpty(inventoryList)){
                                List<PurchaseEqsReq> beanList = BeanPlusUtil.toBeanList(inventoryList, PurchaseEqsReq.class);
                                collect.addAll(beanList);
                            }

                            orderReq.setOrderDetail(detailList);
                            orderReq.setActualQuantity(detailOrderReq.getActualNum());
                            orderReq.setPrice(new BigDecimal(infoDto.getPrice()).multiply(BigDecimal.valueOf(detailOrderReq.getActualNum())));
                            orderReq.setPurchaseList(collect);
                            orderMainReqMap.put(infoDto.getOrderId(),orderReq);
                        }
                    }
                    else {
                        OrderReq orderReq = orderMainReqMap.get(infoDto.getOrderId());
                        List<PrintEpcs> printEpcsList = printEpcsListMap.get(infoDto.getId());
                        List<DetailOrderReq> detailList=new ArrayList<>();
                        Integer actualQuantity=0;
                        BigDecimal totalPrice=BigDecimal.ZERO;
                        if (CollectionUtil.isNotEmpty(printEpcsList)){


                            Integer actualNum = ObjectUtil.isNotNull(infoDto.getActualNum())?infoDto.getActualNum():0;
                            DetailOrderReq detailOrderReq = new DetailOrderReq();
                            detailOrderReq.setId(infoDto.getId());
                            detailOrderReq.setOrderType("finished");
                            detailOrderReq.setActualNum(actualNum+printEpcsList.size());
                            actualQuantity=detailOrderReq.getActualNum();
                            totalPrice=detailOrderReq.getPrice().multiply(BigDecimal.valueOf(detailOrderReq.getActualNum()));


                            Map<String,Object> valueMap=new HashMap<>();
                            //获取detailList以及invInfo
                            valueMap = createDetailInvInfo(valueMap, printEpcsList, detailList, detailOrderReq, infoDto, newBoxMark);
                            Object detailList1 = valueMap.get("detailList");
                            detailList = ((List<?>) detailList1).stream()
                                    .filter(DetailOrderReq.class::isInstance)
                                    .map(DetailOrderReq.class::cast)
                                    .collect(Collectors.toList());
                            Object collect1 = valueMap.get("collect");
                            List<PurchaseEqsReq> collect = ((List<?>) collect1).stream()
                                    .filter(PurchaseEqsReq.class::isInstance)
                                    .map(PurchaseEqsReq.class::cast)
                                    .collect(Collectors.toList());


                            List<DetailOrderReq> orderDetail = orderReq.getOrderDetail();
                            orderDetail.addAll(detailList);
                            orderReq.setOrderDetail(orderDetail);
                            orderReq.setActualQuantity(orderReq.getActualQuantity()+actualQuantity);
                            orderReq.setPrice(orderReq.getPrice().add(totalPrice));
                            List<PurchaseEqsReq> purchaseList = orderReq.getPurchaseList();
                            purchaseList.addAll(collect);
                            orderReq.setPurchaseList(purchaseList);
                            orderMainReqMap.put(infoDto.getOrderId(),orderReq);
                        }
                    }


                    //操作出入库日志
                    if (!orderLogReqMap.containsKey(infoDto.getOrderId())){
                        SummaryLogReq summaryLogReq = new SummaryLogReq();
                        summaryLogReq.setOrderMainId(infoDto.getOrderId());
                        summaryLogReq.setOrderCode(infoDto.getOrderCode());
                        summaryLogReq.setOrgId(infoDto.getOrgId());
                        summaryLogReq.setOrgName(infoDto.getOrgName());
                        summaryLogReq.setUserName(ObjectUtil.isNotNull(policeman)?policeman.getName():infoDto.getUserName());
                        summaryLogReq.setUseTime(DateTimeUtil.getCurrentDateTime());
                        summaryLogReq.setLocationId(infoDto.getWarehouseId());
                        summaryLogReq.setLocationName(infoDto.getWarehouseName());
                        summaryLogReq.setLocationType(0);
                        summaryLogReq.setEquipmentList(infoDto.getTypeName());
                        summaryLogReq.setBussinessType("purchase");
                        summaryLogReq.setDevice("打印机");
                        summaryLogReq.setDeviceType(5);
                        summaryLogReq.setOutInState("in");
                        BigDecimal totalPrice=BigDecimal.ZERO;
                        BigDecimal[] totalPriceArr = {totalPrice};
                        List<PrintEpcs> printEpcsList = printEpcsListMap.get(infoDto.getId());

                        List<String> typeNameList=new ArrayList<>();
                        if (CollectionUtil.isNotEmpty(printEpcsList)){


                            List<DetailLogReq> collect = printEpcsList.stream().map(printEpcs -> {
                                DetailLogReq detailLogReq = new DetailLogReq();
                                detailLogReq.setEpc(printEpcs.getEpc());
                                detailLogReq.setProperty(0);
                                detailLogReq.setPrice(printEpcs.getPrice());
                                detailLogReq.setSizeId(printEpcs.getSizeId());
                                detailLogReq.setSizeName(printEpcs.getSizeName());
                                detailLogReq.setTypeId(printEpcs.getTypeId());
                                detailLogReq.setTypeName(printEpcs.getTypeName());
                                detailLogReq.setSupplierId(printEpcs.getSupplierId());
                                detailLogReq.setSupplierName(printEpcs.getSupplierName());
                                detailLogReq.setErrorState(0);
                                return detailLogReq;
                            }).collect(Collectors.toList());


                            List<Inventory> inventoryList = orderInvMap.get(infoDto.getOrderId());
                            if (CollectionUtil.isNotEmpty(inventoryList)){
                                List<DetailLogReq> beanList = BeanPlusUtil.toBeanList(inventoryList, DetailLogReq.class);

                                collect.addAll(beanList);
                            }
                            collect.forEach(detailLogReq -> {
                                if (!typeNameList.contains(detailLogReq.getTypeName()))
                                    typeNameList.add(detailLogReq.getTypeName());
                                totalPriceArr[0] = totalPriceArr[0].add(detailLogReq.getPrice());
                            });

                            summaryLogReq.setNumber(collect.size());
                            summaryLogReq.setLogDetailList(collect);
                            summaryLogReq.setEquipmentList(String.join(",", typeNameList));
                            summaryLogReq.setPrice(totalPriceArr[0]);
                            orderLogReqMap.put(infoDto.getOrderId(),summaryLogReq);
                        }
                    }
                    else {
                        SummaryLogReq summaryLogReq = orderLogReqMap.get(infoDto.getOrderId());

                        List<PrintEpcs> printEpcsList = printEpcsListMap.get(infoDto.getId());
                        BigDecimal totalPrice=BigDecimal.ZERO;
                        BigDecimal[] totalPriceArr = {totalPrice};
                        List<String> typeNameList=new ArrayList<>();
                        if (CollectionUtil.isNotEmpty(printEpcsList)){


                            List<DetailLogReq> collect = printEpcsList.stream().map(printEpcs -> {
                                DetailLogReq detailLogReq = new DetailLogReq();
                                detailLogReq.setEpc(printEpcs.getEpc());
                                detailLogReq.setProperty(0);
                                detailLogReq.setPrice(printEpcs.getPrice());
                                detailLogReq.setSizeId(printEpcs.getSizeId());
                                detailLogReq.setSizeName(printEpcs.getSizeName());
                                detailLogReq.setTypeId(printEpcs.getTypeName());
                                detailLogReq.setTypeName(printEpcs.getTypeName());
                                detailLogReq.setSupplierId(printEpcs.getSupplierId());
                                detailLogReq.setSupplierName(printEpcs.getSupplierName());
                                detailLogReq.setErrorState(0);
                                return detailLogReq;
                            }).collect(Collectors.toList());

                            List<Inventory> inventoryList = orderInvMap.get(infoDto.getOrderId());
                            if (CollectionUtil.isNotEmpty(inventoryList)){
                                List<DetailLogReq> beanList = BeanPlusUtil.toBeanList(inventoryList, DetailLogReq.class);

                                collect.addAll(beanList);
                            }
                            collect.forEach(detailLogReq -> {
                                if (!typeNameList.contains(detailLogReq.getTypeName()))
                                    typeNameList.add(detailLogReq.getTypeName());
                                totalPriceArr[0] = totalPriceArr[0].add(detailLogReq.getPrice());
                            });

                            summaryLogReq.setNumber(summaryLogReq.getNumber()+collect.size());
                            summaryLogReq.setPrice(summaryLogReq.getPrice().add(totalPrice));
                            List<DetailLogReq> logDetailList = summaryLogReq.getLogDetailList();
                            logDetailList.addAll(collect);
                            summaryLogReq.setLogDetailList(logDetailList);
                            List<String> typeName =  Arrays.asList(summaryLogReq.getEquipmentList().split(","));
                            typeName.addAll(typeNameList);
                            List<String> newTypeNameList = typeNameList.stream().distinct().collect(Collectors.toList());
                            summaryLogReq.setEquipmentList(String.join(",", newTypeNameList));
                            orderLogReqMap.put(infoDto.getOrderId(),summaryLogReq);
                        }
                    }
                }
            }


//          处理单据调用接口
            if (!orderMainReqMap.isEmpty()){
                List<OrderReq> orderReqs = new ArrayList<>(orderMainReqMap.values());
                for (OrderReq orderReq: orderReqs) {
                    OutInLogsReq outInLogsReq = new OutInLogsReq();
                    outInLogsReq.setOrder(orderReq);
                    logSummaryService.processInventoryRecords(outInLogsReq);
                }
            }

            //处理出入库记录接口
            if (!orderLogReqMap.isEmpty()){
                List<SummaryLogReq> summaryLogReqs = new ArrayList<>(orderLogReqMap.values());
                for (SummaryLogReq logSummary: summaryLogReqs) {
                    OutInLogsReq outInLogsReq = new OutInLogsReq();
                    List<SummaryLogReq> logReqList=new ArrayList<>();
                    logReqList.add(logSummary);
                    outInLogsReq.setLogList(logReqList);
                    logSummaryService.processInventoryRecords(outInLogsReq);
                }


            }

            printEpcsService.updateBatchById(list);
        }




        return true;
    }


    //获取更新orderDetail 以及装备信息
    public Map<String,Object> createDetailInvInfo(Map<String,Object> valueMap,List<PrintEpcs> printEpcsList,
                                                  List<DetailOrderReq> detailList,DetailOrderReq detailOrderReq,
                                                  OrderInfoDto infoDto,InventoryBoxMark newBoxMark){

        List<DetailJsonReq> detailJsonReqList=new ArrayList<>();
        Map<BigDecimal,DetailJsonReq> priceMap=new HashMap<>();
        for (PrintEpcs printEpcs:printEpcsList){
            if (priceMap.containsKey(printEpcs.getPrice())){
                DetailJsonReq detailJsonReq = priceMap.get(printEpcs.getPrice());
                detailJsonReq.setNum(detailJsonReq.getNum()+1);
                priceMap.put(printEpcs.getPrice(),detailJsonReq);
            }else {
                DetailJsonReq detailJsonReq = new DetailJsonReq(infoDto.getWarehouseId(),
                        infoDto.getWarehouseName(), infoDto.getTypeId(), infoDto.getTypeName(),
                        infoDto.getSizeId(), infoDto.getSizeName(),printEpcs.getPrice(), 0, 1);
                priceMap.put(printEpcs.getPrice(),detailJsonReq);
            }
        }

        if (ObjectUtil.isNotEmpty(infoDto.getDetailJson())){
            List<DetailJsonReq> detailJsonReqList1 = JSONObject.parseArray(infoDto.getDetailJson(), DetailJsonReq.class);
            for (DetailJsonReq detail:detailJsonReqList1){
                DetailJsonReq detailJsonReq = priceMap.get(detail.getPrice());
                if (ObjectUtil.isNotNull(detailJsonReq)){
                    detail.setNum(detail.getNum()+detailJsonReq.getNum());
                    priceMap.remove(detail.getPrice());
                }
            }
            detailJsonReqList.addAll(detailJsonReqList1);
            if (!priceMap.isEmpty()){
                detailJsonReqList.addAll(new ArrayList<>(priceMap.values()));
            }
        }else {

            detailJsonReqList.addAll(new ArrayList<>(priceMap.values()));
        }
        detailOrderReq.setDetailJson(detailJsonReqList);
        detailList.add(detailOrderReq);



        List<PurchaseEqsReq> collect = printEpcsList.stream().map(printEpcs -> {
            PurchaseEqsReq purchaseEqsReq = new PurchaseEqsReq();
            purchaseEqsReq.setPrice(printEpcs.getPrice());
            purchaseEqsReq.setEpc(printEpcs.getEpc());
            purchaseEqsReq.setEpcType(0);
            purchaseEqsReq.setProperty(0);
            purchaseEqsReq.setTypeId(infoDto.getTypeId());
            purchaseEqsReq.setTypeName(infoDto.getTypeName());
            purchaseEqsReq.setSizeId(infoDto.getSizeId());
            purchaseEqsReq.setSizeName(infoDto.getSizeName());
            purchaseEqsReq.setProductionDate(DateTimeUtil.TimeDateToString(printEpcs.getProductTime(), "yyyy-MM-dd HH:mm:ss"));
            purchaseEqsReq.setWarrantyPeriod(printEpcs.getWarrantyCycle());
            purchaseEqsReq.setMaintenancePeriod(printEpcs.getRepairCycle());
            purchaseEqsReq.setEquipmentType(0);
            purchaseEqsReq.setShelfId(printEpcs.getShelfId());
            purchaseEqsReq.setShelfColumn(printEpcs.getShelfColumn());
            purchaseEqsReq.setShelfRow(printEpcs.getShelfRow());
            purchaseEqsReq.setShelfRange(printEpcs.getShelfRange());
            purchaseEqsReq.setSupplierId(printEpcs.getSupplierId());
            purchaseEqsReq.setSupplierName(printEpcs.getSupplierName());
            purchaseEqsReq.setBoxMarkId(newBoxMark.getId());
            purchaseEqsReq.setLocationId(infoDto.getWarehouseId());
            purchaseEqsReq.setLocationName(infoDto.getWarehouseName());
            purchaseEqsReq.setInstantiationState(1);
            return purchaseEqsReq;
        }).collect(Collectors.toList());

        valueMap.put("detailList",detailList);
        valueMap.put("collect",collect);
        return valueMap;
    }



    //设置日志详情汇总
    public Map<String,Object> createLogDetailList(Map<String,Object> valueMap,List<PrintEpcs> printEpcsList,OrderInfoDto infoDto,Map<String,List<Inventory>> orderInvMap,List<String> typeNameList){

        List<DetailLogReq> collect = printEpcsList.stream().map(printEpcs -> {
            DetailLogReq detailLogReq = new DetailLogReq();
            detailLogReq.setEpc(printEpcs.getEpc());
            detailLogReq.setProperty(0);
            detailLogReq.setPrice(printEpcs.getPrice());
            detailLogReq.setSizeId(printEpcs.getSizeId());
            detailLogReq.setSizeName(printEpcs.getSizeName());
            detailLogReq.setTypeId(printEpcs.getTypeName());
            detailLogReq.setTypeName(printEpcs.getTypeName());
            detailLogReq.setSupplierId(printEpcs.getSupplierId());
            detailLogReq.setSupplierName(printEpcs.getSupplierName());
            detailLogReq.setErrorState(0);
            return detailLogReq;
        }).collect(Collectors.toList());

        List<Inventory> inventoryList = orderInvMap.get(infoDto.getOrderId());
        if (CollectionUtil.isNotEmpty(inventoryList)){
            List<DetailLogReq> beanList = BeanPlusUtil.toBeanList(inventoryList, DetailLogReq.class);

            collect.addAll(beanList);
        }
        collect.forEach(detailLogReq -> {
            if (!typeNameList.contains(detailLogReq.getTypeName()))
                typeNameList.add(detailLogReq.getTypeName());
        });
        valueMap.put("collect",collect);
        valueMap.put("typeNameList",typeNameList);
        return valueMap;
    }

    /**
     * 生成打印入库信息(打印程序内部使用）
     * @param req
     * @return
     */
    @Override
    public Boolean GenerateInventoryWithProgram(GenerateInvWithProgramReq req) {

        if (ObjectUtil.isEmpty(req.getSizeId()) || ObjectUtil.isEmpty(req.getEquId()) ||
                ObjectUtil.isEmpty(req.getEpc()) || ObjectUtil.isEmpty(req.getSupplierId()) ||
                ObjectUtil.isEmpty(req.getWarehouseId()) || ObjectUtil.isNull(req.getWarrantyCycle()) ||
                ObjectUtil.isNull(req.getRepairCycle())){
            throw new JYZBAppException(JyzbV2ExceptionEnum.PARAM_ERROR);
        }
        Boolean result=false;
        if (req.getIsUnboxingLabel()){
            Inventory one = inventoryService.getOne(new LambdaQueryWrapper<Inventory>()
                    .eq(Inventory::getEpc, req.getEpc())
                    .isNotNull(Inventory::getOrgId));

            if (ObjectUtil.isNull(one)){
                throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_INV_ERROR,"物资异常");
            }
            one.setInstantiationState(2);
            result = inventoryService.updateById(one);
        }else {
            //判断库存中是否有装备数据
            Inventory one = inventoryService.getOne(new LambdaQueryWrapper<Inventory>()
                    .eq(Inventory::getEpc, req.getEpc()));
            if (ObjectUtil.isNotNull(one)){
                throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_INV_ERROR,"生成库存失败，库存内已存在此EPC");
            }
            Warehouse warehouse = warehouseService.WarehoustExist(req.getWarehouseId());
            List<Inventory> addInvList=new ArrayList<>();
            Inventory inventoryInfo = createInventoryInfo(null, warehouse.getId(), req.getEquId(), req.getSizeId(), warehouse.getOrgIdInt(),
                    req.getProductTime(), req.getRepairCycle(), req.getWarrantyCycle(), req.getEpc(), req.getSupplierId(),
                    req.getShelfId(), req.getShelfColumn(), req.getShelfRange(), req.getShelfRow(), 2, null);
            addInvList.add(inventoryInfo);
            inventoryService.saveBatch(addInvList);
            addInvList = inventoryMapper.getInvNamesByEpcs(addInvList.stream().map(Inventory::getEpc).collect(Collectors.toList()));
            List<WarehouseInventory> addWareInvList = createWareInvList(addInvList);
            if (CollectionUtil.isNotEmpty(addWareInvList)){
                warehouseInventoryService.saveBatch(addWareInvList);
            }
            result = addInvAndSumInfo(addInvList);
        }
        return result;
    }


    /**
     * 生成打印入库信息(多个epc,箱标限定）
     * @param req
     * @return
     */
    @Override
    @Transactional
    public Boolean GenerateRangeInventory(GenerateRangeInvReq req) {
        Warehouse warehouse = warehouseService.WarehoustExist(req.getWarehouseId());
        List<String> epcList = JSONArray.parseArray(req.getEpcListJson(), String.class);
        if (req.getIsReloadBoxing()){
            InventoryBoxMark boxMark = inventoryBoxMarkService.getOne(new LambdaQueryWrapper<InventoryBoxMark>()
                    .eq(InventoryBoxMark::getEpc, req.getEpc()));
            if (ObjectUtil.isNull(boxMark)){
                throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"无效箱标");
            }
            if (boxMark.getReloadBoxingState() != 1){
                List<String> collect = inventoryService.list(new LambdaQueryWrapper<Inventory>()
                        .eq(Inventory::getBoxMarkId, boxMark.getId())).stream().map(Inventory::getEpc).collect(Collectors.toList());

                if (!epcList.equals(collect)){
                    throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"箱标已打印，但物资不匹配");
                }else {
                    throw new JYZBAppException(CabinetV2ExceptionEnum.GENERATE_EPC_ERROR,"箱标重复打印,清除任务");
                }
            }
            boxMark.setReloadBoxingState(2);
            inventoryBoxMarkService.updateById(boxMark);
            return true;
        }
        if (CollectionUtil.isNotEmpty(epcList)){
            List<Inventory> list = inventoryService.list(new LambdaQueryWrapper<Inventory>().in(Inventory::getEpc, epcList));
            if (CollectionUtil.isNotEmpty(list)){
                List<String> collect = list.stream().map(Inventory::getEpc).collect(Collectors.toList());
                String joinEpc = String.join(",", collect);
                throw new JYZBAppException(CabinetV2ExceptionEnum.BOXING_INVENTORY_ERROR,"生成库存失败，库存内已存在此EPC"+joinEpc);
            }
        }
        InventoryBoxMark newBoxMark = createBoxMark(req.getEpc(), null, epcList.size(), req.getEquId(), req.getSizeId(), req.getSupplierId(),
                req.getWarehouseId(), 0, null);
        inventoryBoxMarkService.save(newBoxMark);
        //创建实体物资入库，并且新增库存汇总信息
        List<Inventory> addInvList=new ArrayList<>();
        for (String epc:epcList){
            Inventory inventoryInfo = createInventoryInfo(newBoxMark.getId(), warehouse.getId(), req.getEquId(),
                    req.getSizeId(), warehouse.getOrgIdInt(), req.getProductTime(), req.getRepairCycle(),
                    req.getWarrantyCycle(), epc, req.getSupplierId(), req.getShelfId(), req.getShelfColumn(),
                    req.getShelfRange(), req.getShelfRow(), 1, 1);
            addInvList.add(inventoryInfo);
        }
        inventoryService.saveBatch(addInvList);
        addInvList = inventoryMapper.getInvNamesByEpcs(epcList);
        List<WarehouseInventory> addWareInvList = createWareInvList(addInvList);
        if (CollectionUtil.isNotEmpty(addWareInvList)){
            warehouseInventoryService.saveBatch(addWareInvList);
        }
        addInvAndSumInfo(addInvList);
        return true;
    }

    /**
     * 更新EPC打印状态
     * @param req
     * @return
     */
    @Override
    @Transactional
    public Boolean UpdateEpcState(UpdateEpcStateReq req) {

        //前提先判断单子是否记账，如果完成记账，那么不管之后有多少新的标签，都不进行上传redis
        //如果是采购自动入库，那么存入redis中去，将orderMain的实际数量进行增加，将orderDetail的实际数量也进行增加

        //获取打印epc信息
        if (ObjectUtil.isEmpty(req.getId())){
            throw new JYZBAppException(JyzbV2ExceptionEnum.ID_ERROR);
        }
        PrintEpcs printEpcs = printEpcsService.getById(req.getId());
        if (ObjectUtil.isNull(printEpcs)){
            throw new JYZBAppException(JyzbV2ExceptionEnum.PRINTEPCS_ERROR);
        }
        //获取子单据信息
        OrderDetail orderDetail = orderDetailService.getById(printEpcs.getOrderDetailId());
        if (ObjectUtil.isNull(printEpcs)){
            throw new JYZBAppException(JyzbV2ExceptionEnum.ORDERDETAIL_ERROR);
        }
        //获取主单局信息
        OrderMain orderMain = orderMainService.orderMainExist(orderDetail.getOrderId());
        if (ObjectUtil.isNotNull(orderMain.getManualState()) && orderMain.getManualState()==1){
            throw new JYZBAppException(JyzbV2ExceptionEnum.ORDERMAIN_ERROR);
        }


        if (ObjectUtil.isNotNull(printEpcs)){
            printEpcs.setCurrentState(1);
            printEpcs.setTid(req.getTid());
            boolean updateResult = printEpcsService.updateById(printEpcs);
            if (updateResult && ObjectUtil.isNotNull(req.getIsDirectEntryStock()) && req.getIsDirectEntryStock()){

                orderMain.setActualQuantity(ObjectUtil.isNull(orderMain.getActualQuantity())?1:orderMain.getActualQuantity()+1);
                orderDetail.setActualNum(ObjectUtil.isNull(orderDetail.getActualNum())?1:orderDetail.getActualNum()+1);
                orderDetail.setModifyQuantity(ObjectUtil.isNull(orderDetail.getModifyQuantity())?1:orderDetail.getModifyQuantity()+1);
                List<DetailJsonReq> list=new ArrayList<>();
                if (ObjectUtil.isNotEmpty(orderDetail.getDetailJson())){
                    List<DetailJsonReq> detailJsonReqList = JSONObject.parseArray(orderDetail.getDetailJson(), DetailJsonReq.class);
                    for (DetailJsonReq detailJsonReq:detailJsonReqList){
                        if (detailJsonReq.getPrice().compareTo(printEpcs.getPrice())==0){
                            detailJsonReq.setNum(detailJsonReq.getNum()+1);
                            detailJsonReq.setModifyQuantity(detailJsonReq.getModifyQuantity()+1);
                        }else {
                            DetailJsonReq one = new DetailJsonReq();
                            one.setLocationId(orderDetail.getWarehouseId());
                            one.setLocationName(orderDetail.getWarehouseName());
                            one.setNum(1);
                            one.setModifyQuantity(1);
                            one.setPrice(printEpcs.getPrice());
                            one.setTypeName(orderDetail.getTypeName());
                            one.setSizeName(orderDetail.getSizeName());
                            one.setProperty(0);
                            one.setSizeId(orderDetail.getSizeId());
                            one.setTypeId(orderDetail.getTypeId());
                            list.add(one);
                        }
                    }
                    list.addAll(detailJsonReqList);
                    orderDetail.setDetailJson(JSONObject.toJSONString(list));
                }else {
                    DetailJsonReq detailJsonReq = new DetailJsonReq();
                    detailJsonReq.setLocationId(orderDetail.getWarehouseId());
                    detailJsonReq.setLocationName(orderDetail.getWarehouseName());
                    detailJsonReq.setNum(1);
                    detailJsonReq.setModifyQuantity(1);
                    detailJsonReq.setPrice(printEpcs.getPrice());
                    detailJsonReq.setProperty(0);
                    detailJsonReq.setTypeName(orderDetail.getTypeName());
                    detailJsonReq.setSizeName(orderDetail.getSizeName());
                    detailJsonReq.setSizeId(orderDetail.getSizeId());
                    detailJsonReq.setTypeId(orderDetail.getTypeId());
                    list.add(detailJsonReq);
                }
                orderDetail.setDetailJson(JSONObject.toJSONString(list));
               //生成信息存储到redis中
                //从redis中获取
                List<Inventory> addInvList=new ArrayList<>();
                List<WarehouseInventory> addWareInvList=new ArrayList<>();

                List<Inventory> inventoryList = outInRecordRedisCache.addInventory("addInvRecord:"+orderMain.getId());
                if (CollectionUtil.isNotEmpty(inventoryList)){
                    addInvList.addAll(inventoryList);
                }

                List<WarehouseInventory> wareInventoryList = outInRecordRedisCache.addWareInventory("addInvWareRecord:"+orderMain.getId());
                if (CollectionUtil.isNotEmpty(wareInventoryList)){
                    addWareInvList.addAll(wareInventoryList);
                }

                WarehouseInventory warehouseInventory = new WarehouseInventory();
                warehouseInventory.setLocationState("in");
                warehouseInventory.setLocationType("0");
                warehouseInventory.setTypeId(orderDetail.getTypeId());
                warehouseInventory.setTypeName(orderDetail.getTypeName());
                warehouseInventory.setSizeId(orderDetail.getSizeId());
                warehouseInventory.setSizeName(orderDetail.getSizeName());
                warehouseInventory.setLocationId(orderDetail.getWarehouseId());
                warehouseInventory.setLocationName(orderDetail.getWarehouseName());
                warehouseInventory.setEpc(printEpcs.getEpc());
                warehouseInventory.setOrgId(orderMain.getEndOrgId());
                warehouseInventory.setOrgName(orderMain.getEndOrgName());
                warehouseInventory.setFlag(0);
                warehouseInventory.setEpcType(0);
                warehouseInventory.setShelfId(printEpcs.getShelfId());
                if (ObjectUtil.isNotNull(printEpcs.getShelfRow())&& ObjectUtil.isNotNull(printEpcs.getShelfColumn()) && ObjectUtil.isNotNull(printEpcs.getShelfRange())){
                    String shelfLocation= printEpcs.getShelfRow()+"/"+printEpcs.getShelfColumn()+"/"+printEpcs.getShelfRange();
                    warehouseInventory.setShelfLocation(shelfLocation);
                }
                warehouseInventory.setCreateTime(DateTimeUtil.getCurrentDateTime());
                warehouseInventory.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                addWareInvList.add(warehouseInventory);


                Inventory inventory = new Inventory();
                if (ObjectUtil.isNotNull(printEpcs.getProductTime())){
                    inventory.setProductionDate(printEpcs.getProductTime());
                }
                inventory.setEpc(printEpcs.getEpc());
                inventory.setTypeId(orderDetail.getTypeId());
                inventory.setSizeId(orderDetail.getSizeId());
                inventory.setEpcType(0);
                inventory.setMaintenancePeriod(printEpcs.getRepairCycle());
                inventory.setWarrantyPeriod(printEpcs.getWarrantyCycle());
                inventory.setProperty(0);
                inventory.setLocationId(orderDetail.getWarehouseId());
                inventory.setSupplierId(printEpcs.getSupplierId());
                inventory.setPrice(printEpcs.getPrice());
                inventory.setId(UUID.randomUUID().toString());
                inventory.setCreateTime(DateTimeUtil.getCurrentDateTime());
                inventory.setState("normal");
                inventory.setBussinessState("normal");
                inventory.setLocationState("in");
                inventory.setLocationType(0);
                inventory.setInstantiationState(2);//已打印或已绑定
                inventory.setShelfId(printEpcs.getShelfId());
                if (ObjectUtil.isNotNull(printEpcs.getShelfRow())&& ObjectUtil.isNotNull(printEpcs.getShelfColumn()) && ObjectUtil.isNotNull(printEpcs.getShelfRange())){
                    String shelfLocation= printEpcs.getShelfRow()+"/"+printEpcs.getShelfColumn()+"/"+printEpcs.getShelfRange();
                    inventory.setShelfLocation(shelfLocation);
                }
                inventory.setOrgId(orderMain.getEndOrgId());
                addInvList.add(inventory);



                //获取采购物资，获取出入库日志
                //获取之后在进行存储
                List<Object> dataByTimestampRange = outInRecordRedisCache.getDataByTimestampRange(orderMain.getId());
                List<LogSummaryReq> beanList = BeanPlusUtil.toBeanList(dataByTimestampRange, LogSummaryReq.class);
                LogSummaryReq logSummaryReq =new LogSummaryReq();
                if (CollectionUtil.isNotEmpty(beanList)){
                    logSummaryReq = beanList.get(0);
                    logSummaryReq.setNumber(logSummaryReq.getNumber()+1);
                    logSummaryReq.setPrice(ObjectUtil.isNull(logSummaryReq.getPrice())?printEpcs.getPrice():logSummaryReq.getPrice().add(printEpcs.getPrice()));
                    String equipmentList = logSummaryReq.getEquipmentList();
                    List<String> typeNameList = new ArrayList<>(Arrays.asList(equipmentList.split(",")));
                    if (CollectionUtil.isNotEmpty(typeNameList)) {
                        if (orderDetail.getTypeName() != null && !typeNameList.contains(orderDetail.getTypeName())) {
                            typeNameList.add(orderDetail.getTypeName());
                        }
                    } else {
                        if (orderDetail.getTypeName() != null) {
                            typeNameList.add(orderDetail.getTypeName());
                        }
                    }
                    logSummaryReq.setEquipmentList(String.join(",", typeNameList));



                }else {

                    logSummaryReq.setOrderMainId(orderMain.getId());
                    logSummaryReq.setOrderCode(orderMain.getOrderCode());
                    logSummaryReq.setOrgId(orderMain.getEndOrgId());
                    logSummaryReq.setOrgName(orderMain.getEndOrgName());
                    logSummaryReq.setLocationId(orderDetail.getWarehouseId());
                    logSummaryReq.setLocationName(orderDetail.getWarehouseName());
                    logSummaryReq.setUserName(orderMain.getEndOrgUserName());
                    logSummaryReq.setUseTime(new Date());
                    logSummaryReq.setEquipmentList(orderDetail.getTypeName());
                    logSummaryReq.setBussinessType("purchase");
                    logSummaryReq.setDeviceType(5);
                    logSummaryReq.setDevice("打印机");
                    logSummaryReq.setLocationType("0");
                    logSummaryReq.setOutInState("in");
                    logSummaryReq.setNumber(1);
                    logSummaryReq.setCreateTime(DateTimeUtil.getCurrentDateTime());
                    logSummaryReq.setPrice(printEpcs.getPrice());

//                    LogSummary logSummary = new LogSummary();
//                    BeanPlusUtil.copyProperties(logSummaryReq,logSummary);
//                    String string=logSummary.getLocationName()+"：入库【"+logSummary.getEquipmentList()+"】，数量："+logSummary.getNumber()+"\n";
//                    OrderLog orderLog = addLog(logSummary,string);
//                    OrderLogReq orderLogReq = new OrderLogReq();
//                    BeanPlusUtil.copyProperties(orderLog,orderLogReq);
//                    List<OrderLogReq> orderLogReqList=new ArrayList<>();
//                    orderLogReqList.add(orderLogReq);
//                    logSummaryReq.setOrderLogList(orderLogReqList);


                }
                List<LogDetailReq> logList = logSummaryReq.getLogList();
                //存放logdetail信息
                LogDetail logDetail = new LogDetail();
                logDetail.setEpc(printEpcs.getEpc());
                logDetail.setTypeId(orderDetail.getTypeId());
                logDetail.setTypeName(orderDetail.getTypeName());
                logDetail.setSizeId(orderDetail.getSizeId());
                logDetail.setSizeName(orderDetail.getSizeName());
                logDetail.setSupplierId(printEpcs.getSupplierId());
                logDetail.setSupplierName(printEpcs.getSupplierName());
                logDetail.setErrorState(0);
                logDetail.setProperty(0);
                logDetail.setPrice(printEpcs.getPrice());
                logDetail.setCreateTime(DateTimeUtil.getCurrentDateTime());
                logDetail.setBussinessType("purchase");
                logDetail.setOutInState("in");
                logDetail.setOrgId(orderMain.getEndOrgId());
                LogDetailReq logDetailReq = new LogDetailReq();
                BeanPlusUtil.copyProperties(logDetail,logDetailReq);
                if (CollectionUtil.isEmpty(logList)){
                    logList=new ArrayList<>();
                    logList.add(logDetailReq);
                }else {
                    logList.add(logDetailReq);
                }
                logSummaryReq.setLogList(logList);

                outInRecordRedisCache.addRecord(orderMain.getId(),logSummaryReq,DateTimeUtil.TimeDateToLong(new Date()));
                //将新增装备存入redis中，在记账的时候取出来直接进行记账
                outInRecordRedisCache.addInvRecord(orderMain.getId(),addInvList,DateTimeUtil.TimeDateToLong(DateTimeUtil.getCurrentDateTime()));
                outInRecordRedisCache.addInvWareRecord(orderMain.getId(),addWareInvList,DateTimeUtil.TimeDateToLong(DateTimeUtil.getCurrentDateTime()));

                orderMainService.updateById(orderMain);
                orderDetailService.updateById(orderDetail);
                printEpcsService.updateById(printEpcs);
            }
        }
        return true;
    }


    private OrderLog addLog(LogSummary logSummary,String string){
        OrderLog orderLog = new OrderLog();
        orderLog.setId(UUID.randomUUID().toString());
        orderLog.setHistoryMsg(string);
        orderLog.setOrderCode(logSummary.getOrderCode());
        orderLog.setBussinessType(logSummary.getBussinessType());
        orderLog.setOrderType(logSummary.getOutInState());
        orderLog.setProcessType("OutAndIn");
        orderLog.setOrgId(logSummary.getOrgId());
        orderLog.setOrgName(logSummary.getOrgName());
        orderLog.setOrderId(logSummary.getOrderMainId());
        orderLog.setCreateTime(DateTimeUtil.getCurrentDateTime());
        return orderLog;
    }
    /**
     * Rfid数据上报
     * @param req
     * @return
     */
//    @Override
//    public Boolean UploadRFIDNew(UploadRFIDNewReq req) {
//
//        return null;
//    }

    /**
     * 获取全部打印列表
     * @param req
     * @return
     */
    @Override
    public GetPrintListDto GetPrintList(GetPrintListReq req) {

        if (ObjectUtil.isEmpty(req.getOrgId())){
            throw new JYZBAppException(JyzbV2ExceptionEnum.ORGID_ERROR);
        }

        if (ObjectUtil.isNull(req.getEpcType())){
            req.setEpcType(1);
        }
        if (ObjectUtil.isNull(req.getLabelType())){
            req.setLabelType("-1");
        }
        if (ObjectUtil.isNull(req.getSize()) || req.getSize()==0){
            req.setSize(50);
        }
        if (ObjectUtil.isNull(req.getPage()) || req.getPage()==0){
            req.setPage(1);
        }
        //获取箱标
        List<GetPrintListDto.dataList> dataXBList=new ArrayList<>();
        dataXBList=inventoryMapper.getdataXBList(req);


        //获取件标
        List<GetPrintListDto.dataList> dataJBList=new ArrayList<>();
        dataJBList=printEpcsMapper.getdataJBList(req);

        List<GetPrintListDto.dataList> returnList=new ArrayList<>();
        GetPrintListDto getPrintListDto = new GetPrintListDto();
        switch (req.getEpcType()){
            case 0:
                returnList.addAll(dataJBList);
                returnList.addAll(dataXBList);
                break ;
            case 1:
                returnList.addAll(dataJBList);
                break;
            case 2:
                returnList.addAll(dataXBList);
                break ;
            default:
                throw new JYZBAppException(CabinetV2ExceptionEnum.GET_PRINT_LIST_ERROR,"epcType错误");
        }
        if (CollectionUtil.isNotEmpty(returnList)){

            int startIndex = (req.getPage() - 1) * req.getSize();
            int endIndex = Math.min(startIndex + req.getSize(), returnList.size());
            List<GetPrintListDto.dataList> subList = returnList.subList(startIndex,endIndex);
            getPrintListDto.setTotal(returnList.size());
            getPrintListDto.setRecord(subList);
        }else {
            getPrintListDto.setTotal(0);
            getPrintListDto.setRecord(new ArrayList<>());
        }
        return getPrintListDto;
    }


    //获取list1中包含list2的元素数据
    private List<Inventory> countCommonElements(List<Inventory> list1, List<String> list2) {
        if (CollectionUtil.isEmpty(list1) || CollectionUtil.isEmpty(list2)) {
            return null; // 返回0表示没有共同元素
        }

        List<String> collect = list1.stream().map(Inventory::getEpc).collect(Collectors.toList());

        List<Inventory> containList=new ArrayList<>();
        //判断list1中有多少list2 的数据
        for (String element : list2) {
            if (collect.contains(element)) {
                List<Inventory> collect1 = list1.stream().filter(inventory -> inventory.getEpc().equals(element)).collect(Collectors.toList());
                containList.addAll(collect1);
            }
        }
        return containList;
    }


    private InventoryBoxMark createBoxMark(String epc,String oldEpc,Integer oneBoxNum,String typeId,String sizeId,
                                           String supplierId,String warehouseId,Integer currentState,Integer reloadBoxingState){
        InventoryBoxMark inventoryBoxMark = new InventoryBoxMark();
        inventoryBoxMark.setId(UUID.randomUUID().toString());
        inventoryBoxMark.setEpc(epc);
        inventoryBoxMark.setOneBoxNum(oneBoxNum);
        inventoryBoxMark.setCreateTime(DateTimeUtil.getCurrentDateTime());
        inventoryBoxMark.setCurrentState(currentState);
        inventoryBoxMark.setEquipmentDetailId(typeId);
        inventoryBoxMark.setSizeId(sizeId);
        inventoryBoxMark.setReloadBoxingState(reloadBoxingState);
        inventoryBoxMark.setOldEpc(oldEpc);
        inventoryBoxMark.setWarehouseId(warehouseId);
        inventoryBoxMark.setSupplierId(supplierId);
        return inventoryBoxMark;
    }


    private Boolean addInvAndSumInfo(List<Inventory> addInventoryList){
        Map<String,Object[]> invSummaryMap=new HashMap<>();
        for (Inventory inventory:addInventoryList) {
            String key=inventory.getOrgId()+inventory.getLocationId()+inventory.getTypeId()+inventory.getSizeId()+inventory.getPrice()+inventory.getProperty();
            if (!invSummaryMap.containsKey(key)){
                Object[] item=new Object[]{inventory.getOrgId(),inventory.getLocationId(),inventory.getTypeId(),inventory.getSizeId(),inventory.getPrice(),inventory.getProperty(),1,
                        inventory.getTypeName(),inventory.getSizeName(),inventory.getLocationName(),inventory.getOrgName(),inventory.getOrgCode()};
                invSummaryMap.put(key,item);
            }else {
                Object[] searchItem = invSummaryMap.get(key);
                searchItem[6]=(Integer)searchItem[6]+1;
                invSummaryMap.put(key,searchItem);
            }
        }
        List<InventorySummary> invSumList = inventorySummaryMapper.selectSum(new ArrayList<>(invSummaryMap.values()));
        List<InventorySummary> addInvSumList=new ArrayList<>();
        for (Object[] obj:invSummaryMap.values()) {
            boolean flag=false;
            for (InventorySummary is:invSumList) {
                if (obj[2].equals(is.getTypeId())
                        && obj[3].equals(is.getSizeId()) && is.getUnitPrice().compareTo((BigDecimal) obj[4])==0 && obj[5].equals(is.getProperty())){
                    is.setStockNumber(is.getStockNumber()+(Integer) obj[6]);
                    is.setNumber(is.getStockNumber()+(Integer) obj[6]);
                    is.setPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getNumber())));
                    flag=true;
                    break;
                }
            }
            if (!flag){
                //新增
                InventorySummary inventorySummary = inventorySummaryService.createInventorySummary((Long)obj[0],
                        (String)obj[10],(String)obj[11],(String) obj[2],(String) obj[7],(String) obj[3],
                        (String) obj[8],(String)obj[1],(String)obj[9],(Integer) obj[6],0,
                        (BigDecimal) obj[4],0,0,0,0,0,0, 0,"0");
                addInvSumList.add(inventorySummary);
            }
        }
        boolean result1=false;
        boolean result2=false;
        boolean result3=false;
        if (CollectionUtil.isNotEmpty(invSumList)){

            result1=inventorySummaryService.updateBatchById(invSumList);
        }
        if (CollectionUtil.isNotEmpty(addInvSumList)){
            result2=inventorySummaryService.saveBatch(addInvSumList);
        }

        List<WarehouseInventory> addWareInvList = BeanPlusUtil.toBeanList(addInventoryList, WarehouseInventory.class);
        result3=warehouseInventoryService.saveBatch(addWareInvList);
        return result3 && result2 && result1;
    }

    private Inventory createInventoryInfo(String boxMarkId, String warehouseId,String typeId,String sizeId,Long orgId,
                                          Date productTime,Integer repairCycle,Integer warrantyCycle,String epc,String supplierId,
                                          String shelfId,Integer shelfColumn,Integer shelfRange,Integer shelfRow,
                                          Integer instantiationState,Integer isInBox){
        Inventory inventory = new Inventory();
        inventory.setBoxMarkId(boxMarkId);
        inventory.setLocationType(0);
        inventory.setLocationId(warehouseId);
        inventory.setTypeId(typeId);
        inventory.setSizeId(sizeId);
        inventory.setOrgId(orgId);
        inventory.setBussinessState("normal");
        inventory.setState("normal");
        inventory.setLocationState("in");
        inventory.setProductionDate(productTime);
        inventory.setMaintenancePeriod(repairCycle);
        inventory.setWarrantyPeriod(warrantyCycle);
        inventory.setCreateTime(DateTimeUtil.getCurrentDateTime());
        inventory.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        inventory.setCreateUser("internal");
        inventory.setUpdateUser("internal");
        inventory.setEpc(epc);
        inventory.setSupplierId(supplierId);
        inventory.setProperty(0);
        inventory.setShelfId(shelfId);
        inventory.setInstantiationState(instantiationState);
        inventory.setIsInBox(isInBox);
        if (ObjectUtil.isNotNull(shelfColumn) && ObjectUtil.isNotNull(shelfRange) && ObjectUtil.isNotNull(shelfRow)){
            inventory.setShelfLocation(shelfColumn+"/"+shelfRange+"/"+shelfRow);
        }
        return inventory;
    }

    private List<WarehouseInventory> createWareInvList(List<Inventory> invList){
        List<WarehouseInventory> addWareInvList = invList.stream().map(inventory -> {
            WarehouseInventory wareInv = new WarehouseInventory();
            wareInv.setOrgName(inventory.getOrgName());
            wareInv.setOrgId(inventory.getOrgId());
            wareInv.setTypeId(inventory.getTypeId());
            wareInv.setTypeName(inventory.getTypeName());
            wareInv.setSizeId(inventory.getSizeId());
            wareInv.setSizeName(inventory.getSizeName());
            wareInv.setLocationId(inventory.getLocationId());
            wareInv.setLocationName(inventory.getLocationName());
            wareInv.setLocationType(inventory.getLocationType().toString());
            wareInv.setEpc(inventory.getEpc());
            wareInv.setFlag(0);
            wareInv.setCreateTime(new Date());
            wareInv.setUpdateTime(DateTimeUtil.getCurrentDateTime());
            wareInv.setLocationState(inventory.getLocationState());
            wareInv.setShelfId(inventory.getShelfId());
            wareInv.setShelfLocation(inventory.getShelfLocation());
            wareInv.setEpcType(inventory.getEpcType());
            return wareInv;
        }).collect(Collectors.toList());
        return addWareInvList;
    }

}
