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


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sw.mes.base.erp.entity.ErpOrder;
import com.sw.mes.base.erp.entity.ReportSapRecord;
import com.sw.mes.base.erp.service.ErpOrderService;
import com.sw.mes.base.erp.service.ReportSapRecordService;
import com.sw.mes.base.factory.init.entity.CrystalMaterialRelation;
import com.sw.mes.base.factory.init.entity.Equipment;
import com.sw.mes.base.factory.init.service.CrystalMaterialRelationService;
import com.sw.mes.base.factory.init.service.EquipmentService;
import com.sw.mes.base.factory.inspect.dto.ProductRuleDto;
import com.sw.mes.base.factory.inspect.dto.ProductRuleValidateDto;
import com.sw.mes.base.factory.inspect.entity.ProductAssemblyRule;
import com.sw.mes.base.factory.inspect.entity.SquareSpellRule;
import com.sw.mes.base.factory.inspect.service.LevelCodeMaintenanceService;
import com.sw.mes.base.factory.inspect.service.ProductAssemblyRuleService;
import com.sw.mes.base.factory.inspect.service.SquareSpellRuleService;
import com.sw.mes.base.factory.material.entity.MaterialModel;
import com.sw.mes.base.factory.material.entity.MaterialModelExtra;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.base.global.GlobalSwitch;
import com.sw.mes.base.global.SwitchConfig;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.entity.SysLog;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.system.service.SysLogService;
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 com.sw.mes.core.api.system.StoreFeignClients;
import com.sw.mes.core.api.system.YbFeignClients;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.*;
import com.sw.mes.core.dto.erp.ErpAddResultDto;
import com.sw.mes.core.dto.erp.ErpRequestDto;
import com.sw.mes.core.dto.mes.pc.yb.YbInspectDataDto;
import com.sw.mes.core.dto.sectionMes.FbInformationReceptionDto;
import com.sw.mes.core.dto.store.WarehouseOutputBillBo;
import com.sw.mes.core.dto.store.WarehouseOutputBillDetailBo;
import com.sw.mes.core.dto.wms.MesasnDto;
import com.sw.mes.core.dto.wms.MesasnOrderDto;
import com.sw.mes.core.entity.FbCheckOutData;
import com.sw.mes.core.entity.MesToErpCcpEntity;
import com.sw.mes.core.entity.TurnstoreTrayItem;
import com.sw.mes.core.enums.EnumValues;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.enums.ErpPypeEnum;
import com.sw.mes.core.enums.SectionIndexRangeEnum;
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.core.utils.*;
import com.sw.mes.fb.checkout.dao.FbCheckOutDataDao;
import com.sw.mes.fb.checkout.service.FbCheckOutDataService;
import com.sw.mes.fb.turnstore.dao.FbTurnstoreTrayDao;
import com.sw.mes.fb.turnstore.dto.*;
import com.sw.mes.fb.turnstore.dto.UpdateStateByTrayIdDto;
import com.sw.mes.fb.turnstore.dto.vo.FbTurnstoreTrayItemVo;
import com.sw.mes.fb.turnstore.entity.FbTurnstoreTray;
import com.sw.mes.fb.turnstore.entity.FbTurnstoreTrayItem;
import com.sw.mes.fb.turnstore.service.FbTurnstoreTrayItemService;
import com.sw.mes.fb.turnstore.service.FbTurnstoreTrayService;
import com.sw.mes.fb.turnstore.service.RawMaterialReceivingService;
import com.sw.mes.plan.entity.FbProductionOrder;
import com.sw.mes.plan.service.FbProductionOrderService;
import com.sw.mes.rabbitmq.service.RabbitMqService;
import com.sw.mes.sap.SapServer;
import com.sw.mes.third.utils.ErpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.sw.mes.base.global.GlobalSwitchNamespace.CODE_SWITCH;
import static com.sw.mes.base.global.GlobalSwitchNamespace.NAMESPACE_FB_CHECK;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Slf4j
@Service
@Transactional
public class FbTurnstoreTrayServiceImpl extends BaseServiceImpl<FbTurnstoreTray> implements FbTurnstoreTrayService {
    FbTurnstoreTrayDao dao;

    @Value("${spring.profiles.active}")
    private String active;

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

    @Autowired
    private DictionaryItemService dictionaryItemService;

    @Autowired
    private FbTurnstoreTrayItemService fbTurnstoreTrayItemService;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private FbCheckOutDataService checkOutService;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private RawMaterialReceivingService receivingService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;

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

    @Autowired
    private FbProductionOrderService productionOrderService;

    @Autowired
    private SapServer sapServer;

    @Autowired
    private RabbitMqService rabbitMqService;
    @Autowired
    private SquareSpellRuleService squareSpellRuleService;
    @Autowired
    private ProductAssemblyRuleService productAssemblyRuleService;
    @Autowired
    private FbCheckOutDataService fbCheckOutDataService;
    @Autowired
    private YbFeignClients ybFeignClients;

    @Autowired
    private ErpRequestUtil erpRequestUtil;
    @Value("${spring.erpServiceUrl}")
    private String erpServiceUrl;
    @Autowired
    private ErpOrderService erpOrderService;
    @Autowired
    private MaterialModelService materialModelService;
    @Autowired
    private FbCheckOutDataDao checkOutDao;

    @Autowired
    private LevelCodeMaintenanceService levelCodeMaintenanceService;

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private CrystalMaterialRelationService crystalMaterialRelationService;

    @Autowired
    private ReportSapRecordService reportSapRecordService;

    @Autowired
    private EquipmentService equipmentService;

