package cn.ezhizao.project.business.controller;

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.redis.RedisCache;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.domain.*;
import cn.ezhizao.project.business.service.*;
import cn.ezhizao.project.system.domain.SysDept;
import cn.ezhizao.project.system.mapper.SysDeptMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
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.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 外协单主
带箱方式，是整单的。如果换新箱子，明细中，都需要更换箱子Controller
 *
 * @author ezhizao
 * @date 2024-05-08
 */
@RestController
@RequestMapping("/business/returnTurnover")
public class BizReturnTurnoverController extends BaseController
{
    @Resource
    private IBizReturnReceiptService bizReturnReceiptService;
    @Resource
    private IBizReturnReceiptDetailService bizReturnReceiptDetailService;
    @Resource
    private IBizOutsourcedOrderDetailProcessService bizOutsourcedOrderDetailProcessService;
    @Resource
    private IBizTechnologicalProcessService bizTechnologicalProcessService;
    @Resource
    private IBizProductionPlanDetailService bizProductionPlanDetailService;
    @Resource
    private IBizCarrierService carrierService;
    @Resource
    private IBizDayworkItemService bizDayworkItemService;
    @Resource
    private IBizDayworkCarrierService bizDayworkCarrierService;
    @Resource
    private IBizLotTechnologicalProcessService bizLotTechnologicalProcessService;
    @Resource
    private IBizProductionResourceGroupSubPlanService bizProductionResourceGroupSubPlanService;
    @Resource
    private IBizOutsourcedOrderDetailService bizOutsourcedOrderDetailService;
    @Resource
    private IBizDayworkService bizDayworkService;
    @Resource
    private IBizProcessInspecionService bizProcessInspecionService;
    @Resource
    private IBizProductionResourceGroupService bizProductionResourceGroupService;
    @Resource
    private IBizCarrierCategoryService carrierCategoryService;
    @Resource
    private IBizTakeStockPeriodService bizTakeStockPeriodService;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private IBizDayworkItemExamineService bizDayworkItemExamineService;
    @Resource
    private RedisCache redisCache;
    @Resource
    HttpServletRequest request;

