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


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
//import com.sw.mes.base.erp.entity.ReportSapRecord;
//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.FactoryModel;
import com.sw.mes.base.factory.init.service.CrystalMaterialRelationService;
import com.sw.mes.base.factory.init.service.FactoryModelService;
import com.sw.mes.base.factory.inspect.entity.FbAppearRule;
import com.sw.mes.base.factory.inspect.service.DefaultCrystalAttrService;
import com.sw.mes.base.factory.inspect.service.FbAppearRuleService;
import com.sw.mes.base.global.GlobalSwitch;
import com.sw.mes.base.global.SwitchConfig;
import com.sw.mes.base.system.dao.DictionaryItemDao;
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.dto.CurrentWipStorageStatusDto;
import com.sw.mes.base.workinprocess.dto.PlanProcessingOrderWipStorageDto;
import com.sw.mes.base.workinprocess.entity.PlanProcessingOrder;
import com.sw.mes.base.workinprocess.entity.WipStorage;
import com.sw.mes.base.workinprocess.service.PlanProcessingOrderService;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.config.rabbit.FbInspectDataBaseChangeAsync;
import com.sw.mes.config.rabbit.FbInspectDataMsgProducer;
import com.sw.mes.core.api.system.YbFeignClients;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.constant.Constants;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.*;
import com.sw.mes.core.dto.mes.pc.yb.YbInspectDataDto;
import com.sw.mes.core.entity.FbCheckOutData;
import com.sw.mes.core.enums.EnumValues;
import com.sw.mes.core.enums.EnumValuesFactory;
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.BeanUtil;
import com.sw.mes.core.utils.IpUtils;
import com.sw.mes.core.utils.NumberUtil;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.fb.aio.entity.GrindingBlanking;
import com.sw.mes.fb.aio.service.EapGrindingMachineService;
import com.sw.mes.fb.aio.service.GrindingBlankingService;
import com.sw.mes.fb.checkout.dao.FbCheckOutRecordDao;
import com.sw.mes.fb.checkout.dao.FbJoinDao;
import com.sw.mes.fb.checkout.dao.RecutDetailDao;
import com.sw.mes.fb.checkout.dto.FbCheckOutRecordDto;
import com.sw.mes.fb.checkout.dto.Flag4MDto;
import com.sw.mes.fb.checkout.entity.FbCheckOutRecord;
import com.sw.mes.fb.checkout.entity.FbJoin;
import com.sw.mes.fb.checkout.entity.OperateCheckOutDataLog;
import com.sw.mes.fb.checkout.entity.RecutDetail;
import com.sw.mes.fb.checkout.service.FbCheckOutDataService;
import com.sw.mes.fb.checkout.service.FbCheckOutRecordService;
import com.sw.mes.fb.checkout.service.FbJoinService;
import com.sw.mes.fb.checkout.service.OperateCheckOutDataLogService;
import com.sw.mes.fb.turnstore.entity.FbTurnstoreTrayItem;
import com.sw.mes.fb.turnstore.entity.RecheckInspectReceiveDetail;
import com.sw.mes.fb.turnstore.service.FbTurnstoreTrayItemService;
import com.sw.mes.fb.turnstore.service.RecheckInspectReceiveDetailService;
import com.sw.mes.grade.service.GradeService;
import com.sw.mes.gread.service.FieldPoolService;
import com.sw.mes.mcs.dto.NoDetectionDto;
import com.sw.mes.plan.entity.FbProductionOrder;
import com.sw.mes.plan.service.FbProductionOrderService;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

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


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Service
@Transactional
@Slf4j
public class FbCheckOutRecordServiceImpl extends BaseServiceImpl<FbCheckOutRecord> implements FbCheckOutRecordService {
    FbCheckOutRecordDao dao;

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

    @Autowired
    private FbInspectDataMsgProducer fbInspectDataMsgProducer;

    @Autowired
    private RecutDetailDao recutDetailDao;

    @Resource
    private YbFeignClients ybFeignService;

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private FbJoinDao fbJoinDao;

    @Autowired
    private DictionaryItemDao dictionaryItemDao;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private FbCheckOutDataService fbCheckOutDataService;

    @Autowired
    private FbCheckOutRecordService fbCheckOutRecordService;

    @Autowired
    private DictionaryItemService dictionaryItemService;

    @Autowired
    private FactoryModelService factoryModelService;

    @Autowired
    private GradeService gradeService;

    @Autowired
    private DefaultCrystalAttrService defaultCrystalAttrService;

    @Autowired
    private OperateCheckOutDataLogService operateCheckOutDataLogService;

    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;

    @Autowired
    private GrindingBlankingService grindingBlankingService;

    @Autowired
    private FbAppearRuleService fbAppearRuleService;

    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private FbInspectDataBaseChangeAsync fbInspectDataBaseChangeAsync;

    @Autowired
    private EapGrindingMachineService eapGrindingMachineService;

    @Autowired
    private FieldPoolService fieldPoolService;

    @Autowired
    private RecheckInspectReceiveDetailService receiveDetailService;

    @Autowired
    private YbFeignClients ybFeignClients;


    @Autowired
    private FbTurnstoreTrayItemService fbTurnstoreTrayItemService;


    @Autowired
    private FbJoinService fbJoinService;

    @Autowired
    private CrystalMaterialRelationService crystalMaterialRelationService;

    @Autowired
    private FbProductionOrderService fbProductionOrderService;

//    @Autowired
//    private ReportSapRecordService reportSapRecordService;


    /**
     * // 通过方棒编号去圆棒检验数据库查询对应数据
     *
     * @param sectionNofb
     * @return
     */
    @Override
    public Result getFbInfoBySectionNofb(String sectionNofb) {
        // 1.通过方棒编号去追溯表中找到对应的圆棒id 编号信息
        RecutDetail bySectionNoFb = recutDetailDao.findBySectionNoFb(sectionNofb);
        String monNo = "";
        Result<GetFbInfoDto> fbInfoByIdResult = ybFeignService.findFbInfoBySectionNoYb(sectionNofb);
        if (bySectionNoFb == null) {
            if (null == fbInfoByIdResult) {
                //为代工数据提供查询
                return ResultGenerator.fail("该方棒" + sectionNofb + "不存在，无法录入数据");
            }
        } else {
            fbInfoByIdResult = ybFeignService.findFbInfoBySectionNoYb(bySectionNoFb.getSectionNo());
        }
        //2.根据圆棒ID编号信息，找到圆棒的相关属性信息
        if (fbInfoByIdResult.getCode() != ResultCode.SUCCESS.getCode()) {
            return ResultGenerator.fail(fbInfoByIdResult.getMessage());
        }
        GetFbInfoDto fbInfoById = fbInfoByIdResult.getData();
        //3.设置方棒编号
        fbInfoById.setFbSectionNo(sectionNofb);

        //4.根据方棒编号查询方棒反切画线明细记录，设置方棒长度
        String length = dao.getProductionPaintingLineDetail(sectionNofb);
        log.info("【{}】方棒长度【{}】,划线长度【{}】", fbInfoById.getFbSectionNo(), fbInfoById.getLength(), length);
        if (length != null) {
            fbInfoById.setLength(new BigDecimal(length));
        }
        log.info("【{}】方棒长度为【{}】,划线长度为【{}】", fbInfoById.getFbSectionNo(), fbInfoById.getLength(), length);

        //查询晶段最后一条工单
//        PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCodeAndOrderType(sectionNofb,3);
//        if (planProcessingOrder != null && planProcessingOrder.getLength() != null && planProcessingOrder.getLength().compareTo(BigDecimal.ZERO) > 0){
//            fbInfoById.setLength(planProcessingOrder.getLength());
//        }
        //5.设置圆棒生成的产品实验等级
        if (fbInfoById.getYbExperiLevel() == null) {
            fbInfoById.setYbExperiLevel(fbInfoById.getProductLevelExperiment());
        }
//        fbInfoById.setSpecification(fbInfoById.getProductTypeSecond());
        // TODO: specificationOption 2022/3/11 暂时写死，后期改为eap采集
        //6.根据圆棒的规则，进行逻辑的计算，得出方棒的规格
        if (fbInfoById.getProductTypeSecond() != null) {
            fbInfoById.setSpecification(fbInfoById.getProductTypeSecond());
        }

        // 7.拼棒信息(未解绑)
        FbJoin byGroupNo = fbJoinDao.findByGroupNoAndState(sectionNofb, 0);
        if (byGroupNo != null) {
            fbInfoById.setSticksCount(byGroupNo.getStickCount());
            fbInfoById.setSpellBarLength(byGroupNo.getTotalLength());
            fbInfoById.setSectionCompose(byGroupNo.getSectionNoGroup());
        }

//        Boolean spotCheck = fbCheckOutDataService.isSpotCheck(sectionNofb);
//        fbInfoById.setIsFbSizeCheck(spotCheck);


        //8.根据站点信息，来判断领料来源和检验类型
        String type = EnumValues.CheckoutName.一次检验.getValue();
        String materialSourceName = EnumValues.MaterialSourceName.磨削机.getValue();
        //上一站是粘方棒来的。检验的时候，就是粘方棒复检
        Result<WipStorage> wipStorageResult = wipStorageService.selectLastWipStorageResult(sectionNofb);
        if (wipStorageResult.getCode().equals(ResultCode.SUCCESS.getCode())) {
            FactoryModel factoryModel = factoryModelService.get(wipStorageResult.getData().getProcessId());
            if (factoryModel == null) {
                throw new BusinessException("当前工序不存在，请检查数据");
            }
            fbInfoById.setDeviceNo(wipStorageResult.getData().getEquipmentCode());
            EnumValuesFactory.WipStorageCode cWipStorageCode = EnumValuesFactory.WipStorageCode.getEnum(factoryModel.getCode());
            //查询方棒检验数据库
            FbCheckOutData fbCheckOutData = fbCheckOutDataService.findDataByFbSectionNo(sectionNofb);
            switch (cWipStorageCode) {
                case 开方:
                    type = fbCheckOutData == null ? EnumValues.CheckoutName.一次检验.getValue() : EnumValues.CheckoutName.返修复检.getValue();
                    materialSourceName = EnumValues.MaterialSourceName.磨削机.getValue();
                    break;
                case 圆棒截断:
                    type = EnumValues.CheckoutName.返切复检.getValue();
                    materialSourceName = EnumValues.MaterialSourceName.切断.getValue();
                    break;
                case 毛棒截断:
                    type = EnumValues.CheckoutName.返切复检.getValue();
                    materialSourceName = EnumValues.MaterialSourceName.切断.getValue();
                    break;
                case 方棒截断:
                    type = EnumValues.CheckoutName.返切复检.getValue();
                    materialSourceName = EnumValues.MaterialSourceName.切断.getValue();
                    break;
                case 方棒检验:
                    //是否分段返切
                    type = EnumValues.CheckoutName.返切复检.getValue();
                    Result<Map<String, Object>> detailByNo = ybFeignClients.findDetailByNo(sectionNofb);
                    if (null != detailByNo.getData() && !detailByNo.getData().isEmpty()) {
                        if (null != detailByNo.getData().get("reason") && "过长分段".equals(detailByNo.getData().get("reason"))) {
                            type = EnumValues.CheckoutName.分段复检.getValue();
                        }
                        if (null != detailByNo.getData().get("segment_no")) {
                            monNo = String.valueOf(detailByNo.getData().get("segment_no"));
                        }
                    }
                    materialSourceName = EnumValues.MaterialSourceName.切断.getValue();
                    break;
//                case 方棒检验:
//
//                    break;
                case 综计WMS:
                    type = fbCheckOutData.getCheckType() == null ? null : fbCheckOutData.getCheckType();
                    materialSourceName = EnumValues.MaterialSourceName.WMS.getValue();
                    break;
                case 粘方棒:
                    type = EnumValues.CheckoutName.粘方棒复检.getValue();
                    materialSourceName = EnumValues.MaterialSourceName.粘方棒.getValue();
                    break;
                default:
                    type = EnumValues.CheckoutName.一次检验.getValue();
            }
        }
        //9．根据方棒检验类型，从字典表中获取检验类型和检验ＩＤ
        List<DictionaryItem> dictionaryItem1s = dictionaryItemService.findByThemeValueAndItemName("FbCheckType", type, true);
        if (dictionaryItem1s.size() <= 0) {
            throw new BusinessException("未查询到【" + type + "】对应的字典配置，请检查数据字典【方棒检验类型】配置是否正确");
        }
        fbInfoById.setCheckoutName(dictionaryItem1s.get(0).getName());
        fbInfoById.setCheckoutId(dictionaryItem1s.get(0).getId());

        //10．根据方棒领料来源，从字典表中获取领料来源Name和领料来源渠道
        List<DictionaryItem> dictionaryItems = dictionaryItemService.findByThemeValueAndItemName("ReceiveMaterials", materialSourceName, true);
        if (dictionaryItems.size() <= 0) {
            throw new BusinessException("未查询到【" + materialSourceName + "】对应的字典配置，请检查数据字典【方棒领料来源】配置是否正确");
        }
        fbInfoById.setMaterialSourceName(dictionaryItems.get(0).getName());
        fbInfoById.setMaterialSourceValue(dictionaryItems.get(0).getValue());

        //11.根据规则，判断是否需要抽检赋值
        Flag4MDto flag4MDto = whetherOrNotSampling(sectionNofb);
        if (flag4MDto != null && materialSourceName == "磨削机") {
            //外观检验是否抽检赋值
            fbInfoById.setIsFbSizeCheck(flag4MDto.getFlagSizeCheck());
            //是否4M
            fbInfoById.setFlag4M(flag4MDto.getFlag4M() ? "1" : "0");
        } else {
            //外观检验是否抽检赋值
            fbInfoById.setIsFbSizeCheck(false);
            //是否4M
            fbInfoById.setFlag4M("0");
        }

        //12.根据拼帮的情况，从ＥＡＰ中获取一体机的编号，进行赋值
        List<String> listSN = new ArrayList<>();
        if (fbInfoById.getSticksCount() != null && fbInfoById.getSticksCount() > 1) {
            listSN = Arrays.asList(fbInfoById.getSectionCompose().split(","));
        } else {
            listSN.add(sectionNofb);
        }
        for (String nofb : listSN) {
            //磨削下料记录
            GrindingBlanking topByFbSectionNoOrderByIdDesc = grindingBlankingService.findTopByFbSectionNoOrderByIdDesc(nofb);
            if (topByFbSectionNoOrderByIdDesc != null && StringUtils.isNoneBlank(topByFbSectionNoOrderByIdDesc.getEquipNo())) {
                //赋值一体机编号
                fbInfoById.setDeviceNo(topByFbSectionNoOrderByIdDesc.getEquipNo());
                //赋边长和直径
                fbInfoById.setEapDiameterMax(topByFbSectionNoOrderByIdDesc.getEapDiameterMax());
                fbInfoById.setEapDiameterMin(topByFbSectionNoOrderByIdDesc.getEapDiameterMin());
//                List<BigDecimal> sides = Arrays.asList(topByFbSectionNoOrderByIdDesc.getEapSide1(), topByFbSectionNoOrderByIdDesc.getEapSide2(), topByFbSectionNoOrderByIdDesc.getEapSide3(), topByFbSectionNoOrderByIdDesc.getEapSide4(), topByFbSectionNoOrderByIdDesc.getEapSide5(), topByFbSectionNoOrderByIdDesc.getEapSide6());
//                BigDecimal maxSide = sides.stream().max(BigDecimal::compareTo).get();
//                BigDecimal minSide = sides.stream().min(BigDecimal::compareTo).get();
                fbInfoById.setEapSideMin(topByFbSectionNoOrderByIdDesc.getBeforhdd12());
                fbInfoById.setEapSideMax(topByFbSectionNoOrderByIdDesc.getBeforhud12());
                break;
            }
        }
        //更新数据
        if (StringUtils.isNotBlank(monNo)) {
            //获取母单晶数据
            FbCheckOutData dataByFbSectionNo = fbCheckOutDataService.findDataByFbSectionNo(monNo);
            if (null != dataByFbSectionNo) {
                if (null == fbInfoById.getEapDiameterMax() && null != dataByFbSectionNo.getEapDiameterMax()) {
                    fbInfoById.setEapDiameterMax(dataByFbSectionNo.getEapDiameterMax());
                }
                if (null == fbInfoById.getEapDiameterMin() && null != dataByFbSectionNo.getEapDiameterMin()) {
                    fbInfoById.setEapDiameterMin(dataByFbSectionNo.getEapDiameterMin());
                }
                if (null == fbInfoById.getEapSideMin() && null != dataByFbSectionNo.getEapSideMin()) {
                    fbInfoById.setEapSideMin(dataByFbSectionNo.getEapSideMin());
                }
                if (null == fbInfoById.getEapSideMax() && null != dataByFbSectionNo.getEapSideMax()) {
                    fbInfoById.setEapSideMax(dataByFbSectionNo.getEapSideMax());
                }
                if (null == fbInfoById.getSideLengthMax() && null != dataByFbSectionNo.getSideLengthMax()) {
                    fbInfoById.setSideLengthMax(dataByFbSectionNo.getSideLengthMax());
                }
                if (null == fbInfoById.getSideLengthMin() && null != dataByFbSectionNo.getSideLengthMin()) {
                    fbInfoById.setSideLengthMin(dataByFbSectionNo.getSideLengthMin());
                }
                if (null == fbInfoById.getDiameterMax() && null != dataByFbSectionNo.getDiameterMax()) {
                    fbInfoById.setDiameterMax(dataByFbSectionNo.getDiameterMax());
                }
                if (null == fbInfoById.getDiameterMin() && null != dataByFbSectionNo.getDiameterMin()) {
                    fbInfoById.setDiameterMin(dataByFbSectionNo.getDiameterMin());
                }
                if (null == fbInfoById.getVerticalityMax() && null != dataByFbSectionNo.getVerticalityMax()) {
                    fbInfoById.setVerticalityMax(dataByFbSectionNo.getVerticalityMax());
                }
                if (null == fbInfoById.getVerticalityMin() && null != dataByFbSectionNo.getVerticalityMin()) {
                    fbInfoById.setVerticalityMin(dataByFbSectionNo.getVerticalityMin());
                }
                if (null == fbInfoById.getChordLengthMax() && null != dataByFbSectionNo.getChordLengthMax()) {
                    fbInfoById.setChordLengthMax(dataByFbSectionNo.getChordLengthMax());
                }
                if (null == fbInfoById.getChordLengthMin() && null != dataByFbSectionNo.getChordLengthMin()) {
                    fbInfoById.setChordLengthMin(dataByFbSectionNo.getChordLengthMin());
                }
            }
        }
        log.info("【{}】方棒长度为【{}】", fbInfoById.getFbSectionNo(), fbInfoById.getLength());

        return ResultGenerator.success(fbInfoById);
    }


