package cn.ezhizao.project.business.service.impl;

import cn.ezhizao.common.utils.SecurityUtils;
import cn.ezhizao.project.business.domain.*;
import cn.ezhizao.project.business.mapper.BizDayworkCarrierMapper;
import cn.ezhizao.project.business.mapper.BizDayworkItemMapper;
import cn.ezhizao.project.business.mapper.BizDayworkMapper;
import cn.ezhizao.project.business.mapper.BizTurnoverMapper;
import cn.ezhizao.project.business.service.IBizDayworkItemService;
import cn.ezhizao.project.system.domain.SysDept;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.jdbc.Null;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 报工记录Service业务层处理
 *
 * @author ezhizao
 * @date 2023-12-04
 */
@Service
public class BizDayworkItemServiceImpl extends ServiceImpl<BizDayworkItemMapper, BizDayworkItem> implements IBizDayworkItemService {
    @Resource
    private BizDayworkItemMapper bizDayworkItemMapper;
    @Resource
    private BizDayworkMapper bizDayworkMapper;
    @Resource
    private BizDayworkCarrierMapper bizDayworkCarrierMapper;

    @Resource
    private BizOutsourcedOrderDetailProcessServiceImpl bizOutsourcedOrderDetailProcessService;

    @Resource
    private BizOutsourcedOrderServiceImpl bizOutsourcedOrderService;
    @Resource
    private BizOutsourcedOrderDetailServiceImpl bizOutsourcedOrderDetailService;
    @Resource
    private BizTurnoverMapper bizTurnoverMapper;

    /**
     * 查询报工记录列表
     *
     * @param bizDayworkItem 报工记录
     * @return 报工记录
     */
    @Override
    public List<BizDayworkItem> getList(BizDayworkItem bizDayworkItem) {
        return bizDayworkItemMapper.getList(bizDayworkItem);
    }

    @Override
    public List<BizDayworkItem> getOutsourcesItemList(BizDayworkItem bizDayworkItem) {
        return bizDayworkItemMapper.getOutsourcesItemList(bizDayworkItem);
    }

    @Override
    public List<SysDept> getDeptInfo(BizDayworkItem bizDayworkItem) {
        return bizDayworkItemMapper.getDeptInfo(bizDayworkItem);
    }

    @Override
    public List<BizDayworkItem> getListByDayworkIds(List<Long> ids) {
        return bizDayworkItemMapper.getListByDayworkIds(ids);
    }

    @Override
    public List<BizDayworkItem> getListInfoByDayworkIds(List<Long> ids) {
        return bizDayworkItemMapper.getListInfoByDayworkIds(ids);
    }

    @Override
    public List<BizDayworkItem> getListByDayworkIdAndProcessStepNumber(BizDayworkItem bizDayworkItem) {
        return bizDayworkItemMapper.getListByDayworkIdAndProcessStepNumber(bizDayworkItem);
    }

    @Override
    public List<BizDayworkItem> getListByDayworkItemIds(List<Long> ids) {
        return bizDayworkItemMapper.getListByDayworkItemIds(ids);
    }


    @Override
    public List<BizDayworkItem> getListByDayworkIdsForOutsourced(List<Long> ids) {
        return bizDayworkItemMapper.getListByDayworkIdsForOutsourced(ids);
    }

    @Override
    public List<BizDayworkItem> getListByLotIds(List<Long> ids) {
        return bizDayworkItemMapper.getListByLotIds(ids);
    }

    /**
     * 查询设备信息
     *
     * @param bizProductionResourceGroupDetail
     * @return
     */
    @Override
    public BizProductionResourceGroupDetail getEquipmentInfo(BizProductionResourceGroupDetail bizProductionResourceGroupDetail) {
        return bizDayworkItemMapper.getEquipmentInfo(bizProductionResourceGroupDetail);
    }

    /**
     * 物理删除
     *
     * @param bizDayworkItem
     * @return 删除结果
     */
    @Override
    public int physicalDelete(BizDayworkItem bizDayworkItem) {
        return bizDayworkItemMapper.physicalDelete(bizDayworkItem);
    }

    @Override
    public void updateDayworkItem(BizDayworkItem bizDayworkItem) {
        bizDayworkItemMapper.updateDayworkItem(bizDayworkItem);
    }

    @Override
    public List<BizDayworkItem> getItemScreen(Long dayWorkId) {
        return bizDayworkItemMapper.getItemScreen(dayWorkId);
    }

    @Override
    public List<BizDayworkItem> selectDayworkItemList(BizDayworkItem item) {
        return bizDayworkItemMapper.selectDayworkItemList(item);
    }

