package com.junmp.jyzb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.junmp.v2.db.api.page.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.junmp.jyzb.api.bean.dto.InventoryDto;
import com.junmp.jyzb.api.bean.dto.hardWareDto.*;
import com.junmp.jyzb.api.bean.query.InventoryReq;
import com.junmp.jyzb.api.bean.query.PoliceEquipmentDetailReq;
import com.junmp.jyzb.api.bean.query.hardWareReq.*;
import com.junmp.jyzb.api.exception.JYZBAppException;
import com.junmp.jyzb.api.exception.enums.CabinetBoxExceptionEnum;
import com.junmp.jyzb.api.exception.enums.CabinetV2ExceptionEnum;
import com.junmp.jyzb.api.exception.enums.ConfigExceptionEnum;
import com.junmp.jyzb.api.exception.enums.InventoryExceptionEnum;
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.common.exception.base.ServiceException;
import com.junmp.v2.common.util.BeanPlusUtil;
import com.junmp.v2.file.api.bean.req.SysFileInfoReq;
import com.junmp.v2.file.api.bean.res.SysFileInfoResp;
import com.junmp.v2.file.biz.entity.SysFileInfo;
import com.junmp.v2.file.biz.service.SysFileInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class HardWareServiceImpl implements HardWareService {
    @Resource
    private CabinetMapper cabinetMapper;

    @Resource
    private EquipmentTypeMapper equipmentTypeMapper;

    @Resource
    private EquipmentSizeMapper equipmentSizeMapper;

    @Resource
    private SupplierMapper supplierMapper;

    @Resource
    private PolicemanService policemanService;

    @Resource
    private InventoryMapper inventoryMapper;

    @Resource
    private ApplicationService applicationService;

    @Resource
    private PoliceFingerService policeFingerService;

    @Resource
    private CabinetWorklogService cabinetWorklogService;

    @Resource
    private CabinetBoxPoliceService cabinetBoxPoliceService;

    @Resource
    private InventoryService inventoryService;

    @Resource
    private CabinetBoxService cabinetBoxService;

    @Resource
    private CabinetService cabinetService;

    @Resource
    private WarehouseInventoryService warehouseInventoryService;

    @Resource
    private InventorySummaryService inventorySummaryService;

    @Resource
    private InventorySummaryMapper inventorySummaryMapper;
    
    @Resource
    private PubOrgService pubOrgService;

    @Resource
    private LogSummaryService logSummaryService;

    @Resource
    private LogSummaryMapper logSummaryMapper;

    @Resource
    private PoliceEquipmentService policeEquipmentService;

    @Resource
    private PoliceEquipmentDetailService policeEquipmentDetailService;

    @Resource
    private CabinetInvErrorMsgService cabinetInvErrorMsgService;

    @Resource
    private CabinetOutinlogService cabinetOutinlogService;

    @Resource
    private SysFileInfoService sysFileInfoService;

    @Resource
    private WarehouseService warehouseService;

    @Resource
    private LogDetailService logDetailService;


    /**
     * 获取系统时间
     * @return
     */
    @Override
    public Date getServerTime() {
        return DateTimeUtil.getCurrentDateTime();
    }

    /**
     * 获取单警柜警员信息
     * @param req
     * @return
     */
    @Override
    public List<HardCabPoliceDto> getAllPoliceByCabinet(HardWareCabReq req) {
        Cabinet one = cabinetService.getOne(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getDevSn, req.getCabinetNum()));
        if (ObjectUtil.isNull(one)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.CABINET_NOT_REG_EXCEPTION);
        }
        return cabinetMapper.getAllPoliceByCabinet(req,one.getOrgIdInt());
    }

    /**
     * 获取epc信息
     */
    @Override
    public Map<String, String> GetEpcInfo(HardWareCabReq req) {
        List<InventoryDto> epcInfoList=cabinetMapper.GetEpcInfo(req);
        Map<String,String> epcMap=new HashMap<>();
        for (InventoryDto inv: epcInfoList) {
            epcMap.put(inv.getEpc(),inv.getTypeName()+"-"+inv.getSizeName());
        }
        return epcMap;
    }


    /**
     * 获取类型列表
     * @param req
     * @return
     */
    @Override
    public List<TypeDto> getListEquipmentDetail(HardWareCabReq req) {
        //类型id列表
        List<TypeDto> list=equipmentTypeMapper.getListEquipmentDetail(req);
        List<String> collect = list.stream().map(TypeDto::getCode).collect(Collectors.toList());

        //号型id列表
        List<SizeDto> sizeList= CollectionUtil.isNotEmpty(collect) ? equipmentSizeMapper.getSizeList(collect) : new ArrayList<>();
        Map<String,List<SizeDto>> sizeMap=new HashMap<>();
        if (CollectionUtil.isNotEmpty(sizeList)){
            for (SizeDto size:sizeList) {
                if (sizeMap.containsKey(size.getDetailId())){
                    List<SizeDto> sizeDtos = sizeMap.get(size.getDetailId());
                    sizeDtos.add(size);
                    sizeMap.put(size.getDetailId(),sizeDtos);
                }else {
                    List<SizeDto> sizeDtos = new ArrayList<>();
                    sizeDtos.add(size);
                    sizeMap.put(size.getDetailId(),sizeDtos);
                }
            }
        }

        //供应商id列表
        Map<String,List<String>> supplierMap=new HashMap<>();
        if (CollectionUtil.isNotEmpty(collect)){
            List<SupplierDto> supplierList=supplierMapper.getSupplierList(collect);
            if (CollectionUtil.isNotEmpty(supplierList)){
                for (SupplierDto supplier:supplierList) {
                    if (sizeMap.containsKey(supplier.getEquipmentId())){
                        List<String> strings = supplierMap.get(supplier.getEquipmentId());
                        strings.add(supplier.getSupplierCode());
                        supplierMap.put(supplier.getEquipmentId(),strings);
                    }else {
                        List<String> strings = new ArrayList<>();
                        strings.add(supplier.getSupplierCode());
                        supplierMap.put(supplier.getEquipmentId(),strings);
                    }
                }
            }
        }

        for (TypeDto typeDto:list) {
            if (!sizeMap.isEmpty()){
                List<SizeDto> sizeDtos = sizeMap.get(typeDto.getId());
                typeDto.setSizeList(sizeDtos);
            }
            if (!supplierMap.isEmpty()){
                List<String> supplierDtos = supplierMap.get(typeDto.getId());
                typeDto.setSupplierList(supplierDtos);
            }
        }
        return CollectionUtil.isNotEmpty(list)?list:new ArrayList<>();
    }

    /**
     * 获取类型号型列表
     * @param req
     * @return
     */
    @Override
    public List<SizeDto> getListEquipmentSizeNoSign(HardWareCabReq req) {
        List<SizeDto> list=equipmentSizeMapper.getListEquipmentSizeNoSign(req);
        return ObjectUtil.isNotEmpty(list)?list:new ArrayList<>();
    }

    /**
     * 获取警员绑定装备列表
     * @param req
     * @return
     */
    @Override
    public EqsDto getBindEqu(HardWarePoliceReq req) {
        Policeman policeman = policemanService.getById(req.getId());
        if (ObjectUtil.isNull(policeman)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.POLICE_INFO_NOT_EXIT);
        }
        EqsDto eqsDto=cabinetMapper.getCabinetBoxByPoliceId(req);
        if (ObjectUtil.isNotNull(eqsDto)){

            List<EqsDto.EqsInfoDto> list=inventoryMapper.getBindEqu(eqsDto.getCabinetBoxId(),policeman.getId());
            if (CollectionUtil.isNotEmpty(list)){
                Integer number = list.get(0).getNumber();
                eqsDto.setInstoreNum(number);
                for (EqsDto.EqsInfoDto eqsInfoDto:list) {
                    if (policeman.getPoliceCode().equals(policeman.getId())){
                        eqsInfoDto.setSize(eqsInfoDto.getSizeName());
                    }else {
                        eqsInfoDto.setSize(eqsInfoDto.getSizeName()+"("+policeman.getName()+")");
                    }
                }
            }else {
                eqsDto.setInstoreNum(0);
            }
            eqsDto.setEquList(list);
        }
        return eqsDto;
    }


    /**
     * 修改单警柜和警员信息
     * @param req
     * @return
     */
    @Override
    @Transactional
    public Boolean updatePoliceAndCabinet(HardWarePoliceReq req) {
        Policeman policeman = policemanService.PoliceExist(req.getUserId());
        boolean result=true;
        switch (req.getType()){
            case "0"://修改密码
                policeman.setPsd(req.getTypeValue1());
                result=policemanService.updateById(policeman);
                if (!result){
                    throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"修改密码失败");
                }
                break;
            case "1"://修改指纹
                //获取警员的指纹
                List<PoliceFinger> addList=new ArrayList<>();
                List<PoliceFinger> list = policeFingerService.list(new LambdaQueryWrapper<PoliceFinger>()
                        .eq(PoliceFinger::getPoliceId, policeman.getId()));
                if (CollectionUtil.isNotEmpty(list)){
                    if (req.getTypeValue1() != null) {
                        if (req.getTypeValue1().isEmpty()) {
                            policeFingerService.remove(new LambdaQueryWrapper<PoliceFinger>()
                                    .eq(PoliceFinger::getPoliceId, policeman.getId())
                                    .eq(PoliceFinger::getFingerNum, 1));
                        } else {
                            policeFingerService.remove(new LambdaQueryWrapper<PoliceFinger>()
                                    .eq(PoliceFinger::getPoliceId, policeman.getId())
                                    .eq(PoliceFinger::getFingerNum, 1));
                            PoliceFinger policeFinger = addFingerInfo(policeman.getId(), 1, 0, req.getTypeValue1());
                            addList.add(policeFinger);
                        }
                    }
                    if (req.getTypeValue2() != null) {
                        if (req.getTypeValue2().isEmpty()) {
                            policeFingerService.remove(new LambdaQueryWrapper<PoliceFinger>()
                                    .eq(PoliceFinger::getPoliceId, policeman.getId())
                                    .eq(PoliceFinger::getFingerNum, 2));
                        } else {
                            policeFingerService.remove(new LambdaQueryWrapper<PoliceFinger>()
                                    .eq(PoliceFinger::getPoliceId, policeman.getId())
                                    .eq(PoliceFinger::getFingerNum, 2));
                            PoliceFinger policeFinger = addFingerInfo(policeman.getId(), 2, 0, req.getTypeValue2());
                            addList.add(policeFinger);
                        }
                    }
                }else {
                    if (ObjectUtil.isNotEmpty(req.getTypeValue1())){
                        PoliceFinger policeFinger = addFingerInfo(policeman.getId(), 1, 0, req.getTypeValue1());
                        addList.add(policeFinger);
                    }
                    if (ObjectUtil.isNotEmpty(req.getTypeValue2())){
                        PoliceFinger policeFinger = addFingerInfo(policeman.getId(), 2, 0, req.getTypeValue2());
                        addList.add(policeFinger);
                    }
                }
                if (CollectionUtil.isNotEmpty(addList)){
                   result= policeFingerService.saveBatch(addList);
                    if (!result){
                        throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"修改指纹失败");
                    }
                }
