package com.junmp.jyzb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.junmp.jyzb.api.bean.PeriodAndDateDto;
import com.junmp.jyzb.api.bean.dto.*;
import com.junmp.jyzb.api.bean.dto.FetchingDataDto.EquipmentDto;
import com.junmp.jyzb.api.bean.query.*;
import com.junmp.jyzb.api.bean.req.BatchEditingInvsReq;
import com.junmp.jyzb.api.bean.req.EquipmentBindReq;
import com.junmp.jyzb.api.bean.req.RabbitMqOrderReq;
import com.junmp.jyzb.api.bean.vo.InventoryVo;
import com.junmp.jyzb.api.exception.enums.CabinetBoxExceptionEnum;
import com.junmp.jyzb.api.exception.enums.CabinetExceptionEnum;
import com.junmp.jyzb.api.exception.enums.InventoryExceptionEnum;
import com.junmp.jyzb.entity.*;

import com.junmp.jyzb.mapper.InventorySummaryMapper;
import com.junmp.jyzb.mapper.LogSummaryMapper;
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.common.util.HttpServletUtil;
import com.junmp.v2.db.api.factory.PageFactory;
import com.junmp.v2.db.api.factory.PageResultFactory;
import com.junmp.v2.db.api.page.PageResult;
import com.junmp.v2.dict.entity.SysDictItem;
import com.junmp.v2.dict.service.SysDictItemService;
import com.junmp.v2.office.api.OfficeExcelApi;
import com.junmp.v2.office.api.bean.ExcelExportParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.junmp.jyzb.mapper.InventoryMapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class InventoryServiceImpl extends ServiceImpl<InventoryMapper, Inventory> implements InventoryService {
    @Resource
    private InventoryMapper inventoryMapper;
    @Resource
    private EquipmentTypeService equipmentTypeService;
    @Resource
    private EquipmentSizeService equipmentSizeService;
    @Resource
    private WarehouseService warehouseService;
    @Resource
    private PubOrgService PubOrgService;

    @Resource
    private CabinetBoxService cabinetBoxService;

    @Resource
    private PubOrgService pubOrgService;

    @Resource
    private CabinetService cabinetService;

    @Resource
    private SupplierService supplierService;
    @Resource
    private ShelfService shelfService;
    @Resource
    private WarehouseAreaService warehouseAreaService;

    @Resource
    private LogSummaryService logSummaryService;
    @Resource
    private LogDetailService logDetailService;

    @Resource
    private OfficeExcelApi officeExcelApi;

    @Resource
    private OrderMainService orderMainService;

    @Resource
    private InventorySummaryService inventorySummaryService;

    @Resource
    private LogSummaryMapper logSummaryMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private RabbitAdmin rabbitAdmin;

    @Resource
    private SysDictItemService sysDictItemService;

    @Resource
    private InventorySummaryMapper inventorySummaryMapper;




    //根据装备id查询出装备的详细信息
    @Override
    public InventoryDto getInventoryDetail(InventoryReq req) {
        Inventory inventory = InventoryExist(req.getId());
        InventoryDto bean = BeanUtil.toBean(inventory, InventoryDto.class);
        // 查询与库存表关联的其他数据
        String orgName= PubOrgService.getById(inventory.getOrgId()).getOrgName();
        String TypeName = equipmentTypeService.getById(inventory.getTypeId()).getName();
        String SizeName = equipmentSizeService.getById(inventory.getSizeId()).getName();
        // 创建并填充对象
        bean.setSizeName(SizeName);
        bean.setTypeName(TypeName);
        bean.setOrgName(orgName);
        return bean;
    }



    //设置仓库库存数量（总数，在库数，出库数，价格）
    @Override
    public boolean UpdateWarehouseInsNum(WarehouseReq req) {
        Warehouse warehouse = warehouseService.WarehoustExist(req.getId());
        boolean b = warehouseService.SetInventoryInfo(warehouse.getId());
        return b;
    }

    //设置单警柜库存数量（总数，在库数，出库数，价格）
    @Override
    public boolean UpdateCabinetInsNum(CabinetReq req) {
        Cabinet cabinet = cabinetService.CabinetExist(req.getId());
        boolean b = cabinetService.SetInventoryInfo(cabinet.getId());
        return b;
    }

    //装备绑定箱门
    @Override
    public boolean InventoryBind(EquipmentBindReq req) {
        //判断箱门是否存在
        CabinetBox cabinetBox = cabinetBoxService.CabinetBoxExist(req.getCabinetBoxId());
        if (Objects.isNull(cabinetBox)){
            throw new ServiceException(CabinetBoxExceptionEnum.CABINETBOX_ISNOT_EXISTS);
        }
        List<String> equipmentList = req.getEquipmentList();
        if (equipmentList.size()==0){
            throw new ServiceException(CabinetExceptionEnum.PARAMETER_ERROR);
        }
        List<Inventory> inventoryList=new ArrayList<>();
        for (String id: equipmentList) {
            Inventory inventory = getById(id);
            //locationId:根据单警柜的不同存放的内容不同，单警柜存放箱门id，仓库存放仓库id
            inventory.setLocationId(req.getCabinetBoxId());
            inventoryList.add(inventory);
        }
        return updateBatchById(inventoryList);
    }

    //根据Epc查询装备信息
    @Override
    public List<InventoryDto> GetInvInfoByEpc(InventoryReq req) {
        //判断传入的是否为空
        List<String> epcList = req.getEpcList();
        if (epcList.size()==0){
            throw new ServiceException(CabinetExceptionEnum.PARAMETER_ERROR);
        }
        List<InventoryDto> inventoryDtoList=inventoryMapper.GetInvInfoByEpc(epcList);

        return inventoryDtoList;
    }


    //查询箱门（cabinetBox下）所有装备简要信息列表（传递cabinetBoxId）
    @Override
    public List<EqsBriefDto> searchEqsByBoxId(CabinetBoxReq req) {
        List<Inventory> list = list(new LambdaQueryWrapper<Inventory>()
                .eq(Inventory::getLocationId, req.getId())
                .orderByDesc(Inventory::getTypeId)
                .orderByDesc(Inventory::getSizeId));
        if (list.size()==0){
            throw new ServiceException(CabinetBoxExceptionEnum.CABINETBOX_ISNOT_EXISTS);
        }
        List<EqsBriefDto> eqsBriefDtoList=new ArrayList<>();
        Iterator<Inventory> iterator = list.iterator();
        while (iterator.hasNext()){
            Inventory next = iterator.next();
            EqsBriefDto eqsBriefDto = new EqsBriefDto();
            BeanPlusUtil.copyProperties(next,eqsBriefDto);
            Map<String, String> map = setNames( eqsBriefDto.getTypeId(),eqsBriefDto.getSizeId(), eqsBriefDto.getSupplierId());
            //设置typeName
            eqsBriefDto.setTypeName(map.get("typeName"));
            //设置sizeName
            eqsBriefDto.setSizeName(map.get("sizeName"));
            //如果有供应商id的前提下，设置supplierName
            if (ObjectUtil.isNotNull(eqsBriefDto.getSupplierId())){
                eqsBriefDto.setSupplierName(map.get("supplierName"));
            }
            eqsBriefDtoList.add(eqsBriefDto);
        }
        return eqsBriefDtoList;
    }

    //查询箱门（cabinetBox下）所有装备简要信息列表page（传递cabinetBoxId）
    @Override
    public PageResult<EqsBriefDto> searchEqsByBoxIdPage(CabinetBoxReq req) {
//        List<EqsBriefDto> eqsBriefDtoList = searchEqsByBoxId(req);
        LambdaQueryWrapper<Inventory> eq = new LambdaQueryWrapper<Inventory>()
                .eq(Inventory::getLocationId, req.getId())
                .orderByDesc(Inventory::getTypeId)
                .orderByDesc(Inventory::getSizeId);
        List<Inventory> list = list(eq);
        long size = list.size();
        Page<Inventory> page = page(PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize()), eq);
        List<Inventory> records = page.getRecords();
        List<EqsBriefDto> eqsBriefDtoList=records.parallelStream()
                .map(inventory -> {
            EqsBriefDto eqsBriefDto = new EqsBriefDto();
            BeanPlusUtil.copyProperties(inventory,eqsBriefDto);
            Map<String, String> map = setNames(eqsBriefDto.getTypeId(), eqsBriefDto.getSizeId(), eqsBriefDto.getSupplierId());
            //设置typeName
            eqsBriefDto.setTypeName(map.get("typeName"));
            //设置sizeName
            eqsBriefDto.setSizeName(map.get("sizeName"));
            //如果有供应商id的前提下，设置supplierName
            if (ObjectUtil.isNotNull(eqsBriefDto.getSupplierId())){
                eqsBriefDto.setSupplierName(map.get("supplierName"));
            }
            return eqsBriefDto;
        }).collect(Collectors.toList());
        Page<EqsBriefDto> page1 = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        page1.setRecords(eqsBriefDtoList);
        page1.setTotal(size);
        return PageResultFactory.createPageResult(page1);
    }

    //根据条件查询仓库/单警柜下的所有装备信息

    public PageResult<InventoryDto> GetDetailByTerms1(InventoryReq req) {
        //判断组织机构是否存在
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        //根据条件查询仓库下的所有装备
        LambdaQueryWrapper<Inventory> eq = new LambdaQueryWrapper<Inventory>()
                .eq(Inventory::getOrgId, req.getOrgId())
                .eq(ObjectUtil.isNotNull(req.getLocationType()),Inventory::getLocationType, req.getLocationType())
                .eq(ObjectUtil.isNotNull(req.getLocationState()) && !req.getLocationState().trim().isEmpty(), Inventory::getLocationState, req.getLocationState())
                .eq(ObjectUtil.isNotNull(req.getBussinessState()) && !req.getBussinessState().trim().isEmpty(), Inventory::getBussinessState, req.getBussinessState())
                .eq(ObjectUtil.isNotNull(req.getTermState()), Inventory::getTermState, req.getTermState())
                .eq(ObjectUtil.isNotNull(req.getSizeId()) && !req.getSizeId().trim().isEmpty(),Inventory::getSizeId,req.getSizeId())
                .eq(ObjectUtil.isNotNull(req.getTypeId()) && !req.getTypeId().trim().isEmpty(),Inventory::getTypeId,req.getTypeId())
                .eq(ObjectUtil.isNotNull(req.getPrice()),Inventory::getPrice,req.getPrice());
        if (req.getLocationType().equals("0")){
            eq.eq(ObjectUtil.isNotNull(req.getLocationId()) && !req.getLocationId().trim().isEmpty(), Inventory::getLocationId, req.getLocationId());
        }else {
            List<CabinetBox> list = cabinetBoxService.list(new LambdaQueryWrapper<CabinetBox>().eq(CabinetBox::getCabinetId, req.getLocationId()));
            Set<String> cabinetList=list.stream().map(CabinetBox::getId).collect(Collectors.toSet());
            eq.in(Inventory::getLocationId,cabinetList);
        }
        long size = list(eq).size();
        Page<Inventory> page = page(PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize()), eq);
        List<Inventory> records = page.getRecords();
        List<InventoryDto> collect = records.parallelStream()
                .map(inventory -> {
                    InventoryDto inventoryDto = new InventoryDto();
                    BeanPlusUtil.copyProperties(inventory, inventoryDto);
                    Map<String, String> map = setNames(inventory.getTypeId(), inventory.getSizeId(), inventory.getSupplierId());
                    //设置typeName
                    inventoryDto.setTypeName(map.get("typeName"));
                    //设置sizeName
                    inventoryDto.setSizeName(map.get("sizeName"));
                    //查询图片并返回
                    inventoryDto.setPhoto(map.get("photo"));
                    //如果有供应商id的前提下，设置supplierName
                    if (ObjectUtil.isNotNull(inventory.getSupplierId())) {
                        inventoryDto.setSupplierName(map.get("supplierName"));
                    }

                    inventoryDto.setOrgName(pubOrg.getOrgName());

                    return inventoryDto;
                }).collect(Collectors.toList());
        Page<InventoryDto> page1 = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        page1.setRecords(collect);
        page1.setTotal(size);
        return PageResultFactory.createPageResult(page1);
    }


    public PageResult<InventoryDto> GetDetailByTerms(InventoryReq req) {
//        //根据条件查询仓库下的所有装备
        int size=inventorySummaryMapper.selectSumByItemsCount(req);
        List<InventoryDto> returnList=inventorySummaryMapper.GetDetailByTerms(req,(req.getPageNo()-1)*req.getPageSize(),req.getPageSize());
        Page<InventoryDto> page1 = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        page1.setRecords(returnList);
        page1.setTotal(size);
        return PageResultFactory.createPageResult(page1);
    }
    //批量进行调整
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public boolean BatchEditingInvsInfo(BatchEditingInvsReq req) {
//        //查询inventory表中数据，对响应数据进行修改
//        //判断是对整一类的装备进行修改还是说对个别几个装备进行批量修改
////        if (req.getInventoryIdList().size()!=0){
//        List<InventorySummary> delList=new ArrayList<>();
//        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
//        int size = req.getInventoryIdList().size();
//        List<Object[]> searchItem=new ArrayList<>();
//        if (req.getPrice().compareTo(req.getOriginalPrice())!=0){
//            Object[] item=new Object[]{req.getOrgId(),req.getLocationId(),req.getTypeId(),req.getSizeId(),req.getPrice()};
//            Object[] item1=new Object[]{req.getOrgId(),req.getLocationId(),req.getTypeId(),req.getSizeId(),req.getOriginalPrice()};
//            searchItem.add(item);
//            searchItem.add(item1);
//            List<InventorySummary> inventorySummaryList = inventorySummaryMapper.selectSumByItems(searchItem);
//            if (inventorySummaryList.size()==1){//等于1表示他修改后的单价的汇总信息没有，需要新增一条
//                InventorySummary is = inventorySummaryList.get(0);
//                is.setStockNumber(Math.max(is.getStockNumber()-size,0));
//                is.setNumber(Math.max(is.getNumber()-size,0));
//                is.setPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getNumber())));
//                if (is.getNumber()==0 && is.getStockNumber()==0 && is.getOutboundNumber()==0 && is.getDestructionNumber()==0){
//                    delList.add(is);
//                }
//                //新增一条数据
//                InventorySummary inventorySummary = new InventorySummary();
//                BeanPlusUtil.copyProperties(req,inventorySummary);
//                inventorySummary.setValuekey(pubOrg.getOrgCode()+req.getLocationId()+req.getTypeId()+req.getSizeId()+req.getPrice());
//                inventorySummary.setOrgName(pubOrg.getOrgName());
//                inventorySummary.setOrgCode(pubOrg.getOrgCode());
//                inventorySummary.setNumber(size);
//                inventorySummary.setStockNumber(size);
//                inventorySummary.setOutboundNumber(0);
//                inventorySummary.setLocationType("0");
//                inventorySummary.setUnitPrice(req.getPrice());
//                inventorySummary.setPrice(req.getOriginalPrice().multiply(BigDecimal.valueOf(size)));
//                inventorySummary.setDestructionPrice(BigDecimal.ZERO);
//                inventorySummary.setBrokenNumberPrice(BigDecimal.ZERO);
//                inventorySummary.setExpireNumberPrice(BigDecimal.ZERO);
//                inventorySummary.setBrokenNumber(0);
//                inventorySummary.setExpireNumber(0);
//                inventorySummary.setDestructionNumber(0);
//                inventorySummary.setNearBrokenNumber(0);
//                inventorySummaryService.save(inventorySummary);
//                inventorySummaryService.updateBatchById(inventorySummaryList);
//            }else {
//                for (InventorySummary is:inventorySummaryList) {
//                    if (is.getUnitPrice().compareTo(req.getOriginalPrice())==0){//如果单价和修改前的价格一致
//                        is.setStockNumber(is.getStockNumber()-size);
//                        is.setNumber(is.getNumber()-size);
//                        is.setPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getNumber())));
//                        if (is.getNumber()==0 && is.getStockNumber()==0 && is.getOutboundNumber()==0 && is.getDestructionNumber()==0){
//                            delList.add(is);
//                        }
//                    }else {//单价和修改后的价格一致
//                        is.setStockNumber(is.getStockNumber()+size);
//                        is.setNumber(is.getNumber()+size);
//                        is.setPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getNumber())));
//                    }
//                }
//
//                inventorySummaryService.updateBatchById(inventorySummaryList);
//            }
//            if (CollectionUtil.isNotEmpty(delList)){
//                inventorySummaryService.removeBatchByIds(delList);
//            }
//        }
//
//            List<Inventory> list = list(new LambdaQueryWrapper<Inventory>().in(Inventory::getId, req.getInventoryIdList()));
//            if (list.size()==0){
//                throw new ServiceException(CabinetExceptionEnum.PARAMETER_ERROR);
//            }else {
//                //批量修改个别装备
////                List<Inventory> collect = list.stream().map(inventory -> {
////                    BeanPlusUtil.copyProperties(req,inventory );
////                    if (ObjectUtil.isNotNull(req.getShelfColumns()) && !req.getShelfColumns().toString().trim().isEmpty()
////                            && ObjectUtil.isNotNull(req.getShelfRanges()) && !req.getShelfRanges().toString().trim().isEmpty()
////                            && ObjectUtil.isNotNull(req.getShelfRows()) && !req.getShelfRows().toString().trim().isEmpty()) {
////                        inventory.setShelfLocation(req.getShelfRanges() + "/" + req.getShelfColumns() + "/" + req.getShelfRows());
////                    }
////                    return inventory;
////                }).collect(Collectors.toList());
////                List<Inventory> list1 = list(new LambdaQueryWrapper<Inventory>().eq(Inventory::getId, list));
//                List<Inventory> collect = list.stream().map(inventory -> {
//                    inventory.setWarrantyPeriod(req.getWarrantyPeriod());
//                    inventory.setMaintenancePeriod(req.getMaintenancePeriod());
//                    inventory.setPrice(req.getPrice());
//                    return inventory;
//                }).collect(Collectors.toList());
//                return updateBatchById(collect);
//            }
//
////        }
////        else {
////            List<Inventory> list = list(createWrapper(req));
////            //直接将一类的数据进行修改
////            List<Inventory> collect = list.stream().map(inventory -> {
////                BeanPlusUtil.copyProperties(req, inventory);
////                if (ObjectUtil.isNotNull(req.getShelfColumns()) && !req.getShelfColumns().toString().trim().isEmpty()
////                        && ObjectUtil.isNotNull(req.getShelfRanges()) && !req.getShelfRanges().toString().trim().isEmpty()
////                        && ObjectUtil.isNotNull(req.getShelfRows()) && !req.getShelfRows().toString().trim().isEmpty()) {
////                    inventory.setShelfLocation(req.getShelfRanges() + "/" + req.getShelfColumns() + "/" + req.getShelfRows());
////                }
////                return inventory;
////            }).collect(Collectors.toList());
////            return updateBatchById(collect);
////        }
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean BatchEditingInvsInfo(BatchEditingInvsReq req) {
        //查询inventory表中数据，对响应数据进行修改
        //判断是对整一类的装备进行修改还是说对个别几个装备进行批量修改
//        if (req.getInventoryIdList().size()!=0){
        List<InventorySummary> delList=new ArrayList<>();
        PubOrg pubOrg = pubOrgService.PubOrgExist(req.getOrgId());
        int size = req.getInventoryIdList().size();
        List<Object[]> searchItem=new ArrayList<>();
        //（判断出库几条，入库几条）
        List<Inventory> list = list(new LambdaQueryWrapper<Inventory>().in(Inventory::getId, req.getInventoryIdList()));
        int stockNum=0;
        int outBoundNum=0;
        for (Inventory inv:list) {
            if (inv.getLocationState().equals("in")){
                stockNum=stockNum+1;
            }else {
                outBoundNum=outBoundNum+1;
            }
        }
        if (req.getPrice().compareTo(req.getOriginalPrice())!=0){
            Object[] item=new Object[]{req.getOrgId(),req.getLocationId(),req.getTypeId(),req.getSizeId(),req.getPrice()};
            Object[] item1=new Object[]{req.getOrgId(),req.getLocationId(),req.getTypeId(),req.getSizeId(),req.getOriginalPrice()};
            searchItem.add(item);
            searchItem.add(item1);
            List<InventorySummary> inventorySummaryList = inventorySummaryMapper.selectSumByItems(searchItem);
            if (inventorySummaryList.size()==1){//等于1表示他修改后的单价的汇总信息没有，需要新增一条
                InventorySummary is = inventorySummaryList.get(0);
                is.setStockNumber(Math.max(is.getStockNumber()-size,0));
                is.setNumber(Math.max(is.getNumber()-size,0));
                is.setPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getNumber())));
                if (is.getNumber()==0 && is.getStockNumber()==0 && is.getOutboundNumber()==0 && is.getDestructionNumber()==0){
                    delList.add(is);
                }
                //新增一条数据
                InventorySummary inventorySummary = new InventorySummary();
                BeanPlusUtil.copyProperties(req,inventorySummary);
                inventorySummary.setValuekey(pubOrg.getOrgCode()+req.getLocationId()+req.getTypeId()+req.getSizeId()+req.getPrice());
                inventorySummary.setOrgName(pubOrg.getOrgName());
                inventorySummary.setOrgCode(pubOrg.getOrgCode());
                inventorySummary.setNumber(size);
                inventorySummary.setStockNumber(size);
                inventorySummary.setOutboundNumber(0);
                inventorySummary.setLocationType("0");
                inventorySummary.setUnitPrice(req.getPrice());
                inventorySummary.setPrice(req.getOriginalPrice().multiply(BigDecimal.valueOf(size)));
                inventorySummary.setDestructionPrice(BigDecimal.ZERO);
                inventorySummary.setBrokenNumberPrice(BigDecimal.ZERO);
                inventorySummary.setExpireNumberPrice(BigDecimal.ZERO);
                inventorySummary.setBrokenNumber(0);
                inventorySummary.setExpireNumber(0);
                inventorySummary.setDestructionNumber(0);
                inventorySummary.setFixNumber(0);
                inventorySummary.setProperty(0);
                inventorySummaryService.save(inventorySummary);
                inventorySummaryService.updateBatchById(inventorySummaryList);
            }else {
                for (InventorySummary is:inventorySummaryList) {
                    if (is.getUnitPrice().compareTo(req.getOriginalPrice())==0){//如果单价和修改前的价格一致
                        if (stockNum!=0){
                            is.setStockNumber(is.getStockNumber()-stockNum);
                            is.setNumber(is.getNumber()-stockNum);
                            is.setPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getNumber())));
                        }
                        if (outBoundNum!=0){
                            is.setOutboundNumber(is.getOutboundNumber()-outBoundNum);
                            is.setNumber(is.getNumber()-outBoundNum);
                            is.setPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getNumber())));
                        }
                        if (is.getNumber()==0 && is.getStockNumber()==0 && is.getOutboundNumber()==0 && is.getDestructionNumber()==0){
                            delList.add(is);
                        }
                    }else {//单价和修改后的价格不一致
                        if (stockNum!=0){
                            is.setStockNumber(is.getStockNumber()+stockNum);
                            is.setNumber(is.getNumber()+stockNum);
                            is.setPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getNumber())));
                        }
                        if (outBoundNum!=0){
                            is.setOutboundNumber(is.getOutboundNumber()+outBoundNum);
                            is.setNumber(is.getNumber()+outBoundNum);
                            is.setPrice(is.getUnitPrice().multiply(BigDecimal.valueOf(is.getNumber())));
                        }
                        if (is.getNumber()==0 && is.getStockNumber()==0 && is.getOutboundNumber()==0 && is.getDestructionNumber()==0){
                            delList.add(is);
                        }
                    }
                }

                inventorySummaryService.updateBatchById(inventorySummaryList);
            }
            if (CollectionUtil.isNotEmpty(delList)){
                inventorySummaryService.removeBatchByIds(delList);
            }
        }

        if (list.size()==0){
            throw new ServiceException(CabinetExceptionEnum.PARAMETER_ERROR);
        }else {
            //批量修改个别装备
//                List<Inventory> collect = list.stream().map(inventory -> {
//                    BeanPlusUtil.copyProperties(req,inventory );
//                    if (ObjectUtil.isNotNull(req.getShelfColumns()) && !req.getShelfColumns().toString().trim().isEmpty()
//                            && ObjectUtil.isNotNull(req.getShelfRanges()) && !req.getShelfRanges().toString().trim().isEmpty()
//                            && ObjectUtil.isNotNull(req.getShelfRows()) && !req.getShelfRows().toString().trim().isEmpty()) {
//                        inventory.setShelfLocation(req.getShelfRanges() + "/" + req.getShelfColumns() + "/" + req.getShelfRows());
//                    }
//                    return inventory;
//                }).collect(Collectors.toList());
//                List<Inventory> list1 = list(new LambdaQueryWrapper<Inventory>().eq(Inventory::getId, list));
            List<Inventory> collect = list.stream().map(inventory -> {
                inventory.setWarrantyPeriod(req.getWarrantyPeriod());
                inventory.setMaintenancePeriod(req.getMaintenancePeriod());
                inventory.setPrice(req.getPrice());
                return inventory;
            }).collect(Collectors.toList());
            return updateBatchById(collect);
        }