    @Override
    public int updateTechnologicalProcessDetailId(Long dayWorkId) {
        return bizDayworkItemMapper.updateTechnologicalProcessDetailId(dayWorkId);
    }

    @Override
    public List<BizDayworkItem> selectLatestItemByDayworkIds(List<Long> dayworkIds) {
        return bizDayworkItemMapper.selectLatestItemByDayworkIds(dayworkIds);
    }

    @Override
    public List<BizDayworkItem> selectItemByOutsourcedDetailIds(List<Long> ids) {
        return bizDayworkItemMapper.selectItemByOutsourcedDetailIds(ids);
    }
    @Override
    @Transactional
    public void saveDayworkItemForOutsource(List<BizOutsourcedOrderDetail> outsourcedOrderDetails) {
        /**********查询周转新信息修改周转状态，新增一条外协部门报工信息，将对应daywork状态修改为进行中************/
        List<BizDayworkItem> dayworkItems = new ArrayList<>();//原周转信息集合
        List<BizDayworkItem> newDayworkItems = new ArrayList<>();//新增报工信息集合
        //修改报工信息
        outsourcedOrderDetails.forEach(detail -> {
            //查询周转信息
            BizDayworkItem bizDayworkItem = new BizDayworkItem();
            bizDayworkItem.setDayworkId(detail.getDayworkId());
            bizDayworkItem.setOutsourceDetailId(detail.getId());
            bizDayworkItem = bizDayworkMapper.getItemListFromOutsourced(bizDayworkItem).get(0);
            //修改状态
            bizDayworkItem.setStatus("7");
            dayworkItems.add(bizDayworkItem);
            //每一道工序新增一条报工信息
            BizDayworkItem finalBizDayworkItem = bizDayworkItem;
            detail.getProcesses().forEach(process -> {
                //新的报工信息
                BizDayworkItem newBizDayworkItem = new BizDayworkItem();
                newBizDayworkItem.setDayworkId(detail.getDayworkId());
                newBizDayworkItem.setOutsourceDetailId(detail.getId());
                newBizDayworkItem.setLotId(detail.getLotId());
                newBizDayworkItem.setProcessId(process.getProcessId());
                newBizDayworkItem.setProcessStepNumber(process.getProcessStepNumber());
                newBizDayworkItem.setStatus("1");
                newBizDayworkItem.setProdNum(detail.getProductNum());
                newBizDayworkItem.setDeptId(finalBizDayworkItem.getDeptId());
                newBizDayworkItem.setDeptName(finalBizDayworkItem.getDeptName());
                newBizDayworkItem.setStartTime(new Date());
                newBizDayworkItem.setDeptCode(finalBizDayworkItem.getDeptCode());
                newBizDayworkItem.setProductionPlanDetailId(finalBizDayworkItem.getProductionPlanDetailId());
                newBizDayworkItem.setTechnologicalProcessId(finalBizDayworkItem.getTechnologicalProcessId());
                newBizDayworkItem.setTechnologicalProcessDetailId(process.getTechnologicalProcessDetailId());
                newBizDayworkItem.setIsWx(1);
                newBizDayworkItem.setFormDayworkItemId(1L);
                newBizDayworkItem.setNickName(detail.getSupplierName());
                newBizDayworkItem.setTenantId(SecurityUtils.getLoginUser().getTenantId());
                newDayworkItems.add(newBizDayworkItem);
            });
        });
        saveOrUpdateBatch(dayworkItems);
        saveBatch(newDayworkItems);
    }