    @Override
    public FbCheckOutRecord findFbCheckOutRecord(String sectionNofb) {
        List<FbCheckOutRecord> list = this.dao.findFbSecitonNo(sectionNofb);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<FbCheckOutRecord> findAllFbCheckOutRecord(String sectionNofb) {
        List<FbCheckOutRecord> list = this.dao.findAllFbCheckOutRecord(sectionNofb);
        if (list != null && list.size() > 0) {
            return list;
        }
        return null;
    }

    @Override
    public void saveAll(List<FbCheckOutRecord> fbCheckOutRecords) {
        dao.saveAll(fbCheckOutRecords);
    }


    // 删除方棒检验数据
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteFbInspect(Long[] ids) {
        for (Long id : ids) {

            FbCheckOutRecord fbCheckOutRecord = new FbCheckOutRecord();
            FbCheckOutRecord fbCheckOutRecord1 = fbCheckOutRecordService.get(id);
            FbCheckOutData fbCheckOutData = fbCheckOutDataService.findDataByFbSectionNo(fbCheckOutRecord1.getFbSectionNo());
            PlanProcessingOrderWipStorageDto planProcessingOrderWipStorageDto = wipStorageService.selectWipStorage(fbCheckOutData.getFbSectionNo(), EnumValuesFactory.WipStorageCode.方棒检验.getKey(), true);

            if (planProcessingOrderWipStorageDto != null) {
                //查询工单是否为组托状态，组托状态下不允许删除
                PlanProcessingOrder planProcessingOrder = planProcessingOrderWipStorageDto.getPlanProcessingOrder();
                if (planProcessingOrder != null && planProcessingOrder.getStatus() == EnumValuesFactory.PlanProcessingOrderStatus.组托.getKey()) {
                    return ResultGenerator.fail(fbCheckOutData.getFbSectionNo() + "已在" + EnumValuesFactory.PlanProcessingOrderStatus.组托.getValue() + "状态，不允许删除。");
                }
                WipStorage wipStorage = planProcessingOrderWipStorageDto.getWipStorage();
                wipStorage.setStatus(EnumValuesFactory.WipStorageStatus.待进站.getKey());
                this.wipStorageService.saveOrUpdate(wipStorage);
            } else {
                throw new BusinessException("【" + fbCheckOutData.getFbSectionNo() + "】工单号不存在");
            }

            fbCheckOutDataService.delete(fbCheckOutData.getId());
            fbCheckOutRecordService.delete(id);
//            FbCheckOutRecord fbCheckOutRecord = new FbCheckOutRecord();
//            BeanUtil.copyBeanPropWithOutNullValue(fbCheckOutRecord, fbCheckOutData, "id");
//            //2删除操作
//            fbCheckOutRecord.setOperateType("2");
//            fbCheckOutRecord.setId(id.intValue());
//            fbCheckOutRecord.setCheckTime(new Date());
//            fbCheckOutRecord.setCheckUserName(BaseContextHandler.getUsername());
//            this.saveOrUpdate(fbCheckOutRecord);

            this.delete(id.intValue());
        }
        return ResultGenerator.success();
    }


    /**
     * 修改获取 修改时获取方棒检验数据库信息的检验类型以及领料来源
     *
     * @param sectionNoFb
     * @return
     */
    @Override
    public Result updateGetCheckType(String sectionNoFb) {
        FbCheckOutData dataByFbSectionNo = this.fbCheckOutDataService.findDataByFbSectionNo(sectionNoFb);
        Map<String, Object> map = new HashMap<>();
        if (null != dataByFbSectionNo) {
            map.put("checkName", dataByFbSectionNo.getCheckType());
            if (StringUtils.isNotBlank(dataByFbSectionNo.getCheckType()) && (dataByFbSectionNo.getCheckType().equals("退货复检") || dataByFbSectionNo.getCheckType().equals("退库复检"))) {
                map.put("materialSourceValue", "WMS");
            } else {
                map.put("materialSourceValue", "磨削机");
            }

        }
        return ResultGenerator.success(map);
    }

    @Override
    public void saveOrUpdateFbCheckOutRecord(FbCheckOutRecord fbCheckOutRecord, Boolean updateFlag, Boolean flag) {
        String point = fbCheckOutRecord.getPoint();
        //1.初始化检验记录,设置检验员，检验时间，修改人，修改时间
        this.initFbCheckOutRecord(fbCheckOutRecord);

        Date date = new Date();
        //边距字段赋值
        if (null != fbCheckOutRecord.getSideLengthRange() && !fbCheckOutRecord.getSideLengthRange().isEmpty()) {
            String sideLengthRange = fbCheckOutRecord.getSideLengthRange();

            List<DictionaryItem> items = dictionaryItemService.findByThemeValueAndItemName("sideLengthRange", sideLengthRange, true);
            if (items.size() > 0) {
                DictionaryItem item = items.get(0);

                if (item.getValue().contains("-")) {
                    String[] sideLengthRanges = item.getValue().split("-");
                    if (null != sideLengthRanges && sideLengthRanges.length == 2) {
                        fbCheckOutRecord.setSideLengthRangeMin(sideLengthRanges[0]);
                        fbCheckOutRecord.setSideLengthRangeMax(sideLengthRanges[1]);
                    }
                } else if (item.getValue().contains("~")) {
                    String[] sideLengthRanges = item.getValue().split("~");
                    if (null != sideLengthRanges && sideLengthRanges.length == 2) {
                        fbCheckOutRecord.setSideLengthRangeMin(sideLengthRanges[0]);
                        fbCheckOutRecord.setSideLengthRangeMax(sideLengthRanges[1]);
                    }
                }
            }
        }

        //2.查询当前站点信息
        Result<CurrentWipStorageStatusDto> currentWipStorageStatusDtoResult = wipStorageService.selectWipStorageResult(fbCheckOutRecord.getFbSectionNo());
        if (currentWipStorageStatusDtoResult.getCode() != 200) {
            throw new BusinessException(currentWipStorageStatusDtoResult.getMessage());
        }
        CurrentWipStorageStatusDto currentWipStorageStatusDto = currentWipStorageStatusDtoResult.getData();
//        if (!currentWipStorageStatusDto.getWipStorageCode().equals(EnumValuesFactory.WipStorageCode.方棒检验.getKey())) {
//            throw new BusinessException("当前站点不在方棒检验，不能录入检验数据");
//        }
        //todo start 3.补充氧碳数据：用于判断当前单晶前后两端是否有合格的氧碳含量，没有则评级异常
       /* try {
            List<DictionaryItem> isSampleValue = dictionaryItemDao.findByThemeValueAndEnable("isSampleValue", true);
            if(!CollectionUtils.isEmpty(isSampleValue)){
                DictionaryItem dictionaryItem = isSampleValue.get(0);
                if(dictionaryItem.getValue().equals("0")){
                    supData1(fbCheckOutRecord);
                } else {
                    supData(fbCheckOutRecord);
                }
            } else {
                supData1(fbCheckOutRecord);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("方棒赋值氧碳数据发生错误" + e.getMessage());
        }*/
        supData1(fbCheckOutRecord);
        //todo end ==========================================================================
        FbCheckOutData fbCheckOutData = null;
        //待进站为新增数据，已进站修改数据
        if (currentWipStorageStatusDto.getWipStorageCode().equals(EnumValuesFactory.WipStorageCode.方棒检验.getKey())
                && currentWipStorageStatusDto.getWipStorageStatus() == EnumValuesFactory.WipStorageStatus.待进站.getKey()) {
            //新增
            updateFlag = false;
            Result result = wipStorageService.inStation(fbCheckOutRecord.getFbSectionNo(), null, false);
            if (result.getCode() != ResultCode.SUCCESS.getCode()) {
                throw new BusinessException("进站失败：" + result);
            }
        } else {
            updateFlag = true;
        }

        if (updateFlag) {
            //修改
            fbCheckOutRecord.setOperateType("1");
            fbCheckOutData = initFbCheckOutData(fbCheckOutRecord, false, flag);
        } else {
            fbCheckOutRecord.setOperateType("0");
            fbCheckOutData = initFbCheckOutData(fbCheckOutRecord, true, flag);
        }
        //4晶段类型赋值
        this.setSectionType(fbCheckOutData);

        //5外观异常录入默认值
        this.setAppearanceDefaults(fbCheckOutData, fbCheckOutRecord);

        //6方棒基础信息默认值
        this.setDefaultsInfo(fbCheckOutData, fbCheckOutRecord);

        //方棒检验赋值重量
        this.setWeightBySpecification(fbCheckOutRecord, fbCheckOutData);

        // 判空，防止返切之后保存未带入数据
        if (null == fbCheckOutRecord.getCheckTime()){
            fbCheckOutRecord.setCheckTime(date);
        }
        if(null == fbCheckOutRecord.getSticksCount()){
            fbCheckOutRecord.setSticksCount(1);
        }
        if (StringUtils.isBlank(fbCheckOutRecord.getWorkOrderType()) && StringUtils.isNotBlank(fbCheckOutRecord.getWorkOrderNo())){
            FbProductionOrder fbProductionOrder= fbProductionOrderService.findByAufnr(fbCheckOutRecord.getWorkOrderNo());
            if (null != fbProductionOrder){
                fbCheckOutRecord.setWorkOrderType(fbProductionOrder.getAuart());
                if (StringUtils.isBlank(fbCheckOutData.getWorkOrderType())){
                    fbCheckOutData.setWorkOrderType(fbProductionOrder.getAuart());
                }
            }
        }

        this.saveOrUpdate(fbCheckOutRecord);
        fbCheckOutData.setExperiLevel(fbCheckOutRecord.getYbExperiLevel());
        Boolean isFbSizeCheck = fbCheckOutRecord.getIsFbSizeCheck();
        if (null != isFbSizeCheck) {
            fbCheckOutData.setFlag4M(isFbSizeCheck ? "1" : "0");
        }

        log.info("处理的方棒单晶:{}", JSONObject.toJSONString(fbCheckOutRecord));

        if(null == fbCheckOutData.getSticksCount()){
            fbCheckOutData.setSticksCount(1);
        }
        if (null == fbCheckOutData.getCheckTime()){
            fbCheckOutData.setCheckTime(date);
        }
        Result<YbInspectDataDto> ybInspectDataDtoResult = ybFeignClients.getInspectDataBaseBySectionNo(fbCheckOutRecord.getYbSectionNo());
        if (ybInspectDataDtoResult.getCode() == 200) {
            YbInspectDataDto ybInspectDataDto = ybInspectDataDtoResult.getData();
            if (null != ybInspectDataDto) {
                fbCheckOutData.setAgainNum(ybInspectDataDto.getAgainNum());
                fbCheckOutData.setActualLength(ybInspectDataDto.getActualLength());
            }
        }
        saveDataAndGrade(fbCheckOutData, point);
    }

    @Override
    public void saveDataAndGrade(FbCheckOutData fbCheckOutData, String point) {
        //评级
        try {
            fbCheckOutDataService.saveOrUpdate(fbCheckOutData);
            PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCode(fbCheckOutData.getFbSectionNo());
            if (null != planProcessingOrder && null != planProcessingOrder.getStatus()
                    && planProcessingOrder.getStatus() == EnumValuesFactory.PlanProcessingOrderStatus.加工中.getKey()){
                Map<String, FbCheckOutData> fbCheckOutDataMap = new HashMap<>();

                fbCheckOutDataMap.put(fbCheckOutData.getFbSectionNo(), fbCheckOutData);
                gradeService.execGrade(fbCheckOutDataMap);
                fbCheckOutData = fbCheckOutDataMap.get(fbCheckOutData.getFbSectionNo());
                //修改工单重量与长度
                updatePlanProcessingOrderInfo(fbCheckOutData.getFbSectionNo(), fbCheckOutData.getTheoryWeightFb(), fbCheckOutData.getLength());
                //检验数据发生变动
                fbInspectDataBaseChangeAsync.fbCheckOutDataChange(fbCheckOutData);
                // 不抽检下发MCS
                noDetection(fbCheckOutData, point);
            }



//            SwitchConfig config = GlobalSwitch.switchConfig(CODE_SWITCH, "knifeProfileWorker", false);
//
//            if (StringUtils.equals(fbCheckOutData.getGradeType(), "正常") && StringUtils.equals(fbCheckOutData.getSectionType(), "标棒") && config.isEnable()) {
//                BigDecimal bigDecimal;
//                if(fbCheckOutData.getWeight().compareTo(new BigDecimal(0)) > 0){
//                    bigDecimal = fbCheckOutData.getWeight();
//                } else {
//                    bigDecimal = fbCheckOutData.getTheoryWeightFb();
//                }
//                ReportSapRecord reportSapRecord = new ReportSapRecord();
//                reportSapRecord.setBatcnNo(fbCheckOutData.getBatchNo());
//                reportSapRecord.setBwart("101");
//                reportSapRecord.setCount(bigDecimal);
//                reportSapRecord.setFbSectionNo(fbCheckOutData.getFbSectionNo());
//                reportSapRecord.setMaterialCode(fbCheckOutData.getMaterialCode());
//                reportSapRecord.setOrderNo(fbCheckOutData.getOrderNo());
//                reportSapRecord.setProcName("刀剖收货");
//                reportSapRecord.setPushTime(new Date());
//                reportSapRecord.setPushType("报工");
//                reportSapRecord.setUnit("KG");
//                reportSapRecord.setUser(BaseContextHandler.getUsername());
//                reportSapRecordService.saveOrUpdate(reportSapRecord);
//
//                Result sendSquareRodInfoResult = ybFeignService.sendSquareRodInfo(fbCheckOutData.getFbSectionNo(), fbCheckOutData.getYbSectionNo(), bigDecimal, BaseContextHandler.getUsername());
//                log.info("方棒上报SAP数据结果为:{}", JSONObject.toJSONString(sendSquareRodInfoResult));
//                if (null == sendSquareRodInfoResult) {
//                    throw new RuntimeException("SAP产出返回为空！");
//                }
//                if (ResultCode.SUCCESS.getCode() != sendSquareRodInfoResult.getCode()) {
//                    throw new RuntimeException("SAP产出上报失败，异常信息为：" + sendSquareRodInfoResult.getMessage());
//                }
//            } else if (StringUtils.equals(fbCheckOutData.getGradeType(), "正常")) {
//                Result sendSquareRodInfoResult = ybFeignService.sendSquareRodInfo(fbCheckOutData.getFbSectionNo(), fbCheckOutData.getYbSectionNo(), fbCheckOutData.getTheoryWeightFb(), BaseContextHandler.getUsername());
//                log.info("方棒上报SAP数据结果为:{}", JSONObject.toJSONString(sendSquareRodInfoResult));
//                if (null == sendSquareRodInfoResult) {
//                    throw new RuntimeException("SAP产出返回为空！");
//                }
//                if (ResultCode.SUCCESS.getCode() != sendSquareRodInfoResult.getCode()) {
//                    throw new RuntimeException("SAP产出上报失败，异常信息为：" + sendSquareRodInfoResult.getMessage());
//                }
//            }


        } catch (Exception e) {
            throw new BusinessException("评级失败:" + e.getMessage());
        }
    }

    private void noDetection(FbCheckOutData fbCheckOutData, String point) {
        NoDetectionDto noDetectionDto = new NoDetectionDto();
        noDetectionDto.setPoint(point);
        noDetectionDto.setCrystalNo(fbCheckOutData.getFbSectionNo());
        noDetectionDto.setLength(fbCheckOutData.getLength());
        noDetectionDto.setConductiveType(fbCheckOutData.getConductionType());
        noDetectionDto.setSpecs(fbCheckOutData.getSpecification());
        noDetectionDto.setProductGrade(fbCheckOutData.getProductLevel());
        noDetectionDto.setProductType(getProductType(fbCheckOutData.getProductType()));
        noDetectionDto.setGradeType(fbCheckOutData.getGradeType());
        noDetectionDto.setSideLengthRange(fbCheckOutData.getSideLengthRange());
        noDetectionDto.setIsFbSizeCheck(fbCheckOutData.getIsFbSizeCheck());
        fbInspectDataBaseChangeAsync.noDetection(noDetectionDto);
    }
    /**
     * 规格转换
     */
    private String getProductType(String productType) {
        List<DictionaryItem> toMCSProductSpec = dictionaryItemService.findByThemeValueAndEnable("ToMCSProductSpec", true);
        Map<String, DictionaryItem> specMap = toMCSProductSpec.stream().collect(Collectors.toMap(DictionaryItem::getName, Function.identity(), (t1, t2) -> t1));
        if (specMap.containsKey(productType)) {
            return specMap.get(productType).getValue();
        } else {
            return "0";
        }
    }
    private void supData1(FbCheckOutRecord fbCheckOutRecord) {

        String ybSectionNo = fbCheckOutRecord.getYbSectionNo();
        Result<YbInspectDataDto> ybInspectData = ybFeignClients.getYbInspectData(ybSectionNo);
        if (ybInspectData.getCode().equals(ResultCode.SUCCESS.getCode())) {
            YbInspectDataDto data = ybInspectData.getData();
            fbCheckOutRecord.setMeanCarrierLifetimeA(data.getMeanCarrierLifetimeA());
            fbCheckOutRecord.setMeanCarrierLifetimeB(data.getMeanCarrierLifetimeB());
            fbCheckOutRecord.setMeanResistivityA(data.getMeanResistivityA());
            fbCheckOutRecord.setMeanResistivityB(data.getMeanResistivityB());
            fbCheckOutRecord.setClosureIdentification(data.getClosureIdentification());
            fbCheckOutRecord.setFormulation(data.getFormulation());
           /* if (null == data.getOxygenContentHead() || null == data.getCarbonContentHead()){
                throw new RuntimeException("圆棒头氧含量中心或头碳含量中心未检测出，请先核对晶棒头片是否检验出!");
            }
            if (null == data.getOxygenContentTail() || null == data.getCarbonContentTail()){
                throw new RuntimeException("圆棒尾氧含量中心或尾碳含量中心未检测出，请先核对晶棒尾片是否检验出!");
            }*/
            if (null != data.getOxygenContentHead()) {
                fbCheckOutRecord.setHeadOxygenContents(data.getOxygenContentHead());
            }
            if (null != data.getOxygenContentTail()) {
                fbCheckOutRecord.setTailOxygenContents(data.getOxygenContentTail());
            }
        } else {
          /*  fbCheckOutRecord.setHeadOxygenContents(null);
            fbCheckOutRecord.setTailOxygenContents(null);*/
            throw new RuntimeException("未查询到圆棒检验信息!");
        }
    }

    private void supData(FbCheckOutRecord fbCheckOutRecord) {
        //todo 改这里面的内容
        String fromMark = fbCheckOutRecord.getFbSectionNo().substring(SectionIndexRangeEnum.基地追溯产品类型.getBeginIndex(), SectionIndexRangeEnum.基地追溯产品类型.getEndIndex());
        if (fromMark.matches("[A-Z]+")) {
            String substring = fbCheckOutRecord.getFbSectionNo().substring(SectionIndexRangeEnum.毛棒范围.getBeginIndex(), SectionIndexRangeEnum.毛棒范围.getEndIndex());
            Result<List<PieceCheckDto1>> byMotherCrystalNo = ybFeignClients.getSampleData(substring);
            Result<List<DataInspectLogDto>> dataByCrystalNo = ybFeignClients.getDataByCrystalNo(substring);
            Result<LongCrystalDto1> crystalData = ybFeignClients.getCrystalData(substring);
            String segmentNumber = fbCheckOutRecord.getFbSectionNo().substring(SectionIndexRangeEnum.截断数.getBeginIndex(), SectionIndexRangeEnum.截断数.getEndIndex()).toUpperCase();
            //非尾段单晶赋值氧含量
            if (null != byMotherCrystalNo.getData() && byMotherCrystalNo.getData().size() > 0 && null != dataByCrystalNo.getData() && dataByCrystalNo.getData().size() > 0 && null != crystalData.getData() && !segmentNumber.equals("W")) {
                //判断单晶是否为循环段
//            if(!StringUtils.isBlank(crystalData.getData().getClosureIdentification())){
//            需要获取头片氧含量数据 并且头片段号不能大于当前单晶的段号
                List<PieceCheckDto1> pieceList = byMotherCrystalNo.getData().stream().filter(pieceCheckDto1 -> !pieceCheckDto1.getPieceNo().substring(SectionIndexRangeEnum.截断数.getBeginIndex(), SectionIndexRangeEnum.截断数.getEndIndex()).toUpperCase().contains("W")
                        && ((!"T".equals(pieceCheckDto1.getPieceNo().substring(SectionIndexRangeEnum.截断数.getBeginIndex(), SectionIndexRangeEnum.截断数.getEndIndex()).toUpperCase())
                        && Integer.valueOf(pieceCheckDto1.getPieceNo().substring(SectionIndexRangeEnum.截断数.getBeginIndex(), SectionIndexRangeEnum.截断数.getEndIndex())) <= Integer.valueOf(segmentNumber))
                        || "T".equals(pieceCheckDto1.getPieceNo().substring(SectionIndexRangeEnum.截断数.getBeginIndex(), SectionIndexRangeEnum.截断数.getEndIndex()).toUpperCase()))).collect(Collectors.toList());
                //T2BP0011R51TP、T2BP0011R511P、T2BP0011R512P、T2BP0011R51WP
                //实验单晶每段都取片 当前单晶取对应的片数据
                Boolean key = false;
                List<PieceCheckDto1> list = new ArrayList<>();
                if (null != pieceList && pieceList.size() > 0) {
                    for (int i = 0; i < pieceList.size(); i++) {
                        if (pieceList.get(i).getPieceNo().substring(SectionIndexRangeEnum.截断数.getBeginIndex(), SectionIndexRangeEnum.截断数.getEndIndex()).toUpperCase().equals(segmentNumber)) {
                            list.add(pieceList.get(i));
                            key = true;
                        }
                    }
                    if (key) {
                        list.sort(Comparator.comparing(PieceCheckDto1::getCheckTime2).reversed());
                        fbCheckOutRecord.setHeadOxygenContents(list.get(0).getOContents());
                    } else {
                        //常规单晶只取头片，头片不合格继续取片，取最新的片数据
                        pieceList.sort(Comparator.comparing(PieceCheckDto1::getCheckTime2).reversed());
                        fbCheckOutRecord.setHeadOxygenContents(pieceList.get(0).getOContents());
                    }
                } else {
                    fbCheckOutRecord.setHeadOxygenContents(null);
                }
                //todo  到这个位置就可以了
//                获取尾氧含量数据
                if ((!StringUtils.isBlank(crystalData.getData().getClosureIdentification()) && !crystalData.getData().getClosureIdentification().contains("完结"))
                        || StringUtils.isBlank(crystalData.getData().getClosureIdentification())) {
//                循环段单晶后端取当前圆棒检验数据的尾氧含量即可（循环段除头段外氧含量默认合格值）
                    List<DataInspectLogDto> collect = dataByCrystalNo.getData().stream().filter(dataInspectLogDto -> dataInspectLogDto.getSectionNo().substring(SectionIndexRangeEnum.截断数.getBeginIndex(), SectionIndexRangeEnum.截断数.getEndIndex()).equals(segmentNumber)).collect(Collectors.toList());
                    if (null != collect && collect.size() > 0) {
                        collect.sort(Comparator.comparing(DataInspectLogDto::getId).reversed());
                        DataInspectLogDto dataInspectLogDto = collect.get(0);
                        fbCheckOutRecord.setTailOxygenContents(dataInspectLogDto.getOxygenContentTail());
                    } else {
                        fbCheckOutRecord.setTailOxygenContents(null);
                    }
                } else {
//                完结单晶后端取尾片数据，尾片不合格继续取片，取最新的尾数据
                    List<PieceCheckDto1> pieceList1 = byMotherCrystalNo.getData().stream().filter(pieceCheckDto1 -> pieceCheckDto1.getPieceNo().substring(SectionIndexRangeEnum.截断数.getBeginIndex(), SectionIndexRangeEnum.截断数.getEndIndex()).toUpperCase().contains("W")
                            || (!"T".equals(pieceCheckDto1.getPieceNo().substring(SectionIndexRangeEnum.截断数.getBeginIndex(), SectionIndexRangeEnum.截断数.getEndIndex()).toUpperCase())
                            && Integer.valueOf(pieceCheckDto1.getPieceNo().substring(SectionIndexRangeEnum.截断数.getBeginIndex(), SectionIndexRangeEnum.截断数.getEndIndex())) >= Integer.valueOf(segmentNumber))).collect(Collectors.toList());
                    if (null != pieceList1 && pieceList1.size() > 0) {
                        pieceList1.sort(Comparator.comparing(PieceCheckDto1::getCheckTime2).reversed());
                        fbCheckOutRecord.setTailOxygenContents(pieceList1.get(0).getOContents());
                    } else {
                        fbCheckOutRecord.setTailOxygenContents(null);
                    }
                }
//            }
                //尾段单晶赋值氧含量
            } else if (null != byMotherCrystalNo.getData() && byMotherCrystalNo.getData().size() > 0 && null != dataByCrystalNo.getData() && dataByCrystalNo.getData().size() > 0 && null != crystalData.getData() && "W".equals(segmentNumber)) {
                //尾段尾氧含量取对应尾片尾氧含量
                if (!StringUtils.isBlank(crystalData.getData().getClosureIdentification()) && crystalData.getData().getClosureIdentification().contains("完结")) {
                    List<PieceCheckDto1> pieceList1 = byMotherCrystalNo.getData().stream().filter(pieceCheckDto1 -> "W".equals(pieceCheckDto1.getPieceNo().toUpperCase())).collect(Collectors.toList());
                    if (null != pieceList1 && pieceList1.size() > 0) {
                        pieceList1.sort(Comparator.comparing(PieceCheckDto1::getCheckTime2).reversed());
                        fbCheckOutRecord.setTailOxygenContents(pieceList1.get(0).getOContents());
                    } else {
                        fbCheckOutRecord.setTailOxygenContents(null);
                    }
                } else {
                    //尾段尾氧含量取对应圆棒尾段尾氧含量
                    List<DataInspectLogDto> collect = dataByCrystalNo.getData().stream().filter(dataInspectLogDto -> "W".equals(dataInspectLogDto.getSectionNo().substring(SectionIndexRangeEnum.截断数.getBeginIndex(), SectionIndexRangeEnum.截断数.getEndIndex()).toUpperCase())).collect(Collectors.toList());
                    collect.sort(Comparator.comparing(DataInspectLogDto::getId).reversed());
                    if (null != collect && collect.size() > 0) {
                        fbCheckOutRecord.setTailOxygenContents(collect.get(0).getOxygenContentTail());
                    } else {
                        fbCheckOutRecord.setTailOxygenContents(null);
                    }
                }
                //尾段头氧含量取对应圆棒尾段的头氧即可
//                List<DataInspectLogDto> collect = dataByCrystalNo.getData().stream().filter(dataInspectLogDto -> "W".equals(dataInspectLogDto.getSectionNo().substring(SectionIndexRangeEnum.截断数.getBeginIndex(), SectionIndexRangeEnum.截断数.getEndIndex()).toUpperCase())).collect(Collectors.toList());
//                collect.sort(Comparator.comparing(DataInspectLogDto::getId).reversed());
//                if (null != collect && collect.size() > 0) {
//                    fbCheckOutRecord.setHeadOxygenContents(collect.get(0).getOxygenContentHead());
//                } else {
//                    fbCheckOutRecord.setHeadOxygenContents(null);
//                }
                //尾端头氧含量值取最新上传的非尾段的样片氧含量值    优化后的逻辑
                //            YTA3BA088111WA

//                List<PieceCheckDto1> pieceList = byMotherCrystalNo.getData().stream().filter(pieceCheckDto1 -> !pieceCheckDto1.getPieceNo().substring(SectionIndexRangeEnum.截断数.getBeginIndex(), SectionIndexRangeEnum.截断数.getEndIndex()).toUpperCase().contains("W")).collect(Collectors.toList());
                List<PieceCheckDto1> pieceList = byMotherCrystalNo.getData();
                if (CollectionUtils.isEmpty(pieceList)) {
                    fbCheckOutRecord.setHeadOxygenContents(null);
                } else {
                    pieceList.sort(Comparator.comparing(PieceCheckDto1::getCheckTime2).reversed());
                    fbCheckOutRecord.setHeadOxygenContents(pieceList.get(0).getOContents());
                }
            } else {
                fbCheckOutRecord.setHeadOxygenContents(null);
                fbCheckOutRecord.setTailOxygenContents(null);
            }
            if (fbCheckOutRecord.getYbSectionNo().startsWith("B") && (null == fbCheckOutRecord.getHeadOxygenContents() || null == fbCheckOutRecord.getTailOxygenContents())) {
                Result<YbInspectDataDto> inspectDataBaseBySectionNo = ybFeignService.getInspectDataBaseBySectionNo(fbCheckOutRecord.getYbSectionNo());
                //代工数据查询圆棒检验数据
                if (inspectDataBaseBySectionNo.getCode() == ResultCode.SUCCESS.getCode()) {
                    YbInspectDataDto data = inspectDataBaseBySectionNo.getData();
                    if (null != data) {
                        BigDecimal oxygenContentHead = data.getOxygenContentHead();
                        BigDecimal oxygenContentTail = data.getOxygenContentTail();
                        fbCheckOutRecord.setHeadOxygenContents(oxygenContentHead);
                        fbCheckOutRecord.setTailOxygenContents(oxygenContentTail);
                    }
                }
            }
        } else {
            String substring = fbCheckOutRecord.getFbSectionNo().substring(0, 12);
            Result<List<PieceCheckDto1>> byMotherCrystalNo = ybFeignClients.getSampleData(substring);
            Result<List<DataInspectLogDto>> dataByCrystalNo = ybFeignClients.getDataByCrystalNo(substring);
            Result<LongCrystalDto1> crystalData = ybFeignClients.getCrystalData(substring);

            String segmentNumber = fbCheckOutRecord.getFbSectionNo().substring(12, 13).toUpperCase();
            //非尾段单晶赋值氧含量
            if (null != byMotherCrystalNo.getData() && byMotherCrystalNo.getData().size() > 0 && null != dataByCrystalNo.getData() && dataByCrystalNo.getData().size() > 0 && null != crystalData.getData() && !segmentNumber.equals("W")) {
                //判断单晶是否为循环段
//            if(!StringUtils.isBlank(crystalData.getData().getClosureIdentification())){
//            需要获取头片氧含量数据 并且头片段号不能大于当前单晶的段号
                List<PieceCheckDto1> pieceList = byMotherCrystalNo.getData().stream().filter(pieceCheckDto1 -> !pieceCheckDto1.getPieceNo().substring(12, 13).toUpperCase().contains("W") && ((!pieceCheckDto1.getPieceNo().substring(12, 13).toUpperCase().equals("T") && Integer.valueOf(pieceCheckDto1.getPieceNo().substring(12, 13)) <= Integer.valueOf(segmentNumber)) || pieceCheckDto1.getPieceNo().substring(12, 13).toUpperCase().equals("T"))).collect(Collectors.toList());
                //T2BP0011R51TP、T2BP0011R511P、T2BP0011R512P、T2BP0011R51WP
                //实验单晶每段都取片 当前单晶取对应的片数据
                Boolean key = false;
                List<PieceCheckDto1> list = new ArrayList<>();
                if (null != pieceList && pieceList.size() > 0) {
                    for (int i = 0; i < pieceList.size(); i++) {
                        if (pieceList.get(i).getPieceNo().substring(12, 13).toUpperCase().equals(segmentNumber)) {
                            list.add(pieceList.get(i));
                            key = true;
                        }
                    }
                    if (key) {
                        list.sort(Comparator.comparing(PieceCheckDto1::getCheckTime2).reversed());
                        fbCheckOutRecord.setHeadOxygenContents(list.get(0).getOContents());
                    } else {
                        //常规单晶只取头片，头片不合格继续取片，取最新的片数据
                        pieceList.sort(Comparator.comparing(PieceCheckDto1::getCheckTime2).reversed());
                        fbCheckOutRecord.setHeadOxygenContents(pieceList.get(0).getOContents());
                    }
                } else {
                    fbCheckOutRecord.setHeadOxygenContents(null);
                }
                //todo  到这个位置就可以了
//                获取尾氧含量数据
                if ((!StringUtils.isBlank(crystalData.getData().getClosureIdentification()) && !crystalData.getData().getClosureIdentification().contains("完结")) || StringUtils.isBlank(crystalData.getData().getClosureIdentification())) {
//                循环段单晶后端取当前圆棒检验数据的尾氧含量即可（循环段除头段外氧含量默认合格值）
                    List<DataInspectLogDto> collect = dataByCrystalNo.getData().stream().filter(dataInspectLogDto -> dataInspectLogDto.getSectionNo().substring(12, 13).equals(segmentNumber)).collect(Collectors.toList());
                    if (null != collect && collect.size() > 0) {
                        collect.sort(Comparator.comparing(DataInspectLogDto::getId).reversed());
                        DataInspectLogDto dataInspectLogDto = collect.get(0);
                        fbCheckOutRecord.setTailOxygenContents(dataInspectLogDto.getOxygenContentTail());
                    } else {
                        fbCheckOutRecord.setTailOxygenContents(null);
                    }
                } else {
//                完结单晶后端取尾片数据，尾片不合格继续取片，取最新的尾数据
                    List<PieceCheckDto1> pieceList1 = byMotherCrystalNo.getData().stream().filter(pieceCheckDto1 -> pieceCheckDto1.getPieceNo().substring(12, 13).toUpperCase().contains("W") || (!pieceCheckDto1.getPieceNo().substring(12, 13).toUpperCase().equals("T") && Integer.valueOf(pieceCheckDto1.getPieceNo().substring(12, 13)) >= Integer.valueOf(segmentNumber))).collect(Collectors.toList());
                    if (null != pieceList1 && pieceList1.size() > 0) {
                        pieceList1.sort(Comparator.comparing(PieceCheckDto1::getCheckTime2).reversed());
                        fbCheckOutRecord.setTailOxygenContents(pieceList1.get(0).getOContents());
                    } else {
                        fbCheckOutRecord.setTailOxygenContents(null);
                    }
                }
//            }
                //尾段单晶赋值氧含量
            } else if (null != byMotherCrystalNo.getData() && byMotherCrystalNo.getData().size() > 0 && null != dataByCrystalNo.getData() && dataByCrystalNo.getData().size() > 0 && null != crystalData.getData() && segmentNumber.equals("W")) {
                //尾段尾氧含量取对应尾片尾氧含量
                if (!StringUtils.isBlank(crystalData.getData().getClosureIdentification()) && crystalData.getData().getClosureIdentification().contains("完结")) {
                    List<PieceCheckDto1> pieceList1 = byMotherCrystalNo.getData().stream().filter(pieceCheckDto1 -> pieceCheckDto1.getPieceNo().toUpperCase().equals("W")).collect(Collectors.toList());
                    if (null != pieceList1 && pieceList1.size() > 0) {
                        pieceList1.sort(Comparator.comparing(PieceCheckDto1::getCheckTime2).reversed());
                        fbCheckOutRecord.setTailOxygenContents(pieceList1.get(0).getOContents());
                    } else {
                        fbCheckOutRecord.setTailOxygenContents(null);
                    }
                } else {
                    //尾段尾氧含量取对应圆棒尾段尾氧含量
                    List<DataInspectLogDto> collect = dataByCrystalNo.getData().stream().filter(dataInspectLogDto -> dataInspectLogDto.getSectionNo().substring(12, 13).toUpperCase().equals("W")).collect(Collectors.toList());
                    collect.sort(Comparator.comparing(DataInspectLogDto::getId).reversed());
                    if (null != collect && collect.size() > 0) {
                        fbCheckOutRecord.setTailOxygenContents(collect.get(0).getOxygenContentTail());
                    } else {
                        fbCheckOutRecord.setTailOxygenContents(null);
                    }
                }
                //尾段头氧含量取对应圆棒尾段的头氧即可
//                List<DataInspectLogDto> collect = dataByCrystalNo.getData().stream().filter(dataInspectLogDto -> dataInspectLogDto.getSectionNo().substring(11, 12).toUpperCase().equals("W")).collect(Collectors.toList());
//                collect.sort(Comparator.comparing(DataInspectLogDto::getId).reversed());
//                if (null != collect && collect.size() > 0) {
//                    fbCheckOutRecord.setHeadOxygenContents(collect.get(0).getOxygenContentHead());
//                } else {
//                    fbCheckOutRecord.setHeadOxygenContents(null);
//                }
                //尾端头氧含量值取最新上传的非尾段的样片氧含量值    优化后的逻辑
//                List<PieceCheckDto1> pieceList = byMotherCrystalNo.getData().stream().filter(pieceCheckDto1 -> !pieceCheckDto1.getPieceNo().substring(11, 12).toUpperCase().contains("W")).collect(Collectors.toList());
                List<PieceCheckDto1> pieceList = byMotherCrystalNo.getData();
                if (CollectionUtils.isEmpty(pieceList)) {
                    fbCheckOutRecord.setHeadOxygenContents(null);
                } else {
                    pieceList.sort(Comparator.comparing(PieceCheckDto1::getCheckTime2).reversed());
                    fbCheckOutRecord.setHeadOxygenContents(pieceList.get(0).getOContents());
                }
            } else {
                fbCheckOutRecord.setHeadOxygenContents(null);
                fbCheckOutRecord.setTailOxygenContents(null);
            }
            if (fbCheckOutRecord.getYbSectionNo().startsWith("B") && (null == fbCheckOutRecord.getHeadOxygenContents() || null == fbCheckOutRecord.getTailOxygenContents())) {
                Result<YbInspectDataDto> inspectDataBaseBySectionNo = ybFeignService.getInspectDataBaseBySectionNo(fbCheckOutRecord.getYbSectionNo());
                //代工数据查询圆棒检验数据
                if (inspectDataBaseBySectionNo.getCode() == ResultCode.SUCCESS.getCode()) {
                    YbInspectDataDto data = inspectDataBaseBySectionNo.getData();
                    if (null != data) {
                        BigDecimal oxygenContentHead = data.getOxygenContentHead();
                        BigDecimal oxygenContentTail = data.getOxygenContentTail();
                        fbCheckOutRecord.setHeadOxygenContents(oxygenContentHead);
                        fbCheckOutRecord.setTailOxygenContents(oxygenContentTail);
                    }
                }
            }
        }
    }

    @Override
    public void updateIsCutBack(int isCutBack, String sectionNo) {
        dao.updateIsCutBack(isCutBack, sectionNo);
    }

    @Override
    public void updateWeight(FbCheckOutRecord updateDto) {
        dao.updateWeight(updateDto.getId(), updateDto.getWeight());
    }

    @Override
    public void updateOxygenCarbonByYbSectionNoList(OxygenCarbonDto oxygenCarbonDto) {

        if (null == oxygenCarbonDto || CollectionUtils.isEmpty(oxygenCarbonDto.getSectionNoList()) || null == oxygenCarbonDto.getHeadFlag()) {
            return;
        }
        Boolean headFlag = oxygenCarbonDto.getHeadFlag();
        List<FbCheckOutRecord> ybSecitonNoList = dao.findYbSecitonNoList(oxygenCarbonDto.getSectionNoList());
        List<String> fbSectionNoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(ybSecitonNoList)) {
            for (FbCheckOutRecord fbCheckOutRecord : ybSecitonNoList) {
                if (headFlag) {
                    fbCheckOutRecord.setTOxygenContent(oxygenCarbonDto.getOContents());
                    fbCheckOutRecord.setTCarbonContent(oxygenCarbonDto.getCContents());
                } else {
                    fbCheckOutRecord.setWOxygenContent(oxygenCarbonDto.getOContents());
                    fbCheckOutRecord.setWCarbonContent(oxygenCarbonDto.getCContents());
                }
                fbSectionNoList.add(fbCheckOutRecord.getFbSectionNo());
                this.saveOrUpdate(fbCheckOutRecord);
            }
        }
        if (fbSectionNoList.size() != 0) {
            List<FbCheckOutData> checkOutDataByFbSectionNoIns = fbCheckOutDataService.findCheckOutDataByFbSectionNoIns(fbSectionNoList);
            if (!CollectionUtils.isEmpty(checkOutDataByFbSectionNoIns)) {
                Map<String, FbCheckOutData> fbCheckOutDataMap = new HashMap<>();
                for (FbCheckOutData fbCheckOutData : checkOutDataByFbSectionNoIns) {
                    if (headFlag) {
                        fbCheckOutData.setTCarbonContent(oxygenCarbonDto.getCContents());
                        fbCheckOutData.setTOxygenContent(oxygenCarbonDto.getOContents());
                    } else {
                        fbCheckOutData.setWCarbonContent(oxygenCarbonDto.getCContents());
                        fbCheckOutData.setWOxygenContent(oxygenCarbonDto.getOContents());
                    }
                    fbCheckOutDataService.saveOrUpdate(fbCheckOutData);
                    //工单状态!=1,不能触发评级

                    PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCode(fbCheckOutData.getFbSectionNo());
                    if (null != planProcessingOrder && null != planProcessingOrder.getStatus()
                            && planProcessingOrder.getStatus() == EnumValuesFactory.PlanProcessingOrderStatus.加工中.getKey()){
                        fbCheckOutDataMap.put(fbCheckOutData.getFbSectionNo(), fbCheckOutData);
                    }
                }
                gradeService.execGrade(fbCheckOutDataMap);
            }

        }

    }


