package cn.ezhizao.project.business.controller;

import cn.ezhizao.common.utils.SecurityUtils;
import cn.ezhizao.common.utils.poi.ExcelUtil;
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.domain.SysDeptUser;
import cn.ezhizao.project.system.domain.SysRole;
import cn.ezhizao.project.system.service.ISysConfigService;
import cn.ezhizao.project.system.service.ISysDeptService;
import cn.ezhizao.project.system.service.ISysDeptUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

//import static cn.ezhizao.common.utils.SecurityUtils.getTenantId;

/**
 * 报工Controller
 *
 * @author ezhizao
 * @date 2023-11-29
 */
@RestController
@RequestMapping("/business/productionDaywork")
public class BizDayworkController extends BaseController {
    @Resource
    private IBizDayworkService bizDayworkService;

    @Resource
    private IBizTechnologicalProcessDetailService bizTechnologicalProcessDetailService;

    @Resource
    private IBizLotTechnologicalProcessDetailService bizTechnologicalAmendDetailService;

    @Resource
    private IBizOutsourcedOrderDetailService bizOutsourcedOrderDetailService;

    @Resource
    private IBizDayworkCarrierService bizDayworkCarrierService;

    @Resource
    private IBizLotTechnologicalProcessDetailService bizLotTechnologicalProcessDetailService;

    @Resource
    private IBizLotService bizLotService;
    @Resource
    private IBizCarrierCategoryService bizCarrierCategoryService;

    @Resource
    private IBizProcessService bizProcessService;
    @Resource
    private IBizDayworkQualifiedService bizDayworkQualifiedService;
    @Resource
    private IBizDayworkItemService bizDayworkItemService;
    @Resource
    private IBizDayworkItemRejectService bizDayworkItemRejectService;
    @Resource
    private IBizCarrierService bizCarrierService;
    @Resource
    private IBizReturnReceiptDetailService bizReturnReceiptDetailService;
    @Resource
    private IBizProductionResourceGroupDetailService bizProductionResourceGroupDetailService;
    @Resource
    private IBizLotTechnologicalProcessService bizLotTechnologicalProcessService;
    @Resource
    private IBizProductionPlanDetailService bizProductionPlanDetailService;
    @Resource
    private IBizDayworkItemHistoryService bizDayworkItemHistoryService;
    @Resource
    private IBizProcessInspecionService bizProcessInspecionService;
    @Resource
    private IBizDayworkItemConsultService bizDayworkItemConsultService;
    @Resource
    private IBizDayworkItemMaxHistoryService bizDayworkItemMaxHistoryService;
    @Resource
    private IBizProcessInspectionDetailService bizProcessInspectionDetailService;
    @Resource
    private IBizDayworkItemConsultPictureService bizDayworkItemConsultPictureService;
    @Resource
    private IBizDayworkItemExamineService bizDayworkItemExamineService;
    @Resource
    private IBizDayworkAuxiliaryItemRejectService bizDayworkAuxiliaryItemRejectService;
    @Resource
    private IBizDayworkAuxiliaryItemService bizDayworkAuxiliaryItemService;
    @Resource
    private ISysDeptService deptService;
    @Resource
    private ISysDeptUserService deptUserService;
    @Resource
    private IBizWorkshopService bizWorkshopService;
    @Resource
    private IBizTurnoverService bizTurnoverService;
    @Resource
    private IBizWorkshopTurnoverService bizWorkshopTurnoverService;
    @Resource
    private IBizFurnaceNoInfoService bizFurnaceNoInfoService;
    @Resource
    private IBizOutsourcedOrderDetailProcessService bizOutsourcedOrderDetailProcessService;
    @Resource
    HttpServletRequest request;
    @Resource
    private ISysConfigService configService;

    /**
     * 查询报工列表
     */
    @GetMapping("/list")
    @Log(title = "查询报工列表", businessType = BusinessType.SELECT)
    public TableDataInfo list(BizDaywork bizDaywork) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizDaywork);
        List<BizDayworkItem> allDayworkItemList = bizDayworkItemService.selectTurnoverList(bizDaywork);
        if(!allDayworkItemList.isEmpty()){
            bizDaywork.setDayworkIds(allDayworkItemList.stream().map(BizDayworkItem::getDayworkId).collect(Collectors.toList()));
        }

        startPage();

        //查询当前生产子计划的批次报工列表
//        try {
            List<BizDaywork> dayworkList = bizDayworkService.getList(bizDaywork);
            if(dayworkList.isEmpty()){
                return getDataTable(dayworkList);
            }
            //查询bizLotList
            List<Long> lotIds = dayworkList.stream().map(BizDaywork::getLotId).collect(Collectors.toList());
            List<BizLot> lotList = bizLotService.query().in("id", lotIds.isEmpty() ? Collections.singletonList(0L) : lotIds).list();
            //查询bizProductionPlanDetailList
            List<Long> productionPlanDetailIds = dayworkList.stream().map(BizDaywork::getProductionPlanDetailId).collect(Collectors.toList());
            List<BizProductionPlanDetail> productionPlanDetailList = bizProductionPlanDetailService.query().in("id", productionPlanDetailIds.isEmpty() ? Collections.singletonList(0L) : productionPlanDetailIds).list();
            //查询deptList
            List<Long> deptIds = dayworkList.stream().map(BizDaywork::getDeptId).collect(Collectors.toList());
            //value label
            List<SysDept> deptList = deptService.getDeptOptions(deptIds);
            //查询dayworkItemList
            List<Long> dayworkIds = dayworkList.stream().map(BizDaywork::getId).collect(Collectors.toList());
            List<BizDayworkItem> dayworkItemList = bizDayworkItemService.query().in("daywork_id", dayworkIds.isEmpty() ? Collections.singletonList(0L) : dayworkIds).list();
            //查询工艺详情
            List<BizDaywork> unNormalDayworkList = dayworkList.stream().filter(l -> l.getIsAmend() == 1 || l.getIsWasteRecycling() == 1).collect(Collectors.toList());
                //不正常工艺工序
                List<BizLotTechnologicalProcessDetail> lotTechnologicalProcessDetailList = bizLotTechnologicalProcessDetailService.query().in("lot_technological_process_id",unNormalDayworkList.isEmpty() ? Collections.singletonList(0L): unNormalDayworkList.stream().map(BizDaywork::getTechnologicalProcessId).collect(Collectors.toList())).list();
                //正常工艺工序
                List<BizTechnologicalProcessDetail> technologicalProcessDetailList = bizTechnologicalProcessDetailService.query().in("technological_process_id", dayworkList.stream().map(BizDaywork::getTechnologicalProcessId).collect(Collectors.toList())).list();
            for (BizDaywork daywork : dayworkList) {
                BizProductionPlanDetail bizProductionPlanDetail = productionPlanDetailList.stream().filter(item -> item.getId().equals(daywork.getProductionPlanDetailId())).findFirst().orElse(null);
                //产品描述
                daywork.setProductDescription(bizProductionPlanDetail.getProductDescription());
                //计划单号
                daywork.setProductionPlanNo(bizProductionPlanDetail.getProductionPlanNo());
                //公司简称
                daywork.setCompanyAlias(bizProductionPlanDetail.getCompanyAlias());
                //工艺版本
                daywork.setTechnologyVersion(bizProductionPlanDetail.getTechnologyVersion());
                //炉号
                daywork.setFurnaceNumber(bizProductionPlanDetail.getFurnaceNumber());
                //单批量
                daywork.setOneLotQuantity(bizProductionPlanDetail.getOneLotQuantity());
                //总批数
                daywork.setTotalLotNumber(bizProductionPlanDetail.getTotalLotNumber());

                BizLot bizLot = lotList.stream().filter(l -> l.getId().equals(daywork.getLotId())).findFirst().orElse(null);
                //单批量
                daywork.setProductionQuantity(bizLot.getProductionQuantity());

                SysDept sysDept = deptList.stream().filter(l -> l.getValue().equals(daywork.getDeptId())).findFirst().orElse(null);
                //工段名称
                daywork.setDeptName(sysDept.getLabel());
                //完工日期
                List<BizDayworkItem> dayworkItemInfo = dayworkItemList.stream().filter(l -> l.getDayworkId().equals(daywork.getId())).sorted(Comparator.comparing(BizDayworkItem::getCreateTime).reversed()).collect(Collectors.toList());
                //当前批次最新工序的报工信息
                List<BizDayworkItem> lastDayworkItemList = dayworkItemList.stream().filter(l -> l.getProcessStepNumber().equals(dayworkItemInfo.get(0).getProcessStepNumber())).collect(Collectors.toList());
                if(daywork.getIsAmend() == 0 && daywork.getIsWasteRecycling() == 0){
                    BizTechnologicalProcessDetail lastTechnologicalProcessDetail = technologicalProcessDetailList.stream().filter(v -> v.getTechnologicalProcessId().equals(daywork.getTechnologicalProcessId())).sorted(Comparator.comparing(BizTechnologicalProcessDetail::getProcessStepNumber).reversed()).findFirst().orElse(null);
                    //已经完成最后一道序
                    if(lastTechnologicalProcessDetail.getProcessStepNumber().equals(lastDayworkItemList.get(0).getProcessStepNumber()) && lastDayworkItemList.stream().anyMatch(l -> l.getStatus().equals("3"))){
                        daywork.setFinishedTime(lastDayworkItemList.stream().filter(l -> l.getStatus().equals("3")).findFirst().orElse(null).getEndTime());
                    }
                }else{
                    //不正常批次
                    BizLotTechnologicalProcessDetail lastLotTechnologicalProcessDetail = lotTechnologicalProcessDetailList.stream().filter(v -> v.getLotTechnologicalProcessId().equals(daywork.getTechnologicalProcessId())).sorted(Comparator.comparing(BizLotTechnologicalProcessDetail::getProcessStepNumber).reversed()).findFirst().orElse(null);
                    //已经完成最后一道序
                    if(lastLotTechnologicalProcessDetail.getProcessStepNumber().equals(lastDayworkItemList.get(0).getProcessStepNumber()) && lastDayworkItemList.stream().anyMatch(l -> l.getStatus().equals("3"))){
                        daywork.setFinishedTime(lastDayworkItemList.stream().filter(l -> l.getStatus().equals("3")).findFirst().orElse(null).getEndTime());
                    }
                }
                //生产状态
                List<BizDayworkItem> collect = lastDayworkItemList.stream()
                        .sorted(Comparator.comparing(BizDayworkItem::getStatus).reversed()).collect(Collectors.toList());
                daywork.setReportStatus(collect.get(0).getStatus());
                if (daywork.getTotalWorkingHours() == null) {
                    daywork.setTotalWorkingHours(Long.valueOf(0));
                }
            }
            //最终返回当前子计划中批次报工的工序是这个人员负责的工序
            return getDataTable(dayworkList);