    @Override
    @Transactional
    public List<BizDaywork> saveDayworkItemForInnerOutsource(List<BizOutsourcedOrderDetail> outsourcedOrderDetails,BizOutsourcedOrder outsourcedOrder) {
        /**********查询周转新信息修改周转状态，新增一条外协部门报工信息，将对应daywork状态修改为进行中************/
        List<BizDayworkItem> dayworkItems = new ArrayList<>();//原周转信息集合
        List<BizDayworkItem> newDayworkItems = new ArrayList<>();//新增周转信息集合
        List<BizDaywork> dayworkList = new ArrayList<>();
        List<BizDaywork> bizDayworkList = bizDayworkMapper.selectBatchIds(outsourcedOrderDetails.stream().map(BizOutsourcedOrderDetail::getDayworkId).collect(Collectors.toList()));
        //查询周转区
        BizTurnover turnover = bizTurnoverMapper.getTurnoverByDeptId(outsourcedOrder.getOutsourceDeptId());
        //修改报工信息
        outsourcedOrderDetails.forEach(detail -> {
            //查询周转信息
            BizDayworkItem bizDayworkItem = new BizDayworkItem();
            bizDayworkItem.setDayworkId(detail.getDayworkId());
            bizDayworkItem.setOutsourceDetailId(detail.getId());
            bizDayworkItem = bizDayworkMapper.getItemListFromOutsourced(bizDayworkItem).get(0);

            //修改状态
            bizDayworkItem.setStatus("7");
            dayworkItems.add(bizDayworkItem);
            //修改daywork的下序工段及合格数
            BizDaywork daywork = bizDayworkList.stream().filter(bizDaywork -> bizDaywork.getId().equals(detail.getDayworkId())).findFirst().orElse(new BizDaywork());
            daywork.setDeptId(outsourcedOrder.getOutsourceDeptId());
            daywork.setTemporaryProcessQualifiedNum(detail.getProductNum());
            dayworkList.add(daywork);
            //新增周转明细
            BizDayworkItem newBizDayworkItem = new BizDayworkItem();
            newBizDayworkItem.setDayworkId(detail.getDayworkId());
            newBizDayworkItem.setOutsourceDetailId(detail.getId());
            newBizDayworkItem.setLotId(detail.getLotId());
            newBizDayworkItem.setProcessId(bizDayworkItem.getProcessId());
            newBizDayworkItem.setProcessStepNumber(bizDayworkItem.getProcessStepNumber());
            newBizDayworkItem.setStatus("4");
            newBizDayworkItem.setProdNum(detail.getProductNum());
            newBizDayworkItem.setQualifiedNum(detail.getProductNum());
            newBizDayworkItem.setDeptId(outsourcedOrder.getOutsourceDeptId());
            newBizDayworkItem.setDeptName(outsourcedOrder.getOutsourceDeptName());
            newBizDayworkItem.setFromDeptId(bizDayworkItem.getDeptId());
            newBizDayworkItem.setFromDeptName(bizDayworkItem.getDeptName());
            newBizDayworkItem.setStartTime(new Date());
            newBizDayworkItem.setProductionPlanDetailId(bizDayworkItem.getProductionPlanDetailId());
            newBizDayworkItem.setTechnologicalProcessId(bizDayworkItem.getTechnologicalProcessId());
            newBizDayworkItem.setTechnologicalProcessDetailId(bizDayworkItem.getTechnologicalProcessDetailId());
            newBizDayworkItem.setIsWx(1);
            newBizDayworkItem.setTurnoverType("2");
            newBizDayworkItem.setTurnoverArea(turnover.getCode());
            newBizDayworkItem.setTurnoverId(turnover.getId().toString());
            newBizDayworkItem.setFormDayworkItemId(1L);
            newBizDayworkItem.setUserId(SecurityUtils.getLoginUser().getUserId());
            newBizDayworkItem.setNickName(SecurityUtils.getLoginUser().getUser().getNickName());
            newBizDayworkItem.setUserName(SecurityUtils.getLoginUser().getUser().getUserName());
            newBizDayworkItem.setTenantId(SecurityUtils.getLoginUser().getTenantId());
            newDayworkItems.add(newBizDayworkItem);

//            //每一道工序新增一条报工信息
//            BizDayworkItem finalBizDayworkItem = bizDayworkItem;
//            detail.getProcesses().forEach(process -> {
//                //新的报工信息
//                BizDayworkItem newBizDayworkItem = new BizDayworkItem();
//                newBizDayworkItem.setDayworkId(detail.getDayworkId());
//                newBizDayworkItem.setOutsourceDetailId(detail.getId());
//                newBizDayworkItem.setLotId(detail.getLotId());
//                newBizDayworkItem.setProcessId(process.getProcessId());
//                newBizDayworkItem.setProcessStepNumber(process.getProcessStepNumber());
//                newBizDayworkItem.setStatus("1");
//                newBizDayworkItem.setProdNum(detail.getProductNum());
//                newBizDayworkItem.setDeptId(finalBizDayworkItem.getDeptId());
//                newBizDayworkItem.setDeptName(finalBizDayworkItem.getDeptName());
//                newBizDayworkItem.setStartTime(new Date());
//                newBizDayworkItem.setDeptCode(finalBizDayworkItem.getDeptCode());
//                newBizDayworkItem.setProductionPlanDetailId(finalBizDayworkItem.getProductionPlanDetailId());
//                newBizDayworkItem.setTechnologicalProcessId(finalBizDayworkItem.getTechnologicalProcessId());
//                newBizDayworkItem.setTechnologicalProcessDetailId(process.getTechnologicalProcessDetailId());
//                newBizDayworkItem.setIsWx(1);
//                newBizDayworkItem.setFormDayworkItemId(1L);
//                newBizDayworkItem.setNickName(detail.getSupplierName());
//                newDayworkItems.add(newBizDayworkItem);
//            });
        });
        saveOrUpdateBatch(dayworkItems);
        saveBatch(newDayworkItems);
        return dayworkList;
    }
    @Override
    @Transactional
    public List<BizDaywork> updateDayworkItemForInnerOutsource(List<BizOutsourcedOrderDetail> outsourcedOrderDetails,List<BizOutsourcedOrderDetail> oldOutsourcedOrderDetails,BizOutsourcedOrder outsourcedOrder) {
        //如果有报工记录则不对dayworkItem进行操作
        //查询周转区
        BizTurnover turnover = bizTurnoverMapper.getTurnoverByDeptId(outsourcedOrder.getOutsourceDeptId());
        List<Long> newOutsourceDetailIds = outsourcedOrderDetails.stream().map(BizOutsourcedOrderDetail::getId).collect(Collectors.toList());
        List<Long> newDayworkIds = outsourcedOrderDetails.stream().map(BizOutsourcedOrderDetail::getDayworkId).collect(Collectors.toList());
        List<Long> oldOutsourceDetailIds = oldOutsourcedOrderDetails.stream().map(BizOutsourcedOrderDetail::getId).collect(Collectors.toList());
        List<Long> oldDayworkIds = oldOutsourcedOrderDetails.stream().map(BizOutsourcedOrderDetail::getDayworkId).collect(Collectors.toList());
        List<Long> totalDayworkIds = Stream.concat(newDayworkIds.stream(), oldDayworkIds.stream())
                .distinct()
                .collect(Collectors.toList());
        //新增的外协批次
        List<BizDayworkItem> dayworkItemList = getListByDayworkIds(totalDayworkIds);
        List<BizDaywork> bizDayworkList = bizDayworkMapper.selectBatchIds(totalDayworkIds);
        List<BizDayworkItem> needAddedDayworkItem = new ArrayList<>();
        List<BizDayworkItem> needUpdateDayworkItem = new ArrayList<>();
        List<BizDayworkItem> needRemoveDayworkItem = new ArrayList<>();
        List<BizDaywork> needUpdateDaywork = new ArrayList<>();
        newOutsourceDetailIds.forEach(id ->{
            //新增
            if(!oldOutsourceDetailIds.contains(id)) {
                BizOutsourcedOrderDetail detail = outsourcedOrderDetails.stream().filter(item -> item.getId().equals(id)).collect(Collectors.toList()).get(0);
                BizDayworkItem bizDayworkItem = dayworkItemList.stream().filter(item -> item.getDayworkId().equals(detail.getDayworkId())).sorted(Comparator.comparing(BizDayworkItem::getCreateTime).reversed()).collect(Collectors.toList()).get(0);
                    bizDayworkItem.setStatus("7");
                    needUpdateDayworkItem.add(bizDayworkItem);
                //新增周转明细
                BizDayworkItem newBizDayworkItem = new BizDayworkItem();
                newBizDayworkItem.setDayworkId(detail.getDayworkId());
                newBizDayworkItem.setOutsourceDetailId(detail.getId());
                newBizDayworkItem.setLotId(detail.getLotId());
                newBizDayworkItem.setProcessId(bizDayworkItem.getProcessId());
                newBizDayworkItem.setProcessStepNumber(bizDayworkItem.getProcessStepNumber());
                newBizDayworkItem.setStatus("4");
                newBizDayworkItem.setProdNum(detail.getProductNum());
                newBizDayworkItem.setQualifiedNum(detail.getProductNum());
                newBizDayworkItem.setDeptId(outsourcedOrder.getOutsourceDeptId());
                newBizDayworkItem.setDeptName(outsourcedOrder.getOutsourceDeptName());
                newBizDayworkItem.setFromDeptId(bizDayworkItem.getDeptId());
                newBizDayworkItem.setFromDeptName(bizDayworkItem.getDeptName());
                newBizDayworkItem.setStartTime(new Date());
                newBizDayworkItem.setProductionPlanDetailId(bizDayworkItem.getProductionPlanDetailId());
                newBizDayworkItem.setTechnologicalProcessId(bizDayworkItem.getTechnologicalProcessId());
                newBizDayworkItem.setTechnologicalProcessDetailId(bizDayworkItem.getTechnologicalProcessDetailId());
                newBizDayworkItem.setIsWx(1);
                newBizDayworkItem.setTurnoverType("2");
                newBizDayworkItem.setTurnoverArea(turnover.getCode());
                newBizDayworkItem.setTurnoverId(turnover.getId().toString());
                newBizDayworkItem.setFormDayworkItemId(1L);
                newBizDayworkItem.setUserId(SecurityUtils.getLoginUser().getUserId());
                newBizDayworkItem.setNickName(SecurityUtils.getLoginUser().getUser().getNickName());
                newBizDayworkItem.setUserName(SecurityUtils.getLoginUser().getUser().getUserName());
                newBizDayworkItem.setTenantId(SecurityUtils.getLoginUser().getTenantId());
                //修改daywork
                needAddedDayworkItem.add(newBizDayworkItem);
                BizDaywork daywork = bizDayworkList.stream().filter(item -> item.getId().equals(detail.getDayworkId())).findFirst().orElse(null);
                daywork.setTemporaryProcessQualifiedNum(detail.getProductNum());
                needUpdateDaywork.add(daywork);
            }else{
                //原本有，判断是否存在报工，如果存在报工，则不修改daywork
                List<BizDayworkItem> collect = dayworkItemList.stream().filter(item -> item.getOutsourceDetailId().equals(id)).collect(Collectors.toList());
                if(!collect.isEmpty() && collect.size()==1) {
                    BizOutsourcedOrderDetail detail = outsourcedOrderDetails.stream().filter(item -> item.getId().equals(id)).collect(Collectors.toList()).get(0);
                    BizDaywork daywork = bizDayworkList.stream().filter(item -> item.getId().equals(detail.getDayworkId())).findFirst().orElse(null);
                    daywork.setTemporaryProcessQualifiedNum(detail.getProductNum());
                    needUpdateDaywork.add(daywork);
                }
            }
        });
        //删除的外协批次
        oldOutsourceDetailIds.forEach(id ->{
            if(!newOutsourceDetailIds.contains(id)) {
                BizOutsourcedOrderDetail detail = oldOutsourcedOrderDetails.stream().filter(item -> item.getId().equals(id)).collect(Collectors.toList()).get(0);
                needRemoveDayworkItem.addAll(dayworkItemList.stream().filter(item -> item.getOutsourceDetailId().equals(id)).collect(Collectors.toList()));
                //同时修改daywork的周转工段及合格数量
                BizDayworkItem lastDayworkItem = dayworkItemList.stream().filter(item -> !item.getOutsourceDetailId().equals(id) && item.getDayworkId().equals(detail.getDayworkId())).sorted(Comparator.comparing(BizDayworkItem::getCreateTime).reversed()).collect(Collectors.toList()).get(0);
                List<BizDayworkItem> lastDayworkItemList = dayworkItemList.stream().filter(item -> item.getDayworkId().equals(detail.getDayworkId()) && item.getProcessStepNumber().equals(lastDayworkItem.getProcessStepNumber()) && (item.getStatus().equals("2") || item.getStatus().equals("3"))).collect(Collectors.toList());
                int sum = lastDayworkItemList.stream().mapToInt(BizDayworkItem::getQualifiedNum).sum();
                BizDaywork daywork = bizDayworkList.stream().filter(item -> item.getId().equals(detail.getDayworkId())).collect(Collectors.toList()).get(0);
                daywork.setDeptId(lastDayworkItem.getDeptId());
                daywork.setProcessQualifiedNum(sum);
                daywork.setTemporaryProcessQualifiedNum(sum);
                needUpdateDaywork.add(daywork);
            }
        });
      saveBatch(needAddedDayworkItem);
      updateBatchById(needUpdateDayworkItem);
      removeBatchByIds(needRemoveDayworkItem);
      return needUpdateDaywork;
    }

