package com.sw.mes.fb.turnstore.service.impl;


import com.alibaba.fastjson.JSON;
import com.sw.mes.base.factory.material.entity.MaterialModel;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.base.global.GlobalSwitch;
import com.sw.mes.base.global.GlobalSwitchNamespace;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.workinprocess.dto.CurrentWipStorageStatusDto;
import com.sw.mes.base.workinprocess.entity.WipStorage;
import com.sw.mes.core.api.system.StoreFeignClients;
import com.sw.mes.core.api.system.YbFeignClients;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.sectionMes.ReturnMaterialFeedBackDto;
import com.sw.mes.core.dto.store.WarehouseInputBillBo;
import com.sw.mes.core.dto.store.WarehouseInputBillDetailBo;
import com.sw.mes.core.dto.wms.RemesstaDto;
import com.sw.mes.core.entity.FbCheckOutData;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.base.factory.init.dto.MesToWmsReceiptDataDto;
import com.sw.mes.base.factory.init.dto.MesToWmsReceiptDto;
import com.sw.mes.fb.checkout.service.FbCheckOutDataService;
import com.sw.mes.fb.checkout.service.FbJoinService;
import com.sw.mes.fb.checkout.service.OperateCheckOutDataLogService;
import com.sw.mes.fb.turnstore.dao.RecheckInspectReceiveDao;
import com.sw.mes.fb.turnstore.entity.FbTurnstoreTray;
import com.sw.mes.fb.turnstore.entity.FbTurnstoreTrayItem;
import com.sw.mes.fb.turnstore.entity.RecheckInspectReceive;
import com.sw.mes.fb.turnstore.entity.RecheckInspectReceiveDetail;
import com.sw.mes.fb.turnstore.service.FbTurnstoreTrayItemService;
import com.sw.mes.fb.turnstore.service.FbTurnstoreTrayService;
import com.sw.mes.fb.turnstore.service.RecheckInspectReceiveDetailService;
import com.sw.mes.fb.turnstore.service.RecheckInspectReceiveService;
import com.sw.mes.base.workinprocess.entity.PlanProcessingOrder;
import com.sw.mes.base.workinprocess.service.PlanProcessingOrderService;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Slf4j
@Service
@Transactional
public class RecheckInspectReceiveServiceImpl extends BaseServiceImpl<RecheckInspectReceive> implements RecheckInspectReceiveService {
    RecheckInspectReceiveDao dao;

    @Autowired
    public void setDao(RecheckInspectReceiveDao dao) {
        super.setBaseDao(dao);
        this.dao = dao;
    }

    @Autowired
    private RecheckInspectReceiveDetailService receiveDetailService;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private FbCheckOutDataService checkOutDataService;

    @Autowired
    private DictionaryItemService dictionaryItemService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;

    @Autowired
    private OperateCheckOutDataLogService operateCheckOutDataLogService;

    @Autowired
    private RecheckInspectReceiveDetailService recheckInspectReceiveDetailService;

    @Autowired
    private FbTurnstoreTrayItemService fbTurnstoreTrayItemService;

    @Autowired
    private FbTurnstoreTrayService fbTurnstoreTrayService;

    @Autowired
    private FbJoinService fbJoinService;

    @Autowired
    private YbFeignClients ybFeignClients;

    @Autowired
    private StoreFeignClients storeFeignClients;

    @Autowired
    private MaterialModelService materialModelService;

    @Autowired
    private FbCheckOutDataService fbCheckOutDataService;

    @Autowired
    @Qualifier(value = "fBMesThreadPoolTaskExecutor")
    private ThreadPoolTaskExecutor fbMesThreadPoolExecutor;

    @Value("${wms.url}")
    private String wmsUrl;