    @Override
    public void saveBackcutInspection(List<BackcutInspectionDto> backcutInspectionDtos) {
        if (CollectionUtils.isEmpty(backcutInspectionDtos)){
            log.info("传入参数为空");
            return;
        }
        BackcutInspectionDto backcutInspectionDto = backcutInspectionDtos.get(0);
        if (StringUtils.isBlank(backcutInspectionDto.getSectionNo())){
            log.info("传入方棒单晶编号为空！");
            return;
        }
        FbCheckOutData fbCheckOutData = fbCheckOutDataService.findDataByFbSectionNo(backcutInspectionDto.getSectionNo());
        if (null == fbCheckOutData){
            log.info("方棒单晶编号记录为空！");
            return;
        }
        Integer retestNo = null != fbCheckOutData.getRetestNo() ? fbCheckOutData.getRetestNo() + 1 : 1;

        List<DictionaryItem> dictionaryItems = dictionaryItemService.findByThemeValueAndItemName(Constants.THEORETICAL_WEIGHT_COEFFICIENTFB, fbCheckOutData.getSpecification(), true);
        BigDecimal weightLossCoefficient = null;
        if (!CollectionUtils.isEmpty(dictionaryItems)) {
            weightLossCoefficient = NumberUtil.Object2BigDecimal(dictionaryItems.get(0).getValue());
        }
        for (BackcutInspectionDto backcutInspectionDtoFor : backcutInspectionDtos){
            if (null != backcutInspectionDtoFor.getType() && backcutInspectionDtoFor.getType() == 0){
                FbCheckOutData fbCheckOutDataNew = new FbCheckOutData();
                BeanUtil.copyProperties(fbCheckOutData, fbCheckOutDataNew, "id", "productLevelFb", "actualLength",
                        "length", "instoreLengthFb", "consumeLengthYb", "theoryWeightFb", "weight", "spellBarLength", "sticksCount","gradeType","sectionType");
                fbCheckOutDataNew.setBackCut(0);
                fbCheckOutDataNew.setCheckoutName(EnumValues.CheckoutName.返切复检.getValue());
                fbCheckOutData.setCheckUserName(backcutInspectionDtoFor.getCheckUserName());
                fbCheckOutDataNew.setFbSectionNo(backcutInspectionDtoFor.getNo());
                fbCheckOutDataNew.setRetestNo(retestNo);
                fbCheckOutDataNew.setHoleLength(0);
                fbCheckOutDataNew.setChipLength(0);
                fbCheckOutDataNew.setUnfinishedLength(0);
                fbCheckOutDataNew.setLineLength(0);
                fbCheckOutDataNew.setSealLength(0);
                fbCheckOutDataNew.setStepLength(0);
                fbCheckOutDataNew.setScratchesLength(0);
                fbCheckOutDataNew.setSticksCount(1);
                fbCheckOutDataNew.setScratch(BigDecimal.ZERO);
                fbCheckOutDataNew.setDifcolorLength(0);
                fbCheckOutDataNew.setRoughnessAbnormality(BigDecimal.ZERO);
                fbCheckOutDataNew.setInstoreLengthFb(backcutInspectionDtoFor.getLength());
                fbCheckOutDataNew.setLength(backcutInspectionDtoFor.getLength());
                if (null != backcutInspectionDtoFor.getLength() && null != weightLossCoefficient){
                    BigDecimal weight = backcutInspectionDtoFor.getLength().divide(weightLossCoefficient, 3, RoundingMode.HALF_UP);
                    fbCheckOutDataNew.setTheoryWeightFb(weight);
                    fbCheckOutDataNew.setWeight(weight);
                }
                FbCheckOutRecord fbCheckOutRecord  = new FbCheckOutRecord();
                saveDataAndGrade(fbCheckOutDataNew, "");
                BeanUtil.copyProperties(fbCheckOutDataNew,fbCheckOutRecord,"id");
                this.saveOrUpdate(fbCheckOutRecord);
            }
        }
    }