    /**
     * 查询外协单主
带箱方式，是整单的。如果换新箱子，明细中，都需要更换箱子列表
     */
    @PreAuthorize("@ss.hasPermi('business:returnTurnover:list')")
    @GetMapping("/getFinishedReturnList")
    public TableDataInfo getFinishedReturnList(BizOutsourcedOrderDetail bizOutsourcedOrderDetail) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizOutsourcedOrderDetail);
        if(bizOutsourcedOrderDetail.getStartTime()!=null) {
            bizOutsourcedOrderDetail.setStartTime(bizOutsourcedOrderDetail.getStartTime()+ " 00:00:00");
        }
        if(bizOutsourcedOrderDetail.getEndTime()!=null) {
            bizOutsourcedOrderDetail.setEndTime(bizOutsourcedOrderDetail.getEndTime()+ " 23:59:59");
        }
        startPage();
        List<BizOutsourcedOrderDetail> list = bizOutsourcedOrderDetailService.getFinishedReturnList(bizOutsourcedOrderDetail);
        //查询周转到外协的工序
        List<Long> outsourceDetailIds = list.stream().map(BizOutsourcedOrderDetail::getId).collect(Collectors.toList());
        List<Long> dayworkIds = list.stream().map(BizOutsourcedOrderDetail::getDayworkId).collect(Collectors.toList());
        List<BizDaywork> dayworks = bizDayworkService.query().in("id", dayworkIds.isEmpty()? Collections.singletonList(0L): dayworkIds).list();
        if(!dayworkIds.isEmpty()) {
            List<BizOutsourcedOrderDetailProcess> outsourceDetailProcess = bizOutsourcedOrderDetailProcessService.query().in("detail_id", outsourceDetailIds).list();
            //如果下道序扫码开始新批次了，则不能编辑载具和周转信息
            List<BizDayworkItem> dayworkItemList = bizDayworkItemService.getListByDayworkIds(dayworkIds);
            for (BizOutsourcedOrderDetail detail : list) {
                detail.setFlag(true);
                //拿到最新的工序
                BizOutsourcedOrderDetailProcess lastProcess = outsourceDetailProcess.stream().filter(process -> process.getDetailId().equals(detail.getId())).sorted(Comparator.comparing(BizOutsourcedOrderDetailProcess::getProcessStepNumber).reversed()).collect(Collectors.toList()).get(0);
                //拿到最新的一条报工
                BizDayworkItem lastItem = dayworkItemList.stream().filter(dayworkItem -> dayworkItem.getDayworkId().equals(detail.getDayworkId())).sorted(Comparator.comparing(BizDayworkItem::getProcessStepNumber).thenComparing(BizDayworkItem::getCreateTime).reversed()).collect(Collectors.toList()).stream().findFirst().orElse(null);
                if(lastItem != null  && !Objects.equals(lastProcess.getProcessStepNumber(), lastItem.getProcessStepNumber())) {
                    detail.setFlag(false);
                }
                BizDaywork daywork = dayworks.stream().filter(l -> l.getId().equals(detail.getDayworkId())).findFirst().orElse(null);
                if (daywork != null) {
                    detail.setIsAmend(daywork.getIsAmend());
                    detail.setIsWaste(daywork.getIsWaste());
                    detail.setIsWasteRecycling(Integer.parseInt(daywork.getIsWasteRecycling().toString()));
                    detail.setIsSuperaddition(daywork.getIsSuperaddition());
                }

            }
//            List<BizDayworkCarrier> dayworkCarrierList = bizDayworkCarrierService.query().in("daywork_id", dayworkIds).eq("is_changed",0).list();
//            for (BizOutsourcedOrderDetail detail : list) {
//                if(!detail.getProductionCarrier().isEmpty()) {
//                    List<String> carrierCode = Arrays.stream(detail.getProductionCarrier().split(",")).collect(Collectors.toList());
//                    List<Long> carrierIds = bizDayworkCarrierService.query().in("carrier_code", carrierCode).eq("is_changed",0).list().stream().map(BizDayworkCarrier::getCarrierId).collect(Collectors.toList());
//                    detail.setDayworkCarrierList(dayworkCarrierList.stream().filter(carrier -> carrier.getDayworkId().equals(detail.getDayworkId())).collect(Collectors.toList()));
//                    detail.setCarrierIds(carrierIds);
//                }else {
//                    //用的原箱
//                    if ("0".equals(detail.getPackagingMethod())) {
//                        List<Long> carrierIds = dayworkCarrierList.stream().filter(carrier -> carrier.getDayworkId().equals(detail.getDayworkId())).map(BizDayworkCarrier::getCarrierId).collect(Collectors.toList());
//                        detail.setCarrierIds(carrierIds);
//                        detail.setDayworkCarrierList(dayworkCarrierList.stream().filter(carrier -> carrier.getDayworkId().equals(detail.getDayworkId())).collect(Collectors.toList()));
//                    } else {
//                        //外协使用新箱，则把新箱解绑，返回空
//                        List<BizDayworkCarrier> wxCarrier = dayworkCarrierList.stream().filter(carrier -> carrier.getDayworkId().equals(detail.getDayworkId())).collect(Collectors.toList());
//                        wxCarrier.stream().forEach(carrier -> {
//                            carrier.setIsChanged(1);
//                        });
//                        bizDayworkCarrierService.updateBatchById(wxCarrier);
//                        detail.setCarrierIds(new ArrayList<>());
//                    }
//                }
//            }
        }
        return getDataTable(list);
    }
    @PostMapping("/getNowBindCarriers")
    public AjaxResult getNowBindCarriers(@ RequestBody BizOutsourcedOrderDetail bizOutsourcedOrderDetail) throws NoSuchFieldException, IllegalAccessException
    {
        List<BizDayworkCarrier> dayworkCarrierList = bizDayworkCarrierService.query().eq("daywork_id", bizOutsourcedOrderDetail.getDayworkId()).eq("is_changed",0).list();
                if(!bizOutsourcedOrderDetail.getProductionCarrier().isEmpty()) {
                    List<String> carrierCode = Arrays.stream(bizOutsourcedOrderDetail.getProductionCarrier().split(",")).collect(Collectors.toList());
                    List<Long> carrierIds = bizDayworkCarrierService.query().in("carrier_code", carrierCode).eq("is_changed",0).list().stream().map(BizDayworkCarrier::getCarrierId).collect(Collectors.toList());
                    bizOutsourcedOrderDetail.setDayworkCarrierList(dayworkCarrierList.stream().filter(carrier -> carrier.getDayworkId().equals(bizOutsourcedOrderDetail.getDayworkId())).collect(Collectors.toList()));
                    bizOutsourcedOrderDetail.setCarrierIds(carrierIds);
                }else {
                    //用的原箱
                    if ("0".equals(bizOutsourcedOrderDetail.getPackagingMethod())) {
                        List<Long> carrierIds = dayworkCarrierList.stream().filter(carrier -> carrier.getDayworkId().equals(bizOutsourcedOrderDetail.getDayworkId())).map(BizDayworkCarrier::getCarrierId).collect(Collectors.toList());
                        bizOutsourcedOrderDetail.setCarrierIds(carrierIds);
                        bizOutsourcedOrderDetail.setDayworkCarrierList(dayworkCarrierList.stream().filter(carrier -> carrier.getDayworkId().equals(bizOutsourcedOrderDetail.getDayworkId())).collect(Collectors.toList()));
                    } else {
                        //外协使用新箱，则把新箱解绑，返回空
                        List<BizDayworkCarrier> wxCarrier = dayworkCarrierList.stream().filter(carrier -> carrier.getDayworkId().equals(bizOutsourcedOrderDetail.getDayworkId())).collect(Collectors.toList());
                        wxCarrier.stream().forEach(carrier -> {
                            carrier.setIsChanged(1);
                        });
                        bizDayworkCarrierService.updateBatchById(wxCarrier);
                        bizOutsourcedOrderDetail.setCarrierIds(new ArrayList<>());
                    }
                }
                return success(bizOutsourcedOrderDetail);
            }

    /**
     * 查询周转工段
     */
    @GetMapping("/getTurnoverDeptList")
    public AjaxResult getTurnoverDeptList(BizReturnReceiptDetail bizReturnReceiptDetail) throws NoSuchFieldException, IllegalAccessException
    {
        List<SysDept> departments = new ArrayList<>();
        BizDaywork daywork = bizDayworkService.query().eq("id",bizReturnReceiptDetail.getDayworkId()).list().get(0);
        daywork.setProcessStepNumber(bizReturnReceiptDetail.getProcessStepNumber());
        BizDaywork info = new BizDaywork();
        if(daywork.getIsWasteRecycling() == 1 || daywork.getIsAmend() == 1) {
            departments = bizReturnReceiptDetailService.getTurnoverAbDeptList(daywork);
        }else {
            departments = bizReturnReceiptDetailService.getTurnoverDeptList(daywork);
        }
        return success(departments);
    }
    @PostMapping("/getProcessInspectionList")
    public AjaxResult getProcessInspectionList(@RequestBody BizOutsourcedOrderDetailProcess bizOutsourcedOrderDetailProcess) throws NoSuchFieldException, IllegalAccessException
    {
        Boolean flag = false;
        List<BizProcessInspecion> processInspecions = bizProcessInspecionService.query().eq("return_receipt_detail_id", bizOutsourcedOrderDetailProcess.getReturnReceiptDetailId()).orderByDesc("create_time").list();
        if (processInspecions.size()>0 &&processInspecions.get(0).getStatus()==1) {
            flag = true;
            return success(flag);
        }
        return success(flag);
    }

    @PostMapping("/getProcessInspectionLists")
    public AjaxResult getProcessInspectionLists(@RequestBody List<BizOutsourcedOrderDetailProcess> bizOutsourcedOrderDetailProcess) throws NoSuchFieldException, IllegalAccessException
    {
        boolean flag = false;
        List<BizProcessInspecion> processInspecions = bizProcessInspecionService.query().in("return_receipt_detail_id", bizOutsourcedOrderDetailProcess.stream().map(BizOutsourcedOrderDetailProcess::getReturnReceiptDetailId).collect(Collectors.toList())).orderByDesc("create_time").list();
        if (processInspecions.size()>0 && bizOutsourcedOrderDetailProcess.stream().allMatch(t -> processInspecions.stream().filter(e -> e.getStatus().equals(1)).anyMatch(e -> e.getReturnReceiptDetailId().equals(t.getReturnReceiptDetailId())))) {
            flag = true;
            return success(flag);
        }
        return success(flag);
    }
    /**
     * 修改外协单主
带箱方式，是整单的。如果换新箱子，明细中，都需要更换箱子
     */
    @PreAuthorize("@ss.hasPermi('business:returnTurnover:edit')")
    @Log(title = "外协周转", businessType = BusinessType.UPDATE)
    @Transactional
    @PutMapping
    public AjaxResult edit(@RequestBody BizOutsourcedOrderDetail outsourcedOrderDetail) throws NoSuchFieldException, IllegalAccessException
    {
        //判断盘点
        BizTakeStockPeriod bizTakeStockPeriod = bizTakeStockPeriodService.query().eq("status",1).one();
        if(bizTakeStockPeriod!=null && bizTakeStockPeriod.getStatus() == 1) {
            return error("正在盘点，不能周转");
        }
        //判断箱子是否没被占用
        List<Long> carrierIds = outsourcedOrderDetail.getCarriers().stream().map(BizCarrier::getId).collect(Collectors.toList());
        List<BizCarrier> carrierList = carrierService.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", outsourcedOrderDetail.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());
        if(collect.size()>1) {
            return error("箱子类型不一致");
        }
        //判断是否有多个铁箱子
        List<BizCarrier> ironCarrierList = carrierList.stream().filter(bizCarrier -> bizCarrier.getCategoryId().equals(1769620722266718210L)).collect(Collectors.toList());
        if(ironCarrierList.size() >1) {
            return error("一个批次不能绑多个铁箱子");
        }
        //如果绑定铁箱子，判断该批次是否能绑定该铁箱（一个计划单能绑定同一个铁箱）
        if (ironCarrierList.size() == 1) {
            List<BizDayworkCarrier> iconDayworkCarrierList = bizDayworkCarrierService.query().ne("daywork_id", outsourcedOrderDetail.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", outsourcedOrderDetail.getDayworkId()).list().get(0);
                if(!iconDaywork.getProductionPlanDetailId().equals(returnDaywork.getProductionPlanDetailId())) {
                    return error("计划单不同，不能绑定该铁箱");
                }

            }
        }
        //下序分选包装审核
        if(outsourcedOrderDetail.getIsSortPackaging() !=null && outsourcedOrderDetail.getIsSortPackaging()==1) {
            List<BizDayworkItemExamine> dayworkItemExamineList = bizDayworkItemExamineService.query().eq("daywork_id", outsourcedOrderDetail.getDayworkId()).list();
            if(!dayworkItemExamineList.isEmpty()){
                bizDayworkItemExamineService.removeBatchByIds(dayworkItemExamineList);
            }
            //新增
            BizDayworkItemExamine examine = new BizDayworkItemExamine();
            examine.setDayworkId(outsourcedOrderDetail.getDayworkId());
            examine.setDayworkItemId(outsourcedOrderDetail.getDayworkItemId());
            examine.setDeptId(outsourcedOrderDetail.getProductionDeptId());
            examine.setProductionPlanDetailId(outsourcedOrderDetail.getProductionPlanDetailId());
            examine.setProductDescription(outsourcedOrderDetail.getProductDescription());
            examine.setLotId(outsourcedOrderDetail.getLotId());
            examine.setLotCode(outsourcedOrderDetail.getLotCode());
            examine.setProductId(outsourcedOrderDetail.getProductId());
            examine.setTechnologicalProcessId(outsourcedOrderDetail.getTechnologicalProcessId());
            examine.setTechnologicalProcessDetailId(outsourcedOrderDetail.getFinishedProcesses().get(outsourcedOrderDetail.getFinishedProcesses().size() - 1).getTechnologicalProcessDetailId());
            examine.setProcessId(outsourcedOrderDetail.getFinishedProcesses().get(outsourcedOrderDetail.getFinishedProcesses().size() - 1).getProcessId());
            examine.setProcessAlias(outsourcedOrderDetail.getFinishedProcesses().get(outsourcedOrderDetail.getFinishedProcesses().size() - 1).getProcessAlias());
            examine.setStatus(0);
            bizDayworkItemExamineService.save(examine);
        }
        //箱子判断完，修改收回单明细的箱号和周转工段
        bizOutsourcedOrderDetailService.updateById(outsourcedOrderDetail);
        //操作dayworkCarrier表，如果该批次已经绑箱，把对应箱解绑，并重新绑定新箱子
        List<BizDayworkCarrier> returnDayworkCarrierList = bizDayworkCarrierService.query().eq("daywork_id", outsourcedOrderDetail.getDayworkId()).eq("process_inspection_id", 0L).eq("is_changed",0).list();
        if (returnDayworkCarrierList.size() > 0){
            returnDayworkCarrierList.stream().forEach(bizDayworkCarrier -> {bizDayworkCarrier.setIsChanged(1);});
            bizDayworkCarrierService.updateBatchById(returnDayworkCarrierList);
        }
        List<BizDayworkCarrier> newDayworkCarrierList = new ArrayList<>();
        for(BizCarrier bizCarrier : outsourcedOrderDetail.getCarriers()) {
            BizDayworkCarrier bizDayworkCarrier = new BizDayworkCarrier();
            bizDayworkCarrier.setCarrierId(bizCarrier.getId());
            bizDayworkCarrier.setCarrierCode(bizCarrier.getCode());
            bizDayworkCarrier.setDayworkId(outsourcedOrderDetail.getDayworkId());
            bizDayworkCarrier.setLotId(outsourcedOrderDetail.getLotId());
            newDayworkCarrierList.add(bizDayworkCarrier);
        }
        bizDayworkCarrierService.saveBatch(newDayworkCarrierList);
        //拿到外协的最后一条报工
        List<Long> dayworkId = new ArrayList<>();
        dayworkId.add(outsourcedOrderDetail.getDayworkId());
        BizDayworkItem lastDayworkItem = bizDayworkItemService.getListByDayworkIdsForOutsourced(dayworkId).stream().sorted(Comparator.comparing(BizDayworkItem::getProcessStepNumber).reversed()).collect(Collectors.toList()).get(0);
        //判断dayworkItem最新的一条状态，如果是7，则把这条删除，重新新增
        List<BizDayworkItem> dayworkItem = bizDayworkItemService.getListByDayworkIds(dayworkId);
        BizDayworkItem bizDayworkItem = dayworkItem.stream().sorted(Comparator.comparing(BizDayworkItem::getProcessStepNumber).thenComparing(BizDayworkItem::getCreateTime).reversed()).collect(Collectors.toList()).get(0);
        if("4".equals(bizDayworkItem.getStatus())){
            bizDayworkItemService.removeById(bizDayworkItem);
        }
        //添加周转的一条dayworkItem
        BizDayworkItem newBizDayworkItem = new BizDayworkItem();
        //拿到周转到外协的最后一条数据
        newBizDayworkItem.setDayworkId(outsourcedOrderDetail.getDayworkId());
        newBizDayworkItem.setProductionPlanDetailId(lastDayworkItem.getProductionPlanDetailId());
        newBizDayworkItem.setLotId(outsourcedOrderDetail.getLotId());
        newBizDayworkItem.setProdNum(outsourcedOrderDetail.getAuditNum());
        newBizDayworkItem.setQualifiedNum(outsourcedOrderDetail.getAuditNum());
        newBizDayworkItem.setTechnologicalProcessId(lastDayworkItem.getTechnologicalProcessId());
        newBizDayworkItem.setTechnologicalProcessDetailId(lastDayworkItem.getTechnologicalProcessDetailId());
        newBizDayworkItem.setProcessStepNumber(lastDayworkItem.getProcessStepNumber());
        newBizDayworkItem.setProcessId(lastDayworkItem.getProcessId());
        newBizDayworkItem.setDeptId(outsourcedOrderDetail.getProductionDeptId());
        newBizDayworkItem.setDeptName(outsourcedOrderDetail.getProductionDeptName());
        newBizDayworkItem.setStatus("4");
        newBizDayworkItem.setNickName("外协");
        newBizDayworkItem.setStartTime(new Date());
        newBizDayworkItem.setTurnoverType("2");
        newBizDayworkItem.setTurnoverArea("外协周转区");
        bizDayworkItemService.save(newBizDayworkItem);
        //修改daywork主表数据
        BizDaywork bizDaywork = bizDayworkService.query().eq("id", outsourcedOrderDetail.getDayworkId()).list().get(0);
        bizDaywork.setProcessQualifiedNum(outsourcedOrderDetail.getAuditNum());
        bizDaywork.setTemporaryProcessQualifiedNum(outsourcedOrderDetail.getAuditNum());
        bizDaywork.setDeptId(outsourcedOrderDetail.getProductionDeptId());
        bizDayworkService.updateById(bizDaywork);
        // 自动派活
        SysDept sysDept = sysDeptMapper.selectDeptById(outsourcedOrderDetail.getProductionDeptId());
        if (sysDept.getAutoAllocation() == 1) {
            // 查资源组
            List<BizProductionResourceGroup> productionResourceGroupList = bizProductionResourceGroupService.list(new QueryWrapper<BizProductionResourceGroup>().eq("dept_id", outsourcedOrderDetail.getProductionDeptId()).eq("is_deactivate", 0));

            //查询是否已经分配资源组
            BizProductionResourceGroupSubPlan groupSubPlan=new BizProductionResourceGroupSubPlan();
            groupSubPlan.setDeptId(outsourcedOrderDetail.getProductionDeptId());
            groupSubPlan.setProductionPlanDetailId(lastDayworkItem.getProductionPlanDetailId());

            List<BizProductionResourceGroupSubPlan> groupSubPlanList = bizProductionResourceGroupSubPlanService.getAotList(groupSubPlan);
            //如果没分配
            if(groupSubPlanList.size()==0){
                //查产品id
                BizProductionPlanDetail productionPlanDetail = bizProductionPlanDetailService.getOne(new QueryWrapper<BizProductionPlanDetail>().eq("id", bizDayworkItem.getProductionPlanDetailId()));
                //存放保存的subPlanList
                List<BizProductionResourceGroupSubPlan> subPlanList = new ArrayList<>();
                for (BizProductionResourceGroup info : productionResourceGroupList) {
                    BizProductionResourceGroupSubPlan subPlan = new BizProductionResourceGroupSubPlan();
                    subPlan.setProductId(productionPlanDetail.getProductId());
                    subPlan.setProductionPlanDetailId(lastDayworkItem.getProductionPlanDetailId());
                    subPlan.setTechnologicalProcessId(outsourcedOrderDetail.getTechnologicalProcessId());
                    subPlan.setResourceGroupId(info.getId());
                    subPlan.setDeptId(outsourcedOrderDetail.getProductionDeptId());
                    subPlan.setResourceGroupCode(info.getCode());
                    subPlanList.add(subPlan);
                }
                bizProductionResourceGroupSubPlanService.saveBatch(subPlanList);
            }

        }
        return success();
    }


    @PreAuthorize("@ss.hasPermi('business:returnTurnover:edit')")
    @Log(title = "外协批量周转", businessType = BusinessType.UPDATE)
    @Transactional
    @PostMapping("/batchTurnover")
    public AjaxResult batchTurnover(@RequestBody BizOutsourcedOrderDetail outsourcedOrderDetail) throws NoSuchFieldException, IllegalAccessException {
       //判断盘点
        BizTakeStockPeriod bizTakeStockPeriod = bizTakeStockPeriodService.query().eq("status",1).one();
        if(bizTakeStockPeriod!=null && bizTakeStockPeriod.getStatus() == 1) {
            return error("正在盘点，不能周转");
        }
        // 批量周转不换箱 则不需要判断是否箱被占用
        //修改收回单明细的箱号和周转工段
        List<BizOutsourcedOrderDetail> batches = outsourcedOrderDetail.getBatches();
        List<BizDayworkItem> addItems = new ArrayList<>();
        List<BizDayworkItem> removeItems = new ArrayList<>();
        List<BizDaywork> updateDaywork = new ArrayList<>();
        List<BizProductionResourceGroupSubPlan> subPlanList = new ArrayList<>();
        //操作dayworkCarrier表，如果该批次已经绑箱，把对应箱解绑，并重新绑定新箱子
        List<BizDayworkCarrier> newDayworkCarrierList = new ArrayList<>();
        List<BizDayworkItem> bizDayworkItems = bizDayworkItemService.getListByDayworkIds(batches.stream().map(BizOutsourcedOrderDetail::getDayworkId).collect(Collectors.toList()));
        List<BizDayworkCarrier> returnDayworkCarrierList = bizDayworkCarrierService.query().in("daywork_id", batches.isEmpty() ? Collections.singletonList(0L) : batches.stream().map(BizOutsourcedOrderDetail::getDayworkId).collect(Collectors.toList())).eq("process_inspection_id", 0L).eq("is_changed",0).list();
        List<BizDaywork> bizDayworks = bizDayworkService.query().in("id", batches.isEmpty() ? Collections.singletonList(0L) : batches.stream().map(BizOutsourcedOrderDetail::getDayworkId).collect(Collectors.toList())).list();

        if (returnDayworkCarrierList.size() > 0){
            returnDayworkCarrierList.stream().forEach(bizDayworkCarrier -> bizDayworkCarrier.setIsChanged(1));
        }
        //下序是否包装审核
          if(outsourcedOrderDetail.getIsSortPackaging()!=null && outsourcedOrderDetail.getIsSortPackaging() == 1) {
              List<BizDayworkItemExamine> dayworkItemExamineList = bizDayworkItemExamineService.query().in("daywork_id", batches.isEmpty() ? Collections.singletonList(0L) : batches.stream().map(BizOutsourcedOrderDetail::getDayworkId).collect(Collectors.toList())).list();
              if(!dayworkItemExamineList.isEmpty()){
                  bizDayworkItemExamineService.removeBatchByIds(dayworkItemExamineList);
              }
              //新增包装前审核
              List<BizDayworkItemExamine> addExamineList = new ArrayList<>();
              for (BizOutsourcedOrderDetail item : batches) {
                  BizDayworkItemExamine examine = new BizDayworkItemExamine();
                  examine.setDayworkId(item.getDayworkId());
                  examine.setDayworkItemId(item.getDayworkItemId());
                  examine.setDeptId(item.getProductionDeptId());
                  examine.setProductionPlanDetailId(item.getProductionPlanDetailId());
                  examine.setProductDescription(item.getProductDescription());
                  examine.setLotId(item.getLotId());
                  examine.setLotCode(item.getLotCode());
                  examine.setProductId(item.getProductId());
                  examine.setTechnologicalProcessId(item.getTechnologicalProcessId());
                  examine.setTechnologicalProcessDetailId(item.getFinishedProcesses().get(item.getFinishedProcesses().size() - 1).getTechnologicalProcessDetailId());
                  examine.setProcessId(item.getFinishedProcesses().get(item.getFinishedProcesses().size() - 1).getProcessId());
                  examine.setProcessAlias(item.getFinishedProcesses().get(item.getFinishedProcesses().size() - 1).getProcessAlias());
                  examine.setStatus(0);
                  addExamineList.add(examine);
              }
              bizDayworkItemExamineService.saveBatch(addExamineList);
          }


        // 自动派活
        SysDept sysDept = sysDeptMapper.selectDeptById(outsourcedOrderDetail.getProductionDeptId());

        List<BizProductionResourceGroup> productionResourceGroupList = bizProductionResourceGroupService.list(new QueryWrapper<BizProductionResourceGroup>().eq("dept_id", outsourcedOrderDetail.getProductionDeptId()).eq("is_deactivate", 0));

        batches.forEach(l -> {
            l.setProductionCarrier(l.getNewCarrierName());
            l.setProductionDeptId(outsourcedOrderDetail.getProductionDeptId());
            l.setProductionDeptName(outsourcedOrderDetail.getProductionDeptName());
            l.getCarriers().forEach(v -> {
                BizDayworkCarrier carrier = new BizDayworkCarrier();
                carrier.setCarrierId(v.getId());
                carrier.setCarrierCode(v.getCode());
                carrier.setDayworkId(l.getDayworkId());
                carrier.setLotId(l.getLotId());
                newDayworkCarrierList.add(carrier);
            });
            BizDaywork daywork = bizDayworks.stream().filter(v -> v.getId().equals(l.getDayworkId())).findFirst().orElse(null);
            BizDayworkItem lastDayworkItem = bizDayworkItems.stream().filter(v -> v.getDayworkId().equals(l.getDayworkId())).sorted(Comparator.comparing(BizDayworkItem::getProcessStepNumber).reversed()).collect(Collectors.toList()).get(0);
            if("4".equals(lastDayworkItem.getStatus())){
                removeItems.add(lastDayworkItem);
            }
            BizDayworkItem item = new BizDayworkItem();
            item.setDayworkId(l.getDayworkId());
            item.setProductionPlanDetailId(lastDayworkItem.getProductionPlanDetailId());
            item.setLotId(l.getLotId());
            item.setProdNum(l.getAuditNum());
            item.setQualifiedNum(l.getAuditNum());
            item.setTechnologicalProcessId(lastDayworkItem.getTechnologicalProcessId());
            item.setTechnologicalProcessDetailId(lastDayworkItem.getTechnologicalProcessDetailId());
            item.setProcessStepNumber(lastDayworkItem.getProcessStepNumber());
            item.setProcessId(lastDayworkItem.getProcessId());
            item.setDeptId(l.getProductionDeptId());
            item.setDeptName(l.getProductionDeptName());
            item.setStatus("4");
            item.setNickName("外协");
            item.setStartTime(new Date());
            item.setTurnoverType("2");
            item.setTurnoverArea("外协周转区");
            addItems.add(item);

            //修改daywork主表数据
            daywork.setProcessQualifiedNum(l.getAuditNum());
            daywork.setTemporaryProcessQualifiedNum(l.getAuditNum());
            daywork.setDeptId(outsourcedOrderDetail.getProductionDeptId());
            updateDaywork.add(daywork);

            if (sysDept.getAutoAllocation() == 1) {
                // 查资源组

                //查询是否已经分配资源组
                BizProductionResourceGroupSubPlan groupSubPlan=new BizProductionResourceGroupSubPlan();
                groupSubPlan.setDeptId(outsourcedOrderDetail.getProductionDeptId());
                groupSubPlan.setProductionPlanDetailId(daywork.getProductionPlanDetailId());

                List<BizProductionResourceGroupSubPlan> groupSubPlanList = bizProductionResourceGroupSubPlanService.getAotList(groupSubPlan);
                //如果没分配
                if(groupSubPlanList.size()==0){
                    //查产品id
                    BizProductionPlanDetail productionPlanDetail = bizProductionPlanDetailService.getOne(new QueryWrapper<BizProductionPlanDetail>().eq("id", item.getProductionPlanDetailId()));
                    for (BizProductionResourceGroup info : productionResourceGroupList) {
                        BizProductionResourceGroupSubPlan subPlan = new BizProductionResourceGroupSubPlan();
                        subPlan.setProductId(productionPlanDetail.getProductId());
                        subPlan.setProductionPlanDetailId(lastDayworkItem.getProductionPlanDetailId());
                        subPlan.setTechnologicalProcessId(outsourcedOrderDetail.getTechnologicalProcessId());
                        subPlan.setResourceGroupId(info.getId());
                        subPlan.setDeptId(outsourcedOrderDetail.getProductionDeptId());
                        subPlan.setResourceGroupCode(info.getCode());
                        subPlanList.add(subPlan);
                    }
                }

            }
        });
        bizOutsourcedOrderDetailService.updateBatchById(batches);
        bizDayworkCarrierService.updateBatchById(returnDayworkCarrierList);
        bizDayworkCarrierService.saveBatch(newDayworkCarrierList);
        bizDayworkItemService.removeBatchByIds(removeItems);
        bizDayworkItemService.saveBatch(addItems);
        bizDayworkService.updateBatchById(updateDaywork);
        bizProductionResourceGroupSubPlanService.saveBatch(subPlanList);
        return success();
    }

    @Log(title = "判断携带箱类型", businessType = BusinessType.SELECT)
    @GetMapping("/checkCarriers")
    public AjaxResult checkCarriers(@RequestParam String carriers) {
        List<String> carrierCodes = Arrays.stream(carriers.split(",")).collect(Collectors.toList());
        List<BizCarrier> carrierList = carrierService.query().in("code", carrierCodes).list();
        List<BizCarrierCategory> categories = carrierCategoryService.query().eq("name", "外协箱").list();
        if (carrierList.stream().anyMatch(t -> categories.stream().anyMatch(e -> t.getCategoryId().equals(e.getId())))) {
            return success(false);
        } else {
            return success(true);
        }

    }
    /**
     * 删除外协单主
带箱方式，是整单的。如果换新箱子，明细中，都需要更换箱子
     */
    @PreAuthorize("@ss.hasPermi('business:returnTurnover:remove')")
    @Log(title = "外协单主带箱方式，是整单的。如果换新箱子，明细中，都需要更换箱子", businessType = BusinessType.DELETE)
    @Transactional
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        bizReturnReceiptService.removeBatchByIds(ids);
        List<BizReturnReceiptDetail> bizReturnReceiptDetailList = bizReturnReceiptDetailService.query().in("master_id", ids).list();
        List<Long> bizReturnReceiptDetailIds = bizReturnReceiptDetailList.stream().map(BizReturnReceiptDetail::getId).collect(Collectors.toList());
        return toAjax(bizReturnReceiptDetailService.removeBatchByIds(bizReturnReceiptDetailIds));
    }
}