    @Override
    @Transactional
    public void updateDayworkItemForOutsource(List<BizOutsourcedOrderDetail> outsourcedOrderDetails,List<BizOutsourcedOrderDetail> oldOutsourcedOrderDetails) {
        //编辑发出单对dayworkItem进行操作
        List<Long> dayworkIds = outsourcedOrderDetails.stream().filter(item ->item.getProductionDeptId() ==null || item.getProductionDeptId() ==0 ).map(BizOutsourcedOrderDetail::getDayworkId).collect(Collectors.toList());
        if (!dayworkIds.isEmpty()) {
            List<Long> outsourcedDetailIds = outsourcedOrderDetails.stream().filter(item -> item.getProductionDeptId() == null || item.getProductionDeptId() == 0).map(BizOutsourcedOrderDetail::getId).collect(Collectors.toList());
            List<Long> totalIds = new ArrayList<>();
            totalIds.addAll(dayworkIds);
            totalIds.addAll(oldOutsourcedOrderDetails.stream().filter(item -> item.getProductionDeptId() == null || item.getProductionDeptId() == 0).map(BizOutsourcedOrderDetail::getDayworkId).collect(Collectors.toList()));
            List<BizDayworkItem> dayworkItemList = getListByDayworkIds(totalIds.stream().distinct().collect(Collectors.toList()));
            //如果是新增的外协明细，则拿到报工信息最新一条，如果is_wx = 0，则吧状态置为7
            List<BizDayworkItem> needUpdateStatus = new ArrayList<>();
            for (int i = 0; i < dayworkIds.size(); i++) {
                Long dayworkId = dayworkIds.get(i);
                BizDayworkItem bizDayworkItem = dayworkItemList.stream().filter(item -> item.getDayworkId().equals(dayworkId)).sorted(Comparator.comparing(BizDayworkItem::getCreateTime).reversed()).collect(Collectors.toList()).get(0);
                if (bizDayworkItem.getIsWx() == 0) {
                    bizDayworkItem.setStatus("7");
                    needUpdateStatus.add(bizDayworkItem);
                }
            }
            if (needUpdateStatus.size() > 0) {
                updateBatchById(needUpdateStatus);
            }
            //判断dayworkItem需要删除、新增、修改
            List<BizDayworkItem> needDeletedDayworkItem = new ArrayList<>();
            List<BizDayworkItem> needAddedDayworkItem = new ArrayList<>();
            List<BizDayworkItem> needUpdateDayworkItem = new ArrayList<>();
            //通过明细id查到添加的dayworkItem
            //通过外协发出单主表id查出原发出单的外协明细（页面删除外协明细）
            List<Long> originalOutsourcedDetailIds = oldOutsourcedOrderDetails.stream().filter(item -> item.getProductionDeptId() == null || item.getProductionDeptId() == 0).map(BizOutsourcedOrderDetail::getId).collect(Collectors.toList());
            originalOutsourcedDetailIds.forEach(item -> {
                //如果新的发出单明细没有不包含旧的，则查询出来dayworkItem然后删除
                if (!outsourcedDetailIds.contains(item)) {
                    needDeletedDayworkItem.addAll(dayworkItemList.stream().filter(info -> info.getOutsourceDetailId().equals(item)).collect(Collectors.toList()));
                }
            });
            outsourcedOrderDetails.stream().filter(item -> item.getProductionDeptId() == null || item.getProductionDeptId() == 0).forEach(detail -> {
                List<BizDayworkItem> originalDayworkItem = dayworkItemList.stream().filter(item -> item.getOutsourceDetailId().equals(detail.getId())).collect(Collectors.toList());
                List<String> newProcessStepNumberList = detail.getProcesses().stream().map(BizOutsourcedOrderDetailProcess::getProcessStepNumber).collect(Collectors.toList());
                //拿到最新的报工明细的工段
                BizDayworkItem lastDayworkItem = dayworkItemList.stream().filter(item -> item.getDayworkId().equals(detail.getDayworkId())).sorted(Comparator.comparing(BizDayworkItem::getCreateTime).reversed()).collect(Collectors.toList()).get(0);
                if (!originalDayworkItem.isEmpty()) {
                    //需要删除的报工明细
                    List<String> oldProcessStepNumberList = originalDayworkItem.stream().map(BizDayworkItem::getProcessStepNumber).collect(Collectors.toList());
                    originalDayworkItem.forEach(item -> {
                        if (!newProcessStepNumberList.contains(item.getProcessStepNumber())) {
                            needDeletedDayworkItem.add(item);
                        }
                    });
                    //需要新增的报工明细
                    detail.getProcesses().forEach(process -> {
                        //新的报工信息
                        if (!oldProcessStepNumberList.contains(process.getProcessStepNumber())) {
                            BizDayworkItem newBizDayworkItem = new BizDayworkItem();
                            newBizDayworkItem.setDayworkId(detail.getDayworkId());
                            newBizDayworkItem.setOutsourceDetailId(detail.getId());
                            newBizDayworkItem.setLotId(detail.getLotId());
                            newBizDayworkItem.setProcessId(process.getProcessId());
                            newBizDayworkItem.setProcessStepNumber(process.getProcessStepNumber());
                            newBizDayworkItem.setStatus("1");
                            newBizDayworkItem.setProdNum(detail.getProductNum());
                            newBizDayworkItem.setDeptId(lastDayworkItem.getDeptId());
                            newBizDayworkItem.setDeptName(lastDayworkItem.getDeptName());
                            newBizDayworkItem.setStartTime(new Date());
                            newBizDayworkItem.setProductionPlanDetailId(lastDayworkItem.getProductionPlanDetailId());
                            newBizDayworkItem.setTechnologicalProcessId(lastDayworkItem.getTechnologicalProcessId());
                            newBizDayworkItem.setTechnologicalProcessDetailId(process.getTechnologicalProcessDetailId());
                            newBizDayworkItem.setIsWx(1);
                            newBizDayworkItem.setTenantId(SecurityUtils.getLoginUser().getTenantId());
                            needAddedDayworkItem.add(newBizDayworkItem);
                        } else {
                            //编辑报工信息
                            BizDayworkItem newBizDayworkItem = new BizDayworkItem();
                            newBizDayworkItem.setDayworkId(detail.getDayworkId());
                            newBizDayworkItem.setOutsourceDetailId(detail.getId());
                            newBizDayworkItem.setLotId(detail.getLotId());
                            newBizDayworkItem.setProcessId(process.getProcessId());
                            newBizDayworkItem.setProcessStepNumber(process.getProcessStepNumber());
                            newBizDayworkItem.setStatus("1");
                            newBizDayworkItem.setProdNum(detail.getProductNum());
                            newBizDayworkItem.setDeptId(lastDayworkItem.getDeptId());
                            newBizDayworkItem.setDeptName(lastDayworkItem.getDeptName());
//                        newBizDayworkItem.setStartTime(new Date());
                            newBizDayworkItem.setProductionPlanDetailId(lastDayworkItem.getProductionPlanDetailId());
                            newBizDayworkItem.setTechnologicalProcessId(lastDayworkItem.getTechnologicalProcessId());
                            newBizDayworkItem.setTechnologicalProcessDetailId(process.getTechnologicalProcessDetailId());
                            newBizDayworkItem.setIsWx(1);
                            newBizDayworkItem.setNickName(detail.getSupplierName());
                            newBizDayworkItem.setTenantId(SecurityUtils.getLoginUser().getTenantId());
                            needUpdateDayworkItem.add(newBizDayworkItem);
                        }
                    });
                } else {
                    //执行新增
                    detail.getProcesses().forEach(process -> {
                        //新的报工信息
                        BizDayworkItem newBizDayworkItem = new BizDayworkItem();
                        newBizDayworkItem.setDayworkId(detail.getDayworkId());
                        newBizDayworkItem.setOutsourceDetailId(detail.getId());
                        newBizDayworkItem.setLotId(detail.getLotId());
                        newBizDayworkItem.setProcessId(process.getProcessId());
                        newBizDayworkItem.setProcessStepNumber(process.getProcessStepNumber());
                        newBizDayworkItem.setStatus("1");
                        newBizDayworkItem.setProdNum(detail.getProductNum());
                        newBizDayworkItem.setDeptId(lastDayworkItem.getDeptId());
                        newBizDayworkItem.setDeptName(lastDayworkItem.getDeptName());
                        newBizDayworkItem.setStartTime(new Date());
                        newBizDayworkItem.setProductionPlanDetailId(lastDayworkItem.getProductionPlanDetailId());
                        newBizDayworkItem.setTechnologicalProcessId(lastDayworkItem.getTechnologicalProcessId());
                        newBizDayworkItem.setTechnologicalProcessDetailId(process.getTechnologicalProcessDetailId());
                        newBizDayworkItem.setIsWx(1);
                        newBizDayworkItem.setNickName(detail.getSupplierName());
                        needAddedDayworkItem.add(newBizDayworkItem);
                    });
                }
            });
            if (!needDeletedDayworkItem.isEmpty()) {
                removeBatchByIds(needDeletedDayworkItem);
            }
            if (!needAddedDayworkItem.isEmpty()) {
                saveBatch(needAddedDayworkItem);
            }
            if (!needUpdateDayworkItem.isEmpty()) {
                updateBatchById(needUpdateDayworkItem);
            }
        }
    }