    /**
     * 修改工单重量与长度
     *
     * @param theoryWeight
     * @param actualLength
     */
    private void updatePlanProcessingOrderInfo(String fbSectionNo, BigDecimal theoryWeight, BigDecimal actualLength) {
        PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCode(fbSectionNo);
        if (planProcessingOrder != null) {
            if (theoryWeight != null) {
                planProcessingOrder.setWeight(theoryWeight);
            }
            if (actualLength != null) {
                planProcessingOrder.setLength(actualLength);
            }
            planProcessingOrderService.createPlanProcessingOrder(planProcessingOrder, null, null);
        }
    }


    /**
     * 初始化检验数据库
     *
     * @param fbCheckOutRecord 检验记录
     * @param isCreate         是否新增：true 新增，false为修改
     * @param flag             标记导入 （true 是）
     * @return
     */
    private FbCheckOutData initFbCheckOutData(FbCheckOutRecord fbCheckOutRecord, Boolean isCreate, Boolean flag) {
        //查询方棒检验数据库
        FbCheckOutData fbCheckOutData = fbCheckOutDataService.findDataByFbSectionNo(fbCheckOutRecord.getFbSectionNo());
        if (fbCheckOutData == null) {
            fbCheckOutData = new FbCheckOutData();
        } else {

            //校验方棒长度是否可以修改
            if (fbCheckOutRecord.getLength().compareTo(fbCheckOutData.getLength()) != 0) {
                //粘棒记录（未解绑的）
                FbJoin fbJoinBySectionNo = fbJoinService.getFbJoinBySectionNo(fbCheckOutRecord.getFbSectionNo());
                if (null != fbJoinBySectionNo) {
                    throw new RuntimeException("当前方棒为拼棒，且未解绑，不允许修改长度！");
                }
                //组托明细
                FbTurnstoreTrayItem bySectionNo = fbTurnstoreTrayItemService.findBySectionNo3(fbCheckOutRecord.getFbSectionNo());
                if (null != bySectionNo && bySectionNo.getReturnInspectionStatus()!=1) {
                    throw new RuntimeException("当前晶棒已是组托中状态，不可修改方棒长度！");
                }
            }
            //新增修改时，将旧数据保存到方棒检验记录中
            OperateCheckOutDataLog operateCheckOutDataLog = new OperateCheckOutDataLog();
            BeanUtil.copyBeanPropWithOutNullValue(operateCheckOutDataLog, fbCheckOutData, "id,isFbSizeCheck");
            if (null != fbCheckOutData.getIsFbSizeCheck()) {
                operateCheckOutDataLog.setIsFbSizeCheck(fbCheckOutData.getIsFbSizeCheck() == true ? 1 : 0);
                //
                operateCheckOutDataLog.setFlag4M(fbCheckOutData.getIsFbSizeCheck() == true ? "1" : "0");
            }
            operateCheckOutDataLog.setOperateTime(new Date());
            operateCheckOutDataLog.setOperator(BaseContextHandler.getUsername());
            if (isCreate) {
                operateCheckOutDataLog.setOperateType(0);
                operateCheckOutDataLog.setRemarks(BaseContextHandler.getUsername() + "新增数据");
            } else {
                operateCheckOutDataLog.setOperateType(1);
                operateCheckOutDataLog.setRemarks(BaseContextHandler.getUsername() + "修改数据");
            }
            operateCheckOutDataLogService.saveOrUpdate(operateCheckOutDataLog);
        }

        if (isCreate) {
            // 2 新增数据，先将检验数据库除id外数据置空
            BeanUtil.copyBeanPropWithNullValue(fbCheckOutData, new FbCheckOutData(), "id,reCheckType,checkType,orderType,orderNo");
            fbCheckOutData.setCheckUserName(BaseContextHandler.getUsername());
            fbCheckOutData.setCheckTime(new Date());
        } else {
            fbCheckOutData.setUpdateUser(BaseContextHandler.getUsername());
            fbCheckOutData.setUpdateTime(new Date());
        }

        //将输入的检验记录非空字段赋值给检验数据库，id除外
        BeanUtil.copyBeanPropWithOutNullValue(fbCheckOutData, fbCheckOutRecord, "id,checkUserName,checkTime,reCheckType,checkType");
        fbCheckOutData.setOrderNo(fbCheckOutRecord.getWorkOrderNo());
        fbCheckOutData.setOrderType(fbCheckOutRecord.getWorkOrderType());
        //检验类型、检验次数赋值
        this.setCheckType(fbCheckOutData, isCreate);

        // TODO 后续订单号有了需要修改
        // 通过订单号找到方棒计划信息
//			if (StringUtils.isNotBlank(fbCheckOutRecordDto.getOrderNo())){
//				FbProductionOrder productionOrderfb = this.fbProductionOrderService.findByAufnr(fbCheckOutRecordDto.getOrderNo());
//				if (productionOrderfb != null){
//
//					fbCheckOutData.setPlanGrade(productionOrderfb.getFbProductModel().getProductLevel());//计划产品等级
//					fbCheckOutData.setPlanSpecs(productionOrderfb.getFbProductModel().getSpecs());// 计划产品规格
//					fbCheckOutData.setPlanDopant(productionOrderfb.getFbProductModel().getDopant());// 计划掺杂剂
//					fbCheckOutData.setPlanStickCount(productionOrderfb.getFbProductModel().getSpellNo());// 计划拼数
//					fbCheckOutData.setPlanLenRange(productionOrderfb.getFbProductModel().getLength());// 计划长度范围
//					fbCheckOutData.setPlanConductiveType(productionOrderfb.getFbProductModel().getConductiveType());// 计划导电类型
//					fbCheckOutData.setPlanResistivity(productionOrderfb.getFbProductModel().getResistivity());// 计划电阻率
//				}
//			}


        //获取圆棒检验信息
        Result<GetFbInfoDto> fbInfoBySectionNofb = this.getFbInfoBySectionNofb(fbCheckOutData.getFbSectionNo());
        if (fbInfoBySectionNofb.getCode() == 200) {
            GetFbInfoDto data = fbInfoBySectionNofb.getData();
            if (data != null) {
                fbCheckOutData.setDopant(data.getDopant());
                //拼数赋值
                fbCheckOutData.setSticksCount(data.getSticksCount());
                //单晶组合赋值
                fbCheckOutData.setSectionCompose(data.getSectionCompose());
                //导入/mcs推送时保存取默认值，其他取用页面值
                if (flag) {
                    // 圆棒实验等级赋值
                    fbCheckOutData.setExperiLevel(data.getProductLevelExperiment());// 实验最终评级
                }
                //产品简称
                fbCheckOutRecord.setAbbreviation(data.getAbbreviation());
                fbCheckOutData.setAbbreviation(data.getAbbreviation());
                //产品配方
                fbCheckOutRecord.setFormulation(data.getFormulation());
                fbCheckOutData.setFormulation(data.getFormulation());
                fbCheckOutRecord.setTOxygenContent(data.getOxygenContentHead());
                fbCheckOutData.setTOxygenContent(data.getOxygenContentHead());

                fbCheckOutRecord.setWOxygenContent(data.getOxygenContentTail());
                fbCheckOutData.setWOxygenContent(data.getOxygenContentTail());
                fbCheckOutRecord.setTCarbonContent(data.getCarbonContentHead());
                fbCheckOutData.setTCarbonContent(data.getCarbonContentHead());
                fbCheckOutRecord.setWCarbonContent(data.getCarbonContentTail());
                fbCheckOutData.setWCarbonContent(data.getCarbonContentTail());
                fbCheckOutRecord.setMeanResistivityA(data.getMeanResistivityA());
                fbCheckOutData.setMeanResistivityA(data.getMeanResistivityA());
                fbCheckOutRecord.setMeanResistivityB(data.getMeanResistivityB());
                fbCheckOutData.setMeanResistivityB(data.getMeanResistivityB());
                fbCheckOutRecord.setMeanCarrierLifetimeA(data.getMeanCarrierLifetimeA());
                fbCheckOutData.setMeanCarrierLifetimeA(data.getMeanCarrierLifetimeA());
                fbCheckOutRecord.setMeanCarrierLifetimeB(data.getMeanCarrierLifetimeB());
                fbCheckOutData.setMeanCarrierLifetimeB(data.getMeanCarrierLifetimeB());
                fbCheckOutRecord.setTResistivity(data.getTResistivity());
                fbCheckOutData.setTResistivity(data.getTResistivity());

                fbCheckOutRecord.setWResistivity(data.getWResistivity());
                fbCheckOutData.setWResistivity(data.getWResistivity());

                fbCheckOutRecord.setTCarrierLifetime(data.getTCarrierLifetime());
                fbCheckOutData.setTCarrierLifetime(data.getTCarrierLifetime());

                fbCheckOutRecord.setWCarrierLifetime(data.getWCarrierLifetime());
                fbCheckOutData.setWCarrierLifetime(data.getWCarrierLifetime());

                fbCheckOutRecord.setConductionType(data.getConductionType());
                fbCheckOutData.setConductionType(data.getConductionType());

                fbCheckOutRecord.setSpecification(data.getSpecification());
                fbCheckOutData.setSpecification(data.getSpecification());

                fbCheckOutRecord.setOutGoing(data.getOutGoing());
                fbCheckOutData.setOutGoing(data.getOutGoing());
                fbCheckOutRecord.setRatingTime(data.getRatingTime());
                fbCheckOutData.setRatingTime(data.getRatingTime());
                fbCheckOutRecord.setCheckTime(data.getCheckTime());
                fbCheckOutData.setCheckTime(data.getCheckTime());
                fbCheckOutRecord.setCheckDate(data.getCheckDate());
                fbCheckOutData.setCheckDate(data.getCheckDate());
                fbCheckOutRecord.setLotNo(data.getLotNo());
                fbCheckOutData.setLotNo(data.getLotNo());
                fbCheckOutRecord.setGradeVersion(data.getGradeVersion());
                fbCheckOutData.setGradeVersion(data.getGradeVersion());
                fbCheckOutData.setCheckUserName(BaseContextHandler.getUsername());
                fbCheckOutRecord.setCheckUserName(BaseContextHandler.getUsername());

                //圆棒长度
                fbCheckOutData.setFurnaceType(data.getFurnaceType());
                fbCheckOutRecord.setFurnaceType(data.getFurnaceType());
                fbCheckOutData.setInstoreLengthYb(data.getInstoreLengthYb());
                fbCheckOutRecord.setInstoreLengthYb(data.getInstoreLengthYb());
                fbCheckOutData.setSectionType(data.getSectionType());
                fbCheckOutRecord.setSectionType(data.getSectionType());
                fbCheckOutData.setLevelCode(data.getLevelCode());
                fbCheckOutRecord.setLevelCode(data.getLevelCode());
                fbCheckOutData.setClosureIdentification(data.getClosureIdentification());
                fbCheckOutRecord.setClosureIdentification(data.getClosureIdentification());
                fbCheckOutData.setCrystalWorkshop(data.getCrystalWorkshop());
                fbCheckOutRecord.setCrystalWorkshop(data.getCrystalWorkshop());
                fbCheckOutData.setArea(data.getArea());
                fbCheckOutRecord.setArea(data.getArea());
                fbCheckOutData.setFactory(data.getFactory());
                fbCheckOutRecord.setFactory(data.getFactory());

                fbCheckOutData.setPlanOrderNo(data.getPlanOrderNo());
                fbCheckOutData.setPlanOrderType(data.getPlanOrderType());
                fbCheckOutData.setPlanGrade(data.getPlanGrade());
                fbCheckOutData.setYbLevel(data.getProductLevel());// 产品最终评级
                fbCheckOutData.setProductLevel(data.getProductLevel());// 产品等级
                fbCheckOutData.setYbExperiLevel(data.getYbExperiLevel());
                fbCheckOutData.setProductType(data.getProductType());
                fbCheckOutData.setHeadTailRecognition(data.getHeadTailRecognition());
                fbCheckOutData.setPiecewiseNum(data.getPiecewiseNum());
                fbCheckOutRecord.setProductType(data.getProductType());
                fbCheckOutRecord.setBatchNo(data.getBatchNo());
//                fbCheckOutData.setOrderNo(data.getOrderNo());
                //fbCheckOutData.setMaterialCode(data.getMaterialCode());
            }
        }
        //处理物料号和工单号,从开方中获取
        CrystalMaterialRelation bySectionNo = crystalMaterialRelationService.findBySectionNo(fbCheckOutData.getYbSectionNo());
        if (null != bySectionNo) {
            fbCheckOutData.setMaterialCode(bySectionNo.getMaterialCode());
            fbCheckOutData.setOrderNo(bySectionNo.getOrderNo());
            fbCheckOutData.setWorkOrderNo(bySectionNo.getOrderNo());
            fbCheckOutRecord.setMaterialCode(bySectionNo.getMaterialCode());
            fbCheckOutRecord.setWorkOrderNo(bySectionNo.getOrderNo());
        }


        if (!isCreate) {
            //修改”产品等级名称“赋值给”圆棒最终评级“
            fbCheckOutData.setYbLevel(fbCheckOutRecord.getProductLevel());// 产品最终评级
            fbCheckOutRecord.setProductLevel(fbCheckOutData.getProductLevel());// 产品最终评级
            //拼棒修改方棒长度时，同步拼棒总长
            List<FbCheckOutData> fbSticksList = new ArrayList<>();
            List<FbCheckOutRecord> fbCheckOutRecordList = new ArrayList<>();
            BigDecimal spellBarLength = fbCheckOutRecord.getLength() == null ? new BigDecimal(0) : fbCheckOutRecord.getLength();
            ;
            if (fbCheckOutData != null && fbCheckOutData.getSticksCount() != null
                    && fbCheckOutData.getSticksCount() > 1 && fbCheckOutData.getSectionCompose() != null) {
                for (String fbSectionNo : fbCheckOutData.getSectionCompose().split(",")) {
                    if (!fbSectionNo.equals(fbCheckOutRecord.getFbSectionNo())) {
                        //组合单晶方棒检验数据库信息
                        FbCheckOutData fbCheckOutDataOther = fbCheckOutDataService.findDataByFbSectionNo(fbSectionNo);
                        if (fbCheckOutDataOther != null) {
                            fbSticksList.add(fbCheckOutDataOther);
                            spellBarLength = spellBarLength.add(fbCheckOutDataOther.getLength() == null ? new BigDecimal(0) : fbCheckOutDataOther.getLength());
                        }
                        //组合单晶方棒检验数据
                        FbCheckOutRecord fbCheckOutRecordOther = this.findFbCheckOutRecord(fbSectionNo);
                        if (fbCheckOutRecordOther != null) {
                            fbCheckOutRecordList.add(fbCheckOutRecordOther);
                        }
                    }
                }
            }

            for (FbCheckOutData fbCheckOutDataOther : fbSticksList) {
                fbCheckOutDataOther.setSpellBarLength(spellBarLength);
                this.setSectionType(fbCheckOutDataOther);
                fbCheckOutDataService.saveOrUpdate(fbCheckOutDataOther);//更新单晶组合拼棒总长
            }
            for (FbCheckOutRecord fbCheckOutRecordOther : fbCheckOutRecordList) {
                fbCheckOutRecordOther.setSpellBarLength(spellBarLength);
                this.saveOrUpdate(fbCheckOutRecordOther);//更新单晶组合拼棒总长
            }
            fbCheckOutRecord.setSpellBarLength(spellBarLength);
            fbCheckOutData.setSpellBarLength(spellBarLength);
        }
//        // 获取长棒信息
//        LongCrystalInfoDto longCrystalDto = ybFeignService.getLongCrystalInfo(fbCheckOutData.getYbSectionNo());
//        if (longCrystalDto != null) {
//
//        }
        return fbCheckOutData;
    }

