package cn.ezhizao.project.business.controller;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.common.utils.uuid.SnowflakeIdWorker;
import cn.ezhizao.framework.aspectj.lang.annotation.Excel;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.domain.*;
import cn.ezhizao.project.business.service.*;
import cn.ezhizao.project.system.domain.SysDept;
import cn.ezhizao.project.system.mapper.SysDeptMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 计划查询Controller
 *
 * @author ezhizao
 * @date 2024-04-09
 */
@RestController
@RequestMapping("/business/lot")
public class BizLotController extends BaseController {
    @Resource
    private IBizLotService bizLotService;

    @Resource
    private IBizLotTechnologicalProcessService bizLotTechnologicalProcessService;

    @Resource
    private IBizLotTechnologicalProcessDetailService bizLotTechnologicalProcessDetailService;
    @Resource
    private IBizTechnologicalProcessDetailService bizTechnologicalProcessDetailService;
    @Resource
    private IBizProductionPlanDetailService bizProductionPlanDetailService;
    @Resource
    private IBizProductService bizProductService;
    @Resource
    private IBizDayworkItemService bizDayworkItemService;
    @Resource
    private IBizDayworkService bizDayworkService;
    @Resource
    private SnowflakeIdWorker snowflakeIdWorker;
    @Resource
    IBizDayworkCarrierService dayworkCarrierService;
    @Resource
    IBizCarrierService carrierService;
    @Resource
    private IBizProcessService bizProcessService;
    @Resource
    private IBizFurnaceNoInfoService bizFurnaceNoInfoService;
    @Resource
    SysDeptMapper deptMapper;
    @Resource
    private IBizQuickDayworkNextInfoService bizQuickDayworkNextInfoService;
    @Resource
    private IBizCarrierCategoryService bizCarrierCategoryService;
    @Resource
    private IBizProcessInspecionService bizProcessInspecionService;
    @Resource
    private IBizDayworkAuxiliaryItemService bizDayworkAuxiliaryItemsService;
    @Resource
    private IBizDayworkItemRejectService bizDayworkItemRejectService;
    @Resource
    HttpServletRequest request;

    /**
     * 查未报工的批次
     */
    @GetMapping("/list")
    @Log(title = "查询报工批次", businessType = BusinessType.SELECT)
    public TableDataInfo list(BizLot bizLot) throws NoSuchFieldException, IllegalAccessException {
        startPage();
        List<BizLot> list = bizLotService.getList(bizLot);
        return getDataTable(list);
    }

    @GetMapping("/getNotStartList")
    @Log(title = "获取未开始批次", businessType = BusinessType.SELECT)
    public TableDataInfo getNotStartList(BizProductionPlanDetail data) throws NoSuchFieldException, IllegalAccessException {
        startPage();
        List<BizLot> list = bizLotService.getNotStartList(data);
        return getDataTable(list);
    }

    /**
     * 查询所有的批次
     */
    @PreAuthorize("@ss.hasPermi('business:lot:list')")
    @GetMapping("/getLotList")
    @Log(title = "查询所有批次", businessType = BusinessType.SELECT)
    public TableDataInfo getLotList(BizLot bizLot) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizLot);
