package cn.iocoder.yudao.module.stockOperate.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.common.RepairErrorCodeConstants;
import cn.iocoder.yudao.common.SoStatusEnum;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.base.service.RepairWorkerService;
import cn.iocoder.yudao.module.company.entity.Company;
import cn.iocoder.yudao.module.company.service.CompanyService;
import cn.iocoder.yudao.module.project.entity.RepairWares;
import cn.iocoder.yudao.module.project.service.RepairWaresService;
import cn.iocoder.yudao.module.stockOperate.entity.DlRepairSo;
import cn.iocoder.yudao.module.stockOperate.entity.DlRepairSoi;
import cn.iocoder.yudao.module.stockOperate.mapper.DlRepairSoMapper;
import cn.iocoder.yudao.module.stockOperate.service.DlRepairSoService;
import cn.iocoder.yudao.module.stockOperate.service.DlRepairSoiService;
import cn.iocoder.yudao.module.stockOperate.vo.DlRepairSoReqVO;
import cn.iocoder.yudao.module.stockOperate.vo.DlRepairSoRespVO;
import cn.iocoder.yudao.module.supplier.service.BaseSupplierService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.tickets.entity.DlTicketWares;
import cn.iocoder.yudao.module.tickets.entity.DlTwItem;
import cn.iocoder.yudao.module.tickets.service.DlRepairTicketsService;
import cn.iocoder.yudao.module.tickets.service.DlRepairTitemService;
import cn.iocoder.yudao.module.tickets.service.DlTicketWaresService;
import cn.iocoder.yudao.module.tickets.service.DlTwItemService;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
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 org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

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

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception0;

/**
 * 针对表【dl_repair_so(采购单领料单)】的数据库操作Service实现
 *
 * @author 小李
 * @date 9:11 2024/9/13
 **/