    /**
     * 修改检验类型、检验次数
     *
     * @param fbCheckOutData
     * @param isCreate
     */
    private void setCheckType(FbCheckOutData fbCheckOutData, Boolean isCreate) {
        //新增时修改检验类型、检验次数
        if (isCreate) {
            //获取上一站点信息WipStorageCode
            Result<WipStorage> wipStorageResult = wipStorageService.selectLastWipStorageResult(fbCheckOutData.getFbSectionNo());
            if (wipStorageResult == null || wipStorageResult.getData() == null) {
                throw new BusinessException("查询上一站点异常");
            }
            FactoryModel factoryModel = wipStorageService.getFactoryModel(wipStorageResult.getData().getProcessId(), wipStorageResult.getData().getProcessName());
            EnumValuesFactory.WipStorageCode cWipStorageCode = EnumValuesFactory.WipStorageCode.getEnum(factoryModel.getCode());
            if (cWipStorageCode != null) {
                switch (cWipStorageCode) {
                    case 开方:
                        handleByKF(fbCheckOutData);
                        break;
                    case 毛棒截断:
                        handleByJD(fbCheckOutData);
                        break;
                    case 圆棒截断:
                        handleByJD(fbCheckOutData);
                        break;
                    case 方棒截断:
                        handleByJD(fbCheckOutData);
                        break;
                    case 综计WMS:
                        handleByZJ(fbCheckOutData);
                        break;
                    case 粘方棒:
                        handleByZFB(fbCheckOutData);
                        break;
                    default:
                        break;

                }
            }


        }
    }