    @Override
    public Result<FbInfoDto> getInfoByFbSectionNo(String fbSectionNo) {
        FbInfoDto fbInfoDto = new FbInfoDto();
        fbInfoDto.setFbSectionNo(fbSectionNo);
        //方棒检验数据
        FbCheckOutData dataByFbSectionNo = fbCheckOutDataService.findDataByFbSectionNo(fbSectionNo);
        if (null == dataByFbSectionNo) {
            return ResultGenerator.fail("方棒检验数据为空！");
        }
        if (null == dataByFbSectionNo.getYbSectionNo() || StringUtils.isEmpty(dataByFbSectionNo.getYbSectionNo())) {
            return ResultGenerator.fail("方棒检验数据中圆棒编号为空，无法获取圆棒相关信息");
        }

        //根据圆棒编号获取圆棒检验信息
        Result<YbInspectDataDto> inspectDataBaseBySectionNo = ybFeignClients.getInspectDataBaseBySectionNo(dataByFbSectionNo.getYbSectionNo());
        if (inspectDataBaseBySectionNo.getCode() == ResultCode.SUCCESS.getCode()) {
            if (null != inspectDataBaseBySectionNo.getData()) {
                YbInspectDataDto data = inspectDataBaseBySectionNo.getData();
                fbInfoDto.setYbSectionNo(dataByFbSectionNo.getYbSectionNo());
                fbInfoDto.setDopant(data.getDopant());
                fbInfoDto.setProductTypeSecond(data.getProductTypeSecond());
                fbInfoDto.setOxygenContentHead(data.getOxygenContentHead());
                fbInfoDto.setOxygenContentTail(data.getOxygenContentTail());
                fbInfoDto.setCarbonContentHead(data.getCarbonContentHead());
                fbInfoDto.setCarbonContentTail(data.getCarbonContentTail());
                fbInfoDto.setWCentreLife(data.getWCentreLife());
                fbInfoDto.setTCentreLife(data.getTCentreLife());
                fbInfoDto.setProductType(data.getProductType());
                fbInfoDto.setClosureIdentification(data.getClosureIdentification());
                fbInfoDto.setProductLevel(data.getProductLevel());
                if (null == dataByFbSectionNo.getCrystalNo() || StringUtils.isEmpty(dataByFbSectionNo.getCrystalNo())) {
                    fbInfoDto.setCrystalNo(data.getCrystalNo());
                    Result<YbInspectDataDto> inspectDatasByCrystalNo = ybFeignClients.getInspectDatasByCrystalNo(data.getCrystalNo());
                    if (inspectDatasByCrystalNo.getCode() == ResultCode.SUCCESS.getCode()) {
                        if (null != inspectDatasByCrystalNo.getData()) {
                            fbInfoDto.setWYCentreLife(inspectDatasByCrystalNo.getData().getWCentreLife());
                        }
                    }
                }
            }
        }
        return ResultGenerator.success(fbInfoDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createTray(ProductAssemblyRule productRule, FbTurnstoreTray fbTurnstoreTray, List<FbTurnstoreTrayItem> items) {
        //生成托号
        createTrayNoTYNew(fbTurnstoreTray, items.get(0), productRule);
        //保存主表
        fbTurnstoreTray.setUser(BaseContextHandler.getUsername());
        Integer tornieNum = productRule.getTornieNum();
        Date date = new Date();
        if (tornieNum == items.size()) {
            fbTurnstoreTray.setReportingTime(date);
        }
        fbTurnstoreTray.setTime(date);
        fbTurnstoreTray.setOperationTime(date);
        if (null == fbTurnstoreTray.getBorderWidth()) {
            fbTurnstoreTray.setBorderWidth("0");
        }
        //fixme 状态设置为待出库状态
        fbTurnstoreTray.setState(0);

        //处理计算不一致时，强行改为明细总数
        if (items.size() != fbTurnstoreTray.getCount()) {
            fbTurnstoreTray.setCount(items.size());
        }
        if (null != productRule.getDirectOrOutgoing()) {
            fbTurnstoreTray.setDirectOrOutgoing(productRule.getDirectOrOutgoing());
        }
        FbTurnstoreTray turnstoreTray = dao.save(fbTurnstoreTray);
        //保存明细字段
        saveItemList(turnstoreTray, items);
        //上报SAP
        SwitchConfig config = GlobalSwitch.switchConfig(CODE_SWITCH, "createTurnStorage", false);
        if (config.isEnable()) {
            pushSap(items);
        }
    }

    @Override
    public void fbWriteOffAccounts(List<FbTurnstoreTrayItem> items) {
        List<PushSapDto> list = new ArrayList<>();
        PushSapAndStoreDto pushSapAndStoreDto = new PushSapAndStoreDto();
        List<WarehouseOutputBillDetailBo> warehouseOutputBillDetailBoList = new ArrayList<>();
        WarehouseOutputBillBo warehouseOutputBillBo = new WarehouseOutputBillBo();
        warehouseOutputBillBo.setType("方棒返切冲销出库");
        warehouseOutputBillBo.setAutoAudit(true);
        for (FbTurnstoreTrayItem item : items) {
            PushSapDto pushSapDto = new PushSapDto();
            FbCheckOutData dataByFbSectionNo = fbCheckOutDataService.findDataByFbSectionNo(item.getSectionNo());
            if (null == dataByFbSectionNo) {
                throw new RuntimeException("未查询到方棒检验数据");
            }
            if (null == dataByFbSectionNo.getOrderNo() || null == dataByFbSectionNo.getMaterialCode()) {
                throw new RuntimeException("方棒：" + item.getSectionNo() + "订单号或物料号为空！");
            }
            //先判断是否上报过，上报过则先冲销
            String fbSectionNo = item.getSectionNo();
            String bwart;
            String backBwart;
            if(null != dataByFbSectionNo.getReplaceCharacter()){
                bwart = "531";
                backBwart = "532";
            } else {
                bwart = "101";
                backBwart = "102";
            }
            ReportSapRecord reportSapRecordWeight = reportSapRecordService.findByFbSectionNoAndBwartAndProcNameAndPushTypeAndTrayNo(fbSectionNo, bwart, "刀剖收货", "报工", item.getTrayNo());
            if (null != reportSapRecordWeight) {

                pushSapDto.setYbSectionNo(dataByFbSectionNo.getYbSectionNo());
                pushSapDto.setWeight(new BigDecimal(0).subtract(reportSapRecordWeight.getCount()));
                pushSapDto.setUserName(BaseContextHandler.getUsername());
                pushSapDto.setFbSectionNo(fbSectionNo);
                pushSapDto.setBwart(backBwart);
                pushSapDto.setBatchNo(reportSapRecordWeight.getBatcnNo());

                pushSapDto.setFbOrderNo(dataByFbSectionNo.getOrderNo());
                pushSapDto.setFbMatnr(dataByFbSectionNo.getMaterialCode());

                list.add(pushSapDto);


                Integer versionId = reportSapRecordWeight.getVersionId();
                String warehouseCode = null;
                CrystalMaterialRelation crystalMaterialRelation = crystalMaterialRelationService.findBySectionNo(dataByFbSectionNo.getYbSectionNo());
                if (null != crystalMaterialRelation) {
                    Equipment byCode = equipmentService.findByCode(crystalMaterialRelation.getDeviceNo());
                    if (null != byCode) {
                        DictionaryItem warehouseLocation = dictionaryItemService.findByThemeValueAndNameAndValueAndEnable("WarehouseLocation", byCode.getArea(), byCode.getSeries(), true);
                        if (null != warehouseLocation) {
                            warehouseCode = warehouseLocation.getExtendValue1();
                        }
                    }
                    BigDecimal bigDecimal = reportSapRecordWeight.getCount();
                    //保存冲销记录
                    saveReportSapRecordDataByReportSapRecord(reportSapRecordWeight, "冲销", backBwart, bigDecimal, versionId + 1, item);
                    WarehouseOutputBillDetailBo warehouseOutputBillDetailBo = new WarehouseOutputBillDetailBo();
                    warehouseOutputBillDetailBo.setBatchNo(reportSapRecordWeight.getBatcnNo());
                    warehouseOutputBillDetailBo.setMaterialModelCode(reportSapRecordWeight.getMaterialCode());
                    warehouseOutputBillDetailBo.setWarehouseCode(warehouseCode);
                    warehouseOutputBillDetailBo.setRequireCount(bigDecimal);
                    warehouseOutputBillDetailBo.setOutputCount(bigDecimal);
                    warehouseOutputBillDetailBo.setCrystalNo(fbSectionNo);
                    warehouseOutputBillDetailBoList.add(warehouseOutputBillDetailBo);
                }
            }
        }

        pushSapAndStoreDto.setPushSapDtoList(list);
        pushSapAndStoreDto.setWarehouseOutputBillBo(warehouseOutputBillBo);
        //sap冲销
        warehouseOutputBillBo.setOutputBillDetails(warehouseOutputBillDetailBoList);
        if (null != pushSapAndStoreDto) {
            Result result = ybFeignClients.sendSquareWriteOffAccounts(pushSapAndStoreDto);
            log.info("方棒上报SAP数据(冲销)结果为:{}", JSONObject.toJSONString(result));
            if (ResultCode.SUCCESS.getCode() != result.getCode()) {
                throw new RuntimeException("SAP产出上报(冲销)失败，异常信息为：" + result.getMessage());
            }
        }
    }


    @Override
    public void pushSap(List<FbTurnstoreTrayItem> items) {
        //上报SAP
        List<PushSapDto> list = new ArrayList<>();
        Integer versionId = 0;
        ReportSapRecord byFbSectionNo = reportSapRecordService.findByFbTrayNo(items.get(0).getTrayNo());
        if (null != byFbSectionNo) {
            versionId = byFbSectionNo.getVersionId();
        }
        for (FbTurnstoreTrayItem item : items) {
            FbCheckOutData dataByFbSectionNo1 = fbCheckOutDataService.findDataByFbSectionNo(item.getSectionNo());
            if (null == dataByFbSectionNo1 || null == dataByFbSectionNo1.getOrderNo() || null == dataByFbSectionNo1.getMaterialCode()) {
                throw new RuntimeException("方棒检验数据缺失(订单、料号)：" + item.getSectionNo());
            }
            PushSapDto pushSapDto = new PushSapDto();
            pushSapDto.setBatchNo(item.getBatchNo());
            String bwart;
            if(!StringUtils.isEmpty(dataByFbSectionNo1.getReplaceCharacter())){
                bwart = "531";
            } else {
                bwart = "101";
            }
            pushSapDto.setBwart(bwart);
            pushSapDto.setFbSectionNo(item.getSectionNo());
            pushSapDto.setUserName(BaseContextHandler.getUsername());

            pushSapDto.setFbOrderNo(dataByFbSectionNo1.getOrderNo());
            pushSapDto.setFbMatnr(dataByFbSectionNo1.getMaterialCode());

            BigDecimal pushCount = new BigDecimal(0);
            if (null != item.getActualWeightFb() && item.getActualWeightFb().compareTo(new BigDecimal(0)) > 0) {
                pushCount = item.getActualWeightFb();
            } else if (null != item.getTheoryWeightFb() && item.getTheoryWeightFb().compareTo(new BigDecimal(0)) > 0) {
                pushCount = item.getTheoryWeightFb();
            }
            pushSapDto.setWeight(pushCount);

            //保存上报记录
            saveReportSapRecordDataByFbTurnstoreTrayItem(item, "报工", bwart, pushCount, versionId + 1);
            FbCheckOutData dataByFbSectionNo = fbCheckOutDataService.findDataByFbSectionNo(item.getSectionNo());
            pushSapDto.setYbSectionNo(dataByFbSectionNo.getYbSectionNo());
            list.add(pushSapDto);
        }

//        try {
        Result result = ybFeignClients.sendSquareRodInfoList(list);
        if (ResultCode.SUCCESS.getCode() != result.getCode()) {
            throw new RuntimeException("SAP产出上报失败，异常信息为：" + result.getMessage());
        }
//        } catch (Exception e) {
//            e.printStackTrace();
//            SysLog syslog = new SysLog();
//            syslog.setCreateTime(new Date());
//            syslog.setType("error");
//            syslog.setCreateUserName("SYSTEM");
//            syslog.setContent(JSON.toJSONString(list));
//            syslog.setResult(e.getMessage());
//            syslog.setName("方棒组托上报SAP");
//            syslog.setMethodName("sendSquareRodInfo()");
//            syslog.setServerAddr("");
//            syslog.setReqType("HTTP");
//            syslog.setReqIp(IpUtils.getLocalIP());
//            sysLogService.save(syslog);
//        }
    }

    @Override
    public FbTurnstoreTrayItem findBySectionNo(String sectionNo) {
        return dao.findBySectionNo(sectionNo);
    }

    @Override
    public FbTurnstoreTrayItemVo validateRule(String sectionNo , boolean isComposeSection) {
        FbTurnstoreTrayItemVo fbTurnstoreTrayItemVo = new FbTurnstoreTrayItemVo();
        ArrayList<FbTurnstoreTrayItem> fbTurnstoreTrayItemList = new ArrayList<>();
        //查询晶段信息
        FbCheckOutData checkOut = checkOutService.findDataByFbSectionNo(sectionNo);
        if (null == checkOut || StringUtils.isBlank(checkOut.getYbLevel())) {
            throw new RuntimeException("当前晶段【" + sectionNo + "】信息不存在或晶段暂未评级!");
        }
        if (StringUtils.isBlank(checkOut.getMaterialCode())) {
            throw new RuntimeException("当前晶段【" + sectionNo + "】信息缺失物料号, 请在方棒评级测试，是否为“正常”，氧含量是否合格!");
        }
        //晶棒重复扫描卡控
        FbTurnstoreTrayItem bySectionNo = fbTurnstoreTrayItemService.findBySectionNo3(sectionNo);
        if (null != bySectionNo && bySectionNo.getReturnInspectionStatus() != 1) {
            throw new RuntimeException("当前晶段【" + sectionNo + "】已经执行过组托！请勿重复组托!");
        }
        ProductAssemblyRule productAssemblyRule = productAssemblyRuleService.findBySpecAndLevelCodeAndProductLevelFbAndLengthAndDirectOrOutgoing(checkOut.getSpecification(),checkOut.getLevelCode(),checkOut.getProductLevelFb(),checkOut.getLength(),0);
        if (null == productAssemblyRule) {
            throw new RuntimeException("组托规则为空!");
        }
        if (!StringUtils.equals(checkOut.getProductLevelFb(), productAssemblyRule.getProductGrade())) {
            if (StringUtils.isEmpty(checkOut.getProductLevelFb()) && "N1".equals(productAssemblyRule.getProductGrade())) {
                //组拖产品等级：N1，当前产品等级： 无
                throw new RuntimeException("单晶【" + sectionNo + "】T氧值为空，请检查样片是否已检验！");
            }
            throw new RuntimeException("单晶【" + sectionNo + "】检验产品等级与规则不一致!");
        }
        //卡控晶棒长度，目前暂时先卡控非拼棒的情况
        String length = productAssemblyRule.getLength();
        if (!StringUtils.isEmpty(length) && length.contains("-")) {
            BigDecimal shortest = new BigDecimal(length.split("-")[0]);
            BigDecimal longest = new BigDecimal(length.split("-")[1]);
            if (null != checkOut.getInstoreLengthFb() && !isComposeSection) {
                if (shortest.compareTo(checkOut.getInstoreLengthFb()) > 0) {
                    throw new RuntimeException("单晶【" + sectionNo + "】长度小于组托规则限制，最小值：" + shortest.doubleValue());
                }
                if (checkOut.getInstoreLengthFb().compareTo(longest) > 0) {
                    throw new RuntimeException("单晶【" + sectionNo + "】长度大于组托规则限制，最大值：" + longest.doubleValue());
                }
            }
        }

        FbTurnstoreTrayItem fbTurnstoreTrayItem = modelMapper.map(checkOut, FbTurnstoreTrayItem.class);
        if (StringUtils.isBlank(fbTurnstoreTrayItem.getSectionNo())) {
            fbTurnstoreTrayItem.setSectionNo(checkOut.getFbSectionNo());
        }
        if (BigDecimal.ZERO.compareTo(checkOut.getTheoryWeightFb()) >= 0) {
            throw new RuntimeException("理论重量不能小于等于0");
        }
        fbTurnstoreTrayItem.setTheoryWeightFb(checkOut.getTheoryWeightFb());
        fbTurnstoreTrayItem.setTCentreLife(checkOut.getTCarrierLifetime());
        fbTurnstoreTrayItem.setTRadialCentre(checkOut.getTResistivity());
        fbTurnstoreTrayItem.setWCentreLife(checkOut.getWCarrierLifetime());
        fbTurnstoreTrayItem.setWRadialCentre(checkOut.getWResistivity());
        fbTurnstoreTrayItem.setOxygenContentHead(checkOut.getTOxygenContent());
        fbTurnstoreTrayItem.setCarbonContentTail(checkOut.getWCarbonContent());
        fbTurnstoreTrayItem.setMaterialNumber(checkOut.getMaterialCode());
        //调整为方棒评级
        fbTurnstoreTrayItem.setProductLevel(checkOut.getProductLevelFb());
        fbTurnstoreTrayItem.setHasGone("切片MES");
        fbTurnstoreTrayItem.setId(null);
        fbTurnstoreTrayItemList.add(fbTurnstoreTrayItem);

        fbTurnstoreTrayItemVo.setFactoryName("5041");
        fbTurnstoreTrayItemVo.setRuleId(productAssemblyRule.getId());
        fbTurnstoreTrayItemVo.setProductLevelSecond(productAssemblyRule.getProductGrade());
        fbTurnstoreTrayItemVo.setLevelCode(productAssemblyRule.getLevelCode());
        fbTurnstoreTrayItemVo.setSpecs(productAssemblyRule.getSpecs());
        fbTurnstoreTrayItemVo.setHasGone("切片MES");
        fbTurnstoreTrayItemVo.setCount(fbTurnstoreTrayItemList.size());
        fbTurnstoreTrayItemVo.setDirectOrOutgoing(0);
        fbTurnstoreTrayItemVo.setTrayItems(fbTurnstoreTrayItemList);
        return fbTurnstoreTrayItemVo;
    }

    @Override
    public void updateSectionMesTrayItemStateBySectionNo(String state, String sectionNo) {
        FbTurnstoreTrayItem fbTurnstoreTrayItem = dao.findBySectionNo(sectionNo);
        Assert.notNull(fbTurnstoreTrayItem, "该方棒组托明细中的晶编号不存在");
        if ("S".equals(state)) {
            //确认接收
            fbTurnstoreTrayItem.setState(1);
        } else if ("C".equals(state)) {
            //拒收
            fbTurnstoreTrayItem.setState(3);
        }
        fbTurnstoreTrayItemService.saveOrUpdate(fbTurnstoreTrayItem);
    }


    public void saveReportSapRecordDataByReportSapRecord(ReportSapRecord reportSapRecord1, String pushType, String bwart, BigDecimal weight, Integer versionId, FbTurnstoreTrayItem item) {

        ReportSapRecord reportSapRecord = new ReportSapRecord();
        reportSapRecord.setBatcnNo(reportSapRecord1.getBatcnNo());
        reportSapRecord.setBwart(bwart);
        reportSapRecord.setCount(weight);
        reportSapRecord.setSectionNo(reportSapRecord1.getSectionNo());
        reportSapRecord.setMaterialCode(reportSapRecord1.getMaterialCode());
        reportSapRecord.setOrderNo(reportSapRecord1.getOrderNo());
        reportSapRecord.setProcName("刀剖收货");
        reportSapRecord.setPushTime(new Date());
        reportSapRecord.setPushType(pushType);
        reportSapRecord.setUnit("KG");
        reportSapRecord.setUser(BaseContextHandler.getUsername());
        reportSapRecord.setVersionId(versionId);
        reportSapRecord.setTrayNo(item.getTrayNo());
        reportSapRecordService.saveOrUpdate(reportSapRecord);
    }

    public void saveReportSapRecordDataByFbTurnstoreTrayItem(FbTurnstoreTrayItem item, String pushType, String bwart, BigDecimal weight, Integer versionId) {

        ReportSapRecord reportSapRecord = new ReportSapRecord();
        reportSapRecord.setBatcnNo(item.getBatchNo());
        reportSapRecord.setBwart(bwart);
        reportSapRecord.setCount(weight);
        reportSapRecord.setSectionNo(item.getSectionNo());
        reportSapRecord.setMaterialCode(item.getMaterialNumber());
        reportSapRecord.setOrderNo(item.getOrderNo());
        reportSapRecord.setProcName("刀剖收货");
        reportSapRecord.setPushTime(new Date());
        reportSapRecord.setPushType(pushType);
        reportSapRecord.setUnit("KG");
        reportSapRecord.setUser(BaseContextHandler.getUsername());
        reportSapRecord.setVersionId(versionId);
        reportSapRecord.setTrayNo(item.getTrayNo());
        reportSapRecordService.saveOrUpdate(reportSapRecord);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTray(FbTurnstoreTray turnstoreTray, List<FbTurnstoreTrayItem> items) {
        if (items.size() != turnstoreTray.getCount()) {
            turnstoreTray.setCount(items.size());
        }
        //判断去向及是否满拖状态
        saveOrUpdate(turnstoreTray);
        //SET明细字段
        saveItemList(turnstoreTray, items);
    }

    @Override
    public Result lengthCheck(ProductRuleDto ruleDto) {
        ProductAssemblyRule ruleByStation = productAssemblyRuleService.findRuleByStation(ruleDto.getStation());
        if (null == ruleByStation) {
            return ResultGenerator.fail("该成品组托规则不存在");
        }
        String length = ruleByStation.getLength();
        if (length.equals("无限制")) {
            return ResultGenerator.success();
        }
        String[] str1 = length.split("-");
        List<String> list = Arrays.asList(str1);

        FbCheckOutData dataByFbSectionNo = fbCheckOutDataService.findDataByFbSectionNo(ruleDto.getSectionNo());
        BigDecimal actualLength = new BigDecimal(0);
        String sectionCompose = dataByFbSectionNo.getSectionCompose();
        if (null == sectionCompose) {
            actualLength = dataByFbSectionNo.getLength();
        } else {
            String[] split = sectionCompose.split(",");
            List<String> list1 = Arrays.asList(split);
            List<FbCheckOutData> checkOutList = checkOutDao.findCheckOutDataByFbSectionNoIns(list1);
            if (checkOutList == null || checkOutList.size() == 0) {
                return ResultGenerator.fail("错误,根据单晶编号获取方棒检验信息失败");
            }
            //计算拼棒总长
            actualLength = checkOutList.stream().map(e -> e.getLength() == null ? new BigDecimal(0) :
                    e.getLength()).reduce(BigDecimal.ZERO, BigDecimal::add);
        }
        if (null == actualLength) {
            return ResultGenerator.fail(dataByFbSectionNo.getFbSectionNo() + "晶段长度为空");
        }
        if (actualLength.floatValue() >= Integer.parseInt(list.get(0)) && actualLength.floatValue() <= Integer.parseInt(list.get(1))) {
            return ResultGenerator.success();
        }

        return ResultGenerator.fail(dataByFbSectionNo.getFbSectionNo() + "晶段长度为" + actualLength.toString() + "不符合长度范围" + length);
    }

    @Override
    public String validateRules(ProductRuleDto ruleDto, FbCheckOutData checkOut) {
        String hun = "混类别";
        String sectionNo = checkOut.getFbSectionNo();
        //判断规格是否符合
        if (null != ruleDto.getSpecs() && !"".equals(ruleDto.getSpecs())) {

            if (null == checkOut.getSpecification() || !ruleDto.getSpecs().contains(checkOut.getSpecification())) {
                return sectionNo + "晶段的规格不符合规则，只能为：" + ruleDto.getSpecs();
            }
        }
        //判断导电型号是否符合
        if (null != ruleDto.getConductiveType() && !"".equals(ruleDto.getConductiveType())) {
            if (null == checkOut.getConductionType() || !ruleDto.getConductiveType().contains(checkOut.getConductionType())) {
                return sectionNo + "晶段的导电型号不符合规则，只能为：" + ruleDto.getConductiveType();
            }
        }
        //判断产品类别是否符合
        if (null != ruleDto.getProductType() && !"".equals(ruleDto.getProductType())) {
            if (null == checkOut.getProductType()) {
                return sectionNo + "晶段的产品类别不符合规则，只能为：" + ruleDto.getProductType();
            }
            String productType = ruleDto.getProductType();
            String[] split = productType.split(",");
            int count = 0;
            for (String s : split) {
                if (s.equals(checkOut.getProductType())) {
                    count++;
                }
            }
            if (count == 0) {
                return sectionNo + "晶段的产品类别不符合规则，只能为：" + ruleDto.getProductType();
            }
        }
        //判断产品等级是否符合
        if (null != ruleDto.getProductGrade() && !"".equals(ruleDto.getProductGrade()) && !hun.equals(ruleDto.getProductGrade())) {
            if (null == checkOut.getYbLevel() || !ruleDto.getProductGrade().contains(checkOut.getYbLevel())) {
                return sectionNo + "晶段的产品等级不符合规则，只能为：" + ruleDto.getProductGrade();
            }
        }


        //判断入库类别是否符合
        if (null != ruleDto.getInputType() && !"".equals(ruleDto.getInputType())) {
            if (null == checkOut.getProductLevelFb() || !ruleDto.getInputType().contains(checkOut.getProductLevelFb())) {
                return sectionNo + "晶段的入库类别不符合规则，只能为：" + ruleDto.getInputType();
            }
        }
        //判断边长KEY是否符合
        if (null != ruleDto.getSideLengthRange() && !"".equals(ruleDto.getSideLengthRange())) {
            if (null != checkOut.getSideLengthRange() && !"".equals(checkOut.getSideLengthRange()) && !ruleDto.getSideLengthRange().equals(checkOut.getSideLengthRange())) {

                return sectionNo + "晶段的边长不符合规则，只能为：" + ruleDto.getSideLengthRange();
            }
        }
        //判断长度范围是否符合
       /* if (null != ruleDto.getLength() && !"".equals(ruleDto.getLength()) && !"非标".equals(ruleDto.getLength())) {
            String length = ruleDto.getLength();
            String lengthType = "不区分棒长";
            if (!lengthType.equals(length) && null != checkOut.getLength()) {
                boolean flag = false;
                String[] lengths = length.split(",");
                for (String s : lengths) {
                    String[] split = s.split("-");
                    if (split.length != 2) {
                        return sectionNo + "晶段的长度范围规则不正确:" + length;
                    }
                    double minLength = Double.parseDouble(split[0]);
                    double maxLength = Double.parseDouble(split[1]);
                    double actualLength;
                    if (null != checkOut.getSpellBarLength()) {
                        actualLength = checkOut.getSpellBarLength().doubleValue();
                    } else {
                        actualLength = checkOut.getLength().doubleValue();
                    }
                    if (minLength <= actualLength && actualLength <= maxLength) {
                        flag = true;
                    }
                }
                if (!flag) {
                    return sectionNo + "晶段的长度范围不符合规则，只能为：" + ruleDto.getLength();
                }
            }
        }*/
        return "符合";
    }

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

    @Override
    public Map<String, FbTurnstoreTray> findByTrayNoList(List<String> trayNoList) {
        List<FbTurnstoreTray> list = dao.findByTrayNoList(trayNoList);
        if (CollectionUtils.isNotEmpty(list)) {
            Map<String, FbTurnstoreTray> map = new HashMap<>();
            for (FbTurnstoreTray tray : list) {
                map.put(tray.getTrayNo(), tray);
            }
            return map;
        }
        return new HashMap<>();
    }

    @Override
    public List<FbTurnstoreTray> findByTime(String startTime, String endTime) {
        return dao.findByTime(startTime, endTime);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateItem(FbTurnstoreTray turnstoreTray, List<FbTurnstoreTrayItem> turnstoreTrayItemList) {
        for (FbTurnstoreTrayItem trayItem : turnstoreTrayItemList) {
            trayItem.setState(turnstoreTray.getState());
            trayItem.setOperationTime(turnstoreTray.getOperationTime());
            trayItem.setUser(turnstoreTray.getUser());
            trayItem.setIsToWms(turnstoreTray.getIsToWms());
            trayItem.setToWmsTime(turnstoreTray.getToWmsTime());
            //更新站点信息
            if ("方棒返修".equals(turnstoreTray.getHasGone())) {
                wipStorageService.outStation(trayItem.getSectionNo(), "D", null);
            } else if ("粘方棒".equals(turnstoreTray.getHasGone())) {
                wipStorageService.outStation(trayItem.getSectionNo(), "C", null);
            } else if ("综计WMS".equals(turnstoreTray.getHasGone()) || "综计返修".equals(turnstoreTray.getHasGone())) {
                //同步站点信息---WMS综计待进站
                wipStorageService.outStation(trayItem.getSectionNo(), "A", null);
            }
            fbTurnstoreTrayItemService.saveOrUpdate(trayItem);
        }
    }

    @Override
    public FbTurnstoreTray getFbTray(String trayNo) {
        FbTurnstoreTray byTrayNo = dao.findByTrayNo(trayNo);
        if (null != byTrayNo) {
            return byTrayNo;
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result initiateReceipt(FbTurnstoreTray turnstoreTray, List<FbTurnstoreTrayItem> turnstoreTrayItemList) {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date currentTime = new Date();
        String currentTimeString = formatter.format(currentTime);
        long warehouseEntryNumber = System.currentTimeMillis();
        FbTurnstoreTrayItem fbTurnstoreTrayItem = turnstoreTrayItemList.get(0);
        //处理外层
        FbCheckOutData dataByFbSectionNo = fbCheckOutDataService.findDataByFbSectionNo(fbTurnstoreTrayItem.getSectionNo());
        if (null == dataByFbSectionNo) {
            throw new RuntimeException("该托号不存在方棒检验明细！");
        }
        List<MesasnDto> mesasnDtoList = new ArrayList<>();
        MesasnDto dto = new MesasnDto();
        dto.setOrganizationid("JINKO");
        dto.setWarehouseid("5041");
        dto.setCustomerid("5041");
        dto.setDocno(String.valueOf(warehouseEntryNumber));//入库单号
        dto.setAsntype("CLCPRK");//入库类型
        dto.setAsnstatus("00");//订单状态
        dto.setAsnreferencea(turnstoreTray.getId().toString());
        dto.setAsnreferenceb("5041");//车间编号
        dto.setAsnreferencec("P32B");//线边库存地
        dto.setAsncreationtime(currentTimeString);//MES创建时间
        dto.setTraceid(turnstoreTray.getTrayNo());//托盘号
        dto.setSerialno(turnstoreTray.getTrayNo());//箱号
        dto.setSku(dataByFbSectionNo.getMaterialCode());//物料编码
        dto.setLotatt01(currentTimeString);//生产日期
        String batchNo = dataByFbSectionNo.getBatchNo();
        if (StringUtils.isNotBlank(batchNo) && batchNo.startsWith("TCN") && batchNo.length() >= 10) {
            batchNo = batchNo.substring(0, 1) + "J" + batchNo.substring(2, 10);
        }
        dto.setLotatt04(batchNo);//入库批次
        dto.setLotatt08("N");//质量状态
        dto.setLotatt09("5041");//厂家
        dto.setLotatt10("5041");//供应商
        dto.setLotatt12(batchNo);//生产批次
        dto.setLotatt19(null != dataByFbSectionNo.getMeanResistivityA() ? dataByFbSectionNo.getMeanResistivityA().toString() : "");//电阻率
        dto.setLotatt20(dataByFbSectionNo.getProductLevel());//等级
        dto.setCreatesource("MES");//创建来源
        ArrayList<MesasnOrderDto> orderList = new ArrayList<>();
        BigDecimal totalWeight = new BigDecimal(0);
        for (FbTurnstoreTrayItem fbTurnstoreTrayItem1 : turnstoreTrayItemList) {
            FbCheckOutData dataByFbSectionNoNew = fbCheckOutDataService.findDataByFbSectionNo(fbTurnstoreTrayItem1.getSectionNo());
            if (null == dataByFbSectionNoNew) {
                throw new RuntimeException("该托号不存在方棒检验明细！");
            }
            MesasnOrderDto mesasnOrderDto = new MesasnOrderDto();
            mesasnOrderDto.setSku(dataByFbSectionNoNew.getMaterialCode());//物料编码
            mesasnOrderDto.setTraceid(turnstoreTray.getTrayNo());//托号
            mesasnOrderDto.setSerialno(fbTurnstoreTrayItem1.getSectionNo());//箱号
            mesasnOrderDto.setExpectedqty(dataByFbSectionNoNew.getTheoryWeightFb().setScale(3, RoundingMode.HALF_UP).toString());
            //计算总重量
            totalWeight = totalWeight.add(dataByFbSectionNoNew.getTheoryWeightFb());
            mesasnOrderDto.setLotatt01(currentTimeString);//生产日期
            mesasnOrderDto.setLotatt03(currentTimeString);//生产日期
            String batchNoNew = dataByFbSectionNoNew.getBatchNo();
            if (StringUtils.isNotBlank(batchNoNew) && batchNoNew.startsWith("TCN") && batchNoNew.length() >= 10) {
                batchNoNew = batchNoNew.substring(0, 1) + "J" + batchNoNew.substring(2, 10);
            }
            mesasnOrderDto.setLotatt04(batchNoNew);//入库批次
            mesasnOrderDto.setLotatt05("5041");//质量状态
            mesasnOrderDto.setLotatt08("N");//质量状态
            mesasnOrderDto.setLotatt09("5041");//厂家
            mesasnOrderDto.setLotatt12(batchNoNew);//生产批次
            // fixme: 直接塞电阻率
            mesasnOrderDto.setLotatt19(dataByFbSectionNoNew.getMeanResistivityA().toString());
            mesasnOrderDto.setLotatt20(dataByFbSectionNoNew.getProductLevel());//等级
            mesasnOrderDto.setDedi06(dataByFbSectionNoNew.getTheoryWeightFb().setScale(3, RoundingMode.HALF_UP).toString());//晶棒重量
            mesasnOrderDto.setDedi07(dataByFbSectionNoNew.getInstoreLengthFb().setScale(0, RoundingMode.HALF_UP).toString());//方棒长度 fixme改成有效长度
            mesasnOrderDto.setDedi08(batchNoNew);//MES下线批
            mesasnOrderDto.setDedi09(dataByFbSectionNoNew.getTheoryWeightFb().setScale(3, RoundingMode.HALF_UP).toString());
            orderList.add(mesasnOrderDto);
        }
        dto.setExpectedqty(String.valueOf(totalWeight.setScale(3, RoundingMode.HALF_UP)));//总重量
        dto.setOrderList(orderList);
        mesasnDtoList.add(dto);
        log.info("====:{}", JSONObject.toJSONString(mesasnDtoList));
        Result mesasn = ybFeignClients.mesasn(mesasnDtoList);
        if (!mesasn.getCode().equals(200)) {
            return ResultGenerator.fail("调用成品MES入库接口失败");
        }
        //fixme 如果报成功了，状态变更为待入库
        turnstoreTray.setState(2);
        turnstoreTray.setConfirmTime(new Date());
        turnstoreTray.setConfirmUser(BaseContextHandler.getUsername());
        turnstoreTray.setWarehouseEntryNumber(String.valueOf(warehouseEntryNumber));
        saveOrUpdate(turnstoreTray);
        //更新明细
        if (null != turnstoreTrayItemList && turnstoreTrayItemList.size() > 0) {
            turnstoreTrayItemList.forEach(turnstoreTrayItem -> {
                turnstoreTrayItem.setState(turnstoreTray.getState());
                turnstoreTrayItem.setToWmsTime(new Date());
                fbTurnstoreTrayItemService.saveOrUpdate(turnstoreTrayItem);
            });
        }
        return ResultGenerator.success();
    }

    @Override
    public void updateTurnstoreTrayStateById(WmsToFbReceiveDto receiveDto, FbTurnstoreTray turnstoreTray) {
        try {
            //更新主表
            saveOrUpdate(turnstoreTray);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Result reportedErp(FbTurnstoreTray turnstoreTray, List<FbTurnstoreTrayItem> turnstoreTrayItemList) {

        Date date = new Date();
        boolean flag = false;
        FbProductionOrder fbProductionOrder = null;
        double sumWeight = 0D;
        double sumLength = 0D;
        String productType = "";
        for (FbTurnstoreTrayItem fbTurnstoreTrayItem : turnstoreTrayItemList) {
            // 上报成功修改ERP上报状态
            fbTurnstoreTrayItem.setReportedState(EnumValues.ReportedErp.已上报.getKey());
            /**
             * 物料名称、物料编码、工单编号、领用数量、仓库编码、领用类别、领料部门、ERP入库批次号、领用状态、上报时间
             */

            if (!flag) {
                fbProductionOrder = productionOrderService.findByAufnr(fbTurnstoreTrayItem.getOrderNo());
                flag = true;
            }
//            sumWeight += fbTurnstoreTrayItem.getWeight().doubleValue();
            sumLength += fbTurnstoreTrayItem.getLength().doubleValue();
            productType = fbTurnstoreTrayItem.getProductType();
        }
        MesToErpCcpEntity mesToErpCcpEntity = new MesToErpCcpEntity();
        // "cwhcode": "315", --仓库编码	从订单，常规：315，研发：316
        mesToErpCcpEntity.setCwhcode("018");
        // "crdcode": "10216", --出库类别/收发类别	常规：10216，研发：10201
        mesToErpCcpEntity.setCrdcode("10206");
        // "cdepcode": "1413", --部门编码	从订单获取
        mesToErpCcpEntity.setCdepcode("1202");
        // "cwhname": "回收原料库", --仓库名称
        mesToErpCcpEntity.setCwhname("开方产成品库（三期）");
        // "cdepname": "开方五车间",--部门名称	从订单获取
        mesToErpCcpEntity.setCdepname("开方一车间");
        if (null != fbProductionOrder) {
            // "iproorderid": "1000009317", --生产订单id	从订单获取
            mesToErpCcpEntity.setIproorderid(fbProductionOrder.getTid());
            // "cinvcode": "100100180103", --材料编码	从订单获取
            mesToErpCcpEntity.setCinvcode(fbProductionOrder.getMatnr());
            // "cmpocode": "2308011408-12吋(BNE01A1)(正泰045)", --订单号     合并汇总用的订单：erpOrderNo
            mesToErpCcpEntity.setCmpocode(fbProductionOrder.getAufnr());

            List<MaterialModel> materialModelByCode = materialModelService.findMaterialModelByCode(fbProductionOrder.getMatnr());
            if (!materialModelByCode.isEmpty()) {
                MaterialModel materialModel = materialModelByCode.get(0);
                // 材料名称  产成品使用母建，回收料使用子健 新增  cinvname
                mesToErpCcpEntity.setCinvname(materialModel.getName());
                //  单位 产成品使用母建，回收料使用子健 新增   cinvm_unit
                mesToErpCcpEntity.setCinvm_unit(materialModel.getUnit().getCode());
            }
            List<ErpOrder> byModIdAndInvCode1 = erpOrderService.findByModIdAndInvCode1(fbProductionOrder.getModid(), fbProductionOrder.getAufnr());
            if (!byModIdAndInvCode1.isEmpty()) {
                ErpOrder erpOrder = byModIdAndInvCode1.get(0);
                // 生产订单行号,目前填写1 产成品使用母建，回收料使用子健 新增  imoseq
                mesToErpCcpEntity.setImoseq(NumberUtil.object2String(erpOrder.getImoseq(), null));
                // 子建行号,目前填写1 产成品使用母建，回收料使用子健 新增    irowno
                mesToErpCcpEntity.setIrowno(NumberUtil.object2String(erpOrder.getIrowno(), null));
            }
            // 规格型号 产成品使用母建，回收料使用子健 新增 cinsted
//            mesToErpCcpEntity.setCinsted(fbProductionOrder.get);

            // 应入库数量，取订单数量 产成品使用母建，回收料使用子健 新增 inquantity todo 不确定
            mesToErpCcpEntity.setInquantity(NumberUtil.object2String(fbProductionOrder.getMenge(), null));

            // 入库记录ID 先不进行填写进行调试 产成品使用母建，回收料使用子健 新增 impoids todo
//            mesToErpCcpEntity.setImpoids();

            // 是否关联副产品 先不进行填写进行调试 产成品使用母建，回收料使用子健 新增    brelated
//            mesToErpCcpEntity.setBrelated();

            // 生产订单号 产成品使用母建，回收料使用子健 新增     cmocode
            mesToErpCcpEntity.setCmocode(fbProductionOrder.getAufnr());


        }
        // "cbatch": "(2)2023-8-16/129BP(A)正泰045", --批号
        mesToErpCcpEntity.setCbatch(turnstoreTray.getTrayNo());
        // "iquantity": "1.0000000000", --数量	同种订单产品合并汇总后的数量
        String borderWidthKey = turnstoreTray.getBorderWidthKey();
        List<DictionaryItem> multipleSideLogicItems = dictionaryItemService.findByThemeValueAndEnable("multipleSideLogic", true);
        Double v = null;
        if (!multipleSideLogicItems.isEmpty() && sumLength > 0) {
            for (DictionaryItem dictionaryItem : multipleSideLogicItems) {
                String name = dictionaryItem.getName();
                String extendValue2 = dictionaryItem.getExtendValue2();
                // 通过方棒边长和产品类别确定方棒折重系数
                if (name.equalsIgnoreCase(borderWidthKey) &&
                        !org.apache.commons.lang3.StringUtils.isEmpty(extendValue2) &&
                        extendValue2.contains(productType)) {
                    String[] split = extendValue2.split(",");
                    if (split.length > 0) {
                        for (int i = 0; i < split.length; i++) {
                            if (split[i].equalsIgnoreCase(productType)) {
                                v = MathUtils.keepDecimalDigits(sumLength / Double.parseDouble(dictionaryItem.getValue()));
                                break;
                            }
                        }
                    }
                    if (null != v) {
                        break;
                    }
                }
            }
        } else {
            return ResultGenerator.fail("数据字典中没有找到方棒系数");
        }
//                mesToErpCcpEntity.setIquantity(String.valueOf(sunWeight));
        if (null != v) {
            mesToErpCcpEntity.setIquantity(String.valueOf(v));
        } else {
            return ResultGenerator.fail("上报数据中，没有匹配到方棒系数");
        }
        // 备注
        mesToErpCcpEntity.setCmemo(turnstoreTray.getStation());
        mesToErpCcpEntity.setErpType(ErpPypeEnum.方棒产出.getKey());
        mesToErpCcpEntity.setDocTime(turnstoreTray.getToWmsTime());
        ErpRequestDto erpRequestDto = new ErpRequestDto();
        erpRequestDto.setMesToErpCcpEntity(mesToErpCcpEntity);
        erpRequestDto.setUrl(erpServiceUrl);
        ErpAddResultDto erpAddResultDto = erpRequestUtil.postToErp(erpRequestDto);
        if (null == erpAddResultDto || !erpAddResultDto.getErrcode().equals(String.valueOf(ResultCode.SUCCESS.getCode()))) {
            throw new RuntimeException("方棒产出上报失败：" + JSONObject.toJSONString(erpAddResultDto.getErrmsg()));
        }
        turnstoreTray.setReportedState(EnumValues.ReportedErp.已上报.getKey());
        // 回写ERP订单
        for (FbTurnstoreTrayItem trayItem : turnstoreTrayItemList) {
            trayItem.setErpOrder(erpAddResultDto.getCcode());
            trayItem.setErpTime(date);
        }
        fbTurnstoreTrayItemService.saveAll(turnstoreTrayItemList);
        turnstoreTray.setErpOrder(erpAddResultDto.getCcode());
        turnstoreTray.setErpTime(date);
        saveOrUpdate(turnstoreTray);

        return ResultGenerator.success();
    }

    @Override
    public Result validateRuleNew(ProductRuleValidateDto ruleDto, boolean isComposeSection) {
        if (null == ruleDto.getRuleId()) {
            return ResultGenerator.fail("组托规则未选择！");
        }
        if (StringUtils.isBlank(ruleDto.getSectionNo())) {
            return ResultGenerator.fail("单晶传入为空！");
        }
        String sectionNo = ruleDto.getSectionNo();
        //查询晶段信息
        FbCheckOutData checkOut = checkOutService.findDataByFbSectionNo(sectionNo);
        if (null == checkOut || StringUtils.isBlank(checkOut.getYbLevel())) {
            return ResultGenerator.fail("当前晶段【" + sectionNo + "】信息不存在或晶段暂未评级!");
        }
        if (StringUtils.isBlank(checkOut.getMaterialCode())) {
            return ResultGenerator.fail("当前晶段【" + sectionNo + "】信息缺失物料号, 请在方棒评级测试，是否为“正常”，氧含量是否合格!");
        }
        //晶棒重复扫描卡控
        FbTurnstoreTrayItem bySectionNo = fbTurnstoreTrayItemService.findBySectionNo3(ruleDto.getSectionNo());
        if (null != bySectionNo && bySectionNo.getReturnInspectionStatus() != 1) {
            return ResultGenerator.fail("当前晶段【" + sectionNo + "】已经执行过组托！请勿重复组托!");
        }
        ProductAssemblyRule productAssemblyRule = productAssemblyRuleService.get(ruleDto.getRuleId());
        if (null == productAssemblyRule) {
            return ResultGenerator.fail("组托规则为空!");
        }
        //获取等级码中的物料号
//        List<String> materialCodeList = levelCodeMaintenanceService.findByLevelCodeAndModelAndSpecificationAndProductLevel(productAssemblyRule.getLevelCode(),
//                productAssemblyRule.getConductiveType(), productAssemblyRule.getSpecs(), productAssemblyRule.getProductGrade());
//        if (CollectionUtils.isEmpty(materialCodeList)) {
//            return ResultGenerator.fail("等级码维护的维护的物料号为空!");
//        }
//        if (!materialCodeList.contains(checkOut.getMaterialCode())) {
//            return ResultGenerator.fail("单晶【" + sectionNo + "】料号跟组托规则物料号不一致!");
//        }
        if (!StringUtils.equals(checkOut.getProductLevelFb(), productAssemblyRule.getProductGrade())) {
            if (StringUtils.isEmpty(checkOut.getProductLevelFb()) && "N1".equals(productAssemblyRule.getProductGrade())) {
                //组拖产品等级：N1，当前产品等级： 无
                return ResultGenerator.fail("单晶【" + sectionNo + "】T氧值为空，请检查样片是否已检验！");
            }
            return ResultGenerator.fail("单晶【" + sectionNo + "】检验产品等级与规则不一致!");
        }
        //卡控晶棒长度，目前暂时先卡控非拼棒的情况
        String length = productAssemblyRule.getLength();
        if (!StringUtils.isEmpty(length) && length.contains("-")) {
            BigDecimal shortest = new BigDecimal(length.split("-")[0]);
            BigDecimal longest = new BigDecimal(length.split("-")[1]);
            if (null != checkOut.getInstoreLengthFb() && !isComposeSection) {
                if (shortest.compareTo(checkOut.getInstoreLengthFb()) > 0) {
                    return ResultGenerator.fail("单晶【" + sectionNo + "】长度小于组托规则限制，最小值：" + shortest.doubleValue());
                }
                if (checkOut.getInstoreLengthFb().compareTo(longest) > 0) {
                    return ResultGenerator.fail("单晶【" + sectionNo + "】长度大于组托规则限制，最大值：" + longest.doubleValue());
                }
            }
        }
        List<FbTurnstoreTrayItem> result = new ArrayList<>();
        FbTurnstoreTrayItem fbTurnstoreTrayItem = modelMapper.map(checkOut, FbTurnstoreTrayItem.class);
        if (StringUtils.isBlank(fbTurnstoreTrayItem.getSectionNo())) {
            fbTurnstoreTrayItem.setSectionNo(checkOut.getFbSectionNo());
        }
        if (BigDecimal.ZERO.compareTo(checkOut.getTheoryWeightFb()) >= 0) {
            throw new RuntimeException("理论重量不能小于等于0");
        }
        fbTurnstoreTrayItem.setTheoryWeightFb(checkOut.getTheoryWeightFb());
        fbTurnstoreTrayItem.setTCentreLife(checkOut.getTCarrierLifetime());
        fbTurnstoreTrayItem.setTRadialCentre(checkOut.getTResistivity());
        fbTurnstoreTrayItem.setWCentreLife(checkOut.getWCarrierLifetime());
        fbTurnstoreTrayItem.setWRadialCentre(checkOut.getWResistivity());
        fbTurnstoreTrayItem.setOxygenContentHead(checkOut.getTOxygenContent());
        fbTurnstoreTrayItem.setCarbonContentTail(checkOut.getWCarbonContent());
        fbTurnstoreTrayItem.setMaterialNumber(checkOut.getMaterialCode());
        //调整为方棒评级
        fbTurnstoreTrayItem.setProductLevel(checkOut.getProductLevelFb());
        fbTurnstoreTrayItem.setId(null);
        result.add(fbTurnstoreTrayItem);
        return ResultGenerator.success(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStateByTrayNo(UpdateStateByTrayNoDto dto) {
        FbTurnstoreTray fbTurnstoreTrayDb = dao.findByWarehouseEntryNumber(dto.getZinbd());
        Assert.notNull(fbTurnstoreTrayDb, "方棒组拖信息不存在");
        String wmsAuditResult;
        try {
            wmsAuditResult = objectMapper.writeValueAsString(dto);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        if ("S".equals(dto.getZshjg())) {
            fbTurnstoreTrayDb.setState(1);
            fbTurnstoreTrayDb.setWmsAuditResult(wmsAuditResult);
        } else if ("C".equals(dto.getZshjg())) {
            fbTurnstoreTrayDb.setState(3);
            fbTurnstoreTrayDb.setWmsAuditResult(wmsAuditResult);
        }
        saveOrUpdate(fbTurnstoreTrayDb);
        List<FbTurnstoreTrayItem> fbTurnstoreTrayItemList = fbTurnstoreTrayItemService.findByTrayId(fbTurnstoreTrayDb.getId());
        if (CollectionUtils.isNotEmpty(fbTurnstoreTrayItemList)) {
            for (FbTurnstoreTrayItem fbTurnstoreTrayItem : fbTurnstoreTrayItemList) {
                fbTurnstoreTrayItem.setState(fbTurnstoreTrayDb.getState());
                fbTurnstoreTrayItemService.saveOrUpdate(fbTurnstoreTrayItem);
            }
        }
    }

    @Override
    public Result sectionMesInitiateReceipt(FbTurnstoreTray turnstoreTray, List<FbTurnstoreTrayItem> turnstoreTrayItemList) {
        List<FbInformationReceptionDto> fbInformationReceptionDtoList = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(turnstoreTrayItemList)) {
            Map<String, FbTurnstoreTrayItem> cache = turnstoreTrayItemList.stream().collect(Collectors.toMap(FbTurnstoreTrayItem::getSectionNo, (p) -> p));
            //做去重使用
            Set<String> sectionSet = new HashSet<>();
            for (FbTurnstoreTrayItem fbTurnstoreTrayItem : turnstoreTrayItemList) {
                FbCheckOutData dataByFbSectionNoNew = fbCheckOutDataService.findDataByFbSectionNo(fbTurnstoreTrayItem.getSectionNo());
                if (null == dataByFbSectionNoNew) {
                    throw new RuntimeException("该托号不存在方棒检验明细！");
                }
                if (StringUtils.isEmpty(fbTurnstoreTrayItem.getSectionCompose())) {
                    FbInformationReceptionDto dto = new FbInformationReceptionDto();
                    dto.setTurnstoreTrayId(fbTurnstoreTrayItem.getId().toString());
                    dto.setSiliconRodNo(fbTurnstoreTrayItem.getSectionNo());//方棒晶编
                    dto.setCrystalPullingBinds("整棒");//单晶组合关系
                    dto.setSiliconRodLength(String.valueOf(dataByFbSectionNoNew.getInstoreLengthFb()));//有效长度 fixme 取有效长度
                    dto.setWeight(String.valueOf(fbTurnstoreTrayItem.getTheoryWeightFb()));//重量
                    dto.setUnit("KG");//单位
                    dto.setMaterialNo(fbTurnstoreTrayItem.getMaterialNumber());//物料编码
                    dto.setSpecification(fbTurnstoreTrayItem.getSpecification());//规格
                    dto.setPartNumberType(fbTurnstoreTrayItem.getConductionType());//P/N型
                    dto.setSourceBase("山西大基地拉晶工厂");//来源基地
                    dto.setGradeCode(fbTurnstoreTrayItem.getProductLevelFb());//等级码
                    dto.setHeadresistance(String.valueOf(dataByFbSectionNoNew.getMeanResistivityA()));//头电阻
                    dto.setTailresistor(String.valueOf(dataByFbSectionNoNew.getMeanResistivityB()));//尾电阻
                    dto.setTouShaozi(String.valueOf(dataByFbSectionNoNew.getMeanCarrierLifetimeA()));//头少子
                    dto.setWeiShaozi(String.valueOf(dataByFbSectionNoNew.getMeanCarrierLifetimeB()));//尾少子
                    dto.setTOxygen(String.valueOf(dataByFbSectionNoNew.getTOxygenContent()));//头氧
                    dto.setTCarbon(String.valueOf(dataByFbSectionNoNew.getTCarbonContent()));//头碳
                    dto.setWOxygen(String.valueOf(dataByFbSectionNoNew.getWOxygenContent()));//尾氧
                    dto.setWCarbon(String.valueOf(dataByFbSectionNoNew.getWCarbonContent()));//尾碳
                    dto.setRemark(fbTurnstoreTrayItem.getSquareRodRemark());//备注
                    dto.setRodBatch(fbTurnstoreTrayItem.getBatchNo());//方棒批次
                    //处理定向标识
                    getZorientationind(dataByFbSectionNoNew, dto);
//                根据物料号查询物料标识
                    MaterialModel materialModel = materialModelService.findByCode(fbTurnstoreTrayItem.getMaterialNumber());
                    dto.setStitchPerSegment("0");//每段拼缝
                    dto.setTotalLength(String.valueOf(dataByFbSectionNoNew.getInstoreLengthFb()));//总长度
                    dto.setTotalWeight(String.valueOf(fbTurnstoreTrayItem.getTheoryWeightFb()));//总重量
                    dto.setWerksto("5031");//调入方工厂
                    dto.setLgortto("P122");//调入方库存地点
                    dto.setWerksFrom("5041");//调出方工厂
                    dto.setLgortFrom("P32B");//调出方库存地点
                    dto.setTrayId(String.valueOf(fbTurnstoreTrayItem.getTrayNo()));//托盘id
                    dto.setDoped(turnstoreTray.getLevelCode());//掺杂
                    dto.setMaterialDesc(materialModel.getName());//物料描述
                    List<MaterialModelExtra> extras = materialModel.getExtras();
                    for (MaterialModelExtra extra : extras) {
                        String key = extra.getKey();
                        if ("S12".equals(key)) {
                            dto.setRodSize(extra.getCharVal());//尺寸
                        }
                        if ("S13".equals(key)) {
                            dto.setComBineType(extra.getCharVal());//晶体类别
                        }
                    }
                    fbInformationReceptionDtoList.add(dto);
                } else {//处理拼棒的情况
                    //0、这个晶编是否已经被处理过
                    if (sectionSet.contains(fbTurnstoreTrayItem.getSectionNo())) {
                        continue;
                    }
                    String[] arr = fbTurnstoreTrayItem.getSectionCompose().split(",");
                    ArrayList<String> sectionMoList = new ArrayList<>(Arrays.asList(arr));
                    FbInformationReceptionDto dto = new FbInformationReceptionDto();
                    int size = sectionMoList.size();
                    dto.setStitchPerSegment(String.valueOf(size - 1));//每段拼缝
                    switch (size) {
                        case 2:
                            dto.setCrystalPullingBinds("双拼棒");//单晶组合关系
                            break;
                        case 3:
                            dto.setCrystalPullingBinds("三拼棒");//单晶组合关系
                            break;
                        case 4:
                            dto.setCrystalPullingBinds("四拼棒");//单晶组合关系
                            break;
                        case 5:
                            dto.setCrystalPullingBinds("五拼棒");//单晶组合关系
                            break;
                        case 6:
                            dto.setCrystalPullingBinds("六拼棒");//单晶组合关系
                            break;
                        case 7:
                            dto.setCrystalPullingBinds("七拼棒");//单晶组合关系
                            break;
                        case 8:
                            dto.setCrystalPullingBinds("八拼棒");//单晶组合关系
                            break;
                        case 9:
                            dto.setCrystalPullingBinds("九拼棒");//单晶组合关系
                            break;
                        case 10:
                            dto.setCrystalPullingBinds("十拼棒");//单晶组合关系
                            break;
                        default:
                            dto.setCrystalPullingBinds(size + "拼棒");//单晶组合关系
                            break;
                    }
                    sectionMoList.remove(fbTurnstoreTrayItem.getSectionNo());
                    //剩下的list里面需要去补数据的
                    //1、单晶编号用fbTurnstoreTrayItem.getSectionCompose()替代
                    //dto.setSiliconRodNo(fbTurnstoreTrayItem.getSectionCompose());//方棒晶编
                    dto.setSiliconRodNo(fbTurnstoreTrayItem.getSectionNo());//方棒晶编
                    dto.setTurnstoreTrayId(fbTurnstoreTrayItem.getId().toString());
                    dto.setSiliconRodLength(String.valueOf(fbTurnstoreTrayItem.getInstoreLengthFb()));//有效长度
                    dto.setWeight(String.valueOf(fbTurnstoreTrayItem.getTheoryWeightFb()));//重量
                    dto.setRodBatch(fbTurnstoreTrayItem.getBatchNo());//方棒批次
                    dto.setPartNumberType(fbTurnstoreTrayItem.getConductionType());//P/N型
                    //处理定向标识
                    getZorientationind(dataByFbSectionNoNew, dto);

                    //总数
                    BigDecimal totalLength = fbTurnstoreTrayItem.getInstoreLengthFb();
                    BigDecimal totalWeight = fbTurnstoreTrayItem.getTheoryWeightFb();

                    dto.setHeadresistance(String.valueOf(dataByFbSectionNoNew.getMeanResistivityA()));//头电阻
                    dto.setTailresistor(String.valueOf(dataByFbSectionNoNew.getMeanResistivityB()));//尾电阻
                    dto.setTouShaozi(String.valueOf(dataByFbSectionNoNew.getMeanCarrierLifetimeA()));//头少子
                    dto.setWeiShaozi(String.valueOf(dataByFbSectionNoNew.getMeanCarrierLifetimeB()));//尾少子
                    dto.setTOxygen(String.valueOf(dataByFbSectionNoNew.getTOxygenContent()));//头氧
                    dto.setTCarbon(String.valueOf(dataByFbSectionNoNew.getTCarbonContent()));//头碳
                    dto.setWOxygen(String.valueOf(dataByFbSectionNoNew.getWOxygenContent()));//尾氧
                    dto.setWCarbon(String.valueOf(dataByFbSectionNoNew.getWCarbonContent()));//尾碳


                    //3、要把每一个值都拼起来
                    for (String sectionNo : sectionMoList) {
                        sectionNo = sectionNo.toUpperCase();
                        FbTurnstoreTrayItem item = cache.get(sectionNo);
                        FbCheckOutData fbCheckOutData = fbCheckOutDataService.findDataByFbSectionNo(sectionNo);
                        totalLength = totalLength.add(item.getInstoreLengthFb());
                        totalWeight = totalWeight.add(item.getTheoryWeightFb());

                        dto.setSiliconRodNo(dto.getSiliconRodNo() + "," + item.getSectionNo());//方棒晶编
                        dto.setSiliconRodLength(dto.getSiliconRodLength() + "," + item.getInstoreLengthFb().toString());
                        dto.setWeight(dto.getWeight() + "," + item.getTheoryWeightFb().toString());
                        dto.setRodBatch(dto.getRodBatch() + "," + item.getBatchNo());//方棒批次
                        dto.setTurnstoreTrayId(dto.getTurnstoreTrayId() + "," + item.getId().toString());
                        dto.setPartNumberType(dto.getPartNumberType() + "," + item.getConductionType());//P/N型
                        //处理定向标识
                        if ("非定向".equals(fbCheckOutData.getZorientationind()) || "".equals(fbCheckOutData.getZorientationind()) || StringUtils.isBlank(fbCheckOutData.getZorientationind())) {
                            dto.setOrientationType(dto.getOrientationType() + "," + fbCheckOutData.getZorientationind());
                        } else if (StringUtils.isNotBlank(fbCheckOutData.getZorientationind()) && "JD".equals(fbCheckOutData.getZorientationind())) {
                            dto.setOrientationType(dto.getOrientationType() + "," + fbCheckOutData.getZorientationind());
                        } else {
                            if (StringUtils.isNotBlank(fbCheckOutData.getOrderNo())) {
                                FbProductionOrder fbProductionOrder = productionOrderService.findByAufnr(fbCheckOutData.getOrderNo());
                                if (Objects.nonNull(fbProductionOrder)) {
                                    if ("非定向".equals(fbProductionOrder.getZorientationind()) || "".equals(fbProductionOrder.getZorientationind()) || StringUtils.isBlank(fbProductionOrder.getZorientationind())) {
                                        dto.setOrientationType(dto.getOrientationType() + "," + fbProductionOrder.getZorientationind());
                                    } else if (StringUtils.isNotBlank(fbProductionOrder.getZorientationind()) && "JD".equals(fbProductionOrder.getZorientationind())) {
                                        dto.setOrientationType(dto.getOrientationType() + "," + fbProductionOrder.getZorientationind());
                                    }
                                }
                            }
                        }

                        //检验参数
                        dto.setHeadresistance(dto.getHeadresistance() + "," + fbCheckOutData.getMeanResistivityA());//头电阻
                        dto.setTailresistor(dto.getTailresistor() + "," + fbCheckOutData.getMeanResistivityB());//尾电阻
                        dto.setTouShaozi(dto.getTouShaozi() + "," + fbCheckOutData.getMeanCarrierLifetimeA());//头少子
                        dto.setWeiShaozi(dto.getWeiShaozi() + "," + fbCheckOutData.getMeanCarrierLifetimeB());//尾少子
                        dto.setTOxygen(dto.getTOxygen() + "," + fbCheckOutData.getTOxygenContent());//头氧
                        dto.setTCarbon(dto.getTCarbon() + "," + fbCheckOutData.getTCarbonContent());//头碳
                        dto.setWOxygen(dto.getWOxygen() + "," + fbCheckOutData.getWOxygenContent());//尾氧
                        dto.setWCarbon(dto.getWCarbon() + "," + fbCheckOutData.getWCarbonContent());//尾碳
                        sectionSet.add(sectionNo);
                    }

                    //4、重新赋值
                    dto.setTotalLength(String.valueOf(totalLength));//总长度
                    dto.setTotalWeight(String.valueOf(totalWeight));//总重量

                    //不需要拼接的数据
                    dto.setUnit("KG");//单位
                    dto.setMaterialNo(fbTurnstoreTrayItem.getMaterialNumber());//物料编码
                    dto.setSpecification(fbTurnstoreTrayItem.getSpecification());//规格
                    dto.setSourceBase("山西大基地拉晶工厂");//来源基地
                    dto.setGradeCode(fbTurnstoreTrayItem.getProductLevelFb());//等级码
                    dto.setRemark(fbTurnstoreTrayItem.getSquareRodRemark());//备注
                    //根据物料号查询物料标识
                    MaterialModel materialModel = materialModelService.findByCode(fbTurnstoreTrayItem.getMaterialNumber());
                    dto.setWerksto("5031");//调入方工厂
                    dto.setLgortto("P122");//调入方库存地点
                    dto.setWerksFrom("5041");//调出方工厂
                    dto.setLgortFrom("P32B");//调出方库存地点
                    dto.setTrayId(String.valueOf(fbTurnstoreTrayItem.getTrayNo()));//托盘id
                    dto.setDoped(turnstoreTray.getLevelCode());//掺杂
                    dto.setMaterialDesc(materialModel.getName());//物料描述
                    List<MaterialModelExtra> extras = materialModel.getExtras();
                    for (MaterialModelExtra extra : extras) {
                        String key = extra.getKey();
                        if ("S12".equals(key)) {
                            dto.setRodSize(extra.getCharVal());//尺寸
                        }
                        if ("S13".equals(key)) {
                            dto.setComBineType(extra.getCharVal());//晶体类别
                        }
                    }
                    sectionSet.add(fbTurnstoreTrayItem.getSectionNo());

                    fbInformationReceptionDtoList.add(dto);
                }
            }
            log.info("====:{}", JSONObject.toJSONString(fbInformationReceptionDtoList));
            Result mesasn = ybFeignClients.fbInformationReception(fbInformationReceptionDtoList);
            if (!mesasn.getCode().equals(200)) {
                return ResultGenerator.fail("调用切片MES方棒信息接收接口失败");
            }
            //发起入库成功之后,组托状态修改成 2:待入库
            turnstoreTray.setState(2);
            turnstoreTray.setConfirmTime(new Date());
            turnstoreTray.setConfirmUser(BaseContextHandler.getUsername());
            turnstoreTray.setWarehouseEntryNumber(String.valueOf(System.currentTimeMillis()));
            saveOrUpdate(turnstoreTray);
            //更新明细
            if (null != turnstoreTrayItemList && turnstoreTrayItemList.size() > 0) {
                turnstoreTrayItemList.forEach(turnstoreTrayItem -> {
                    turnstoreTrayItem.setState(turnstoreTray.getState());
                    fbTurnstoreTrayItemService.saveOrUpdate(turnstoreTrayItem);
                });
            }
            return ResultGenerator.success();
        }
        return ResultGenerator.fail("切片MES发起入库失败");
    }

    private void getZorientationind(FbCheckOutData dataByFbSectionNoNew, FbInformationReceptionDto dto) {
        if ("非定向".equals(dataByFbSectionNoNew.getZorientationind()) || "".equals(dataByFbSectionNoNew.getZorientationind()) || StringUtils.isBlank(dataByFbSectionNoNew.getZorientationind())) {
            dto.setOrientationType("");
        } else if (StringUtils.isNotBlank(dataByFbSectionNoNew.getZorientationind()) && "JD".equals(dataByFbSectionNoNew.getZorientationind())) {
            dto.setOrientationType(dataByFbSectionNoNew.getZorientationind());
        } else {
            if (StringUtils.isNotBlank(dataByFbSectionNoNew.getOrderNo())) {
                FbProductionOrder fbProductionOrder = productionOrderService.findByAufnr(dataByFbSectionNoNew.getOrderNo());
                if (Objects.nonNull(fbProductionOrder)) {
                    if ("非定向".equals(fbProductionOrder.getZorientationind()) || "".equals(fbProductionOrder.getZorientationind()) || StringUtils.isBlank(fbProductionOrder.getZorientationind())) {
                        dto.setOrientationType("");
                    } else if (StringUtils.isNotBlank(fbProductionOrder.getZorientationind()) && "JD".equals(fbProductionOrder.getZorientationind())) {
                        dto.setOrientationType(fbProductionOrder.getZorientationind());
                    }
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStateByTrayId(UpdateStateByTrayIdDto dto) {
        FbTurnstoreTray fbTurnstoreTrayDb = dao.findByTrayNo(dto.getTrayId());
        Assert.notNull(fbTurnstoreTrayDb, "方棒组拖信息不存在");
        String wmsAuditResult;
        try {
            wmsAuditResult = objectMapper.writeValueAsString(dto);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        if ("S".equals(dto.getState())) {
            fbTurnstoreTrayDb.setState(1);
            fbTurnstoreTrayDb.setWmsAuditResult(wmsAuditResult);
        } else if ("C".equals(dto.getState())) {
            fbTurnstoreTrayDb.setState(2);
            fbTurnstoreTrayDb.setWmsAuditResult(wmsAuditResult);
        }
        saveOrUpdate(fbTurnstoreTrayDb);
        List<FbTurnstoreTrayItem> fbTurnstoreTrayItemList = fbTurnstoreTrayItemService.findByTrayId(fbTurnstoreTrayDb.getId());
        if (CollectionUtils.isNotEmpty(fbTurnstoreTrayItemList)) {
            for (FbTurnstoreTrayItem fbTurnstoreTrayItem : fbTurnstoreTrayItemList) {
                fbTurnstoreTrayItem.setState(fbTurnstoreTrayDb.getState());
                fbTurnstoreTrayItemService.saveOrUpdate(fbTurnstoreTrayItem);
            }
        }
    }

    @Override
    public FbTurnstoreTrayPrintDto getPrintInfo(Integer id) {
        if (null == id) {
            throw new RuntimeException("传入Id为空！");
        }
        FbTurnstoreTray fbTurnstoreTray = this.get(id);
        if (null == fbTurnstoreTray) {
            throw new RuntimeException("不存在该Id托号信息！");
        }
        //增加排序
        List<FbTurnstoreTrayItem> itemsByTrayId = fbTurnstoreTrayItemService.getItemsByTrayIdByOrder(id);
        List<String> sectionNoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(itemsByTrayId)) {
            for (FbTurnstoreTrayItem fbTurnstoreTrayItem : itemsByTrayId) {
                sectionNoList.add(fbTurnstoreTrayItem.getSectionNo());
            }
        }
        if (sectionNoList.size() == 0) {
            throw new RuntimeException("该托号不存在明细单晶！");
        }
        List<FbTurnstoreDetailPrintDto> printDtoListNew = new ArrayList<>();
        Integer indexNew = 1;
        for (FbTurnstoreTrayItem fbTurnstoreTrayItem : itemsByTrayId) {
            FbCheckOutData dataByFbSectionNo = fbCheckOutDataService.findDataByFbSectionNo(fbTurnstoreTrayItem.getSectionNo());
            if (null == dataByFbSectionNo) {
                throw new RuntimeException("该托号不存在方棒检验明细！");
            }

            FbTurnstoreDetailPrintDto fbTurnstoreDetailPrintDto = new FbTurnstoreDetailPrintDto();
            if (null != dataByFbSectionNo.getWeight() && dataByFbSectionNo.getWeight().compareTo(BigDecimal.ZERO) > 0) {
                fbTurnstoreDetailPrintDto.setWeight(dataByFbSectionNo.getWeight());
            } else {
                fbTurnstoreDetailPrintDto.setWeight(dataByFbSectionNo.getTheoryWeightFb());
            }
            fbTurnstoreDetailPrintDto.setLength(dataByFbSectionNo.getInstoreLengthFb());//fixme 修改成方棒有效长度
            fbTurnstoreDetailPrintDto.setSerialNo(indexNew);
            fbTurnstoreDetailPrintDto.setSectionNo(dataByFbSectionNo.getFbSectionNo());
            fbTurnstoreDetailPrintDto.setLevelCode(dataByFbSectionNo.getLevelCode());
            //t少子 tCarrierLifetime meanCarrierLifetimeA
            fbTurnstoreDetailPrintDto.setTCarrierLifetime(dataByFbSectionNo.getMeanCarrierLifetimeA());
            //w少子
            fbTurnstoreDetailPrintDto.setWCarrierLifetime(dataByFbSectionNo.getMeanCarrierLifetimeB());
            //a电阻均值 meanResistivityA meanResistivityA
            fbTurnstoreDetailPrintDto.setTResistivity(dataByFbSectionNo.getMeanResistivityA());
            //b电阻均值
            fbTurnstoreDetailPrintDto.setWResistivity(dataByFbSectionNo.getMeanResistivityB());
            //T氧
            fbTurnstoreDetailPrintDto.setTOxygenContent(dataByFbSectionNo.getTOxygenContent());
            //W碳
            fbTurnstoreDetailPrintDto.setWCarbonContent(dataByFbSectionNo.getWCarbonContent());
            fbTurnstoreDetailPrintDto.setSpecification(dataByFbSectionNo.getSpecification());
            printDtoListNew.add(fbTurnstoreDetailPrintDto);
            indexNew++;
        }

        List<FbCheckOutData> checkOutDataByFbSectionNoIns = fbCheckOutDataService.findCheckOutDataByFbSectionNoIns(sectionNoList);
        if (CollectionUtils.isEmpty(checkOutDataByFbSectionNoIns)) {
            throw new RuntimeException("该托号不存在方棒检验明细！");
        }
        FbCheckOutData fbCheckOutData = checkOutDataByFbSectionNoIns.get(0);
        FbTurnstoreTrayPrintDto fbTurnstoreTrayPrintDto = new FbTurnstoreTrayPrintDto();
        fbTurnstoreTrayPrintDto.setAbbreviation(fbCheckOutData.getAbbreviation());
        Date date = new Date();

        CrystalMaterialRelation bySectionNo = crystalMaterialRelationService.findBySectionNo(fbCheckOutData.getFbSectionNo());
        if (null != bySectionNo) {
            fbTurnstoreTrayPrintDto.setMaterialCode(bySectionNo.getMaterialCode());
            if (null != bySectionNo.getMaterialModelId()) {
                MaterialModel materialModel = materialModelService.get(bySectionNo.getMaterialModelId());
                fbTurnstoreTrayPrintDto.setMaterialName(materialModel.getName());
            }
        }
        fbTurnstoreTrayPrintDto.setCount(itemsByTrayId.size());
        fbTurnstoreTrayPrintDto.setPackageDate(fbTurnstoreTray.getOperationTime());
        fbTurnstoreTrayPrintDto.setPackageUser(fbTurnstoreTray.getUser());
        fbTurnstoreTrayPrintDto.setPrintDate(date);
        fbTurnstoreTray.setPrintTime(date);
        fbTurnstoreTrayPrintDto.setOperationTime(fbTurnstoreTray.getOperationTime());
        BigDecimal totalWeight = new BigDecimal(0);
        BigDecimal meanResistivityA = BigDecimal.ZERO;
        BigDecimal totalLength = BigDecimal.ZERO;
        List<FbTurnstoreDetailPrintDto> printDtoList = new ArrayList<>();


        BigDecimal artSegmentNo = BigDecimal.ZERO;
        BigDecimal rtSegmentNo = BigDecimal.ZERO;
        BigDecimal aSegmentNo = BigDecimal.ZERO;
        Integer singleNo = 0;
        Integer doubleNo = 0;
        Integer index = 0;
        for (FbCheckOutData fbCheckOutData1 : checkOutDataByFbSectionNoIns) {
            index++;
            if (StringUtils.equals(fbCheckOutData1.getHeadTailRecognition(), "T段")) {
                artSegmentNo = artSegmentNo.add(fbCheckOutData1.getTheoryWeightFb());
                rtSegmentNo = rtSegmentNo.add(fbCheckOutData1.getTheoryWeightFb());
            } else if (StringUtils.equals(fbCheckOutData1.getHeadTailRecognition(), "W段")) {
                aSegmentNo = aSegmentNo.add(fbCheckOutData1.getTheoryWeightFb());
                artSegmentNo = artSegmentNo.add(fbCheckOutData1.getTheoryWeightFb());
            } else if (StringUtils.equals(fbCheckOutData1.getHeadTailRecognition(), "T段W段")) {
                artSegmentNo = artSegmentNo.add(fbCheckOutData1.getTheoryWeightFb());
                rtSegmentNo = rtSegmentNo.add(fbCheckOutData1.getTheoryWeightFb());
            }
            if (null != fbCheckOutData1.getSticksCount()) {
                if (fbCheckOutData1.getSticksCount() == 1) {
                    singleNo++;
                } else {
                    doubleNo++;
                }
            }

            FbTurnstoreDetailPrintDto fbTurnstoreDetailPrintDto = new FbTurnstoreDetailPrintDto();
            BigDecimal wb = fbCheckOutData1.getTheoryWeightFb();
            totalWeight = totalWeight.add(fbCheckOutData1.getTheoryWeightFb());
            fbTurnstoreDetailPrintDto.setWeight(wb);

            totalLength = totalLength.add(fbCheckOutData1.getInstoreLengthFb());//fixme 修改成方棒有效长度
            if (fbCheckOutData1.getMeanResistivityA() != null) {
                meanResistivityA = meanResistivityA.add(fbCheckOutData1.getMeanResistivityA());
            }

            fbTurnstoreDetailPrintDto.setLength(fbCheckOutData1.getInstoreLengthFb());//fixme 修改成方棒有效长度
            fbTurnstoreDetailPrintDto.setSerialNo(index);
            fbTurnstoreDetailPrintDto.setSectionNo(fbCheckOutData1.getFbSectionNo());
            fbTurnstoreDetailPrintDto.setLevelCode(fbCheckOutData1.getLevelCode());
            //t少子 tCarrierLifetime meanCarrierLifetimeA
            fbTurnstoreDetailPrintDto.setTCarrierLifetime(fbCheckOutData1.getMeanCarrierLifetimeA());
            //w少子
            fbTurnstoreDetailPrintDto.setWCarrierLifetime(fbCheckOutData1.getMeanCarrierLifetimeB());
            //a电阻均值 meanResistivityA meanResistivityA
            fbTurnstoreDetailPrintDto.setTResistivity(fbCheckOutData1.getMeanResistivityA());
            //b电阻均值
            fbTurnstoreDetailPrintDto.setWResistivity(fbCheckOutData1.getMeanResistivityB());
            //T氧
            fbTurnstoreDetailPrintDto.setTOxygenContent(fbCheckOutData1.getTOxygenContent());
            //W碳
            fbTurnstoreDetailPrintDto.setWCarbonContent(fbCheckOutData1.getWCarbonContent());
            fbTurnstoreDetailPrintDto.setSpecification(fbCheckOutData1.getSpecification());
            printDtoList.add(fbTurnstoreDetailPrintDto);

        }
        fbTurnstoreTrayPrintDto.setTotalLength(totalLength);
        fbTurnstoreTrayPrintDto.setTotalWeight(totalWeight.setScale(3, RoundingMode.HALF_UP));
        fbTurnstoreTrayPrintDto.setMeanResistivityA(meanResistivityA.divide(new BigDecimal(fbTurnstoreTray.getCount()), 2, BigDecimal.ROUND_HALF_UP));
        fbTurnstoreTrayPrintDto.setPrintDtoList(printDtoListNew);
        String remark = fbTurnstoreTray.getCount() + " 刀 " + fbCheckOutData.getSpecification() + "规格";
        String count = itemsByTrayId.size() + " 刀 ";
        String spec = fbCheckOutData.getSpecification() + "规格";
        String detail = null;
        if (singleNo == 0) {
            detail = "(双根 " + doubleNo + " 刀)";
        } else if (doubleNo == 0) {
            detail = "(单根 " + singleNo + " 刀)";
        } else {
            detail = "(单根 " + singleNo + " 刀 , 双根 " + doubleNo + " 刀)";
        }
        BigDecimal divideART = artSegmentNo.divide(totalWeight, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
        BigDecimal divideTR = rtSegmentNo.divide(totalWeight, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
        BigDecimal divideA = aSegmentNo.divide(totalWeight, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
        String ATR = "ATR段( " + divideART + "% ) TR段( " + divideTR + "% ) A段( " + divideA + "% )";
        remark = count + spec + detail + ATR;
        fbTurnstoreTrayPrintDto.setRemark(remark);
        //fixme 加个开关，临时处理一下
        SwitchConfig config = GlobalSwitch.switchConfig(NAMESPACE_FB_CHECK, "trayno_remark", false);
        if (config != null && config.isEnable() && fbTurnstoreTray.getTrayNo().equals(config.getValue())) {//如果托号等于这个
            fbTurnstoreTrayPrintDto.setRemark(config.getDescription());
        }
        fbTurnstoreTrayPrintDto.setTrayNo(fbTurnstoreTray.getTrayNo());
        return fbTurnstoreTrayPrintDto;
    }

    @Override
    public void updateSectionMesTrayItemState(FbTurnstoreTray turnstoreTray, List<FbTurnstoreTrayItem> trayItemList) {
        //更新明细表
        ThreadManager.getThreadPollProxy().execute(() -> {
            try {
                updateTrayItemList(turnstoreTray, trayItemList);
            } catch (Exception e) {
                e.printStackTrace();
                //回滚表头信息
                turnstoreTray.setState(0);
                //todo 数据库字段只有50
                turnstoreTray.setRemark("失败原因：" + e.getMessage().substring(0, 40));
                saveOrUpdate(turnstoreTray);
            }
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTrayItemState(WmsToFbReceiveDto receiveDto, FbTurnstoreTray turnstoreTray, List<FbTurnstoreTrayItem> trayItemList) {
        //更新明细表
        ThreadManager.getThreadPollProxy().execute(() -> {
            try {
                updateTrayItemList(turnstoreTray, trayItemList);
            } catch (Exception e) {
                e.printStackTrace();
                //回滚表头信息
                turnstoreTray.setState(0);
                //todo 数据库字段只有50
                turnstoreTray.setRemark("失败原因：" + e.getMessage().substring(0, 40));
                saveOrUpdate(turnstoreTray);
            }
        });
    }

    /**
     * 更新组托明细相关内容
     *
     * @param turnstoreTray 组托主表
     * @param trayItemList  组表明细列表
     */
    public void updateTrayItemList(FbTurnstoreTray turnstoreTray, List<FbTurnstoreTrayItem> trayItemList) {
//        List<FbTurnstoreTrayItem> turnstoreTrayItemGrs = new ArrayList<>();
//        List<FbTurnstoreTrayItem> turnstoreTrayItemGrcs = new ArrayList<>();
        try {
            for (FbTurnstoreTrayItem trayItem : trayItemList) {
                //解锁组托状态
                PlanProcessingOrder planProcessingOrder = updatePlanOrder(trayItem.getSectionNo());
                if (1 == turnstoreTray.getState()) {
                    //成功--执行进站操作
                    wipStorageService.inStation(trayItem.getSectionNo(), null, false);
                    //完成组托状态
                    overPlanOrder(planProcessingOrder);
//                    turnstoreTrayItemGrs.add(trayItem);
                } else if (3 == turnstoreTray.getState()) {
                    //拒收---执行退站操作
                    wipStorageService.exitStation(trayItem.getSectionNo());
                } else {
                    //冲销---出站到方棒检验进站状态
                    wipStorageService.outStation(trayItem.getSectionNo(), "A", EnumValuesFactory.WipStorageStatus.已进站.getKey());
//                    turnstoreTrayItemGrcs.add(trayItem);
                }
                //将信息更新至明细
                trayItem.setState(turnstoreTray.getState());
                trayItem.setConfirmTime(turnstoreTray.getConfirmTime());
                trayItem.setConfirmUser(turnstoreTray.getConfirmUser());
                if (null != turnstoreTray.getRemark()) {
                    trayItem.setReturnRemark(turnstoreTray.getRemark());
                }
                fbTurnstoreTrayItemService.saveOrUpdate(trayItem);
            }
//            //发送GR信息
//            if (turnstoreTrayItemGrs.size() > 0) {
//                sapServer.sendGr(turnstoreTrayItemGrs);
//            }
//            //发送GR信息(冲销)
//            if (turnstoreTrayItemGrcs.size() > 0) {
//                sapServer.sendGrc(turnstoreTrayItemGrcs);
//            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * 解锁组托状态
     *
     * @param sectionNo 单晶编号
     */
    public PlanProcessingOrder updatePlanOrder(String sectionNo) {
        //解锁组托状态
        PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCode(sectionNo);
        if (null == planProcessingOrder) {
            throw new BusinessException(sectionNo + "工单号不存在");
        }
        planProcessingOrder.setStatus(EnumValuesFactory.PlanProcessingOrderStatus.加工中.getKey());
        planProcessingOrderService.saveOrUpdate(planProcessingOrder);
        return planProcessingOrder;
    }

    /**
     * 完成组托状态
     *
     * @param planProcessingOrder 单晶编号
     */
    public void overPlanOrder(PlanProcessingOrder planProcessingOrder) {
        //解锁组托状态
        planProcessingOrder.setStatus(EnumValuesFactory.PlanProcessingOrderStatus.入库完成.getKey());
        planProcessingOrderService.saveOrUpdate(planProcessingOrder);
    }

    @Override
    public List<FbTurnstoreTrayItem> groupItemList(FbCheckOutData checkOut) {
        List<FbTurnstoreTrayItem> trayItemList = new ArrayList<>();
        //如果是拼棒则带出所有晶段信息
        String split = ",";
        if (null != checkOut.getSectionCompose() && checkOut.getSectionCompose().contains(split)) {
            String[] sections = checkOut.getSectionCompose().split(split);
            if (sections.length > 0) {
                for (String sectionNo : sections) {
                    FbCheckOutData checkOutData = checkOutService.findDataByFbSectionNo(sectionNo);
                    if (null != checkOutData) {
                        trayItemList.add(packageItemList(checkOutData));
                    }
                }
            }
        } else {
            //组装当前晶段信息
            trayItemList.add(packageItemList(checkOut));
        }
        return trayItemList;
    }

    @Override
    public FbTurnstoreTrayItem groupItem(FbCheckOutData checkOutData) {
        return packageItemList(checkOutData);
    }


    private Result valudate(FbCheckOutData checkOut) {
        String sectionNo = checkOut.getFbSectionNo();
        if (null == checkOut.getMaterialNumber()) {
            return ResultGenerator.fail(sectionNo + ": 料号不能为空");
        } else if (null == checkOut.getWeight()) {
            return ResultGenerator.fail(sectionNo + ": 实际称重不能为空");
        } else if (null == checkOut.getLength()) {
            return ResultGenerator.fail(sectionNo + ": 硅棒总长不能为空");
        } else if (null == checkOut.getOrderNo()) {
            return ResultGenerator.fail(sectionNo + ": 订单号不能为空");
        } else if (null == checkOut.getProductLevel()) {
            return ResultGenerator.fail(sectionNo + ": 产品等级不能为空");
        } else if (null == checkOut.getProductLevelFb()) {
            return ResultGenerator.fail(sectionNo + ": 入库类别不能为空");
        } else if (null == checkOut.getProductType()) {
            return ResultGenerator.fail(sectionNo + ": 产品类别不能为空");
        }
        return ResultGenerator.success();
    }

    @Override
    public Result validateRuleAndData(ProductRuleDto ruleDto, FbCheckOutData checkOutData, String state) {
        //校验是否符合组托规则
        if ("综计WMS".equals(ruleDto.getHasGone()) || "综计返修".equals(ruleDto.getHasGone())) {
            String message = validateRules(ruleDto, checkOutData);
            if (!"符合".equals(message) && !message.contains("晶段的入库类别不符合规则")) {
                return ResultGenerator.fail(message);
            }
            if (!message.contains("晶段的入库类别不符合规则")) {
                state = "true";
            }
            //校验检验数据是否完整
            Result result = valudate(checkOutData);
            if (result.getCode() != ResultCode.SUCCESS.getCode()) {
                return ResultGenerator.fail(result.getMessage());
            }
        }
        //查询是否处于当前站点
        wipStorageService.selectWipStorage(checkOutData.getFbSectionNo(), EnumValuesFactory.WipStorageCode.方棒检验.getKey(), true);
        //查询是否存在
        List<FbTurnstoreTrayItem> trayItemList = fbTurnstoreTrayItemService.findBySectionNoValidate(checkOutData.getFbSectionNo());
        if (null != trayItemList && !trayItemList.isEmpty()) {
            for (FbTurnstoreTrayItem trayItem : trayItemList) {
                if (9 == trayItem.getState()) {
                    return ResultGenerator.fail("该晶段已进行组托，不能重复组托,所在托号为: " + trayItem.getTrayNo());
                } else if ("退料".equals(trayItem.getHasGone()) && 1 == trayItem.getState()) {
                    return ResultGenerator.fail("该晶段已发起退料且接收，不能重复组托,所在托号为: " + trayItem.getTrayNo());
                }
            }
        }
        //组装组托详情
        return ResultGenerator.success(state, groupItem(checkOutData));
    }

    /**
     * 组装详情列表
     *
     * @param checkOut
     */
    private FbTurnstoreTrayItem packageItemList(FbCheckOutData checkOut) { //TODO 打托信息上传接口
        FbTurnstoreTrayItem turnstoreTrayItem = new FbTurnstoreTrayItem();
        BeanUtil.copyProperties(checkOut, turnstoreTrayItem, BeanUtil.getIgnoreProperties(checkOut, null, null));

        //单晶组合
//        if (null == checkOut.getSectionCompose()) {
//            turnstoreTrayItem.setSectionCompose(sectionNo + ";");
//        } else {
//            //替换
//            String replaceAll = checkOut.getSectionCompose().replaceAll(",", ";");
//            turnstoreTrayItem.setSectionCompose(replaceAll + ";");
//        }
        //组托  产品等级  取 方棒的产品等级
        turnstoreTrayItem.setProductLevel(checkOut.getProductLevel());

//        //组托  生产日期  取 方棒检验时间
//        turnstoreTrayItem.setCheckTime(checkOut.getCheckTime());
//
//        //组托  物料编码  取 方棒物料编码
//        turnstoreTrayItem.setPlanMaterialCode(checkOut.getPlanMaterialCode());

//        turnstoreTrayItem.setSpecification(checkOut.getSpecification());

        if (checkOut.getLength() != null && checkOut.getCollapseLossSh() != null && checkOut.getCollapseLossZh() != null && checkOut.getCollapseLossXia() != null) {
            turnstoreTrayItem.setEffectiveLength(checkOut.getLength().subtract(checkOut.getCollapseLossSh()).subtract(checkOut.getCollapseLossZh()).subtract(checkOut.getCollapseLossXia()));
        }
        turnstoreTrayItem.setFbExperiLevel(checkOut.getExperiLevel());
        turnstoreTrayItem.setCustomerType(checkOut.getYbLevel());
        turnstoreTrayItem.setBevel(checkOut.getLengthSlope());
        turnstoreTrayItem.setOrderNo(checkOut.getOrderNo());
        turnstoreTrayItem.setDopant(checkOut.getDopant());
        //组托  单晶编号  取 方棒的单晶编号
        String sectionNo = checkOut.getFbSectionNo();
        turnstoreTrayItem.setSectionNo(sectionNo);

        //边距max
        if (null != checkOut.getSideLengthMax() && checkOut.getSideLengthMax().compareTo(BigDecimal.ZERO) > 0) {
            turnstoreTrayItem.setSideLengthMax(checkOut.getSideLengthMax());
        } else {
            turnstoreTrayItem.setSideLengthMax(checkOut.getEapSideMax());
        }
        //边距min
        if (null != checkOut.getSideLengthMin() && checkOut.getSideLengthMin().compareTo(BigDecimal.ZERO) > 0) {
            turnstoreTrayItem.setSideLengthMin(checkOut.getSideLengthMin());
        } else {
            turnstoreTrayItem.setSideLengthMin(checkOut.getEapSideMin());
        }
        //直径max
        if (null != checkOut.getDiameterMax() && checkOut.getDiameterMax().compareTo(BigDecimal.ZERO) > 0) {
            turnstoreTrayItem.setDiameterMax(checkOut.getDiameterMax());
        } else {
            turnstoreTrayItem.setDiameterMax(checkOut.getEapDiameterMax());
        }
        //直径min
        if (null != checkOut.getDiameterMin() && checkOut.getDiameterMin().compareTo(BigDecimal.ZERO) > 0) {
            turnstoreTrayItem.setDiameterMin(checkOut.getDiameterMin());
        } else {
            turnstoreTrayItem.setDiameterMin(checkOut.getEapDiameterMin());
        }

//        //工厂
//        String factory = sectionNo.substring(1, 2);
//        DictionaryItem factoryCate = dictionaryItemService.findByThemeValueAndValueAndEnable("FactoryCate", factory, true);
//        if (null != factoryCate) {
//            factory = factoryCate.getName();
//        }
//        turnstoreTrayItem.setFactoryName(factory);
//        //库存地点
//        turnstoreTrayItem.setStockPlace("Q003");
//        if (checkOut.getSticksCount() > 1 && null != checkOut.getSpellBarLength()) {
//            turnstoreTrayItem.setTotalLength(checkOut.getSpellBarLength());
//        }


        turnstoreTrayItem.setSquareRodRemark(checkOut.getSquareRodRemarks());
        //获取圆棒检验数据
        Result<YbInspectDataDto> ybInspectDataDtoResult;
        YbInspectDataDto ybInspectDataDto;
        ybInspectDataDtoResult = ybFeignClients.getInspectDataBaseBySectionNo(checkOut.getYbSectionNo());
        ybInspectDataDto = ybInspectDataDtoResult.getData();
        if (null == ybInspectDataDto) {
            String fromMark = checkOut.getYbSectionNo().substring(SectionIndexRangeEnum.基地追溯产品类型.getBeginIndex(), SectionIndexRangeEnum.基地追溯产品类型.getEndIndex());
            if (fromMark.matches("[A-Z]+")) {
                ybInspectDataDtoResult = ybFeignClients.accordSquareGetInspect(checkOut.getYbSectionNo().substring(SectionIndexRangeEnum.毛棒到截断位数.getBeginIndex(), SectionIndexRangeEnum.毛棒到截断位数.getEndIndex()));
            } else {
                ybInspectDataDtoResult = ybFeignClients.accordSquareGetInspect(checkOut.getYbSectionNo().substring(0, 13));
            }
            ybInspectDataDto = ybInspectDataDtoResult.getData();
        }
        if (ybInspectDataDtoResult.getCode() == ResultCode.SUCCESS.getCode()) {
            if (null != ybInspectDataDto) {
//                turnstoreTrayItem.setAgainNum(ybInspectDataDto.getAgainNum());
//                turnstoreTrayItem.setCrystalWorkshop(ybInspectDataDto.getCrystalNo().substring(1, 2));
//                turnstoreTrayItem.setHeadDefectGrade(ybInspectDataDto.getHeadDefectGrade());
//                turnstoreTrayItem.setHeadTailRecognition(ybInspectDataDto.getHeadTailRecognition());
//                turnstoreTrayItem.setTLifeMin(ybInspectDataDto.getTCentreLife());
//                turnstoreTrayItem.setWLifeMin(ybInspectDataDto.getWCentreLife());
//                turnstoreTrayItem.setTCentreLife(ybInspectDataDto.getTCentreLife());
                turnstoreTrayItem.setWCentreLife(ybInspectDataDto.getWCentreLife());
//                turnstoreTrayItem.setOxygenContentHead(ybInspectDataDto.getOxygenContentHead());
                turnstoreTrayItem.setOxygenContentHead(checkOut.getHeadOxygenContents());
                turnstoreTrayItem.setCarbonContentTail(ybInspectDataDto.getCarbonContentTail());
                //尾中心少子寿命
                turnstoreTrayItem.setWLifeMin(ybInspectDataDto.getWCentreLife());
                //头中心少子寿命
                turnstoreTrayItem.setLife(ybInspectDataDto.getTCentreLife());

//                turnstoreTrayItem.setCarbonContentHead(ybInspectDataDto.getCarbonContentHead());
//                turnstoreTrayItem.setCarbonContentTail(ybInspectDataDto.getCarbonContentTail());
//                turnstoreTrayItem.setCheckTime(ybInspectDataDto.getCreateTime());
//                turnstoreTrayItem.setTRadialCentre(ybInspectDataDto.getTRadialCentre());
//                turnstoreTrayItem.setTRadialEdge(ybInspectDataDto.getTRadialEdge1());
//                turnstoreTrayItem.setWRadialCentre(ybInspectDataDto.getWRadialCentre());
//                turnstoreTrayItem.setWRadialEdge(ybInspectDataDto.getWRadialEdge1());
            }
        } else {
            throw new BusinessException("圆棒检验数据获取失败，请重试");
        }
        return turnstoreTrayItem;
    }

    /**
     * 生成托号
     *
     * @param productRule     组托规则
     * @param fbTurnstoreTray 组托信息
     */
    public void createTrayNo(ProductAssemblyRule productRule, FbTurnstoreTray fbTurnstoreTray) {
        //规则匹配托号
        StringBuilder trayNo = new StringBuilder();
        String order3Num = null;
        String order5Num = null;
        String num3Value;
        String num5Value;
        String key5 = "FBOrderNum5";
        String key3 = "FBOrderNum3";

        //日期获取
        long time = new DateUtil().getChangeShiftsTime().getTime();
        Calendar cal = Calendar.getInstance();
        if (System.currentTimeMillis() < time) {
            cal.add(Calendar.DATE, -1);
        } else {
            cal.add(Calendar.DATE, 0);
        }
        String date = new SimpleDateFormat("yyMMdd").format(cal.getTime());
        if ("综计WMS".equals(fbTurnstoreTray.getHasGone()) || "综计返修".equals(fbTurnstoreTray.getHasGone())) {
            String spacer = ",";
            String workShop = "六期方棒";
            //第一位:厂别:Y
            DictionaryItem shopValue;
            shopValue = dictionaryItemService.findByThemeValueAndNameAndEnable("workShop", workShop, true);
            if (null != shopValue) {
                trayNo.append(shopValue.getValue());
            } else {
                trayNo.append("L");
            }
            //第二位:整拼类型
            DictionaryItem pinValue;
            if (null == productRule.getSticksCount()) {
                String pin = "混拼";
                pinValue = dictionaryItemService.findByThemeValueAndNameAndEnable("spell", pin, true);
            } else {
                String type = productRule.getSticksCount() + "拼";
                pinValue = dictionaryItemService.findByThemeValueAndNameAndEnable("spell", type, true);
                fbTurnstoreTray.setSticksCount(productRule.getSticksCount());
            }
            if (null != pinValue) {
                trayNo.append(pinValue.getValue());
            } else {
                trayNo.append("Z");
            }
            //第三位:棒长
            String lengthType = "不区分棒长";
            String dtoLength = productRule.getLength();
            DictionaryItem lengthValue;
            if (lengthType.equals(dtoLength)) {
                lengthValue = dictionaryItemService.findByThemeValueAndNameAndEnable("rodLength", lengthType, true);
            } else if (dtoLength.contains(spacer)) {
                lengthValue = dictionaryItemService.findByThemeValueAndNameAndEnable("rodLength", "800-900", true);
            } else {
                lengthValue = dictionaryItemService.findByThemeValueAndNameAndEnable("rodLength", dtoLength, true);
            }
            if (null != lengthValue) {
                trayNo.append(lengthValue.getValue());
            } else {
                trayNo.append("0");
            }
            //第四位:规格型号
            String spec = "转规格";
            String specs = productRule.getConductiveType() + "型" + productRule.getSpecs().substring(0, 3);
            DictionaryItem specValue;
            if (specs.contains("转")) {
                specValue = dictionaryItemService.findByThemeValueAndNameAndEnable("specMod", spec, true);
            } else {
                specValue = dictionaryItemService.findByThemeValueAndNameAndEnable("specMod", specs, true);
            }
            if (null != specValue) {
                trayNo.append(specValue.getValue());
            } else {
                trayNo.append("Z");
            }
            //第五位:产品等级
            String grade = "混类别";
            String productGrade = productRule.getProductGrade();
            DictionaryItem gradeValue;
            if (productGrade.contains(spacer) || productGrade.contains(grade)) {
                gradeValue = dictionaryItemService.findByThemeValueAndNameAndEnable("productRat", grade, true);
            } else {
                gradeValue = dictionaryItemService.findByThemeValueAndNameAndEnable("productRat", productGrade, true);
            }
            if (null != gradeValue) {
                trayNo.append(gradeValue.getValue());
            } else {
                trayNo.append("Z");
            }
            //第六-十一位:日期
            trayNo.append(date);
            //第十二-十四位:顺序号
            if (redisTemplate.hasKey(key3)) {
                //先获取redis中的顺序号
                num3Value = (String) redisTemplate.opsForValue().get(key3);
                int num3 = Integer.parseInt(num3Value);
                //如果数据库最大值-缓存=1,则+2,否则+1
                Integer num = dao.findOrderNumByWMS();
                if (null != num && num - num3 == 1) {
                    order3Num = String.valueOf(num3 + 2);
                } else {
                    order3Num = String.valueOf(num3 + 1);
                }
                if (order3Num.length() == 1) {
                    order3Num = "00" + order3Num;
                } else if (order3Num.length() == 2) {
                    order3Num = "0" + order3Num;
                }
            } else {
                order3Num = "001";
            }
            trayNo.append(order3Num);
            /*//第十五位:实验等级
            DictionaryItem experValue;
            if (null == productRule.getExperGrade() || productRule.getExperGrade().contains(spacer)) {
                experValue = dictionaryItemService.findByThemeValueAndNameAndEnable("tempSign", grade, true);
            } else {
                experValue = dictionaryItemService.findByThemeValueAndNameAndEnable("tempSign", productRule.getExperGrade(), true);
            }
            if (null != experValue) {
                trayNo.append(experValue.getValue());
            } else {
                trayNo.append("Z");
            }
            //第十六位:入库类别
            DictionaryItem categoryValue;
            if (null == productRule.getInputType() || productRule.getInputType().contains(spacer)) {
                trayNo.append("Z");
            } else {
                categoryValue = dictionaryItemService.findByThemeValueAndNameAndEnable("storType", productRule.getInputType(), true);
                if (null != categoryValue) {
                    trayNo.append(categoryValue.getValue());
                } else {
                    trayNo.append("Z");
                }
            }*/
            if ("六期".equals(fbTurnstoreTray.getFactoryName())) {
                fbTurnstoreTray.setFactoryName("1031");
            }
        } else {
            trayNo.append("F").append(date);
            //其他去向的托号按照流水号生成（年月日+五位流水）
            //Integer num = dao.findOrderNumBy();
            if (redisTemplate.hasKey(key5)) {
                //先获取redis中的顺序号
                num5Value = (String) redisTemplate.opsForValue().get(key5);
                order5Num = String.valueOf(Integer.parseInt(num5Value) + 1);
                if (order5Num.length() == 1) {
                    order5Num = "0000" + order5Num;
                } else if (order5Num.length() == 2) {
                    order5Num = "000" + order5Num;
                } else if (order5Num.length() == 3) {
                    order5Num = "00" + order5Num;
                } else if (order5Num.length() == 4) {
                    order5Num = "0" + order5Num;
                }
            } else {
                order5Num = "00001";
            }
            trayNo.append(order5Num);
        }
        //判断拖号是否重复
        if (null != dao.checkTrayNo(trayNo.toString())) {
            throw new RuntimeException("错误，生成的拖号已存在");
        }
        fbTurnstoreTray.setTrayNo(trayNo.toString());
        //更新缓存
        //每天08:59:59秒重置
        long timeLong;
        if (System.currentTimeMillis() < time) {
            //小于当天08:59:59,计算至当天08:59:59
            timeLong = time - System.currentTimeMillis();
        } else {
            //大于当天08:59:59,计算至第二天08:59:59点
            timeLong = new DateUtil().getCurrentDayEndTime().getTime() + 32400000 - System.currentTimeMillis();
        }
        if (timeLong > 1000) {
            if (null != order3Num) {
                fbTurnstoreTray.setOrderNum(Integer.parseInt(order3Num));
                redisTemplate.opsForValue().set(key3, order3Num, timeLong / 1000, TimeUnit.SECONDS);
            } else {
                fbTurnstoreTray.setOrderNum(Integer.parseInt(order5Num));
                redisTemplate.opsForValue().set(key5, order5Num, timeLong / 1000, TimeUnit.SECONDS);
            }
        }
    }

    public void createTrayNoTYNew(FbTurnstoreTray fbTurnstoreTray, FbTurnstoreTrayItem fbTurnstoreTrayItem, ProductAssemblyRule productRule) {

        if (StringUtils.isBlank(fbTurnstoreTrayItem.getSectionNo())) {
            throw new RuntimeException("明细单晶编号为空");
        }
        StringBuilder trayNo = new StringBuilder();
        // 1基地：太原 定向
        trayNo.append(fbTurnstoreTrayItem.getSectionNo().substring(0, 2));

        //尺寸
        trayNo.append(fbTurnstoreTrayItem.getSectionNo().substring(3, 4));
        //等级
        trayNo.append(productRule.getProductGrade());

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String format = formatter.format(date);

        //年月日
        String year = format.substring(2, 4);
        trayNo.append(year);
        String month = format.substring(5, 7);
        switch (month) {
            case "10":
                trayNo.append("A");
                break;
            case "11":
                trayNo.append("B");
                break;
            case "12":
                trayNo.append("C");
                break;
            default:
                trayNo.append(Integer.valueOf(month));
                break;
        }
        String day = format.substring(8);
        trayNo.append(day);
        //流水号
        Integer count = 0;
        Integer index = 1;
        if (redisTemplate.hasKey(format)) {
            count = Integer.valueOf(redisTemplate.opsForValue().get(format).toString());
        }
        redisTemplate.opsForValue().set(format, count + 1, 24, TimeUnit.HOURS);
        trayNo.append(String.format("%03d", count + 1));

        fbTurnstoreTray.setTrayNo(trayNo.toString());
    }

    /**
     * 生成托号
     *
     * @param productRule     组托规则
     * @param fbTurnstoreTray 组托信息
     */
    public void createTrayNoMk(FbTurnstoreTray fbTurnstoreTray, ProductAssemblyRule productRule) {
        //规则匹配托号
        //P222080707   P写死 1，2，3是从工厂数据过来，时间就是当前的年月，流水号：就是当前的组托顺序，保留4位，最高是9999，查询最近一次的组托流水码

        //根据月日构建流水号的key
        String key4 = "FBOrderNum4";
        long nyTime = System.currentTimeMillis() - 30600000;
        String nyTimeStr = new SimpleDateFormat("MM").format(nyTime);
        key4 = key4 + nyTimeStr;

        //关于当天的流水号标志
        String keyDt = "FBOrderNum4DT";

        StringBuilder trayNo = new StringBuilder();
        StringBuilder classNo = new StringBuilder();
        //白班标志
        String bbbz = "白班";
        trayNo.append("Y");

        //工厂名称/dictionaryItem
        String factoryName = fbTurnstoreTray.getFactoryName();
        trayNo.append(factoryName);

        //日期获取
        long time = new DateUtil().getChangeShiftsTime().getTime();
        Calendar cal = Calendar.getInstance();
        if (System.currentTimeMillis() < time) {
            cal.add(Calendar.DATE, -1);
            bbbz = "夜班";
        } else {
            cal.add(Calendar.DATE, 0);
        }
        String date = new SimpleDateFormat("yyMM").format(cal.getTime());
        trayNo.append(date);
        String classDate = new SimpleDateFormat("MMdd").format(cal.getTime());
        String classDateTime = new SimpleDateFormat("HH:mm").format(cal.getTime());
        classNo.append(classDate);
        classNo.append(bbbz);
        classNo.append("第");

        //流水号
        String order4Num = null;
        String num4Value;
        //当天流水号
        String order4NumDt = null;
        String num4ValueDt;

        String num = null;
        if (redisTemplate.hasKey(key4)) {
            //先获取redis中的顺序号
            num4Value = (String) redisTemplate.opsForValue().get(key4);
            order4Num = String.valueOf(Integer.parseInt(num4Value) + 1);

            if (order4Num.length() == 1) {
                order4Num = "000" + order4Num;
            } else if (order4Num.length() == 2) {
                order4Num = "00" + order4Num;
            } else if (order4Num.length() == 3) {
                order4Num = "0" + order4Num;
            }
        } else {
            order4Num = "0001";
            //月初进行刷新
            String ordKey = "FBOrderNum4" + new DateUtil().getLastMonth();
            redisTemplate.delete(ordKey);
        }

        //当天流水号叠加
        if (redisTemplate.hasKey(keyDt)) {
            num4ValueDt = (String) redisTemplate.opsForValue().get(keyDt);
            order4NumDt = String.valueOf(Integer.parseInt(num4ValueDt) + 1);
            num = order4NumDt;
        } else {
            num = "1";
        }

        trayNo.append(order4Num);
        classNo.append(num);
        classNo.append("托");
        classNo.append(classDateTime);
        //判断拖号是否重复
        if (null != dao.checkTrayNo(trayNo.toString())) {
            throw new RuntimeException("错误，生成的拖号已存在");
        }

        //判断当天流水号是否重复
        if (null != dao.checkClassNo(classNo.toString())) {
            throw new RuntimeException("错误，生成的拖号已存在");
        }

        fbTurnstoreTray.setTrayNo(trayNo.toString());
        fbTurnstoreTray.setClassNo(classNo.toString());

        if (productRule.getStation() != null) {
            String[] radeArr = productRule.getSpecs().split("[*]");
            if (radeArr.length > 1) {
                String spc = radeArr[1];
                fbTurnstoreTray.setPrintBz(spc + "-" + num);
            }
        }

        redisTemplate.opsForValue().set(key4, order4Num);

        long timeLong;
        if (System.currentTimeMillis() < time) {
            //小于当天08:59:59,计算至当天08:59:59
            timeLong = time - System.currentTimeMillis();
        } else {
            //大于当天08:59:59,计算至第二天08:59:59点
            timeLong = new DateUtil().getCurrentDayEndTime().getTime() + 30600000 - System.currentTimeMillis();
        }
        if (timeLong > 1000) {
            fbTurnstoreTray.setOrderNum(Integer.parseInt(num));
            redisTemplate.opsForValue().set(keyDt, num, timeLong / 1000, TimeUnit.SECONDS);
        }
    }

    private void saveItemList(FbTurnstoreTray fbTurnstoreTray, List<FbTurnstoreTrayItem> items) {
        if (null == fbTurnstoreTray.getState()) {
            fbTurnstoreTray.setState(0);
        }
//        判断工单定向标识是否一致
        FbTurnstoreTrayItem fbTurnstoreTrayItem1 = items.get(0);
        FbCheckOutData fbCheckOutDataDb = fbCheckOutDataService.findDataByFbSectionNo(fbTurnstoreTrayItem1.getSectionNo());
        if (Objects.isNull(fbCheckOutDataDb)){
            throw new RuntimeException("该晶编号"+fbTurnstoreTrayItem1.getSectionNo()+"未在方棒检验数据库中查询到数据");
        }
        for (FbTurnstoreTrayItem item : items) {
            FbCheckOutData fbCheckOutData = fbCheckOutDataService.findDataByFbSectionNo(item.getSectionNo());
            if (Objects.isNull(fbCheckOutData)){
                throw new RuntimeException("该晶编号"+item.getSectionNo()+"未在方棒检验数据库中查询到数据");
            }
            if (!fbCheckOutDataDb.getZorientationind().equals(fbCheckOutData.getZorientationind())) {
                throw new RuntimeException("工单定向标识不一致");
            }
        }
        for (int i = 0; i < items.size(); i++) {
            /*if (9 == fbTurnstoreTray.getState()) {
                items.get(i).setState(fbTurnstoreTray.getState());
            }*/
            FbTurnstoreTrayItem fbTurnstoreTrayItem = items.get(i);
//            String batchNo = fbTurnstoreTrayItem.getBatchNo();
//            if (StringUtils.isNotBlank(batchNo) && (batchNo.startsWith("TCN") || batchNo.startsWith("TJN")) && batchNo.length() > 10) {
//                batchNo = batchNo.substring(0, 1) + "J" + batchNo.substring(2, 10);
//                fbTurnstoreTrayItem.setBatchNo(batchNo);
//            }
//            理论重量
            if (BigDecimal.ZERO.compareTo(fbTurnstoreTrayItem.getTheoryWeightFb()) >= 0) {
                throw new RuntimeException("理论重量不能小于等于0");
            }
            //序号
            if (null == fbTurnstoreTrayItem.getOrderNum()) {
                fbTurnstoreTrayItem.setOrderNum(i + 1);
            }
            //空操作人赋值
            if (null == fbTurnstoreTrayItem.getUser()) {
                if (null != fbTurnstoreTray.getUpdateUser()) {
                    fbTurnstoreTrayItem.setUser(fbTurnstoreTray.getUpdateUser());
                } else {
                    fbTurnstoreTrayItem.setUser(fbTurnstoreTray.getUser());
                }
            }
            fbTurnstoreTrayItem.setTrayId(fbTurnstoreTray.getId());
            fbTurnstoreTrayItem.setTrayNo(fbTurnstoreTray.getTrayNo());
            fbTurnstoreTrayItem.setState(fbTurnstoreTray.getState());//fixme 增加状态字段，保持跟外层的一致
            if (null != fbTurnstoreTray.getToWmsTime()) {
                fbTurnstoreTrayItem.setToWmsTime(fbTurnstoreTray.getToWmsTime());
            }
            if (null != fbTurnstoreTray.getTime()) {
                fbTurnstoreTrayItem.setTime(fbTurnstoreTray.getTime());
            }
            if (null != fbTurnstoreTray.getOperationTime()) {
                fbTurnstoreTrayItem.setOperationTime(fbTurnstoreTray.getOperationTime());
            }
            fbTurnstoreTrayItem.setFactoryName(fbTurnstoreTray.getFactoryName());
            fbTurnstoreTrayItem.setSectionNo(fbTurnstoreTrayItem.getSectionNo().toUpperCase());
            if (null == fbTurnstoreTrayItem.getTotalLength()) {
                fbTurnstoreTrayItem.setTotalLength(fbTurnstoreTrayItem.getLength());
            }
            //锁定为组托状态
            PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCode(fbTurnstoreTrayItem.getSectionNo());
            if (null != planProcessingOrder) {
                if ("退料".equals(fbTurnstoreTray.getHasGone())) {
                    planProcessingOrder.setStatus(EnumValuesFactory.PlanProcessingOrderStatus.已作废.getKey());
                } else {
                    planProcessingOrder.setStatus(EnumValuesFactory.PlanProcessingOrderStatus.组托.getKey());
                }
                planProcessingOrderService.saveOrUpdate(planProcessingOrder);
            }
            fbTurnstoreTrayItem.setFactoryName("5041");
            FbCheckOutData fbCheckOutData = fbCheckOutDataService.findDataByFbSectionNo(fbTurnstoreTrayItem.getSectionNo());
            if (Objects.nonNull(fbCheckOutData)) {
                fbTurnstoreTrayItem.setCarbonContentTail(fbCheckOutData.getWCarbonContent());
                fbTurnstoreTrayItem.setCarbonContentHead(fbCheckOutData.getTCarbonContent());
                fbTurnstoreTrayItem.setOxygenContentHead(fbCheckOutData.getTOxygenContent());
                fbTurnstoreTrayItem.setOxygenContentTail(fbCheckOutData.getWOxygenContent());
                //TCentreLife 头少子
                fbTurnstoreTrayItem.setLife(fbCheckOutData.getMeanCarrierLifetimeA());
                //w少子
                fbTurnstoreTrayItem.setWLifeMin(fbCheckOutData.getMeanCarrierLifetimeB());
                //头电阻 TRadialCentre tRadialCentre
                fbTurnstoreTrayItem.setTRadialCentre(fbCheckOutData.getMeanResistivityA());
                //尾电阻
                fbTurnstoreTrayItem.setWRadialCentre(fbCheckOutData.getMeanResistivityB());
                //有效长度
                fbTurnstoreTrayItem.setEffectiveLength(fbCheckOutData.getInstoreLengthFb());
                //入库长度
                fbTurnstoreTrayItem.setInstoreLengthFb(fbCheckOutData.getInstoreLengthFb());
                //实际重量
                fbTurnstoreTrayItem.setActualWeightFb(fbCheckOutData.getWeight());
//                等级码处理
                if (!fbTurnstoreTray.getLevelCode().equals(fbCheckOutData.getLevelCode())) {
                    throw new RuntimeException("单晶编号:" + fbTurnstoreTrayItem.getSectionNo() + "方棒检验数据库等级码与方棒组托中不一致");
                }
            }
            fbTurnstoreTrayItem.setReturnInspectionStatus(0);
            FbTurnstoreTrayItem fbTurnstoreTrayItemDb = fbTurnstoreTrayItemService.findBySectionNoAndReturnInspectionStatus(fbTurnstoreTrayItem.getSectionNo(), 1);
            if (Objects.nonNull(fbTurnstoreTrayItemDb)) {
                fbTurnstoreTrayItem.setReturnInspectionStatus(2);
            }
//            单晶组合关系
            if (StringUtils.isNotBlank(fbTurnstoreTrayItem.getSectionCompose())) {
                String sectionCompose = fbTurnstoreTrayItem.getSectionCompose().toUpperCase();
                fbTurnstoreTrayItem.setSectionCompose(sectionCompose);
            }
            fbTurnstoreTrayItemService.saveOrUpdate(fbTurnstoreTrayItem);
        }
    }

    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();
    }
}