//        }
//        else {
//            List<Inventory> list = list(createWrapper(req));
//            //直接将一类的数据进行修改
//            List<Inventory> collect = list.stream().map(inventory -> {
//                BeanPlusUtil.copyProperties(req, inventory);
//                if (ObjectUtil.isNotNull(req.getShelfColumns()) && !req.getShelfColumns().toString().trim().isEmpty()
//                        && ObjectUtil.isNotNull(req.getShelfRanges()) && !req.getShelfRanges().toString().trim().isEmpty()
//                        && ObjectUtil.isNotNull(req.getShelfRows()) && !req.getShelfRows().toString().trim().isEmpty()) {
//                    inventory.setShelfLocation(req.getShelfRanges() + "/" + req.getShelfColumns() + "/" + req.getShelfRows());
//                }
//                return inventory;
//            }).collect(Collectors.toList());
//            return updateBatchById(collect);
//        }
    }

    //修改库存信息汇总
    @Transactional(rollbackFor = Exception.class)
    public boolean setInventorySummary(BatchEditingInvsReq req){
        //查询字典表中的临近报废天数
        SysDictItem sysDictItem = sysDictItemService.getOne(new LambdaQueryWrapper<SysDictItem>()
                .eq(SysDictItem::getItemText, "nearBrokenNumber"));
        //如果配置找不到，那就默认设置为15天为临近报废（如果装备的质保期小于15天了，就是为临近报废）
        Integer nearBrokenNumberDays;
        if (ObjectUtil.isNotNull(sysDictItem)){
            nearBrokenNumberDays=15;
        }else {
            nearBrokenNumberDays=Integer.parseInt(sysDictItem.getItemValue());
        }
        //先将其删除再全部重新添加计算
        List<InventorySummary> list = inventorySummaryService.list(new LambdaQueryWrapper<InventorySummary>()
                .eq(ObjectUtil.isNotNull(req.getOrgId()),InventorySummary::getOrgId,req.getOrgId())
                .eq(ObjectUtil.isNotNull(req.getLocationId()),InventorySummary::getLocationId,req.getLocationId())
                .eq(ObjectUtil.isNotNull(req.getSizeId()),InventorySummary::getSizeId,req.getSizeId())
                .eq(ObjectUtil.isNotNull(req.getTypeId()),InventorySummary::getTypeId,req.getTypeId()));
        boolean b = inventorySummaryService.removeBatchByIds(list);
        boolean a = inventoryMapper.insertInventorySummary(req,nearBrokenNumberDays);
        return (a && b);
    }

    //根据货架id获取装备列表汇总信息(list)
    @Override
    public List<InventorySummary> ShelfInventoryList(ShelfReq req) {
        //判断货架是否存在
        Shelf shelf = shelfService.ShelfExist(req.getShelfId());
        warehouseService.WarehoustExist(shelf.getWarehouseId());
        //通过货架id获取装备列表汇总
        return inventoryMapper.getSumByShelf(req.getShelfId());
    }

    //根据货架id获取装备列表汇总信息(page)
    @Override
    public PageResult<InventorySummary> ShelfInventoryPage(ShelfReq req) {
        //判断货架是否存在
        Shelf shelf = shelfService.ShelfExist(req.getShelfId());
        warehouseService.WarehoustExist(shelf.getWarehouseId());
        Page<InventorySummary> page = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        IPage<InventorySummary> pages = inventoryMapper.ShelfInventoryPage(page,req.getShelfId());
        page.setRecords(pages.getRecords());
        return PageResultFactory.createPageResult(page);
    }

    //通过货架id查询装备简要信息（list）
    @Override
    public List<EqsBriefDto> ShelfInventoryDetail(InventoryReq req) {
        //判断货架是否存在
        Shelf shelf = shelfService.ShelfExist(req.getShelfId());
        warehouseService.WarehoustExist(shelf.getWarehouseId());
        List<Inventory> list = list(new LambdaQueryWrapper<Inventory>()
                .eq(Inventory::getShelfId, req.getShelfId())
                .orderByDesc(Inventory::getTypeId)
                .orderByDesc(Inventory::getSizeId));
        List<EqsBriefDto> eqsBriefDtoList=list.parallelStream()
                .map(inventory -> {
                    EqsBriefDto eqsBriefDto = new EqsBriefDto();
                    BeanPlusUtil.copyProperties(inventory,eqsBriefDto);
                    Map<String, String> map = setNames( eqsBriefDto.getTypeId(),eqsBriefDto.getSizeId(), eqsBriefDto.getSupplierId());
                    //设置typeName
                    eqsBriefDto.setTypeName(map.get("typeName"));
                    //设置sizeName
                    eqsBriefDto.setSizeName(map.get("sizeName"));
                    //如果有供应商id的前提下，设置supplierName
                    if (ObjectUtil.isNotNull(eqsBriefDto.getSupplierId())){
                        eqsBriefDto.setSupplierName(map.get("supplierName"));
                    }
                    return eqsBriefDto;
                }).collect(Collectors.toList());
        return eqsBriefDtoList;
    }

    //通过货架id查询装备简要信息（page）
    @Override
    public PageResult<EqsBriefDto> ShelfInventoryPage(InventoryReq req) {
        Shelf shelf = shelfService.ShelfExist(req.getShelfId());
        warehouseService.WarehoustExist(shelf.getWarehouseId());
        LambdaQueryWrapper<Inventory> eq = new LambdaQueryWrapper<Inventory>()
                .eq(Inventory::getShelfId, req.getShelfId())
                .orderByDesc(Inventory::getTypeId)
                .orderByDesc(Inventory::getSizeId);
        List<Inventory> list = list(eq);
        long size = list.size();
        Page<Inventory> page = page(PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize()), eq);
        List<Inventory> records = page.getRecords();
        List<EqsBriefDto> eqsBriefDtoList=records.parallelStream()
            .map(inventory -> {
                EqsBriefDto eqsBriefDto = new EqsBriefDto();
                BeanPlusUtil.copyProperties(inventory,eqsBriefDto);
                Map<String, String> map = setNames( eqsBriefDto.getTypeId(),eqsBriefDto.getSizeId(), eqsBriefDto.getSupplierId());
                //设置typeName
                eqsBriefDto.setTypeName(map.get("typeName"));
                //设置sizeName
                eqsBriefDto.setSizeName(map.get("sizeName"));
                //如果有供应商id的前提下，设置supplierName
                if (ObjectUtil.isNotNull(eqsBriefDto.getSupplierId())){
                    eqsBriefDto.setSupplierName(map.get("supplierName"));
                }
                return eqsBriefDto;
            }).collect(Collectors.toList());
        Page<EqsBriefDto> page1 = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        page1.setRecords(eqsBriefDtoList);
        page1.setTotal(size);
        return PageResultFactory.createPageResult(page1);
    }


    /**
     * 通过区域id查询装备汇总信息
     * @param req
     * @return
     */
    @Override
    public List<InventorySummary> AreaInventoryList(WarehouseAreaReq req) {
        //判断区域是否存在
        WarehouseArea warehouseArea = warehouseAreaService.WarehouseAreaExist(req.getId());
        warehouseService.WarehoustExist(warehouseArea.getWarehouseId());
        //通过区域id获取装备列表汇总
        return inventoryMapper.getSumByArea(req.getId());
    }

    @Override
    public PageResult<InventorySummary> AreaInventoryPage(WarehouseAreaReq req) {
        //判断区域是否存在
        WarehouseArea warehouseArea = warehouseAreaService.WarehouseAreaExist(req.getId());
        warehouseService.WarehoustExist(warehouseArea.getWarehouseId());
        Page<InventorySummary> page = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        IPage<InventorySummary> pages= inventoryMapper.AreaInventoryPage(page,req.getId());
        page.setRecords(pages.getRecords());
        return PageResultFactory.createPageResult(page);
    }


    //通过单警柜箱门id获取箱门下的装备汇总信息(list)
    @Override
    public List<InventorySummary> EqsByCabinetBoxId(CabinetBoxReq req) {
        cabinetBoxService.CabinetBoxExist(req.getId());
        return inventoryMapper.getSumByCabinetBox(req.getId());
    }

    //通过单警柜箱门id获取箱门下的装备汇总信息(page)
    @Override
    public PageResult<InventorySummary> EqsByCabinetBoxIdPage(CabinetBoxReq req) {
        cabinetBoxService.CabinetBoxExist(req.getId());
        Page<InventorySummary> page=new Page<>(req.getPageNo(), req.getPageSize());
        IPage<InventorySummary> pages = inventoryMapper.EqsByCabinetBoxIdPage(page,req.getId());
        page.setRecords(pages.getRecords());
        return PageResultFactory.createPageResult(page);
    }

    //通过组织机构id将该组织下的装备进行导出
    @Override
    public void ExportInventoryExcel(InventoryReq req){
        //判断组织机构是否存在
        pubOrgService.PubOrgExist(req.getOrgId());
        //查询该组织机构下的所有装备信息
        List<InventoryVo> list = inventoryMapper.selectListByOrg(req.getOrgId());
        HttpServletResponse response = HttpServletUtil.getResponse();
        ExcelExportParam param = new ExcelExportParam();
        param.setDataList(list);
        param.setClazz(Inventory.class);
        param.setResponse(response);
        param.setFileName("装备列表.xls");
        //对数据进行导出
        officeExcelApi.easyExportDownload(param);
    }


    //查询装备数量报表
    @Override
    public List<EqsSumDto> GetListEquipment(InventoryReq req) {
        //通过获取传递的查询条件进行查询，得到最终的装备数量报表
        return inventoryMapper.GetListEquipment(req);
    }



    //通过id判断装备是否存在
    @Override
    public Inventory InventoryExist(String id) {
        Inventory invMap=this.getById(id);
        if (ObjectUtil.isNull(invMap)){
            throw new ServiceException(InventoryExceptionEnum.INVENTORY_NOT_EXIST);
        }
        return invMap;
    }

    //通用方法，用于设置对象的typeName属性，sizeName属性和supplierName属性
    public Map<String,String> setNames (String typeId,String sizeId,String supplierId){
        Map<String,String> map=new HashMap<>();
        EquipmentSize one = equipmentSizeService.getOne(new LambdaQueryWrapper<EquipmentSize>()
                .eq(EquipmentSize::getId, sizeId));
        String sizeName=one.getName();
        String photo=one.getPhoto();
        String typeName = equipmentTypeService.getOne(new LambdaQueryWrapper<EquipmentType>()
                .eq(EquipmentType::getId, typeId)).getName();
        //如果有供应商id的前提下，设置supplierName
        if (ObjectUtil.isNotNull(supplierId) && !supplierId.trim().isEmpty()){
            String supplierName = supplierService.getOne(new LambdaQueryWrapper<Supplier>()
                    .eq(Supplier::getId, supplierId)).getName();
            map.put("supplierName",supplierName);
        }
        map.put("sizeName",sizeName);
        map.put("typeName",typeName);
        map.put("photo",photo);
        return map;
    }

    //创建条件查询
    public LambdaQueryWrapper<Inventory> createWrapper(BatchEditingInvsReq req){
        LambdaQueryWrapper<Inventory> wrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isEmpty(req)){
            return wrapper;
        }
        wrapper.eq(ObjectUtil.isNotNull(req.getOrgId()),Inventory::getOrgId,req.getOrgId());
        wrapper.eq(ObjectUtil.isNotNull(req.getLocationId()),Inventory::getLocationId,req.getLocationId());
        wrapper.eq(ObjectUtil.isNotNull(req.getSizeId()),Inventory::getSizeId,req.getSizeId());
        wrapper.eq(ObjectUtil.isNotNull(req.getTypeId()),Inventory::getTypeId,req.getTypeId());
        return wrapper;
    }


    //判断epc是否存在
    @Override
    public List<String> checkEPCList(EpcCheckReq req) {
        return inventoryMapper.checkEPCList(req.getEpcList());
    }

    //根据条件查询满足条件的数据（用于快速移库修改装备仓库id）
    @Override
    public List<Inventory> selectEqsByItem(List<Object[]> searchCriteria) {
        return inventoryMapper.selectEqsByItem(searchCriteria);
    }

    @Override
    public List<EquipmentDto> alignInventoryInfo(InventoryReq req) {
        String date = DateTimeUtil.TimeLongToString(req.getUpdateTime());
        List<EquipmentDto> equipmentDtos = inventoryMapper.alignInventoryInfo(req.getOrgId(), req.getLocationId(), date, req.getTypeIdList(), req.getSizeIdList());
        return equipmentDtos;
    }



    //装备导入（判断导入的数据是否存在redis中，如果不存在，则判断数据库是否存在相同的epc，如果存在提示报错，并且讲该次导入的数据存储到redis中，为下一次进行作比较）
    @Override
    public boolean EqsImport(InventoryReq req) {
        List<InventoryReq> eqsList = req.getEqsList();

        return false;
    }

    @Override
    public PageResult<InventoryDto> EqsByState(InventoryReq req) {
        List<InventoryDto> list=inventoryMapper.EqsByState(req,(req.getPageNo()-1)*req.getPageSize(),req.getPageSize());
        int size=inventoryMapper.EqsByStateSum(req);
        Page<InventoryDto> page = PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize());
        page.setRecords(list);
        page.setTotal(size);
        return PageResultFactory.createPageResult(page);
    }

    @Override
    public List<PeriodAndDateDto> GetByPeriodAndDate(InventoryReq req) {
        List<PeriodAndDateDto> list=inventoryMapper.GetByPeriodAndDate(req);
        if (CollectionUtil.isEmpty(list)){
            return new ArrayList<>();
        }
        return list;
    }


}