    @Override
    public void removeByOutsourceIds(List<Long> ids) {
        List<BizDayworkItem> dayworkItemList = selectItemByOutsourcedDetailIds(ids);
        removeBatchByIds(dayworkItemList);

    }

    @Override
    public Long getLatestDayworkItemId(BizDayworkItem bizDayworkItem) {
        return bizDayworkItemMapper.getLatestDayworkItemId(bizDayworkItem);
    }

    @Override
    public BizDayworkItem getLastItem(BizDayworkItem bizDayworkItem) {
        return bizDayworkItemMapper.getLastItem(bizDayworkItem);
    }

    @Override
    public List<BizDayworkItem> getLastFinished(BizDayworkItem dayworkItem) {
        return bizDayworkItemMapper.getLastFinished(dayworkItem);
    }

    @Override
    public List<BizDayworkItem> getSpecialList(BizDayworkItem dayworkItem) {
        return  bizDayworkItemMapper.getSpecialList(dayworkItem);
    }

    /**
     * 查询特殊报工信息，先查询所有是特殊报工(is_special=1)的明细(daywork_item)的数据查出来，查询时跟据创建时间正序排列
     * 再根据dayweokId进行分组，将最后一条报工状态大于4的去掉，因为状态大于4表示搬运已经进行周转或已经送达
     * 再判断最后一条报工是状态是否大于3，如果大于3则表示已经提交了周转申请工段已经发生变化所有如果最后一条报工大于3则需要取上一条报工
     * 根据报工信息的工段来判断是否为当前登陆人员选择的工段，如果是则将该条dayworkdId存到集合里查询
     */
    @Override
    public List<Long> screenDayworkItem(List<BizDayworkItem> dayworkItemList, BizDayworkItem bizDayworkItem) {
        //按照dayworkid分组
        Map<Long, List<BizDayworkItem>> groupedMap = dayworkItemList.stream().collect(Collectors.groupingBy(BizDayworkItem::getDayworkId));
        List<List<BizDayworkItem>> itemList = new ArrayList<>(groupedMap.values());
        //查询出符合当前选择工段的数据
        //符合条件的数据
        List<Long> ids=new ArrayList<>();
        for (List<BizDayworkItem> items : itemList) {
            if (!items.isEmpty()) {
                BizDayworkItem currentItem = items.get(items.size() - 1); // 获取最后一个元素
                //如果最后一条数据状态>4,表示搬运已经进行周转或已经送达，跳出当前循环不做查询
                if(Integer.parseInt(currentItem.getStatus()) > 4){
                    continue;
                }
                //根据查询条件查询最一条状态是否符合查询状态，不符合直接跳出
                if(bizDayworkItem.getItemStatus()!=null && Integer.parseInt(currentItem.getStatus())!=bizDayworkItem.getItemStatus()){
                    continue;
                }

                // 如果当前元素的 status 大于 3，则查找上一条数据
                if (Integer.parseInt(currentItem.getStatus()) > 3 && items.size() > 1) {
                    currentItem = items.get(items.size() - 2); // 获取倒数第二个元素
                }

                if(bizDayworkItem.getDeptId()!=null){
                    // 比较 deptId 是否一致
                    if (Objects.equals(currentItem.getDeptId(), bizDayworkItem.getDeptId())) {
                        ids.add(currentItem.getDayworkId());
                    }
                }else {
                    ids.add(currentItem.getDayworkId());
                }
            }
        }
        //将符合条件的dayworkId返回
        return ids;
    }