//        } catch(Exception e) {
//            TableDataInfo error = new TableDataInfo();
//            error.setCode(500);
//            error.setMsg("报工数据异常，请联系管理员");
//            return error;
//        }
    }

    @GetMapping("/lotList")
    @Log(title = "查询批次列表", businessType = BusinessType.SELECT)
    public TableDataInfo lotList(BizLot bizLot) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizLot);
        // 获取批次信息列表
        startPage();
        List<BizLot> lotList = bizLotService.getList(bizLot);
        BizDaywork bizDaywork = new BizDaywork();
        bizDaywork.setLotIds(lotList.isEmpty() ? Collections.singletonList(0L) : lotList.stream().map(BizLot::getId).collect(Collectors.toList()));
        List<BizDaywork> bizDayworkList = bizDayworkService.getList(bizDaywork);
        lotList.forEach(l -> {
            l.setDaywork(bizDayworkList.stream().filter(d -> d.getLotId().equals(l.getId())).findFirst().orElse(null));
        });
        //最终返回当前子计划中批次报工的工序是这个人员负责的工序
        return getDataTable(lotList);
    }

    @GetMapping("/listDayworkLot")
    @Log(title = "查询报工批次", businessType = BusinessType.SELECT)
    public TableDataInfo listDayworkLot(BizDaywork bizDaywork) {
        startPage();
        List<BizDaywork> dayworkList = bizDayworkService.getListFromNoCurrent(bizDaywork);
        if (dayworkList.size() == 0) {
            return getDataTable(dayworkList);
        }
        List<BizProductionPlanDetail> productionPlanDetail = bizProductionPlanDetailService.query().in("id", dayworkList.stream().map(BizDaywork::getProductionPlanDetailId).collect(Collectors.toList())).list();
        productionPlanDetail.forEach(productionPlan -> {
            dayworkList.forEach(daywork -> {
                if (productionPlan.getId().equals(daywork.getProductionPlanDetailId())) {
                    daywork.setProductDescription(productionPlan.getProductDescription());
                }
            });
        });

        return getDataTable(dayworkList);
    }

    @GetMapping("/listForOutsource")
    @Log(title = "查询外协列表", businessType = BusinessType.SELECT)
    public TableDataInfo listForOutsource(BizDaywork bizDaywork) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizDaywork);
        // 已经在页面中存在的daywork id
        List<Long> existingDayworkIds = bizDaywork.getExistingDayworkIds();
        BizDayworkItem dayworkItem = new BizDayworkItem();
        dayworkItem.setDeptCode(bizDaywork.getDeptCode());
        List<BizDayworkItem> dayworkItemList = bizDayworkService.getItemListForOutsource(dayworkItem);

        List<Long> dayworkIds = dayworkItemList.stream().map(BizDayworkItem::getDayworkId).collect(Collectors.toList());
        // 如果得到的集合是空集合，放入一个0元素，传到xml中，进行SQL组合
        // 否则，SQL组合，不会进行 IN 的判断，导致把所有数据都得到了。
        if (dayworkIds.isEmpty()) {
            dayworkIds.add(0L);
        }
        bizDaywork.setDayworkIds(dayworkIds);
        startPage();
        String config = configService.selectConfigByKey("switch_data_source");
        if ("true".equals(config)) {
            setTenantId(bizDaywork);
        }
        List<BizDaywork> dayworkList = bizDayworkService.getListForOutsource(bizDaywork);
        long total = new PageInfo(dayworkList).getTotal();
        //根据查询的daywork信息上发出单查询是否存在
        List<BizOutsourcedOrderDetail> orderDetails = bizOutsourcedOrderDetailService.query().in("daywork_id", dayworkIds).eq("deleted", 0).list();
        //如果有查询是否回收
        if (orderDetails.size() > 0) {
            //以回收的数据
            List<BizReturnReceiptDetail> returnReceiptDetails = bizReturnReceiptDetailService.query().in("outsource_detail_id", orderDetails.stream().map(BizOutsourcedOrderDetail::getId).collect(Collectors.toList())).eq("deleted", 0).list();

            //如果数据相同则表示全部回收
            if (orderDetails.size() != returnReceiptDetails.size()) {
                // 将 returnReceiptDetails 中的 id 收集到一个 Set 中，以便快速查找
                Set<Long> returnReceiptDetailIds = returnReceiptDetails.stream()
                        .map(BizReturnReceiptDetail::getOutsourceDetailId) // 假设 getId() 返回 BizReturnReceiptDetail 对象的 id
                        .collect(Collectors.toSet());

                // 使用 stream() 和 filter() 筛选出那些 id 不在 returnReceiptDetailIds 中的 orderDetails
                List<BizOutsourcedOrderDetail> filteredOrderDetails = orderDetails.stream()
                        .filter(orderDetail -> !returnReceiptDetailIds.contains(orderDetail.getId())) // 筛选出 id 不在 returnReceiptDetails 中的元素
                        .collect(Collectors.toList());

                // 使用 Stream API 收集所有唯一的 dayworkId 到一个 Set 中
                Set<Long> uniqueDayworkIds = filteredOrderDetails.stream()
                        .map(BizOutsourcedOrderDetail::getDayworkId) // 假设 getDayworkId() 返回 BizOutsourcedOrderDetail 对象的 dayworkId
                        .collect(Collectors.toSet());

                //将未回收的从集合中移除
                // 使用 stream() 和 filter() 创建一个新的 dayworkList，排除那些 dayworkId 出现在 dayworkIdsToDelete 中的 BizDaywork 对象
                List<BizDaywork> updatedDayworkList = dayworkList.stream()
                        .filter(daywork -> !uniqueDayworkIds.contains(daywork.getId())) // 假设 getId() 返回 BizDaywork 对象的 id
                        .collect(Collectors.toList());

                dayworkList = updatedDayworkList;
            }
        }

        dayworkList.forEach(daywork -> {
            dayworkItemList.forEach(item -> {
                if (daywork.getId().equals(item.getDayworkId())) {
                    daywork.setProductNum(item.getQualifiedNum());
                    daywork.setTurnoverDate(item.getCreateTime());
                }
            });

        });
        TableDataInfo dataTable = getDataTable(dayworkList);
        dataTable.setTotal(total);

        return dataTable;
    }
    @GetMapping("/listForInnerOutsource")
    @Log(title = "查询外协列表", businessType = BusinessType.SELECT)
    public TableDataInfo listForInnerOutsource(BizDaywork bizDaywork) {
        // 已经在页面中存在的daywork id
        List<Long> existingDayworkIds = bizDaywork.getExistingDayworkIds();
        BizDayworkItem dayworkItem = new BizDayworkItem();
        dayworkItem.setDeptCode(bizDaywork.getDeptCode());
        List<BizDayworkItem> dayworkItemList = bizDayworkService.getItemListForOutsource(dayworkItem);

        List<Long> dayworkIds = dayworkItemList.stream().map(BizDayworkItem::getDayworkId).collect(Collectors.toList());
        // 如果得到的集合是空集合，放入一个0元素，传到xml中，进行SQL组合
        // 否则，SQL组合，不会进行 IN 的判断，导致把所有数据都得到了。
        if (dayworkIds.isEmpty()) {
            dayworkIds.add(0L);
        }
        bizDaywork.setDayworkIds(dayworkIds);
        startPage();
        List<BizDaywork> dayworkList = bizDayworkService.getListForInnerOutsource(bizDaywork);
        long total = new PageInfo(dayworkList).getTotal();
        //根据查询的daywork信息上发出单查询是否存在
        List<BizOutsourcedOrderDetail> orderDetails = bizOutsourcedOrderDetailService.query().in("daywork_id", dayworkIds).eq("deleted", 0).list();
        //如果有查询是否回收
        if (orderDetails.size() > 0) {
            //以回收的数据
            List<BizReturnReceiptDetail> returnReceiptDetails = bizReturnReceiptDetailService.query().in("outsource_detail_id", orderDetails.stream().map(BizOutsourcedOrderDetail::getId).collect(Collectors.toList())).eq("deleted", 0).list();

            //如果数据相同则表示全部回收
            if (orderDetails.size() != returnReceiptDetails.size()) {
                // 将 returnReceiptDetails 中的 id 收集到一个 Set 中，以便快速查找
                Set<Long> returnReceiptDetailIds = returnReceiptDetails.stream()
                        .map(BizReturnReceiptDetail::getOutsourceDetailId) // 假设 getId() 返回 BizReturnReceiptDetail 对象的 id
                        .collect(Collectors.toSet());

                // 使用 stream() 和 filter() 筛选出那些 id 不在 returnReceiptDetailIds 中的 orderDetails
                List<BizOutsourcedOrderDetail> filteredOrderDetails = orderDetails.stream()
                        .filter(orderDetail -> !returnReceiptDetailIds.contains(orderDetail.getId())) // 筛选出 id 不在 returnReceiptDetails 中的元素
                        .collect(Collectors.toList());

                // 使用 Stream API 收集所有唯一的 dayworkId 到一个 Set 中
                Set<Long> uniqueDayworkIds = filteredOrderDetails.stream()
                        .map(BizOutsourcedOrderDetail::getDayworkId) // 假设 getDayworkId() 返回 BizOutsourcedOrderDetail 对象的 dayworkId
                        .collect(Collectors.toSet());

                //将未回收的从集合中移除
                // 使用 stream() 和 filter() 创建一个新的 dayworkList，排除那些 dayworkId 出现在 dayworkIdsToDelete 中的 BizDaywork 对象
                List<BizDaywork> updatedDayworkList = dayworkList.stream()
                        .filter(daywork -> !uniqueDayworkIds.contains(daywork.getId())) // 假设 getId() 返回 BizDaywork 对象的 id
                        .collect(Collectors.toList());

                dayworkList = updatedDayworkList;
            }
        }

        dayworkList.forEach(daywork -> {
            dayworkItemList.forEach(item -> {
                if (daywork.getId().equals(item.getDayworkId())) {
                    daywork.setProductNum(item.getQualifiedNum());
                    daywork.setTurnoverDate(item.getCreateTime());
                }
            });

        });
        TableDataInfo dataTable = getDataTable(dayworkList);
        dataTable.setTotal(total);

        return dataTable;
    }

    @GetMapping("/processesForOutsource")
    @Log(title = "查询外协工序", businessType = BusinessType.SELECT)
    public TableDataInfo listProcessesForOutsource(BizDaywork bizDaywork) throws NoSuchFieldException, IllegalAccessException {
        //查找当前生产子计划的批次报工信息，找到最后一条包报工信息
        BizDaywork daywork = bizDayworkService.query().eq("lot_id", bizDaywork.getLotId()).eq("deleted", 0).one();
        BizDayworkItem dayworkItem = new BizDayworkItem();
        dayworkItem.setDayworkId(daywork.getId());
        //List<BizDayworkItem> dayworkItemList = bizDayworkItemService.getList(dayworkItem);
        //用户再次提交时传入外协明细id
        dayworkItem.setOutsourceDetailId(bizDaywork.getOutsourceDetailId());
        List<BizDayworkItem> dayworkItemList = bizDayworkItemService.getOutsourcesItemList(dayworkItem);
        List<BizDayworkItem> finishedItem = bizDayworkItemService.getLastFinished(dayworkItem);
        if (dayworkItemList.size() > 0) {
            dayworkItem = dayworkItemList.get(0);
        } else {
            List<BizTechnologicalProcessDetail> processList = new ArrayList<>();
            return getDataTable(processList);
        }
        dayworkItem.setKeyword(bizDaywork.getKeyword());
//            setTenantId(dayworkItem);
        dayworkItem.setTenantId(0L);
        //根据当前工序查找之后的工序列表
        //是否单批单改或废品回用
//        startPage();
        if (daywork.getIsAmend() == 1 || daywork.getIsWasteRecycling() == 1) {
            List<BizLotTechnologicalProcessDetail> processList = bizLotTechnologicalProcessDetailService.getProcessList(dayworkItem).stream().filter(v -> v.getProcessStepNumber().compareTo(finishedItem.get(0).getProcessStepNumber()) > 0).collect(Collectors.toList());
            return getDataTable(processList);
        } else {
            List<BizTechnologicalProcessDetail> processList = bizTechnologicalProcessDetailService.getProcessList(dayworkItem).stream().filter(v -> v.getProcessStepNumber().compareTo(finishedItem.get(0).getProcessStepNumber()) > 0).collect(Collectors.toList());
            return getDataTable(processList);
        }

    }
    @PostMapping("/processesMultiForOutsource")
    @Log(title = "查询外协工序", businessType = BusinessType.SELECT)
    public TableDataInfo processesMultiForOutsource(@RequestBody Map<String, Object> data) {
        //查找当前生产子计划的批次报工信息，找到最后一条包报工信息
        List<Map<String, Object>> bizDayworkList = (List<Map<String, Object>>) data.get("dayworkList");
        String keyword = data.get("keyword").toString();

        List<BizDaywork> dayworks = convertToBizDayworkList(bizDayworkList);

        String lastProcessStep = "1000";
        String lastFinishProcessStep = "1000";
        BizDayworkItem dayworkItem = new BizDayworkItem();
        List<BizDaywork> dayworkList = bizDayworkService.query().in("lot_id", dayworks.stream().map(BizDaywork::getLotId).collect(Collectors.toList())).eq("deleted", 0).list();

        for (BizDaywork daywork : dayworkList) {
            BizDaywork dayworkInfo = dayworks.stream().filter(v -> v.getLotId().equals(daywork.getLotId())).findFirst().orElse(null);
            dayworkItem.setDayworkId(daywork.getId());
            dayworkItem.setLotId(daywork.getLotId());
            dayworkItem.setOutsourceDetailId(dayworkInfo.getOutsourceDetailId());
            List<BizDayworkItem> dayworkItemList = bizDayworkItemService.getOutsourcesItemList(dayworkItem);
            List<BizDayworkItem> finishedItem = bizDayworkItemService.getLastFinished(dayworkItem);

            if (dayworkItemList.size() > 0) {
                BizDayworkItem firstItem = dayworkItemList.get(0);
                if (firstItem.getProcessStepNumber().compareTo(lastProcessStep) > 0) {
                    lastProcessStep = firstItem.getProcessStepNumber();
                    dayworkItem = firstItem;
                }
                if (finishedItem.size() > 0 && finishedItem.get(0).getProcessStepNumber().compareTo(lastFinishProcessStep) > 0) {
                    lastFinishProcessStep = finishedItem.get(0).getProcessStepNumber();
                }
            } else {
                List<BizTechnologicalProcessDetail> processList = new ArrayList<>();
                return getDataTable(processList);
            }
        }

        dayworkItem.setKeyword(keyword);
        dayworkItem.setProcessStepNumber(lastFinishProcessStep);

        List<BizTechnologicalProcessDetail> processList = bizTechnologicalProcessDetailService.getProcessList(dayworkItem);

        return getDataTable(processList);

    }
    private List<BizDaywork> convertToBizDayworkList(List<Map<String, Object>> dayworkList) {
        List<BizDaywork> dayworks = new ArrayList<>();
        for (Map<String, Object> item : dayworkList) {
            BizDaywork daywork = new BizDaywork();
            daywork.setOutsourceDetailId(Long.valueOf(item.get("outsourceDetailId").toString())); // 根据实际字段设置
            daywork.setLotId(Long.valueOf( item.get("lotId").toString())); // 根据实际字段设置
            // 继续设置其他字段...
            dayworks.add(daywork);
        }
        return dayworks;
    }

    @GetMapping("/getLotPosition")
    @Log(title = "查询批次位置", businessType = BusinessType.SELECT)
    public TableDataInfo getLotPosition(BizDaywork bizDaywork) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizDaywork);
        startPage();
        List<BizDaywork> list = bizDayworkService.getLotPosition(bizDaywork);
        list.stream().forEach(item -> {
            if (item.getTurnoverArea().equals("车间内周转看place字段")) {
                item.setTurnoverArea(null);
            }
        });
        return getDataTable(list);
    }

    //查询辅助报工数据
    @GetMapping("/listDayworkAuxiliaryItem")
    @Log(title = "查询辅助报工列表", businessType = BusinessType.SELECT)
    public AjaxResult listDayworkAuxiliaryItem(BizDayworkItem bizDayworkItem) throws NoSuchFieldException, IllegalAccessException {
        //根据工序查询对饮工序的辅助报工信息

        return success(bizDayworkAuxiliaryItemService.query().eq("daywork_id", bizDayworkItem.getDayworkId()).eq("process_step_number", bizDayworkItem.getProcessStepNumber()).orderByAsc("create_time").list());
    }

    /**
     * 查询报工列表
     *
     * @param bizDayworkItem 查询条件
     * @return TableDataInfo
     */
    @GetMapping("/listItem")
    @Log(title = "查询报工列表", businessType = BusinessType.SELECT)
    public TableDataInfo listItem(BizDayworkItem bizDayworkItem) throws NoSuchFieldException, IllegalAccessException {
        startPage();
        //查询批次报工信息列表
        List<BizDayworkItem> itemList = bizDayworkService.getItemList(bizDayworkItem);

        List<BizLotTechnologicalProcessDetail> lotProcessList = new ArrayList<>();//新工序列表
        List<BizTechnologicalProcessDetail> processList = new ArrayList<>();//标准工序列表
        BizDaywork bizDaywork = itemList.isEmpty() ? null : bizDayworkService.getById(itemList.get(0).getDayworkId());
        if (!itemList.isEmpty()) {
            //是否废回用或单批但改
            if (bizDaywork.getIsAmend() == 1 || bizDaywork.getIsWasteRecycling() == 1) {
                //查询新工序列表
                lotProcessList = bizLotTechnologicalProcessDetailService.query().eq("lot_technological_process_id", itemList.get(0).getTechnologicalProcessId()).list();
            } else {
                //查询标准工列表
                processList = bizTechnologicalProcessDetailService.query().eq("technological_process_id", itemList.get(0).getTechnologicalProcessId()).list();
            }
        }
        for (BizDayworkItem item : itemList) {
            if (item.getRejectNum() == null) {
                item.setRejectNum(0);
            }
            //是单批单改或废品回用
            //根据当前工序id设置当前工序
            if (bizDaywork.getIsAmend() == 1 || bizDaywork.getIsWasteRecycling() == 1) {
                lotProcessList.forEach(lotProcess -> {
                    if (item.getTechnologicalProcessDetailId().equals(lotProcess.getId())) {
                        item.setProcessAlias(lotProcess.getProcessAlias());
                    }
                });
            } else {
                processList.forEach(process -> {
                    if (item.getTechnologicalProcessDetailId().equals(process.getId())) {
                        item.setProcessAlias(process.getProcessAlias());
                    }
                });
            }
        }
        //如果进行到最后一条报工，则不能删除，拿到工艺计划单的最后一道工序步骤编码
        String lastProcessStepNumber;
        String firstProcessStepNumber;

        TableDataInfo info = getDataTable(itemList);
        Map<String, Object> map = new HashMap<>();
        if (!itemList.isEmpty() && bizDaywork != null) {
            if (bizDaywork.getIsAmend() == 1 || bizDaywork.getIsWasteRecycling() == 1) {
                lastProcessStepNumber = bizLotTechnologicalProcessDetailService.query().eq("lot_technological_process_id", bizDaywork.getTechnologicalProcessId())
                        .orderByDesc("process_step_number").list().get(0).getProcessStepNumber();
                firstProcessStepNumber = bizLotTechnologicalProcessDetailService.query()
                        .ne("process_key", "BL")
                        .eq("lot_technological_process_id", bizDaywork.getTechnologicalProcessId())
                        .orderByAsc("process_step_number").list().get(0).getProcessStepNumber();
            } else {
                lastProcessStepNumber = bizTechnologicalProcessDetailService.query()
                        .eq("technological_process_id", bizDaywork.getTechnologicalProcessId())
                        .ne("tenant_id", 9).orderByDesc("process_step_number").list().get(0).getProcessStepNumber();
                firstProcessStepNumber = bizTechnologicalProcessDetailService.query()
                        .ne("process_key", "BL")
                        .eq("technological_process_id", bizDaywork.getTechnologicalProcessId())
                        .ne("tenant_id", 9).orderByAsc("process_step_number").list().get(0).getProcessStepNumber();
            }
            map.put("lastProcessStepNumber", lastProcessStepNumber);
            map.put("isFirst", firstProcessStepNumber);
        }

        map.put("latestProcessId", bizDayworkItemService.getLatestDayworkItemId(bizDayworkItem));
        map.put("lastItem", bizDayworkItemService.getLastItem(bizDayworkItem));
        info.setOthers(map);
        return info;
    }

    @GetMapping("/listOriginalItem")
    @Log(title = "查询报工列表", businessType = BusinessType.SELECT)
    public TableDataInfo listOriginalItem(BizDayworkItem bizDayworkItem) throws NoSuchFieldException, IllegalAccessException {
        startPage();
        //查询批次报工信息列表
        List<BizDayworkItem> itemList = bizDayworkService.getItemListWithTurnover(bizDayworkItem);

        List<BizLotTechnologicalProcessDetail> lotProcessList = new ArrayList<>();//新工序列表
        List<BizTechnologicalProcessDetail> processList = new ArrayList<>();//标准工序列表
        BizDaywork bizDaywork = itemList.isEmpty() ? null : bizDayworkService.getById(itemList.get(0).getDayworkId());
        if (!itemList.isEmpty()) {
            //是否废回用或单批但改
            if (bizDaywork.getIsAmend() == 1 || bizDaywork.getIsWasteRecycling() == 1) {
                //查询新工序列表
                lotProcessList = bizLotTechnologicalProcessDetailService.query().eq("lot_technological_process_id", itemList.get(0).getTechnologicalProcessId()).list();
            } else {
                //查询标准工列表
                processList = bizTechnologicalProcessDetailService.query().eq("technological_process_id", itemList.get(0).getTechnologicalProcessId()).list();
            }
        }
        for (BizDayworkItem item : itemList) {

            if (item.getOriginalRejectNum() == null) {
                item.setRejectNum(0);
            } else {
                item.setRejectNum(item.getOriginalRejectNum());
            }
            //是单批单改或废品回用
            //根据当前工序id设置当前工序
            if (bizDaywork.getIsAmend() == 1 || bizDaywork.getIsWasteRecycling() == 1) {
                lotProcessList.forEach(lotProcess -> {
                    if (item.getTechnologicalProcessDetailId().equals(lotProcess.getId())) {
                        item.setProcessAlias(lotProcess.getProcessAlias());
                    }
                });
            } else {
                processList.forEach(process -> {
                    if (item.getTechnologicalProcessDetailId().equals(process.getId())) {
                        item.setProcessAlias(process.getProcessAlias());
                    }
                });
            }
        }
        //如果进行到最后一条报工，则不能删除，拿到工艺计划单的最后一道工序步骤编码
        String lastProcessStepNumber;
        String firstProcessStepNumber;

        TableDataInfo info = getDataTable(itemList);
        Map<String, Object> map = new HashMap<>();
        if (!itemList.isEmpty() && bizDaywork != null) {
            if (bizDaywork.getIsAmend() == 1 || bizDaywork.getIsWasteRecycling() == 1) {
                lastProcessStepNumber = bizLotTechnologicalProcessDetailService.query().eq("lot_technological_process_id", bizDaywork.getTechnologicalProcessId())
                        .orderByDesc("process_step_number").list().get(0).getProcessStepNumber();
                firstProcessStepNumber = bizLotTechnologicalProcessDetailService.query()
                        .ne("process_key", "BL")
                        .eq("lot_technological_process_id", bizDaywork.getTechnologicalProcessId())
                        .orderByAsc("process_step_number").list().get(0).getProcessStepNumber();
            } else {
                lastProcessStepNumber = bizTechnologicalProcessDetailService.query()
                        .eq("technological_process_id", bizDaywork.getTechnologicalProcessId())
                        .ne("tenant_id", 9).orderByDesc("process_step_number").list().stream().findFirst().orElse(new BizTechnologicalProcessDetail()).getProcessStepNumber();
                firstProcessStepNumber = bizTechnologicalProcessDetailService.query()
                        .ne("process_key", "BL")
                        .eq("technological_process_id", bizDaywork.getTechnologicalProcessId())
                        .ne("tenant_id", 9).orderByAsc("process_step_number").list().stream().findFirst().orElse(new BizTechnologicalProcessDetail()).getProcessStepNumber();
            }
            map.put("lastProcessStepNumber", lastProcessStepNumber);
            map.put("isFirst", firstProcessStepNumber);
        }

        map.put("latestProcessId", bizDayworkItemService.getLatestDayworkItemId(bizDayworkItem));
        map.put("lastItem", bizDayworkItemService.getLastItem(bizDayworkItem));
        info.setOthers(map);
        return info;
    }

    /**
     * 查询报工日报列表
     *
     * @param bizDayworkItem 查询条件
     * @return TableDataInfo
     */
    @GetMapping("/listReportItem")
    @Log(title = "查询报工日报列表", businessType = BusinessType.SELECT)
    public TableDataInfo listReportItem(BizDayworkItem bizDayworkItem) throws NoSuchFieldException, IllegalAccessException {
        startPage();
        //查询批次报工信息列表
        List<BizDayworkItem> itemList = bizDayworkService.listReportItem(bizDayworkItem);
        List<Long> lotIds = itemList.stream().filter(item -> item.getProdNum() == 0).map(BizDayworkItem::getLotId).collect(Collectors.toList());
        List<BizLot> lotList = bizLotService.query().in("id", lotIds.isEmpty() ? Collections.singletonList(0L) : itemList.stream().filter(item -> item.getProdNum() == 0).map(BizDayworkItem::getLotId).collect(Collectors.toList())).list();
        //首序投产数为0，所以查询如果prodNum为0，其他是第一条报工的时候，给prodNum赋值单批量
        itemList.forEach(item -> {
            if (item.getProdNum() == 0) {
                //拿到第一条报工的工序步骤，为了判断这个投产数为0，是不是该工序步骤的报工，如果是，就给它的投产量赋值为单批量
                String processStepNumber = itemList.stream().filter(v -> v.getDayworkId().equals(item.getDayworkId())).sorted(Comparator.comparing(BizDayworkItem::getProcessStepNumber)).collect(Collectors.toList()).get(0).getProcessStepNumber();
                if (item.getProcessStepNumber().equals(processStepNumber)) {
                    item.setProdNum(lotList.stream().filter(lot -> lot.getId().equals(item.getLotId())).findFirst().get().getProductionQuantity());
                }
            }
            if (item.getRejectNum() == null) {
                item.setRejectNum(0);
            }
        });

        return getDataTable(itemList);
    }

    @PostMapping("/getDayworkItemDetail")
    @Log(title = "查询报工明细", businessType = BusinessType.SELECT)
    public AjaxResult getDayworkItemDetail(@RequestBody BizDayworkItem bizDayworkItem) {
        BizDayworkItem dayworkItemInfo = new BizDayworkItem();
        List<BizProcessInspecion> processInspectionList = bizProcessInspecionService.query().eq("daywork_item_id", bizDayworkItem.getId()).orderByDesc("create_time").list();
        //序检
        dayworkItemInfo.setProcessInspection(processInspectionList.isEmpty() ? null : processInspectionList.get(0));
        //废品信息
        List<BizDayworkItemReject> rejectListByItemId = bizDayworkItemRejectService.getRejectListByItemId(bizDayworkItem.getId());
        dayworkItemInfo.setGroupRejectList(rejectListByItemId.isEmpty() ? new ArrayList<>() : rejectListByItemId);
        //咨询信息
        List<BizDayworkItemConsult> dayworkItemConsult = bizDayworkItemConsultService.query().eq("daywork_item_id", bizDayworkItem.getId()).eq("process_inspection_id", 0).list();
        dayworkItemInfo.setConsultList(dayworkItemConsult.isEmpty() ? new ArrayList<>() : dayworkItemConsult);
        return success(dayworkItemInfo);
    }

    @PostMapping("/getProcessDetail")
    @Log(title = "查询报工工艺列表", businessType = BusinessType.SELECT)
    public AjaxResult getProcessDetail(@RequestBody BizDaywork bizDaywork) {
        if (bizDaywork.getIsAmend() == 1 || bizDaywork.getIsWasteRecycling() == 1) {
            List<BizLotTechnologicalProcessDetail> list = bizLotTechnologicalProcessDetailService.query()
                    .eq("lot_technological_process_id", bizDaywork.getTechnologicalProcessId())
                    .orderByAsc("process_step_number")
                    .list();
            return success(list);
        } else {
            List<BizTechnologicalProcessDetail> list = bizTechnologicalProcessDetailService.query()
                    .eq("technological_process_id", bizDaywork.getTechnologicalProcessId()).ne("tenant_id", 9)
                    .orderByAsc("process_step_number")
                    .list();
            return success(list);
        }
    }

    /**
     * 修改报工列表
     *
     * @param bizDayworkItem
     * @return TableDataInfo
     */
    @PostMapping("/updateItem")
    @Log(title = "修改报工列表", businessType = BusinessType.UPDATE)
    public AjaxResult updateItem(@RequestBody BizDayworkItem bizDayworkItem) {
//        String tenantId = request.getHeader("tenantId");
//        bizDayworkItem.setTenantId(Long.valueOf(tenantId));
        return toAjax(bizDayworkItemService.saveOrUpdate(bizDayworkItem));
    }

    /**
     * 获取工序列表
     */
    @GetMapping("/getProcessList")
    @Log(title = "获取工序列表", businessType = BusinessType.SELECT)
    public AjaxResult getProcessList(BizDayworkItem bizDayworkItem) {
        if (bizDayworkItem.getIsAmend() == 1 || bizDayworkItem.getIsWasteRecycling() == 1) {
//            BizLotTechnologicalProcess bizLotTechnologicalProcess = bizLotTechnologicalProcessService.query().eq("lot_id", bizDayworkItem.getLotId()).eq("is_stop",0).list().get(0);
//            List<BizLotTechnologicalProcessDetail> bizLotTechnologicalProcessDetail = bizLotTechnologicalProcessDetailService.query().eq("lot_technological_process_id", bizLotTechnologicalProcess.getId()).list();
            List<BizLotTechnologicalProcessDetail> bizLotTechnologicalProcessDetail = bizLotTechnologicalProcessDetailService.query().eq("lot_technological_process_id", bizDayworkItem.getTechnologicalProcessId()).list();
            List<BizProcess> process = new ArrayList<>();
            for (BizLotTechnologicalProcessDetail item : bizLotTechnologicalProcessDetail) {
                BizProcess bizProcess = new BizProcess();
                bizProcess.setLabel(item.getProcessAlias());
                bizProcess.setValue(item.getProcessId());
                process.add(bizProcess);
            }
            return success(process);
        }
        return success(bizDayworkService.getProcessList(bizDayworkItem));
    }

    //删除报工明细
    @DeleteMapping("/{ids}")
    @Transactional
    @Log(title = "删除报工明细", businessType = BusinessType.DELETE)
    public AjaxResult deletedItem(@PathVariable Long ids) {
        //判断如果是首序，则必须留一条报工
        BizDayworkItem bizDayworkItem = bizDayworkItemService.getById(ids);
        BizDayworkItem item = new BizDayworkItem();
        item.setDayworkId(bizDayworkItem.getDayworkId());
        //第一条报工
        BizDayworkItem firstItem = bizDayworkItemService.getList(item).stream().sorted(Comparator.comparing(BizDayworkItem::getCreateTime)).collect(Collectors.toList()).get(0);
        item.setProcessStepNumber(bizDayworkItem.getProcessStepNumber());
        //拿到同一个工序步骤的报工信息
        List<BizDayworkItem> totalItem = bizDayworkItemService.getList(item);
        //如果要删除的报工是这个工序的最后一条报工，且是首序
//        if (totalItem.size() == 1 && bizDayworkItem.getProcessStepNumber().equals(firstItem.getProcessStepNumber())) {
////            return error("首序报工至少存在一条");
//        } else {
            //删除废品
            List<BizDayworkItemReject> dayworkItemRejectList = bizDayworkItemRejectService.query().eq("daywork_item_id", bizDayworkItem.getId()).list();
            //普通报工是周转申请的时候，向daywork上存合格数，分选报工则是工序已完成的时候存
            if (bizDayworkItem.getIsSort() == 1) {
                //如果该条报工状态是3，则删除时同时将这道序
                // 删除的废品量加回daywork的两个合格数
                if (bizDayworkItem.getStatus().equals("3")) {
                    BizDaywork daywork = bizDayworkService.query().eq("id", bizDayworkItem.getDayworkId()).one();
                    List<BizDayworkItem> dayworkItemList = bizDayworkItemService.query().eq("daywork_id", bizDayworkItem.getDayworkId()).eq("process_step_number", bizDayworkItem.getProcessStepNumber()).list();
                    List<BizDayworkItemReject> rejectList = bizDayworkItemRejectService.query().in("daywork_item_id", dayworkItemList.stream().map(BizDayworkItem::getId).collect(Collectors.toList())).list();
                    int sum = (int) rejectList.stream().mapToLong(BizDayworkItemReject::getRejectNum).sum();
                    //如果当前序报工只有当前一条，bizDaywork上合格数是上道序的合格数
                    if (dayworkItemList.size() == 1) {
                        //拿到上一道序的合格数
                        List<BizDayworkItem> lastList = bizDayworkItemService.query().eq("daywork_id", bizDayworkItem.getDayworkId()).ne("process_step_number", bizDayworkItem.getProcessStepNumber()).ne("status", 4).ne("status", 5).ne("status", 7).orderByDesc("process_step_number").list();
                        if (!lastList.isEmpty()) {
                            String lastProcessStepNumber = lastList.get(0).getProcessStepNumber();
                            List<BizDayworkItem> lastDayworkItemList = lastList.stream().filter(v -> v.getProcessStepNumber().equals(lastProcessStepNumber)).collect(Collectors.toList());
                            sum = (int) lastDayworkItemList.stream().mapToLong(BizDayworkItem::getQualifiedNum).sum();
                            daywork.setTemporaryProcessQualifiedNum(sum);
                            daywork.setProcessQualifiedNum(sum);
                            bizDayworkService.updateById(daywork);
                        }
                    } else {
                        daywork.setTemporaryProcessQualifiedNum(daywork.getTemporaryProcessQualifiedNum() + sum);
                        daywork.setProcessQualifiedNum(daywork.getProcessQualifiedNum() + sum);
                        bizDayworkService.updateById(daywork);
                    }
                }
            }
            if (!dayworkItemRejectList.isEmpty()) {
                bizDayworkItemRejectService.removeBatchByIds(dayworkItemRejectList);
            }
            //删除辅助报工废品
            List<BizDayworkAuxiliaryItemReject> dayworkAuxiliaryItemRejectList = bizDayworkAuxiliaryItemRejectService.query().eq("daywork_item_id", bizDayworkItem.getId()).list();
            if (!dayworkAuxiliaryItemRejectList.isEmpty()) {
                bizDayworkAuxiliaryItemRejectService.removeBatchByIds(dayworkAuxiliaryItemRejectList);
            }
            //删除辅助报工主表
            List<BizDayworkItem> list = bizDayworkItemService.getListByDayworkIdAndProcessStepNumber(bizDayworkItem);
            List<BizDayworkAuxiliaryItem> dayworkAuxiliaryItemList = bizDayworkAuxiliaryItemService.query().eq("lot_id", bizDayworkItem.getLotId()).eq("process_step_number", bizDayworkItem.getProcessStepNumber()).list();
            if (totalItem.size() == 1 && !dayworkAuxiliaryItemList.isEmpty()) {
                bizDayworkAuxiliaryItemService.removeBatchByIds(dayworkAuxiliaryItemList);
            }
            //判断当前员工是否是邀请报工加进来的，如果是邀请报工的，则判断是否删除资源组及工段
            deleTemporanyPeople(bizDayworkItem);
            //判断如果是周转数据。则需要将原工段修改
        if(bizDayworkItem.getStatus().equals("4") || bizDayworkItem.getStatus().equals("5")|| bizDayworkItem.getStatus().equals("7")){
            BizDaywork daywork = bizDayworkService.query().eq("id", bizDayworkItem.getDayworkId()).one();
            daywork.setDeptId(bizDayworkItem.getFromDeptId());
            bizDayworkService.updateById(daywork);
        }
            //删除工序检验
            bizDayworkItemService.removeById(bizDayworkItem);
        if (totalItem.size() == 1 && bizDayworkItem.getProcessStepNumber().equals(firstItem.getProcessStepNumber())) {
            // 还要删炉号 载具 报工
            BizDaywork bizDaywork = bizDayworkService.getById(bizDayworkItem.getDayworkId());
            List<BizDayworkCarrier> carrier = bizDayworkCarrierService.query().eq("daywork_id", bizDayworkItem.getDayworkId()).list();
            List<BizFurnaceNoInfo> bizFurnaceNoInfo = bizFurnaceNoInfoService.query().eq("daywork_id", bizDayworkItem.getDayworkId()).list();
            bizDayworkService.removeById(bizDaywork.getId());
            bizDayworkCarrierService.removeBatchByIds(carrier);
            bizFurnaceNoInfoService.removeBatchByIds(bizFurnaceNoInfo);
        }
//        }

//        List<Long> id = new ArrayList<>();
//        id.add(bizDayworkItem.getDayworkId());
//        List<BizDayworkItem> itemList = bizDayworkItemService.getListByDayworkIds(id).stream().filter(item -> item.getProcessStepNumber().equals(bizDayworkItem.getProcessStepNumber())).collect(Collectors.toList());
////        List<BizDayworkItem> turnoverList = itemList.stream().filter(item -> "4".equals(item.getStatus()) || "5".equals(item.getStatus()) || "7".equals(item.getStatus())).collect(Collectors.toList());
//        BizDaywork daywork = bizDayworkService.query().eq("id", bizDayworkItem.getDayworkId()).list().get(0);
//        if(!turnoverList.isEmpty()) {
//            bizDayworkItemService.removeById(turnoverList.get(0));
//            //修改daywork主表的工段和合格数信息
//            daywork.setDeptId(bizDayworkItem.getDeptId());
//            daywork.setTemporaryProcessQualifiedNum(daywork.getProcessQualifiedNum());
//            bizDayworkService.updateById(daywork);
//        }
//        //判断该条报工是否是该工序最后一条报工
//        List<BizDayworkItem> hasList = bizDayworkItemService.getListByDayworkIds(id).stream().filter(item -> item.getProcessStepNumber().equals(bizDayworkItem.getProcessStepNumber())).collect(Collectors.toList());
//        if(hasList.isEmpty()) {
//            //如果没查到，则代表删除的这一条为最后一条，则新增一条未开始的报工
//            BizDayworkItem dayworkItem = new BizDayworkItem();
//            dayworkItem.setDayworkId(bizDayworkItem.getDayworkId());;
//            if (daywork.getIsAmend() == 1) {
//                dayworkItem.setFormDayworkItemId(1L);
//            }
//            dayworkItem.setProcessStepNumber(bizDayworkItem.getProcessStepNumber());
//            dayworkItem.setProductionPlanDetailId(bizDayworkItem.getProductionPlanDetailId());
//            dayworkItem.setTechnologicalProcessId(bizDayworkItem.getTechnologicalProcessId());
//            dayworkItem.setUserId(bizDayworkItem.getUserId());
//            dayworkItem.setUserName(bizDayworkItem.getUserName());
//            dayworkItem.setProdNum(bizDayworkItem.getProdNum());
//            dayworkItem.setNickName(bizDayworkItem.getNickName());
//            //0114 这里要把前段显示的item的processId传进来
//            dayworkItem.setProcessId(bizDayworkItem.getProcessId());
//            dayworkItem.setTechnologicalProcessDetailId(bizDayworkItem.getTechnologicalProcessDetailId());
//            dayworkItem.setDeptId(bizDayworkItem.getDeptId());
//            dayworkItem.setDeptName(bizDayworkItem.getDeptName());
//            dayworkItem.setLotId(bizDayworkItem.getLotId());
//            bizDayworkItemService.save(dayworkItem);
//        }
        return success();
    }

    //删除邀请报工人员
    public void deleTemporanyPeople(BizDayworkItem bizDayworkItem) {
        List<BizProductionResourceGroupDetail> resourceGroupDetailList = bizProductionResourceGroupDetailService.query().eq("protem_process_step_number", bizDayworkItem.getProcessStepNumber())
                .eq("protem_process_id", bizDayworkItem.getProcessId())
                .eq("protem_daywork_id", bizDayworkItem.getDayworkId())
                .eq("common_type", "person")
                .eq("common_id", bizDayworkItem.getUserId())
                .list();
        if (!resourceGroupDetailList.isEmpty()) {
            bizProductionResourceGroupDetailService.removeBatchByIds(resourceGroupDetailList);
        }
        //删除工段下的邀请报工人员
        List<SysDeptUser> deptUserList = deptUserService.query()
                .eq("dept_id", bizDayworkItem.getDeptId())
                .eq("user_id", bizDayworkItem.getUserId())
                .eq("is_temporary", bizDayworkItem.getDayworkId()).list();
        if (!deptUserList.isEmpty()) {
            deptUserService.removeBatchByIds(deptUserList);
        }
    }
    //更换炉号查询的批次信息
    @GetMapping("/getDayworkList")
    @Log(title = "更换炉号查询批次信息", businessType = BusinessType.SELECT)
    public TableDataInfo getDayworkList(BizDaywork bizDaywork) throws NoSuchFieldException, IllegalAccessException, ParseException {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//        if(bizDaywork.getStartTime()!=null) {
//            String startDateString = sdf.format(bizDaywork.getStartTime());
//            String newStartTimeString = startDateString + " 00:00:00";
//            Date newStartTime = sdf.parse(newStartTimeString);
//            bizDaywork.setStartTime(newStartTime);
//        }
//        if(bizDaywork.getEndTime()!=null) {
//            String endDateString = sdf.format(bizDaywork.getEndTime());
//            String newEndTimeString = endDateString + " 23:59:59";
//            Date newEndTime = sdf.parse(newEndTimeString);
//            bizDaywork.setEndTime(newEndTime);
//        }
        startPage();
        setTenantId(bizDaywork);
        List<BizDaywork> list = bizDayworkService.getDayworkList(bizDaywork);
        return getDataTable(list);
    }

