package com.maintain.business.service.impl;
import java.util.Date;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.maintain.business.domain.*;
import com.maintain.business.domain.bo.ErpMaterialPickingInfoAddBo;
import com.maintain.business.domain.bo.ErpMaterialPickingInfoBo;
import com.maintain.business.domain.vo.*;
import com.maintain.business.mapper.*;
import com.maintain.business.service.IErpMaterialService;
import com.maintain.common.core.domain.BaseEntity;
import com.maintain.common.core.domain.entity.SysDept;
import com.maintain.common.enums.InventoryType;
import com.maintain.common.enums.IsEnableStatus;
import com.maintain.common.enums.PickingState;
import com.maintain.common.exception.ServiceException;
import com.maintain.common.helper.LoginHelper;
import com.maintain.common.utils.StringUtils;
import com.maintain.common.core.page.TableDataInfo;
import com.maintain.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.maintain.common.utils.poi.ExcelUtil;
import com.maintain.common.utils.poi.MergeCellModel;
import com.maintain.common.utils.poi.SheetPO;
import com.maintain.common.utils.redis.RedisUtils;
import com.maintain.system.mapper.SysDeptMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.maintain.business.domain.bo.ErpMaterialPickingBo;
import com.maintain.business.service.IErpMaterialPickingService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 报修单-领料出库单Service业务层处理
 *
 * @author liushuai
 * @date 2025-04-01
 */
@RequiredArgsConstructor
@Service
public class ErpMaterialPickingServiceImpl implements IErpMaterialPickingService {

    private final ErpMaterialPickingMapper baseMapper;
    private final ErpMaterialPickingInfoMapper pickingInfoMapper;
    private final ErpMaterialPutawayInfoMapper putawayInfoMapper;
    private final ErpRepairFormMapper repairFormMapper;
    private final ErpCarMapper carMapper;
    private final IErpMaterialService materialService;
    private final ErpMaterialMapper materialMapper;
    private final ErpMaterialInventoryRecordMapper materialInventoryRecordMapper;
    private final ErpWarehouseMapper warehouseMapper;
    private final SysDeptMapper deptMapper;
    private final ErpMaterialVendorMapper vendorMapper;

    /**
     * 查询报修单-领料出库单
     */
    @Override
    public ErpMaterialPickingVo queryById(Long id){
        ErpMaterialPickingVo materialVo = baseMapper.selectVoById(id);
        LambdaQueryWrapper<ErpMaterialPickingInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(ErpMaterialPickingInfo::getPickingId, id);
        List<ErpMaterialPickingInfoVo> infoVoList = pickingInfoMapper.selectVoList(lqw);
        if (!infoVoList.isEmpty()) {
            for (ErpMaterialPickingInfoVo infoVo : infoVoList) {
                if (infoVo.getRecordId() != null) {
                    ErpMaterialInventoryRecordVo recordVo = materialInventoryRecordMapper.customQueryInventoryById(infoVo.getRecordId());
                    infoVo.setInventory(recordVo.getInventory());
                }
            }
            materialVo.setPickingInfoList(infoVoList);
        }
        return materialVo;
    }