    @Override
    public List<BizDayworkItem> selectListOfspecial(List<BizDaywork> dayworks) {
        return bizDayworkItemMapper.selectListOfspecial(dayworks);
    }

    @Override
    public List<BizDayworkItem> selectBydayworkId(List<Long> dayworkIds) {
        return bizDayworkItemMapper.selectBydayworkId(dayworkIds);
    }

    @Override
    public int removeSpecial(List<Long> firstDayworkIds) {
        return bizDayworkItemMapper.removeSpecial(firstDayworkIds);
    }

    @Override
    public List<BizDayworkItem> getListForLotTechnological(BizDayworkItem bizDayworkItem) {
        return bizDayworkItemMapper.getListForLotTechnological(bizDayworkItem);
    }


    /**
     * 保存工序结束时当前工序箱数
     * @param dayworkItems
     */
    @Override
    public void saveCarrierNum(List<BizDayworkItem> dayworkItems) {
        /**
         * 1.因为只在工序结束时保存箱数所以在传入的dayworkItem集合中筛选出status=3的数据
         * 2.根据筛选出的数据中的dayworkId查询出当前绑定的箱数，只计算普通蓝箱子和铁箱子，不计算外协箱子，检测箱子
         * 3.将对应的箱数保存到dayworkItem中
         */

        //将工序已完成status='3'的数据筛选出来
        List<BizDayworkItem> dayworkItemList=dayworkItems.stream().filter(item -> "3".equals(item.getStatus())).collect(Collectors.toList());
        if(!dayworkItemList.isEmpty()){
            // 提取dayworkId到一个新的集合中
            List<Long> dayworkIds = dayworkItemList.stream()
                    .map(BizDayworkItem::getDayworkId) // 提取dayworkId
                    .collect(Collectors.toList()); // 收集到新的列表中

            //根据dayworkId查询绑定信息只查询蓝箱子和铁箱子
            List<BizDayworkCarrier> dayworkCarriers=bizDayworkCarrierMapper.getListBayDayworkId(dayworkIds);
            Map<Long, Integer> countsByDayworkId = dayworkCarriers.stream().collect(Collectors.groupingBy(BizDayworkCarrier::getDayworkId,Collectors.summingInt(carrier -> 1)));

            //将对应的箱数保存到dayworkItem中
            for (BizDayworkItem dayworkItem:dayworkItemList){
                dayworkItem.setCarrierNum(countsByDayworkId.get(dayworkItem.getDayworkId()));
            }
            super.saveOrUpdateBatch(dayworkItemList);

        }

    }


}