    @Override
    public RecheckInspectReceive findByTrayNo(String trayNo) {
        return dao.findByTrayNo(trayNo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateState(RecheckInspectReceive receive, List<RecheckInspectReceiveDetail> detailDtoList) {
        RecheckInspectReceive recheckInspectReceiveDb = get(receive.getId());
        Assert.notNull(recheckInspectReceiveDb, "退库复检数据不存在");
        Assert.isTrue(recheckInspectReceiveDb.getState() == 0, "此退库复检数据不属于接收或拒绝范围内");
        recheckInspectReceiveDb.setState(receive.getState());
        recheckInspectReceiveDb.setConfirmUser(BaseContextHandler.getUsername());
        recheckInspectReceiveDb.setConfirmTime(new Date());
//        修改主表
        saveOrUpdate(recheckInspectReceiveDb);
        if (CollectionUtils.isEmpty(detailDtoList)) {
            throw new RuntimeException("退货复检明细不能为空");
        }

        if (null == recheckInspectReceiveDb.getSectionMesReturnResult()) {
            List<RemesstaDto> wmsList = buildWms(receive, detailDtoList);
            Result remessta = ybFeignClients.remessta(wmsList);
            if (!remessta.getCode().equals(200)) {
                log.error("调用成品返工车间MES接收状态回传接口失败信息:{}", remessta.getMessage());
                throw new RuntimeException("调用成品返工车间MES接收状态回传接口" + remessta.getMessage());
            }
            wms(receive, detailDtoList);
        } else {
            ArrayList<ReturnMaterialFeedBackDto> returnMaterialFeedBackDtoArrayList = buildSectionMes(receive, detailDtoList, recheckInspectReceiveDb);
            //            通知切片mes
            Result result = ybFeignClients.returnMaterialFeedBack(returnMaterialFeedBackDtoArrayList);
            if (!result.getCode().equals(200)) {
                log.error("调用切片mes退料反馈接口失败信息:{}", result.getMessage());
                throw new RuntimeException("调用切片mes退料反馈接口失败");
            }
            sectionMes(receive, detailDtoList);
        }
//      全部成功之后修改方棒组托明细中的退货复检状态
        if (receive.getState() == 1) {
            for (RecheckInspectReceiveDetail recheckInspectReceiveDetail : detailDtoList) {
                FbTurnstoreTrayItem fbTurnstoreTrayItemDb = fbTurnstoreTrayItemService.findBySectionNo3(recheckInspectReceiveDetail.getCrystalNo());
                if (Objects.nonNull(fbTurnstoreTrayItemDb)) {
                    fbTurnstoreTrayItemDb.setReturnInspectionStatus(1);
                    fbTurnstoreTrayItemService.saveOrUpdate(fbTurnstoreTrayItemDb);
                }
            }
        }
    }

    private void sectionMes(RecheckInspectReceive receive, List<RecheckInspectReceiveDetail> detailDtoList) {
        if (receive.getState() != 1) {
            return;
        }
//        WarehouseInputBillBo warehouseInputBillBo = new WarehouseInputBillBo();
//        warehouseInputBillBo.setCreateUserName(BaseContextHandler.getUsername());
//        warehouseInputBillBo.setCreateUserId(BaseContextHandler.getUserID());
//        warehouseInputBillBo.setType("切片退货入库");
//        warehouseInputBillBo.setAutomaticOut(false);
//        warehouseInputBillBo.setAutoAudit(true);
//        ArrayList<WarehouseInputBillDetailBo> warehouseInputBillDetailBoArrayList = new ArrayList<>();
//
//        for (RecheckInspectReceiveDetail recheckInspectReceiveDetail : detailDtoList) {
//            WarehouseInputBillDetailBo bo = new WarehouseInputBillDetailBo();
//            FbTurnstoreTrayItem fbTurnstoreTrayItem = fbTurnstoreTrayItemService.findBySectionNo1(recheckInspectReceiveDetail.getCrystalNo());
//            if (Objects.nonNull(fbTurnstoreTrayItem)) {
//                MaterialModel materialModel = materialModelService.findByCode(fbTurnstoreTrayItem.getMaterialNumber());
//                if (Objects.nonNull(materialModel)) {
//                    bo.setMaterialModelId(Long.valueOf
//                            (materialModel.getId()));
//                    bo.setMaterialModelCode(materialModel.getCode());
//                    bo.setMaterialModelName(materialModel.getName());
//                    bo.setMaterialTypeName(materialModel.getMaterialType().getName());
//                    bo.setSpecification(materialModel.getSpecification());
//                    bo.setMaterialTh(materialModel.getNumberOfDrawings());
//                    bo.setUnitName(materialModel.getUnit().getName());
//                    bo.setCount(fbTurnstoreTrayItem.getTheoryWeightFb());
//                    bo.setSupplier("太原晶科");
//                    bo.setSupplierCode("TYJK");
//                    bo.setWarehouseCode("P32A");
//                    bo.setBatchNo(recheckInspectReceiveDetail.getBatchNo());
//                    bo.setCrystalNo(recheckInspectReceiveDetail.getCrystalNo());
//                    warehouseInputBillDetailBoArrayList.add(bo);
//                }
//            }
//        }
//        warehouseInputBillBo.setInputBillDetails(warehouseInputBillDetailBoArrayList);
//        Result<String> storeResult = storeFeignClients.inputApply(warehouseInputBillBo);
//        if (storeResult.getCode() != ResultCode.SUCCESS.getCode()) {
//            log.error("切片MES线边仓入库调拨失败:{}", storeResult.getMessage());
//            throw new RuntimeException("切片MES线边仓入库调拨失败！异常为：" + storeResult.getMessage());
//        }
        for (RecheckInspectReceiveDetail detail : detailDtoList) {
            //                   确认接收之后，重新修改工单表状态为加工中
            PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCode(detail.getCrystalNo());
            if (null == planProcessingOrder) {
                throw new BusinessException(detail.getCrystalNo() + "工单号不存在");
            }
            planProcessingOrder.setStatus(EnumValuesFactory.PlanProcessingOrderStatus.加工中.getKey());
            planProcessingOrderService.saveOrUpdate(planProcessingOrder);

            Result<CurrentWipStorageStatusDto> currentWipStorageStatusDtoResult = wipStorageService.selectWipStorageResult(detail.getCrystalNo());
            if (currentWipStorageStatusDtoResult.getCode() != ResultCode.SUCCESS.getCode()) {
                throw new BusinessException("查询站点信息失败");
            }
            if (currentWipStorageStatusDtoResult.getData() == null) {
                throw new BusinessException("站点信息为空");
            }
            CurrentWipStorageStatusDto currentWipStorageStatusDto = currentWipStorageStatusDtoResult.getData();
            if (!(currentWipStorageStatusDto.getWipStorageCode().equals(EnumValuesFactory.WipStorageCode.方棒检验.getKey())
                    && currentWipStorageStatusDto.getWipStorageStatus() == EnumValuesFactory.WipStorageStatus.已进站.getKey())) {
                wipStorageService.exitStation(detail.getCrystalNo());
            }
            WipStorage wipStorage = wipStorageService.findWipStorageByProcessingOrderCode(detail.getCrystalNo());
            if (Objects.nonNull(wipStorage)) {
                wipStorage.setStatus(0);
                wipStorageService.saveOrUpdate(wipStorage);
            }
        }
    }

    private void wms(RecheckInspectReceive receive, List<RecheckInspectReceiveDetail> detailDtoList) {
        if (receive.getState() == 1) {
            WarehouseInputBillBo warehouseInputBillBo = new WarehouseInputBillBo();
            warehouseInputBillBo.setCreateUserName(BaseContextHandler.getUsername());
            warehouseInputBillBo.setCreateUserId(BaseContextHandler.getUserID());
            warehouseInputBillBo.setType("WMS退货入库");
            warehouseInputBillBo.setAutomaticOut(false);
            warehouseInputBillBo.setAutoAudit(true);
            ArrayList<WarehouseInputBillDetailBo> warehouseInputBillDetailBoArrayList = new ArrayList<>();

            for (RecheckInspectReceiveDetail recheckInspectReceiveDetail : detailDtoList) {
                WarehouseInputBillDetailBo bo = new WarehouseInputBillDetailBo();
                MaterialModel materialModel = materialModelService.findByCode(recheckInspectReceiveDetail.getMaterialNumber());
                if (Objects.nonNull(materialModel)) {
                    bo.setMaterialModelId(Long.valueOf(materialModel.getId()));
                    bo.setMaterialModelCode(materialModel.getCode());
                    bo.setMaterialModelName(materialModel.getName());
                    bo.setMaterialTypeName(materialModel.getMaterialType().getName());
                    bo.setSpecification(materialModel.getSpecification());
                    bo.setMaterialTh(materialModel.getNumberOfDrawings());
                    bo.setUnitName(materialModel.getUnit().getName());
                    bo.setCount(recheckInspectReceiveDetail.getWeight());
                    bo.setSupplier("太原晶科");
                    bo.setSupplierCode("TYJK");
                    bo.setWarehouseCode("P32A");
                    bo.setBatchNo(recheckInspectReceiveDetail.getBatchNo());
                    bo.setCrystalNo(recheckInspectReceiveDetail.getCrystalNo());
                    warehouseInputBillDetailBoArrayList.add(bo);
                }
            }
            warehouseInputBillBo.setInputBillDetails(warehouseInputBillDetailBoArrayList);
            Result<String> result = storeFeignClients.inputApply(warehouseInputBillBo);
            if (result.getCode() != ResultCode.SUCCESS.getCode()) {
                log.error("WMS线边仓入库调拨失败:{}", result.getMessage());
                throw new RuntimeException("WMS线边仓入库调拨失败！异常为：" + result.getMessage());
            }
            for (RecheckInspectReceiveDetail detail : detailDtoList) {
                //                   确认接收之后，重新修改工单表状态为加工中
                PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCode(detail.getCrystalNo());
                if (null == planProcessingOrder) {
                    throw new BusinessException(detail.getCrystalNo() + "工单号不存在");
                }
                planProcessingOrder.setStatus(EnumValuesFactory.PlanProcessingOrderStatus.加工中.getKey());
                planProcessingOrderService.saveOrUpdate(planProcessingOrder);

                Result<CurrentWipStorageStatusDto> currentWipStorageStatusDtoResult = wipStorageService.selectWipStorageResult(detail.getCrystalNo());
                if (currentWipStorageStatusDtoResult.getCode() != ResultCode.SUCCESS.getCode()) {
                    throw new BusinessException("查询站点信息失败");
                }
                if (currentWipStorageStatusDtoResult.getData() == null) {
                    throw new BusinessException("站点信息为空");
                }
                CurrentWipStorageStatusDto currentWipStorageStatusDto = currentWipStorageStatusDtoResult.getData();
                if (!(currentWipStorageStatusDto.getWipStorageCode().equals(EnumValuesFactory.WipStorageCode.方棒检验.getKey())
                        && currentWipStorageStatusDto.getWipStorageStatus() == EnumValuesFactory.WipStorageStatus.已进站.getKey())) {
                    wipStorageService.exitStation(detail.getCrystalNo());
                }
                WipStorage wipStorage = wipStorageService.findWipStorageByProcessingOrderCode(detail.getCrystalNo());
                if (Objects.nonNull(wipStorage)) {
                    wipStorage.setStatus(0);
                    wipStorageService.saveOrUpdate(wipStorage);
                }
            }
        }
    }

    private List<RemesstaDto> buildWms(RecheckInspectReceive receive, List<RecheckInspectReceiveDetail> detailDtoList) {
        //        wms退库复检集合
        ArrayList<RemesstaDto> wmsList = new ArrayList<>();
        //       更新退货复检明细表信息
        for (RecheckInspectReceiveDetail detail : detailDtoList) {
            FbTurnstoreTrayItem turnstoreTrayItemDb = fbTurnstoreTrayItemService.findBySectionNo1(detail.getCrystalNo());
            Assert.notNull(turnstoreTrayItemDb, "该方棒编号" + detail.getCrystalNo() + "在方棒组托明细中不存在");
            detail.setState(receive.getState());
            detail.setConfirmUser(BaseContextHandler.getUsername());
            detail.setConfirmTime(new Date());
//            wms参数封装
            receiveDetailService.saveOrUpdate(detail);
            RemesstaDto remesstaDto = new RemesstaDto();
            remesstaDto.setOrganizationid("JINKO");
            remesstaDto.setWarehouseid("5041");
            remesstaDto.setCustomerid("5041");
            remesstaDto.setDocno(receive.getOutOrderNo());
            remesstaDto.setAufn(receive.getOutOrderNo());
            remesstaDto.setTraceid(detail.getTrayNo());
            remesstaDto.setSerialno(detail.getCrystalNo());
            remesstaDto.setSku(detail.getMaterialNumber());
            remesstaDto.setLotatt04(detail.getBatchNo());

            if (receive.getState() == 1) {
                remesstaDto.setBillresult("S");
            } else if (receive.getState() == 2) {
                remesstaDto.setBillresult("C");
            }
            wmsList.add(remesstaDto);
        }

        return wmsList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>
                (Comparator.comparing(RemesstaDto::getSku)
                        .thenComparing(RemesstaDto::getLotatt04)
                        .thenComparing(RemesstaDto::getTraceid))), ArrayList::new));
    }

    private ArrayList<ReturnMaterialFeedBackDto> buildSectionMes(RecheckInspectReceive receive, List<RecheckInspectReceiveDetail> detailDtoList, RecheckInspectReceive recheckInspectReceiveDb) {
        //        切片mes退库复检集合
        ArrayList<ReturnMaterialFeedBackDto> returnMaterialFeedBackDtoArrayList = new ArrayList<>();
        detailDtoList.forEach(recheckInspectReceiveDetail -> {
            recheckInspectReceiveDetail.setState(receive.getState());
            recheckInspectReceiveDetail.setConfirmUser(BaseContextHandler.getUsername());
            recheckInspectReceiveDetail.setConfirmTime(new Date());
            receiveDetailService.saveOrUpdate(recheckInspectReceiveDetail);
            //            通知切片mes参数封装
            ReturnMaterialFeedBackDto dto = new ReturnMaterialFeedBackDto();
            dto.setSiliconRodNo(recheckInspectReceiveDetail.getCrystalNo());
            dto.setTrayId(recheckInspectReceiveDetail.getTrayNo());
            dto.setSectionMesReturnResult(recheckInspectReceiveDb.getSectionMesReturnResult());
            if (recheckInspectReceiveDetail.getState() == 1) {
                dto.setState("S");
            } else if (recheckInspectReceiveDetail.getState() == 2) {
                dto.setState("C");
            }
            returnMaterialFeedBackDtoArrayList.add(dto);

        });
        return returnMaterialFeedBackDtoArrayList;
    }

    @Override
    public Result mesToWmsReceipt(String outOrderNo, Integer state) {
        MesToWmsReceiptDto mesToWmsReceiptDto = new MesToWmsReceiptDto();
        MesToWmsReceiptDataDto mesToWmsReceiptDataDto = new MesToWmsReceiptDataDto();
        mesToWmsReceiptDataDto.setOrderNum(outOrderNo);
        mesToWmsReceiptDataDto.setIsReceive("S");
        if (2 == state) {
            mesToWmsReceiptDataDto.setIsReceive("E");
        }
        //调用接口
        String jsonString = JSON.toJSONString(mesToWmsReceiptDataDto);
        mesToWmsReceiptDto.setZDATA(jsonString);
        String content = JSON.toJSONString(mesToWmsReceiptDto);
        String url = wmsUrl + "api/YC6MES/otherinteraction";
        String send = send(content, url);
        if (null != send && send.contains("\"ztype\":\"E\"")) {
            return ResultGenerator.fail(send);
        }
        return ResultGenerator.success();
    }

    @Override
    public void audit(Integer id, Integer state) {
        RecheckInspectReceive recheckInspectReceiveDb = get(id);
        Assert.notNull(recheckInspectReceiveDb, "退库复检数据不存在");
        Assert.isTrue(recheckInspectReceiveDb.getState() == 0, "此退库复检数据不属于接收或拒绝范围内");
        recheckInspectReceiveDb.setState(state);
//        修改主表
        saveOrUpdate(recheckInspectReceiveDb);
//        修改明细表
        List<RecheckInspectReceiveDetail> recheckInspectReceiveDetailList = receiveDetailService.findByRecheckReceiveId(id);
//        切片mes退库复检集合
        ArrayList<ReturnMaterialFeedBackDto> returnMaterialFeedBackDtoArrayList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(recheckInspectReceiveDetailList)) {
            recheckInspectReceiveDetailList.forEach(recheckInspectReceiveDetail -> {
                recheckInspectReceiveDetail.setState(state);
                receiveDetailService.saveOrUpdate(recheckInspectReceiveDetail);
                //            通知切片mes
                ReturnMaterialFeedBackDto dto = new ReturnMaterialFeedBackDto();
                dto.setSiliconRodNo(recheckInspectReceiveDetail.getCrystalNo());
                dto.setTrayId(recheckInspectReceiveDetail.getTrayNo());
                dto.setSectionMesReturnResult(recheckInspectReceiveDb.getSectionMesReturnResult());
                if (state == 1) {
                    dto.setState("S");
                } else if (state == 2) {
                    dto.setState("C");
                }
                returnMaterialFeedBackDtoArrayList.add(dto);
            });
        }

        if (null == recheckInspectReceiveDb.getSectionMesReturnResult()) {
            //        通知wms
            ArrayList<RemesstaDto> list = new ArrayList<>();
            RemesstaDto dto = new RemesstaDto();
            dto.setOrganizationid("JINKO");
            dto.setWarehouseid("5041");
            dto.setCustomerid("5041");
            dto.setDocno(recheckInspectReceiveDb.getOutOrderNo());
            dto.setAufn(recheckInspectReceiveDb.getId().toString());
            dto.setTraceid(recheckInspectReceiveDb.getTrayNo());
            dto.setSerialno(recheckInspectReceiveDb.getTrayNo());
            if (state == 1) {
                dto.setBillresult("S");
            } else if (state == 2) {
                dto.setBillresult("C");
            }
            list.add(dto);
            ybFeignClients.remessta(list);
        } else {
            ybFeignClients.returnMaterialFeedBack(returnMaterialFeedBackDtoArrayList);
        }
    }

    @Override
    public void sectionMesReturnInspection(RecheckInspectReceive receive, List<RecheckInspectReceiveDetail> detailList) {
        ArrayList<RecheckInspectReceiveDetail> recheckInspectReceiveDetailList = new ArrayList<>();
        if (CollectionUtils.isEmpty(detailList) || Objects.isNull(receive)) {
            throw new RuntimeException("退货复检或者退货复检明细不能为空");
        }

        RecheckInspectReceive recheckInspectReceiveDb = dao.findByTrayNo(receive.getTrayNo());
        if (Objects.nonNull(recheckInspectReceiveDb)) {
            throw new RuntimeException("该托号" + receive.getTrayNo() + "在退库复检表已经存在请检查数据");
        }
        for (RecheckInspectReceiveDetail detail : detailList) {
            if (!receive.getTrayNo().equals(detail.getTrayNo())) {
                throw new RuntimeException("主表托号" + receive.getTrayNo() + "与明细表托号" + detail.getTrayNo() + "不一致，请检查数据");
            }
        }
        receive.setTrayNo(receive.getTrayNo());
        receive.setState(0);
        receive.setSapWorkOrder(receive.getOutOrderNo());
        receive.setSource("切片mes");
        receive.setApplyTime(new Date());
        receive.setCustomer("切片mes");
        receive.setUser("切片mes");
        receive.setSectionMesReturnResult(receive.getSectionMesReturnResult());
        for (RecheckInspectReceiveDetail receiveDetail : detailList) {
            String[] split = receiveDetail.getCrystalNo().split(",");
            for (String section : split) {
                RecheckInspectReceiveDetail detail = new RecheckInspectReceiveDetail();
                FbTurnstoreTrayItem turnstoreTrayItemDb = fbTurnstoreTrayItemService.findBySectionNo1(section);
                Assert.notNull(turnstoreTrayItemDb, "该方棒编号" + receiveDetail.getCrystalNo() + "在方棒组托明细中不存在");
                MaterialModel materialModel = materialModelService.findByCode(turnstoreTrayItemDb.getMaterialNumber());
                detail.setRecheckReceiveId(receive.getId());
                detail.setState(0);
                detail.setTrayNo(receiveDetail.getTrayNo());
                detail.setCrystalNo(section);
                detail.setFbProductLevel(turnstoreTrayItemDb.getProductLevelFb());
                detail.setSpecs(turnstoreTrayItemDb.getSpecification());
                detail.setLength(turnstoreTrayItemDb.getLength());
                detail.setTheoryWeight(turnstoreTrayItemDb.getTheoryWeightFb());
                detail.setWeight(turnstoreTrayItemDb.getTheoryWeightFb());
                detail.setConductiveType(turnstoreTrayItemDb.getConductionType());
                detail.setCollapseLoss(turnstoreTrayItemDb.getCollapseLoss());
                detail.setLengthSlope(turnstoreTrayItemDb.getLengthSlope());
                detail.setCrystalGrayness(turnstoreTrayItemDb.getCrystalGrayness());
                detail.setLineScratch(turnstoreTrayItemDb.getLineScratch());
                detail.setScratch(turnstoreTrayItemDb.getScratch());
                detail.setNoFriction(turnstoreTrayItemDb.getNoFriction());
                detail.setSizeException(turnstoreTrayItemDb.getSizeException());
                detail.setSquareRodRemark(turnstoreTrayItemDb.getSquareRodRemark());
                detail.setSquareRodRemark(turnstoreTrayItemDb.getSquareRodRemark());
                detail.setCheckoutName("退货复检");
                detail.setHasGone(turnstoreTrayItemDb.getHasGone());
                detail.setSpecification(turnstoreTrayItemDb.getSpecification());
                detail.setCheckTime(turnstoreTrayItemDb.getCheckTime());
                detail.setProductLevel(turnstoreTrayItemDb.getProductLevel());
                if (Objects.nonNull(materialModel)) {
                    detail.setDopant(materialModel.getDopant());
                    detail.setMaterialNumber(materialModel.getCode());
                    receive.setProductCode(materialModel.getCode());
                }
                recheckInspectReceiveDetailList.add(detail);
            }
        }
//              保存主表
        receive.setCrystalNum(recheckInspectReceiveDetailList.size());
        saveOrUpdate(receive);
//        把检验类型更新到方棒组托数据库中
        for (RecheckInspectReceiveDetail detail : recheckInspectReceiveDetailList) {
            detail.setRecheckReceiveId(receive.getId());
            FbCheckOutData fbCheckOutDataDb = fbCheckOutDataService.findDataByFbSectionNo(detail.getCrystalNo());
            if (Objects.nonNull(fbCheckOutDataDb)) {
                fbCheckOutDataDb.setReturnSource("切片MES");
                fbCheckOutDataDb.setCheckoutName("退货复检");
                fbCheckOutDataService.saveOrUpdate(fbCheckOutDataDb);
            }
        }
//                    保存明细表
        receiveDetailService.saveAll(recheckInspectReceiveDetailList);
    }

    @Override
    public void wmsReturnInspection(RecheckInspectReceive recheckInspectReceive, List<RecheckInspectReceiveDetail> detailList) {
        if (CollectionUtils.isEmpty(detailList) || Objects.isNull(recheckInspectReceive)) {
            throw new RuntimeException("退货复检或者退货复检明细不能为空");
        }
//            退货复检主表集合
        ArrayList<RecheckInspectReceive> recheckInspectReceiveArrayList = new ArrayList<>();
        for (RecheckInspectReceiveDetail detail : detailList) {
            FbTurnstoreTrayItem turnstoreTrayItemDb = fbTurnstoreTrayItemService.findBySectionNo1(detail.getCrystalNo());
            Assert.notNull(turnstoreTrayItemDb, "该晶编号" + detail.getCrystalNo() + "未查询到方棒组托信息");
            RecheckInspectReceive receive = new RecheckInspectReceive();
            //退货复检主表参数封装
            receive.setState(0);
            receive.setTrayNo(detail.getTrayNo());
            receive.setCustomer("wms");
            receive.setUser("wms");
            receive.setProductCode(detail.getMaterialNumber());
            receive.setOutOrderNo(recheckInspectReceive.getOutOrderNo());
            receive.setSource(recheckInspectReceive.getSource());
            receive.setSapWorkOrder(detail.getSapWorkOrder());
            recheckInspectReceiveArrayList.add(receive);
//                退货复检明细参数封装
//                查询物料主数据
            MaterialModel materialModel = materialModelService.findByCode(turnstoreTrayItemDb.getMaterialNumber());
            detail.setState(0);
            detail.setCrystalNo(turnstoreTrayItemDb.getSectionNo());
            detail.setFbProductLevel(turnstoreTrayItemDb.getProductLevelFb());
            detail.setSpecs(turnstoreTrayItemDb.getSpecification());
            detail.setLength(turnstoreTrayItemDb.getLength());
            detail.setTheoryWeight(turnstoreTrayItemDb.getTheoryWeightFb());
            detail.setConductiveType(turnstoreTrayItemDb.getConductionType());
            detail.setCollapseLoss(turnstoreTrayItemDb.getCollapseLoss());
            detail.setLengthSlope(turnstoreTrayItemDb.getLengthSlope());
            detail.setCrystalGrayness(turnstoreTrayItemDb.getCrystalGrayness());
            detail.setLineScratch(turnstoreTrayItemDb.getLineScratch());
            detail.setScratch(turnstoreTrayItemDb.getScratch());
            detail.setNoFriction(turnstoreTrayItemDb.getNoFriction());
            detail.setSizeException(turnstoreTrayItemDb.getSizeException());
            detail.setSquareRodRemark(turnstoreTrayItemDb.getSquareRodRemark());
            detail.setSquareRodRemark(turnstoreTrayItemDb.getSquareRodRemark());
            detail.setCheckoutName("退货复检");
            detail.setHasGone(turnstoreTrayItemDb.getHasGone());
            detail.setSpecification(turnstoreTrayItemDb.getSpecification());
            detail.setCheckTime(turnstoreTrayItemDb.getCheckTime());
            detail.setProductLevel(turnstoreTrayItemDb.getProductLevel());
            if (Objects.nonNull(materialModel)) {
                detail.setDopant(materialModel.getDopant());
                detail.setMaterialNumber(materialModel.getCode());
            }
        }
//        退货复检主表根据托号进行分组
        Map<String, List<RecheckInspectReceive>> recheckInspectReceiveMap = recheckInspectReceiveArrayList.stream().collect(Collectors.groupingBy(RecheckInspectReceive::getTrayNo));

//        退货复检明细主表根据托号进行分组
        Map<String, List<RecheckInspectReceiveDetail>> listMap = detailList.stream().collect(Collectors.groupingBy(RecheckInspectReceiveDetail::getTrayNo));

        for (Map.Entry<String, List<RecheckInspectReceiveDetail>> entry : listMap.entrySet()) {
            String trayNo = entry.getKey();
            List<RecheckInspectReceiveDetail> recheckInspectReceiveDetailList = entry.getValue();
            //            查询该托号数据库是否已经存在
            RecheckInspectReceive recheckInspectReceiveDb = dao.findByTrayNo(trayNo);
            if (Objects.nonNull(recheckInspectReceiveDb)) {
                throw new RuntimeException("该托号" + trayNo + "在退库复检表已经存在请检查数据");
            }
            List<RecheckInspectReceive> recheckInspectReceiveList = recheckInspectReceiveMap.get(trayNo);
            RecheckInspectReceive receive = recheckInspectReceiveList.get(0);
            receive.setApplyTime(new Date());

            receive.setCrystalNum(recheckInspectReceiveDetailList.size());

            this.saveOrUpdate(receive);

//            退货复检明细参数补充
            for (RecheckInspectReceiveDetail detail : recheckInspectReceiveDetailList) {
                detail.setRecheckReceiveId(receive.getId());
                //                更新方棒检验数据库的检验类型为退货复检
                FbCheckOutData fbCheckOutDataDb = fbCheckOutDataService.findDataByFbSectionNo(detail.getCrystalNo());
                if (Objects.nonNull(fbCheckOutDataDb)) {
                    fbCheckOutDataDb.setReturnSource("综计WMS");
                    fbCheckOutDataDb.setCheckoutName("退货复检");
                    fbCheckOutDataService.saveOrUpdate(fbCheckOutDataDb);
                }
            }
            //                    保存退货复检明细表
            receiveDetailService.saveAll(recheckInspectReceiveDetailList);
        }
    }

    private String send(String data, String url) {
        HttpHeaders headers = new HttpHeaders();
        MediaType mediaType = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(mediaType);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> httpEntity = new HttpEntity<>(data, headers);
        //使用exchange请求接口
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return exchange.getBody();
    }

}