    /**
     * 查询报修单-领料出库单列表
     */
    @Override
    public TableDataInfo<ErpMaterialPickingVo> queryPageList(ErpMaterialPickingBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpMaterialPicking> lqw = buildQueryWrapper(bo);
        Page<ErpMaterialPickingVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询物料出库列表(包含明细)
     *
     * @param bo
     * @param pageQuery
     */
    @Override
    public TableDataInfo<ErpMaterialPickingVo> queryPageInfoList(ErpMaterialPickingBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpMaterialPicking> lqw = buildQueryWrapper(bo);
        Page<ErpMaterialPickingVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        // 查询出库明细列表
        for (ErpMaterialPickingVo pickingVo : result.getRecords()) {
            List<ErpMaterialPickingInfoVo> infoVoList = pickingInfoMapper.selectVoList(new LambdaQueryWrapper<>(ErpMaterialPickingInfo.class).eq(ErpMaterialPickingInfo::getPickingId, pickingVo.getId()));
            for (ErpMaterialPickingInfoVo infoVo : infoVoList) {
                LambdaQueryWrapper<ErpMaterialPutawayInfo> putawayInfoLambdaQueryWrapper = Wrappers.lambdaQuery();
                putawayInfoLambdaQueryWrapper.eq(ErpMaterialPutawayInfo::getMaterialId, infoVo.getMaterialId());
                List<ErpMaterialPutawayInfoVo> putawayInfoVos = putawayInfoMapper.selectVoList(putawayInfoLambdaQueryWrapper);
                Set<BigDecimal> priceSet = putawayInfoVos.stream()
                    .map(ErpMaterialPutawayInfoVo::getPutawayPrice)
                    .filter(Objects::nonNull)  // 排除 null 值
                    .collect(Collectors.toSet());
                infoVo.setPriceList(priceSet);
            }
            pickingVo.setPickingInfoList(infoVoList);
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询报修单-领料出库单列表
     */
    @Override
    public List<ErpMaterialPickingVo> queryList(ErpMaterialPickingBo bo) {
        LambdaQueryWrapper<ErpMaterialPicking> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpMaterialPicking> buildQueryWrapper(ErpMaterialPickingBo bo) {
        List<SysDept> sysDeptList = deptMapper.selectChildrenDeptById(LoginHelper.getDeptId(), null);
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpMaterialPicking> lqw = Wrappers.lambdaQuery();
        lqw.eq( bo.getType() != null, ErpMaterialPicking::getType, bo.getType());
        lqw.eq(bo.getSettlementState() != null, ErpMaterialPicking::getSettlementState, bo.getSettlementState());
        lqw.eq(bo.getRepairFormId() != null, ErpMaterialPicking::getRepairFormId, bo.getRepairFormId());
        lqw.like(StringUtils.isNotBlank(bo.getRepairNumber()), ErpMaterialPicking::getRepairNumber, bo.getRepairNumber());
        lqw.like(StringUtils.isNotBlank(bo.getReturnNumber()), ErpMaterialPicking::getReturnNumber, bo.getReturnNumber());
        lqw.like(StringUtils.isNotBlank(bo.getOutNumber()), ErpMaterialPicking::getOutNumber, bo.getOutNumber());
        lqw.eq(bo.getCarId() != null, ErpMaterialPicking::getCarId, bo.getCarId());
        lqw.like(StringUtils.isNotBlank(bo.getPlateNumber()), ErpMaterialPicking::getPlateNumber, bo.getPlateNumber());
        lqw.eq(bo.getOutMoney() != null, ErpMaterialPicking::getOutMoney, bo.getOutMoney());
        lqw.eq(bo.getReceiveUserId() != null, ErpMaterialPicking::getReceiveUserId, bo.getReceiveUserId());
        lqw.like(StringUtils.isNotBlank(bo.getReceiveUserName()), ErpMaterialPicking::getReceiveUserName, bo.getReceiveUserName());
        lqw.eq(bo.getReceiveTime() != null, ErpMaterialPicking::getReceiveTime, bo.getReceiveTime());
        lqw.eq(bo.getState() != null, ErpMaterialPicking::getState, bo.getState());
        lqw.in(bo.getStateList() != null, ErpMaterialPicking::getState, bo.getStateList());
        lqw.in(bo.getRepairFormId() == null && !sysDeptList.isEmpty(), ErpMaterialPicking::getCreateDeptId, sysDeptList.stream().map(SysDept::getDeptId).collect(Collectors.toList()));
        lqw.orderByDesc(BaseEntity::getCreateTime);
        return lqw;
    }

    /**
     * 新增领料出库单
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertByBo(ErpMaterialPickingBo bo) {
        ErpMaterialPicking add = BeanUtil.toBean(bo, ErpMaterialPicking.class);
        ErpRepairForm repairForm = repairFormMapper.selectById(bo.getRepairFormId());
        ErpCar erpCar = carMapper.selectById(repairForm.getCarId());
        add.setCarId(erpCar.getId());
        add.setOutNumber(RedisUtils.generateNextNumber("CK"));
        add.setRepairNumber(repairForm.getRepairNumber());
        add.setPlateNumber(erpCar.getPlateNumber());
        add.setReceiveUserId(LoginHelper.getUserId());
        add.setReceiveUserName(LoginHelper.getUsername());
        add.setReceiveTime(new Date());
        ErpMaterialVendor materialVendor = vendorMapper.selectById(bo.getVendorId());
        add.setVendorId(materialVendor.getId());
        add.setVendorName(materialVendor.getVendorName());
        BigDecimal moneyTotal = bo.getMaterialList().stream().map(ErpMaterialPickingInfoAddBo::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        add.setOutMoney(moneyTotal);
        add.setCreateDeptId(LoginHelper.getDeptId());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            List<ErpMaterialPickingInfo> collect = bo.getMaterialList().stream().map(item -> {
                ErpMaterialPickingInfo info = BeanUtil.toBean(item, ErpMaterialPickingInfo.class);
                info.setId(null);
                info.setRepairFormId(bo.getRepairFormId());
                info.setPickingId(add.getId());
                info.setState(bo.getState());
                /* 查询记录 */
                ErpMaterialInventoryRecord record = materialInventoryRecordMapper.selectById(item.getRecordId());
                info.setPutawayPrice(record.getPrice());
                info.setPutawayMoney(record.getMoney());
                return info;
            }).collect(Collectors.toList());
            pickingInfoMapper.insertBatch(collect);

            /* 创建物料库存记录表 */
            if (bo.getState().equals(PickingState.TWO.getCode())) {
                List<ErpMaterialInventoryRecord> inventoryRecordList = collect.stream().map(item -> {
                    ErpMaterialInventoryRecordVo recordVo = materialInventoryRecordMapper.customQueryInventoryById(item.getRecordId());
                    if (null == recordVo) {
                        throw new ServiceException("仓库["+item.getWarehouseName()+"]中物料["+item.getMaterialName()+"]库存异常，请联系管理员！");
                    }
                    if (item.getCollectNumber().compareTo(recordVo.getInventory()) > 0) {
                        throw new ServiceException("仓库["+item.getWarehouseName()+"]中物料["+item.getMaterialName()+"]库存不足，请调整后重试!");
                    }
                    /* 记录已出数量 */
                    ErpMaterialInventoryRecord inventoryRecord = materialInventoryRecordMapper.selectById(item.getRecordId());
                    if (null == inventoryRecord) {
                        throw new ServiceException("库存存在异常，请联系管理员！！！");
                    }
                    ErpMaterialPutawayInfo putawayInfo = putawayInfoMapper.selectById(inventoryRecord.getInfoId());
                    putawayInfo.setIssuedNumber(putawayInfo.getIssuedNumber().add(item.getCollectNumber()));
                    putawayInfoMapper.updateById(putawayInfo);
                    /* 创建库存记录 */
                    ErpMaterialInventoryRecord record = new ErpMaterialInventoryRecord();
                    record.setInfoId(item.getId());
                    record.setMaterialId(item.getMaterialId());
                    ErpWarehouseVo warehouseVo = warehouseMapper.selectVoById(item.getWarehouseId());
                    record.setWarehouseId(warehouseVo.getId());
                    record.setDeptId(warehouseVo.getDeptId());
                    record.setVendorId(item.getVendorId());
                    record.setNumber(item.getCollectNumber());
                    record.setPrice(item.getPrice());
                    record.setMoney(item.getMoney());
                    record.setType(InventoryType.picking.getCode());
                    return record;
                }).collect(Collectors.toList());
                materialInventoryRecordMapper.insertBatch(inventoryRecordList);
            }
        }
        return flag;
    }