    /**
     * 复检次数赋值，新增数据（即当前站点为方棒检验待进站状态）时
     * 如果检验数据库中无数据，复检次数赋值为0，否则 复检次数+1
     *
     * @param fbCheckOutData
     */
    private void setReCheckType(FbCheckOutData fbCheckOutData) {

        if (fbCheckOutData.getId() == null) {
            fbCheckOutData.setReCheckType("0");
            //反切生成新编号的晶段，继承父晶段属性
            RecutDetail recutDetail = recutDetailDao.findBySectionNoFb(fbCheckOutData.getFbSectionNo());
            if (recutDetail != null && recutDetail.getParentId() != 0) {
                RecutDetail recutDetailParent = recutDetailDao.getOne(recutDetail.getParentId());
                if (recutDetailParent != null) {
                    FbCheckOutData fbCheckOutDataParent = fbCheckOutDataService.findDataByFbSectionNo(recutDetailParent.getSectionNoFb());
                    if (fbCheckOutDataParent != null) {
                        //方棒分段返切自编号订单类型为ZH04
                        fbCheckOutData.setOrderType("ZH04");
                        fbCheckOutData.setReCheckType("0".equals(fbCheckOutDataParent.getReCheckType()) ? "1" : fbCheckOutDataParent.getReCheckType());
                    }
                }
            }
        } else {
            if (StringUtils.isEmpty(fbCheckOutData.getReCheckType())) {
                fbCheckOutData.setReCheckType("1");
            } else {
                Integer checkTimes = Integer.valueOf(fbCheckOutData.getReCheckType()) + 1;
                fbCheckOutData.setReCheckType(checkTimes.toString());
            }
            //订单类型：复检订单类型固定为 ZH04
            fbCheckOutData.setOrderType("ZH04");
        }


        List<DictionaryItem> dictionaryItem1s = dictionaryItemService.findByThemeValueAndItemName("FbCheckType", fbCheckOutData.getCheckType(), true);
        if (dictionaryItem1s.size() <= 0) {
            throw new BusinessException("未查询到【" + fbCheckOutData.getCheckType() + "】对应的字典配置，请检查数据字典【方棒检验类型】配置是否正确");
        }
        fbCheckOutData.setCheckoutName(dictionaryItem1s.get(0).getName());
        fbCheckOutData.setCheckoutId(dictionaryItem1s.get(0).getId());


        List<DictionaryItem> dictionaryItems = dictionaryItemService.findByThemeValueAndItemName("ReceiveMaterials", fbCheckOutData.getMaterialSourceValue(), true);
        if (dictionaryItems.size() <= 0) {
            throw new BusinessException("未查询到【" + fbCheckOutData.getMaterialSourceValue() + "】对应的字典配置，请检查数据字典【方棒领料来源】配置是否正确");
        }
        fbCheckOutData.setMaterialSourceValue(dictionaryItems.get(0).getValue());
    }

    /**
     * 粘方棒到检验，
     * 检验类型为 粘方棒复检，复检次数加一 订单类型为ZH04
     *
     * @param fbCheckOutData
     */
    private void handleByZFB(FbCheckOutData fbCheckOutData) {

        fbCheckOutData.setCheckType(EnumValues.CheckoutName.粘方棒复检.getValue());
        fbCheckOutData.setMaterialSourceValue(EnumValues.MaterialSourceName.粘方棒.getValue());
        this.setReCheckType(fbCheckOutData);
    }

    /**
     * 综计wms到检验，
     * <p>
     * 接收类型来判断退货复检’还是“退库复检”，领料来源wms，次数加一 订单类型为ZH04
     *
     * @param fbCheckOutData
     */
    private void handleByZJ(FbCheckOutData fbCheckOutData) {
        //退库复检接收已处理，此处不在处理(20220722改为在此处处理)
        int reCheck = 1;
        if (null != fbCheckOutData.getReCheckType()) {
            reCheck = Integer.parseInt(fbCheckOutData.getReCheckType()) + 1;
        }
        fbCheckOutData.setReCheckType(String.valueOf(reCheck));
        //更新订单类型
        fbCheckOutData.setOrderType("ZH04");

        RecheckInspectReceiveDetail byCrystalNoAndState = receiveDetailService.findByCrystalNoAndState(fbCheckOutData.getFbSectionNo(), 1);
        if (null != byCrystalNoAndState) {
            fbCheckOutData.setCheckoutName(byCrystalNoAndState.getQuitType());
            fbCheckOutData.setCheckType(byCrystalNoAndState.getQuitType());
        }
    }

    /**
     * 截断站到检验
     * 检验类型为 反切复检，领料来源为截断机，订单类型为 ZH04 复检次数+1
     *
     * @param fbCheckOutData
     */
    private void handleByJD(FbCheckOutData fbCheckOutData) {
        fbCheckOutData.setCheckType(EnumValues.CheckoutName.返切复检.getValue());
        fbCheckOutData.setMaterialSourceValue(EnumValues.MaterialSourceName.切断.getValue());


        this.setReCheckType(fbCheckOutData);

    }

    /**
     * 开方站到检验的
     * <p>
     * 领料来源为磨削机，判断一下之前有没有检验数据，
     * 没数据：检验类型为 一次检验，订单类型为 复检次数为 0
     * 有数据：检验类型为返修复检，订单类型为 ZH04 复检次数+1
     *
     * @param fbCheckOutData
     */
    private void handleByKF(FbCheckOutData fbCheckOutData) {
        if (fbCheckOutData.getId() == null) {
            //无检验数据
            fbCheckOutData.setCheckType(EnumValues.CheckoutName.一次检验.getValue());
            // 查询订单类型
            fbCheckOutData.setOrderType("ZH01");
//            List<FbOrderMatchingInfo> fbOrderMatchingInfoList = fbOrderMatchingInfoService.findBySectionNo(fbCheckOutData.getYbSectionNo());
//            if (fbOrderMatchingInfoList.size() > 0) {
//                FbOrderMatchingInfo fbOrderMatchingInfo = fbOrderMatchingInfoList.get(0);
//                fbCheckOutData.setOrderNo(fbOrderMatchingInfo.getFbOrderNo());
//                FbProductionOrder fbProductionOrder = fbProductionOrderService.get(fbOrderMatchingInfo.getFbOrderId());
//                if (fbProductionOrder!=null){
//                    fbCheckOutData.setOrderType(fbProductionOrder.getAuart());
//                }
//            }
            fbCheckOutData.setMaterialSourceValue(EnumValues.MaterialSourceName.磨削机.getValue());
        } else {
            //有检验数据
            fbCheckOutData.setCheckType(EnumValues.CheckoutName.返修复检.getValue());
            fbCheckOutData.setMaterialSourceValue(EnumValues.MaterialSourceName.磨削机.getValue());
        }
        this.setReCheckType(fbCheckOutData);
    }

    /**
     * 晶段类型赋值
     *
     * @param fbCheckOutData
     */
    private void setSectionType(FbCheckOutData fbCheckOutData) {
        //页面：圆棒生产管理》默认值维护》晶棒属性 根据 规格参杂剂长度判 断
        String specification = fbCheckOutData.getSpecification();
        if (specification != null) {
            String[] split = specification.split("\\*");
            if (split.length > 0) {
                specification = split[0];
            }
        }
        String dopant = fbCheckOutData.getDopant();
        String type = defaultCrystalAttrService.getDefaultCrystalAttrOneTimes(dopant, specification, fbCheckOutData.getProductLevel(), fbCheckOutData.getSticksCount() != null && fbCheckOutData.getSticksCount() > 1 ? fbCheckOutData.getSpellBarLength() : fbCheckOutData.getLength());
        fbCheckOutData.setSectionType(type);
    }