@Service
public class DlRepairSoServiceImpl extends ServiceImpl<DlRepairSoMapper, DlRepairSo>
        implements DlRepairSoService {

    @Resource
    private DlRepairSoiService repairSoiService;

    @Resource
    private DeptApi deptApi;

    @Resource
    private CompanyService companyService;

    @Resource
    @Lazy
    private RepairWaresService waresService;

    @Resource
    @Lazy
    private DlTicketWaresService ticketWaresService;

    @Resource
    @Lazy
    private DlTwItemService twItemService;

    @Resource
    @Lazy
    private DlRepairTicketsService ticketsService;

    @Resource
    @Lazy
    private DlRepairTitemService titemService;

    @Resource
    @Lazy
    private RepairWorkerService repairWorkerService;
    @Resource
    private AdminUserApi userApi;
    @Resource
    private BaseSupplierService supplierService;

    @Resource
    @Lazy
    private RepairWaresService repairWaresService;

    /**
     * 采购单/领料单 新增
     *
     * @param repairSoRespVO 采购单对象
     * @author 小李
     * @date 10:49 2024/9/14
     **/
    @DSTransactional
    @Override
    public void createRepairSo(DlRepairSoRespVO repairSoRespVO) {
        repairSoRespVO.setSoTime(new Date());
        // 加个判断，可能出现没有设置价格的情况
        if (repairSoRespVO.getGoodsList() != null){
            repairSoRespVO.getGoodsList().forEach(item -> {
                if (item.getGoodsPrice() == null){
                    throw exception0(500, "有配件未设置进价");
                }
            });
        }
        //保存供应商
        if (StringUtils.isEmpty(repairSoRespVO.getSupplierId())){
            //采购单中录入供应商或无供应商情况
            if (StringUtils.isNotEmpty(repairSoRespVO.getSupplierName())) {
                //没有选择直接录入的情况
                String supplierId = supplierService.appSaveSupplier(repairSoRespVO.getSupplierName());
                //为供应商id赋值
                repairSoRespVO.setSupplierId(supplierId);
            }
        }
        // 取当前登录用户的门店信息
        Long deptId = SecurityFrameworkUtils.getLoginUserDeptId();
        repairSoRespVO.setDeptId(deptId);

        DeptRespDTO dept = deptApi.getDept(deptId);
        if (ObjectUtil.isNotEmpty(dept)) {
            repairSoRespVO.setCorpId(dept.getCorpId());
            Company company = companyService.getById(dept.getCorpId());
            if (ObjectUtil.isNotEmpty(company)) {
                repairSoRespVO.setCorpName(company.getCorpName());
            }
        }

        // 新增主表
        // 如果是采购单，就把状态变为部分入库
        if (repairSoRespVO.getSoType() != null && repairSoRespVO.getSoType().equals("01")){
            repairSoRespVO.setSoStatus("02");
        }
        baseMapper.insertOrUpdate(repairSoRespVO);
        // 新增子表
        if (CollectionUtil.isEmpty(repairSoRespVO.getGoodsList())) {
            throw exception(RepairErrorCodeConstants.GOODS_IS_EMPTY);
        }
        repairSoRespVO.getGoodsList().forEach(item -> {
            item.setSoId(repairSoRespVO.getId());
//            item.setSoiType(repairSoRespVO.getSoType());
        });
        repairSoiService.saveBatch(repairSoRespVO.getGoodsList());

        // 操作配件库存表
        // 获取所有需要操作的数据----生成采购单的时候，不直接操作库存，放到下面的inWares方法去操作
       if (repairSoRespVO.getSoType() != null && !repairSoRespVO.getSoType().equals("01")){
           List<DlRepairSoi> goodsList = repairSoRespVO.getGoodsList();
           List<String> ids = goodsList.stream().map(DlRepairSoi::getGoodsId).collect(Collectors.toList());
           List<RepairWares> repairWares = waresService.listByIds(ids);
           // 更新库存和进价
           List<RepairWares> newWares = repairWares.stream().map(item -> {
               // 取数据
               DlRepairSoi repairSoi = goodsList.stream().filter(i -> i.getGoodsId().equals(item.getId())).collect(Collectors.toList()).get(0);
               // 设置新值
               // 如果是采购入库，数量+，如果是领料出库，数量-
               // 01, 03 是采购 02 是领料
               BigDecimal count = new BigDecimal(repairSoi.getGoodsCount());
               RepairWares wares = new RepairWares();
               wares.setId(item.getId());
               wares.setStock("02".equals(repairSoRespVO.getSoType()) ? item.getStock().subtract(count) : item.getStock().add(count));
               // 更新进价
               wares.setPurPrice(repairSoi.getGoodsPrice());
               return wares;
           }).collect(Collectors.toList());
           waresService.updateBatchById(newWares);
       }
    }

    /**
     * 采购单/领料单新增分页
     *
     * @param repairSoReqVO 查询对象
     * @author 小李
     * @date 18:14 2024/9/14
     **/
    @Override
    public IPage<DlRepairSo> getRepairSoPage(DlRepairSoReqVO repairSoReqVO, Page<DlRepairSo> page) {
        return baseMapper.getRepairSoPage(repairSoReqVO, page);
    }

    /**
     * 采购单/领料单 作废
     *
     * @param repairSoReqVO 作废对象
     * @author 小李
     * @date 11:12 2024/9/18
     **/
    @Override
    @DSTransactional
    public void voidRepairSo(DlRepairSoReqVO repairSoReqVO) {
        baseMapper.updateById(repairSoReqVO);

        // 下面的代码是因为这个接口还有地方在用
        // 查主表
        DlRepairSo so = baseMapper.selectById(repairSoReqVO.getId());
        // 查当前登录操作人的userId
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        // 如果主表记录的领退料人与操作人一致，即是员工点击的作废，即需要通知仓库
        boolean flag = so.getUserId().equals(loginUserId);
        if (flag) {
            repairWorkerService.sentMessage(Long.valueOf(so.getCreator()), (so.getSoType().equals("02") ? "领料单:" : "退料单:") + so.getSoNo() + "已被" + so.getUserName() + "作废");
            // 需要更新库存和申请表数据
            // 查单据子表
            List<DlRepairSoi> sois = repairSoiService.list(new LambdaQueryWrapper<DlRepairSoi>().in(DlRepairSoi::getSoId, so.getId()));
            // 查要操作申请表子表
            List<DlTwItem> oldTwItems = twItemService.list(new LambdaQueryWrapper<DlTwItem>().and(item -> {
                item.eq(DlTwItem::getTwId, so.getTwId())
                        .in(DlTwItem::getWaresId, sois.stream().map(DlRepairSoi::getGoodsId).collect(Collectors.toList()));
            }));
            // 查要操作的配件
            List<RepairWares> oldWares = repairWaresService.list(new LambdaQueryWrapper<RepairWares>().in(RepairWares::getId, sois.stream().map(DlRepairSoi::getGoodsId).collect(Collectors.toList())));
            // 新的申请表子表数据和配件数据
            List<DlTwItem> newTwItems = new ArrayList<>();
            List<RepairWares> newWares = new ArrayList<>();
            // 需要区分是领料还是退料
            // 得到新申请表子表数据
            oldTwItems.forEach(item -> {
                DlTwItem dlTwItem = new DlTwItem();
                dlTwItem.setId(item.getId());
                sois.stream().filter(i -> i.getGoodsId().equals(item.getWaresId())).findFirst().ifPresent(repairSoiByTwItem -> {
                    if (so.getSoType().equals("02")){
                        dlTwItem.setWaresAlreadyCount(item.getWaresAlreadyCount() - repairSoiByTwItem.getGoodsCount());
                        dlTwItem.setWaresCouldCount(item.getWaresCouldCount() + repairSoiByTwItem.getGoodsCount());
                        dlTwItem.setWaresStatus("02");
                    }else {
                        dlTwItem.setWaresAlreadyCount(item.getWaresAlreadyCount() + repairSoiByTwItem.getGoodsCount());
                        dlTwItem.setWaresCouldCount(item.getWaresCouldCount() - repairSoiByTwItem.getGoodsCount());
                    }
                });
                newTwItems.add(dlTwItem);
            });
            // 得到新配件数据
            oldWares.forEach(item -> {
                RepairWares wares = new RepairWares();
                wares.setId(item.getId());
                sois.stream().filter(i -> i.getGoodsId().equals(wares.getId())).findFirst().ifPresent(repairSoiByWares -> {
                    if (so.getSoType().equals("02")){
                        wares.setStock(item.getStock().add(BigDecimal.valueOf(repairSoiByWares.getGoodsCount())));
                    }else {
                        wares.setStock(item.getStock().subtract(BigDecimal.valueOf(repairSoiByWares.getGoodsCount())));
                    }
                });
                newWares.add(wares);
            });

            // 更新申请表子表
            twItemService.updateBatchById(newTwItems);
            // 更新配件
            repairWaresService.updateBatchById(newWares);
        }
    }

    /**
     * 采购单/领料单 查看
     *
     * @param id 主键
     * @author 小李
     * @date 9:34 2024/9/22
     **/
    @Override
    public DlRepairSoRespVO getRepairSoById(String id) {
        // 查主表
        DlRepairSo dlRepairSo = baseMapper.selectById(id);
        DlRepairSoRespVO result = BeanUtil.toBean(dlRepairSo, DlRepairSoRespVO.class);

        // 查子表
        List<DlRepairSoi> list = repairSoiService.list(new LambdaQueryWrapper<DlRepairSoi>().eq(DlRepairSoi::getSoId, result.getId()));
        if (!list.isEmpty()) {
            //所有有配件的分类
            List<Map<String, String>> typeMapList = waresService.getAllTypeList();
            Map<String, String> typeMap = new HashMap<>();
            for (Map<String, String> map : typeMapList) {
                typeMap.put(map.get("id"), map.get("name"));
            }
            //关联查配件信息
            List<RepairWares> repairWaresList = waresService.listByIds(list.stream().map(DlRepairSoi::getGoodsId).collect(Collectors.toList()));
            Map<String, RepairWares> waresMap = repairWaresList.stream().collect(Collectors.toMap(RepairWares::getId, Function.identity()));
            list.forEach(item -> {
                item.setWares(waresMap.get(item.getGoodsId()));
                item.setTypeName(typeMap.get(item.getWares().getType()));
            });
        }
        result.setGoodsList(list);
        return result;
    }

    /**
     * 员工确认领料
     *
     * @param id 单据ID 领料单主表
     * @author 小李
     * @date 11:58 2024/10/21
     **/
    @Override
    @DSTransactional
    public void confirmGet(String id) {
        // 查子表
        List<DlRepairSoi> sois = repairSoiService
                .list(new LambdaQueryWrapper<DlRepairSoi>()
                        .eq(DlRepairSoi::getSoId, id)
                );
        // 查库存---生成领料单的时候更新了
//        List<RepairWares> wares = waresService
//                .list(new LambdaQueryWrapper<RepairWares>()
//                        .in(RepairWares::getId, sois.stream()
//                                .map(DlRepairSoi::getGoodsId)
//                                .collect(Collectors.toList())
//                        ));
//        // 更新库存
//        List<RepairWares> newWares = wares.stream().map(item -> {
//            RepairWares ware = new RepairWares();
//            ware.setId(item.getId());
//            sois.stream().filter(i -> i.getGoodsId().equals(item.getId())).findFirst().ifPresent(i -> {
//                ware.setStock(item.getStock().subtract(BigDecimal.valueOf(i.getGoodsCount())));
//            });
//            return ware;
//        }).collect(Collectors.toList());
//        waresService.updateBatchById(newWares);
        // 更新主表状态 为已领料
        DlRepairSo dlRepairSo = new DlRepairSo();
        dlRepairSo.setId(id);
        dlRepairSo.setSoStatus(SoStatusEnum.PICKED.getCode());
        baseMapper.updateById(dlRepairSo);

        // 更新申请表的数据----生成领料单的时候更新了
//        // 查申请表的子表对应的配件信息
//        List<DlTwItem> twItems = twItemService.list(new LambdaQueryWrapper<DlTwItem>().and(item -> {
//            item.eq(DlTwItem::getTwId, so.getTwId())
//                    .in(DlTwItem::getWaresId, sois.stream().map(DlRepairSoi::getGoodsId).collect(Collectors.toList()));
//        }));
//        // 更新子表
//        List<DlTwItem> newTwItems = twItems.stream().map(item -> {
//            DlTwItem dlTwItem = new DlTwItem();
//            dlTwItem.setId(item.getId());
//            dlTwItem.setWaresAlreadyCount(ObjectUtil.isNotEmpty(item.getWaresAlreadyCount()) ? item.getWaresAlreadyCount() + item.getWaresCouldCount() : item.getWaresCouldCount());
//            dlTwItem.setWaresStatus(dlTwItem.getWaresAlreadyCount().equals(item.getWaresCount()) ? "01" : item.getWaresStatus());
//            return dlTwItem;
//        }).collect(Collectors.toList());
//        twItemService.updateBatchById(newTwItems);

        // 查最新的子表信息
        DlRepairSo so = baseMapper.selectOne(new LambdaQueryWrapper<DlRepairSo>().eq(DlRepairSo::getId, id));
        List<DlTwItem> list = twItemService.list(new LambdaQueryWrapper<DlTwItem>().eq(DlTwItem::getTwId, so.getTwId()));
        // 判断是部分完成还是全部完成
        DlTicketWares dlTicketWares = new DlTicketWares();
        dlTicketWares.setId(so.getTwId());
        List<DlTwItem> flag = list.stream().filter(item -> !item.getWaresStatus().equals("01")).collect(Collectors.toList());
        dlTicketWares.setStatus(CollectionUtil.isEmpty(flag) ? "03" : "04");
        // 更新主表的状态
        ticketWaresService.updateById(dlTicketWares);

        // 查主表记录
        DlRepairSo newSo = baseMapper.selectById(id);
        // 通知仓库
        repairWorkerService.sentMessage(Long.valueOf(newSo.getCreator()), newSo.getUserName() + "已确认领料单:" + newSo.getSoNo());
    }

    /**
     * 员工确认退料
     *
     * @param id 退料单主表ID
     * @author 小李
     * @date 19:41 2024/10/21
     **/
    @Override
    @DSTransactional
    public void confirmBack(String id) {
        // 更新主表
        baseMapper.update(new LambdaUpdateWrapper<DlRepairSo>()
                .set(DlRepairSo::getSoStatus, SoStatusEnum.RETURNED.getCode())
                .eq(DlRepairSo::getId, id)
        );
        // 更新配件申请表----生成退料单的时候更新了
//        DlRepairSo so = baseMapper.selectOne(new LambdaQueryWrapper<DlRepairSo>().eq(DlRepairSo::getId, id));
//        // 查配件退料表子表
//        List<DlRepairSoi> sois = repairSoiService.list(new LambdaQueryWrapper<DlRepairSoi>().eq(DlRepairSoi::getSoId, so.getId()));
//        // 查申请表子表
//        List<DlTwItem> twItems = twItemService.list(new LambdaQueryWrapper<DlTwItem>().eq(DlTwItem::getTwId, so.getTwId()));
//        // 得到需要更新的数据
//        List<DlTwItem> newTwItems = twItems.stream().map(item -> {
//            DlTwItem dlTwItem = new DlTwItem();
//            dlTwItem.setId(item.getId());
//            sois.stream().filter(i -> i.getGoodsId().equals(item.getWaresId())).findFirst().ifPresent(i -> {
//                dlTwItem.setWaresBackCount(
//                        ObjectUtil.isNotEmpty(item.getWaresBackCount())
//                                ? item.getWaresCount() + item.getWaresBackCount()
//                                : i.getGoodsCount());
//                // 如果退料数就是领料申请数，那就是全退了
//                if (i.getGoodsCount().equals(dlTwItem.getWaresCount())) {
//                    dlTwItem.setWaresStatus("03");
//                }
//            });
//            return dlTwItem;
//        }).collect(Collectors.toList());
//        twItemService.updateBatchById(newTwItems);
//        // 更新库存
//        // 查库存
//        List<RepairWares> wares = waresService.list(new LambdaQueryWrapper<RepairWares>().in(RepairWares::getId, sois.stream().map(DlRepairSoi::getGoodsId).collect(Collectors.toList())));
//        // 构建新数据
//        List<RepairWares> newWares = wares.stream().map(item -> {
//            RepairWares ware = new RepairWares();
//            ware.setId(item.getId());
//            sois.stream().filter(i -> i.getGoodsId().equals(item.getId())).findFirst().ifPresent(i -> {
//                ware.setStock(item.getStock().add(BigDecimal.valueOf(i.getGoodsCount())));
//            });
//            return ware;
//        }).collect(Collectors.toList());
//        waresService.updateBatchById(newWares);

        // 更新维修工单----最后完成工单的时候来更新
//        // 查配件退料表子表
//        List<DlRepairSoi> sois = repairSoiService.list(new LambdaQueryWrapper<DlRepairSoi>().eq(DlRepairSoi::getSoId, so.getId()));
//        // 查申请表主表
//        DlTicketWares ticketWares = ticketWaresService.getOne(new LambdaQueryWrapper<DlTicketWares>().eq(DlTicketWares::getId, so.getTwId()));
//        // 查维修工单子表为配件的数据
//        List<DlRepairTitem> titems = titemService.list(new LambdaQueryWrapper<DlRepairTitem>().and(item -> {
//            item.eq(DlRepairTitem::getTicketId, ticketWares.getTicketId())
//                    .eq(DlRepairTitem::getItemType, "02")
//                    .in(DlRepairTitem::getPartId, sois.stream().map(DlRepairSoi::getGoodsId).collect(Collectors.toList()));
//        }));
//        // 构建新数据，更新维修工单子表
//        List<DlRepairTitem> newTitems = titems.stream().map(item -> {
//            DlRepairTitem titem = new DlRepairTitem();
//            titem.setId(item.getId());
//            sois.stream().filter(i -> i.getGoodsId().equals(item.getPartId())).findFirst().ifPresent(i -> {
//                titem.setItemCount(item.getItemCount() - i.getGoodsCount());
//                BigDecimal itemDiscount = ObjectUtil.isNotEmpty(item.getItemDiscount()) ? item.getItemDiscount() : BigDecimal.ONE;
//                titem.setItemMoney(new BigDecimal(titem.getItemCount()).multiply(item.getItemPrice()).multiply(itemDiscount));
//            });
//            return titem;
//        }).collect(Collectors.toList());
//        // 分开全部退料了的和没有全部退料的数据
//        List<DlRepairTitem> delTitems = newTitems.stream().filter(item -> item.getItemCount() == 0).collect(Collectors.toList());
//        if (CollectionUtil.isEmpty(delTitems)) {
//            titemService.updateBatchById(newTitems);
//        } else {
//            titemService.removeBatchByIds(delTitems);
//            List<DlRepairTitem> updateTitems = newTitems.stream().filter(item -> !delTitems.contains(item)).collect(Collectors.toList());
//            if (CollectionUtil.isEmpty(updateTitems)) {
//                titemService.updateBatchById(updateTitems);
//            }
//
//        }
//        // 更新维修工单
//        DlRepairTickets tickets = ticketsService.getOne(new LambdaQueryWrapper<DlRepairTickets>().eq(DlRepairTickets::getId, ticketWares.getTicketId()));
//        // 查最新的子表信息
//        List<DlRepairTitem> list = titemService.list(new LambdaQueryWrapper<DlRepairTitem>().in(DlRepairTitem::getTicketId, tickets.getId()));
//        // 计算工单总子项、工单配件总价、工单总价
//        DlRepairTickets newTickets = new DlRepairTickets();
//        newTickets.setId(tickets.getId());
//        newTickets.setCount(list.stream().mapToInt(DlRepairTitem::getItemCount).sum());
//        newTickets.setPartPrice(list.stream()
//                .filter(item -> item.getItemType().equals("02"))
//                .map(DlRepairTitem::getItemMoney)
//                .reduce(BigDecimal.ZERO, BigDecimal::add));
//        BigDecimal projectPrice = tickets.getProjectPrice() == null ? BigDecimal.ZERO : tickets.getProjectPrice();
//        BigDecimal otherPrice = tickets.getOtherPrice() != null ? tickets.getOtherPrice() : BigDecimal.ZERO;
//        BigDecimal partPrice = newTickets.getPartPrice() == null ? BigDecimal.ZERO : newTickets.getPartPrice();
//        newTickets.setTotalPrice(projectPrice.add(partPrice).add(otherPrice));
//        ticketsService.updateById(newTickets);

        // 查主表
        DlRepairSo newSo = baseMapper.selectById(id);
        // 通知仓库
        repairWorkerService.sentMessage(Long.valueOf(newSo.getCreator()), newSo.getUserName() + "已确认退料单:" + newSo.getSoNo());
    }

    /**
     * 采购入库
     *
     * @param reqVO （接参实体中需传入：采购单id，单据编号soNo，备注remark,入库总价totalPrice，子表中商品id，子表中入库数量inCount）
     * @author PQZ
     * @date 14:32 2024/10/24
     **/
    @Override
    @DSTransactional
    public void inWare(DlRepairSoReqVO reqVO) {
        /*1、基础数据准备*/
        //获取当前登录用户
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserRespDTO user = userApi.getUser(userId);
        //采购单
        DlRepairSo dlRepairSo = getById(reqVO.getId());
        //需要保存的入库单
        DlRepairSo inSo = new DlRepairSo();
        //过滤掉入库数量为null或0的情况(此为无效数据)
        List<DlRepairSoi> filterWare = reqVO.getSoiList().stream().filter(item -> item.getInCount() != null && item.getInCount() > 0).collect(Collectors.toList());
        //如果为空代表无需入库
        if (CollectionUtil.isEmpty(filterWare)) {
            return;
        }
        //即将入库采购品
        List<DlRepairSoi> pmsWaresList = repairSoiService.listByIds(filterWare.stream().map(DlRepairSoi::getId).collect(Collectors.toList()));
        //初始化本次入库采购品
        List<DlRepairSoi> inWaresList = new ArrayList<>();
        //原始配件库相关配件---不是用wareId，是用GoodsId，wareId是仓库
        List<RepairWares> waresList = waresService.listByIds(pmsWaresList.stream().map(DlRepairSoi::getGoodsId).collect(Collectors.toList()));

        /*2、采购单转入库单*/
        //入库单关联采购单
        inSo.setMainId(dlRepairSo.getId());
        inSo.setMainTable("dl_repair_so");
        //05表示入库单
        inSo.setSoType("05");
        //入库单号
        inSo.setSoNo(reqVO.getSoNo());
        //入库人
        inSo.setUserId(userId);
        inSo.setUserName(user.getNickname());
        //入库时间
        inSo.setSoTime(new Date());
        //入库商品总价
        inSo.setTotalPrice(reqVO.getTotalPrice());
        save(inSo);

        /*3、入库配件处理*/
        Map<String, DlRepairSoi> filterWareMap = filterWare.stream().collect(Collectors.toMap(DlRepairSoi::getId, soi -> soi));
        pmsWaresList.forEach(item -> {
            DlRepairSoi filterSoi = filterWareMap.get(item.getId());
            DlRepairSoi inWares = BeanUtil.copyProperties(item, DlRepairSoi.class);
            //采购单id
            inWares.setSoId(inSo.getId());
            //采购品原始id
            inWares.setRawId(item.getId());
            //入库数量
            inWares.setInCount(filterSoi.getInCount());
            inWares.setId(null);
            //采购品中入库数量字段累加
            item.setInCount(item.getInCount() == null ? 0 : item.getInCount() + filterSoi.getInCount());
            inWaresList.add(inWares);
        });
        //更新采购品
        repairSoiService.updateBatchById(pmsWaresList);
        //新增入库采购品
        repairSoiService.saveBatch(inWaresList);

        /*4、原始配件库处理*/
        //入库配件按照原始配件库id分组，目的取出数量---不是用wareId，是用GoodsId，wareId是仓库
        Map<String, DlRepairSoi> wareMap = filterWare.stream().collect(Collectors.toMap(DlRepairSoi::getGoodsId, soi -> soi));
        //采购配件按照按照原始配件库id分组，目的取出价格---不是用wareId，是用GoodsId，wareId是仓库
        Map<String, DlRepairSoi> itemsMap = pmsWaresList.stream().collect(Collectors.toMap(DlRepairSoi::getGoodsId,soi -> soi));
        waresList.forEach(item -> {
            DlRepairSoi filterSoi = wareMap.get(item.getId());
            DlRepairSoi itemSoi = itemsMap.get(item.getId());
            //进价
            item.setPurPrice(itemSoi.getGoodsPrice());
            item.setStock((item.getStock() == null ? new BigDecimal(0) : item.getStock()).add(new BigDecimal(filterSoi.getInCount())));
        });
        waresService.updateBatchById(waresList);

        // 更新采购单的状态，如果是全部入库完了，就是03已入库，反之不变
        // 查该采购单的所有采购配件
        List<DlRepairSoi> sois = repairSoiService.list(new LambdaQueryWrapper<DlRepairSoi>().eq(DlRepairSoi::getSoId, reqVO.getId()));
        // 过滤出入库数量大于等于采购数量的数据 （入库数量可以大于采购的数量）
        List<DlRepairSoi> allInSois = sois.stream().filter(item -> item.getInCount() >= item.getGoodsCount()).collect(Collectors.toList());
        // 如果allInSois的size就是sois的size，那就是全部都入库了
        if (CollectionUtil.isNotEmpty(allInSois) && allInSois.size() == sois.size()) {
            // 更新采购单的状态为已入库
            baseMapper.update(new LambdaUpdateWrapper<DlRepairSo>()
                    .set(DlRepairSo::getSoStatus, "03")
                    .eq(DlRepairSo::getId, reqVO.getId())
            );
        }
    }
}