//        String tenantId = request.getHeader("tenantId");
//        bizLot.setTenantId(Long.valueOf(tenantId));
        if (bizLot.getStartTime() != null) {
            bizLot.setStartTime(bizLot.getStartTime() + " 00:00:00");
        }
        if (bizLot.getEndTime() != null) {
            bizLot.setEndTime(bizLot.getEndTime() + " 23:59:59");
        }
        startPage();
        List<BizLot> list = bizLotService.getLotList(bizLot);
        //拿到所有lotId
        List<Long> lotIds = new ArrayList<>();
        //
        return getDataTable(list);
    }

    @GetMapping("/getLastLot")
    @Log(title = "获取最后一个批次", businessType = BusinessType.SELECT)
    public AjaxResult getLastLot(BizLot bizLot) {
//        String tenantId = request.getHeader("tenantId");
//        bizLot.setTenantId(Long.valueOf(tenantId));
        BizLot lastLot = bizLotService.getLastLot(bizLot);
        return success(lastLot);
    }

    @GetMapping("/getLastLotBeforeGen")
    @Log(title = "获取最后一个批次", businessType = BusinessType.SELECT)
    public AjaxResult getLastLotBeforeGen(BizLot bizLot) {
//        String tenantId = request.getHeader("tenantId");
//        bizLot.setTenantId(Long.valueOf(tenantId));
        // 获取生产计划单
        // 获取生产计划单的追加数量和总数量
        // 生成尾批编码
        BizProductionPlanDetail conditions = new BizProductionPlanDetail();
        conditions.setId(bizLot.getProductionPlanDetailId());
        List<BizProductionPlanDetail> bizProductionPlanDetail = bizProductionPlanDetailService.getList(conditions);

        final String baseCode = bizProductionPlanDetail.get(0).getProductionPlanNo().substring(0, 4);
        final String baseCodeSeq = bizProductionPlanDetail.get(0).getProductionPlanNo().substring(4, 7) + bizProductionPlanDetail.get(0).getLineNumber().toString();
//        BizLot lastLot = bizLotService.getLastLot(bizLot);
        String latestCode = baseCode + baseCodeSeq + String.format("%03d", bizProductionPlanDetail.get(0).getTotalLotNumber() + bizProductionPlanDetail.get(0).getSuperadditionTotalNumber() + bizProductionPlanDetail.get(0).getWasteRecyclingNumber()) + "0";
        bizLot.setLotCode(latestCode);
        return success(bizLot);
    }

    @GetMapping("/getAllLot")
    @Log(title = "获取计划单下所有批次", businessType = BusinessType.SELECT)
    public AjaxResult getAllLot(BizProductionPlanDetail productionPlanDetail) {
        List<BizLot> list = bizLotService.getAllLot(productionPlanDetail.getId());
        return success(list);
    }

    /**
     * 查询批次的工序
     */
    @PostMapping("/getProcess")
    @Log(title = "查询批次工序", businessType = BusinessType.SELECT)
    public AjaxResult getProcess(@RequestBody BizLot bizLot) {
        //单批单改或多批单改
        if (bizLot.getIsAmend() == 1 || bizLot.getIsWasteRecycling() == 1) {
            QueryWrapper<BizLotTechnologicalProcessDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("lot_technological_process_id", bizLot.getTechnologicalProcessId());
            List<BizLotTechnologicalProcessDetail> list = bizLotTechnologicalProcessDetailService.list(wrapper);
            return success(list);
        } else {
            //查原始工艺工序表
            QueryWrapper<BizTechnologicalProcessDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("technological_process_id", bizLot.getTechnologicalProcessId()).ne("tenant_id", 9);
            return success(bizTechnologicalProcessDetailService.list(wrapper));
        }
    }

    /**
     * 查询计划单下所有的批次
     */
    @GetMapping("/getLotInfo")
    @Log(title = "查询计划单下所有的批次", businessType = BusinessType.SELECT)
    public TableDataInfo getLotInfo(BizProductionPlanDetail bizProductionPlanDetail) throws NoSuchFieldException, IllegalAccessException {
//        String tenantId = request.getHeader("tenantId");
//        bizLot.setTenantId(Long.valueOf(tenantId));
        startPage();
        List<BizLot> list = bizLotService.getLotInfo(bizProductionPlanDetail);
        return getDataTable(list);
    }

    @GetMapping("/getProcessList")
    @Log(title = "获取工序列表", businessType = BusinessType.SELECT)
    public AjaxResult getProcessList(BizLot bizLot) throws NoSuchFieldException, IllegalAccessException {
        if (bizLot.getStartTime() != null) {
            bizLot.setStartTime(bizLot.getStartTime() + " 00:00:00");
        }
        if (bizLot.getEndTime() != null) {
            bizLot.setEndTime(bizLot.getEndTime() + " 23:59:59");
        }
        //通过时间查询当前工序
        QueryWrapper<BizLot> queryWrapper = new QueryWrapper<>();
        if (bizLot.getStartTime() != null) {
            queryWrapper.gt("create_time", bizLot.getStartTime());
        }
        if (bizLot.getEndTime() != null) {
            queryWrapper.lt("create_time", bizLot.getEndTime());
        }
        if (bizLot.getLotCode() != null) {
            queryWrapper.like("lot_code", bizLot.getLotCode());
        }
        QueryWrapper<BizProductionPlanDetail> wrapper = new QueryWrapper<>();
        if (bizLot.getProductionPlanNo() != null) {
            wrapper.like("production_plan_no", bizLot.getProductionPlanNo());
        }
        if (bizLot.getLineNumber() != null) {
            wrapper.eq("line_number", bizLot.getLineNumber());
        }
        if (bizLot.getProductDescription() != null) {
            wrapper.like("product_description", bizLot.getProductDescription());
        }
        List<BizProductionPlanDetail> bizProductionPlanDetailList = bizProductionPlanDetailService.list(wrapper);
        List<Long> bizProductionPlanDetailIds = bizProductionPlanDetailList.stream().map(BizProductionPlanDetail::getId).collect(Collectors.toList());
        queryWrapper.in("production_plan_detail_id", bizProductionPlanDetailIds.isEmpty() ? Collections.singletonList(0L) : bizProductionPlanDetailIds);
        List<BizLot> bizLotList = bizLotService.list(queryWrapper);
        List<Long> lotIds = bizLotList.stream().map(BizLot::getId).collect(Collectors.toList());
        //查询dayworkList
        List<BizDaywork> dayworkList = bizDayworkService.query().in("lot_id", lotIds.isEmpty() ? Collections.singletonList(0L) : bizLotList.stream().map(BizLot::getId).collect(Collectors.toList())).list();
        List<Long> dayworkIds = dayworkList.stream().map(BizDaywork::getId).collect(Collectors.toList());
        List<BizDayworkItem> dayworkItemList = new ArrayList<>();
        //查询dayworkItemList
        if (!dayworkIds.isEmpty()) {
            dayworkItemList = bizDayworkItemService.getListByDayworkIds(dayworkIds);
        }
        //拿到所有的工序
        List<BizProcess> bizProcessList = bizProcessService.query().list();
        List<BizProcess> processList = new ArrayList<>();
        for (Long item : dayworkIds) {
            BizProcess process = new BizProcess();
            //拿到最新一条报工
            BizDayworkItem bizDayworkItem = dayworkItemList.stream().filter(daywork -> daywork.getDayworkId().equals(item)).max(Comparator.comparing(BizDayworkItem::getCreateTime)).orElse(null);
            if (bizDayworkItem != null) {
                process.setValue(bizDayworkItem.getProcessId());
                process.setLabel(bizProcessList.stream().filter(item1 -> item1.getId().equals(bizDayworkItem.getProcessId())).collect(Collectors.toList()).get(0).getProcessAlias());
                if (bizLot.getProcessAlias() == null || process.getLabel().contains(bizLot.getProcessAlias())) {
                    processList.add(process);
                }
            }
        }
        return success(processList.stream().distinct().collect(Collectors.toList()));
    }

    /**
     * 通过批次号查找批次信息
     */
    @PostMapping("/getLotInfoByLotCode")
    @Log(title = "通过批次号查询批次信息", businessType = BusinessType.SELECT)
    public AjaxResult getLotInfoByLotCode(@RequestBody BizLot bizLot) throws NoSuchFieldException, IllegalAccessException {
        QueryWrapper<BizLot> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("lot_code", bizLot.getLotCode());
        return success(bizLotService.getOne(queryWrapper));
    }

    /**
     * 导出计划查询列表
     */
    @PreAuthorize("@ss.hasPermi('business:lot:export')")
    @Log(title = "导出计划查询列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizLot bizLot) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizLot);
        List<BizLot> list = bizLotService.getList(bizLot);
        ExcelUtil<BizLot> util = new ExcelUtil<BizLot>(BizLot.class);
        util.exportExcel(response, list, "计划查询数据");
    }

    /**
     * 废品回用
     */
    @PreAuthorize("@ss.hasPermi('business:lot:wasteRecycling')")
    @PostMapping("/addWasteRecycling")
    @Log(title = "新增废品回用", businessType = BusinessType.INSERT)
    @Transactional
    public AjaxResult addWasteRecycling(@RequestBody BizLot bizLot) {
        //废品回用保存，首先存废品回用新生成的批次
        List<BizLot> lotList = new ArrayList<>();
        for (String item : bizLot.getLotCodeList()) {
            BizLot bizLot1 = new BizLot();
            bizLot1.setLotCode(item);
            bizLot1.setIsWasteRecycling(1L);
            bizLot1.setProductionPlanDetailId(bizLot.getProductionPlanDetailId());
            bizLot1.setTechnologicalProcessId(bizLot.getTechnologicalProcessId());
            bizLot1.setTechnologyVersion(bizLot.getTechnologyVersion());
            bizLot1.setProductId(bizLot.getProductId());
            bizLot1.setProductionQuantity(bizLot.getProductionQuantity());
            bizLot1.setRequisitionDepartmentId(bizLot.getRequisitionDepartmentId());
            bizLot1.setRequisitionDepartmentName(bizLot.getRequisitionDepartmentName());
            lotList.add(bizLot1);
        }
        bizLotService.saveBatch(lotList);
        //新增批次存完,存废品回用工艺表
        List<BizLotTechnologicalProcess> technologicalWasteRecyclingList = new ArrayList<>();
        for (BizLot item : lotList) {
            BizLotTechnologicalProcess bizTechnologicalWasteRecycling = new BizLotTechnologicalProcess();
            bizTechnologicalWasteRecycling.setLotId(item.getId());
            bizTechnologicalWasteRecycling.setLotCode(item.getLotCode());
            bizTechnologicalWasteRecycling.setProductionPlanDetailId(bizLot.getProductionPlanDetailId());
            bizTechnologicalWasteRecycling.setTechnologicalProcessId(bizLot.getTechnologicalProcessId());
            bizTechnologicalWasteRecycling.setTechnologyVersion(bizLot.getTechnologyVersion());
            bizTechnologicalWasteRecycling.setProductDescription(bizLot.getProductDescription());
            bizTechnologicalWasteRecycling.setProductShaftCategory(bizLot.getProcessList().get(0).getProductShaftCategory());
            bizTechnologicalWasteRecycling.setProductCode(bizLot.getProcessList().get(0).getProductCode());
            bizTechnologicalWasteRecycling.setProductId(bizLot.getProductId());
            bizTechnologicalWasteRecycling.setProductShaftCategoryName(bizLot.getProcessList().get(0).getProductShaftCategoryName());
            bizTechnologicalWasteRecycling.setAmendmentVersions(1);
            technologicalWasteRecyclingList.add(bizTechnologicalWasteRecycling);
        }
        bizLotTechnologicalProcessService.saveBatch(technologicalWasteRecyclingList);
        //将废品工艺存回lot表
        for (BizLot item : lotList) {
            for (BizLotTechnologicalProcess info : technologicalWasteRecyclingList) {
                if (item.getId().equals(info.getLotId())) {
                    item.setTechnologicalProcessId(info.getId());
                }
            }
        }
        bizLotService.updateBatchById(lotList);
        //废品工艺表存完，存废品工序表
        List<BizLotTechnologicalProcessDetail> technologicalWasteRecyclingDetailList = new ArrayList<>();
        for (BizLotTechnologicalProcess item : technologicalWasteRecyclingList) {
            for (BizLotTechnologicalProcessDetail info : bizLot.getProcessList()) {
                BizLotTechnologicalProcessDetail bizTechnologicalWasteRecyclingDetail = new BizLotTechnologicalProcessDetail();
                bizTechnologicalWasteRecyclingDetail.setLotTechnologicalProcessId(item.getId());
                bizTechnologicalWasteRecyclingDetail.setLotId(item.getLotId());
                bizTechnologicalWasteRecyclingDetail.setTechnologyVersion(item.getTechnologyVersion());
                bizTechnologicalWasteRecyclingDetail.setProductId(info.getProductId());
                bizTechnologicalWasteRecyclingDetail.setProductCode(info.getProductCode());
                bizTechnologicalWasteRecyclingDetail.setProcessStepNumber(info.getProcessStepNumber());
                bizTechnologicalWasteRecyclingDetail.setProcessId(info.getProcessId());
                bizTechnologicalWasteRecyclingDetail.setProcessKey(info.getProcessKey());
                bizTechnologicalWasteRecyclingDetail.setProcessCode(info.getProcessCode());
                bizTechnologicalWasteRecyclingDetail.setProcessAlias(info.getProcessAlias());
                bizTechnologicalWasteRecyclingDetail.setProductShaftCategory(info.getProductShaftCategory());
                bizTechnologicalWasteRecyclingDetail.setProductShaftCategoryName(info.getProductShaftCategoryName());
                bizTechnologicalWasteRecyclingDetail.setProductDescription(info.getProductDescription());
                technologicalWasteRecyclingDetailList.add(bizTechnologicalWasteRecyclingDetail);
            }
        }
        return success(bizLotTechnologicalProcessDetailService.saveBatch(technologicalWasteRecyclingDetailList));
    }

    /**
     * 获取计划查询详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:lot:query')")
    @GetMapping(value = "/{id}")
    @Log(title = "获取计划查询详细信息", businessType = BusinessType.SELECT)
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bizLotService.getById(id));
    }

    /**
     * 新增计划查询
     */
    @PreAuthorize("@ss.hasPermi('business:lot:add')")
    @Log(title = "新增计划查询", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizLot bizLot) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizLot);
        return toAjax(bizLotService.save(bizLot));
    }

    /**
     * 修改计划查询
     */
    @PreAuthorize("@ss.hasPermi('business:lot:edit')")
    @Log(title = "修改计划查询", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizLot bizLot) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizLot);
        return toAjax(bizLotService.updateById(bizLot));
    }

    /**
     * 删除计划查询
     */
    @PreAuthorize("@ss.hasPermi('business:lot:remove')")
    @Log(title = "删除计划查询", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(bizLotService.removeBatchByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('business:lot:query')")
    @Log(title = "分批信息", businessType = BusinessType.SELECT)
    @PostMapping("/getLotInfoForInBatches")
    public AjaxResult getLotInfoForInBatches(@RequestBody BizLot bizLot) {
        // 分批信息需要批次信息
        List<BizLot> lots = bizLotService.getList(bizLot);
        if (lots.size() == 0) {
            return error("没有找到批次信息");
        }
        BizLot lot = lots.get(0);
        List<BizLot> existsLots = bizLotService.query().likeRight("lot_code", lot.getLotCode().substring(0, lot.getLotCode().length() - 1)).list();
        lot.setLatestLotCode(existsLots.stream().sorted(Comparator.comparing(BizLot::getLotCode).reversed()).findFirst().orElse(new BizLot()).getLotCode());
        // 产品描述
        BizProduct product = bizProductService.getById(lot.getProductId());
        lot.setProductCode(product.getProductCode());
        lot.setProductDescription(product.getDescription());
        // 计划单号
        if (lot.getProductionPlanDetailId() != null) {
            BizProductionPlanDetail productionPlanDetail = bizProductionPlanDetailService.getById(lot.getProductionPlanDetailId());
            lot.setProductionPlanNo(productionPlanDetail.getProductionPlanNo());
            // 下达日期
            lot.setIssueDate(productionPlanDetail.getIssueDate());
        }
        // 当前工段
        BizDaywork bizDaywork = bizDayworkService.query().eq("lot_id", bizLot.getId()).one();
        if (bizDaywork != null) {
            BizDayworkItem conditions = new BizDayworkItem();
            conditions.setDayworkId(bizDaywork.getId());
            List<BizDayworkItem> dayworkItemList = bizDayworkItemService.getList(conditions);
            BizDayworkItem dayworkItem = dayworkItemList.stream().sorted(Comparator.comparing(BizDayworkItem::getProcessStepNumber).thenComparing(BizDayworkItem::getStatus).reversed()).collect(Collectors.toList()).stream().findFirst().orElse(new BizDayworkItem());
            SysDept dept = deptMapper.selectDeptById(dayworkItem.getDeptId());
            lot.setCurrentDept(dept != null ? dept.getDeptName() : null);
            // 当前批次对应箱号
            List<BizDayworkCarrier> dayworkCarriers = dayworkCarrierService.query().in("daywork_id", dayworkItemList.isEmpty() ? Collections.singletonList("0") : dayworkItemList.stream().map(v -> v.getDayworkId()).collect(Collectors.toList())).eq("is_changed", 0).list();
            List<BizCarrier> carriers = new ArrayList<>();
            dayworkCarriers.forEach(l -> {
                BizCarrier carrier = new BizCarrier();
                carrier.setCode(l.getCarrierCode());
                carrier.setId(l.getCarrierId());
                carriers.add(carrier);
            });
            // 判断当前工序是在周转状态还是进行中状态
            Integer qualified = 0;
            if (Arrays.asList("4", "5", "7").contains(dayworkItem.getStatus())) {
                // 假设是周转状态合格数量为prodNum
                qualified = dayworkItem.getProdNum();
            } else {
                // 假设进行中，合格数为已完成的生产的合格数总和
                qualified = dayworkItemList.stream().filter(v -> v.getTechnologicalProcessDetailId().equals(dayworkItem.getTechnologicalProcessDetailId())).mapToInt(BizDayworkItem::getQualifiedNum).sum();
            }
            // 假设是进行中 合格数量是所有正在生产的中已完成的总和
            lot.setQualifiedNum(qualified);
            // 当前工序投产量
            lot.setProdNum(dayworkItem.getProdNum());
            // 当前工段合格数量
            lot.setCarriers(carriers);
            lot.setDaywork(bizDaywork);
        } else {
            lot.setCarriers(new ArrayList<>());
        }
        return success(lot);
    }

    @PreAuthorize("@ss.hasPermi('business:lot:inBatch')")
    @Log(title = "分批保存", businessType = BusinessType.INSERT)
    @PostMapping("/saveIsBatches")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveInBatches(@RequestBody BizLot bizLot) throws NoSuchFieldException, IllegalAccessException {
        List<BizLot> sparateList = bizLot.getSparateList();
        List<BizDaywork> bizDayworks = new ArrayList<>();
        List<BizDayworkItem> bizDayworkItems = new ArrayList<>();
        List<BizDayworkCarrier> newDayworkCarriers = new ArrayList<>();
        List<BizDayworkItem> delDayworkItems = new ArrayList<>();
        List<BizFurnaceNoInfo> furnaceNoInfos = new ArrayList<>();
        List<BizQuickDayworkNextInfo> quickDayworkNextInfos = new ArrayList<>();
        List<BizDayworkItemReject> updateDayworkItemRejects = new ArrayList<>();
        List<BizDayworkItemReject> removeDayworkItemRejects = new ArrayList<>();
        // 判断绑定箱是否重复
        List<Long> carrierIds = new ArrayList<>();
        sparateList.stream().filter(v -> !bizLot.getId().equals(v.getId())).forEach(x -> carrierIds.addAll(x.getCarriers().stream().map(BizCarrier::getId).collect(Collectors.toList())));
        List<BizCarrier> carriers = carrierService.query().in("id", carrierIds.isEmpty() ? Collections.singletonList("0") : carrierIds).list();
        List<BizDayworkCarrier> dayworkCarriers = dayworkCarrierService.query().in("carrier_id", carrierIds.isEmpty() ? Collections.singletonList("-1") : carrierIds).eq("is_changed", 0).list();

        // 判断是否有已经被使用的
        List<BizDaywork> dayworks = bizDayworkService.query().in("id", dayworkCarriers.isEmpty() ? Collections.singletonList("0") : dayworkCarriers.stream().map(BizDayworkCarrier::getDayworkId).collect(Collectors.toList())).list();
        // 判断是否已报工
        List<BizDaywork> baseDayworks = bizDayworkService.getList(new BizDaywork().setLotId(bizLot.getId()));
        List<BizFurnaceNoInfo> oldFurnaceNo = bizFurnaceNoInfoService.query().in("daywork_id", baseDayworks.isEmpty() ? Collections.singletonList("0") : baseDayworks.stream().map(BizDaywork::getId).collect(Collectors.toList())).list();
        // 箱类型 先不管
        List<BizCarrierCategory> bizCarrierCategories = bizCarrierCategoryService.query().in("id", carriers.isEmpty() ? Collections.singletonList(0L) : carriers.stream().map(BizCarrier::getCategoryId).collect(Collectors.toList())).list();

        carriers.forEach(l -> {
            BizCarrierCategory c = bizCarrierCategories.stream().filter(v -> v.getId().equals(l.getCategoryId())).findFirst().orElse(new BizCarrierCategory());
            l.setIsAllowMore(c.getIsAllowMore());
        });
        // 判断是否是铁箱
        for (BizLot lot : sparateList) {
            List<BizCarrier> itemCarrier = carriers.stream().filter(e -> lot.getCarriers().stream().anyMatch(v -> v.getId().equals(e.getId()))).collect(Collectors.toList());
            if (itemCarrier.size() > 1 && itemCarrier.stream().anyMatch(e -> e.getIsAllowMore().equals(1))) {
                return error("一个批次不能绑一个以上铁箱");
            }
            // 判断都是蓝箱子 是否有其他绑定批次
            if (itemCarrier.size() > 0 && itemCarrier.stream().allMatch(item -> item.getIsAllowMore().equals(0) && sparateList.stream().anyMatch(e -> !e.getLotCode().equals(lot.getLotCode()) && e.getCarriers().stream().anyMatch(v -> itemCarrier.stream().anyMatch(t -> t.getId().equals(e.getId())))))) {
                return error("蓝箱不能装多批");
            }
            // 判断蓝箱是否绑定其他批次
            if (itemCarrier.size() > 0 && itemCarrier.stream().allMatch(item -> item.getIsAllowMore().equals(0)) && dayworks.stream().anyMatch(e -> !e.getId().equals(bizLot.getId()))) {
                return error("蓝箱不能绑多批");
            }
        }
        // 判断是否装多批 并且是同一生产计划
        if (dayworks.stream().anyMatch(e -> !baseDayworks.stream().allMatch(v -> v.getProductionPlanDetailId().equals(e.getProductionPlanDetailId())))) {
            return error("载具已绑定其他计划单");
        }
        List<BizDayworkItem> baseDayworkItems;
        if (baseDayworks.size() > 0) {
            baseDayworkItems = bizDayworkItemService.getList(new BizDayworkItem().setDayworkId(baseDayworks.get(0).getId()));
        } else {
            baseDayworkItems = new ArrayList<>();
        }
        String lastProcessStep = baseDayworkItems.stream().max(Comparator.comparing(BizDayworkItem::getProcessStepNumber)).orElse(new BizDayworkItem()).getProcessStepNumber();
        // 判断最后一道工序是否有邀请报工,假设有邀请报工则不可分批
        List<BizDayworkItem> lastProcessItem = baseDayworkItems.stream().filter(v -> v.getProcessStepNumber().equals(lastProcessStep)).collect(Collectors.toList());
        if (lastProcessItem.stream().noneMatch(v -> v.getStatus().compareTo("4") >= 0) && lastProcessItem.stream().anyMatch(v -> !v.getUserId().equals(lastProcessItem.get(0).getUserId()))) {
            return error("最后一道工序存在邀请报工，不能进行分批");
        }
        List<BizDayworkItemReject> latestRejects = bizDayworkItemRejectService.query().in("daywork_item_id", lastProcessItem.isEmpty() ? Collections.singletonList(0L) : lastProcessItem.stream().map(BizDayworkItem::getId).collect(Collectors.toList())).list();
        Map<String, List<BizDayworkItemReject>> rejectGroupByReason = latestRejects.stream().collect(Collectors.groupingBy(BizDayworkItemReject::getReason, Collectors.toList()));
        List<BizQuickDayworkNextInfo> oldQuickDayworkNextInfos = bizQuickDayworkNextInfoService.query().in("daywork_item_id", baseDayworkItems.isEmpty() ? Collections.singletonList(0L) : baseDayworkItems.stream().map(BizDayworkItem::getId).collect(Collectors.toList())).list();
        AtomicBoolean necessaryOfCarrier = new AtomicBoolean(true);
        if (baseDayworks.size() > 0) {
            sparateList.forEach(l -> {
//                l.setQualifiedNum(l.getLotNumber());
                if (l.getId() == null) {
                    l.setFromCount(bizLot.getSplitCount() + 1);
                    l.setId(snowflakeIdWorker.nextId());
                    // 分批复制报工详情
                    baseDayworks.forEach(v -> {
                        BizDaywork newDaywork = new BizDaywork(v);
                        newDaywork.setId(snowflakeIdWorker.nextId());
                        newDaywork.setProcessQualifiedNum(l.getLotNumber());
                        newDaywork.setTemporaryProcessQualifiedNum(l.getLotNumber());
                        newDaywork.setProductionQuantity(l.getLotNumber());
                        newDaywork.setId(snowflakeIdWorker.nextId());
                        newDaywork.setLotId(l.getId());
                        newDaywork.setLotCode(l.getLotCode());
                        bizDayworks.add(newDaywork);
                        List<BizDayworkItem> items = baseDayworkItems.stream().filter(e -> e.getDayworkId().equals(v.getId())).sorted(Comparator.comparing(BizDayworkItem::getCreateTime).reversed()).collect(Collectors.toList());
                        // 最后一个报工是周转 修改周转数量为分批数
                        if (items.size() > 0 && Arrays.asList("4", "7", "5").contains(items.get(0).getStatus())) {
                            // 必须有箱，有箱为true 没有箱为false
                            necessaryOfCarrier.set(necessaryOfCarrier.get() && !l.getCarriers().isEmpty());
                            BizDayworkItem turnitem = new BizDayworkItem(items.get(0));
                            turnitem.setProdNum(l.getQualifiedNum());
                            turnitem.setQualifiedNum(l.getQualifiedNum());
                            turnitem.setDayworkId(newDaywork.getId());
                            turnitem.setLotId(l.getId());
                            turnitem.setId(null);
                            turnitem.setFromLotId(bizLot.getId());
                            turnitem.setIsSplitHistory(1);
                            newDaywork.setTemporaryProcessQualifiedNum(l.getQualifiedNum());

                            items.subList(1, items.size()).forEach(e -> {
                                BizDayworkItem item = new BizDayworkItem(e);
                                item.setCreateTime(e.getCreateTime());
                                item.setDayworkId(newDaywork.getId());
                                item.setLotId(l.getId());
                                item.setId(snowflakeIdWorker.nextId());
                                item.setFromLotId(!item.getFromLotId().equals(0L) ? bizLot.getId() : item.getFromLotId());
                                item.setIsSplitHistory(1);
                                bizDayworkItems.add(item);
                            });
                            bizDayworkItems.add(turnitem);
                        } else {
                            // 最后一个报工不是周转
                            // 获取最后一个报工工序的第一个报工，删除其他然后修改状态为最大的那个
                            List<BizDayworkItem> currentItems = items.stream().filter(e -> e.getTechnologicalProcessDetailId().equals(items.get(0).getTechnologicalProcessDetailId())).sorted(Comparator.comparing(BizDayworkItem::getCreateTime)).collect(Collectors.toList());
                            List<BizDayworkItem> copyItems = items.stream().filter(e -> currentItems.stream().noneMatch(t -> t.getId().equals(e.getId()))).collect(Collectors.toList());
                            copyItems.forEach(e -> {
                                BizDayworkItem item = new BizDayworkItem(e);
                                item.setDayworkId(newDaywork.getId());
                                item.setLotId(l.getId());
                                item.setCreateTime(e.getCreateTime());
                                item.setId(snowflakeIdWorker.nextId());
                                item.setFromLotId(!item.getFromLotId().equals(0L) ? bizLot.getId() : item.getFromLotId());
                                item.setIsSplitHistory(1);
                                bizDayworkItems.add(item);
                                if (item.getIsQuick().equals(1)) {
                                    BizQuickDayworkNextInfo old = oldQuickDayworkNextInfos.stream().filter(a -> a.getDayworkItemId().equals(e.getId())).findFirst().orElse(new BizQuickDayworkNextInfo());
                                    BizQuickDayworkNextInfo quickDayworkNextInfo = new BizQuickDayworkNextInfo(old);
                                    quickDayworkNextInfo.setDayworkItemId(item.getId());
                                    quickDayworkNextInfos.add(quickDayworkNextInfo);
                                }
                            });
                            BizDayworkItem latestItem = new BizDayworkItem(currentItems.get(0));
//                            BizQuickDayworkNextInfo old = oldQuickDayworkNextInfos.stream().filter(a -> a.getDayworkItemId().equals(latestItem.getId())).findFirst().orElse(new BizQuickDayworkNextInfo());
                            BizQuickDayworkNextInfo old = oldQuickDayworkNextInfos.stream().filter(a -> a.getDayworkItemId().equals(currentItems.get(0).getId())).findFirst().orElse(new BizQuickDayworkNextInfo());
                            latestItem.setStatus(currentItems.stream().max(Comparator.comparing(BizDayworkItem::getStatus)).orElse(new BizDayworkItem()).getStatus());
                            latestItem.setProdNum(l.getLotNumber());
                            latestItem.setQualifiedNum(l.getQualifiedNum());
                            latestItem.setDayworkId(newDaywork.getId());
                            latestItem.setId(snowflakeIdWorker.nextId());
                            latestItem.setLotId(l.getId());
                            latestItem.setFromLotId(bizLot.getId());
                            latestItem.setIsSplitHistory(1);
                            if (latestItem.getStatus().equals("3")) {
                                newDaywork.setTemporaryProcessQualifiedNum(l.getQualifiedNum());
                            }
                            if (latestItem.getIsQuick().equals(1)) {
                                BizQuickDayworkNextInfo quickDayworkNextInfo = new BizQuickDayworkNextInfo(old);
                                quickDayworkNextInfo.setDayworkItemId(latestItem.getId());
                                quickDayworkNextInfos.add(quickDayworkNextInfo);
                            }
                            bizDayworkItems.add(latestItem);
                        }
                        oldFurnaceNo.forEach(f -> {
                            BizFurnaceNoInfo furnaceNoInfo = new BizFurnaceNoInfo(f);
                            furnaceNoInfo.setId(null);
                            furnaceNoInfo.setDayworkId(newDaywork.getId());
                            furnaceNoInfos.add(furnaceNoInfo);
                        });
                        // 判断最后一个报工是那种情况
//                        newDayworks.add(newDaywork);
                        // 关联载具
                        l.getCarriers().forEach(e -> {
                            BizDayworkCarrier carrier = new BizDayworkCarrier();
                            BizCarrier item = carriers.stream().filter(x -> x.getId().equals(e.getId())).findFirst().orElse(new BizCarrier());
                            carrier.setCarrierCode(item.getCode());
                            carrier.setLotId(l.getId());
                            carrier.setCarrierId(item.getId());
                            carrier.setProductId(newDaywork.getProductId());
                            carrier.setDayworkId(newDaywork.getId());
                            carrier.setProductionPlanDetailId(newDaywork.getProductionPlanDetailId());
                            carrier.setProductionPlanId(newDaywork.getProductionPlanId());
                            carrier.setProductionPlanDetailSubDetailId(newDaywork.getProductionPlanDetailSubDetailId());
                            carrier.setTechnologicalProcessId(newDaywork.getTechnologicalProcessId());
                            newDayworkCarriers.add(carrier);
                        });
                    });
//                    bizDayworks.addAll(newDayworks);
                } else {
                    l.setSplitCount(l.getSplitCount() + 1);
                    BizDaywork bizDaywork = baseDayworks.isEmpty() ? null : new BizDaywork(baseDayworks.get(0));
                    assert bizDaywork != null;
                    bizDaywork.setProductionQuantity(l.getLotNumber());
                    bizDaywork.setProcessQualifiedNum(l.getLotNumber());
                    bizDaywork.setTemporaryProcessQualifiedNum(l.getLotNumber());
                    bizDayworks.add(bizDaywork);
                    // 本批将当前报工数量改成分批后的数量
                    // 获取最新报工信息
                    BizDayworkItem latestItem = baseDayworkItems.stream().filter(v -> v.getDayworkId().equals(baseDayworks.get(0).getId())).max(Comparator.comparing(BizDayworkItem::getCreateTime)).orElse(new BizDayworkItem());
                    if ("0".equals(latestItem.getStatus())) {
                        // 假设最新报工是状态未开始开始的产品数量
                        latestItem.setProdNum(l.getLotNumber());
                        latestItem.setIsSplitHistory(1);
                        latestItem.setFromLotId(latestItem.getFromLotId().equals(0L) ? bizLot.getId(): latestItem.getFromLotId());
                        bizDayworkItems.add(latestItem);
                    } else if (Arrays.asList("4", "5", "7").contains(latestItem.getStatus())) {
                        // 假设最新是周转，只改周转数量
                        latestItem.setProdNum(l.getQualifiedNum());
                        bizDaywork.setTemporaryProcessQualifiedNum(l.getQualifiedNum());
                        latestItem.setQualifiedNum(l.getQualifiedNum());
                        latestItem.setIsSplitHistory(1);
                        latestItem.setFromLotId(latestItem.getFromLotId().equals(0L) ? bizLot.getId(): latestItem.getFromLotId());
                        if (latestItem.getStatus().equals("3")) {
                            bizDaywork.setTemporaryProcessQualifiedNum(l.getQualifiedNum());
                        }
                        bizDayworkItems.add(latestItem);
                    } else {
                        // 删除多的报工，只保留第一条并将状态改成最大的状态。
                        List<BizDayworkItem> currentItems = baseDayworkItems.stream().filter(v -> v.getTechnologicalProcessDetailId().equals(latestItem.getTechnologicalProcessDetailId())).sorted(Comparator.comparing(BizDayworkItem::getCreateTime)).collect(Collectors.toList());
                        currentItems.forEach(v -> {
                            v.setIsSplitHistory(1);
                            v.setFromLotId(v.getFromLotId().equals(0L) ? bizLot.getId(): v.getFromLotId());
                        });
                        BizDayworkItem updateItem = currentItems.get(0);
                        updateItem.setStatus(currentItems.stream().max(Comparator.comparing(BizDayworkItem::getStatus)).orElse(new BizDayworkItem()).getStatus());
                        updateItem.setProdNum(l.getLotNumber());
                        updateItem.setQualifiedNum(l.getQualifiedNum());
                        long rejectNum = latestRejects.stream().mapToLong(BizDayworkItemReject::getRejectNum).sum();
                        updateItem.setRejectNum(Math.toIntExact(rejectNum));
                        bizDayworkItems.add(updateItem);
                        rejectGroupByReason.forEach((k,v) -> {
                            if (v.size() > 1) {
                                BizDayworkItemReject b = v.get(0);
                                b.setDayworkItemId(updateItem.getId());
                                b.setRejectNum(v.stream().mapToLong(BizDayworkItemReject::getRejectNum).sum());
                                updateDayworkItemRejects.add(b);
                                removeDayworkItemRejects.addAll(v.stream().filter(e -> updateDayworkItemRejects.stream().noneMatch(t -> t.getId().equals(e.getId()))).collect(Collectors.toList()));
                            } else {
                                v.forEach(e -> e.setDayworkItemId(updateItem.getId()));
                                updateDayworkItemRejects.addAll(v);
                            }
                        });
                        delDayworkItems.addAll(currentItems.stream().filter(e -> bizDayworkItems.stream().noneMatch(t -> t.getId().equals(e.getId()))).collect(Collectors.toList()));
                    }
                    List<BizDayworkItem> historyDayworkItem = baseDayworkItems.stream().filter(e -> e.getDayworkId().equals(baseDayworks.get(0).getId())).filter(e -> bizDayworkItems.stream().noneMatch(t -> t.getId().equals(e.getId()))).filter(e -> delDayworkItems.stream().noneMatch(t -> t.getId().equals(e.getId()))).collect(Collectors.toList());
                    historyDayworkItem.forEach(v -> {
                        v.setIsSplitHistory(1);
                        v.setFromLotId(v.getFromLotId().equals(0L) ? bizLot.getId(): v.getFromLotId());
                    });
                    bizDayworkItems.addAll(historyDayworkItem);
                }
            });
        }
        if (!necessaryOfCarrier.get()) {
            return error("周转状态下分批必须绑箱");
        }
        // 将报工信息复制一份
        return toAjax(
                (bizDayworks.isEmpty() || bizDayworkService.saveOrUpdateBatch(bizDayworks)) &&
                        (delDayworkItems.isEmpty() || bizDayworkItemService.removeBatchByIds(delDayworkItems)) &&
                        (bizDayworkItems.isEmpty() || bizDayworkItemService.saveOrUpdateBatch(bizDayworkItems)) &&
                        (newDayworkCarriers.isEmpty() || dayworkCarrierService.saveBatch(newDayworkCarriers)) &&
                        (furnaceNoInfos.isEmpty() || bizFurnaceNoInfoService.saveBatch(furnaceNoInfos)) &&
                        (quickDayworkNextInfos.isEmpty() || bizQuickDayworkNextInfoService.saveBatch(quickDayworkNextInfos)) &&
                        (updateDayworkItemRejects.isEmpty() || bizDayworkItemRejectService.saveOrUpdateBatch(updateDayworkItemRejects)) &&
                        (removeDayworkItemRejects.isEmpty() || bizDayworkItemRejectService.removeBatchByIds(removeDayworkItemRejects)) &&
                        bizLotService.saveOrUpdateBatch(sparateList)
        );
//        return toAjax(true);
    }

    @Log(title = "判断是否可以恢复分批", businessType = BusinessType.SELECT)
    @PostMapping("/checkRecover")
    public AjaxResult checkRecover(@RequestBody BizLot bizLot) {
        // 判断该批次是否为分批
        bizLot = bizLotService.getById(bizLot.getId());
        if (bizLot.getFromId() == null || bizLot.getFromId().equals(0L)) {
            // 没有分批来源不能进行合批
            return error("请选择子批进行还原");
        }
        List<BizLot> bizLotList = bizLotService.query().eq("from_id", bizLot.getFromId()).list();
        BizLot fromLot = bizLotService.getById(bizLot.getFromId());
        // 判断是否有再次分批
        if (bizLotService.query().in("from_id", bizLotList.stream().map(BizLot::getId).collect(Collectors.toList())).count() > 0) {
            return error("该分批有再次分批，不能退回");
        }
        if (!fromLot.getSplitCount().equals(bizLot.getFromCount())) {
            return error("该分批有再次分批不能退回");
        }
        bizLotList = bizLotList.stream().filter(v -> v.getFromCount().equals(fromLot.getSplitCount())).collect(Collectors.toList());
        List<Long> lotIds = bizLotList.stream().map(BizLot::getId).collect(Collectors.toList());
        lotIds.add(fromLot.getId());
        // 判断分批之后有没有新报工/新发出单/新质检 假设有则不能修改
        // 判断分批后是否重新绑定载具 重新绑定载具就不能还原
        // 判断分批后有辅助报工 有则无法还原
        List<BizDaywork> bizDayworks = bizDayworkService.query().in("lot_id", lotIds).list();
        List<BizDayworkItem> bizDayworkItems = bizDayworkItemService.query().in("daywork_id", bizDayworks.isEmpty() ? Collections.singletonList(0L) : bizDayworks.stream().map(BizDaywork::getId).collect(Collectors.toList())).list();
        Date splitDate = bizLotList.stream().max(Comparator.comparing(BizLot::getCreateTime)).orElse(new BizLot()).getCreateTime();
        if (bizDayworkItems.stream().anyMatch(v -> v.getIsSplitHistory().equals(0)) || bizDayworkItems.stream().anyMatch(v -> v.getUpdateTime() != null && v.getUpdateTime().compareTo(splitDate) > 0)) {
            return error("分批后有新报工，无法退回");
        }
        List<BizProcessInspecion> bizProcessInspecions = bizProcessInspecionService.query().in("daywork_id", bizDayworks.isEmpty() ? Collections.singletonList(0L) : bizDayworks.stream().map(BizDaywork::getId).collect(Collectors.toList())).list();
        if (bizProcessInspecions.stream().anyMatch(v -> v.getCreateTime().compareTo(splitDate) > 0)) {
            return error("分批之后有新质检，无法退回");
        }
        List<BizDayworkCarrier> bizDayworkCarriers = dayworkCarrierService.query().in("daywork_id", bizDayworks.isEmpty() ? Collections.singletonList(0L) : bizDayworks.stream().map(BizDaywork::getId).collect(Collectors.toList())).eq("is_changed", 0).list();
        if (bizDayworkCarriers.stream().anyMatch(v -> v.getCreateTime().compareTo(splitDate) > 0)) {
            return error("该批次载具信息已发生变化，无法退回");
        }
        // 判断是否有新的辅助报工
        List<BizDayworkAuxiliaryItem> bizDayworkAuxiliaryItems = bizDayworkAuxiliaryItemsService.query().in("daywork_id", bizDayworks.isEmpty() ? Collections.singletonList(0L) : bizDayworks.stream().map(BizDaywork::getId).collect(Collectors.toList())).list();
        if (bizDayworkAuxiliaryItems.stream().anyMatch(v -> v.getCreateTime().compareTo(splitDate) > 0 || v.getUpdateTime().compareTo(splitDate) > 0)) {
            return error("分批之后修改了辅助报工，无法退回");
        }
        // 以上检测都通过则返回可以退回的批次列表
        bizLotList.add(fromLot);
        return success(bizLotList);
    }

    @Log(title = "还原分批", businessType = BusinessType.UPDATE)
    @PostMapping("/recoverBatches")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult recoverBatches(@RequestBody List<BizLot> bizLotList) {
        List<BizDaywork> bizDayworks = bizDayworkService.query().in("lot_id", bizLotList.isEmpty() ? Collections.singletonList(0L) : bizLotList.stream().map(BizLot::getId).collect(Collectors.toList())).list();
        List<BizDayworkItem> bizDayworkItems = bizDayworkItemService.query().in("daywork_id", bizDayworks.isEmpty() ? Collections.singletonList(0L) : bizDayworks.stream().map(BizDaywork::getId).collect(Collectors.toList())).list();
        List<BizDayworkCarrier> bizDayworkCarriers = dayworkCarrierService.query().in("daywork_id", bizDayworks.isEmpty() ? Collections.singletonList(0L) : bizDayworks.stream().map(BizDaywork::getId).collect(Collectors.toList())).list();
        List<BizQuickDayworkNextInfo> bizQuickDayworkNextInfos = bizQuickDayworkNextInfoService.query().in("daywork_item_id", bizDayworkItems.isEmpty() ? Collections.singletonList(0L) : bizDayworkItems.stream().map(BizDayworkItem::getId).collect(Collectors.toList())).list();
        List<BizFurnaceNoInfo> bizFurnaceNoInfos = bizFurnaceNoInfoService.query().in("daywork_id", bizDayworks.isEmpty() ? Collections.singletonList(0L) : bizDayworks.stream().map(BizDaywork::getId).collect(Collectors.toList())).list();
        // 将子批次的投产数量加到母批次中
        BizLot fromBizLot = bizLotList.stream().filter(v -> bizLotList.stream().anyMatch(t -> t.getFromId().equals(v.getId()))).findFirst().orElse(null);
        if (fromBizLot == null) {
            return error("未查询到母批次，请联系管理员");
        }
        fromBizLot.setSplitCount(fromBizLot.getSplitCount() - 1);
        fromBizLot.setProductionQuantity(bizLotList.stream().mapToInt(BizLot::getProductionQuantity).sum());
        List<BizLot> childLot = bizLotList.stream().filter(v -> !v.getId().equals(fromBizLot.getId())).collect(Collectors.toList());
        List<BizDaywork> childDaywork = bizDayworks.stream().filter(v -> childLot.stream().anyMatch(e -> e.getId().equals(v.getLotId()))).collect(Collectors.toList());
        List<BizDayworkItem> childDayworkItems = bizDayworkItems.stream().filter(v -> childDaywork.stream().anyMatch(e -> e.getId().equals(v.getDayworkId()))).collect(Collectors.toList());
        List<BizDayworkItem> childLatest = new ArrayList<>();
        childDaywork.forEach(l -> {
            List<BizDayworkItem> items = childDayworkItems.stream().filter(v -> v.getDayworkId().equals(l.getId())).sorted(Comparator.comparing(BizDayworkItem::getCreateTime).reversed()).collect(Collectors.toList());
            if (!items.isEmpty()) {
                childLatest.add(items.get(0));
            }
        });
        List<BizDayworkCarrier> childCarrierList = bizDayworkCarriers.stream().filter(v -> childDaywork.stream().allMatch(e -> e.getId().equals(v.getDayworkId()))).collect(Collectors.toList());
        List<BizQuickDayworkNextInfo> childQuickItem = bizQuickDayworkNextInfos.stream().filter(v -> childDayworkItems.stream().anyMatch(t -> t.getId().equals(v.getDayworkItemId()))).collect(Collectors.toList());
        List<BizFurnaceNoInfo> childFurnaceNoInfo = bizFurnaceNoInfos.stream().filter(v -> childDaywork.stream().anyMatch(t -> t.getId().equals(v.getDayworkId()))).collect(Collectors.toList());
        // 将母批次的报工投产数量改为总的报工投产数量
        BizDaywork fromDaywork = bizDayworks.stream().filter(v -> v.getLotId().equals(fromBizLot.getId())).findFirst().orElse(null);
        if (fromDaywork == null) {
            return error("未查到母批次报工，请联系管理员");
        }
//        fromDaywork.setProductionQuantity(bizDayworks.stream().mapToInt(BizDaywork::getProductionQuantity).sum());
        fromDaywork.setProcessQualifiedNum(bizDayworks.stream().mapToInt(BizDaywork::getProcessQualifiedNum).sum());
        fromDaywork.setTemporaryProcessQualifiedNum(bizDayworks.stream().mapToInt(BizDaywork::getTemporaryProcessQualifiedNum).sum());
        // 将母批次的最新报工明细中的合格数改为总合格数
        List<BizDayworkItem> fromDayworkItems = bizDayworkItems.stream().filter(v -> v.getDayworkId().equals(fromDaywork.getId())).sorted(Comparator.comparing(BizDayworkItem::getCreateTime)).collect(Collectors.toList());
        // 获取最新一条报工然后合并prodNum和qualityNumber
        BizDayworkItem latestItem = fromDayworkItems.isEmpty() ? null : fromDayworkItems.get(0);
        List<BizDayworkCarrier> fromDayworkCarriers = bizDayworkCarriers.stream().filter(v -> v.getDayworkId().equals(fromDaywork.getId())).collect(Collectors.toList());
        List<BizQuickDayworkNextInfo> fromQuickInfo = bizQuickDayworkNextInfos.stream().filter(v -> fromDayworkItems.stream().anyMatch(t -> t.getId().equals(v.getDayworkItemId()))).collect(Collectors.toList());
        if (latestItem != null) {
            latestItem.setProdNum(latestItem.getProdNum() + childLatest.stream().mapToInt(BizDayworkItem::getProdNum).sum());
            latestItem.setQualifiedNum(latestItem.getQualifiedNum() + childLatest.stream().mapToInt(BizDayworkItem::getQualifiedNum).sum());
        }
        bizLotService.updateById(fromBizLot);
        bizDayworkService.updateById(fromDaywork);
        bizDayworkItemService.updateById(latestItem);
        // 删除子批次
        bizLotService.removeBatchByIds(childLot);
        // 删除子批次的报工
        bizDayworkService.removeBatchByIds(childDaywork);
        // 删除子批次的报工明细
        bizDayworkItemService.removeBatchByIds(childDayworkItems);
        // 删除子批次快速报工记录
        bizQuickDayworkNextInfoService.removeBatchByIds(childQuickItem);
        // 删除子批次绑定的载具
        dayworkCarrierService.removeBatchByIds(childCarrierList);
        // 删除子批次的炉号
        bizFurnaceNoInfoService.removeBatchByIds(childFurnaceNoInfo);
        return success();
    }

    @Log(title="判断当前箱是否为一箱多批箱", businessType = BusinessType.SELECT)
    @PostMapping("/checkLotCarrierCategory")
    public AjaxResult checkLotCarrierCategory(@RequestBody List<BizLot> bizLot) {
        List<BizDaywork> bizDayworks = bizDayworkService.query().in("lot_id", bizLot.stream().map(BizLot::getId).collect(Collectors.toList())).list();
        List<BizDayworkCarrier> dayworkCarriers = dayworkCarrierService.query().eq("is_changed", 0).in("daywork_id", bizDayworks.isEmpty() ? Collections.singletonList(0L) : bizDayworks.stream().map(BizDaywork::getId).collect(Collectors.toList())).list();
        List<BizCarrier> carriers = carrierService.query().in("id", dayworkCarriers.isEmpty() ? Collections.singletonList(0L) : dayworkCarriers.stream().map(BizDayworkCarrier::getCarrierId).collect(Collectors.toList())).list();
        List<BizCarrierCategory> carrierCategories = bizCarrierCategoryService.query().in("id", carriers.isEmpty() ? Collections.singletonList(0L) : carriers.stream().map(BizCarrier::getCategoryId).collect(Collectors.toList())).list();
        if (carrierCategories.stream().anyMatch(t -> t.getIsAllowMore() == 1)) {
            return error("修改批次有绑定一箱多批的载具，请更换普通载具进行修改");
        } else {
            return success(carriers);
        }
    }
}