    /**
     * 初始化检验数据
     *
     * @param fbCheckOutRecord
     */
    private void initFbCheckOutRecord(FbCheckOutRecord fbCheckOutRecord) {
        if (fbCheckOutRecord.getId() == null || fbCheckOutRecord.getId() == 0) {
            fbCheckOutRecord.setCheckTime(new Date());
            fbCheckOutRecord.setCheckUserName(BaseContextHandler.getUsername());
        } else {
            fbCheckOutRecord.setUpdateTime(new Date());
            fbCheckOutRecord.setUpdateUser(BaseContextHandler.getUsername());
        }
        if (null == fbCheckOutRecord.getCheckTime()){
            fbCheckOutRecord.setCheckTime(new Date());
        }

        //处理返切
        RecutDetail recutDetail = recutDetailDao.findBySectionNoFb(fbCheckOutRecord.getFbSectionNo());
        if (null != recutDetail && null != recutDetail.getParentId() && recutDetail.getParentId() != 0){
            fbCheckOutRecord.setBackCut(1);
        }else {
            fbCheckOutRecord.setBackCut(0);
        }
        //根据反切详情赋值圆棒消耗长度
//        this.setConsumeLengthYbByReCutDetail(fbCheckOutRecord);
        // 根据规格赋值重量
//        this.setWeightBySpecification(fbCheckOutRecord);
        // 计算方棒入库长度
//        this.setInstoreLength(fbCheckOutRecord);
    }

    /**
     * 外观异常录入默认值
     *
     * @param fbCheckOutData 检验记录
     */
    private void setAppearanceDefaults(FbCheckOutData fbCheckOutData, FbCheckOutRecord fbCheckOutRecord) {
        //默认值0
        BigDecimal defaultValue = BigDecimal.ZERO;

        //线痕长度(mm)
        if (fbCheckOutData.getLineScratch() == null) {
            fbCheckOutData.setLineScratch(defaultValue);
        }

        //划痕长度(mm)
        if (fbCheckOutData.getScratch() == null) {
            fbCheckOutData.setScratch(defaultValue);
        }

        //刀痕长度(mm)
        if (fbCheckOutData.getKnifeScratch() == null) {
            fbCheckOutData.setKnifeScratch(defaultValue);
        }

        //崩损(mm)
        if (fbCheckOutData.getCollapseLoss() == null) {
            fbCheckOutData.setCollapseLoss(defaultValue);
        }

        //崩损灰皮边缘
        if (fbCheckOutData.getDamageGreyHideEdge() == null) {
            fbCheckOutData.setDamageGreyHideEdge(defaultValue);
        }

        //崩损灰皮非边缘
        if (fbCheckOutData.getBrokenGreyNoEdge() == null) {
            fbCheckOutData.setBrokenGreyNoEdge(defaultValue);
        }

        //未磨到长度(mm)
        if (fbCheckOutData.getNoFriction() == null) {
            fbCheckOutData.setNoFriction(defaultValue);
        }

        //晶体灰皮长度(mm)
        if (fbCheckOutData.getCrystalGrayness() == null) {
            fbCheckOutData.setCrystalGrayness(defaultValue);
        }

        //方棒灰皮长度(mm)
        if (fbCheckOutData.getSquareRodGrayness() == null) {
            fbCheckOutData.setSquareRodGrayness(defaultValue);
        }

        //灰皮边缘
        if (fbCheckOutData.getGreyHideEdge() == null) {
            fbCheckOutData.setGreyHideEdge(defaultValue);
        }

        //灰皮非边缘
        if (fbCheckOutData.getGreyHideCenter() == null) {
            fbCheckOutData.setGreyHideCenter(defaultValue);
        }

        //裂纹
        if (fbCheckOutData.getCrack() == null) {
            fbCheckOutData.setCrack(defaultValue);
        }

        //尺寸异常长度(mm)
        if (fbCheckOutData.getSizeException() == null) {
            fbCheckOutData.setSizeException(defaultValue);
        }

        //水印
        if (fbCheckOutData.getWaterMark() == null) {
            fbCheckOutData.setWaterMark(defaultValue);
        }

        //亮斑
        if (fbCheckOutData.getHotSpot() == null) {
            fbCheckOutData.setHotSpot(defaultValue);
        }
        //棱崩
        if (fbCheckOutData.getRidgeBroken() == null) {
            fbCheckOutData.setRidgeBroken(defaultValue);
        }

        //阴阳面
        if (fbCheckOutData.getYinYangFace() == null) {
            fbCheckOutData.setYinYangFace(defaultValue);
        }

        //砂轮亮点
        if (fbCheckOutData.getWheelHighLights() == null) {
            fbCheckOutData.setWheelHighLights(defaultValue);
        }
        //外圆手感
        if (fbCheckOutData.getRoundHandle() == null) {
            fbCheckOutData.setRoundHandle(defaultValue);

        }

        //平面手感
        if (fbCheckOutData.getFlatHandle() == null) {
            fbCheckOutData.setFlatHandle(defaultValue);
        }

        //砂轮印
        if (fbCheckOutData.getWheelMark() == null) {
            fbCheckOutData.setWheelMark(defaultValue);
        }

        //色差
        if (fbCheckOutData.getColourDifference() == null) {
            fbCheckOutData.setColourDifference(defaultValue);
        }

        //塌边（mm）
        if (fbCheckOutData.getCollapse() == null) {
            fbCheckOutData.setCollapse(defaultValue);
        }

        //滚轮印
        if (fbCheckOutData.getRollerPrint() == null) {
            fbCheckOutData.setRollerPrint(defaultValue);
        }

        //砂轮印扣减(mm)
        if (fbCheckOutData.getWheelPrintReduce() == null) {
            fbCheckOutData.setWheelPrintReduce(defaultValue);
        }

        //粗糙度异常(mm)
        if (fbCheckOutData.getRoughnessAbnormality() == null) {
            fbCheckOutData.setRoughnessAbnormality(defaultValue);
        }

        //斜面扣减(mm)
        if (fbCheckOutData.getBevelDeduction() == null) {
            fbCheckOutData.setBevelDeduction(defaultValue);
        }


        //线痕长度(mm)
        if (fbCheckOutRecord.getLineScratch() == null) {
            fbCheckOutRecord.setLineScratch(defaultValue);
        }

        //划痕长度(mm)
        if (fbCheckOutRecord.getScratch() == null) {
            fbCheckOutRecord.setScratch(defaultValue);
        }

        //刀痕长度(mm)
        if (fbCheckOutRecord.getKnifeScratch() == null) {
            fbCheckOutRecord.setKnifeScratch(defaultValue);
        }

        //崩损(mm)
        if (fbCheckOutRecord.getCollapseLoss() == null) {
            fbCheckOutRecord.setCollapseLoss(defaultValue);
        }

        //崩损灰皮边缘
        if (fbCheckOutRecord.getDamageGreyHideEdge() == null) {
            fbCheckOutRecord.setDamageGreyHideEdge(defaultValue);
        }

        //崩损灰皮非边缘
        if (fbCheckOutRecord.getBrokenGreyNoEdge() == null) {
            fbCheckOutRecord.setBrokenGreyNoEdge(defaultValue);
        }

        //未磨到长度(mm)
        if (fbCheckOutRecord.getNoFriction() == null) {
            fbCheckOutRecord.setNoFriction(defaultValue);
        }

        //晶体灰皮长度(mm)
        if (fbCheckOutRecord.getCrystalGrayness() == null) {
            fbCheckOutRecord.setCrystalGrayness(defaultValue);
        }

        //方棒灰皮长度(mm)
        if (fbCheckOutRecord.getSquareRodGrayness() == null) {
            fbCheckOutRecord.setSquareRodGrayness(defaultValue);
        }

        //灰皮边缘
        if (fbCheckOutRecord.getGreyHideEdge() == null) {
            fbCheckOutRecord.setGreyHideEdge(defaultValue);
        }

        //灰皮非边缘
        if (fbCheckOutRecord.getGreyHideCenter() == null) {
            fbCheckOutRecord.setGreyHideCenter(defaultValue);
        }

        //裂纹
        if (fbCheckOutRecord.getCrack() == null) {
            fbCheckOutRecord.setCrack(defaultValue);
        }

        //尺寸异常长度(mm)
        if (fbCheckOutRecord.getSizeException() == null) {
            fbCheckOutRecord.setSizeException(defaultValue);
        }

        //水印
        if (fbCheckOutRecord.getWaterMark() == null) {
            fbCheckOutRecord.setWaterMark(defaultValue);
        }

        //亮斑
        if (fbCheckOutRecord.getHotSpot() == null) {
            fbCheckOutRecord.setHotSpot(defaultValue);
        }
        //棱崩
        if (fbCheckOutRecord.getRidgeBroken() == null) {
            fbCheckOutRecord.setRidgeBroken(defaultValue);
        }

        //阴阳面
        if (fbCheckOutRecord.getYinYangFace() == null) {
            fbCheckOutRecord.setYinYangFace(defaultValue);
        }

        //砂轮亮点
        if (fbCheckOutRecord.getWheelHighLights() == null) {
            fbCheckOutRecord.setWheelHighLights(defaultValue);
        }
        //外圆手感
        if (fbCheckOutRecord.getRoundHandle() == null) {
            fbCheckOutRecord.setRoundHandle(defaultValue);

        }

        //平面手感
        if (fbCheckOutRecord.getFlatHandle() == null) {
            fbCheckOutRecord.setFlatHandle(defaultValue);
        }

        //砂轮印
        if (fbCheckOutRecord.getWheelMark() == null) {
            fbCheckOutRecord.setWheelMark(defaultValue);
        }

        //色差
        if (fbCheckOutRecord.getColourDifference() == null) {
            fbCheckOutRecord.setColourDifference(defaultValue);
        }

        //塌边（mm）
        if (fbCheckOutRecord.getCollapse() == null) {
            fbCheckOutRecord.setCollapse(defaultValue);
        }

        //滚轮印
        if (fbCheckOutRecord.getRollerPrint() == null) {
            fbCheckOutRecord.setRollerPrint(defaultValue);
        }

        //砂轮印扣减(mm)
        if (fbCheckOutRecord.getWheelPrintReduce() == null) {
            fbCheckOutRecord.setWheelPrintReduce(defaultValue);
        }

        //粗糙度异常(mm)
        if (fbCheckOutRecord.getRoughnessAbnormality() == null) {
            fbCheckOutRecord.setRoughnessAbnormality(defaultValue);
        }

        //斜面扣减(mm)
        if (fbCheckOutRecord.getBevelDeduction() == null) {
            fbCheckOutRecord.setBevelDeduction(defaultValue);
        }
    }

    /**
     * 方棒检验录入默认值
     *
     * @param fbCheckOutData 检验记录
     */
    private void setDefaultsInfo(FbCheckOutData fbCheckOutData, FbCheckOutRecord fbCheckOutRecord) {
        //默认值0
        BigDecimal defaultValue = BigDecimal.ZERO;

        //长度斜(mm)
        if (fbCheckOutData.getLengthSlope() == null) {
            fbCheckOutData.setLengthSlope(defaultValue);
        }
        //头斜(mm)
        if (fbCheckOutData.getHeadSlope() == null) {
            fbCheckOutData.setHeadSlope(defaultValue);
        }
        //尾斜(mm)
        if (fbCheckOutData.getTailSlope() == null) {
            fbCheckOutData.setTailSlope(defaultValue);
        }
        //放行长度(mm)
        if (fbCheckOutData.getConcessionLength() == null) {
            fbCheckOutData.setConcessionLength(defaultValue);
        }
        //返切长度(mm)
        if (fbCheckOutData.getRecutLength() == null) {
            fbCheckOutData.setRecutLength(defaultValue);
        }
        //缝宽(mm)
        if (fbCheckOutData.getCrackWidth() == null) {
            fbCheckOutData.setCrackWidth(defaultValue);
        }
        //平边晶向
        if (StringUtils.isBlank(fbCheckOutData.getFlatOrientation())) {
            fbCheckOutData.setFlatOrientation("0");
        }
        //晶体晶向(mm)
        if (StringUtils.isBlank(fbCheckOutData.getOrientation())) {
            fbCheckOutData.setOrientation("0");
        }
        //直径max
        if (fbCheckOutData.getDiameterMax() == null) {
            fbCheckOutData.setDiameterMax(defaultValue);
        }
        //直径min
        if (fbCheckOutData.getDiameterMin() == null) {
            fbCheckOutData.setDiameterMin(defaultValue);
        }
        //边长max
        if (fbCheckOutData.getSideLengthMax() == null) {
            fbCheckOutData.setSideLengthMax(defaultValue);
        }
        //边长min
        if (fbCheckOutData.getSideLengthMin() == null) {
            fbCheckOutData.setSideLengthMin(defaultValue);
        }
        //垂直度max
        if (fbCheckOutData.getVerticalityMax() == null) {
            fbCheckOutData.setVerticalityMax(defaultValue);
        }
        //垂直度min
        if (fbCheckOutData.getVerticalityMin() == null) {
            fbCheckOutData.setVerticalityMin(defaultValue);
        }
        //弧长投影max
        if (fbCheckOutData.getProjectionMax() == null) {
            fbCheckOutData.setProjectionMax(defaultValue);
        }
        //弧长投影min
        if (fbCheckOutData.getProjectionMin() == null) {
            fbCheckOutData.setProjectionMin(defaultValue);
        }
        //弦长max
        if (fbCheckOutData.getChordLengthMax() == null) {
            fbCheckOutData.setChordLengthMax(defaultValue);
        }
        //弦长min
        if (fbCheckOutData.getChordLengthMin() == null) {
            fbCheckOutData.setChordLengthMin(defaultValue);
        }
        //平面锥度max
        if (fbCheckOutData.getPlaneTaperMax() == null) {
            fbCheckOutData.setPlaneTaperMax(defaultValue);
        }
        //平面锥度min
        if (fbCheckOutData.getPlaneTaperMin() == null) {
            fbCheckOutData.setPlaneTaperMin(defaultValue);
        }


        //长度斜(mm)
        if (fbCheckOutRecord.getLengthSlope() == null) {
            fbCheckOutRecord.setLengthSlope(defaultValue);
        }
        //头斜(mm)
        if (fbCheckOutRecord.getHeadSlope() == null) {
            fbCheckOutRecord.setHeadSlope(defaultValue);
        }
        //尾斜(mm)
        if (fbCheckOutRecord.getTailSlope() == null) {
            fbCheckOutRecord.setTailSlope(defaultValue);
        }
        //放行长度(mm)
        if (fbCheckOutRecord.getConcessionLength() == null) {
            fbCheckOutRecord.setConcessionLength(defaultValue);
        }
        //返切长度(mm)
        if (fbCheckOutRecord.getRecutLength() == null) {
            fbCheckOutRecord.setRecutLength(defaultValue);
        }
        //缝宽(mm)
        if (fbCheckOutRecord.getCrackWidth() == null) {
            fbCheckOutRecord.setCrackWidth(defaultValue);
        }
        //平边晶向
        if (StringUtils.isBlank(fbCheckOutRecord.getFlatOrientation())) {
            fbCheckOutRecord.setFlatOrientation("0");
        }
        //晶体晶向(mm)
        if (StringUtils.isBlank(fbCheckOutRecord.getOrientation())) {
            fbCheckOutRecord.setOrientation("0");
        }
        //直径max
        if (fbCheckOutRecord.getDiameterMax() == null) {
            fbCheckOutRecord.setDiameterMax(defaultValue);
        }
        //直径min
        if (fbCheckOutRecord.getDiameterMin() == null) {
            fbCheckOutRecord.setDiameterMin(defaultValue);
        }
        //边长max
        if (fbCheckOutRecord.getSideLengthMax() == null) {
            fbCheckOutRecord.setSideLengthMax(defaultValue);
        }
        //边长min
        if (fbCheckOutRecord.getSideLengthMin() == null) {
            fbCheckOutRecord.setSideLengthMin(defaultValue);
        }
        //垂直度max
        if (fbCheckOutRecord.getVerticalityMax() == null) {
            fbCheckOutRecord.setVerticalityMax(defaultValue);
        }
        //垂直度min
        if (fbCheckOutRecord.getVerticalityMin() == null) {
            fbCheckOutRecord.setVerticalityMin(defaultValue);
        }
        //弧长投影max
        if (fbCheckOutRecord.getProjectionMax() == null) {
            fbCheckOutRecord.setProjectionMax(defaultValue);
        }
        //弧长投影min
        if (fbCheckOutRecord.getProjectionMin() == null) {
            fbCheckOutRecord.setProjectionMin(defaultValue);
        }
        //弦长max
        if (fbCheckOutRecord.getChordLengthMax() == null) {
            fbCheckOutRecord.setChordLengthMax(defaultValue);
        }
        //弦长min
        if (fbCheckOutRecord.getChordLengthMin() == null) {
            fbCheckOutRecord.setChordLengthMin(defaultValue);
        }
        //平面锥度max
        if (fbCheckOutRecord.getPlaneTaperMax() == null) {
            fbCheckOutRecord.setPlaneTaperMax(defaultValue);
        }
        //平面锥度min
        if (fbCheckOutRecord.getPlaneTaperMin() == null) {
            fbCheckOutRecord.setPlaneTaperMin(defaultValue);
        }
    }