//    @Transactional
//    @DeleteMapping("/maxDel/{ids}")
//    public AjaxResult delDayworkItemMax(@PathVariable Long ids) {
//        BizDayworkItem bizDayworkItem = bizDayworkItemService.getById(ids);
//        bizDayworkItemService.removeById(bizDayworkItem);
//        //如果该批次没有报工，则删除该daywork
//        List<BizDayworkItem> dayworkItemList = bizDayworkItemService.query().eq("daywork_id", bizDayworkItem.getDayworkId()).list();
//        if (dayworkItemList.isEmpty()) {
//            bizDayworkService.removeById(bizDayworkItem.getDayworkId());
//            //解绑载具
//            List<BizDayworkCarrier> carriers = bizDayworkCarrierService.query().eq("daywork_id", bizDayworkItem.getDayworkId()).list();
//            carriers.forEach(carrier -> {
//                carrier.setIsChanged(1);
//            });
//            bizDayworkCarrierService.removeBatchByIds(carriers);
//        }else {
//            //修改daywork的工段信息，合格数
//            List<BizDayworkItem> dscDayworkItemList = dayworkItemList.stream().sorted(Comparator.comparing(BizDayworkItem::getCreateTime).reversed()).collect(Collectors.toList());
//            //拿到最后一条的报工工段和工序步骤
//            Long latestDeptId = dscDayworkItemList.get(0).getDeptId();
//            String latestProcessStepNumber = dscDayworkItemList.get(0).getProcessStepNumber();
//            //拿到当前工序的报工合格数
//            Integer qualifiedNum = dscDayworkItemList.stream().filter(item -> item.getProcessStepNumber().equals(latestProcessStepNumber) && (item.getStatus().equals("3") || item.getStatus().equals("2") || item.getStatus().equals("1"))).mapToInt(BizDayworkItem::getQualifiedNum).sum();
//            BizDaywork daywork = bizDayworkService.query().eq("id", bizDayworkItem.getDayworkId()).list().get(0);
//            daywork.setDeptId(latestDeptId);
//            //拿到上一道序的报工合格数为当前序的投产数
//            List<BizDayworkItem> secondLatest = dayworkItemList.stream().filter(item -> !item.getProcessStepNumber().equals(latestProcessStepNumber)).sorted(Comparator.comparing(BizDayworkItem::getCreateTime).reversed()).collect(Collectors.toList());
//            //没有上一道序
//            if (secondLatest.isEmpty()) {
//                //判断最后一道序的状态
//                if (dscDayworkItemList.get(0).getStatus().equals("4") || dscDayworkItemList.get(0).getStatus().equals("5") || dscDayworkItemList.get(0).getStatus().equals("7")) {
//                    daywork.setTemporaryProcessQualifiedNum(qualifiedNum);
//                    daywork.setProcessQualifiedNum(0);
//                } else {
//                    daywork.setTemporaryProcessQualifiedNum(0);
//                    daywork.setProcessQualifiedNum(0);
//                }
//            } else {
//                //存在上一道序，则合格数设置为上一道序的投产数
//                String secondLatestProcessNumber = secondLatest.get(0).getProcessStepNumber();
//                int secondQuantityNum = secondLatest.stream().filter(item -> item.getProcessStepNumber().equals(secondLatestProcessNumber) && (item.getStatus().equals("3") || item.getStatus().equals("2") || item.getStatus().equals("1"))).mapToInt(BizDayworkItem::getQualifiedNum).sum();
//                //最新序周转
//                if (dscDayworkItemList.get(0).getStatus().equals("4") || dscDayworkItemList.get(0).getStatus().equals("5") || dscDayworkItemList.get(0).getStatus().equals("7")) {
//                    daywork.setTemporaryProcessQualifiedNum(qualifiedNum);
//                    daywork.setProcessQualifiedNum(secondQuantityNum);
//                } else {
//                    //正常报工
//                    daywork.setTemporaryProcessQualifiedNum(secondQuantityNum);
//                    daywork.setProcessQualifiedNum(secondQuantityNum);
//                }
//            }
//            //修改daywork主表
//            bizDayworkService.updateById(daywork);
//        }
//            //删除废品表
//            List<BizDayworkItemReject> dayworkItemRejectList = bizDayworkItemRejectService.query().eq("daywork_item_id", ids).list();
//        if(!dayworkItemRejectList.isEmpty()) {
//            bizDayworkItemRejectService.removeBatchByIds(dayworkItemRejectList);
//            //删除检测信息
//            List<BizProcessInspecion> processInspection = bizProcessInspecionService.query().eq("daywork_item_id", ids).list();
//            if(!processInspection.isEmpty()) {
//                List<Long> processInspectionIds = processInspection.stream().map(BizProcessInspecion::getId).collect(Collectors.toList());
//                bizProcessInspecionService.removeBatchByIds(processInspection);
//                //解绑检测载具
//                if(!processInspectionIds.isEmpty()) {
//                    List<BizDayworkCarrier> inspectionCarrier = bizDayworkCarrierService.query().eq("process_inspection_id", processInspectionIds).list();
//                    inspectionCarrier.forEach(carrier -> {
//                        carrier.setIsChanged(1);
//                    });
//                    bizDayworkCarrierService.updateBatchById(inspectionCarrier);
//                }
//                List<BizProcessInspectionDetail> processInspectionDetailList = bizProcessInspectionDetailService.query().in("process_inspection_id", processInspectionIds).list();
//                if (!processInspectionDetailList.isEmpty()) {
//                    //删除检测详细
//                    bizProcessInspectionDetailService.removeBatchByIds(processInspectionDetailList);
//                }
//            }
//            //删除咨询信息
//            List<BizDayworkItemConsult> dayworkItemConsultList = bizDayworkItemConsultService.query().eq("daywork_item_id", ids).list();
//            if(!dayworkItemConsultList.isEmpty()) {
//                List<Long> consultIds = dayworkItemConsultList.stream().map(BizDayworkItemConsult::getId).collect(Collectors.toList());
//                if(!consultIds.isEmpty()) {
//                    bizDayworkItemConsultService.removeBatchByIds(dayworkItemConsultList);
//                    List<BizDayworkItemConsultPicture> dayworkItemConsultPictures = bizDayworkItemConsultPictureService.query().eq("daywork_item_consult_id", consultIds).list();
//               if(!dayworkItemConsultPictures.isEmpty()) {
//                   bizDayworkItemConsultPictureService.removeBatchByIds(dayworkItemConsultPictures);
//               }
//                }
//            }
//            //删除审核信息
//            List<BizDayworkItemExamine> dayworkItemExamine = bizDayworkItemExamineService.query().eq("daywork_item_id", ids).list();
//            if (!dayworkItemExamine.isEmpty()){
//                bizDayworkItemExamineService.removeBatchByIds(dayworkItemExamine);
//            }
//        }
//
//        return success();
//    }

    /**
     * 获取批次工序信息
     */
    @GetMapping("/getDayworkItemProcess/{id}")
    @Log(title = "获取批次工序信息", businessType = BusinessType.SELECT)
    public AjaxResult getDayworkItemProcess(@PathVariable("id") String lotCode) {
        //查询批次信息
        HashMap<String, Object> map = new HashMap<>();
        try {
            BizLot lot = new BizLot();
            lot.setLotCode(lotCode);
            List<BizLot> lotList = bizLotService.getList(lot);
            lot = lotList.size() > 0 ? lotList.get(0) : null;
            if (lot != null) {
                //查询当前工序
                BizDaywork daywork = new BizDaywork();
                BizDayworkItem item = new BizDayworkItem();
                daywork.setLotId(lot.getId());
                daywork.setProductionPlanDetailId(lot.getProductionPlanDetailId());
                daywork.setLotCode(lotCode);
                //判断是否有内部外协
                List<BizOutsourcedOrderDetailProcess> outsourcedOrderDetailProcessList = bizOutsourcedOrderDetailProcessService.query().eq("lot_id", lot.getId()).orderByDesc("process_step_number").list();
                //查询报工数据
                List<BizDaywork> dayworkList = bizDayworkService.getList(daywork);
                //没有数据表示未开始报工
                if (dayworkList.size() > 0) {
                    daywork = bizDayworkService.getList(daywork).get(0);
                    item.setDayworkId(daywork.getId());
                    item = bizDayworkItemService.getList(item).get(0);
                    if (lot.getIsAmend() == 1 || lot.getIsWasteRecycling() == 1) {
                        if(!outsourcedOrderDetailProcessList.isEmpty() && item.getProcessStepNumber().compareTo(outsourcedOrderDetailProcessList.get(0).getProcessStepNumber())< 0){
                            BizLotTechnologicalProcessDetail processDetail = bizLotTechnologicalProcessDetailService.getById(outsourcedOrderDetailProcessList.get(0).getTechnologicalProcessDetailId());
                            item.setProcessStepNumber(processDetail.getProcessStepNumber());
                        }else {
                            BizLotTechnologicalProcessDetail processDetail = bizLotTechnologicalProcessDetailService.getById(item.getTechnologicalProcessDetailId());
                            item.setProcessStepNumber(processDetail.getProcessStepNumber());
                        }
                    } else {
                        if(!outsourcedOrderDetailProcessList.isEmpty() && item.getProcessStepNumber().compareTo(outsourcedOrderDetailProcessList.get(0).getProcessStepNumber())< 0){
                            BizTechnologicalProcessDetail processDetail = bizTechnologicalProcessDetailService.getById(outsourcedOrderDetailProcessList.get(0).getTechnologicalProcessDetailId());
                            item.setProcessStepNumber(processDetail.getProcessStepNumber());
                        }else {
                            BizTechnologicalProcessDetail processDetail = bizTechnologicalProcessDetailService.getById(item.getTechnologicalProcessDetailId());
                            item.setProcessStepNumber(processDetail.getProcessStepNumber());
                        }
                    }
                } else {
                    item = null;
                }
                //是否单批单改
                if (lot.getIsAmend() == 1 || lot.getIsWasteRecycling() == 1) {
                    BizLotTechnologicalProcessDetail amendDetail = new BizLotTechnologicalProcessDetail();
                    amendDetail.setLotTechnologicalProcessId(lot.getTechnologicalProcessId());
                    List<BizLotTechnologicalProcessDetail> amendDetailList = bizTechnologicalAmendDetailService.getList(amendDetail);
                    map.put("processDetails", amendDetailList);
                } else {
                    //查询工序列表
                    List<BizTechnologicalProcessDetail> processDetails = bizTechnologicalProcessDetailService.getProcessDetailsByTechnicalProcessId(lot.getTechnologicalProcessId());
                    map.put("processDetails", processDetails);
                }
                map.put("dayworkItem", item);
                map.put("lot", lot);
            } else {
                throw new RuntimeException("未查询到该批次信息！");
            }
        } catch (Exception e) {
            throw new RuntimeException("批次信息异常！");
        }

        return success(map);
    }

    @PostMapping("/checkUseEquipment")
    @Log(title = "检测社保使用情况", businessType = BusinessType.SELECT)
    public AjaxResult checkUseEquipment(@RequestBody List<BizProductionResourceGroupDetail> bizProductionResourceGroupDetailList) {
        List<BizProductionResourceGroupDetail> equipmentDetail = bizProductionResourceGroupDetailList.stream().filter(item ->
                item.getCommonType().equals("equipmentDetail")).collect(Collectors.toList());
        String errorMessage = "";
        for (BizProductionResourceGroupDetail item : equipmentDetail) {
            List<BizDayworkItem> list = bizProductionResourceGroupDetailService.checkUseEquipment(item);
            if (list.size() > 0) {
                errorMessage = errorMessage + item.getCommonName() + ",";
            }
        }
        if ("".equals(errorMessage)) {
            return success();
        }
        return error(errorMessage + "设备正在使用不能删除");
    }

    /**
     * 获取报工记录的工段
     */
    @GetMapping("/getDeptInfo")
    @Log(title = "获取报工记录的工段", businessType = BusinessType.SELECT)
    public AjaxResult getDeptList(BizDayworkItem bizDayworkItem) {
        return success(bizDayworkItemService.getDeptInfo(bizDayworkItem));
    }

    /**
     * 获取计划详情
     */
    @GetMapping("/getDayworkInfo")
    @Log(title = "获取计划详情", businessType = BusinessType.SELECT)
    public TableDataInfo getDayworkInfo(BizDaywork daywork) {
        return getDataTable(bizDayworkService.getDayworkInfo(daywork));
    }

    @GetMapping("/getProducedLot")
    @Log(title = "获取计划单批次", businessType = BusinessType.SELECT)
    public TableDataInfo getProducedLot(BizProductionPlanDetail data) {

        return getDataTable(bizDayworkService.getProducedLot(data));
    }

    @GetMapping("/getItemProcess")
    @Log(title = "获取报工工艺列表", businessType = BusinessType.SELECT)
    public AjaxResult getItemProcess(BizProductionPlanDetail data) {
        //拿到生产计划
        BizProductionPlanDetail bizProductionPlanDetail = bizProductionPlanDetailService.query().eq("production_plan_No", data.getProductionPlanNo()).eq("line_number", data.getLineNumber()).list().get(0);
        List<BizDaywork> bizDayworkList = bizDayworkService.query().eq("production_plan_detail_id", bizProductionPlanDetail.getId()).list();
        List<Long> dayworkIds = bizDayworkList.stream().map(BizDaywork::getId).collect(Collectors.toList());
        List<BizProcess> newProcess = new ArrayList<>();
        if (!dayworkIds.isEmpty()) {
            List<BizDayworkItem> dayworkItemList = bizDayworkItemService.getListByDayworkIds(dayworkIds);
            //拿到所有的process
            List<BizProcess> processList = bizProcessService.query().list();
            for (BizDaywork item : bizDayworkList) {
                BizProcess process = new BizProcess();
                BizDayworkItem bizDayworkItem = dayworkItemList.stream().filter(item1 -> item1.getDayworkId().equals(item.getId())).sorted(Comparator.comparing(BizDayworkItem::getProcessStepNumber).reversed()).collect(Collectors.toList()).get(0);
                process.setValue(bizDayworkItem.getProcessId());
                process.setLabel(processList.stream().filter(item1 -> item1.getId().equals(process.getValue())).collect(Collectors.toList()).get(0).getProcessAlias());
                if (newProcess.stream().filter(item1 -> item1.getValue().equals(process.getValue())).collect(Collectors.toList()).size() == 0) {
                    newProcess.add(process);
                }
            }
        }
        return success(newProcess);
    }

    /**
     * 获取计划详情的工段列表
     */
    @GetMapping("/getDeptList")
    @Log(title = "获取计划详情的工段列表", businessType = BusinessType.SELECT)
    public AjaxResult getDeptList(BizDaywork daywork) {
        return success(bizDayworkService.getDeptList(daywork));
    }

    @GetMapping("/getDeptListForUser")
    @Log(title = "获取用户工段", businessType = BusinessType.SELECT)
    public AjaxResult getDeptListForUser() {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        List<Long> ids = new ArrayList<>();
        if (userId != 1) {
            QueryWrapper<SysDeptUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("deleted", 0);

            List<SysDeptUser> deptUserList = deptUserService.list(queryWrapper);
            //工段下员工
            if (deptUserList.size() > 0) {
                for (SysDeptUser item : deptUserList) {
                    ids.add(item.getDeptId());
                }
            }
        } else {
            SysDept sysDept = new SysDept();
            sysDept.setType("0");
            sysDept.setIsWorkSection(1);
            List<SysDept> deptList = deptService.selectDeptList(sysDept);
            ids = deptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        }
        List<SysDept> deptOptions = new ArrayList<>();
        if (ids.size() > 0) {
            deptOptions = deptService.getDeptOptions(ids);
        }
        TableDataInfo info = getDataTable(deptOptions);
        return success(info);
    }

    /**
     * 获取计划详情的工序列表
     */
    @GetMapping("/getDayworkProcessList")
    @Log(title = "获取计划详情的工序列表", businessType = BusinessType.SELECT)
    public AjaxResult getDayworkProcessList(BizDaywork daywork) {
        return success(bizDayworkService.getDayworkProcessList(daywork));
    }
    @GetMapping("/getDayworkWasteProcessList")
    @Log(title = "获取批废工序列表", businessType = BusinessType.SELECT)
    public AjaxResult getDayworkWasteProcessList(BizDaywork daywork) {
        return success(bizDayworkService.getDayworkWasteProcessList(daywork));
    }
    /**
     * 导出批次报工列表
     */
    @Log(title = "导出批次报工列表", businessType = BusinessType.EXPORT)
    @PostMapping("/download")
    public void download(HttpServletResponse response, BizDayworkItem bizDayworkItem) throws NoSuchFieldException, IllegalAccessException {
        List<BizDayworkItem> itemList = bizDayworkService.listReportItem(bizDayworkItem);
        List<Long> lotIds = itemList.stream().filter(item -> item.getProdNum() == 0).map(BizDayworkItem::getLotId).collect(Collectors.toList());
        List<BizLot> lotList = bizLotService.query().in("id", lotIds.isEmpty() ? Collections.singletonList(0L) : itemList.stream().filter(item -> item.getProdNum() == 0).map(BizDayworkItem::getLotId).collect(Collectors.toList())).list();
        //首序投产数为0，所以查询如果prodNum为0，其他是第一条报工的时候，给prodNum赋值单批量
        itemList.forEach(item -> {
            if (item.getProdNum() == 0) {
                //拿到第一条报工的工序步骤，为了判断这个投产数为0，是不是该工序步骤的报工，如果是，就给它的投产量赋值为单批量
                String processStepNumber = itemList.stream().filter(v -> v.getDayworkId().equals(item.getDayworkId())).sorted(Comparator.comparing(BizDayworkItem::getProcessStepNumber)).collect(Collectors.toList()).get(0).getProcessStepNumber();
                if (item.getProcessStepNumber().equals(processStepNumber)) {
                    item.setProdNum(lotList.stream().filter(lot -> lot.getId().equals(item.getLotId())).findFirst().get().getProductionQuantity());
                }
            }
            if ("0".equals(item.getStatus())) {
                item.setStatus("未开始");
            }
            if ("1".equals(item.getStatus())) {
                item.setStatus("进行中");
            }
            if ("2".equals(item.getStatus())) {
                item.setStatus("报工结束");
            }
            if ("3".equals(item.getStatus())) {
                item.setStatus("工序已完成");
            }
            if (item.getWorkingHours() != null) {
                int seconds = (int) Math.floor((item.getWorkingHours() / 1000) % 60);
                int minutes = (int) Math.floor((item.getWorkingHours() / (1000 * 60)) % 60);
                int hours = (int) Math.floor(item.getWorkingHours() / (1000 * 60 * 60));
                String time = hours + "小时" + minutes + "分钟" + seconds + "秒";
                item.setTotalTime(time);
            }
            if (item.getRejectNum() == null) {
                item.setRejectNum(0);
            }
        });
        ExcelUtil<BizDayworkItem> util = new ExcelUtil<>(BizDayworkItem.class);
        util.exportExcel(response, itemList, "报工数据");
    }

    /**
     * 导出批次报工列表
     */
    @Log(title = "导出批次报工列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizDaywork bizDaywork) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizDaywork);
        List<BizDaywork> list = bizDayworkService.getList(bizDaywork);
        ExcelUtil<BizDaywork> util = new ExcelUtil<>(BizDaywork.class);
        util.exportExcel(response, list, "报工数据");
    }

    /**
     * 获取报工详细信息
     */
    @GetMapping(value = "/{id}")
    @Log(title = "获取报工详细信息", businessType = BusinessType.SELECT)
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bizDayworkService.getById(id));
    }

    /**
     * 获取报工废品数信息
     */
    @GetMapping("/getDayworkItemRejectList")
    @Log(title = "获取报工废品数信息", businessType = BusinessType.SELECT)
    public AjaxResult getDayworkItemRejectList(BizDayworkItemReject bizDayworkItemReject) {
        return success(bizDayworkItemRejectService.getList(bizDayworkItemReject));
    }

    /*普通报工废品*/
    @GetMapping("/getOriginalDayworkItemRejectList")
    @Log(title = "普通报工废品", businessType = BusinessType.SELECT)
    public AjaxResult getOriginalDayworkItemRejectList(BizDayworkItemReject bizDayworkItemReject) {
        return success(bizDayworkItemRejectService.getOriginalDayworkItemRejectList(bizDayworkItemReject));
    }

    /**
     * 查询当前是否为首序
     */
    @Log(title = "查询当前是否为首序", businessType = BusinessType.SELECT)
    @GetMapping(value = "/getIsFirstOrder/{dayWorkId}")
    public AjaxResult getIsFirstOrder(@PathVariable("dayWorkId") Long dayWorkId) {
        HashMap<String, Object> map = new HashMap<>();
        //根据dayWorkId查询出当前工序的报工记录(按照工序筛选每道工序只查询一条数据)
        List<BizDayworkItem> list = bizDayworkItemService.getItemScreen(dayWorkId);
        //查询出来的数据等于1条则为首序
        if (list.size() == 1) {
            map.put("isFirstOrder", true);
        } else {
            map.put("isFirstOrder", false);
        }
        return success(map);
    }

    /**
     * 修改dayworkItem和dayworkItemReject
     *
     * @param bizDayworkItem
     * @return TableDataInfo
     */
    @Transactional
    @PostMapping("/updateDayworkItemInfo")
    @Log(title = "修改报工信息", businessType = BusinessType.SELECT)
    public AjaxResult updateDayworkItemInfo(@RequestBody BizDayworkItem bizDayworkItem) {
//        String tenantId = request.getHeader("tenantId");
//        bizDayworkItem.setTenantId(Long.valueOf(tenantId));
        if (bizDayworkItem.getStatus().equals("3")) {
            //往合格数中间表新增数据
            BizDayworkQualified bizDayworkQualified = new BizDayworkQualified();
            bizDayworkQualified.setDayworkId(bizDayworkItem.getDayworkId());
            bizDayworkQualified.setTemporaryProcessQualifiedNum(bizDayworkItem.getTemporaryProcessQualifiedNum());
            bizDayworkQualified.setProcessId(bizDayworkItem.getProcessId());
            bizDayworkQualified.setProcessQualifiedNum(bizDayworkItem.getProdNum());
            bizDayworkQualified.setProductionPlanDetailId(bizDayworkItem.getProductionPlanDetailId());
            bizDayworkQualifiedService.save(bizDayworkQualified);
        }
        //前端判断，如果状态从工序已完成变成报工结束时，将中间表数据删除
        if (bizDayworkItem.getFlag() != null) {
            QueryWrapper<BizDayworkQualified> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("deleted", 0);
            queryWrapper.eq("daywork_id", bizDayworkItem.getDayworkId());
            queryWrapper.eq("process_id", bizDayworkItem.getProcessId());
            List<BizDayworkQualified> list = bizDayworkQualifiedService.list(queryWrapper);
            if (list.size() > 0) {
                bizDayworkQualifiedService.removeById(list.get(0));
            }

        }
        //修改biz_daywork表的process_qualified_num(这道序的合格总数）
        QueryWrapper<BizDaywork> query = new QueryWrapper<>();
        query.eq("deleted", 0);
        query.eq("id", bizDayworkItem.getDayworkId());
        BizDaywork daywork = bizDayworkService.list(query).get(0);
        daywork.setTemporaryProcessQualifiedNum(bizDayworkItem.getTemporaryProcessQualifiedNum());
        bizDayworkService.updateById(daywork);
        //修改报工信息
        bizDayworkItem.setUpdateTime(new Date());
        bizDayworkItem.setUpdaterId(getUserId());
        bizDayworkItemService.updateDayworkItem((bizDayworkItem));
        //修改报工信息的废弃表
        QueryWrapper<BizDayworkItemReject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("daywork_item_id", bizDayworkItem.getId());
        queryWrapper.eq("process_inspection_id", 0);
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("daywork_auxiliary_item_id", 0);
        queryWrapper.eq("daywork_auxiliary_item_reject_id", 0);
        List<BizDayworkItemReject> oldList = bizDayworkItemRejectService.list(queryWrapper);
        saveOrUpdateBatch(bizDayworkItemRejectService, bizDayworkItem.getGroupRejectList(), oldList);
        return success();
    }

    /**
     * 修改dayworkItem和dayworkItemReject
     *
     * @param bizDayworkItem
     * @return TableDataInfo
     */
    @Transactional
    @PostMapping("/updateDayworkItemInfoForNum")
    @Log(title = "修改报工信息中的数量", businessType = BusinessType.SELECT)
    public AjaxResult updateDayworkItemInfoForNum(@RequestBody BizDayworkItem bizDayworkItem) {
//        String tenantId = request.getHeader("tenantId");
//        bizDayworkItem.setTenantId(Long.valueOf(tenantId));
        saveHistory(bizDayworkItem);

        if (bizDayworkItem.getStatus().equals("3")) {
            //往合格数中间表新增数据
            BizDayworkQualified bizDayworkQualified = new BizDayworkQualified();
            bizDayworkQualified.setDayworkId(bizDayworkItem.getDayworkId());
            bizDayworkQualified.setTemporaryProcessQualifiedNum(bizDayworkItem.getTemporaryProcessQualifiedNum());
            bizDayworkQualified.setProcessId(bizDayworkItem.getProcessId());
            bizDayworkQualified.setProcessQualifiedNum(bizDayworkItem.getProdNum());
            bizDayworkQualified.setProductionPlanDetailId(bizDayworkItem.getProductionPlanDetailId());
            bizDayworkQualifiedService.save(bizDayworkQualified);
        }
        //前端判断，如果状态从工序已完成变成报工结束时，将中间表数据删除
        if (bizDayworkItem.getFlag() != null) {
            QueryWrapper<BizDayworkQualified> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("deleted", 0);
            queryWrapper.eq("daywork_id", bizDayworkItem.getDayworkId());
            queryWrapper.eq("process_id", bizDayworkItem.getProcessId());
            List<BizDayworkQualified> list = bizDayworkQualifiedService.list(queryWrapper);
            if (list.size() > 0) {
                bizDayworkQualifiedService.removeById(list.get(0));
            }

        }
        //修改biz_daywork表的process_qualified_num(这道序的合格总数）
        // 判断是否是这个报工的最后一条报工明细
        BizDayworkItem lastItem = bizDayworkItemService.getLastItem(bizDayworkItem);
        if (lastItem.getId().equals(bizDayworkItem.getId())) {
            QueryWrapper<BizDaywork> query = new QueryWrapper<>();
            query.eq("deleted", 0);
            query.eq("id", bizDayworkItem.getDayworkId());
            BizDaywork daywork = bizDayworkService.list(query).get(0);
            daywork.setTemporaryProcessQualifiedNum(bizDayworkItem.getProdNum());
            daywork.setProcessQualifiedNum(bizDayworkItem.getProdNum());
            bizDayworkService.updateById(daywork);
        }

        //修改报工信息
        bizDayworkItem.setUpdateTime(new Date());
        bizDayworkItem.setUpdaterId(getUserId());
        bizDayworkItemService.updateDayworkItem((bizDayworkItem));
        //修改报工信息的废弃表
        QueryWrapper<BizDayworkItemReject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("daywork_item_id", bizDayworkItem.getId());
        queryWrapper.eq("process_inspection_id", 0);
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("daywork_auxiliary_item_id", 0);
        queryWrapper.eq("daywork_auxiliary_item_reject_id", 0);
        List<BizDayworkItemReject> oldList = bizDayworkItemRejectService.list(queryWrapper);
        saveOrUpdateBatch(bizDayworkItemRejectService, bizDayworkItem.getGroupRejectList(), oldList);
        return success();
    }

    @Transactional
    @PostMapping("/updateDayworkItemInfoForTurnover")
    @Log(title = "修改周转报工信息", businessType = BusinessType.SELECT)
    public AjaxResult updateDayworkItemInfoForTurnover(@RequestBody BizDayworkItem bizDayworkItem) {
        saveTurnoverHistory(bizDayworkItem);

        List<BizDayworkItem> items = bizDayworkItemService.query().eq("daywork_id", bizDayworkItem.getDayworkId()).ge("status", "4").list();

        BizDayworkItem lastItem = items.stream().sorted(Comparator.comparing(BizDayworkItem::getCreateTime).reversed()).findFirst().orElse(new BizDayworkItem());
//                bizDayworkItemService.getLastItem(bizDayworkItem);
        if (lastItem.getId().equals(bizDayworkItem.getId())) {
            QueryWrapper<BizDaywork> query = new QueryWrapper<>();
            query.eq("deleted", 0);
            query.eq("id", bizDayworkItem.getDayworkId());
            BizDaywork daywork = bizDayworkService.list(query).get(0);
            daywork.setTemporaryProcessQualifiedNum(bizDayworkItem.getProdNum());
            daywork.setProcessQualifiedNum(bizDayworkItem.getProdNum());
            daywork.setDeptId(bizDayworkItem.getDeptId());
            bizDayworkService.updateById(daywork);
        }
        //修改报工信息
        bizDayworkItem.setUpdateTime(new Date());
        bizDayworkItem.setUpdaterId(getUserId());
        bizDayworkItemService.updateDayworkItem((bizDayworkItem));
        //修改报工信息的废弃表
        QueryWrapper<BizDayworkItemReject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("daywork_item_id", bizDayworkItem.getId());
        queryWrapper.eq("process_inspection_id", 0);
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("daywork_auxiliary_item_id", 0);
        queryWrapper.eq("daywork_auxiliary_item_reject_id", 0);
        List<BizDayworkItemReject> oldList = bizDayworkItemRejectService.list(queryWrapper);
        saveOrUpdateBatch(bizDayworkItemRejectService, bizDayworkItem.getGroupRejectList(), oldList);
        return success();
    }

    private void saveTurnoverHistory(BizDayworkItem bizDayworkItem) {
        BizDayworkItem oldItem = bizDayworkItemService.getById(bizDayworkItem.getId());
        List<BizDayworkItemReject> dayworkIRejectList = bizDayworkItemRejectService.query().eq("daywork_item_id", bizDayworkItem.getId()).list();
        BizDayworkItemHistory bizDayworkItemHistory = new BizDayworkItemHistory();
        bizDayworkItemHistory.setDayworkItemId(bizDayworkItem.getId());
        bizDayworkItemHistory.setUserId(oldItem.getUserId());
        bizDayworkItemHistory.setNickName(oldItem.getNickName());
        bizDayworkItemHistory.setDayworkId(oldItem.getDayworkId());
        bizDayworkItemHistory.setProductDescription(bizDayworkItem.getProductDescription());
        bizDayworkItemHistory.setProductionPlanNo(bizDayworkItem.getProductionPlanNo());
        bizDayworkItemHistory.setProductionPlanDetailId(bizDayworkItem.getProductionPlanDetailId());
        bizDayworkItemHistory.setLotCode(bizDayworkItem.getLotCode());
        bizDayworkItemHistory.setProdNum(oldItem.getProdNum());
        bizDayworkItemHistory.setQualifiedNum(oldItem.getQualifiedNum());
        bizDayworkItemHistory.setRejectNum(dayworkIRejectList.isEmpty() ? 0 : (int) dayworkIRejectList.stream().mapToLong(BizDayworkItemReject::getRejectNum).sum());
        bizDayworkItemHistory.setTechnologyVersion(bizDayworkItem.getTechnologyVersion());
        bizDayworkItemHistory.setTechnologicalProcessId(oldItem.getTechnologicalProcessId());
        bizDayworkItemHistory.setTechnologicalProcessDetailId(oldItem.getTechnologicalProcessDetailId());
        bizDayworkItemHistory.setProcessStepNumber(oldItem.getProcessStepNumber());
        bizDayworkItemHistory.setProcessId(oldItem.getProcessId());
        bizDayworkItemHistory.setStartTime(bizDayworkItem.getStartTime());
        bizDayworkItemHistory.setEndTime(bizDayworkItem.getEndTime());
        bizDayworkItemHistory.setTurnoverId(oldItem.getTurnoverId());
        bizDayworkItemHistory.setTurnoverArea(oldItem.getTurnoverArea());
        bizDayworkItemHistory.setTurnoverType(oldItem.getTurnoverType());
        bizDayworkItemHistory.setPlace(oldItem.getPlace());
        bizDayworkItemHistory.setPlaceId(oldItem.getPlace());
        bizDayworkItemHistory.setDeptId(oldItem.getDeptId());
        bizDayworkItemHistory.setDeptName(oldItem.getDeptName());
        bizDayworkItemHistory.setFromDeptId(oldItem.getFromDeptId());
        bizDayworkItemHistory.setFromDeptName(oldItem.getFromDeptName());
        bizDayworkItemHistoryService.save(bizDayworkItemHistory);
    }

    public void saveHistory(BizDayworkItem bizDayworkItem) {
        // 更新历史
        BizDayworkItem oldItem = bizDayworkItemService.getById(bizDayworkItem.getId());
        List<BizDayworkItemReject> dayworkIRejectList = bizDayworkItemRejectService.query().eq("daywork_item_id", bizDayworkItem.getId()).list();
        BizDayworkItemHistory bizDayworkItemHistory = new BizDayworkItemHistory();
        bizDayworkItemHistory.setDayworkItemId(bizDayworkItem.getId());
        bizDayworkItemHistory.setUserId(oldItem.getUserId());
        bizDayworkItemHistory.setNickName(oldItem.getNickName());
        bizDayworkItemHistory.setDayworkId(oldItem.getDayworkId());
        bizDayworkItemHistory.setProductDescription(bizDayworkItem.getProductDescription());
        bizDayworkItemHistory.setProductionPlanNo(bizDayworkItem.getProductionPlanNo());
        bizDayworkItemHistory.setProductionPlanDetailId(bizDayworkItem.getProductionPlanDetailId());
        bizDayworkItemHistory.setLotCode(bizDayworkItem.getLotCode());
        bizDayworkItemHistory.setProdNum(oldItem.getProdNum());
        bizDayworkItemHistory.setQualifiedNum(oldItem.getQualifiedNum());
        bizDayworkItemHistory.setRejectNum(dayworkIRejectList.isEmpty() ? 0 : (int) dayworkIRejectList.stream().mapToLong(BizDayworkItemReject::getRejectNum).sum());
        bizDayworkItemHistory.setTechnologyVersion(bizDayworkItem.getTechnologyVersion());
        bizDayworkItemHistory.setTechnologicalProcessId(oldItem.getTechnologicalProcessId());
        bizDayworkItemHistory.setTechnologicalProcessDetailId(oldItem.getTechnologicalProcessDetailId());
        bizDayworkItemHistory.setProcessStepNumber(oldItem.getProcessStepNumber());
        bizDayworkItemHistory.setProcessId(oldItem.getProcessId());
        bizDayworkItemHistory.setStartTime(bizDayworkItem.getStartTime());
        bizDayworkItemHistory.setEndTime(bizDayworkItem.getEndTime());
        bizDayworkItemHistoryService.save(bizDayworkItemHistory);
    }

    public void saveHistoryMax(BizDayworkItem bizDayworkItem) {
        // 更新历史
        BizDayworkItem oldItem = bizDayworkItemService.getById(bizDayworkItem.getId());
        List<BizDayworkItemReject> dayworkIRejectList = bizDayworkItemRejectService.query().eq("daywork_item_id", bizDayworkItem.getId()).list();
        //载具信息
        List<BizDayworkCarrier> dayworkCarrierList = bizDayworkCarrierService.query().eq("is_changed", 0).eq("daywork_id", oldItem.getDayworkId()).list();
        BizDayworkItemMaxHistory bizDayworkItemHistory = new BizDayworkItemMaxHistory();
        bizDayworkItemHistory.setDayworkItemId(bizDayworkItem.getId());
        bizDayworkItemHistory.setUserId(oldItem.getUserId());
        bizDayworkItemHistory.setNickName(oldItem.getNickName());
        bizDayworkItemHistory.setDayworkId(oldItem.getDayworkId());
        bizDayworkItemHistory.setProductDescription(bizDayworkItem.getProductDescription());
        bizDayworkItemHistory.setProductionPlanNo(bizDayworkItem.getProductionPlanNo());
        bizDayworkItemHistory.setProductionPlanDetailId(bizDayworkItem.getProductionPlanDetailId());
        bizDayworkItemHistory.setLotCode(bizDayworkItem.getLotCode());
        bizDayworkItemHistory.setProdNum(oldItem.getProdNum());
        bizDayworkItemHistory.setQualifiedNum(oldItem.getQualifiedNum());
        bizDayworkItemHistory.setRejectNum(dayworkIRejectList.isEmpty() ? 0 : (int) dayworkIRejectList.stream().mapToLong(BizDayworkItemReject::getRejectNum).sum());
        bizDayworkItemHistory.setTechnologyVersion(bizDayworkItem.getTechnologyVersion());
        bizDayworkItemHistory.setTechnologicalProcessId(oldItem.getTechnologicalProcessId());
        bizDayworkItemHistory.setTechnologicalProcessDetailId(oldItem.getTechnologicalProcessDetailId());
        bizDayworkItemHistory.setProcessStepNumber(oldItem.getProcessStepNumber());
        bizDayworkItemHistory.setProcessId(oldItem.getProcessId());
        bizDayworkItemHistory.setStartTime(bizDayworkItem.getStartTime());
        bizDayworkItemHistory.setEndTime(bizDayworkItem.getEndTime());
        bizDayworkItemHistory.setEquipmentDetailId(oldItem.getEquipmentDetailId());
        bizDayworkItemHistory.setEquipmentDetailCode(oldItem.getEquipmentDetailCode());
        String carrierCode = dayworkCarrierList.stream().map(BizDayworkCarrier::getCarrierCode).collect(Collectors.joining(","));
        List<Long> carrierIds = dayworkCarrierList.stream()
                .map(BizDayworkCarrier::getCarrierId) // 提取 carrierId 属性
                .collect(Collectors.toList()); // 收集到列表
        String carrierIdsString = carrierIds.stream()
                .map(Object::toString) // 将每个 Long 转换为 String
                .collect(Collectors.joining(",")); // 连接成字符串
        bizDayworkItemHistory.setCarrierId(carrierIdsString);
        bizDayworkItemHistory.setCarrierCode(carrierCode);
        bizDayworkItemMaxHistoryService.save(bizDayworkItemHistory);
    }

    @Transactional
    @PostMapping("/updateDayworkItemInfoMax")
    @Log(title = "修改报工信息最高权限", businessType = BusinessType.UPDATE)
    public AjaxResult updateDayworkItemInfoMax(@RequestBody BizDayworkItem bizDayworkItem) {
        //判断箱子
        //判断箱子是否没被占用
        if (!bizDayworkItem.getCarrierIds().isEmpty()) {
            List<Long> carrierIds = bizDayworkItem.getCarrierIds();
            if (!carrierIds.isEmpty() && carrierIds.stream().noneMatch(Objects::isNull)) {
                List<BizCarrier> carrierList = bizCarrierService.query().in("id", carrierIds).list();
                //拿到其中的蓝箱子
                List<BizCarrier> blueCarrierList = carrierList.stream().filter(bizCarrier -> bizCarrier.getCategoryId().equals(2L)).collect(Collectors.toList());
                List<Long> blueCarrierIds = blueCarrierList.stream().map(BizCarrier::getId).collect(Collectors.toList());
                List<BizDayworkCarrier> dayworkCarrierList = bizDayworkCarrierService.query().in("carrier_id", blueCarrierIds.isEmpty() ? Collections.singletonList(0L) : blueCarrierList.stream().map(BizCarrier::getId).collect(Collectors.toList())).ne("daywork_id", bizDayworkItem.getDayworkId()).eq("is_changed", 0).list();
                if (dayworkCarrierList.size() > 0) {
                    String alreadyUseCarrierList = dayworkCarrierList.stream().map(BizDayworkCarrier::getCarrierCode).collect(Collectors.joining(","));
                    return error("载具编号" + alreadyUseCarrierList + "已被占用");
                }
                //判断箱子是否是同类型
                List<Long> collect = carrierList.stream().map(BizCarrier::getCategoryId).distinct().collect(Collectors.toList());
                List<BizCarrierCategory> carrierCategoryList = bizCarrierCategoryService.query().in("id", collect).list();
                if (collect.size() > 1) {
                    return error("箱子类型不一致");
                }
                //判断是否有多个铁箱子
                List<BizCarrierCategory> ironCarrierList = carrierCategoryList.stream().filter(item->item.getIsAllowMore()==1).collect(Collectors.toList());
                if (!ironCarrierList.isEmpty() && carrierIds.size()>1) {
                    return error("一个批次不能绑多个铁箱子");
                }
                //如果绑定铁箱子，判断该批次是否能绑定该铁箱（一个计划单能绑定同一个铁箱）
                if (!ironCarrierList.isEmpty() && carrierIds.size()==1) {
                    List<BizDayworkCarrier> iconDayworkCarrierList = bizDayworkCarrierService.query().ne("daywork_id", bizDayworkItem.getDayworkId()).eq("carrier_id", ironCarrierList.get(0).getId()).list();
                    if (iconDayworkCarrierList.size() > 0) {
                        //铁箱子的报工
                        BizDaywork iconDaywork = bizDayworkService.query().eq("id", iconDayworkCarrierList.get(0).getDayworkId()).list().get(0);
                        //退回单的报工
                        BizDaywork returnDaywork = bizDayworkService.query().eq("id", bizDayworkItem.getDayworkId()).list().get(0);
                        if (!iconDaywork.getProductionPlanDetailId().equals(returnDaywork.getProductionPlanDetailId())) {
                            return error("计划单不同，不能绑定该铁箱");
                        }

                    }
                }
                saveHistoryMax(bizDayworkItem);
                //删除箱子,做判断，因为检测箱子不显示，不能删除检测箱子
                List<BizDayworkCarrier> removeCarrierList = bizDayworkCarrierService.query().eq("daywork_id", bizDayworkItem.getDayworkId()).list();
                if (!removeCarrierList.isEmpty()) {
                    List<BizCarrier> needRemoveCarrierList = new ArrayList<>();
                    List<Long> carrierIdsList = removeCarrierList.stream().map(BizDayworkCarrier::getCarrierId).collect(Collectors.toList());
                    List<BizCarrier> carrier = bizCarrierService.query().in("id", carrierIdsList).list();
                    carrier.forEach(item -> {
                        if (item.getIsInspection() == 0) {
                            needRemoveCarrierList.add(item);
                        }
                    });
                    if (!needRemoveCarrierList.isEmpty()) {
                        List<BizDayworkCarrier> needRemoveDayworkList = bizDayworkCarrierService.query().eq("daywork_id", bizDayworkItem.getDayworkId()).in("carrier_id", needRemoveCarrierList.stream().map(BizCarrier::getId).collect(Collectors.toList())).list();
                        needRemoveDayworkList.forEach(item -> {
                            item.setIsChanged(1);
                        });
                        if (!needRemoveDayworkList.isEmpty()) {
                            bizDayworkCarrierService.removeBatchByIds(needRemoveDayworkList);
                        }
                    }

                }

                //重新绑箱
                List<BizDayworkCarrier> dayworkCarriers = new ArrayList<>();
                List<Long> distinctCarrier = new ArrayList<>();
                //绑定箱子
                carrierList.forEach(item -> {
                    BizDayworkCarrier bizDayworkCarrier = new BizDayworkCarrier();
                    if (!distinctCarrier.contains(item.getId())) {
                        distinctCarrier.add(item.getId());
                        bizDayworkCarrier.setDayworkId(bizDayworkItem.getDayworkId());
                        bizDayworkCarrier.setCarrierId(item.getId());
                        bizDayworkCarrier.setCarrierCode(item.getCode());
                        dayworkCarriers.add(bizDayworkCarrier);
                    }

                });
                bizDayworkCarrierService.saveBatch(dayworkCarriers);
            } else {
                saveHistoryMax(bizDayworkItem);
            }
        } else {
            saveHistoryMax(bizDayworkItem);
            //删除箱子,做判断，因为检测箱子不显示，不能删除检测箱子
            List<BizDayworkCarrier> removeCarrierList = bizDayworkCarrierService.query().eq("daywork_id", bizDayworkItem.getDayworkId()).list();
            if (!removeCarrierList.isEmpty()) {
                List<BizCarrier> needRemoveCarrierList = new ArrayList<>();
                List<Long> carrierIdsList = removeCarrierList.stream().map(BizDayworkCarrier::getCarrierId).collect(Collectors.toList());
                List<BizCarrier> carrier = bizCarrierService.query().in("id", carrierIdsList).list();
                carrier.forEach(item -> {
                    if (item.getIsInspection() == 0) {
                        needRemoveCarrierList.add(item);
                    }
                });
                if (!needRemoveCarrierList.isEmpty()) {
                    List<BizDayworkCarrier> needRemoveDayworkList = bizDayworkCarrierService.query().eq("daywork_id", bizDayworkItem.getDayworkId()).in("carrier_id", needRemoveCarrierList.stream().map(BizCarrier::getId).collect(Collectors.toList())).list();
                    needRemoveDayworkList.forEach(item -> {
                        item.setIsChanged(1);
                    });
                    if (!needRemoveDayworkList.isEmpty()) {
                        bizDayworkCarrierService.removeBatchByIds(needRemoveDayworkList);
                    }
                }
            }
        }
        //修改报工信息
        bizDayworkItem.setUpdateTime(new Date());
        bizDayworkItem.setUpdaterId(getUserId());
        bizDayworkItemService.updateDayworkItem((bizDayworkItem));
        //修改报工信息的废弃表
        QueryWrapper<BizDayworkItemReject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("daywork_item_id", bizDayworkItem.getId());
        queryWrapper.eq("process_inspection_id", 0);
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("daywork_auxiliary_item_id", 0);
        queryWrapper.eq("daywork_auxiliary_item_reject_id", 0);
        List<BizDayworkItemReject> oldList = bizDayworkItemRejectService.list(queryWrapper);
        saveOrUpdateBatch(bizDayworkItemRejectService, bizDayworkItem.getGroupRejectList(), oldList);
        return success();
    }

    @GetMapping("/processesForOutsourceByFirst")
    @Log(title = "获取首序外协工序", businessType = BusinessType.SELECT)
    public TableDataInfo listProcessesForOutsourceByFirst(BizLot bizLot) {
        //查找当前生产子计划的批次报工信息，找到最后一条包报工信息
        //List<BizDayworkItem> dayworkItemList = bizDayworkItemService.getList(dayworkItem);
        //用户再次提交时传入外协明细id
        BizLot currentLot = bizLotService.getById(bizLot.getId());
        currentLot.setKeyword(bizLot.getKeyword());
        //根据当前工序查找之后的工序列表
        //是否单批单改或废品回用
//        startPage();
        if (currentLot.getIsAmend() == 1 || currentLot.getIsWasteRecycling() == 1) {
            List<BizLotTechnologicalProcessDetail> processList = bizLotTechnologicalProcessDetailService.getProcessList(currentLot);
            return getDataTable(processList);
        } else {
            List<BizTechnologicalProcessDetail> processList = bizTechnologicalProcessDetailService.getProcessList(currentLot);
            return getDataTable(processList);
        }
    }
    @PostMapping("/multiProcessesForOutsourceByFirst")
    @Log(title = "获取首序外协工序", businessType = BusinessType.SELECT)
    public TableDataInfo multiProcessesForOutsourceByFirst(@RequestBody Map<String, Object> data) {
        List<Map<String, Object>> bizDayworkList = (List<Map<String, Object>>) data.get("dayworkList");
        String keyword = data.get("keyword").toString();
        List<BizDaywork> dayworks = convertToBizDayworkList(bizDayworkList);
        BizLot currentLot = bizLotService.getById(dayworks.get(0).getLotId());
        currentLot.setKeyword(keyword);
        //根据当前工序查找之后的工序列表
        //是否单批单改或废品回用
//        startPage();
            List<BizTechnologicalProcessDetail> processList = bizTechnologicalProcessDetailService.getProcessList(currentLot);
            return getDataTable(processList);
    }
    @PostMapping("/updateDayworkFurnace")
    @Log(title = "修改报工炉号", businessType = BusinessType.SELECT)
    public AjaxResult updateDayworkFurnace(@RequestBody BizDaywork bizDaywork) {
        List<BizFurnaceNoInfo> furnaceList = bizFurnaceNoInfoService.query().in("daywork_id", bizDaywork.getDayworkIds()).list();
        furnaceList.forEach(item->{
            item.setBrandNumber(bizDaywork.getFurnaceNoInfo().getBrandNumber());
            item.setDiameter(bizDaywork.getFurnaceNoInfo().getDiameter());
            item.setFactory(bizDaywork.getFurnaceNoInfo().getFactory());
            item.setFirstTechnicalRequirement(bizDaywork.getFurnaceNoInfo().getFirstTechnicalRequirement());
            item.setFurnaceNumber(bizDaywork.getFurnaceNoInfo().getFurnaceNumber());
            item.setIncomingDate(bizDaywork.getFurnaceNoInfo().getIncomingDate());
            item.setRawMaterialCode(bizDaywork.getFurnaceNoInfo().getRawMaterialCode());
            item.setSecondTechnicalRequirement(bizDaywork.getFurnaceNoInfo().getSecondTechnicalRequirement());
            item.setShape(bizDaywork.getFurnaceNoInfo().getShape());
            item.setSpec(bizDaywork.getFurnaceNoInfo().getSpec());
        });
        return success(bizFurnaceNoInfoService.updateBatchById(furnaceList));
    }
    @GetMapping("/getAllWorkShop")
    @Log(title = "获取所有车间和周转区", businessType = BusinessType.SELECT)
    public AjaxResult getAllWorkShop(SysDept dept) {
        // 获取所有的车间和车间内工段
        List<BizWorkshop> workShopList = bizWorkshopService.query().list();
        List<BizTurnover> bizTurnovers = bizTurnoverService.query().eq("status", 0).list();
        List<BizWorkshopTurnover> bizWorkshopTurnovers = bizWorkshopTurnoverService.query().eq("status", 0).list();

        SysDept conditions = new SysDept();
        conditions.setIsWorkSection(1);
        List<SysDept> depts = deptService.selectDeptList(conditions);
        List<SysDept> departments = new ArrayList<>();
        if (dept.getIsAmend() == 1 || dept.getIsWasteRecycling() == 1) {
            BizLot bizLot = bizLotService.query().eq("id", dept.getLotId()).list().get(0);
            dept.setLotTechnologicalProcessId(bizLot.getTechnologicalProcessId());
            departments = deptService.selectDeptListByTechnologyWasteRecyclingId(dept);
        } else {
            departments = deptService.selectDeptListByPlanDetailsId(dept);
        }
        List<BizWorkshop> finalWorkShopList = workShopList;
        depts.forEach(l -> {
            l.setTurnovers(bizTurnovers.stream().filter(v -> v.getDeptId().equals(l.getDeptId())).collect(Collectors.toList()));
        });
        departments.forEach(l -> {
            BizWorkshop bizWorkshop = finalWorkShopList.stream().filter(v -> v.getId().equals(l.getWorkshopId())).findFirst().orElse(null);
            l.setWorkshopName(bizWorkshop == null ? null : bizWorkshop.getName());
            l.setTurnovers(bizTurnovers.stream().filter(v -> v.getDeptId().equals(l.getDeptId())).collect(Collectors.toList()));
        });
        depts.forEach(l -> {
            BizWorkshop bizWorkshop = finalWorkShopList.stream().filter(v -> v.getId().equals(l.getWorkshopId())).findFirst().orElse(null);
            l.setWorkshopName(bizWorkshop == null ? null : bizWorkshop.getName());
            l.setTurnovers(bizTurnovers.stream().filter(v -> v.getDeptId().equals(l.getDeptId())).collect(Collectors.toList()));
        });
        workShopList.forEach(l -> {
            l.setTurnovers(bizWorkshopTurnovers.stream().filter(v -> v.getWorkshopId().equals(l.getId())).collect(Collectors.toList()));
        });
        List<SysDept> finalDepartments = departments;
        List<BizWorkshop> nextWorkShopList = workShopList.stream().filter(v -> finalDepartments.stream().anyMatch(e -> e.getWorkshopId().equals(v.getId()))).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("workshops", nextWorkShopList);
        map.put("allWorkshops", workShopList);
        map.put("depts", departments);
        map.put("allDepts", depts);
        return success(map);
    }
}
