package cn.ezhizao.project.business.controller;

import java.util.*;
import java.util.stream.Collectors;
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.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
    SysDeptMapper deptMapper;

    @Resource
    private IBizCarrierCategoryService bizCarrierCategoryService;
    @Resource
    HttpServletRequest request;

    /**
     * 查未报工的批次
     */
    @GetMapping("/list")
    public TableDataInfo list(BizLot bizLot) throws NoSuchFieldException, IllegalAccessException
    {
        startPage();
        List<BizLot> list = bizLotService.getList(bizLot);
        return getDataTable(list);
    }
    @GetMapping("/getNotStartList")
    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")
    public TableDataInfo getLotList(BizLot bizLot) throws NoSuchFieldException, IllegalAccessException
    {
//        String tenantId = request.getHeader("tenantId");
//        bizLot.setTenantId(Long.valueOf(tenantId));
        startPage();
        List<BizLot> list = bizLotService.getLotList(bizLot);
        return getDataTable(list);
    }
    @GetMapping("/getLastLot")
    public AjaxResult getLastLot( BizLot bizLot)
    {
//        String tenantId = request.getHeader("tenantId");
//        bizLot.setTenantId(Long.valueOf(tenantId));
        BizLot lastLot = bizLotService.getLastLot(bizLot);
        return success(lastLot);
    }
    /**
     * 查询批次的工序
     */
    @PostMapping("getProcess")
    public AjaxResult getProcess(@RequestBody BizLot bizLot)
    {
        //单批单改或多批单改
        if(bizLot.getIsAmend()==1) {
            QueryWrapper<BizLotTechnologicalProcess> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_stop",0);
            queryWrapper.eq("lot_id",bizLot.getId());
            BizLotTechnologicalProcess technologicalAmend = bizLotTechnologicalProcessService.getOne(queryWrapper);
            QueryWrapper<BizLotTechnologicalProcessDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("technological_amend_id",technologicalAmend.getId());
            List<BizLotTechnologicalProcessDetail> list = bizLotTechnologicalProcessDetailService.list(wrapper);
            return success(list);
        }else{
            //该批是否废品回用
            if(bizLot.getIsWasteRecycling() == 1) {
                QueryWrapper<BizLotTechnologicalProcess> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("lot_id",bizLot.getId());
                BizLotTechnologicalProcess wasteRecycling = bizLotTechnologicalProcessService.getOne(queryWrapper);
                QueryWrapper<BizLotTechnologicalProcessDetail> wrapper = new QueryWrapper<>();
                wrapper.eq("technological_waste_recycling_id",wasteRecycling.getId());
                List<BizLotTechnologicalProcessDetail> list = bizLotTechnologicalProcessDetailService.list(wrapper);
                return success(list);
            }
            //查原始工艺工序表
            else {
                QueryWrapper<BizTechnologicalProcessDetail> wrapper = new QueryWrapper<>();
                wrapper.eq("technological_process_id",bizLot.getTechnologicalProcessId());
                return success(bizTechnologicalProcessDetailService.list(wrapper));
            }
        }
    }

    /**
     * 查询计划单下所有的批次
     */
    @GetMapping("/getLotInfo")
    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);
    }
    /**
     * 通过批次号查找批次信息
     */
    @PostMapping("/getLotInfoByLotCode")
    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, "计划查询数据");
    }
    /**
     * 废品回用
     */
    @PostMapping("/addWasteRecycling")
    @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}")
    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();
        BizDayworkItem conditions = new BizDayworkItem();
        conditions.setLotId(lot.getId());
        List<BizDayworkItem> dayworkItemList = bizDayworkItemService.getList(conditions);
        BizDayworkItem dayworkItem = dayworkItemList.stream().sorted(Comparator.comparing(BizDayworkItem::getCreateTime).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);
        return success(lot);
    }

    @PreAuthorize("@ss.hasPermi('business:lot:add')")
    @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<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("0"): carrierIds).eq("is_changed", 0).list();

        // 箱类型 先不管
        List<BizCarrierCategory> bizCarrierCategories = bizCarrierCategoryService.query().in( "id", carriers.isEmpty() ? Collections.singletonList(0L): carriers.stream().map(BizCarrier::getCategoryId).collect(Collectors.toList())).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()));

        if (dayworks.stream().anyMatch(e -> !baseDayworks.stream().allMatch(v -> v.getProductionPlanDetailId().equals(e.getProductionPlanDetailId())))) {
            return error("载具已绑定其他计划单");
        }
        List<BizDayworkItem> baseDayworkItems = bizDayworkItemService.getList(new BizDayworkItem().setLotId(bizLot.getId()));
        if (baseDayworks.size() > 0) {
            sparateList.forEach(l -> {
                l.setQualifiedNum(l.getLotNumber());
                if (l.getId() == null) {
                    l.setId(snowflakeIdWorker.nextId());
                    // 分批复制报工详情
                    List<BizDaywork> newDayworks = new ArrayList<>();
                    baseDayworks.forEach(v -> {
                        BizDaywork newDaywork = new BizDaywork(v);
                        newDaywork.setId(snowflakeIdWorker.nextId());
                        newDaywork.setProcessQualifiedNum(l.getLotNumber());
                        newDaywork.setTemporaryProcessQualifiedNum(l.getLotNumber());
                        newDaywork.setId(snowflakeIdWorker.nextId());
                        newDaywork.setLotId(l.getId());
                        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())) {
                            BizDayworkItem turnitem = new BizDayworkItem(items.get(0));
                            turnitem.setProdNum(l.getLotNumber());
                            turnitem.setQualifiedNum(l.getQualifiedNum());
                            turnitem.setDayworkId(newDaywork.getId());
                            turnitem.setLotId(l.getId());
                            turnitem.setId(null);
                            bizDayworkItems.add(turnitem);
                            items.subList(1, items.size()).forEach(e -> {
                                BizDayworkItem item = new BizDayworkItem(e);
                                item.setDayworkId(newDaywork.getId());
                                item.setLotId(l.getId());
                                item.setId(null);
                                bizDayworkItems.add(item);
                            });
                        } 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.setId(null);
                                bizDayworkItems.add(item);
                            });
                            BizDayworkItem latestItem = currentItems.get(0);
                            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(null);
                            latestItem.setLotId(l.getId());
                            bizDayworkItems.add(latestItem);
                        }
                        // 判断最后一个报工是那种情况
                        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 {
                    BizDaywork bizDaywork = baseDayworks.isEmpty() ? null : baseDayworks.get(0);
                    if (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());
                        bizDayworkItems.add(latestItem);
                    } else if (Arrays.asList("4", "5", "7").contains(latestItem.getStatus())) {
                        // 假设最新是周转，只改周转数量
                        latestItem.setProdNum(l.getLotNumber());
                        latestItem.setQualifiedNum(l.getLotNumber());
                        bizDayworkItems.add(latestItem);
                    } else {
                        // 删除多的报工，只保留第一条并将状态改成最大的状态。
                        List<BizDayworkItem> currentItems = baseDayworkItems.stream().filter(v -> v.getTechnologicalProcessDetailId().equals(latestItem.getTechnologicalProcessId())).sorted(Comparator.comparing(BizDayworkItem::getCreateTime)).collect(Collectors.toList());
                        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());
                        bizDayworkItems.add(updateItem);
                        delDayworkItems.addAll(currentItems.stream().filter(e -> currentItems.stream().noneMatch(t -> t.getId().equals(e.getId()))).collect(Collectors.toList()));
                    }
                }
            });
        }
        // 将报工信息复制一份
        return toAjax(
                bizLotService.saveOrUpdateBatch(sparateList) &&
                        (bizDayworks.isEmpty() || bizDayworkService.saveOrUpdateBatch(bizDayworks)) &&
                        (delDayworkItems.isEmpty() || bizDayworkItemService.removeBatchByIds(delDayworkItems)) &&
                        (bizDayworkItems.isEmpty() || bizDayworkItemService.saveOrUpdateBatch(bizDayworkItems)) &&
                        (newDayworkCarriers.isEmpty() || dayworkCarrierService.saveBatch(newDayworkCarriers))
        );
//        return toAjax(true);
    }
}