    /**
     * 根据检验名称计算方棒入库长度
     * <p>
     * 正常单晶：（方棒长度-线痕 、划痕、刀痕、崩损、未磨到、晶体灰皮、方棒灰皮、棱崩、亮斑）
     *
     * @param fbCheckOutRecord
     */
    private void setInstoreLength(FbCheckOutRecord fbCheckOutRecord) {
        if (fbCheckOutRecord.getCheckoutName().equals("正常单晶")) {
            if (fbCheckOutRecord.getLength() != null && fbCheckOutRecord.getLineScratch() != null
                    && fbCheckOutRecord.getScratch() != null && fbCheckOutRecord.getKnifeScratch() != null
                    && fbCheckOutRecord.getCollapseLoss() != null && fbCheckOutRecord.getNoFriction() != null
                    && fbCheckOutRecord.getCrystalGrayness() != null && fbCheckOutRecord.getSquareRodGrayness() != null
                    && fbCheckOutRecord.getRidgeBroken() != null && fbCheckOutRecord.getHotSpot() != null) {
                BigDecimal instoreLenthFb = fbCheckOutRecord.getLength().subtract(fbCheckOutRecord.getLineScratch()).subtract(fbCheckOutRecord.getScratch()).subtract(fbCheckOutRecord.getKnifeScratch())
                        .subtract(fbCheckOutRecord.getCollapseLoss()).subtract(fbCheckOutRecord.getNoFriction()).subtract(fbCheckOutRecord.getCrystalGrayness())
                        .subtract(fbCheckOutRecord.getSquareRodGrayness()).subtract(fbCheckOutRecord.getRidgeBroken()).subtract(fbCheckOutRecord.getHotSpot());
                fbCheckOutRecord.setInstoreLengthFb(instoreLenthFb);
            }
        }
        if (fbCheckOutRecord.getCheckoutName().equals("二类单晶")) {

        }
    }

    private void setConsumeLengthYbByReCutDetail(FbCheckOutRecord fbCheckOutRecord) {
        RecutDetail recutDetail = recutDetailDao.findBySectionNoFb(fbCheckOutRecord.getFbSectionNo());
        if (recutDetail == null) {
            throw new BusinessException("未查询到反切数据");
        }
        fbCheckOutRecord.setConsumeLengthYb(recutDetail.getParentId() == 0 ? fbCheckOutRecord.getInstoreLengthYb() : fbCheckOutRecord.getLength());


    }

    /**
     * 根据规格计算方棒称重、理论重量并赋值
     * <p>
     * <p>
     * 方棒称重 :方棒长度 * 方棒实际称重系数
     * 方棒理论重量: 入库长度 / 理论重量系数
     *
     * @param fbCheckOutRecord
     */
    private void setWeightBySpecification(FbCheckOutRecord fbCheckOutRecord, FbCheckOutData fbCheckOutData) {
        //改计算公式赋值
//        String fbSpecs = "";
//        String fbLength = "";
        if (fbCheckOutRecord.getSpecification() != null && fbCheckOutRecord.getWeight().intValue() == 0 && fbCheckOutRecord.getLength() != null) {
//            String[] split = fbCheckOutRecord.getSpecification().split("[*]");
//            if (split.length > 0) {
//                fbSpecs = split[0];
//                fbLength = split[1];
//            }
            // 方棒称重 :方棒长度 * 方棒实际称重系数
            String productWeight = this.dictionaryItemDao.findValueByThemeValueAndItemNameAndItemExtendValue("ProductWeight", fbCheckOutRecord.getSpecification());
            if (StringUtils.isNotBlank(productWeight)) {
                BigDecimal FbweightDecimal = fbCheckOutRecord.getLength().multiply(new BigDecimal(productWeight));
                BigDecimal Fbweight = FbweightDecimal.setScale(2, BigDecimal.ROUND_DOWN);// 保留2位小数
                fbCheckOutRecord.setWeight(Fbweight);
                fbCheckOutData.setWeight(Fbweight);
            }
            // 方棒理论重量: 入库长度 / 理论重量系数
//        String weightRatio = this.dictionaryItemDao.findValueByThemeValueAndItemExtendValue("WeightRatio", fbSpecs);
//        if (StringUtils.isNotBlank(weightRatio)) {
//            BigDecimal weightRatioDecimal = fbCheckOutRecord.getInstoreLengthFb().divide(new BigDecimal(weightRatio), 3, RoundingMode.HALF_UP);
//            fbCheckOutRecord.setTheoryWeightFb(weightRatioDecimal);
//        }
        }
    }

    @Override
    public Result<FbCheckOutRecordDto> findFbCheckOutRecordInfoById(Long id) {
        //查询方棒检验数据库
        FbCheckOutRecord fbCheckOutRecord = this.get(Integer.parseInt(id.toString()));
        if (fbCheckOutRecord == null) {
            return ResultGenerator.fail("该方棒对应方棒检验信息不存在！");
        }

        Result<GetFbInfoDto> fbInfoByIdResult = ybFeignService.findFbInfoBySectionNoYb(fbCheckOutRecord.getYbSectionNo());
        if (fbInfoByIdResult.getCode() != ResultCode.SUCCESS.getCode()) {
            return ResultGenerator.fail(fbInfoByIdResult.getMessage());
        }
        GetFbInfoDto fbInfoById = fbInfoByIdResult.getData();
//
//        GetFbInfoDto fbInfoById = ybFeignService.findFbInfoBySectionNoYb(fbCheckOutRecord.getYbSectionNo());
//        if(fbInfoById == null){
//            return ResultGenerator.fail("该方棒对应圆棒:【" + fbCheckOutRecord.getYbSectionNo() + "】信息不存在,请先录入圆棒数据");
//        }

        if (fbInfoById.getYbExperiLevel() == null) {
            fbInfoById.setYbExperiLevel(fbInfoById.getProductLevelExperiment());
        }

        //重新赋值产品等级
        fbCheckOutRecord.setProductLevel(fbInfoById.getProductLevel());
        //重新赋值实验等级
        fbCheckOutRecord.setYbExperiLevel(fbInfoById.getYbExperiLevel());

        FbCheckOutRecordDto map = modelMapper.map(fbCheckOutRecord, FbCheckOutRecordDto.class);
        //todo 用反切明细的长度  返回结果增加个字段记录创建接口查询的那个长度
        Result<GetFbInfoDto> fbInfoBySectionNoYb = ybFeignService.findFbInfoBySectionNoYb(fbCheckOutRecord.getFbSectionNo());
        if (fbInfoBySectionNoYb.getCode() == ResultCode.SUCCESS.getCode()) {
            GetFbInfoDto data = fbInfoBySectionNoYb.getData();
            if (null != data.getLength()) {
                map.setUnmodifiedLength(data.getLength());
            }
        }
        if (null == map.getUnmodifiedLength()) {
            String length = dao.getProductionPaintingLineDetail(fbCheckOutRecord.getFbSectionNo());
            map.setUnmodifiedLength(new BigDecimal(length));
        }

        //磨削下料记录
        GrindingBlanking topByFbSectionNoOrderByIdDesc = grindingBlankingService.findTopByFbSectionNoOrderByIdDesc(map.getFbSectionNo());
        if (topByFbSectionNoOrderByIdDesc != null) {
            //赋边长和直径
            map.setEapDiameterMax(topByFbSectionNoOrderByIdDesc.getEapDiameterMax());
            map.setEapDiameterMin(topByFbSectionNoOrderByIdDesc.getEapDiameterMin());
//            List<BigDecimal> sides = Arrays.asList(topByFbSectionNoOrderByIdDesc.getEapSide1(), topByFbSectionNoOrderByIdDesc.getEapSide2(), topByFbSectionNoOrderByIdDesc.getEapSide3(), topByFbSectionNoOrderByIdDesc.getEapSide4(), topByFbSectionNoOrderByIdDesc.getEapSide5(), topByFbSectionNoOrderByIdDesc.getEapSide6());
            BigDecimal maxSide = topByFbSectionNoOrderByIdDesc.getBeforhud12();
            BigDecimal minSide = topByFbSectionNoOrderByIdDesc.getBeforhdd12();
            map.setEapSideMin(minSide);
            map.setEapSideMax(maxSide);
        }


        return ResultGenerator.success(map);
    }

    /**
     * 查询方棒时候需要抽检
     *
     * @return
     */
    @Override
    public Flag4MDto whetherOrNotSampling(String sectionNoFb) {
        Flag4MDto flag4MDto = new Flag4MDto();
        flag4MDto.setFlag4M(false);
        flag4MDto.setFlagSizeCheck(false);
        String result = "结果 : " + JSON.toJSONString(flag4MDto);
        try {
            try {
                GrindingBlanking grindingBlanking = grindingBlankingService.findTopByFbSectionNoOrderByIdDesc(sectionNoFb);
                if (grindingBlanking != null) {
                    //eap磨削下料记录4M标识为1则为抽检
                    if (grindingBlanking.getFlag4M() != null && grindingBlanking.getFlag4M() >= 1) {
                        flag4MDto.setFlagSizeCheck(true);
                        flag4MDto.setFlag4M(true);
                        result = "sn" + grindingBlanking.getSn() + ",||磨削下料上传4M标识：" + grindingBlanking.getFlag4M() + "||结果 : " + JSON.toJSONString(flag4MDto);
                    } else {
                        if (grindingBlanking.getEquipNo() != null) {
                            //根据方棒编号匹配外观检验规则
                            List<FbAppearRule> fbAppearRuleList = fbAppearRuleService.findFbAppearRuleBySeries(grindingBlanking.getEquipNo().replace("MX", ""));
                            if (fbAppearRuleList != null && fbAppearRuleList.size() > 0) {
                                for (FbAppearRule fbAppearRule : fbAppearRuleList) {
                                    if (fbAppearRule.getPiecesNum() != null) {
                                        String piecesNum = StringUtils.unwrap(fbAppearRule.getPiecesNum(), ",").replace("，", ",");
                                        String[] split = piecesNum.split(",");
                                        for (String num : split) {
                                            if (num.equals(grindingBlanking.getGrindingOrder())) {
                                                flag4MDto.setFlagSizeCheck(true);
                                            }
                                        }
                                    }
                                }
                            }
                            result = "sn:" + grindingBlanking.getSn() + "||equipNo：" + grindingBlanking.getEquipNo() +
                                    "||磨面顺序号grindingOrder:" + grindingBlanking.getGrindingOrder() + "||匹配外观检验规则：" + JSON.toJSONString(fbAppearRuleList) + "||结果 : " + JSON.toJSONString(flag4MDto);
                        }
                    }
                }
            } catch (Exception e) {
                result = "sn:" + sectionNoFb + " || Exception" + e.getMessage();
            }
            SysLog syslog = new SysLog();
            syslog.setCreateTime(new Date());
            syslog.setType("info");
            syslog.setStatus(ResultCode.SUCCESS.getCode());
            syslog.setCreateUserId(BaseContextHandler.getUserID());
            syslog.setCreateUserName(BaseContextHandler.getUsername());
            syslog.setContent(sectionNoFb);
            syslog.setMethodName("whetherOrNotSampling");
            syslog.setName("匹配方棒是否抽检：" + sectionNoFb);
            syslog.setServerAddr("http://" + IpUtils.getLocalIP());
            syslog.setReqType("GET");
            syslog.setReqIp(IpUtils.getWebServiceReqIP());
            syslog.setResult(result);
            sysLogService.save(syslog);
        } catch (Exception e) {

        }
        return flag4MDto;
    }

    @Override
    public List<FbCheckOutRecord> findBySectionNoList(List<String> sectionNoList) {
        return dao.findBySectionNoList(sectionNoList);
    }
    public FbCheckOutData toData(FbCheckOutRecordDto dto) {
        FbCheckOutData data = new FbCheckOutData();

        BeanUtils.copyProperties(dto, data, BeanUtil.getIgnoreProperties(dto, null, null));
        return data;
    }


    public FbCheckOutData toUpdateData(FbCheckOutRecordDto dto, FbCheckOutData checkOutData) {


        BeanUtils.copyProperties(dto, checkOutData, BeanUtil.getIgnoreProperties(dto, null, null));
        checkOutData.setId(checkOutData.getId());
        return checkOutData;
    }

    public FbCheckOutRecord fromDto(FbCheckOutRecordDto dto) {
        return modelMapper.map(dto, FbCheckOutRecord.class);
    }

}