//                if (CollectionUtil.isNotEmpty(list)){
//                    result= policeFingerService.updateBatchById(list);
//                    if (!result){
//                        throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"修改指纹失败");
//                    }
//                }
                break;
            case "2"://修改人脸
                policeman.setFaceInfo2(req.getTypeValue1());
                result= policemanService.updateById(policeman);
                if (!result){
                    throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"修改人脸失败");
                }
                break;
            default:
                break;
        }
        return result;
    }


    //添加指纹方法
    private PoliceFinger addFingerInfo(String policeId,Integer fingerNum,Integer type,String fingerInfo){
        PoliceFinger policeFinger = new PoliceFinger();
        policeFinger.setPoliceId(policeId);
        policeFinger.setFingerNum(fingerNum);
        policeFinger.setFingerInfo(fingerInfo);
        policeFinger.setCreateTime(DateTimeUtil.getCurrentDateTime());
        policeFinger.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        policeFinger.setType(type);
        return policeFinger;
    }

    /**获取软件版本更新（2.0）
     * @param req
     * @return
     */
    @Override
    public Application getLastUpdate(HardWarePoliceReq req) {
        //根据appCode获取数据
        Application one = applicationService.getOne(new LambdaQueryWrapper<Application>()
                .eq(Application::getAppCode, req.getAppCode()));
        if (ObjectUtil.isNull(one)){
            throw new ServiceException(ConfigExceptionEnum.SOFT_IS_NOT_EXIST);
        }
        if (one.getAddress().contains("http")){
            // 使用正则表达式匹配地址中的内容
            Pattern pattern = Pattern.compile("http://.*?/(.*)");
            Matcher matcher = pattern.matcher(one.getAddress());

            if (matcher.find()) {
                one.setAddress("/"+matcher.group(1));
            }

        }
        return one;
    }

    /**
     * 根据设备号和版本号获取版本更新内容以及设备号是否需要升级
     * @param req
     * @return
     */
    @Override
    public LastUpAndUpgradeDto GetLastUpdateAndUpgrade(LastUpAndUpgradeReq req) {

        Application one = applicationService.getOne(new LambdaQueryWrapper<Application>()
                .eq(Application::getAppCode, req.getAppCode()));
        if (ObjectUtil.isNull(one)){
            throw new ServiceException(ConfigExceptionEnum.SOFT_IS_NOT_EXIST);
        }
        LastUpAndUpgradeDto lastUpAndUpgradeDto = new LastUpAndUpgradeDto();
        BeanPlusUtil.copyProperties(one,lastUpAndUpgradeDto);
        Cabinet cabinet = cabinetService.CabinetExistByNum(req.getServerNum());
        lastUpAndUpgradeDto.setIsUpgrade(cabinet.getIsUpgrade());
        return lastUpAndUpgradeDto;
    }

    /**库存
     * @param req
     * @return
     */
    @Override
    public InvCabDto inventoryCabinet(HardWareCabReq req) {
        InvCabDto invCabDto = new InvCabDto();
        //根据主柜号获取装备的在库总数
        int size=inventoryMapper.getInvCountByCab(req);
        invCabDto.setTotalCount(String.valueOf(size));
        List<InvCabDto.InvDto> list=inventoryMapper.getInvByCab(req.getCabinetNum(),req.getType());
        invCabDto.setTotalElements(String.valueOf(list.size()));
        invCabDto.setContent(list);
        return invCabDto;
    }


    /**上报单警柜操作日志
     * @param req
     * @return
     */
    @Override
    public Boolean addWorklog(HardWareCabReq req) {
        List<CabinetWorklog> addList=new ArrayList<>();
        if (CollectionUtil.isNotEmpty(req.getLogList())){
            for (HardWareCabReq.WorkLogReq workLogReq:req.getLogList()) {
                CabinetWorklog cabinetWorklog = new CabinetWorklog();
                cabinetWorklog.setDate(ObjectUtil.isNotEmpty(workLogReq.getDate())
                        ? DateTimeUtil.TimeStringToDate(workLogReq.getDate(),"yyyy/MM/dd HH:mm:ss")
                        : DateTimeUtil.getCurrentDateTime());
                cabinetWorklog.setId(UUID.randomUUID().toString());
                cabinetWorklog.setIsDeal(workLogReq.getIsDeal());
                cabinetWorklog.setName(workLogReq.getName());
                cabinetWorklog.setPhoto(workLogReq.getPhoto());
                cabinetWorklog.setType(workLogReq.getType());
                cabinetWorklog.setDeviceNo(req.getCabinetMainNo());
                cabinetWorklog.setLogInfo(workLogReq.getLogInfo());
                addList.add(cabinetWorklog);
            }
        }
        if (CollectionUtil.isNotEmpty(addList)){
            cabinetWorklogService.saveBatch(addList);
        }
        return true;
    }

    /**
     * 获取公共柜下绑定的警员信息（公共柜使用）
     * @param req
     * @return
     */
    @Override
    public List<GetCabinetPolicemanMultipleDto> getCabinetPolicemanMultiple(HardWareCabReq req) {
        if (ObjectUtil.isNotEmpty(req.getCabinetRealID())){
            List<GetCabinetPolicemanMultipleDto> list = cabinetMapper.getCabinetPolicemanMultiple(req);
            return ObjectUtil.isNotEmpty(list)?list:new ArrayList<>();
        }else {
           return new ArrayList<>();
        }

    }


    /**
     * 用户箱门绑定（公共柜）
     * @param req
     * @return
     */
    @Override
    @Transactional
    public Boolean addPoliceAndCabinetMutiple(HardWareCabReq req) {
        //查询单警柜下面所有的公共柜id存入
        List<CabinetBox> boxList= cabinetMapper.getBoxList(req.getCabinetRealID(), 2);
        Map<String,String> boxMap=new HashMap<>();
        for (CabinetBox cabinetBox:boxList) {
            String key=cabinetBox.getBoxNo().toString();
             if (!boxMap.containsKey(key)){
                 boxMap.put(key,cabinetBox.getId());
             }
        }
        if (ObjectUtil.isEmpty(req.getUserId()) && ObjectUtil.isEmpty(req.getBoxNo())){
            throw new ServiceException(CabinetBoxExceptionEnum.CABINETBOX_PARAM_REQUIRE);
        }
        if (ObjectUtil.isNotEmpty(req.getUserId())){
            //清空userId下的公共柜人员绑定信息
            List<CabinetBoxPolice> delList=cabinetMapper.getBoxBindUserList(req.getCabinetRealID(), req.getUserId(),req.getBoxNo(),2);
            cabinetBoxPoliceService.removeBatchByIds(delList);

        }else {
            //清空boxNo下的公共柜人员绑定信息
            List<CabinetBoxPolice> delList=cabinetMapper.getBoxBindUserList(req.getCabinetRealID(), req.getUserId(),req.getBoxNo(),2);
            cabinetBoxPoliceService.removeBatchByIds(delList);
        }
        List<CabinetBoxPolice> addList=new ArrayList<>();
        if (CollectionUtil.isNotEmpty(req.getList())){
            for (HardWareCabReq.BoxUserReq boxUserReq : req.getList()) {
                CabinetBoxPolice cabinetBoxPolice = new CabinetBoxPolice();
                cabinetBoxPolice.setPoliceId(boxUserReq.getUserId());
                if (boxMap.get(boxUserReq.getBoxNo())== null){
                    throw new ServiceException(CabinetBoxExceptionEnum.CABINETBOX_TYPR_ERROR);
                }
                cabinetBoxPolice.setCabinetBoxId(boxMap.get(boxUserReq.getBoxNo()));
                cabinetBoxPolice.setCreateTime(DateTimeUtil.getCurrentDateTime());
                cabinetBoxPolice.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                addList.add(cabinetBoxPolice);
            }
        }
        if (CollectionUtil.isNotEmpty(addList)){
            cabinetBoxPoliceService.saveBatch(addList);
        }
        return true;
    }

    /**
     * 绑定单警柜和警员信息
     * @param req
     * @return
     */
    @Override
    @Transactional
    public Boolean AddPoliceAndCabinet(HardWarePoliceReq req) {
        Policeman policeman = policemanService.getById(req.getUserId());
        if (ObjectUtil.isNull(policeman)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"警员信息不存在");
        }
        String cabinetBoxId="";
        //根据单警柜编码获取单警柜信息
        Cabinet cabinet = cabinetService.getOne(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getDevSn,req.getCabinetRealID()));
        if (ObjectUtil.isNull(cabinet)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"主柜信息不存在");
        }
        CabinetBox one = cabinetBoxService.getOne(new LambdaQueryWrapper<CabinetBox>().eq(CabinetBox::getCabinetId, cabinet.getId()).eq(CabinetBox::getBoxNo, req.getCabinetChildID()));
        //判断该警员是否绑定单警柜，判断该箱门下面是否有在柜装备，如果有绑定失败
        List<CabinetBoxPolice> boxList = cabinetMapper.getBoxBindUserList(req.getCabinetRealID(), req.getUserId(),"", 1);
        boolean result=true;
        if (CollectionUtil.isNotEmpty(boxList)){
            //获取箱门中在柜数（如果在柜报错，如果出柜直接解绑）
            Set<String> locationIdList=boxList.stream().map(CabinetBoxPolice::getCabinetBoxId).collect(Collectors.toSet());
            CabinetBoxPolice cabinetBoxPolice = boxList.get(0);

            InventorySummary invSum=inventoryMapper.getSumByLocationIdList(locationIdList);
            if (ObjectUtil.isNotNull(invSum)){

                if (invSum.getStockNumber()>0){
                    throw new JYZBAppException(CabinetV2ExceptionEnum.CABINETBOX_UNBIND_ERROR);
                }
                if (invSum.getOutboundNumber()>0){
                    result=inventoryService.update(new LambdaUpdateWrapper<Inventory>().set(Inventory::getEqsBindState,0)
                            .in(Inventory::getLocationId,locationIdList));
                    if (!result){
                        throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"装备解绑失败");
                    }
                }

            }
            if (!cabinetBoxPolice.getCabinetBoxId().equals(one.getId())){
                cabinetBoxPolice.setCabinetBoxId(one.getId());
                cabinetBoxPoliceService.updateById(cabinetBoxPolice);
            }
        }else {
            List<CabinetBox> boxList1 = cabinetMapper.getBoxList(req.getCabinetRealID(), 1);
            List<CabinetBox> addBoxList=new ArrayList<>();
            if (CollectionUtil.isNotEmpty(boxList1)){
                Integer boxNo = boxList1.get(0).getBoxNo();
                for (int i = boxNo; i < req.getCabinetChildID(); i++){
                    CabinetBox cabinetBox = new CabinetBox();
                    String boxId=UUID.randomUUID().toString();
                    cabinetBox.setId(boxId);
                    cabinetBox.setCabinetId(cabinet.getId());
                    cabinetBox.setBoxNo(i+1);
                    cabinetBox.setBoxName((i+1)+"号箱门");
                    cabinetBox.setContainType(1);
                    cabinetBox.setCreateTime(DateTimeUtil.getCurrentDateTime());
                    cabinetBox.setUpdateTime(DateTimeUtil.getCurrentDateTime());
                    addBoxList.add(cabinetBox);
                    if ((i+1)== req.getCabinetChildID()){
                        cabinetBoxId=boxId;
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(addBoxList)){
                result=cabinetBoxService.saveBatch(addBoxList);
                if (!result){
                    throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"新增箱门失败");
                }
            }
            CabinetBoxPolice cabinetBoxPolice = new CabinetBoxPolice();
            cabinetBoxPolice.setCabinetBoxId(ObjectUtil.isEmpty(cabinetBoxId)?one.getId():cabinetBoxId);
            cabinetBoxPolice.setPoliceId(req.getUserId());
            cabinetBoxPolice.setCreateTime(DateTimeUtil.getCurrentDateTime());
            cabinetBoxPolice.setUpdateTime(DateTimeUtil.getCurrentDateTime());
            cabinetBoxPoliceService.save(cabinetBoxPolice);
        }

        if (ObjectUtil.isNotEmpty(req.getFaceFeatures()))
        {
            policeman.setFaceInfo2(req.getFaceFeatures());
        }
        if (ObjectUtil.isNotEmpty(req.getPassword()))
        {
            policeman.setPsd(req.getPassword());
        }
        result=policemanService.updateById(policeman);
        if (!result){
            throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"更新人员信息失败");
        }
        List<PoliceFinger> addPoliceFingerList=new ArrayList<>();
        if (ObjectUtil.isNotEmpty(req.getFinger1Features()) || ObjectUtil.isNotEmpty(req.getFinger2Features()))
        {
            List<PoliceFinger> list = policeFingerService.list(new LambdaQueryWrapper<PoliceFinger>().eq(PoliceFinger::getPoliceId, req.getUserId()));
            if (CollectionUtil.isNotEmpty(list)){
                for (PoliceFinger policeFinger:list) {
                    if (policeFinger.getFingerNum().equals(1) && ObjectUtil.isNotEmpty(req.getFinger1Features())){//指纹1存在直接替换
                        policeFinger.setFingerInfo(req.getFinger1Features());
                        break;
                    }
                    if (policeFinger.getFingerNum().equals(2)&& ObjectUtil.isNotEmpty(req.getFinger2Features())){//指纹2存在直接替换
                        policeFinger.setFingerInfo(req.getFinger2Features());
                        break;
                    }else if (ObjectUtil.isNotEmpty(req.getFinger1Features())){//指纹1不存在直接新增
                        PoliceFinger policeFinger1 = addFingerInfo(req.getUserId(), 1, 0, req.getFinger1Features());
                        addPoliceFingerList.add(policeFinger1);
                        break;
                    }else {//指纹2不存在直接新增
                        PoliceFinger policeFinger2 = addFingerInfo(req.getUserId(), 2, 0, req.getFinger2Features());
                        addPoliceFingerList.add(policeFinger2);
                        break;
                    }
                }
                policeFingerService.updateBatchById(list);

            }else {
                if (ObjectUtil.isNotEmpty(req.getFinger1Features())){//指纹1不存在直接新增
                    PoliceFinger policeFinger1 = addFingerInfo(req.getUserId(), 1, 0, req.getFinger1Features());
                    addPoliceFingerList.add(policeFinger1);

                }
                if (ObjectUtil.isNotEmpty(req.getFinger1Features())){//指纹2不存在直接新增
                    PoliceFinger policeFinger2 = addFingerInfo(req.getUserId(), 2, 0, req.getFinger2Features());
                    addPoliceFingerList.add(policeFinger2);

                }
            }

        }
        if (CollectionUtil.isNotEmpty(addPoliceFingerList)){
            policeFingerService.saveBatch(addPoliceFingerList);
        }

        return true;
    }

    /**
     * 解绑单警柜和警员信息
     * @param req
     * @return
     */
    @Override
    @Transactional
    public Boolean deletePoliceAndCabinet(HardWarePoliceReq req) {
        policemanService.PoliceExist(req.getUserId());
        List<CabinetBoxPolice> boxList = cabinetMapper.getBoxBindUserList(req.getCabinetRealID(), req.getUserId(), req.getCabinetChildID().toString(), 1);
        CabinetBoxPolice cabinetBoxPolice =null;
        if (CollectionUtil.isEmpty(boxList)){
            throw new ServiceException(CabinetBoxExceptionEnum.CABINETBOX_ISNOT_EXISTS);
        }else {
            cabinetBoxPolice= boxList.get(0);
        }
        //获取箱门中在柜数（如果在柜报错，如果出柜直接解绑）
        Set<String> locationIdList=boxList.stream().map(CabinetBoxPolice::getCabinetBoxId).collect(Collectors.toSet());
        InventorySummary invSum=inventoryMapper.getSumByLocationIdList(locationIdList);
        if (ObjectUtil.isNotNull(invSum)){

            if (invSum.getStockNumber()>0){
                throw new ServiceException(CabinetV2ExceptionEnum.CABINETBOX_UNBIND_ERROR);
            }
            if (invSum.getOutboundNumber()>0){
                inventoryService.update(new LambdaUpdateWrapper<Inventory>().set(Inventory::getEqsBindState,0)
                        .in(Inventory::getLocationId,locationIdList));

            }
        }

        return cabinetBoxPoliceService.removeById(cabinetBoxPolice);
    }


    /**
     * 修改单警柜整柜模式
     * @param req
     * @return
     */
    @Override
    @Transactional
    public Boolean changeCabinetType(HardWareCabReq req) {
        //获取主柜下的所有箱门信息
        Cabinet cabinet = cabinetService.getOne(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getDevSn,req.getCurrentCabinetNum()));
        if (ObjectUtil.isNull(cabinet)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"单警柜不存在");
        }
        List<CabinetBox> boxList = cabinetMapper.getBoxList(req.getCurrentCabinetNum(), null);
        if (CollectionUtil.isEmpty(boxList)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"箱子信息不存在");
        }
        //获取到箱门id
        List<String> collect = boxList.stream().map(CabinetBox::getId).collect(Collectors.toList());

        //删除箱门的人员绑定关系
        boolean result =true;
        cabinetBoxPoliceService.remove(new LambdaQueryWrapper<CabinetBoxPolice>().in(CabinetBoxPolice::getCabinetBoxId,collect));
        //将装备进行解绑操作同时计算装备汇总
        List<Inventory> invList = inventoryService.list(new LambdaQueryWrapper<Inventory>()
                .in(Inventory::getLocationId, collect));
        List<WarehouseInventory> wareInvList = warehouseInventoryService.list(new LambdaQueryWrapper<WarehouseInventory>()
                .in(WarehouseInventory::getLocationId, collect));
        if (CollectionUtil.isNotEmpty(invList)){

            invList.forEach(inventory -> {inventory.setLocationState("out");inventory.setEqsBindState(0);inventory.setPoliceId("0");});
            result = inventoryService.updateBatchById(invList);
            if (!result){
                throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"修改失败");
            }
        }
        if (CollectionUtil.isNotEmpty(wareInvList)){

            wareInvList.forEach(warehouseInventory -> {warehouseInventory.setLocationState("out");});
            result = warehouseInventoryService.updateBatchById(wareInvList);
            if (!result){
                throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"修改失败");
            }
        }
        List<InventorySummary> invSumList = inventorySummaryService.list(new LambdaQueryWrapper<InventorySummary>().eq(InventorySummary::getLocationId, cabinet.getId()));
        if (CollectionUtil.isNotEmpty(invSumList)){
            for (InventorySummary invSum:invSumList) {
                invSum.setOutboundNumber(invSum.getStockNumber()+invSum.getOutboundNumber());
                invSum.setStockNumber(0);
            }
            result = inventorySummaryService.updateBatchById(invSumList);
            if (!result){
                throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"修改失败");
            }
        }

        //更新箱门的模式（0单警模式，1值班模式，2公共模式分别对应3.0的1，3，2）
        for (CabinetBox cabinetBox: boxList) {
            switch (req.getType()){
                case "1"://值班柜
                    cabinetBox.setContainType(3);
                    break;
                case "2"://公共柜
                    cabinetBox.setContainType(2);
                    break;
                case "0"://单警柜
                    cabinetBox.setContainType(1);
                    break;
                default:
                    break;
            }
        }
        result = cabinetBoxService.updateBatchById(boxList);
        if (!result){
            throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"箱门模式修改失败");
        }
        return true;
    }

    /**
     * 公共柜箱门绑定装备
     * @param req
     * @return
     */
    @Override
    @Transactional
    public List<HardWareInvDto> bindingInventory(HardWareCabReq req) {
        Cabinet cabinet = cabinetService.CabinetExistByNum(req.getCabinetID());
        PubOrg pubOrg = pubOrgService.PubOrgExist(cabinet.getOrgIdInt());
        CabinetBox one = cabinetBoxService.getOne(new LambdaQueryWrapper<CabinetBox>()
                .eq(CabinetBox::getCabinetId, cabinet.getId())
                .eq(CabinetBox::getBoxNo, req.getCabinetChildID()));
        if (ObjectUtil.isNull(one)){
            throw new ServiceException(CabinetBoxExceptionEnum.CABINETBOX_ISNOT_EXISTS);
        }
        //获取装备
        List<Inventory> invList = inventoryService.list(new LambdaQueryWrapper<Inventory>()
                .in(Inventory::getEpc, req.getRFIDList()));
        if (CollectionUtil.isNotEmpty(invList)){
//            invList.get(0).getOrgId()
            List<String> collect = invList.stream().map(Inventory::getEpc).collect(Collectors.toList());
            List<String> epcList=new ArrayList<>();
            for (String epc: req.getRFIDList()) {
                if (!collect.contains(epc)){
                    epcList.add(epc);
                }
            }
            if (CollectionUtil.isNotEmpty(epcList)){
                throw new JYZBAppException(InventoryExceptionEnum.INVENTORY_NOT_EXIST,req.getRFIDList());
            }
        }else {
            throw new JYZBAppException(InventoryExceptionEnum.INVENTORY_NOT_EXIST,req.getRFIDList());
        }
        //判断装备状态，如果仓库在库则直接选取一个领用出库的装备进行替换，领用出库数减少；如果仓库出库，那么直接修改位置信息和在库状态，出库数减少；
        //如果装备在单警柜出库并且绑定状态，直接报错装备已绑定，并且装备在出柜状态，
        // 如果装备位于在库状态，那么如果装备的位置信息一致提示已绑定，
        // 如果在别的单警柜在柜，那么原来的单警柜的在柜数减少，汇总减少，现在的装备的在柜数增加，（需要判断箱门是否在同一个主柜，如果同一个主柜，那么汇总表不需要变更，只需要变更位置信息）
        PoliceEquipmentDetailReq policeEquipmentDetailReq = new PoliceEquipmentDetailReq();
        policeEquipmentDetailReq.setOrgCode(pubOrg.getOrgCode());
        policeEquipmentDetailReq.setDevSn(req.getCabinetID());
        policeEquipmentDetailReq.setLocationId(one.getId());
        policeEquipmentDetailReq.setEpcsList(req.getRFIDList());
        inventoryService.EqsBindOrUnbindCabinet(policeEquipmentDetailReq);

        List<InventoryDto> inventoryDtos = inventoryService.GetInvInfoByEpc(req.getRFIDList());
        List<HardWareInvDto> returnList=new ArrayList<>();
        for (InventoryDto inv:inventoryDtos) {
            HardWareInvDto hardWareInvDto = new HardWareInvDto();
            hardWareInvDto.setEpc(inv.getEpc());
            hardWareInvDto.setExpireTime(DateTimeUtil.addMonsAfterDate(inv.getProductionDate(),inv.getWarrantyPeriod()));
            hardWareInvDto.setEquName(inv.getTypeName());
            hardWareInvDto.setSizeName(inv.getSizeName());
            hardWareInvDto.setWarrantyCycle(inv.getWarrantyPeriod());
            returnList.add(hardWareInvDto);
        }
        return returnList;
    }

    /**
     * 上传RFID离线数据
     * @param req
     * @return
     */
    @Override
    public List<UploadRFIDListInnerDto> uploadRFIDListInner(UploadRFIDListInnerReq req) {

        Map<String,List<String>> cabinetMap=new HashMap<>();
        List<String> epcList=new ArrayList<>();

        for (UploadRFIDListInnerReq.UploadRFIDReq uploadRFIDReq:req.getRFIDUpList()) {

            if (ObjectUtil.isNull(uploadRFIDReq.getCabinetID()) || ObjectUtil.isEmpty(uploadRFIDReq.getCabinetID())){
                throw new JYZBAppException(CabinetBoxExceptionEnum.BOXS_ISNOT_EXISTS,"主柜编号不能为空");
            }
            if (ObjectUtil.isNull(uploadRFIDReq.getCabinetChildID()) || ObjectUtil.isEmpty(uploadRFIDReq.getCabinetChildID())){
                throw new JYZBAppException(CabinetBoxExceptionEnum.BOXS_ISNOT_EXISTS,"箱门号不能为空");

            }
            if (ObjectUtil.isNull(uploadRFIDReq.getTime())){
                throw new JYZBAppException(CabinetBoxExceptionEnum.BOXS_ISNOT_EXISTS,"时间不能为空");

            }
            //将主柜下面的箱门全部查询出来之后再map过滤分组
            //获取前端传递的主柜号以及箱门号
            if (!cabinetMap.containsKey(uploadRFIDReq.getCabinetID())){
                List<String> boxNumList=new ArrayList<>();
                boxNumList.add(uploadRFIDReq.getCabinetChildID());
                cabinetMap.put(uploadRFIDReq.getCabinetID(),boxNumList);
            }else {
                List<String> strings = cabinetMap.get(uploadRFIDReq.getCabinetID());
                strings.add(uploadRFIDReq.getCabinetChildID());
                cabinetMap.put(uploadRFIDReq.getCabinetID(),strings);
            }
            if (CollectionUtil.isNotEmpty(uploadRFIDReq.getRFIDList())){
                epcList.addAll(uploadRFIDReq.getRFIDList());
            }

        }
        List<MapReq> reqList=new ArrayList<>();
        //我先得获取所有的箱门号
        for (String key:cabinetMap.keySet()) {
            MapReq mapReq = new MapReq();
            mapReq.setDevSn(key);
            mapReq.setBoxList(cabinetMap.get(key));
            reqList.add(mapReq);
        }
        List<String> boxList=cabinetMapper.getBoxListByCab(reqList);
        //获取所有装备()
        List<String> reqEpcList=new ArrayList<>();
        List<Inventory> invList =  inventoryMapper.getInvByCabBoxList(boxList,reqEpcList);
        //修改的在库装备和出库装备汇总
        List<Inventory> inInvList=new ArrayList<>();
        List<Inventory> outInvList=new ArrayList<>();
        for (Inventory inventory:invList) {
            if (inventory.getLocationState().equals("in")){
                inInvList.add(inventory);

            }else {
                outInvList.add(inventory);

            }
        }
        List<Inventory> totalChangeList=new ArrayList<>();
        List<Inventory> updateIntoOutList=new ArrayList<>();
        List<Inventory> updateOutToInList=new ArrayList<>();

        for (UploadRFIDListInnerReq.UploadRFIDReq uploadRFIDReq:req.getRFIDUpList()) {
            if (CollectionUtil.isNotEmpty(uploadRFIDReq.getRFIDList())){//判断是否有在柜的，如果有则分情况而定
                for (Inventory inventory:inInvList) {
                    if (!epcList.contains(inventory.getEpc())){
                        inventory.setLocationState("out");
                        inventory.setUpdateTime(uploadRFIDReq.getTime());
                        updateIntoOutList.add(inventory);
                        totalChangeList.add(inventory);
                    }

                }
                for (Inventory inventory:outInvList) {
                    if (epcList.contains(inventory.getEpc())){
                        inventory.setLocationState("in");
                        inventory.setUpdateTime(uploadRFIDReq.getTime());
                        updateOutToInList.add(inventory);
                        totalChangeList.add(inventory);
                    }
                }
            }
        }
        //获取到并且新增入库记录（由出库转为入库）

        if (CollectionUtil.isNotEmpty(updateOutToInList)){
            String orgName=updateOutToInList.get(0).getOrgName();
            List<InventoryReq> collect = BeanPlusUtil.toBeanList(updateOutToInList, InventoryReq.class);
            logSummaryService.addLogSummaryByInv(collect,null,null,"normal",1,"1",null,orgName,null);

        }
        //获取到并且新增出库记录(由入库转为出库)
        if (CollectionUtil.isNotEmpty(updateIntoOutList)){
            String orgName=updateIntoOutList.get(0).getOrgName();
            List<InventoryReq> collect = BeanPlusUtil.toBeanList(updateIntoOutList, InventoryReq.class);
            logSummaryService.addLogSummaryByInv(collect,null,null,"normal",1,"1",null,orgName,null);

        }


        //汇总同一装备类别、号型、单价、资产类型，查询出库存汇总数据，并且将库存汇总数据进行修改
        Map<String,Object[]> searchMap=new HashMap<>();
        if (CollectionUtil.isNotEmpty(totalChangeList)){
            for (Inventory inventory:totalChangeList){
                String key=inventory.getOrgId()+"-"+inventory.getDevSn()+"-"+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;
                        objects[7]=(Integer)objects[7]-1;
                    }else {
                        objects[6]=(Integer)objects[6]-1;
                        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,-1};
                    }else {
                        item=new Object[]{inventory.getOrgId(),inventory.getCabinetId(),inventory.getTypeId(),inventory.getSizeId(),inventory.getPrice(),inventory.getProperty(),-1,1};
                    }
                    searchMap.put(key,item);
                }
            }
            List<InventorySummary> inventorySummaryList = inventorySummaryMapper.selectSum(new ArrayList<>(searchMap.values()));
            for (InventorySummary invSum:inventorySummaryList) {
                for (String key:searchMap.keySet()) {
                    List<String> keyList = Arrays.asList(key.split("-"));
                    Long orgId = Long.valueOf(keyList.get(0));
                    String locationId = keyList.get(1);
                    String typeId = keyList.get(2);
                    String sizeId = keyList.get(3);
                    BigDecimal unitPrice = new BigDecimal(keyList.get(4));
                    Integer property = Integer.valueOf(keyList.get(5));
                    Integer inNum = Integer.valueOf(keyList.get(6));
                    Integer outNum = Integer.valueOf(keyList.get(7));
                    if (invSum.getOrgId().equals(orgId) && invSum.getLocationId().equals(locationId) &&
                            invSum.getTypeId().equals(typeId) &&invSum.getSizeId().equals(sizeId) &&
                            invSum.getUnitPrice().equals(unitPrice) &&invSum.getProperty().equals(property)){
                        invSum.setStockNumber(invSum.getStockNumber()+inNum);
                        invSum.setOutboundNumber(invSum.getOutboundNumber()+outNum);
                    }
                    break;
                }
            }
            inventorySummaryService.updateBatchById(inventorySummaryList);
        }

        //更新状态
        if (CollectionUtil.isNotEmpty(updateIntoOutList)){
            inventoryService.updateBatchById(updateIntoOutList);
            List<String> collect = updateIntoOutList.stream().map(Inventory::getEpc).collect(Collectors.toList());
            warehouseInventoryService.update(new LambdaUpdateWrapper<WarehouseInventory>()
                    .set(WarehouseInventory::getLocationState,"out")
                    .in(WarehouseInventory::getEpc,collect));
        }
        if (CollectionUtil.isNotEmpty(updateOutToInList)){
            inventoryService.updateBatchById(updateOutToInList);
            List<String> collect = updateOutToInList.stream().map(Inventory::getEpc).collect(Collectors.toList());
            warehouseInventoryService.update(new LambdaUpdateWrapper<WarehouseInventory>()
                    .set(WarehouseInventory::getLocationState,"in")
                    .in(WarehouseInventory::getEpc,collect));
        }

        List<UploadRFIDListInnerDto> dtoList=new ArrayList<>();
        for (Inventory inventory:totalChangeList) {
            UploadRFIDListInnerDto dto = new UploadRFIDListInnerDto();
            dto.setName(inventory.getTypeName()+"-"+inventory.getSizeName());
            dto.setEPC(inventory.getEpc());
            dto.setState(inventory.getLocationState());
            dto.setTime(inventory.getUpdateTime());
            dto.setBoxNum(inventory.getBoxNo());
            dto.setUserName(inventory.getUpdateUser());
            dtoList.add(dto);
        }

        //最终返回有更改状态的物资信息
        return dtoList;
    }

    /**
     * 上传RFID数据
     * @param req
     * @return
     */
    @Override
    public List<UploadRFIDInnerDto> uploadRFIDInner(UploadRFIDInnerReq req) {
        List<UploadRFIDInnerDto> returnList=new ArrayList<>();

        //获取箱门信息
        Cabinet cabinet=cabinetService.getOne(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getDevSn,req.getCabinetID()));
        if (ObjectUtil.isNull(cabinet)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"单警柜不存在");
        }
        CabinetBox one = cabinetBoxService.getOne(new LambdaQueryWrapper<CabinetBox>()
                .eq(CabinetBox::getBoxNo, req.getCabinetChildID())
                .eq(CabinetBox::getCabinetId, cabinet.getId()));
        //获取箱门对应绑定警员信息
        if (ObjectUtil.isNull(one)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"箱门信息不存在");
        }

        Policeman policeman=cabinetMapper.getPoliceByBoxId(one.getId());
        if (ObjectUtil.isNull(policeman)){
            throw new JYZBAppException(CabinetV2ExceptionEnum.POLICE_NOT_EXIST,"该箱门未绑定警员");
        }
        PubOrg pubOrg = pubOrgService.PubOrgExist(policeman.getOrgId());

        //获取前端绑定装备情况
        List<Inventory> invlist=new ArrayList<>();
        //前端传递的rfid
        if (CollectionUtil.isNotEmpty(req.getRFIDList())){
            invlist = inventoryMapper.getInvEpcList(null,req.getRFIDList(),null,null);
        }
        //存放错误归还装备
        List<Inventory> errorReturnList=new ArrayList<>();
        //第二次错还及以上（针对错还并且未拿出装备，一直需要提示报错还）
        List<Inventory> errorReturnMoreList=new ArrayList<>();
        //存放日志
        List<Inventory> logInvList=new ArrayList<>();

        //查询出警员绑定的装备
        List<Inventory> policeInvList=inventoryMapper.getInvEpcList(policeman.getId(),null,null,1);
        //警员绑定装备下的在柜装备
        List<String> inEPCList = policeInvList.stream()
                .filter(inventory -> inventory.getLocationState().equals("in"))
                .map(Inventory::getEpc).collect(Collectors.toList());
        Map<String, Object[]> invSumMap = new HashMap<>();
        Map<String, Object[]> addSumMap = new HashMap<>();

        List<InventorySummary> delSumList = new ArrayList<>();
        List<InventorySummary> addSumList = new ArrayList<>();

        //判断少拿标志
        boolean flag=false;

        List<Inventory> inventoryList=new ArrayList<>();
        //装备绑定、解绑传true
        if (req.getRebind()) {


            //获取前端传递的rfid的位置信息，如果位置信息为仓库在库，从领用出库的装备中获取一条进行替换
            //如果位置信息为仓库出库，那么直接将仓库出库数减少，装备总数进行减少，单警柜在库数增加
            //如果位置信息在单警柜，判断两个箱门位置是否相同，如果不相同报错装备已经绑定柜子，请先解绑，如果位置在该单警柜，那么不进行任何操作
            //如果是绑定装备新增一条入库的记录，如果是出库新增一条出库的记录


            //判断前端是否有新的需要绑定的装备(警员装备为空就一定是新绑定关系)
            if (CollectionUtil.isEmpty(policeInvList) && CollectionUtil.isNotEmpty(invlist)) {
                //全部第一次绑定

                //判断前端是否有新的需要绑定的装备
                Map<String, List<Inventory>> stringListMap = EqsBind(req.getUrl(),invlist, logInvList, cabinet, invSumMap, addSumMap, one, policeman, delSumList, addSumList, pubOrg, errorReturnList,req.getRebind(),errorReturnMoreList);
                logInvList = stringListMap.get("logInvList");
                errorReturnList=stringListMap.get("errorReturnList");
                errorReturnMoreList=stringListMap.get("errorReturnMoreList");
                for (Inventory inventory:invlist) {
                    UploadRFIDInnerDto uploadRFIDInnerDto = new UploadRFIDInnerDto();
                    uploadRFIDInnerDto.setEPC(inventory.getEpc());
                    uploadRFIDInnerDto.setState("in");
                    uploadRFIDInnerDto.setName(inventory.getTypeName()+"-"+inventory.getSizeName());
                    uploadRFIDInnerDto.setTime(req.getTime());
                    uploadRFIDInnerDto.setBoxNum(req.getCabinetChildID());
                    uploadRFIDInnerDto.setUserName(policeman.getName());
                    uploadRFIDInnerDto.setIdCardNo(policeman.getIdCard());
                    returnList.add(uploadRFIDInnerDto);
                }

            }
            else if (CollectionUtil.isNotEmpty(policeInvList)) {
                //装备可能存在绑定可能存在解绑关系

                List<Inventory> updateInvList=new ArrayList<>();
                List<String> collect = policeInvList.stream().map(Inventory::getEpc).collect(Collectors.toList());
                List<String> collectInvEpcList=new ArrayList<>();
                List<String> unbindEpcList=new ArrayList<>();
                List<Inventory> addBindInvList=new ArrayList<>();
                //前端传递的epc没有警员绑定装备，进行解绑
                List<Inventory> unbindList=new ArrayList<>();
                if (CollectionUtil.isNotEmpty(invlist)){
                    for (int i=0;i<invlist.size();i++) {
                        Inventory inventory = invlist.get(i);
                        if (!collect.contains(inventory.getEpc())){
                            addBindInvList.add(inventory);
                            invlist.remove(inventory);
                            i--;
                        }
                    }
                    if (CollectionUtil.isNotEmpty(invlist)){
                        collectInvEpcList=invlist.stream().map(Inventory::getEpc).collect(Collectors.toList());
                    }
                    for (Inventory inventory:policeInvList){
                        if (!collectInvEpcList.contains(inventory.getEpc())){//不包含表示需要解绑的装备
                            unbindEpcList.add(inventory.getEpc());
                        }
                    }
                    List<Inventory> collect1 = policeInvList.stream().filter(inventory -> unbindEpcList.contains(inventory.getEpc())).collect(Collectors.toList());

                    unbindList.addAll(collect1);
                }else {

                    unbindList.addAll(policeInvList);

                }

                //解绑装备
                if (CollectionUtil.isNotEmpty(unbindList)){
                    for (Inventory inventory : unbindList){
                        if (inventory.getLocationState().equals("in")){
                            String key=inventory.getOrgId()+ inventory.getLocationId()+ inventory.getTypeId()+inventory.getSizeId()+inventory.getPrice()+inventory.getProperty();
                            if (!invSumMap.containsKey(key)) {
                                Object[] item = new Object[]{inventory.getOrgId(), inventory.getLocationId(), inventory.getTypeId(), inventory.getSizeId(), inventory.getPrice(), inventory.getProperty(), 0};
                                item[6]=(Integer)item[6]+1;
                                invSumMap.put(key, item);
                            } else {
                                Object[] item = invSumMap.get(key);
                                item[6]=(Integer)item[6]+1;
                                invSumMap.put(key, item);
                            }
                        }
                        inventory.setLocationState("out");
                        inventory.setEqsBindState(0);
                        inventory.setPoliceId("");
                        inventory.setLocationId(inventory.getOldLocationId());
                        inventory.setPhoto((StrUtil.isNotEmpty(req.getUrl()) || ObjectUtil.isNotNull(req.getUrl()))?req.getUrl():null);
                        inventory.setLocationName(cabinet.getName());
                        logInvList.add(inventory);
                        updateInvList.add(inventory);

                    }

                    if (!invSumMap.isEmpty()){
                        List<Object[]> list =  new ArrayList<>(invSumMap.values());
                        List<InventorySummary> oldSummaryList = inventorySummaryMapper.selectSum(list);
                        if (CollectionUtil.isNotEmpty(oldSummaryList)){
                            for (InventorySummary oldSum:oldSummaryList) {
                                String key= oldSum.getOrgId()+oldSum.getLocationId()+oldSum.getTypeId()+oldSum.getSizeId()+oldSum.getUnitPrice()+oldSum.getProperty();
                                Object[] objects = invSumMap.get(key);
                                if ((Integer)objects[6]>0){
                                    oldSum.setOutboundNumber(oldSum.getOutboundNumber()+(Integer) objects[6]);
                                    oldSum.setStockNumber(oldSum.getStockNumber()-(Integer) objects[6]);
                                    oldSum.setPrice(oldSum.getUnitPrice().multiply(BigDecimal.valueOf(oldSum.getNumber())));
                                }
                            }
                            inventorySummaryService.updateBatchById(oldSummaryList);
                        }
                        invSumMap.clear();
                    }
                    //更新装备
                    inventoryService.updateBatchById(updateInvList);
                    List<String> epcList = updateInvList.stream().map(Inventory::getEpc).collect(Collectors.toList());
                    warehouseInventoryService.update(new LambdaUpdateWrapper<WarehouseInventory>().in(WarehouseInventory::getEpc, epcList)
                            .set(WarehouseInventory::getLocationId, one.getId())
                            .set(WarehouseInventory::getLocationState, "out"));
                }


                //如果原来是出库状态，走绑定打开箱门接口就默认它是入库状态，添加入库日志，和返回前端值，并且修改库存汇总
                List<Inventory> updateOutToInList=new ArrayList<>();
                List<String> outEpcList = policeInvList.stream().filter(inventory -> inventory.getLocationState().equals("out")).map(Inventory::getEpc).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(outEpcList)){
                    for (Inventory inventory:invlist){
                        if (outEpcList.contains(inventory.getEpc())){
                            updateOutToInList.add(inventory);
                        }
                    }
                }
                //将出库改成入库
                if (CollectionUtil.isNotEmpty(updateOutToInList)){
                    for (Inventory inventory : updateOutToInList){
                        String key=inventory.getOrgId()+ inventory.getLocationId()+ inventory.getTypeId()+inventory.getSizeId()+inventory.getPrice()+inventory.getProperty();
                        if (!invSumMap.containsKey(key)) {
                            Object[] item = new Object[]{inventory.getOrgId(), inventory.getLocationId(), inventory.getTypeId(), inventory.getSizeId(), inventory.getPrice(), inventory.getProperty(),1};
                            invSumMap.put(key, item);
                        } else {
                            Object[] item = invSumMap.get(key);
                            item[6]=(Integer)item[6]+1;
                            invSumMap.put(key, item);
                        }

                        inventory.setLocationState("in");
                        inventory.setEqsBindState(1);
                        inventory.setLocationId(inventory.getOldLocationId());
                        inventory.setPhoto((StrUtil.isNotEmpty(req.getUrl()) || ObjectUtil.isNotNull(req.getUrl()))?req.getUrl():null);
                        inventory.setLocationName(cabinet.getName());
                        logInvList.add(inventory);
                    }

                    if (!invSumMap.isEmpty()){
                        List<Object[]> list =  new ArrayList<>(invSumMap.values());
                        List<InventorySummary> oldSummaryList = inventorySummaryMapper.selectSum(list);
                        if (CollectionUtil.isNotEmpty(oldSummaryList)){
                            for (InventorySummary oldSum:oldSummaryList) {
                                String key= oldSum.getOrgId()+oldSum.getLocationId()+oldSum.getTypeId()+oldSum.getSizeId()+oldSum.getUnitPrice()+oldSum.getProperty();
                                Object[] objects = invSumMap.get(key);
                                if ((Integer)objects[6]>0){
                                    oldSum.setOutboundNumber(oldSum.getOutboundNumber()-(Integer) objects[6]);
                                    oldSum.setStockNumber(oldSum.getStockNumber()+(Integer) objects[6]);
                                }
                            }
                            inventorySummaryService.updateBatchById(oldSummaryList);
                        }
                        invSumMap.clear();
                    }
                    //更新装备
                    inventoryService.updateBatchById(updateOutToInList);
                    List<String> epcList = updateOutToInList.stream().map(Inventory::getEpc).collect(Collectors.toList());
                    warehouseInventoryService.update(new LambdaUpdateWrapper<WarehouseInventory>().in(WarehouseInventory::getEpc, epcList)
                            .set(WarehouseInventory::getLocationId, one.getId())
                            .set(WarehouseInventory::getLocationState, "in"));
                }




                //判断前端是否有新的需要绑定的装备
                if (CollectionUtil.isNotEmpty(addBindInvList)){

                    Map<String, List<Inventory>> stringListMap = EqsBind(req.getUrl(),addBindInvList, logInvList, cabinet, invSumMap, addSumMap, one, policeman, delSumList, addSumList, pubOrg, errorReturnList,req.getRebind(),errorReturnMoreList);
                    logInvList = stringListMap.get("logInvList");
                    errorReturnList=stringListMap.get("errorReturnList");
                    errorReturnMoreList=stringListMap.get("errorReturnMoreList");
                    for (Inventory inventory:addBindInvList) {
                        UploadRFIDInnerDto uploadRFIDInnerDto = new UploadRFIDInnerDto();
                        uploadRFIDInnerDto.setEPC(inventory.getEpc());
                        uploadRFIDInnerDto.setState("in");
                        uploadRFIDInnerDto.setName(inventory.getTypeName()+"-"+inventory.getSizeName());
                        uploadRFIDInnerDto.setTime(req.getTime());
                        uploadRFIDInnerDto.setBoxNum(req.getCabinetChildID());
                        uploadRFIDInnerDto.setUserName(policeman.getName());
                        uploadRFIDInnerDto.setIdCardNo(policeman.getIdCard());
                        returnList.add(uploadRFIDInnerDto);
                    }
                }



            }

        }

        else {
            //日常出入库
            List<Inventory> updateInvList=new ArrayList<>();
            //警员存在的绑定关系
            List<String> collect = policeInvList.stream().map(Inventory::getEpc).collect(Collectors.toList());
            List<Inventory> addBindList=new ArrayList<>();
            if (CollectionUtil.isNotEmpty(invlist)){

                for (int i=0;i<invlist.size();i++){
                    Inventory inventory = invlist.get(i);
                    if (!collect.contains(inventory.getEpc())){
                        addBindList.add(inventory);
//                        invlist.remove(inventory);
//                        i--;
                    }
                }
            }
            //新增绑定关系
            if (CollectionUtil.isNotEmpty(addBindList)){
//                addBindList.forEach(inventory -> inventory.setLocationId(inventory.getOldLocationId()));
                Map<String, List<Inventory>> stringListMap = EqsBind(req.getUrl(),addBindList, logInvList, cabinet, invSumMap, addSumMap, one, policeman, delSumList, addSumList, pubOrg, errorReturnList,req.getRebind(),errorReturnMoreList);
                logInvList = stringListMap.get("logInvList");
                errorReturnList=stringListMap.get("errorReturnList");
                errorReturnMoreList=stringListMap.get("errorReturnMoreList");
                for (Inventory inventory:addBindList) {
                    UploadRFIDInnerDto uploadRFIDInnerDto = new UploadRFIDInnerDto();
                    uploadRFIDInnerDto.setEPC(inventory.getEpc());
                    uploadRFIDInnerDto.setState("in");
                    uploadRFIDInnerDto.setName(inventory.getTypeName()+"-"+inventory.getSizeName());
                    uploadRFIDInnerDto.setTime(req.getTime());
                    uploadRFIDInnerDto.setBoxNum(req.getCabinetChildID());
                    uploadRFIDInnerDto.setUserName(policeman.getName());
                    uploadRFIDInnerDto.setIdCardNo(policeman.getIdCard());
                    returnList.add(uploadRFIDInnerDto);
                }
            }


            //箱门的在库数和出库数进行查询
            List<String> inEpcList=new ArrayList<>();
            List<Inventory> inInvList=new ArrayList<>();
            List<String> outEpcList=new ArrayList<>();
            //拿到箱门中的装备
            List<Inventory> boxBindEqsList=inventoryMapper.getInvEpcList(null,null, one.getId(),1);
//            boxBindEqsList=boxBindEqsList.stream().filter(inventory -> inventory.getBindLocationId() == null || inventory.getBindLocationId().isEmpty())
//                    .collect(Collectors.toList());

            for (Inventory inventory:boxBindEqsList) {
                if (inventory.getLocationState().equals("in")){
                    inEpcList.add(inventory.getEpc());
                    inInvList.add(inventory);
                }else {
                    outEpcList.add(inventory.getEpc());
                }
            }

            Map<String,Object[]> updateOldSumMap=new HashMap<>();
            Map<String,Object[]> updateNewSumMap=new HashMap<>();
            List<Inventory> updateOutToInList=new ArrayList<>();

            //查询出原来bindLocationId中的数值是都存在
            List<Inventory> bindEqsList = inventoryService.list(new LambdaQueryWrapper<Inventory>().eq(Inventory::getEqsBindState, 1).eq(Inventory::getBindLocationId, one.getId()));
            List<String> bindEqsEpcList = bindEqsList.stream().map(Inventory::getEpc).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(invlist)){

                for (Inventory inventory:invlist) {
                    String key = inventory.getOrgId() + inventory.getLocationId() + inventory.getTypeId() + inventory.getSizeId() + inventory.getPrice() + inventory.getProperty();
                    String key1 = inventory.getOrgId() + inventory.getBindCabinetId() + inventory.getTypeId() + inventory.getSizeId() + inventory.getPrice() + inventory.getProperty();

                    //由出库状态转为在库状态(不包含第二次错还，第二次错还指的是已经错还过一次并且位置信息已经改成该错还箱门了)
                    if (CollectionUtil.isNotEmpty(outEpcList) && outEpcList.contains(inventory.getEpc()) && (ObjectUtil.isEmpty(inventory.getBindLocationId())|| inventory.getBindLocationId().isEmpty() || inventory.getBindLocationId().equals(""))){
                        flag=true;
                        //添加一条入库装备存入返回列表
                        UploadRFIDInnerDto uploadRFIDInnerDto = new UploadRFIDInnerDto();
                        uploadRFIDInnerDto.setEPC(inventory.getEpc());
                        uploadRFIDInnerDto.setState("in");
                        uploadRFIDInnerDto.setName(inventory.getTypeName() + "-" + inventory.getSizeName());
                        uploadRFIDInnerDto.setTime(req.getTime());
                        uploadRFIDInnerDto.setBoxNum(req.getCabinetChildID());
                        uploadRFIDInnerDto.setUserName(policeman.getName());
                        uploadRFIDInnerDto.setIdCardNo(policeman.getIdCard());
                        returnList.add(uploadRFIDInnerDto);

                        if (!updateOldSumMap.containsKey(key)) {
                            Object[] item = new Object[]{inventory.getOrgId(), inventory.getLocationId(), inventory.getTypeId(), inventory.getSizeId(), inventory.getPrice(), inventory.getProperty(), 1, -1};
                            updateOldSumMap.put(key, item);
                        } else {
                            Object[] item = updateOldSumMap.get(key);
                            item[6] = (Integer) item[6] + 1;
                            item[7] = (Integer) item[7] - 1;
                            updateOldSumMap.put(key, item);
                        }
                        inventory.setLocationState("in");
                        inventory.setLocationId(inventory.getOldLocationId());
                        updateInvList.add(inventory);
                        updateOutToInList.add(inventory);
                        inventory.setPhoto((StrUtil.isNotEmpty(req.getUrl()) || ObjectUtil.isNotNull(req.getUrl()))?req.getUrl():null);
                        inventory.setLocationName(cabinet.getName());
                        logInvList.add(inventory);
                    }
                    //如果前端传递的值bindLocationId中存在，那么视为是正确的归还入库，则将状态进行修正并且将位置关系进行修正
                    if (bindEqsEpcList.contains(inventory.getEpc())){
                        //添加一条入库装备存入返回列表
                        UploadRFIDInnerDto uploadRFIDInnerDto = new UploadRFIDInnerDto();
                        uploadRFIDInnerDto.setEPC(inventory.getEpc());
                        uploadRFIDInnerDto.setState("in");
                        uploadRFIDInnerDto.setName(inventory.getTypeName() + "-" + inventory.getSizeName());
                        uploadRFIDInnerDto.setTime(req.getTime());
                        uploadRFIDInnerDto.setBoxNum(req.getCabinetChildID());
                        uploadRFIDInnerDto.setUserName(policeman.getName());
                        uploadRFIDInnerDto.setIdCardNo(policeman.getIdCard());
                        returnList.add(uploadRFIDInnerDto);

                        if (!updateOldSumMap.containsKey(key1)) {
                            Object[] item = new Object[]{inventory.getOrgId(), inventory.getBindCabinetId(), inventory.getTypeId(), inventory.getSizeId(), inventory.getPrice(), inventory.getProperty(), 0, -1};
                            updateOldSumMap.put(key, item);
                        } else {
                            Object[] item = updateOldSumMap.get(key1);
                            item[7] = (Integer) item[7] - 1;
                            updateOldSumMap.put(key, item);
                        }

                        if (!updateNewSumMap.containsKey(key)) {
                            Object[] item = new Object[]{inventory.getOrgId(), inventory.getLocationId(), inventory.getTypeId(), inventory.getSizeId(), inventory.getPrice(), inventory.getProperty(), 1, 0};
                            updateNewSumMap.put(key, item);
                        } else {
                            Object[] item = updateNewSumMap.get(key);
                            item[6] = (Integer) item[6] + 1;
                            updateNewSumMap.put(key, item);
                        }
                        inventory.setLocationState("in");

                        inventory.setLocationId(inventory.getBindLocationId());
                        inventory.setBindLocationId("");
                        updateInvList.add(inventory);
                        updateOutToInList.add(inventory);
                        inventory.setPhoto((StrUtil.isNotEmpty(req.getUrl()) || ObjectUtil.isNotNull(req.getUrl()))?req.getUrl():null);
                        inventory.setLocationName(cabinet.getName());
                        logInvList.add(inventory);
                    }
                    //第二次错还及以上
                    if (inventory.getLocationState().equals("out") && inventory.getOldLocationId().equals(one.getId()) && (ObjectUtil.isNotEmpty(inventory.getBindLocationId())|| !inventory.getBindLocationId().isEmpty())){
                        UploadRFIDInnerDto uploadRFIDInnerDto = new UploadRFIDInnerDto();
                        uploadRFIDInnerDto.setEPC(inventory.getEpc());
                        uploadRFIDInnerDto.setState("in");
                        uploadRFIDInnerDto.setName(inventory.getTypeName() + "-" + inventory.getSizeName());
                        uploadRFIDInnerDto.setTime(req.getTime());
                        uploadRFIDInnerDto.setBoxNum(req.getCabinetChildID());
                        uploadRFIDInnerDto.setUserName(policeman.getName());
                        uploadRFIDInnerDto.setIdCardNo(policeman.getIdCard());
                        returnList.add(uploadRFIDInnerDto);

                        if (!updateOldSumMap.containsKey(key1)) {
                            Object[] item = new Object[]{inventory.getOrgId(), inventory.getBindCabinetId(), inventory.getTypeId(), inventory.getSizeId(), inventory.getPrice(), inventory.getProperty(), 1, -1};
                            updateOldSumMap.put(key, item);
                        } else {
                            Object[] item = updateOldSumMap.get(key1);
                            item[6] = (Integer) item[6] + 1;
                            item[7] = (Integer) item[7] - 1;
                            updateOldSumMap.put(key, item);
                        }

                        inventory.setLocationState("in");
                        inventory.setLocationId(inventory.getOldLocationId());
                        updateInvList.add(inventory);
                        inventory.setPhoto((StrUtil.isNotEmpty(req.getUrl()) || ObjectUtil.isNotNull(req.getUrl()))?req.getUrl():null);
                        inventory.setLocationName(cabinet.getName());
//                        updateOutToInList.add(inventory);
                        logInvList.add(inventory);
                    }

                }
                //前端传递的epc
                List<String> collect1 = invlist.stream().map(Inventory::getEpc).collect(Collectors.toList());
                //库中包含的在库装备
                for (Inventory inventory :inInvList){
                    String key = inventory.getOrgId() + inventory.getLocationId() + inventory.getTypeId() + inventory.getSizeId() + inventory.getPrice() + inventory.getProperty();
                    //状态由在库转为出库
                    if (!collect1.contains(inventory.getEpc())){
                        //添加一条入库装备存入返回列表
                        UploadRFIDInnerDto uploadRFIDInnerDto = new UploadRFIDInnerDto();
                        uploadRFIDInnerDto.setEPC(inventory.getEpc());
                        uploadRFIDInnerDto.setState("out");
                        uploadRFIDInnerDto.setName(inventory.getTypeName()+"-"+inventory.getSizeName());
                        uploadRFIDInnerDto.setTime(req.getTime());
                        uploadRFIDInnerDto.setBoxNum(req.getCabinetChildID());
                        uploadRFIDInnerDto.setUserName(policeman.getName());
                        uploadRFIDInnerDto.setIdCardNo(policeman.getIdCard());
                        returnList.add(uploadRFIDInnerDto);

                        if (!updateOldSumMap.containsKey(key)){
                            Object[] item = new Object[]{inventory.getOrgId(), inventory.getLocationId(), inventory.getTypeId(), inventory.getSizeId(), inventory.getPrice(), inventory.getProperty(), 0,0};
                            item[6]=(Integer)item[6]-1;
                            item[7]=(Integer)item[7]+1;
                            updateOldSumMap.put(key, item);
                        }else {
                            Object[] item = updateOldSumMap.get(key);
                            item[6]=(Integer)item[6]-1;
                            item[7]=(Integer)item[7]+1;
                            updateOldSumMap.put(key, item);
                        }

                        inventory.setLocationState("out");
                        inventory.setLocationId(inventory.getOldLocationId());
                        updateInvList.add(inventory);
                        inventory.setPhoto((StrUtil.isNotEmpty(req.getUrl()) || ObjectUtil.isNotNull(req.getUrl()))?req.getUrl():null);
                        inventory.setLocationName(cabinet.getName());
                        logInvList.add(inventory);
                    }
                    else {
                        if (ObjectUtil.isEmpty(inventory.getBindLocationId()) || inventory.getBindLocationId().isEmpty()){
                            inventoryList.add(inventory);
                        }
                    }
                }
            }

            else {
                //装备全部领用出去
                List<Inventory> collect1 = boxBindEqsList.stream().filter(inventory -> inEpcList.contains(inventory.getEpc())).collect(Collectors.toList());

                for (Inventory inventory : collect1 ) {

                    //添加一条出库装备存入返回列表
                    UploadRFIDInnerDto uploadRFIDInnerDto = new UploadRFIDInnerDto();
                    uploadRFIDInnerDto.setEPC(inventory.getEpc());
                    uploadRFIDInnerDto.setState("out");
                    uploadRFIDInnerDto.setName(inventory.getTypeName()+"-"+inventory.getSizeName());
                    uploadRFIDInnerDto.setTime(req.getTime());
                    uploadRFIDInnerDto.setBoxNum(req.getCabinetChildID());
                    uploadRFIDInnerDto.setUserName(policeman.getName());
                    uploadRFIDInnerDto.setIdCardNo(policeman.getIdCard());
                    returnList.add(uploadRFIDInnerDto);

                    String key=inventory.getOrgId()+inventory.getLocationId()+inventory.getTypeId()+inventory.getSizeId()+inventory.getPrice()+inventory.getProperty();
                    if (!updateOldSumMap.containsKey(key)){
                        Object[] item = new Object[]{inventory.getOrgId(), inventory.getLocationId(), inventory.getTypeId(), inventory.getSizeId(), inventory.getPrice(), inventory.getProperty(), -1,1};
                        updateOldSumMap.put(key, item);
                    }else {
                        Object[] item = updateOldSumMap.get(key);
                        item[7]=(Integer)item[7]+1;
                        item[6]=(Integer)item[6]-1;
                        updateOldSumMap.put(key, item);
                    }

                    inventory.setLocationState("out");
                    inventory.setLocationId(inventory.getOldLocationId());
                    updateInvList.add(inventory);
                    inventory.setPhoto((StrUtil.isNotEmpty(req.getUrl()) || ObjectUtil.isNotNull(req.getUrl()))?req.getUrl():null);
                    inventory.setLocationName(cabinet.getName());
                    logInvList.add(inventory);
                }
            }

            if (updateOldSumMap.size()>0){

                List<Object[]> list =  new ArrayList<>(updateOldSumMap.values());
                List<InventorySummary> oldSummaryList = inventorySummaryMapper.selectSum(list);
                for (InventorySummary oldSum:oldSummaryList) {
                    String key= oldSum.getOrgId()+oldSum.getLocationId()+oldSum.getTypeId()+oldSum.getSizeId()+oldSum.getUnitPrice()+oldSum.getProperty();
                    Object[] objects = updateOldSumMap.get(key);
                    if (ObjectUtil.isNotNull(objects)){
                        oldSum.setOutboundNumber(oldSum.getOutboundNumber()+(Integer) objects[7]);
                        oldSum.setStockNumber(oldSum.getStockNumber()+(Integer) objects[6]);
                        oldSum.setNumber(oldSum.getOutboundNumber()+oldSum.getStockNumber());
                        oldSum.setPrice(oldSum.getUnitPrice().multiply(BigDecimal.valueOf(oldSum.getNumber())));
                    }

                }
                if (CollectionUtil.isNotEmpty(oldSummaryList)){
                    inventorySummaryService.updateBatchById(oldSummaryList);
                }
            }

            if (updateNewSumMap.size()>0){

                List<Object[]> list =  new ArrayList<>(updateNewSumMap.values());
                List<InventorySummary> newSummaryList = inventorySummaryMapper.selectSum(list);
                for (InventorySummary newSum:newSummaryList) {
                    String key= newSum.getOrgId()+newSum.getLocationId()+newSum.getTypeId()+newSum.getSizeId()+newSum.getUnitPrice()+newSum.getProperty();
                    Object[] objects = updateNewSumMap.get(key);
                    if (ObjectUtil.isNotNull(objects)){
                        newSum.setOutboundNumber(newSum.getOutboundNumber()-(Integer) objects[7]);
                        newSum.setStockNumber(newSum.getStockNumber()+(Integer) objects[6]);
                        newSum.setNumber(newSum.getOutboundNumber()+newSum.getStockNumber());
                        newSum.setPrice(newSum.getUnitPrice().multiply(BigDecimal.valueOf(newSum.getNumber())));
                    }

                }
                if (CollectionUtil.isNotEmpty(newSummaryList)){
                    inventorySummaryService.updateBatchById(newSummaryList);
                }
            }


            //更新装备
            if (CollectionUtil.isNotEmpty(updateInvList)){

                inventoryService.updateBatchById(updateInvList);

                List<String> collect1 = updateInvList.stream().map(Inventory::getEpc).collect(Collectors.toList());
                List<WarehouseInventory> list = warehouseInventoryService.list(new LambdaQueryWrapper<WarehouseInventory>().in(WarehouseInventory::getEpc, collect1));
                for (WarehouseInventory warehouseInventory:list){
                    Inventory inventory1 = updateInvList.stream().filter(inventory -> inventory.getEpc().equals(warehouseInventory.getEpc())).collect(Collectors.toList()).get(0);
                    warehouseInventory.setLocationState(inventory1.getLocationState());
//                    warehouseInventory.setB
                }
                boolean update = warehouseInventoryService.updateBatchById(list);
                System.out.println("update = " + update);
            }


            //现在的装备数据
            List<Inventory> boxBindAllEqsList=inventoryMapper.getInvEpcList(null,null, one.getId(),1);
            List<Inventory> outList = boxBindAllEqsList.stream()
                    .filter(inventory -> inventory.getLocationState().equals("out"))
                    .filter(inventory -> inventory.getBindLocationId() == null || inventory.getBindLocationId().isEmpty())
                    .collect(Collectors.toList());

            //少拿
            //如果flag=false表示没有入库装备并且在库装备中存在该装备
            boolean result=false;
            if (CollectionUtil.isNotEmpty(invlist)){
                List<String> collect1 = invlist.stream().map(Inventory::getEpc).collect(Collectors.toList());
                for (String s:inEPCList){
                    if (!collect1.contains(s)){
                        result=true;
                        break;
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(inventoryList) && !flag && result){
                UploadRFIDInnerDto uploadRFIDInnerDto = new UploadRFIDInnerDto();
                uploadRFIDInnerDto.setState("error");
                uploadRFIDInnerDto.setMsg("missTake");
                uploadRFIDInnerDto.setTime(req.getTime());
                uploadRFIDInnerDto.setBoxNum(req.getCabinetChildID());
                uploadRFIDInnerDto.setUserName(policeman.getName());
                uploadRFIDInnerDto.setIdCardNo(policeman.getIdCard());
                for (Inventory inv:inventoryList) {
                    uploadRFIDInnerDto.setEPC(ObjectUtil.isNotEmpty(uploadRFIDInnerDto.getEPC())?
                            uploadRFIDInnerDto.getEPC()+","+ inv.getEpc()
                            : inv.getEpc());
                    uploadRFIDInnerDto.setName(ObjectUtil.isNotEmpty(uploadRFIDInnerDto.getName())?
                            uploadRFIDInnerDto.getName()+","+ inv.getTypeName()+"-"+inv.getSizeName()
                            : inv.getTypeName()+"-"+inv.getSizeName());
                }
                returnList.add(uploadRFIDInnerDto);
            }
            //少还

            if ((CollectionUtil.isNotEmpty(outList) && !result && CollectionUtil.isNotEmpty(invlist) )
                    || (CollectionUtil.isNotEmpty(outList) && CollectionUtil.isNotEmpty(updateOutToInList))) {
                UploadRFIDInnerDto uploadRFIDInnerDto = new UploadRFIDInnerDto();
                uploadRFIDInnerDto.setState("error");
                uploadRFIDInnerDto.setMsg("missReturn");
                uploadRFIDInnerDto.setTime(req.getTime());
                uploadRFIDInnerDto.setBoxNum(req.getCabinetChildID());
                uploadRFIDInnerDto.setUserName(policeman.getName());
                uploadRFIDInnerDto.setIdCardNo(policeman.getIdCard());
                for (Inventory inv:outList) {
                    uploadRFIDInnerDto.setEPC(ObjectUtil.isNotEmpty(uploadRFIDInnerDto.getEPC())?
                            uploadRFIDInnerDto.getEPC()+","+ inv.getEpc()
                            : inv.getEpc());
                    uploadRFIDInnerDto.setName(ObjectUtil.isNotEmpty(uploadRFIDInnerDto.getName())?
                            uploadRFIDInnerDto.getName()+","+ inv.getTypeName()+"-"+inv.getSizeName()
                            : inv.getTypeName()+"-"+inv.getSizeName());
                }
                returnList.add(uploadRFIDInnerDto);
            }

//            List<Inventory> newBindEqsList = inventoryService.list(new LambdaQueryWrapper<Inventory>().eq(Inventory::getEqsBindState, 1).eq(Inventory::getBindLocationId, one.getId()));
            List<Inventory> newBindEqsList = inventoryMapper.getBindEqsList(one.getId());
            if (CollectionUtil.isNotEmpty(newBindEqsList)){
                UploadRFIDInnerDto uploadRFIDInnerDto = new UploadRFIDInnerDto();
                uploadRFIDInnerDto.setState("error");
                uploadRFIDInnerDto.setMsg("missReturn");
                uploadRFIDInnerDto.setTime(req.getTime());
                uploadRFIDInnerDto.setBoxNum(req.getCabinetChildID());
                uploadRFIDInnerDto.setUserName(policeman.getName());
                uploadRFIDInnerDto.setIdCardNo(policeman.getIdCard());
                for (Inventory inv:newBindEqsList) {
                    uploadRFIDInnerDto.setEPC(ObjectUtil.isNotEmpty(uploadRFIDInnerDto.getEPC())?
                            uploadRFIDInnerDto.getEPC()+","+ inv.getEpc()
                            : inv.getEpc());
                    uploadRFIDInnerDto.setName(ObjectUtil.isNotEmpty(uploadRFIDInnerDto.getName())?
                            uploadRFIDInnerDto.getName()+","+ inv.getTypeName()+"-"+inv.getSizeName()
                            : inv.getTypeName()+"-"+inv.getSizeName());
                }
                returnList.add(uploadRFIDInnerDto);
            }
            //过期
            for (Inventory inventory:boxBindAllEqsList) {
                if (ObjectUtil.isNotNull(inventory.getWarrantyPeriod())
                        && inventory.getWarrantyPeriod() !=0 && ObjectUtil.isNotNull(inventory.getProductionDate())
                        && DateTimeUtil.addMonsAfterDate(inventory.getProductionDate(),inventory.getWarrantyPeriod()).compareTo(DateTimeUtil.getCurrentDateTime())<0){
                    UploadRFIDInnerDto uploadRFIDInnerDto = new UploadRFIDInnerDto();
                    uploadRFIDInnerDto.setState("exceed");
                    uploadRFIDInnerDto.setMsg("物资"+inventory.getTypeName()+"-"+inventory.getSizeName()+"已于"+
                            DateTimeUtil.TimeDateToString(DateTimeUtil.addMonsAfterDate(inventory.getProductionDate(),inventory.getWarrantyPeriod()),"yyyy-MM-dd HH:mm:ss")+"过期");
                    uploadRFIDInnerDto.setTime(req.getTime());
                    uploadRFIDInnerDto.setBoxNum(req.getCabinetChildID());
                    uploadRFIDInnerDto.setUserName(policeman.getName());
                    uploadRFIDInnerDto.setIdCardNo(policeman.getIdCard());
                    uploadRFIDInnerDto.setEPC(inventory.getEpc());
                    uploadRFIDInnerDto.setName(inventory.getTypeName()+"-"+inventory.getSizeName());
                    returnList.add(uploadRFIDInnerDto);
                }
            }

        }

        List<InventoryReq> collect = BeanPlusUtil.toBeanList(logInvList, InventoryReq.class);
        logSummaryService.addLogSummaryByInv(collect,null,null,"normal",1,"1",policeman.getName(),pubOrg.getOrgName(), req.getCabinetID());

        //将错误信息存入表中
        List<CabinetInvErrorMsg> cabinetInvErrorMsgList=new ArrayList<>();
        for (UploadRFIDInnerDto uploadRFIDInnerDto:returnList) {
            if (uploadRFIDInnerDto.getState().equals("error") || uploadRFIDInnerDto.getState().equals("exceed")){
                CabinetInvErrorMsg cabinetInvErrorMsg = new CabinetInvErrorMsg();
                cabinetInvErrorMsg.setDevSn(cabinet.getDevSn());
                cabinetInvErrorMsg.setLocation(cabinet.getLocation());
                cabinetInvErrorMsg.setBoxNo(one.getBoxNo());
                cabinetInvErrorMsg.setBoxId(one.getId());
                cabinetInvErrorMsg.setOrgId(pubOrg.getOrgId());
                cabinetInvErrorMsg.setState(uploadRFIDInnerDto.getState());
                cabinetInvErrorMsg.setMsg(uploadRFIDInnerDto.getMsg());
                cabinetInvErrorMsg.setPushTime(DateTimeUtil.getCurrentDateTime());
                cabinetInvErrorMsg.setUserName(uploadRFIDInnerDto.getUserName());
                cabinetInvErrorMsg.setCurrentUserName(uploadRFIDInnerDto.getCurrentUserName());
                cabinetInvErrorMsg.setEpc(uploadRFIDInnerDto.getEPC());
                cabinetInvErrorMsgList.add(cabinetInvErrorMsg);
            }
        }
        if (CollectionUtil.isNotEmpty(cabinetInvErrorMsgList)){
            cabinetInvErrorMsgService.saveBatch(cabinetInvErrorMsgList);
        }

        Map<String, Object[]> oldSumMap = new HashMap<>();
        Map<String, Object[]> newSumMap = new HashMap<>();

        //错还
        if (CollectionUtil.isNotEmpty(errorReturnList) || CollectionUtil.isNotEmpty(errorReturnMoreList)){
            UploadRFIDInnerDto uploadRFIDInnerDto = new UploadRFIDInnerDto();
            uploadRFIDInnerDto.setState("error");
            uploadRFIDInnerDto.setMsg("wrongReturn");
            uploadRFIDInnerDto.setTime(req.getTime());
            uploadRFIDInnerDto.setBoxNum(req.getCabinetChildID());
            uploadRFIDInnerDto.setUserName(policeman.getName());
            uploadRFIDInnerDto.setIdCardNo(policeman.getIdCard());
            uploadRFIDInnerDto.setCurrentUserName(policeman.getName());
            for (Inventory errorInv:errorReturnList) {
                uploadRFIDInnerDto.setEPC(ObjectUtil.isNotEmpty(uploadRFIDInnerDto.getEPC())?
                        uploadRFIDInnerDto.getEPC()+","+ errorInv.getEpc()
                        : errorInv.getEpc());
                uploadRFIDInnerDto.setName(ObjectUtil.isNotEmpty(uploadRFIDInnerDto.getName())?
                        uploadRFIDInnerDto.getName()+","+ errorInv.getTypeName()+"-"+errorInv.getSizeName()+"-"+errorInv.getSizeName()+"-"+errorInv.getPoliceName()
                        : errorInv.getTypeName()+"-"+errorInv.getSizeName()+"-"+errorInv.getPoliceName());
            }
            if (CollectionUtil.isNotEmpty(errorReturnMoreList)){
                for (Inventory errorInv:errorReturnMoreList) {
                    uploadRFIDInnerDto.setEPC(ObjectUtil.isNotEmpty(uploadRFIDInnerDto.getEPC())?
                            uploadRFIDInnerDto.getEPC()+","+ errorInv.getEpc()
                            : errorInv.getEpc());
                    uploadRFIDInnerDto.setName(ObjectUtil.isNotEmpty(uploadRFIDInnerDto.getName())?
                            uploadRFIDInnerDto.getName()+","+ errorInv.getTypeName()+"-"+errorInv.getSizeName()+"-"+errorInv.getPoliceName()
                            : errorInv.getTypeName()+"-"+errorInv.getSizeName()+"-"+errorInv.getPoliceName());
                }
            }
            returnList.add(uploadRFIDInnerDto);
            //将错还的报错，但是修改在库状态和库存汇总
            
            for (Inventory inventory:errorReturnList){

                //原来装备所在地
                String key = inventory.getOrgId() + inventory.getLocationId() + inventory.getTypeId() + inventory.getSizeId() + inventory.getPrice() + inventory.getProperty();
                //存入所在地
                String key1 = inventory.getOrgId() + cabinet.getId() + inventory.getTypeId() + inventory.getSizeId() + inventory.getPrice() + inventory.getProperty();
                //item【6】表示在库
                //item【7】表示出库
                if (!oldSumMap.containsKey(key)) {

                    Object[] item = new Object[]{inventory.getOrgId(), inventory.getLocationId(), inventory.getTypeId(), inventory.getSizeId(), inventory.getPrice(), inventory.getProperty(),0, 1};
                    oldSumMap.put(key, item);
                } else {
                    Object[] item = oldSumMap.get(key);
                    item[7] = (Integer) item[7] + 1;
                    oldSumMap.put(key, item);
                }

                //item[6]表示在库
                if (!newSumMap.containsKey(key1)) {
                    Object[] item = new Object[]{inventory.getOrgId(), cabinet.getId(), inventory.getTypeId(), inventory.getSizeId(), inventory.getPrice(), inventory.getProperty(), 1, inventory.getTypeName(), inventory.getSizeName(), cabinet.getName()};
                    newSumMap.put(key1, item);
                } else {
                    Object[] item = newSumMap.get(key1);
                    item[6] = (Integer) item[6] + 1;
                    newSumMap.put(key1, item);
                }

                if (ObjectUtil.isEmpty(inventory.getBindLocationId()) || inventory.getBindLocationId().isEmpty()){

                    inventory.setBindLocationId(inventory.getOldLocationId());
                }
//                inventory.setBindLocationId(inventory.getOldLocationId());
                inventory.setLocationId(one.getId());
                inventory.setLocationState("in");
            }
            //更新装备汇总数
            //获取原装备下的汇总数据，进行更新

            if (CollectionUtil.isNotEmpty(errorReturnList)){
                Boolean aBoolean = updateInventorySummary(oldSumMap, newSumMap, pubOrg);
                System.out.println("aBoolean = " + aBoolean);

                inventoryService.updateBatchById(errorReturnList);
                List<String> epcList = errorReturnList.stream().map(Inventory::getEpc).collect(Collectors.toList());
                List<WarehouseInventory> list = warehouseInventoryService.list(new LambdaQueryWrapper<WarehouseInventory>().in(WarehouseInventory::getEpc, epcList));
                list.forEach(warehouseInventory ->{ warehouseInventory.setLocationId(one.getId());warehouseInventory.setLocationState("in");warehouseInventory.setLocationType("1");});
                boolean b = warehouseInventoryService.updateBatchById(list);
                System.out.println("b = " + b);
                System.out.println("b = " + 111);
            }


        }
        return returnList;

    }
    
    
    private Boolean updateInventorySummary(Map<String, Object[]> oldSumMap, Map<String, Object[]> newSumMap,PubOrg pubOrg){
        //更新装备汇总数
        //获取原装备下的汇总数据，进行更新
        List<Object[]> oldCollect = new ArrayList<>(oldSumMap.values());
        List<InventorySummary> oldDelateList=new ArrayList<>();
        List<InventorySummary> newAddList=new ArrayList<>();
        if (CollectionUtil.isNotEmpty(oldCollect)){

            List<InventorySummary> oldSumList = inventorySummaryMapper.selectSum(oldCollect);

            for (int i=0; i<oldSumList.size();i++) {
                InventorySummary oldSum = oldSumList.get(i);
                String key = oldSum.getOrgId() + oldSum.getLocationId()+ oldSum.getTypeId() + oldSum.getSizeId() + oldSum.getUnitPrice() + oldSum.getProperty();
                Object[] objects = oldSumMap.get(key);
                oldSum.setStockNumber(Math.max(oldSum.getStockNumber() - (Integer) objects[6],0));
                oldSum.setOutboundNumber(Math.max(oldSum.getOutboundNumber() - (Integer) objects[7],0));
                oldSum.setNumber(Math.max(oldSum.getNumber() - (Integer) objects[6]- (Integer) objects[7],0));
                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) {
                    oldDelateList.add(oldSum);
                    oldSumList.remove(oldSum);
                    i--;
                }
            }
            if (CollectionUtil.isNotEmpty(oldDelateList)) {
                inventorySummaryService.removeBatchByIds(oldDelateList);
            }
            if (CollectionUtil.isNotEmpty(oldSumList)) {
                inventorySummaryService.updateBatchById(oldSumList);
            }
        }

        //将现存箱门的装备添加在库数
        List<Object[]> newCollect =  new ArrayList<>(newSumMap.values());
        if (CollectionUtil.isNotEmpty(newCollect)){

            List<InventorySummary> newSumList = inventorySummaryMapper.selectSum(newCollect);
            for (String key:newSumMap.keySet()){
                boolean flag=false;
                Object[] obj = newSumMap.get(key);
                for (InventorySummary invSum : newSumList){
                    String cabKey= invSum.getOrgId() + invSum.getLocationId() + invSum.getTypeId() + invSum.getSizeId() + invSum.getUnitPrice() + invSum.getProperty();
                    if (key.equals(cabKey)) {
                        invSum.setNumber(invSum.getNumber() + (Integer) obj[6]);
                        invSum.setPrice(invSum.getUnitPrice().multiply(BigDecimal.valueOf(invSum.getNumber())));
                        invSum.setStockNumber(invSum.getStockNumber() + (Integer) obj[6]);
                        flag=true;
                        break;
                    }
                }
                if (!flag){
                    InventorySummary inventorySummary = inventorySummaryService.createInventorySummary(pubOrg.getOrgId(),
                            pubOrg.getOrgName(), pubOrg.getOrgCode(), (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,
                            (Integer) obj[5], 0, 0, 0, 0, "1");
                    newAddList.add(inventorySummary);
                }
            }

            if (CollectionUtil.isNotEmpty(newAddList)) {
                inventorySummaryService.saveBatch(newAddList);
            }
            if (CollectionUtil.isNotEmpty(newSumList)) {
                inventorySummaryService.updateBatchById(newSumList);
            }
        }
        return true;
    }


    private  Map<String,List<Inventory>> EqsBind(String url,List<Inventory> invlist,List<Inventory>logInvList,Cabinet cabinet,
                                                Map<String,Object[]> invSumMap,Map<String,Object[]> addSumMap,CabinetBox one,
                                                Policeman policeman,List<InventorySummary> delSumList,
                                                 List<InventorySummary> addSumList,PubOrg pubOrg,List<Inventory> errorReturnList,Boolean rebind,List<Inventory> errorReturnMoreList){

        for (int i=0;i<invlist.size();i++) {
            Inventory inventory = invlist.get(i);
            if (inventory==null){
                continue;
            }
            //原来装备所在地
            String key = inventory.getOrgId() + inventory.getLocationId() + inventory.getTypeId() + inventory.getSizeId() + inventory.getPrice() + inventory.getProperty();
            //存入所在地
            String key1 = inventory.getOrgId() + cabinet.getId() + inventory.getTypeId() + inventory.getSizeId() + inventory.getPrice() + inventory.getProperty();
            //位于仓库
            if (inventory.getLocationType().equals(0) && inventory.getLocationState().equals("in")) {
                //装备位于仓库在库
                //去数据库找领用出库装备
                Inventory one1 = inventoryService.getOne(new LambdaQueryWrapper<Inventory>()
                        .eq(Inventory::getOrgId, inventory.getOrgId())
                        .eq(Inventory::getLocationId, inventory.getLocationId())
                        .eq(Inventory::getTypeId, inventory.getTypeId())
                        .eq(Inventory::getSizeId, inventory.getSizeId())
                        .eq(Inventory::getPrice, inventory.getPrice())
                        .eq(Inventory::getProperty, inventory.getProperty())
                        .eq(Inventory::getBussinessState, "use")
                        .eq(Inventory::getLocationState, "out")
                        .last("limit 1"));
                one1.setBussinessState("normal");
                one1.setLocationState("in");
                inventoryService.updateById(one1);
                warehouseInventoryService.update(new LambdaUpdateWrapper<WarehouseInventory>()
                        .eq(WarehouseInventory::getEpc, one1.getEpc())
                        .set(WarehouseInventory::getLocationState, "in"));
                //并且把出入库记录进行替换
                LogDetail out = logDetailService.getOne(new LambdaQueryWrapper<LogDetail>()
                        .eq(LogDetail::getEpc, one1.getEpc())
                        .eq(LogDetail::getOutInState, "out")
                        .orderByDesc(LogDetail::getCreateTime)
                        .last("limit 1"));
                if (ObjectUtil.isNotNull(out)){
                    out.setEpc(inventory.getEpc());
                }
                logDetailService.updateById(out);

                //item【6】表示出库
                //insummap表示原来位置的map，用于减去库存出库数和总数
                if (!invSumMap.containsKey(key)) {

                    Object[] item = new Object[]{inventory.getOrgId(), inventory.getLocationId(), inventory.getTypeId(), inventory.getSizeId(), inventory.getPrice(), inventory.getProperty(),0, 1};
                    invSumMap.put(key, item);
                } else {
                    Object[] item = invSumMap.get(key);
                    item[7] = (Integer) item[7] + 1;
                    invSumMap.put(key, item);
                }

                //item[6]表示在库
                //addSumMap表示现在位置的map，用于添加库存在库数和总数
                if (!addSumMap.containsKey(key1)) {
                    Object[] item = new Object[]{inventory.getOrgId(), cabinet.getId(), inventory.getTypeId(), inventory.getSizeId(), inventory.getPrice(), inventory.getProperty(), 1, inventory.getTypeName(), inventory.getSizeName(), cabinet.getName()};
                    addSumMap.put(key1, item);
                } else {
                    Object[] item = addSumMap.get(key1);
                    item[6] = (Integer) item[6] + 1;
                    addSumMap.put(key1, item);
                }


                //编辑装备状态以及位置状态
                inventory.setLocationId(one.getId());
                inventory.setLocationState("in");
                inventory.setLocationType(1);
                inventory.setEqsBindState(1);
                inventory.setPoliceId(policeman.getId());
                Inventory inventory1 = new Inventory();
                BeanPlusUtil.copyProperties(inventory,inventory1);
                inventory1.setPhoto((StrUtil.isNotEmpty(url) || ObjectUtil.isNotNull(url))?url:null);
                inventory1.setLocationName(cabinet.getName());
                logInvList.add(inventory1);

            }

            //装备绑定在别的警员头上
            else if (ObjectUtil.isNotNull(inventory.getEqsBindState()) && inventory.getEqsBindState().equals(1) && !inventory.getPoliceId().equals(policeman.getId())) {
                //如果是走的归还那么提示错误归还，否则重新绑定警员关系
                if (rebind){
                    //判断bindLocationId位置状态是否为空，如果为空（或者bindLocationId与locationId一致）则表示从原箱门进行直接解绑后再进行绑定
                    //如果bindLocationId位置不为空并且不相等，则表示是从错还箱门中直接解绑并且再进行绑定关系

                    //item【6】表示在库
                    //item【7】表示出库
                    //insummap表示原来位置的map，用于减去库存出库数和总数
                    if (!invSumMap.containsKey(key) && inventory.getLocationState().equals("in")) {

                        Object[] item = new Object[]{inventory.getOrgId(), inventory.getLocationId(), inventory.getTypeId(), inventory.getSizeId(), inventory.getPrice(), inventory.getProperty(), 1,0};
                        invSumMap.put(key, item);

                    } else if (!invSumMap.containsKey(key) && inventory.getLocationState().equals("out")) {
                        Object[] item = new Object[]{inventory.getOrgId(), inventory.getLocationId(), inventory.getTypeId(), inventory.getSizeId(), inventory.getPrice(), inventory.getProperty(), 0,1};
                        invSumMap.put(key, item);
                    } else if (invSumMap.containsKey(key) && inventory.getLocationState().equals("in")){
                        Object[] item = invSumMap.get(key);
                        item[6] = (Integer) item[6] + 1;
                        invSumMap.put(key, item);
                    }else {
                        Object[] item = invSumMap.get(key);
                        item[7] = (Integer) item[7] + 1;
                        invSumMap.put(key, item);
                    }

                    //item[6]表示在库
                    //addSumMap表示现在位置的map，用于添加库存在库数和总数
                    if (!addSumMap.containsKey(key1)) {
                        Object[] item = new Object[]{inventory.getOrgId(), cabinet.getId(), inventory.getTypeId(), inventory.getSizeId(), inventory.getPrice(), inventory.getProperty(), 1, inventory.getTypeName(), inventory.getSizeName(), cabinet.getName()};
                        addSumMap.put(key1, item);
                    } else {
                        Object[] item = addSumMap.get(key1);
                        item[6] = (Integer) item[6] + 1;
                        addSumMap.put(key1, item);
                    }

                    //修改绑定关系
                    inventory.setLocationId(one.getId());
                    inventory.setLocationState("in");
                    inventory.setBussinessState("normal");
                    inventory.setLocationType(1);
                    inventory.setEqsBindState(1);
                    inventory.setPoliceId(policeman.getId());
                    inventory.setBindLocationId("");
                    Inventory inventory1 = new Inventory();
                    BeanPlusUtil.copyProperties(inventory,inventory1);
                    inventory1.setPhoto((StrUtil.isNotEmpty(url) || ObjectUtil.isNotNull(url))?url:null);
                    inventory1.setLocationName(cabinet.getName());
                    logInvList.add(inventory1);
                }else {
                    //装备绑定在别的警员下
                    //不处理，并且报错错误归还
                    //第一次错还以后bindLocationId不为空，如果数据库中的位置信息不是in，那么就默认已经是领用出去之后再次错还回来，否则则不管（第一次错还已处理，在库状态）
                    if (ObjectUtil.isEmpty(inventory.getBindLocationId()) && !inventory.getLocationState().equals("in")){
                        errorReturnList.add(inventory);
                    } 
                    //如果locationId和箱门id一致并且bindLocationId不为空，则表示是还是错还到该柜
                    else if (ObjectUtil.isNotEmpty(inventory.getBindLocationId()) && inventory.getOldLocationId().equals(one.getId()) && (inventory.getLocationState().equals("in") || inventory.getLocationState().equals("out"))) {
                        errorReturnMoreList.add(inventory);
                    }
                    //如果locationId和箱门id 不一致 并且bindLocationId不为空，则表示是从第二个错还的柜子错还到第三个，那么还是报错错误归还，将第二个柜子的数量减少，第三个箱子的数量增多
                    else if (ObjectUtil.isNotEmpty(inventory.getBindLocationId()) && !inventory.getOldLocationId().equals(one.getId()) && inventory.getLocationState().equals("out")) {
                        errorReturnList.add(inventory);
                    }
                    invlist.remove(inventory);
                    i--;
                }

            }
            //如果是在仓库外面或者是在单警柜外面未绑定状态
            else {
                //item【6】表示在库
                //item【7】表示出库
                if (!invSumMap.containsKey(key)) {

                    Object[] item = new Object[]{inventory.getOrgId(), inventory.getLocationId(), inventory.getTypeId(), inventory.getSizeId(), inventory.getPrice(), inventory.getProperty(),0, 1};
                    invSumMap.put(key, item);
                } else {
                    Object[] item = invSumMap.get(key);
                    item[7] = (Integer) item[7] + 1;
                    invSumMap.put(key, item);
                }

                //item[6]表示在库
                if (!addSumMap.containsKey(key1)) {
                    Object[] item = new Object[]{inventory.getOrgId(), cabinet.getId(), inventory.getTypeId(), inventory.getSizeId(), inventory.getPrice(), inventory.getProperty(), 1, inventory.getTypeName(), inventory.getSizeName(), cabinet.getName()};
                    addSumMap.put(key1, item);
                } else {
                    Object[] item = addSumMap.get(key1);
                    item[6] = (Integer) item[6] + 1;
                    addSumMap.put(key1, item);
                }

                inventory.setLocationId(one.getId());
                inventory.setLocationState("in");
                inventory.setBussinessState("normal");
                inventory.setLocationType(1);
                inventory.setEqsBindState(1);
                inventory.setPoliceId(policeman.getId());
                inventory.setBindLocationId("");
                Inventory inventory1 = new Inventory();
                BeanPlusUtil.copyProperties(inventory,inventory1);
                inventory1.setPhoto((StrUtil.isNotEmpty(url) || ObjectUtil.isNotNull(url))?url:null);
                inventory1.setLocationName(cabinet.getName());
                logInvList.add(inventory1);
            }
        }

        Boolean aBoolean = updateInventorySummary(invSumMap, addSumMap, pubOrg);
        System.out.println("aBoolean = " + aBoolean);
        //更新装备状态
       // invlist表示的是我现在库里面所存在的epc列表
        if (CollectionUtil.isNotEmpty(invlist)){

            inventoryService.updateBatchById(invlist);
            List<String> epcList = invlist.stream().map(Inventory::getEpc).collect(Collectors.toList());
            List<WarehouseInventory> list = warehouseInventoryService.list(new LambdaQueryWrapper<WarehouseInventory>().in(WarehouseInventory::getEpc, epcList));
            list.forEach(warehouseInventory ->{ warehouseInventory.setLocationId(one.getId());warehouseInventory.setLocationState("in");warehouseInventory.setLocationType("1");});
            warehouseInventoryService.updateBatchById(list);
        }

        Map<String,List<Inventory>> returnMap=new HashMap<>();
        returnMap.put("logInvList",logInvList);
        returnMap.put("errorReturnList",errorReturnList);
        returnMap.put("errorReturnMoreList",errorReturnMoreList);
        return returnMap;

    }




    /**
     * 上报值班柜出入库日志
     * @param req
     * @return
     */

    @Override
    @Transactional
    public Boolean addInOutlog(AddInOutLogReq req) {
        //获取单警柜主柜
        Cabinet cabinet = cabinetService.CabinetExistByNum(req.getCabinetMainNo());
        List<String> epcList=new ArrayList<>();
        List<String> boxList=new ArrayList<>();

        for (AddInOutLogReq.LogListReq logReq:req.getLogList()) {
            //获取到去重的epcList并且我需要最新的前端传递包含箱门号和主柜号的List为后面判断进行一个过滤
            if (!epcList.contains(logReq.getEpc())){
                epcList.add(logReq.getEpc());
            }
            //获取到去重的boxList
            if (!boxList.contains(logReq.getBoxNum())){
                boxList.add(logReq.getBoxNum());
            }
        }
        //根据箱门id和单警柜信息获取箱门的所有信息
        if (CollectionUtil.isNotEmpty(boxList)){
            List<CabinetBox> boxInfoList=cabinetMapper.getBoxIdList(cabinet.getId(),boxList);
            if (CollectionUtil.isEmpty(boxInfoList)){
                throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"箱门不存在");
            }
        }
        //将日志进行添加
        List<CabinetOutinlog> collect = req.getLogList().stream().map(logListReq -> {
            CabinetOutinlog cabinetOutinlog = new CabinetOutinlog();
            BeanPlusUtil.copyProperties(logListReq, cabinetOutinlog);
            cabinetOutinlog.setOperationTime(ObjectUtil.isNotEmpty(logListReq.getTime())?DateTimeUtil.TimeStringToDate(logListReq.getTime(),"yyyy/MM/dd HH:mm:ss"):DateTimeUtil.getCurrentDateTime());
            cabinetOutinlog.setPushTime(DateTimeUtil.getCurrentDateTime());
            cabinetOutinlog.setCreateTime(DateTimeUtil.getCurrentDateTime());
            cabinetOutinlog.setOrgId(cabinet.getOrgIdInt());
            cabinetOutinlog.setDevSn(cabinet.getDevSn());
            cabinetOutinlog.setBoxNo(Integer.valueOf(logListReq.getBoxNum()));
            return cabinetOutinlog;
        }).collect(Collectors.toList());

        return cabinetOutinlogService.saveBatch(collect);
    }