    /**
     * 修改领料出库单
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateByBo(ErpMaterialPickingBo bo) {
        ErpMaterialPicking update = BeanUtil.toBean(bo, ErpMaterialPicking.class);
        BigDecimal moneyTotal = bo.getMaterialList().stream().map(ErpMaterialPickingInfoAddBo::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        ErpRepairForm repairForm = repairFormMapper.selectById(bo.getRepairFormId());
        ErpCar erpCar = carMapper.selectById(repairForm.getCarId());
        update.setCarId(erpCar.getId());
        update.setRepairNumber(repairForm.getRepairNumber());
        update.setPlateNumber(erpCar.getPlateNumber());
        update.setOutMoney(moneyTotal);
        ErpMaterialVendor materialVendor = vendorMapper.selectById(bo.getVendorId());
        update.setVendorId(materialVendor.getId());
        update.setVendorName(materialVendor.getVendorName());
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            // 删除原有绑定
            LambdaQueryWrapper<ErpMaterialPickingInfo> lqw = Wrappers.lambdaQuery();
            lqw.eq(ErpMaterialPickingInfo::getPickingId, update.getId());
            pickingInfoMapper.delete(lqw);

            // 批量新增材料明细
            List<ErpMaterialPickingInfoAddBo> materialList = bo.getMaterialList();
            List<ErpMaterialPickingInfo> collect = materialList.stream().map(item -> {
                ErpMaterialPickingInfo info = BeanUtil.toBean(item, ErpMaterialPickingInfo.class);
                info.setId(null);
                info.setPickingId(update.getId());
                info.setRepairFormId(update.getRepairFormId());
                info.setState(bo.getState());
                info.setPrice(item.getPrice());
                info.setMoney(item.getMoney());
                /* 查询记录 */
                ErpMaterialInventoryRecord record = materialInventoryRecordMapper.selectById(item.getRecordId());
                info.setPutawayPrice(record.getPrice());
                info.setPutawayMoney(record.getMoney());
                return info;
            }).collect(Collectors.toList());
            pickingInfoMapper.insertBatch(collect);

            /* 创建物料库存记录表 */
            if (bo.getState().equals(PickingState.TWO.getCode())) {
                List<ErpMaterialInventoryRecord> inventoryRecordList = collect.stream().map(item -> {
                    ErpMaterialInventoryRecordVo recordVo = materialInventoryRecordMapper.customQueryInventoryById(item.getRecordId());
                    if (null == recordVo) {
                        throw new ServiceException("仓库["+item.getWarehouseName()+"]中物料["+item.getMaterialName()+"]库存异常，请联系管理员！");
                    }
                    if (item.getCollectNumber().compareTo(recordVo.getInventory()) > 0) {
                        throw new ServiceException("仓库["+item.getWarehouseName()+"]中物料["+item.getMaterialName()+"]库存不足，请调整后重试!");
                    }
                    /* 记录已出数量 */
                    ErpMaterialInventoryRecord inventoryRecord = materialInventoryRecordMapper.selectById(item.getRecordId());
                    if (null == inventoryRecord) {
                        throw new ServiceException("库存存在异常，请联系管理员！！！");
                    }
                    ErpMaterialPutawayInfo putawayInfo = putawayInfoMapper.selectById(inventoryRecord.getInfoId());
                    putawayInfo.setIssuedNumber(putawayInfo.getIssuedNumber().add(item.getCollectNumber()));
                    putawayInfoMapper.updateById(putawayInfo);
                    /* 创建库存记录 */
                    ErpMaterialInventoryRecord record = new ErpMaterialInventoryRecord();
                    record.setInfoId(item.getId());
                    record.setMaterialId(item.getMaterialId());
                    ErpWarehouseVo warehouseVo = warehouseMapper.selectVoById(item.getWarehouseId());
                    record.setWarehouseId(warehouseVo.getId());
                    record.setDeptId(warehouseVo.getDeptId());
                    record.setVendorId(item.getVendorId());
                    record.setNumber(item.getCollectNumber());
                    record.setPrice(item.getPrice());
                    record.setMoney(item.getMoney());
                    record.setType(InventoryType.picking.getCode());
                    return record;
                }).collect(Collectors.toList());
                materialInventoryRecordMapper.insertBatch(inventoryRecordList);
            }
        }
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpMaterialPicking entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除领料出库单
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        // 删除领料出库单
        boolean flag = baseMapper.deleteBatchIds(ids) > 0;
        if (flag) {
            // 删除物料库存记录数据
            LambdaQueryWrapper<ErpMaterialPickingInfo> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.in(ErpMaterialPickingInfo::getPickingId, ids);
            List<ErpMaterialPickingInfoVo> pickingInfoVoList = pickingInfoMapper.selectVoList(queryWrapper);
            if (!pickingInfoVoList.isEmpty()) {
                LambdaQueryWrapper<ErpMaterialInventoryRecord> lambdaQueryWrapper = Wrappers.lambdaQuery();
                lambdaQueryWrapper.in(ErpMaterialInventoryRecord::getInfoId, pickingInfoVoList.stream().map(ErpMaterialPickingInfoVo::getId).collect(Collectors.toList()));
                materialInventoryRecordMapper.delete(lambdaQueryWrapper);
            }
            // 删除领料出库单明细
            LambdaUpdateWrapper<ErpMaterialPickingInfo> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.in(ErpMaterialPickingInfo::getPickingId, ids);
            pickingInfoMapper.delete(updateWrapper);
        }
        return flag;
    }

    /**
     * 批量确认物料出库
     *
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean confirmByIds(Collection<Long> ids) {
        // 更新物料出库状态
        LambdaUpdateWrapper<ErpMaterialPicking> lqw = Wrappers.lambdaUpdate();
        lqw.in(ErpMaterialPicking::getId, ids);
        lqw.set(ErpMaterialPicking::getState, PickingState.TWO.getCode());
        boolean flag = baseMapper.update(lqw) > 0;
        if (flag) {
            LambdaQueryWrapper<ErpMaterialPickingInfo> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.in(ErpMaterialPickingInfo::getPickingId, ids).eq(ErpMaterialPickingInfo::getState, PickingState.ONE.getCode());
            List<ErpMaterialPickingInfoVo> pickingInfoVoList = pickingInfoMapper.selectVoList(queryWrapper);
            List<ErpMaterialInventoryRecord> inventoryRecordList = pickingInfoVoList.stream().map(item -> {
                ErpMaterialInventoryRecordVo recordVo = materialInventoryRecordMapper.customQueryInventoryById(item.getRecordId());
                if (null == recordVo) {
                    throw new ServiceException("仓库["+item.getWarehouseName()+"]中物料["+item.getMaterialName()+"]库存异常，请联系管理员！");
                }
                if (item.getCollectNumber().compareTo(recordVo.getInventory()) > 0) {
                    throw new ServiceException("仓库["+item.getWarehouseName()+"]中物料["+item.getMaterialName()+"]库存不足，请调整后重试!");
                }
                /* 记录已出数量 */
                ErpMaterialPutawayInfo putawayInfo = putawayInfoMapper.selectById(recordVo.getInfoId());
                putawayInfo.setIssuedNumber(putawayInfo.getIssuedNumber().add(item.getCollectNumber()));
                putawayInfoMapper.updateById(putawayInfo);
                /* 创建库存记录 */
                ErpMaterialInventoryRecord record = new ErpMaterialInventoryRecord();
                record.setInfoId(item.getId());
                record.setMaterialId(item.getMaterialId());
                ErpWarehouseVo warehouseVo = warehouseMapper.selectVoById(item.getWarehouseId());
                record.setWarehouseId(warehouseVo.getId());
                record.setDeptId(warehouseVo.getDeptId());
                record.setVendorId(item.getVendorId());
                record.setNumber(item.getCollectNumber());
                record.setPrice(item.getPrice());
                record.setMoney(item.getMoney());
                record.setType(InventoryType.picking.getCode());
                return record;
            }).collect(Collectors.toList());
            materialInventoryRecordMapper.insertBatch(inventoryRecordList);

            // 更新出库明细状态
            LambdaUpdateWrapper<ErpMaterialPickingInfo> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.in(ErpMaterialPickingInfo::getPickingId, ids).set(ErpMaterialPickingInfo::getState, PickingState.TWO.getCode());
            pickingInfoMapper.update(updateWrapper);
        }
        return flag;
    }

    /**
     * 新增物料出库退料单
     *
     * @param bo
     */
    @Override
    public Boolean insertReturnByBo(ErpMaterialPickingBo bo) {
        ErpMaterialPicking materialPicking = baseMapper.selectById(bo.getId());
        materialPicking.setReturnNumber(RedisUtils.generateNextNumber("TL"));
        materialPicking.setReturnTime(new Date());
        // 更新领料出库单状态
        materialPicking.setState(PickingState.THREE.getCode());
        boolean flag = baseMapper.updateById(materialPicking) > 0;
        if (flag) {
            // 更新领料出库明细状态
            LambdaUpdateWrapper<ErpMaterialPickingInfo> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper
                .eq(ErpMaterialPickingInfo::getPickingId, bo.getId())
                .set(ErpMaterialPickingInfo::getState, PickingState.THREE.getCode());
            pickingInfoMapper.update(updateWrapper);
            // 创建物料库存记录数据
            LambdaQueryWrapper<ErpMaterialPickingInfo> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(ErpMaterialPickingInfo::getPickingId, bo.getId());
            List<ErpMaterialPickingInfoVo> pickingInfoVoList = pickingInfoMapper.selectVoList(queryWrapper);
            if (!pickingInfoVoList.isEmpty()) {
                List<ErpMaterialInventoryRecord> inventoryRecordList = pickingInfoVoList.stream().map(item -> {
                    /* 回退入库明细中已出数量 */
                    ErpMaterialInventoryRecordVo recordVo = materialInventoryRecordMapper.customQueryInventoryById(item.getRecordId());
                    ErpMaterialPutawayInfo putawayInfo = putawayInfoMapper.selectById(recordVo.getInfoId());
                    putawayInfo.setIssuedNumber(putawayInfo.getIssuedNumber().subtract(item.getCollectNumber()));
                    putawayInfoMapper.updateById(putawayInfo);

                    /* 创建库存记录 */
                    ErpMaterialInventoryRecord record = new ErpMaterialInventoryRecord();
                    record.setInfoId(item.getId());
                    record.setMaterialId(item.getMaterialId());
                    ErpWarehouseVo warehouseVo = warehouseMapper.selectVoById(item.getWarehouseId());
                    record.setWarehouseId(warehouseVo.getId());
                    record.setDeptId(warehouseVo.getDeptId());
                    record.setVendorId(item.getVendorId());
                    record.setNumber(item.getCollectNumber());
                    record.setPrice(item.getPrice());
                    record.setMoney(item.getMoney());
                    record.setType(InventoryType.back.getCode());
                    return record;
                }).collect(Collectors.toList());
                materialInventoryRecordMapper.insertBatch(inventoryRecordList);
            }
        }
        return flag;
    }

    @Override
    public void export(ErpMaterialPickingBo bo, HttpServletResponse response) {
        String sheetName ="供应商材料消耗明细表";
        String title ="供应商铺货结算表";
        List<SysDept> sysDeptList = deptMapper.selectChildrenDeptById(LoginHelper.getDeptId(), null);
        if (!sysDeptList.isEmpty()){
            bo.setDeptIds(sysDeptList.stream().map(SysDept::getDeptId).collect(Collectors.toList()));
        }
        List<ErpMaterialPickingExportVo> list =  pickingInfoMapper.getExportList(bo);
        //生成合并单元格信息
        List<MergeCellModel> mergeCellList = new ArrayList<>();
        Integer centerMergedAnchorExcelRowIndex = null;
        if (CollectionUtils.isNotEmpty(list)){
            list.forEach(item -> {
                item.setIndex(String.valueOf(list.indexOf(item) + 1));
            });
            //合计统计
            ErpMaterialPickingExportVo erpMaterialPickingExportVo1 = new ErpMaterialPickingExportVo();
            // 合计文案须落在合并区域左上角列：index=0 为序号(Integer)，合并 0~10 时左上角为空会“吃掉”7、8 列的合计文字
            erpMaterialPickingExportVo1.setIndex("合计");
            list.add(erpMaterialPickingExportVo1);
            // 双行表头：第 0 行为大标题，第 1 行为列名；合计行 Excel 行号 = list.size() + 1
            int totalExcelRowIndex = list.size() + 1;
            centerMergedAnchorExcelRowIndex = totalExcelRowIndex;
            mergeCellList.add(MergeCellModel.createMergeCellModel(sheetName, totalExcelRowIndex, totalExcelRowIndex, 0, 10));
            //计算数量总和
            BigDecimal collectNumber = list.stream().map(ErpMaterialPickingExportVo::getCollectNumber).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            erpMaterialPickingExportVo1.setCollectNumber(collectNumber);
            //计算价格总和
            BigDecimal money = list.stream().map(ErpMaterialPickingExportVo::getMoney).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
            erpMaterialPickingExportVo1.setMoney(money);

            //签名地方
            ErpMaterialPickingExportVo erpMaterialPickingExportVo2 = new ErpMaterialPickingExportVo();
            erpMaterialPickingExportVo2.setWorkshopName("车间仓库员签名：");
            erpMaterialPickingExportVo2.setMaterialSpecifications("车间负责人签名：");
            list.add(erpMaterialPickingExportVo2);
        }
        List<SheetPO> sheetPOList = new ArrayList<>();
        SheetPO<ErpMaterialPickingExportVo> sheetPO = new SheetPO<>();
        sheetPOList.add(sheetPO);
        Map<String, String> titleMap = new HashMap<>();
        titleMap.put("title", title);
        sheetPO.setData(list);
        sheetPO.setTitleMap(titleMap);
        sheetPO.setClazz(ErpMaterialPickingExportVo.class);
        sheetPO.setSheetNo(1);
        sheetPO.setMergeCellList(mergeCellList);
        sheetPO.setSheetName(sheetName);
        sheetPO.setWhiteFirstHeadRow(true);
        sheetPO.setCenterMergedAnchorExcelRowIndex(centerMergedAnchorExcelRowIndex);
        ExcelUtil.exportSheetSetTitle(response, title, sheetPOList);
    }
}