//    @Override
//    @Transactional
//    public Boolean addInOutlog(AddInOutLogReq req) {
//        //获取单警柜主柜
//        Cabinet cabinet = cabinetService.CabinetExistByNum(req.getCabinetMainNo());
//        List<String> epcList=new ArrayList<>();
//        List<String> boxList=new ArrayList<>();
//        Map<String, AddInOutLogReq.LogListReq> epcLogMap = new HashMap<>();
//
//        for (AddInOutLogReq.LogListReq logReq:req.getLogList()) {
//            //获取到去重的epcList并且我需要最新的前端传递包含箱门号和主柜号的List为后面判断进行一个过滤
//            if (!epcList.contains(logReq.getEpc())){
//                epcList.add(logReq.getEpc());
//            }
//            //获取到去重的boxList
//            if (!boxList.contains(logReq.getBoxNum())){
//                boxList.add(logReq.getBoxNum());
//            }
//            if (epcLogMap.containsKey(logReq.getEpc())) {
//                if (DateTimeUtil.TimeStringToDate(logReq.getTime(),"yyyy/MM/dd HH:mm:ss").after(DateTimeUtil.TimeStringToDate(epcLogMap.get(logReq.getEpc()).getTime() ,"yyyy/MM/dd HH:mm:ss"))) {
//                    epcLogMap.put(logReq.getEpc(), logReq);
//                }
//            } else {
//                epcLogMap.put(logReq.getEpc(), logReq);
//            }
//        }
//        //根据箱门id和单警柜信息获取箱门的所有信息
//        List<CabinetBox> boxInfoList=new ArrayList<>();
//        if (CollectionUtil.isNotEmpty(boxList)){
//            boxInfoList=cabinetMapper.getBoxIdList(cabinet.getId(),boxList);
//        }
//
//        //根据前端传递的epcList获取绑定的装备
//        List<Inventory> invList=inventoryMapper.getInvEpcList(null,epcList,null,1);
//        //获取最新的操作时间来修改装备的状态
//        List<AddInOutLogReq.LogListReq> lasterLogList=new ArrayList<>(epcLogMap.values());
//
//        for (AddInOutLogReq.LogListReq invLogReq:lasterLogList){
//            for (Inventory inventory:invList){
//                if (inventory.getEpc().equals(invLogReq.getEpc())){
//                    //判断数据位置是否一致，如果一致则判断状态是否一致
//                    List<CabinetBox> collect = boxInfoList.stream().filter(cabinetBox -> cabinetBox.getBoxNo().toString().equals(invLogReq.getBoxNum())).collect(Collectors.toList());
//                    if (CollectionUtil.isEmpty(collect)){
//                        throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"箱门不存在");
//                    }
//                    String boxId= collect.get(0).getId();
//                    //如果说箱门位置信息相同,出入库状态相同
//                    if (boxId.equals(inventory.getOldLocationId()) && invLogReq.getState().equals(inventory.getLocationState())){
//                        break;
//                    }
//                    //如果箱门位置信息相同，出入库状态不同，则进行修改在库数和出库数，装备总数不变
//                    else if (boxId.equals(inventory.getOldLocationId()) && ! invLogReq.getState().equals(inventory.getLocationState())) {
//
//                        break;
//                    }
//                    //如果位置信息不相同，并且状态是error（公共柜模式存在错还，不处理）
//                    else if (!boxId.equals(inventory.getOldLocationId()) && invLogReq.getState().equals("error")) {
//                        break;
//                    }
//                    //如果位置信息不相同，状态不是error,则直接替换，将原来的装备对应的库存根据原来状态进行减少，装备总数也进行减少；将现在的装备根据现在的状态进行增加，装备总数也增加
//                    else if (!boxId.equals(inventory.getOldLocationId()) && !invLogReq.getState().equals("error")) {
//
//                        break;
//                    }
//                }
//            }
//        }
//
//        List<InventoryReq> collect = BeanPlusUtil.toBeanList(invList, InventoryReq.class);
//        //将日志进行添加
//        for (AddInOutLogReq.LogListReq logReq:req.getLogList() ) {
//            for (InventoryReq invReq:collect) {
//                if (invReq.getEpc().equals(logReq.getEpc())){
//                    invReq.setPhoto(logReq.getPhoto());
//                    invReq.setCreateTime(DateTimeUtil.TimeStringToDate(logReq.getTime(),"yyyy/MM/dd HH:mm:ss"));
//                    invReq.setLocationState(logReq.getState());
//                    invReq.setCreateUser(logReq.getUserName());
//                    invReq.setUpdateUser(logReq.getUserName());
//                    List<CabinetBox> collect1 = boxIdList.stream().filter(cabinetBox -> cabinetBox.getBoxNo().toString().equals(logReq.getBoxNum())).collect(Collectors.toList());
//                    invReq.setLocationId(collect1.get(0).getId());
//                }
//            }
//        }
//        if (CollectionUtil.isNotEmpty(collect)){
//
//            return logSummaryService.addLogSummaryByInv(collect,null,null,"normal",1,"1",null,collect.get(0).getOrgName(),req.getCabinetMainNo());
//        }
//        return true;
//    }

    /**
     * 人员绑定装备（跟单景柜无关，单警柜只是识别epc的跳板）
     * @param req
     * @return
     */
    @Override
    @Transactional
    public Object bindingInventoryByPoliceId(BindingInventoryByPoliceIdReq req) {
        List<String> rfidList = req.getRFIDList();
        if (CollectionUtil.isNotEmpty(rfidList)){
            throw new JYZBAppException(CabinetBoxExceptionEnum.BOXS_ISNOT_EXISTS,"epcList不能为空");
        }
        List<Inventory> list = inventoryMapper.getInvEpcList(null,rfidList,null,null);
        List<String> epcList = list.stream().map(Inventory::getEpc).collect(Collectors.toList());

        for (String epc:rfidList) {
            if (!epcList.contains(epc)){
                BindingInventoryByPoliceIdDto dto = new BindingInventoryByPoliceIdDto();
                dto.setEquipmentName(null);
                dto.setErrEpc(epc);
                dto.setErrMsg("无效物资");
                return dto;
            }
        }
        //绑定装备
        if (req.getIsBind()){
            if (ObjectUtil.isNull(req.getPoliceId()) || ObjectUtil.isEmpty(req.getPoliceId())){
                throw new JYZBAppException(CabinetV2ExceptionEnum.PARAM_ERROR,"警员id不能为空");
            }
            Policeman policeman = policemanService.getById(req.getPoliceId());
            if (ObjectUtil.isNull(policeman)){
                throw new JYZBAppException(CabinetV2ExceptionEnum.POLICE_INFO_NOT_EXIT);
            }
            for (String epc:rfidList) {
                Inventory inv = list.stream().filter(inventory -> inventory.getEpc().equals(epc)).findFirst().get();
                if (inv.getState().equals("broken")) {
                    BindingInventoryByPoliceIdDto dto = new BindingInventoryByPoliceIdDto();
                    dto.setEquipmentName(inv.getTypeName());
                    dto.setErrEpc(epc);
                    dto.setErrMsg("物资已报废");
                    return dto;
                }
                if (ObjectUtil.isNotNull(inv.getPoliceId())) {
                    BindingInventoryByPoliceIdDto dto = new BindingInventoryByPoliceIdDto();
                    dto.setEquipmentName(inv.getTypeName());
                    dto.setErrEpc(epc);
                    dto.setErrMsg("物资已被绑定");
                    return dto;
                }
                inv.setPoliceId(policeman.getId());
            }
            inventoryService.updateBatchById(list);
        }
        //解绑装备
        else {
            //更新绑定关系
            list.forEach(inventory -> {inventory.setPoliceId("0");inventory.setLocationId(inventory.getOldLocationId());});
            inventoryService.updateBatchById(list);

        }
        List<BindingInventoryByPoliceIdDto> collect = list.stream().map(inventory -> {
            BindingInventoryByPoliceIdDto dto = new BindingInventoryByPoliceIdDto();
            dto.setSuccessEpc(inventory.getEpc());
            dto.setEquipmentName(inventory.getTypeName());
            return dto;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 上传日志文件
     * @param req
     * @return
     */
    @Override
    @Transactional
    public Boolean uploadLog(UploadLogReq req) {
        //如果存在，直接删除之后再进行添加
        String name = req.getLogFile().getName();
        System.out.println("name = " + name);
        String originalFilename = req.getLogFile().getOriginalFilename();
        System.out.println("originalFilename = " + originalFilename);
        List<SysFileInfo> list = sysFileInfoService.list(new LambdaQueryWrapper<SysFileInfo>().eq(SysFileInfo::getFileOriginName, originalFilename));
        if (CollectionUtil.isNotEmpty(list)){
            sysFileInfoService.removeBatchByIds(list);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
        sdf.setLenient(false);
        Date time;
        if (ObjectUtil.isNotEmpty(req.getDirectoy())){
            try {
                time = sdf.parse(req.getDirectoy());
            } catch (ParseException e) {
                throw new JYZBAppException(CabinetV2ExceptionEnum.FILE_UPLOAD_ERROR,"日期错误");
            }
        }else {
            throw new JYZBAppException(CabinetV2ExceptionEnum.FILE_UPLOAD_ERROR,"日期错误");
        }
        try {
            if (req.getId() == null || req.getId().isEmpty()) {
                throw new JYZBAppException(CabinetV2ExceptionEnum.FILE_UPLOAD_ERROR,"id为空");
            } else if (req.getType() != 0 && req.getType() != 1) {
                throw new JYZBAppException(CabinetV2ExceptionEnum.FILE_UPLOAD_ERROR,"类型错误");
            } else if (req.getLogFile() == null) {
                throw new JYZBAppException(CabinetV2ExceptionEnum.FILE_UPLOAD_ERROR,"文件为空");
            } else if (req.getLogFile().getSize() > 1024 * 1024 * 3) {
                throw new JYZBAppException(CabinetV2ExceptionEnum.FILE_UPLOAD_ERROR,"文件过大");
            } else {
                String entityType = (req.getType() == 0) ? "Channel" : "Cabinet";
                SysFileInfoReq sysFileInfoReq = new SysFileInfoReq();
                sysFileInfoReq.setFileBucket("jyzb");
                sysFileInfoReq.setFileObjectName("LogFile/"+entityType+"/"+req.getId().replace("-", "")+"/"+req.getDirectoy()+"/");
                sysFileInfoReq.setFileLocation(3);
                SysFileInfoResp sysFileInfoResp = sysFileInfoService.uploadFile(req.getLogFile(), sysFileInfoReq);
                System.out.println("sysFileInfoResp = " + sysFileInfoResp);
                return true;
            }
        } catch (Exception ex) {
            throw new JYZBAppException(CabinetV2ExceptionEnum.FILE_UPLOAD_ERROR,"文件上传失败");
        }
    }

    /**
     * 上传图片文件
     * @param req
     * @return
     */
    @Override
    public Boolean uploadPic(UploadPicReq req) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
        sdf.setLenient(false);
        Date time;
        Cabinet cabinet=null;
        Warehouse warehouse=null;
        if (ObjectUtil.isNotEmpty(req.getDirectoy())){
            try {
                time = sdf.parse(req.getDirectoy());
            } catch (ParseException e) {
                throw new JYZBAppException(CabinetV2ExceptionEnum.FILE_UPLOAD_ERROR,"日期错误");
            }
        }else {
            throw new JYZBAppException(CabinetV2ExceptionEnum.FILE_UPLOAD_ERROR,"日期错误");
        }
        try {
            if (req.getId() == null || req.getId().isEmpty()) {
                throw new JYZBAppException(CabinetV2ExceptionEnum.FILE_UPLOAD_ERROR,"id为空");
            } else if (req.getType() != 0 && req.getType() != 1) {
                throw new JYZBAppException(CabinetV2ExceptionEnum.FILE_UPLOAD_ERROR,"类型错误");
            } else if (req.getPicture() == null) {
                throw new JYZBAppException(CabinetV2ExceptionEnum.FILE_UPLOAD_ERROR,"文件为空");
            } else if (req.getPicture().getSize() > 1024 * 1024 * 3) {
                throw new JYZBAppException(CabinetV2ExceptionEnum.FILE_UPLOAD_ERROR,"文件过大");
            }else if (req.getType()==1){
                cabinet = cabinetService.getOne(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getDevSn, req.getId()));
                if (cabinet==null){
                    throw new JYZBAppException(CabinetV2ExceptionEnum.FILE_UPLOAD_ERROR,"id错误，单警柜不存在");
                }
            } else if (req.getType()==0) {
                warehouse = warehouseService.getById(req.getId());
                if (warehouse==null){
                    throw new JYZBAppException(CabinetV2ExceptionEnum.FILE_UPLOAD_ERROR,"id错误，仓库不存在");
                }
            }
            String entityType = (req.getType() == 0) ? "Channel" : "Cabinet";

//            if (req.getPicture().getContentType().contains("image")) {
            SysFileInfoReq sysFileInfoReq = new SysFileInfoReq();
            sysFileInfoReq.setFileBucket("jyzb");
            sysFileInfoReq.setFileObjectName("SnapPic/"+entityType+"/"+req.getId().replace("-", "")+"/"+req.getDirectoy()+"/");
            sysFileInfoReq.setFileLocation(3);
            SysFileInfoResp sysFileInfoResp = sysFileInfoService.uploadFile(req.getPicture(), sysFileInfoReq);
            String url="/SnapPic/"+entityType+"/"+req.getId().replace("-", "")+"/"+req.getDirectoy()+"/"+ sysFileInfoResp.getFileOriginName();
//            }else {
//                throw new JYZBAppException(CabinetV2ExceptionEnum.FILE_UPLOAD_ERROR,"unsupport media type");
//            }

            List<LogSummary> list= logSummaryMapper.getListByPrictureUrl(url);
            List<CabinetOutinlog> logList= cabinetOutinlogService.getListByPrictureUrl(url);

//            List<LogSummary> list = logSummaryService.list(new LambdaQueryWrapper<LogSummary>().eq(LogSummary::getPicture, url));


            if (CollectionUtil.isNotEmpty(list)){
                list.forEach(logSummary -> logSummary.setPicture(sysFileInfoResp.getAccessUrl()));
                logSummaryService.updateBatchById(list);
            }
            if (CollectionUtil.isNotEmpty(logList)){
                logList.forEach(cabinetOutinlog -> cabinetOutinlog.setPhoto(sysFileInfoResp.getAccessUrl()));
                cabinetOutinlogService.updateBatchById(logList);
            }

        } catch (Exception ex) {
            throw new JYZBAppException(CabinetV2ExceptionEnum.FILE_UPLOAD_ERROR,ex.getMessage());
        }
        return true;
    }

    /**
     * 更新成功修改设备版本号
     * @param req
     * @return
     */
    @Override
    public Boolean UpdateCabinetVersion(LastUpAndUpgradeReq req) {
        Cabinet cabinet = cabinetService.CabinetExistByNum(req.getServerNum());
        cabinet.setVersion(req.getVersion());
        return cabinetService.updateById(cabinet);
    }

    @Override
    public PageResult<CabinetOutinlog> getCabinetOutInLogPage(CabinetOutinlogReq req) {
        return cabinetOutinlogService.getCabinetOutInLogPage(req);
    }


}
