package com.sw.mes.inspect.service.impl;


import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sw.mes.base.factory.init.entity.CrystalMaterialRelation;
import com.sw.mes.base.factory.init.entity.Equipment;
import com.sw.mes.base.factory.init.entity.FactoryModel;
import com.sw.mes.base.factory.init.service.CrystalMaterialRelationService;
import com.sw.mes.base.factory.init.service.DeviceService;
import com.sw.mes.base.factory.init.service.EquipmentService;
import com.sw.mes.base.factory.init.service.FactoryModelService;
import com.sw.mes.base.factory.inspect.entity.DefaultSample;
import com.sw.mes.base.factory.inspect.entity.EarlyWarningManagement;
import com.sw.mes.base.factory.inspect.entity.WarningRuleConfiguration;
import com.sw.mes.base.factory.inspect.service.DefaultCrystalAttrService;
import com.sw.mes.base.factory.inspect.service.DefaultSampleService;
import com.sw.mes.base.factory.inspect.service.EarlyWarningManagementService;
import com.sw.mes.base.factory.inspect.service.WarningRuleConfigurationService;
import com.sw.mes.base.factory.material.entity.MaterialModel;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.base.factory.utils.excel.EasyExcelUtil;
import com.sw.mes.base.global.GlobalSwitch;
import com.sw.mes.base.global.GlobalSwitchNamespace;
import com.sw.mes.base.system.dto.InventoryManageLogExcelDto;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.entity.InventoryManageLog;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.system.service.InventoryManageLogService;
import com.sw.mes.base.system.service.SysLogService;
import com.sw.mes.base.workinprocess.dto.CurrentWipStorageStatusDto;
import com.sw.mes.base.workinprocess.dto.ErrorClosePlanProcessingOrderDto;
import com.sw.mes.base.workinprocess.dto.PlanProcessingOrderDto;
import com.sw.mes.base.workinprocess.entity.PlanProcessingOrder;
import com.sw.mes.base.workinprocess.entity.WipStorage;
import com.sw.mes.base.workinprocess.service.CrystalLossRecordService;
import com.sw.mes.base.workinprocess.service.PlanProcessingOrderService;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.config.rabbit.InspectDataBaseChangeAsync;
import com.sw.mes.core.annotation.ServiceLogs;
import com.sw.mes.core.api.system.FbFeignClients;
import com.sw.mes.core.api.system.StoreFeignClients;
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.PushSapDto;
import com.sw.mes.core.dto.RankResultDto;
import com.sw.mes.core.dto.WarehouseModelDto;
import com.sw.mes.core.dto.YbInspectDataToMcsDto;
import com.sw.mes.core.dto.sap.SendReportSapGoodsmvtDto;
import com.sw.mes.core.dto.store.*;
import com.sw.mes.core.entity.CrystalLossRecord;
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.enums.SeedMassageEnum;
import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.*;
import com.sw.mes.dingTalk.service.DingTalkService;
import com.sw.mes.enumvalue.EnumValuesServer;
import com.sw.mes.grade.entity.RuleTest;
import com.sw.mes.grade.entity.RuleTestData;
import com.sw.mes.grade.service.GradeService;
import com.sw.mes.grade.service.RuleTestDataService;
import com.sw.mes.grade.service.RuleTestService;
import com.sw.mes.gread.common.EnumValuesGrade;
import com.sw.mes.gread.entity.FieldPool;
import com.sw.mes.gread.entity.GradeRule;
import com.sw.mes.gread.entity.GradeVersion;
import com.sw.mes.gread.service.FieldPoolService;
import com.sw.mes.gread.service.GradeRuleService;
import com.sw.mes.gread.service.GradeVersionService;
import com.sw.mes.inspect.dao.YbInspectDataDao;
import com.sw.mes.inspect.dto.YbInspectDataCUDto;
import com.sw.mes.inspect.dto.YbInspectDataPdaAutomaticDto;
import com.sw.mes.inspect.dto.YbInspectDataSideLengthUpdateDto;
import com.sw.mes.inspect.entity.AutomaticInspectMiddle;
import com.sw.mes.inspect.entity.YbInspectData;
import com.sw.mes.inspect.entity.YbInspectDataLog;
import com.sw.mes.inspect.service.AutomaticInspectMiddleService;
import com.sw.mes.inspect.service.YbInspectDataLogService;
import com.sw.mes.inspect.service.YbInspectDataService;
import com.sw.mes.sap.entity.ReportSapGoodsmvt;
import com.sw.mes.sap.entity.ReportSapWorkinghours;
import com.sw.mes.sap.service.ReportSapGoodsmvtService;
import com.sw.mes.sap.service.ReportSapWorkinghoursService;
import com.sw.mes.utils.ExcelUtil;
import com.sw.mes.utils.StringUtils;
import com.sw.mes.wipstorage.service.WipStorageYbService;
import com.sw.mes.yb.alloy.entity.AlloyMasterAlloy;
import com.sw.mes.yb.alloy.service.AlloyMasterAlloyService;
import com.sw.mes.yb.check.dao.PieceCheckDAO;
import com.sw.mes.yb.check.entity.PieceCheck;
import com.sw.mes.yb.check.service.PieceCheckService;
import com.sw.mes.yb.mcs.dto.YbCheckResultDto;
import com.sw.mes.yb.mcs.service.CodingRecordService;
import com.sw.mes.yb.pad.dao.PieceDetailDao;
import com.sw.mes.yb.pad.dao.SectionNoDetailDao;
import com.sw.mes.yb.pad.entity.ProductionBackCuttingRecord;
import com.sw.mes.yb.pad.entity.ProductionPaintingLine;
import com.sw.mes.yb.pad.entity.ProductionPaintingLineDetail;
import com.sw.mes.yb.pad.entity.SectionNoDetail;
import com.sw.mes.yb.pad.service.ProductionPaintingLineDetailService;
import com.sw.mes.yb.pad.service.ProductionPaintingLineService;
import com.sw.mes.yb.pad.service.ProductionRecutService;
import com.sw.mes.yb.pad.service.SectionNoDetailService;
import com.sw.mes.yb.pc.dto.GetFbInfoDto;
import com.sw.mes.yb.pc.entity.DataInspectLog;
import com.sw.mes.yb.pc.service.DataInspectLogService;
import com.sw.mes.yb.plan.entity.ProductionOrder;
import com.sw.mes.yb.plan.service.ProductionOrderService;
import com.sw.mes.yb.production.entity.CrystalBatchOperation;
import com.sw.mes.yb.production.entity.LongCrystal;
import com.sw.mes.yb.production.entity.OutgoMarkOperate;
import com.sw.mes.yb.production.service.CrystalBatchOperationService;
import com.sw.mes.yb.production.service.LongCrystalService;
import com.sw.mes.yb.production.service.OutgoMarkOperateService;
import com.sw.mes.yb.seed.enums.InputBillStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Slf4j
@Service
@Transactional
public class YbInspectDataServiceImpl extends BaseServiceImpl<YbInspectData> implements YbInspectDataService {
    YbInspectDataDao dao;

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

    @Autowired
    private GradeService gradeService;

    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;

    @Autowired
    private RuleTestService ruleTestService;

    @Autowired
    private RuleTestDataService ruleTestDataService;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private InspectDataBaseChangeAsync inspectDataBaseChangeAsync;

    @Autowired
    private YbInspectDataLogService ybInspectDataLogService;

    @Autowired
    private ProductionRecutService productionRecutService;
    @Autowired
    private ProductionPaintingLineDetailService productionPaintingLineDetailService;
    @Autowired
    private ProductionPaintingLineService productionPaintingLineService;
    @Autowired
    private SectionNoDetailDao sectionNoDetailDao;
    @Autowired
    private DictionaryItemService dictionaryItemService;
    @Autowired
    private PieceDetailDao pieceDetailDao;
    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private PieceCheckDAO pieceCheckDAO;

    @Autowired
    private DataInspectLogService dataInspectLogService;

    @Autowired
    private CodingRecordService codingRecordService;

    @Autowired
    InventoryManageLogService inventoryManageLogService;

    @Autowired
    private YbInspectDataService ybInspectDataService;


    @Autowired
    private CrystalBatchOperationService crystalBatchOperationService;

    @Autowired
    private WarningRuleConfigurationService warningRuleConfigurationService;

    @Autowired
    private EarlyWarningManagementService earlyWarningManagementService;

    @Autowired
    private FieldPoolService fieldPoolService;

    @Autowired
    private AutomaticInspectMiddleService automaticInspectMiddleService;

    @Autowired
    private GradeRuleService gradeRuleService;

    @Autowired
    private GradeVersionService gradeVersionService;

    @Autowired
    private FbFeignClients fbFeignClients;

    @Autowired
    private DingTalkService dingTalkService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private AlloyMasterAlloyService alloyMasterAlloyService;

    @Autowired
    ModelMapper modelMapper;

    private static final String T = "1Y";
    private static final String W = "1Y";

    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        Specification<InventoryManageLog> specification = DynamicSpecifications.bySearchFilter(request, InventoryManageLog.class);
        List<InventoryManageLog> InventoryManageLogs = inventoryManageLogService.findByExampleSort(specification, null);
        try {
//            List<String> sectionNos = InventoryManageLogs.stream().map(InventoryManageLog::getRoundSn).collect(Collectors.toList());
//            List<YbInspectData> ybInspectDataList = this.findBySections(sectionNos);
            List<InventoryManageLogExcelDto> inventoryManageLogExcelDtoList = new ArrayList<>();
            if (!InventoryManageLogs.isEmpty()) {
                InventoryManageLogs.stream().forEach(inventoryManageLog -> {
                    InventoryManageLogExcelDto inventoryManageLogExcelDto = new InventoryManageLogExcelDto();
                    YbInspectData ybInspectData = this.findBySectionNo(inventoryManageLog.getRoundSn());
                    if (null != ybInspectData) {
                        inventoryManageLogExcelDto.setOrderNo(ybInspectData.getOrderNo());
                        inventoryManageLogExcelDto.setMaterialCode(ybInspectData.getMaterialCode());
                        inventoryManageLogExcelDto.setProductTypeSecond(ybInspectData.getProductTypeSecond());
                        inventoryManageLogExcelDto.setCheckoutName(ybInspectData.getCheckoutName());
                        inventoryManageLogExcelDto.setProductLevel(ybInspectData.getProductLevel());
                        inventoryManageLogExcelDto.setProductLevelExperiment(ybInspectData.getProductLevelExperiment());
                        inventoryManageLogExcelDto.setConductiveType(ybInspectData.getConductiveType());
                        inventoryManageLogExcelDto.setActualLength(ybInspectData.getActualLength());
                        inventoryManageLogExcelDto.setActualWeight(ybInspectData.getActualWeight());
                    }
                    inventoryManageLogExcelDto.setSectionNo(inventoryManageLog.getRoundSn());
                    inventoryManageLogExcelDto.setCreateTime(inventoryManageLog.getCreateTime());
                    inventoryManageLogExcelDtoList.add(inventoryManageLogExcelDto);
                });
            }
            EasyExcelUtil.setResponse(response);
            EasyExcel.write(response.getOutputStream(), InventoryManageLogExcelDto.class).sheet("出入库记录导出Excel").doWrite(inventoryManageLogExcelDtoList);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<YbInspectData> findBySections(List<String> sectionNoList) {
        return dao.findBySections(sectionNoList);
    }

    @Override
    public Map<String, Object> findBySectionNoMap(String sectionNo) {
        List<Map<String, Object>> inspectData = dao.findBySectionNoMap(sectionNo);
        if (inspectData != null && inspectData.size() > 0) {
            return inspectData.get(0);
        }
        return null;
    }

    @Override
    public YbInspectData findBySectionNo(String sectionNo) {
        List<YbInspectData> inspectData = dao.findBySectionNo(sectionNo);
        if (inspectData != null && inspectData.size() > 0) {
            return inspectData.get(0);
        }
        return null;
    }

    @Override
    public YbInspectData findByLikeSectionNo(String sectionNo) {
        return dao.findByLikeSectionNo("%" + sectionNo + "%");
    }

    @Override
    public List<YbInspectData> getInspectDatasByCrystalNo(String crystalNo) {
        List<YbInspectData> datas = dao.getInspectDatasByCrystalNo(crystalNo);
        if (datas != null && datas.size() > 0) {
            return datas;
        }
        return null;
    }

    @Override
    public YbInspectData getSectionNo(String sectionNo) {
        sectionNo = sectionNo + "%";
        List<YbInspectData> inspectData = dao.getSectionNo(sectionNo);
        if (inspectData != null && inspectData.size() > 0) {
            return inspectData.get(0);
        }
        return null;
    }


    /**
     * 根据晶段编号获取 圆棒检验数据库详细信息
     *
     * @param sectionNo
     * @return
     */
    @Override
    public YbInspectDataCUDto getYbInspectDataDto(String sectionNo) {
        sectionNo = com.sw.mes.core.utils.StringUtils.trim(sectionNo);
        wipStorageService.selectWipStorage(sectionNo, EnumValuesFactory.WipStorageCode.圆棒检验.getKey(), false);
        YbInspectData ybInspectData = this.findBySectionNo(sectionNo);
        if (null == ybInspectData) {
            ybInspectData = new YbInspectData();
            // 通过圆棒编号 去追溯表判断晶段是否存在
            SectionNoDetail sectionNoDetail = sectionNoDetailService.findBySectionNo(sectionNo);
            if (sectionNoDetail == null) {
                throw new RuntimeException(sectionNo + "晶段信息不存在，数据异常");
            }
            LongCrystal longCrystal = longCrystalService.get(sectionNoDetail.getCrystalId());
            if (longCrystal == null) {
                throw new RuntimeException(sectionNo + "长棒信息不存在，数据异常");
            }
            ybInspectData.setSectionNo(sectionNo);
            ybInspectData.setDiameterMax(longCrystal.getMaxDiam());
            ybInspectData.setDiameterMin(longCrystal.getMinDiam());
            this.initInspectData(ybInspectData, sectionNoDetail, longCrystal);
        }
        YbInspectDataCUDto ybInspectDataCuDto = new YbInspectDataCUDto();
        BeanUtil.copyBeanPropWithNullValue(ybInspectDataCuDto, ybInspectData, "id");
        return ybInspectDataCuDto;
    }

    @Override
    public List<YbInspectData> findByLotNo(String lotNo) {
        return dao.findByLotNo(lotNo);
    }

    @Override
    public void updateOrderTypeBySectionNoList(List<String> sectionNoList, String orderType, String checkoutName) {
        if (CollectionUtils.isNotEmpty(sectionNoList)) {
            dao.updateOrderTypeBySectionNoList(sectionNoList, orderType, checkoutName);
        }
    }

    @Override
    public void updateOrderTypeBySectionNoListNoType(List<String> sectionNoList, String orderType, String checkoutName) {
        if (CollectionUtils.isNotEmpty(sectionNoList)) {
            dao.updateOrderTypeBySectionNoListNoType(sectionNoList, orderType, checkoutName);
        }
    }


    @Override
    public Integer updateSticksCountFbSectionNoList(List<String> sectionNoList, Integer sticksCount, BigDecimal totalLength, String sectionType, String SectionNoGroup) {
        return dao.updateSticksCountFbSectionNoList(sectionNoList, sticksCount, totalLength, sectionType, SectionNoGroup);
    }

    @Autowired
    private SectionNoDetailService sectionNoDetailService;
    @Autowired
    private LongCrystalService longCrystalService;
    @Autowired
    private ProductionOrderService productionOrderService;
    @Autowired
    private DefaultCrystalAttrService defaultCrystalAttrService;
    @Autowired
    private DefaultSampleService defaultSampleService;

    @Autowired
    private PieceCheckService pieceCheckService;

    @Autowired
    private OutgoMarkOperateService outgoMarkOperateService;

    @Autowired
    private WipStorageYbService wipStorageYbService;

    @Autowired
    private ReportSapGoodsmvtService reportSapGoodsmvtService;

    @Autowired
    private ReportSapWorkinghoursService reportSapWorkinghoursService;
    @Autowired
    private CrystalMaterialRelationService crystalMaterialRelationService;

    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private MaterialModelService materialModelService;

    @Autowired
    private StoreFeignClients storeFeignClients;

    @Autowired
    private CrystalLossRecordService crystalLossRecordService;
    @Autowired
    private FactoryModelService factoryModelService;

    @Override
    public Result saveYbInspectData(YbInspectDataCUDto ybInspectDataCdto) {

        /**
         * 根据头尾信息自动计算中间段
         * 1、查询是否开启：开启则自动计算
         * 2、需要头部头信息及尾部尾信息都存在并且电性能合格才计算
         * 3、需要查询划线明细找到所有单晶计算系数
         *
         * 1. （头中心电阻-尾中心电阻）/（1Y长度+2Y长度+3Y长度.........+WY长度）=C(系数)
         * 2. 1Y、2Y、3Y......WY电性能必须为合格( 电阻范围0.4-1.1；  寿命大于70（W寿命）)
         * 3. 边缘电阻=中心电阻+0.1
         *
         * （B=W ;A=T）
         * 1. 1Y的B面电阻=2Y的A面电阻，2Y的B面电阻=3Y的A面电阻.........以此类推
         * 4. 1Y的B面中心电阻=头部中心电阻-（C*1Y的长度），1Y的B边缘电阻=1Y的B面中心电阻+0.1
         * 5. 2Y的B面中心电阻=1Y的B面中心电阻-（C*2Y的长度），2Y的B边缘电阻=2Y的B面中心电阻+0.1，
         * 6. 3Y的B面中心电阻=2Y的B面中心电阻-（C*3Y的长度），3Y的B边缘电阻=3Y的B面中心电阻+0.1，
         * 7. 寿命计算公式同上
         * 8. 唯一不同，边缘寿命=中心寿命+80
         *
         * 当头段尾段数据发生反切时，中间段寿命、电阻率不随着发生变化；反切情况，中间段可不需考虑。
         */

        Boolean whetherAllInput = false;
       /* //查询数据字典
        List<DictionaryItem> automaticCalculation = dictionaryItemService.findByThemeValueAndEnable("automaticCalculation", true);
        Map<String, String> collect = automaticCalculation.stream().collect(Collectors.toMap(DictionaryItem::getName, DictionaryItem::getValue));
        if (collect.containsKey("是否开启") && collect.get("是否开启").equals("1")) {

            List<ProductionPaintingLineDetail> productionPaintingLineDetails = new ArrayList<>();
            YbInspectData bySectionNo;
            //电阻率
            BigDecimal tRadialCentre = new BigDecimal(0);
            BigDecimal tRadialEdge1 = new BigDecimal(0);
            BigDecimal tRadialEdge2 = new BigDecimal(0);
            BigDecimal wRadialCentre = new BigDecimal(0);
            BigDecimal wRadialEdge1 = new BigDecimal(0);
            BigDecimal wRadialEdge2 = new BigDecimal(0);

            //寿命
            BigDecimal tCentreLife = new BigDecimal(0);
            BigDecimal tLifeEdge1 = new BigDecimal(0);
            BigDecimal tLifeEdge2 = new BigDecimal(0);
            BigDecimal wCentreLife = new BigDecimal(0);
            BigDecimal wLifeEdge11 = new BigDecimal(0);
            BigDecimal wLifeEdge12 = new BigDecimal(0);

            BigDecimal resistivityCoefficient = new BigDecimal(0);
            BigDecimal lifeCoefficient = new BigDecimal(0);

            //判断TW段信息是否全部录入以及电性能是否合格
            if (ybInspectDataCdto.getSectionNo().endsWith("1Y")) {
                String sectionNo = ybInspectDataCdto.getSectionNo().substring(0, ybInspectDataCdto.getSectionNo().lastIndexOf("1Y")) + "WY";
                bySectionNo = ybInspectDataService.findBySectionNo(sectionNo);
                if (null != bySectionNo) {
                    tRadialCentre = ybInspectDataCdto.getTRadialCentre();
                    tRadialEdge1 = ybInspectDataCdto.getTRadialEdge1();
                    tRadialEdge2 = ybInspectDataCdto.getTRadialEdge2();
                    wRadialCentre = bySectionNo.getWRadialCentre();
                    wRadialEdge1 = bySectionNo.getWLifeEdge1();
                    wRadialEdge2 = bySectionNo.getWLifeEdge2();

                    tCentreLife = ybInspectDataCdto.getTCentreLife();
                    tLifeEdge1 = ybInspectDataCdto.getTLifeEdge1();
                    tLifeEdge2 = ybInspectDataCdto.getTLifeEdge2();
                    wCentreLife = bySectionNo.getWCentreLife();
                    wLifeEdge11 = bySectionNo.getWLifeEdge1();
                    wLifeEdge12 = bySectionNo.getWLifeEdge2();
                }

            }
            if (ybInspectDataCdto.getSectionNo().endsWith("WY")) {
                String sectionNo = ybInspectDataCdto.getSectionNo().substring(0, ybInspectDataCdto.getSectionNo().lastIndexOf("WY")) + "1Y";
                bySectionNo = ybInspectDataService.findBySectionNo(sectionNo);
                if (null != bySectionNo) {
                    tRadialCentre = bySectionNo.getTRadialCentre();
                    tRadialEdge1 = bySectionNo.getTRadialEdge1();
                    tRadialEdge2 = bySectionNo.getTRadialEdge2();
                    wRadialCentre = ybInspectDataCdto.getWRadialCentre();
                    wRadialEdge1 = ybInspectDataCdto.getWRadialEdge1();
                    wRadialEdge2 = ybInspectDataCdto.getWRadialEdge2();

                    tCentreLife = bySectionNo.getTCentreLife();
                    tLifeEdge1 = bySectionNo.getTLifeEdge1();
                    tLifeEdge2 = bySectionNo.getTLifeEdge2();
                    wCentreLife = ybInspectDataCdto.getWCentreLife();
                    wLifeEdge11 = ybInspectDataCdto.getWLifeEdge1();
                    wLifeEdge12 = ybInspectDataCdto.getWLifeEdge2();
                }
            }

            if (collect.containsKey("电阻范围") && collect.containsKey("寿命范围（大于）")) {
                String[] radialRange = collect.get("电阻范围").split("-");
                String[] lifeRange = collect.get("寿命范围（大于）").split("-");
                if (null != tRadialCentre && tRadialCentre.compareTo(new BigDecimal(Double.valueOf(radialRange[0]))) > 0 && tRadialCentre.compareTo(new BigDecimal(Double.valueOf(radialRange[1]))) < 0
                        && null != tCentreLife && tCentreLife.compareTo(new BigDecimal(Double.valueOf(lifeRange[0]))) > 0 && null != wCentreLife && wCentreLife.compareTo(new BigDecimal(Double.valueOf(lifeRange[0]))) > 0) {
                    whetherAllInput = true;
                }
            }

            if (whetherAllInput) {
                BigDecimal totalLength = new BigDecimal(0);
                //查询画线记录
                ProductionPaintingLineDetail bySegmentNo = productionPaintingLineDetailService.findBySegmentNo(ybInspectDataCdto.getSectionNo());
                Long crystalId = bySegmentNo.getCrystalId();
                List<ProductionPaintingLineDetail> byCrystalId = productionPaintingLineDetailService.findByCrystalId(crystalId);
                LongCrystal longCrystal = longCrystalService.get(crystalId);
                if (CollectionUtils.isNotEmpty(byCrystalId)) {
                    productionPaintingLineDetails = byCrystalId.stream().filter(productionPaintingLineDetail -> productionPaintingLineDetail.getOperateReversecutDrawId() == 0 && productionPaintingLineDetail.getType() == 0).collect(Collectors.toList());
                    for (ProductionPaintingLineDetail productionPaintingLineDetail : productionPaintingLineDetails) {
                        totalLength = totalLength.add(productionPaintingLineDetail.getLength());
                    }
                    productionPaintingLineDetails.sort(Comparator.comparing(ProductionPaintingLineDetail::getId));
                }

                List<DictionaryItem> itemList = dictionaryItemService.findItemByThemeValue("WeightRatio", true);
                Map<String, String> weightCoefficient = itemList.stream().collect(Collectors.toMap(DictionaryItem::getName, DictionaryItem::getValue));

                //计算电阻率系数
                if (totalLength.compareTo(new BigDecimal(0)) > 0) {
                    resistivityCoefficient = tRadialCentre.subtract(wRadialCentre).divide(totalLength, 10, BigDecimal.ROUND_HALF_UP);
                }

                //计算寿命系数
                if (totalLength.compareTo(new BigDecimal(0)) > 0) {
                    lifeCoefficient = tCentreLife.subtract(wCentreLife).divide(totalLength, 10, BigDecimal.ROUND_HALF_UP);
                }

                Double[] resistivityList = new Double[productionPaintingLineDetails.size()];
                Double[] lifeList = new Double[productionPaintingLineDetails.size()];

                for (int i = 0; i < productionPaintingLineDetails.size(); i++) {
                    YbInspectDataCUDto ybInspectDataCUDto1 = new YbInspectDataCUDto();
                    ybInspectDataCUDto1.setSectionNo(productionPaintingLineDetails.get(i).getNo());
                    ybInspectDataCUDto1.setActualLength(productionPaintingLineDetails.get(i).getLength());
                    ybInspectDataCUDto1.setActualWeight(productionPaintingLineDetails.get(i).getLength().divide(new BigDecimal(weightCoefficient.get(longCrystal.getSpecs())), 3, BigDecimal.ROUND_HALF_UP));
                    ybInspectDataCUDto1.setProductTypeSecond(longCrystal.getSpecs());
                    ybInspectDataCUDto1.setConductiveType(longCrystal.getConductiveType());
                    ybInspectDataCUDto1.setDopant(longCrystal.getDopant());
                    ybInspectDataCUDto1.setDiameterMax(longCrystal.getMaxDiam());
                    ybInspectDataCUDto1.setDiameterMin(longCrystal.getMinDiam());
                    ybInspectDataCUDto1.setCheckReback("无");
                    ybInspectDataCUDto1.setSideLengthRange(longCrystal.getSideLengthRange());
                    ybInspectDataCUDto1.setEdgeBark(new BigDecimal(0));
                    ybInspectDataCUDto1.setCollapseLine(new BigDecimal(0));
                    ybInspectDataCUDto1.setDistortion(new BigDecimal(0));
                    ybInspectDataCUDto1.setSlopeLength(new BigDecimal(0));
                    ybInspectDataCUDto1.setCrack(new BigDecimal(0));

                    if (i == 0) {
                        ybInspectDataCUDto1.setTRadialCentre(tRadialCentre);
                        ybInspectDataCUDto1.setTRadialEdge1(tRadialEdge1);
                        ybInspectDataCUDto1.setTRadialEdge2(tRadialEdge2);
                        ybInspectDataCUDto1.setTCentreLife(tCentreLife);
                        ybInspectDataCUDto1.setTLifeEdge1(tLifeEdge1);
                        ybInspectDataCUDto1.setTLifeEdge2(tLifeEdge2);

                    } else {
                        BigDecimal resistivity = new BigDecimal(resistivityList[i - 1]);
                        BigDecimal life = new BigDecimal(lifeList[i - 1]);
                        ybInspectDataCUDto1.setTRadialCentre(resistivity);
                        ybInspectDataCUDto1.setTRadialEdge1(resistivity.add(new BigDecimal(collect.get("电阻率边缘（加）"))));
                        ybInspectDataCUDto1.setTRadialEdge2(resistivity.add(new BigDecimal(collect.get("电阻率边缘（加）"))));
                        ybInspectDataCUDto1.setTCentreLife(life);
                        ybInspectDataCUDto1.setTLifeEdge1(life.add(new BigDecimal(collect.get("寿命边缘（加）"))));
                        ybInspectDataCUDto1.setTLifeEdge2(life.add(new BigDecimal(collect.get("寿命边缘（加）"))));

                    }

                    if (i == productionPaintingLineDetails.size() - 1) {
                        ybInspectDataCUDto1.setWRadialCentre(wRadialCentre);
                        ybInspectDataCUDto1.setWRadialEdge1(wRadialEdge1);
                        ybInspectDataCUDto1.setWRadialEdge2(wRadialEdge2);
                        ybInspectDataCUDto1.setWCentreLife(wCentreLife);
                        ybInspectDataCUDto1.setWLifeEdge1(wLifeEdge11);
                        ybInspectDataCUDto1.setWLifeEdge2(wLifeEdge12);
                    } else if (i == 0) {
                        supplementaryData(collect, resistivityCoefficient, lifeCoefficient, productionPaintingLineDetails, ybInspectDataCUDto1, resistivityList, lifeList, i, tRadialCentre, tCentreLife);
                    } else {
                        BigDecimal resistivity = new BigDecimal(resistivityList[i - 1]);
                        BigDecimal life = new BigDecimal(lifeList[i - 1]);
                        supplementaryData(collect, resistivityCoefficient, lifeCoefficient, productionPaintingLineDetails, ybInspectDataCUDto1, resistivityList, lifeList, i, resistivity, life);
                    }
                    if ((ybInspectDataCdto.getSectionNo().endsWith("1Y") && ybInspectDataCUDto1.getSectionNo().endsWith("WY")) ||
                            (ybInspectDataCdto.getSectionNo().endsWith("WY") && ybInspectDataCUDto1.getSectionNo().endsWith("1Y"))) {
                        continue;
                    }
                    List<ProductionBackCuttingRecord> allBySegmentNo = productionRecutService.findAllBySegmentNo1(ybInspectDataCUDto1.getSectionNo());
                    if (CollectionUtils.isNotEmpty(allBySegmentNo)) {
                        continue;
                    }
                    execYbInspectData(ybInspectDataCUDto1);
                }
            }
        }*/

        //原来只有这部分，上面的代码为新增代码
        if (!whetherAllInput) {
            Result result = execYbInspectData(ybInspectDataCdto);
            return result;
        }
        return ResultGenerator.success();
    }

    @Override
    public Result saveYbInspectDataNew(YbInspectDataCUDto ybInspectDataCdto) {

        /**
         对于电阻率，逻辑是根据后面的电阻率 1，电阻率 2，电阻率3的3 个值取平均值到电阻率即可。T寿命，W 寿命的逻辑和电阻率保持一致。
         */
        //电阻率计算 A
        BigDecimal divideDecimal = new BigDecimal(3);
        if (null == ybInspectDataCdto.getMeanResistivityA()) {
            BigDecimal resistivityAOne = null == ybInspectDataCdto.getResistivityAOne() ? BigDecimal.ZERO : ybInspectDataCdto.getResistivityAOne();
            BigDecimal resistivityATwo = null == ybInspectDataCdto.getResistivityATwo() ? BigDecimal.ZERO : ybInspectDataCdto.getResistivityATwo();
            BigDecimal resistivityAThree = null == ybInspectDataCdto.getResistivityAThree() ? BigDecimal.ZERO : ybInspectDataCdto.getResistivityAThree();
            ybInspectDataCdto.setMeanResistivityA((resistivityAOne.add(resistivityATwo).add(resistivityAThree)).divide(divideDecimal, 2, BigDecimal.ROUND_HALF_UP));

        }
        //电阻率计算 B
        if (null == ybInspectDataCdto.getMeanResistivityB()) {
            BigDecimal resistivityBOne = null == ybInspectDataCdto.getResistivityBOne() ? BigDecimal.ZERO : ybInspectDataCdto.getResistivityBOne();
            BigDecimal resistivityBTwo = null == ybInspectDataCdto.getResistivityBTwo() ? BigDecimal.ZERO : ybInspectDataCdto.getResistivityBTwo();
            BigDecimal resistivityBThree = null == ybInspectDataCdto.getResistivityBThree() ? BigDecimal.ZERO : ybInspectDataCdto.getResistivityBThree();
            ybInspectDataCdto.setMeanResistivityB((resistivityBOne.add(resistivityBTwo).add(resistivityBThree)).divide(divideDecimal, 2, BigDecimal.ROUND_HALF_UP));
        }

        //A少子寿命均值
        if (null == ybInspectDataCdto.getMeanCarrierLifetimeA()) {
            BigDecimal carrierLifetimeAOne = null == ybInspectDataCdto.getCarrierLifetimeAOne() ? BigDecimal.ZERO : ybInspectDataCdto.getCarrierLifetimeAOne();
            BigDecimal carrierLifetimeATwo = null == ybInspectDataCdto.getCarrierLifetimeATwo() ? BigDecimal.ZERO : ybInspectDataCdto.getCarrierLifetimeATwo();
            BigDecimal carrierLifetimeAThree = null == ybInspectDataCdto.getCarrierLifetimeAThree() ? BigDecimal.ZERO : ybInspectDataCdto.getCarrierLifetimeAThree();
            ybInspectDataCdto.setMeanCarrierLifetimeA((carrierLifetimeAOne.add(carrierLifetimeATwo).add(carrierLifetimeAThree)).divide(divideDecimal, 2, BigDecimal.ROUND_HALF_UP));
        }
        //B少子寿命均值
        if (null == ybInspectDataCdto.getMeanCarrierLifetimeB()) {
            BigDecimal carrierLifetimeBOne = null == ybInspectDataCdto.getCarrierLifetimeBOne() ? BigDecimal.ZERO : ybInspectDataCdto.getCarrierLifetimeBOne();
            BigDecimal carrierLifetimeBTwo = null == ybInspectDataCdto.getCarrierLifetimeBTwo() ? BigDecimal.ZERO : ybInspectDataCdto.getCarrierLifetimeBTwo();
            BigDecimal carrierLifetimeBThree = null == ybInspectDataCdto.getCarrierLifetimeBThree() ? BigDecimal.ZERO : ybInspectDataCdto.getCarrierLifetimeBThree();
            ybInspectDataCdto.setMeanCarrierLifetimeB((carrierLifetimeBOne.add(carrierLifetimeBTwo).add(carrierLifetimeBThree)).divide(divideDecimal, 2, BigDecimal.ROUND_HALF_UP));
        }

        //添加卡控，圆棒检验，人工检验方式里数据录入变更:T(头段)只测A面和A(尾段)只测B面
        if (StringUtils.isBlank(ybInspectDataCdto.getSectionNo())) {
            throw new BusinessException("检验晶段编号为空！");
        }
        if (null == ybInspectDataCdto.getPdaFlag() || !ybInspectDataCdto.getPdaFlag()){
            if (ybInspectDataCdto.getSectionNo().endsWith("A") && (ybInspectDataCdto.getMeanCarrierLifetimeB().compareTo(BigDecimal.ZERO) <= 0 ||
                    ybInspectDataCdto.getMeanResistivityB().compareTo(BigDecimal.ZERO) <= 0)) {
                throw new BusinessException("尾段B面电阻率或少子寿命未检出！");
            }
            if (ybInspectDataCdto.getSectionNo().endsWith("T") && (ybInspectDataCdto.getMeanCarrierLifetimeA().compareTo(BigDecimal.ZERO) <= 0 ||
                    ybInspectDataCdto.getMeanResistivityA().compareTo(BigDecimal.ZERO) <= 0)) {
                throw new BusinessException("头段A面电阻率或少子寿命未检出！");
            }
        }

        Result result = this.execYbInspectData(ybInspectDataCdto);
        return result;
    }

    private void supplementaryData(Map<String, String> collect, BigDecimal resistivityCoefficient, BigDecimal lifeCoefficient, List<ProductionPaintingLineDetail> byCrystalId, YbInspectDataCUDto ybInspectDataCUDto1, Double[] resistivityList, Double[] lifeList, int i, BigDecimal resistivity, BigDecimal life) {
        BigDecimal bwRadialCentre = resistivity.subtract(resistivityCoefficient.multiply(byCrystalId.get(i).getLength()));
        //ybInspectDataCUDto1.setWRadialCentre(bwRadialCentre);
        //ybInspectDataCUDto1.setWRadialEdge1(bwRadialCentre.add(new BigDecimal(collect.get("电阻率边缘（加）"))));
        ybInspectDataCUDto1.setWRadialEdge2(bwRadialCentre.add(new BigDecimal(collect.get("电阻率边缘（加）"))));

        BigDecimal bwCentreLife = life.subtract(lifeCoefficient.multiply(byCrystalId.get(i).getLength()));
        //ybInspectDataCUDto1.setWCentreLife(bwCentreLife);
        // ybInspectDataCUDto1.setWLifeEdge1(bwCentreLife.add(new BigDecimal(collect.get("寿命边缘（加）"))));
        ybInspectDataCUDto1.setWLifeEdge2(bwCentreLife.add(new BigDecimal(collect.get("寿命边缘（加）"))));

        resistivityList[i] = Double.valueOf(bwRadialCentre.toString());
        lifeList[i] = Double.valueOf(bwCentreLife.toString());
    }

    private Result execYbInspectData(YbInspectDataCUDto ybInspectDataCdto) {

        Result<CurrentWipStorageStatusDto> currentWipStorageStatusDtoResult = wipStorageService.selectWipStorageResult(ybInspectDataCdto.getSectionNo());
        if (currentWipStorageStatusDtoResult.getCode() != ResultCode.SUCCESS.getCode()) {
            throw new BusinessException(currentWipStorageStatusDtoResult.getMessage());
        }
        CurrentWipStorageStatusDto currentWipStorageStatusDto = currentWipStorageStatusDtoResult.getData();
        if (currentWipStorageStatusDto == null || currentWipStorageStatusDto.getWipStorageCode() == null || currentWipStorageStatusDto.getWipStorageStatus() == null) {
            throw new BusinessException("站点信息查询失败，请检查在制品信息");
        }

        //添加批次锁定校验
        crystalBatchOperationService.judgeCrystalNoIsLock(null, ybInspectDataCdto.getSectionNo(), false);
        //查询历史数据
        YbInspectData ybInspectDataOld = findBySectionNo(ybInspectDataCdto.getSectionNo());
        if (ybInspectDataOld != null) {
            ybInspectDataCdto.setId(ybInspectDataOld.getId());
            ybInspectDataCdto.setDopant(ybInspectDataOld.getDopant());
            ybInspectDataCdto.setProductTypeSecond(ybInspectDataOld.getProductTypeSecond());
            ybInspectDataCdto.setConductiveType(ybInspectDataOld.getConductiveType());
        }
        //是否处于圆棒检验待进站状态
        boolean isStatus = currentWipStorageStatusDto.getWipStorageCode().equals(EnumValuesFactory.WipStorageCode.圆棒检验.getKey())
                && currentWipStorageStatusDto.getWipStorageStatus() == EnumValuesFactory.WipStorageStatus.待进站.getKey();

        // 新增请求，并且不在圆棒检验待进站，将其变为修改请求
        if (ybInspectDataCdto.getId() == null && !isStatus) {
            if (ybInspectDataOld != null) {
                //把该条数据至为设备上传状态
                ybInspectDataCdto.setId(-1L);
            }
        }

        //防止更新将理论重量更新为0
        if ((null == ybInspectDataCdto.getTheoryWeight() || ybInspectDataCdto.getTheoryWeight().compareTo(BigDecimal.ZERO) == 0)
                && null != ybInspectDataCdto.getActualLength()) {
            List<DictionaryItem> dictionaryItems = dictionaryItemService.findByThemeValueAndItemName(Constants.WEIGHT_RATIO, ybInspectDataCdto.getProductTypeSecond(), true);
            if (!org.springframework.util.CollectionUtils.isEmpty(dictionaryItems)) {
                BigDecimal weightLossCoefficient = NumberUtil.Object2BigDecimal(dictionaryItems.get(0).getValue());
                if (null != weightLossCoefficient && weightLossCoefficient.compareTo(BigDecimal.ONE) > 0) {
                    ybInspectDataCdto.setTheoryWeight(ybInspectDataCdto.getActualLength().divide(weightLossCoefficient, 3, RoundingMode.HALF_UP));
                }
            }
        }

        //新增数据
        if (ybInspectDataCdto.getId() == null) {
            return execAddYbInspectData(ybInspectDataCdto, ybInspectDataOld, isStatus);
        }
        //修改
        else {
            return execUpdateYbInspectData(ybInspectDataCdto, ybInspectDataOld, isStatus);
        }
    }

    @Override
    public Result updateYbInspectDataSideLengthRange(YbInspectDataSideLengthUpdateDto dto) {
        List<String> sectionNos = dto.getSectionNos();
        if (!sectionNos.isEmpty()) {
            for (String sectionNo : sectionNos) {
                SectionNoDetail sectionNoDetail = sectionNoDetailService.findBySectionNo(sectionNo);

                if (null != sectionNoDetail) {
                    LongCrystal longCrystal = longCrystalService.get(sectionNoDetail.getCrystalId());

                    //查询历史数据
                    YbInspectData ybInspectDataOld = findBySectionNo(sectionNo);
                    if (!longCrystal.getSideLengthRange().isEmpty() && null != ybInspectDataOld && (ybInspectDataOld.getSideLengthRange() == null || ybInspectDataOld.getSideLengthRange().isEmpty())) {
                        //多边距字段赋值
                        ybInspectDataOld.setSideLengthRange(longCrystal.getSideLengthRange());
                        saveOrUpdate(ybInspectDataOld);
                    }
                }
            }
        }
        return ResultGenerator.success();
    }

    @Override
    public Result updateYbInspectResistivity(YbInspectDataCUDto ybInspectDataCdto) {
        //查询历史数据
        YbInspectData ybInspectDataOld = findBySectionNo(ybInspectDataCdto.getSectionNo());
        Assert.notNull(ybInspectDataOld, "当前晶棒无检验信息！");

        BeanUtil.copyBeanPropWithOutNullValue(ybInspectDataOld, ybInspectDataCdto, "id");
        ybInspectDataOld.setUpdateTime(new Date());
        ybInspectDataOld.setUpdateUser(BaseContextHandler.getUsername());
        saveOrUpdate(ybInspectDataOld);
        saveDataInspectLog(ybInspectDataOld);//保存圆棒检验记录表
        return ResultGenerator.success("操作成功！");
    }

    /**
     * 执行圆棒检验数据新增
     *
     * @param ybInspectDataCdto 本次上传的检验数据
     * @param ybInspectDataOld  该晶段的历史数据
     * @param isStatus          当前在制品状态是否满足 圆棒检验[待进站]
     * @return 是否成功
     */
    private Result execAddYbInspectData(YbInspectDataCUDto ybInspectDataCdto, YbInspectData ybInspectDataOld, boolean isStatus) {
        String sectionNo = ybInspectDataCdto.getSectionNo();
        // 处于圆棒检验待进站状态的新增请求，就处理过站操作
        if (isStatus) {
            Result result = wipStorageService.inStation(ybInspectDataCdto.getSectionNo(), null, false);
            if (result.getCode() != ResultCode.SUCCESS.getCode()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        Boolean individualFlage = sectionNo.endsWith("R");
        //添加判断，对于样片值的获取，其中T段，T02 段，w 段，需要等待样片实际值出来后进行流转，否则则进库等待，其余段可以直接流转
        Boolean waitSampleFlag = sectionNo.endsWith("A") || sectionNo.endsWith("T") || individualFlage;
        String pieceNoHead = "";
        String pieceNoEnd = "";
        // 第一次检验新增，初始化数据
        if (ybInspectDataOld == null) {
            ybInspectDataOld = new YbInspectData();
            ybInspectDataOld.setSectionNo(sectionNo);
            // 通过圆棒编号 去追溯表判断晶段是否存在
            SectionNoDetail sectionNoDetail = sectionNoDetailService.findBySectionNo(ybInspectDataCdto.getSectionNo());
            if (sectionNoDetail == null) {
                return ResultGenerator.fail(ybInspectDataCdto.getSectionNo() + "晶段信息不存在，数据异常");
            }
            if (null != sectionNoDetail.getSectionPosiotion() && sectionNoDetail.getSectionPosiotion() == 2) {
                waitSampleFlag = true;
            }
            if (individualFlage) {
                pieceNoHead = sectionNoDetail.getPieceNoHead();
                pieceNoEnd = sectionNoDetail.getPieceNoEnd();
            }
            if (waitSampleFlag) {
                if (!individualFlage) {
                    pieceNoHead = this.handlePieceNo(sectionNoDetail.getCrystalNo() + "T", true);
                    pieceNoEnd = this.handlePieceNo(sectionNoDetail.getCrystalNo() + "A", false);
                }
            }
            LongCrystal longCrystal = longCrystalService.get(sectionNoDetail.getCrystalId());
            if (longCrystal == null) {
                return ResultGenerator.fail(ybInspectDataCdto.getSectionNo() + "长棒信息不存在，数据异常");
            }
            initInspectData(ybInspectDataOld, sectionNoDetail, longCrystal);
            //赋值段号
            ybInspectDataOld.setPiecewiseNum(sectionNoDetail.getSegmentNum());
            if (sectionNoDetail.getParentId() == 0) {
                ybInspectDataOld.setCheckoutName("一次检验");
                ybInspectDataOld.setReCheckType("0");
            }
            // 如果是反切第一次，需继承父单晶的一些属性
            else {
                SectionNoDetail sectionNoDetailParent = sectionNoDetailService.get(sectionNoDetail.getParentId());
                if (sectionNoDetailParent != null && sectionNoDetailParent.getId() != null) {
                    YbInspectData ybInspectDataParent = findBySectionNo(sectionNoDetailParent.getSectionNo());
                    if (ybInspectDataParent != null) {
                        if (ybInspectDataParent.getReCheckType() != null) {
                            String checkTypeF = (Integer.parseInt(ybInspectDataParent.getReCheckType()) + 1) + "";
                            ybInspectDataOld.setReCheckType(checkTypeF);
                        }
                        ybInspectDataOld.setCheckoutName(EnumValues.CheckoutName.返切复检.getValue());
                        ybInspectDataOld.setOrderType(ybInspectDataParent.getOrderType());
                        ybInspectDataOld.setHeadTailRecognition(ybInspectDataParent.getHeadTailRecognition());
                    }else {
                        ybInspectDataOld.setCheckoutName(EnumValues.CheckoutName.返切复检.getValue());
                        ybInspectDataOld.setReCheckType("1");
                    }
                }
            }
            //赋值头尾样片信息
            setSampleData(ybInspectDataOld, sectionNoDetail.getPieceNoHead(), sectionNoDetail.getPieceNoEnd(), sectionNoDetail.getSegmentNum());
        } else {
            ybInspectDataOld.setCheckoutName("复检");
            //更新复检次数
            ybInspectDataOld.setReCheckType(String.valueOf(NumberUtil.String2Integer(ybInspectDataOld.getReCheckType(), 0) + 1));
            //新增，并且有历史数据，记录日志数据
            YbInspectDataLog ybInspectDataLog = ybInspectDataLogService.findByInspectDataId(ybInspectDataOld.getId());
            List<YbInspectData> ybInspectDatas = new LinkedList<>();
            //查看有没有日志记录
            if (ybInspectDataLog != null) {
                ybInspectDatas = JSON.parseArray(ybInspectDataLog.getDataLog(), YbInspectData.class);
            } else {
                ybInspectDataLog = new YbInspectDataLog();
                ybInspectDataLog.setInspectDataId(ybInspectDataOld.getId());
                ybInspectDataLog.setSectionNo(ybInspectDataOld.getSectionNo());
            }
            ybInspectDataLog.setUserUpdate(BaseContextHandler.getUsername());
            ybInspectDataLog.setGmtUpdate(new Date());
            ybInspectDatas.add(ybInspectDataOld);
            ybInspectDataLog.setDataLog(JSON.toJSONString(ybInspectDatas));
            ybInspectDataLogService.saveOrUpdate(ybInspectDataLog);
            handleContentInfo(ybInspectDataOld, ybInspectDataOld.getCrystalNo());
        }
        //获取晶段属性
        String sectionType = defaultCrystalAttrService.getDefaultCrystalAttrOneTimes(ybInspectDataOld.getDopant(), ybInspectDataOld.getProductTypeSecond(), ybInspectDataOld.getProductLevel(), ybInspectDataOld.getSticksCount() != null && ybInspectDataOld.getSticksCount() > 1 ? ybInspectDataOld.getSpellBarLength() : ybInspectDataOld.getActualLength());
        //继承历史数据，更新本次数据
//        BeanUtil.copyBeanPropWithNullValue(ybInspectDataOld, ybInspectDataCdto, "id");
        BeanUtils.copyProperties(ybInspectDataCdto, ybInspectDataOld, BeanUtil.getIgnoreProperties(ybInspectDataCdto, "id", null));
        ybInspectDataOld.setInspector(BaseContextHandler.getUsername());
        ybInspectDataOld.setCreateTime(new Date());
        // 完结尾查询完结头氧值
        try {
            LongCrystal longCrystal = longCrystalService.findByCrystalNo(ybInspectDataOld.getCrystalNo());
            if (null != longCrystal.getClosureIdentification() && longCrystal.getClosureIdentification().equals(EnumValuesServer.FINALIDENTIFICATION)) {
                setEndOxygenAndCarbon(ybInspectDataOld, longCrystal);
            } else if (!longCrystal.getClosureIdentification().equals(EnumValuesServer.FINALIDENTIFICATION)) {
                ybInspectDataOld.setEndCarbonContentHead(new BigDecimal(0));
                ybInspectDataOld.setEndOxygenContentHead(new BigDecimal(0));
                ybInspectDataOld.setEndCarbonContentTail(new BigDecimal(0));
                ybInspectDataOld.setEndOxygenContentTail(new BigDecimal(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 判断晶段类型
        ybInspectDataOld.setSectionType(sectionType);
        //补充完结标识
        LongCrystal byCrystalNo = longCrystalService.findByCrystalNo(ybInspectDataOld.getCrystalNo());
        if (byCrystalNo == null) {
            throw new RuntimeException("晶棒信息不存在！");
        }
        //调整完结方式
        ybInspectDataOld.setClosureIdentification(StringUtils.equals(byCrystalNo.getWindUp(),EnumValuesServer.FINALIDENTIFICATION) ? "是" :"否");
//        ybInspectDataOld.setSideLengthRange(ybInspectDataCdto.getSideLengthRange());

        //添加判断，对于样片值的获取，其中T段，T02 段，w 段，需要等待样片实际值出来后进行流转，否则则进库等待，其余段可以直接流转
        Boolean ratedFlage = false;
        if (waitSampleFlag) {

            if (StringUtils.isNotBlank(pieceNoHead)) {
                PieceCheck pieceCheckHead = pieceCheckService.getByPieceNo(pieceNoHead);
                if (null == pieceCheckHead) {
                    ratedFlage = true;
                } else {
                    ybInspectDataOld.setCarbonContentHead(pieceCheckHead.getcContents());
                    ybInspectDataOld.setOxygenContentHead(pieceCheckHead.getoContents());
                }
            }
            if (StringUtils.isNotBlank(pieceNoEnd)) {
                PieceCheck pieceCheckTail = pieceCheckService.getByPieceNo(pieceNoHead);
                if (null == pieceCheckTail) {
                    ratedFlage = true;
                } else {
                    ybInspectDataOld.setCarbonContentTail(pieceCheckTail.getcContents());
                    ybInspectDataOld.setOxygenContentTail(pieceCheckTail.getoContents());
                }
            }
        }
        //需求修改，处理返切未检验数据
        if (GlobalSwitch.enable(GlobalSwitchNamespace.NAMESPACE_YB_CHECK, "AutomaticRoundBackCut", true)) {
            this.handleDefaultOxygenAndCarbonNew(ybInspectDataOld);
        }else {
            this.handleDefaultOxygenAndCarbon(ybInspectDataOld);
        }
        //卡控放在评级规则中
        ratedFlage = false;
        if (!ratedFlage) {
            Result<String> stringResult = saveDataAndGrade(ybInspectDataOld, false);
            if (null != stringResult && stringResult.getCode().equals("400")) {
                return stringResult;
            }
        } else {
            saveOrUpdate(ybInspectDataOld);
            PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCodeAndOrderType(sectionNo, EnumValuesFactory.PlanProcessingOrderOrderType.晶段.getKey());
            if (planProcessingOrder == null) {
                throw new BusinessException("工单不存在，请联系管理员");
            }
            // 满足不能评级条件，直接创建评级记录
            createRuleTest(sectionNo, "等待样片检验数据不再触发评级");
        }
        saveDataInspectLog(ybInspectDataOld);//保存圆棒检验记录表

        //添加处理中间段数据记录过站录入
        long l = System.currentTimeMillis();

        //添加逻辑 处理是否需要还原母单晶
        this.reducedMotheCrystal(ybInspectDataOld);

        //处理评级
        if (GlobalSwitch.enable(GlobalSwitchNamespace.NAMESPACE_YB_CHECK, "automaticInspectMiddleNew", true)) {
            this.handleAutomaticInspectMiddleNew(ybInspectDataOld);
        } else {
            this.handleAutomaticInspectMiddle(ybInspectDataOld);
        }
        Map<String, Object> bySectionNoMap = BeanUtil.convertObjectToMap(ybInspectDataOld, YbInspectData.class);
        ThreadManager.getThreadPollProxy().execute(() -> {
            //处理预警机制
            ybInspectDataService.verificationManagement(bySectionNoMap);
        });
        log.info("新加处理耗时：{}", System.currentTimeMillis() - l);
        return ResultGenerator.success();
    }


    /**
     * 处理是否需要还原母单晶
     * @param ybInspectData
     */
    private void reducedMotheCrystal(YbInspectData ybInspectData){
        if (null == ybInspectData || StringUtils.isBlank(ybInspectData.getSectionNo()) || ybInspectData.getSectionNo().length() < 18){
            return;
        }
        SectionNoDetail sectionNoDetail = sectionNoDetailService.findBySectionNo(ybInspectData.getSectionNo());
        if (null == sectionNoDetail || null == sectionNoDetail.getReductionCrystal() || sectionNoDetail.getReductionCrystal() == 0){
            return;
        }
        SectionNoDetail sectionNoDetailParent = sectionNoDetailService.get(sectionNoDetail.getParentId());
        if (null == sectionNoDetailParent || StringUtils.isBlank(sectionNoDetailParent.getSectionNo())){
            return;
        }
        YbInspectData bySectionNo = this.findBySectionNo(sectionNoDetailParent.getSectionNo());
        if (null != bySectionNo){
            return;
        }
        YbInspectData ybInspectDataNew = new YbInspectData();
        BeanUtil.copyProperties(ybInspectData, ybInspectDataNew, "id",  "reCheckType", "reduceCrystalLength", "materialLoss");
        ybInspectDataNew.setUpdateUser("返切还原");
        ybInspectDataNew.setUpdateTime(new Date());
        if (null != ybInspectData.getReCheckType() && Integer.valueOf(ybInspectData.getReCheckType()) > 0){
            ybInspectDataNew.setReCheckType((Integer.valueOf(ybInspectData.getReCheckType()) - 1) + "");
        }else {
            ybInspectDataNew.setReCheckType("1");
        }
        ybInspectDataNew.setId(null);

        ybInspectDataNew.setSectionNo(sectionNoDetailParent.getSectionNo());
        ybInspectDataNew.setActualLength(sectionNoDetailParent.getLength());
        List<DictionaryItem> dictionaryItems = dictionaryItemService.findByThemeValueAndItemName(Constants.WEIGHT_RATIO, ybInspectData.getProductTypeSecond(), true);
        BigDecimal weight = BigDecimal.ZERO;
        if (CollectionUtils.isNotEmpty(dictionaryItems)) {
            BigDecimal weightLossCoefficient = NumberUtil.Object2BigDecimal(dictionaryItems.get(0).getValue());
            if (null != weightLossCoefficient && weightLossCoefficient.compareTo(BigDecimal.ONE) > 0) {
                weight = sectionNoDetailParent.getLength().divide(weightLossCoefficient, 3, RoundingMode.HALF_UP);
            }
        }
        ybInspectDataNew.setTheoryWeight(weight);
        ybInspectDataNew.setActualWeight(weight);
        ybInspectDataNew.setPiecewiseNum(sectionNoDetailParent.getSectionPosiotion());
        ybInspectDataNew.setSticksCount(1);
        this.saveOrUpdate(ybInspectDataNew);
    }


    /**
     * 圆棒检验评级之前判断氧碳是否存在，不存在赋值0
     *
     * @param ybInspectData
     */
    @Override
    public void handleDefaultOxygenAndCarbon(YbInspectData ybInspectData) {
        if (null != ybInspectData) {
            if (StringUtils.isBlank(ybInspectData.getSectionNo())) {
                return;
            }
            SectionNoDetail sectionNoDetail = sectionNoDetailService.findBySectionNo(ybInspectData.getSectionNo());
            if (null != sectionNoDetail) {
                if (ybInspectData.getSectionNo().endsWith("T") || (null != sectionNoDetail.getOxygenCarbonMark() && sectionNoDetail.getOxygenCarbonMark() == 1)) {

                    YbInspectData bySectionNoTail = null;
                    if (GlobalSwitch.enable(GlobalSwitchNamespace.NAMESPACE_YB_CHECK, "AutomaticRoundBackCut", true)) {
                        bySectionNoTail = this.findByCrystalNoAndOxygenCarbonMark(ybInspectData.getCrystalNo(), EnumValuesFactory.OxygenCarbonMarkStatus.TAIL_DEPEND.getKey());
                    }else {
                        bySectionNoTail = ybInspectDataService.findBySectionNo(ybInspectData.getCrystalNo() + "A");
                    }
                    if (null != bySectionNoTail) {
                        //
                        this.handleYbInspectDataABInfo(bySectionNoTail, ybInspectData, false);
                    }

                } else if (ybInspectData.getSectionNo().endsWith("A") || (null != sectionNoDetail.getOxygenCarbonMark() && sectionNoDetail.getOxygenCarbonMark() == 2)) {
                    YbInspectData bySectionNoHead = null;
                    if (GlobalSwitch.enable(GlobalSwitchNamespace.NAMESPACE_YB_CHECK, "AutomaticRoundBackCut", true)) {
                        bySectionNoHead = this.findByCrystalNoAndOxygenCarbonMark(ybInspectData.getCrystalNo(), EnumValuesFactory.OxygenCarbonMarkStatus.HEAD_DEPEND.getKey());
                    }else {
                        bySectionNoHead = ybInspectDataService.findBySectionNo(ybInspectData.getCrystalNo() + "T");
                    }
                    if (null != bySectionNoHead) {
                        //
                        this.handleYbInspectDataABInfo(bySectionNoHead, ybInspectData, true);
                    }
                }
                this.handleOxygenAndCarbonContent(ybInspectData,sectionNoDetail,ybInspectData.getCrystalNo());
                //赋值头尾电阻和少子寿命
               this.handleResistorsAndLifetime(ybInspectData);
            }
/*
            //T氧含量中心
            if (null == ybInspectData.getOxygenContentHead()) {
                ybInspectData.setOxygenContentHead(BigDecimal.ZERO);
            }
            //T碳含量中心
            if (null == ybInspectData.getCarbonContentHead()) {
                ybInspectData.setCarbonContentHead(BigDecimal.ZERO);
            }
            //W氧含量中心
            if (null == ybInspectData.getOxygenContentTail()) {
                ybInspectData.setOxygenContentTail(BigDecimal.ZERO);
            }
            //W碳含量中心
            if (null == ybInspectData.getCarbonContentTail()) {
                ybInspectData.setCarbonContentTail(BigDecimal.ZERO);
            }

            //本身尾头尾时将AB面值从头尾赋值
            if (StringUtils.isNotBlank(ybInspectData.getSectionNo()) && StringUtils.isNotBlank(ybInspectData.getCrystalNo())) {
                if (ybInspectData.getSectionNo().endsWith("T")) {
                    YbInspectData bySectionNoTail = ybInspectDataService.findBySectionNo(ybInspectData.getCrystalNo() + "A");
                    if (null != bySectionNoTail) {
                        this.handleYbInspectDataABInfo(bySectionNoTail, ybInspectData, false);
                    }

                } else if (ybInspectData.getSectionNo().endsWith("A")) {
                    YbInspectData bySectionNoHead = ybInspectDataService.findBySectionNo(ybInspectData.getCrystalNo() + "T");
                    if (null != bySectionNoHead) {
                        this.handleYbInspectDataABInfo(bySectionNoHead, ybInspectData, true);
                    }
                }
                //暂时修复问题，后期优化，防止返切值覆盖问题，处理问题返切取片不赋值问题
                SectionNoDetail bySectionNo = sectionNoDetailService.findBySectionNo(ybInspectData.getSectionNo());
                if (null != bySectionNo) {
                    if (StringUtils.isNotBlank(bySectionNo.getPieceNoHead())) {
                        PieceCheck byPieceNoHead = pieceCheckService.getByPieceNo(bySectionNo.getPieceNoHead());
                        if (null != byPieceNoHead) {
                            ybInspectData.setCarbonContentHead(byPieceNoHead.getcContents());
                            ybInspectData.setOxygenContentHead(byPieceNoHead.getoContents());
                        } else {
                            ybInspectData.setCarbonContentHead(BigDecimal.ZERO);
                            ybInspectData.setOxygenContentHead(BigDecimal.ZERO);
                        }
                    }
                    if (StringUtils.isNotBlank(bySectionNo.getPieceNoEnd())) {
                        PieceCheck byPieceNoTail = pieceCheckService.getByPieceNo(bySectionNo.getPieceNoEnd());
                        if (null != byPieceNoTail) {
                            ybInspectData.setCarbonContentTail(byPieceNoTail.getcContents());
                            ybInspectData.setOxygenContentTail(byPieceNoTail.getoContents());
                        } else {
                            ybInspectData.setCarbonContentTail(BigDecimal.ZERO);
                            ybInspectData.setOxygenContentTail(BigDecimal.ZERO);
                        }
                    }
                }
                //处理掉特殊逻辑
                if(ybInspectData.getSectionNo().endsWith("T1")){
                    ProductionBackCuttingRecord productionBackCuttingRecord = productionRecutService.findBySectionNo(ybInspectData.getCrystalNo() + "T");
                    if (null != productionBackCuttingRecord && StringUtils.isNotBlank(productionBackCuttingRecord.getCause()) && productionBackCuttingRecord.getCause().contains("返切不复测")){
                        DefaultSample defaultSample = defaultSampleService.findByDopantLikeAndSpecificationsLikeAndProductTypeLike(ybInspectData.getDopant(), ybInspectData.getProductTypeSecond(),ybInspectData.getProductType());
                        ybInspectData.setOxygenContentHead(NumberUtil.Object2BigDecimal(defaultSample.getOxygenCenterHead(), null));
                        //注释W氧含量中心 赋默认值
                        //ybInspectData.setOxygenContentTail(NumberUtil.Object2BigDecimal(defaultSample.getOxygenCenterTail(), null));
                    }
                }
            }*/


        }

    }


    /**
     * 新关联逻辑，需关联返切数据
     * @param ybInspectData
     */
    public void handleDefaultOxygenAndCarbonNew(YbInspectData ybInspectData) {
        if (null != ybInspectData) {
            if (StringUtils.isBlank(ybInspectData.getSectionNo()) || StringUtils.isBlank(ybInspectData.getCrystalNo())) {
                return;
            }
            //查询返切记录
            String sectionNo = ybInspectData.getSectionNo();
            String crystalNo = ybInspectData.getCrystalNo();
            ProductionBackCuttingRecord productionBackCuttingRecord = productionRecutService.findBySectionNo(sectionNo.substring(0, sectionNo.length() - 1));
            if (null != productionBackCuttingRecord && null != productionBackCuttingRecord.getInspectionMark() && productionBackCuttingRecord.getInspectionMark() == 1){
                SectionNoDetail sectionNoDetail = sectionNoDetailService.findBySectionNo(sectionNo);
                if (null == sectionNoDetail){
                    throw new BusinessException("单晶追溯信息不存在！");
                }
                Boolean oxygenCarbonMarkHead = false;
                Boolean oxygenCarbonMarkTail = false;
                if (null != sectionNoDetail.getOxygenCarbonMark()){
                    oxygenCarbonMarkHead = sectionNoDetail.getOxygenCarbonMark() == EnumValuesFactory.OxygenCarbonMarkStatus.HEAD_DEPEND.getKey();
                    oxygenCarbonMarkTail = sectionNoDetail.getOxygenCarbonMark() == EnumValuesFactory.OxygenCarbonMarkStatus.TAIL_DEPEND.getKey();
                    if (oxygenCarbonMarkHead && (ybInspectData.getMeanCarrierLifetimeA().compareTo(BigDecimal.ZERO) <= 0 || ybInspectData.getMeanResistivityA().compareTo(BigDecimal.ZERO) <= 0)){
                        throw new BusinessException("头段A面电阻率或少子寿命未检出！");
                    }else if (oxygenCarbonMarkTail && (ybInspectData.getMeanCarrierLifetimeB().compareTo(BigDecimal.ZERO) <= 0 || ybInspectData.getMeanResistivityB().compareTo(BigDecimal.ZERO) <= 0)){
                        throw new BusinessException("尾段B面电阻率或少子寿命未检出！");
                    }
                }
                //查询头数据
                if (!oxygenCarbonMarkHead){
                    YbInspectData ybInspectDataHead = this.findByCrystalNoAndOxygenCarbonMark(crystalNo, EnumValuesFactory.OxygenCarbonMarkStatus.HEAD_DEPEND.getKey());
                    if (null != ybInspectDataHead) {
                        this.handleYbInspectDataABInfo(ybInspectDataHead, ybInspectData, true);
                    }
                }
                //查询尾数据
                if (!oxygenCarbonMarkTail){
                    YbInspectData ybInspectDataTail = this.findByCrystalNoAndOxygenCarbonMark(crystalNo, EnumValuesFactory.OxygenCarbonMarkStatus.TAIL_DEPEND.getKey());
                    if (null != ybInspectDataTail) {
                        this.handleYbInspectDataABInfo(ybInspectDataTail, ybInspectData, false);
                    }
                }

                if (null != ybInspectData.getHeadTailRecognition() && !StringUtils.equals(ybInspectData.getHeadTailRecognition(),"T段W段")){
                    if (oxygenCarbonMarkHead){
                        ybInspectData.setHeadTailRecognition("T段");
                    }
                    if (oxygenCarbonMarkTail){
                        ybInspectData.setHeadTailRecognition("W段");
                    }
                }
                this.handleOxygenAndCarbonContent(ybInspectData,sectionNoDetail,crystalNo);
                this.handleResistorsAndLifetime(ybInspectData);
            }else {
                this.handleDefaultOxygenAndCarbon(ybInspectData);
            }
        }
    }

    private void handleOxygenAndCarbonContent(YbInspectData ybInspectData,SectionNoDetail sectionNoDetail,String crystalNo){

        if (null == ybInspectData || null == sectionNoDetail){
            return;
        }

        Boolean oxygenCarbonMarkHead = null != sectionNoDetail.getOxygenCarbonMark() && sectionNoDetail.getOxygenCarbonMark() == EnumValuesFactory.OxygenCarbonMarkStatus.HEAD_DEPEND.getKey();
        Boolean oxygenCarbonMarkTail = null != sectionNoDetail.getOxygenCarbonMark() && sectionNoDetail.getOxygenCarbonMark() == EnumValuesFactory.OxygenCarbonMarkStatus.TAIL_DEPEND.getKey();

        if (StringUtils.isNotBlank(sectionNoDetail.getPieceNoHead())) {
            PieceCheck pieceCheck = pieceCheckService.getByPieceNo(sectionNoDetail.getPieceNoHead());
            if (null != pieceCheck) {
                ybInspectData.setOxygenContentHead(pieceCheck.getoContents());
                ybInspectData.setCarbonContentHead(pieceCheck.getcContents());
            } else {
                ybInspectData.setOxygenContentHead(BigDecimal.ZERO);
                ybInspectData.setCarbonContentHead(BigDecimal.ZERO);
            }
        }else {
            SectionNoDetail sectionNoDetailHead = sectionNoDetailService.findByCrystalNoAndOxygenCarbonMark(crystalNo, 1);
            if (null != sectionNoDetailHead) {
                PieceCheck pieceCheckHead = pieceCheckService.getByPieceNo(sectionNoDetailHead.getPieceNoHead());
                if (null != pieceCheckHead) {
                    if (!oxygenCarbonMarkHead){
                        DefaultSample defaultSample = defaultSampleService.findByDopantLikeAndSpecificationsLikeAndProductTypeLike(sectionNoDetail.getDopant(), sectionNoDetail.getSpecs(), null);
                        if (null != defaultSample) {
                            if (null != pieceCheckHead.getoContents() && NumberUtil.isNumeric(defaultSample.getOxygenCenterHead())
                                    && pieceCheckHead.getoContents().compareTo(new BigDecimal(defaultSample.getOxygenCenterHead())) <= 0) {
                                ybInspectData.setOxygenContentHead(pieceCheckHead.getoContents());
                                ybInspectData.setCarbonContentHead(pieceCheckHead.getcContents());
                            } else {
                                //剔除头段返切不复测影响
                                ybInspectData.setOxygenContentHead(pieceCheckHead.getoContents());
                                ybInspectData.setCarbonContentHead(pieceCheckHead.getcContents());
                                //处理氧碳返切测试
                                Map<String, Object> inspectMap = BeanUtil.convertObjectToMap(ybInspectData, YbInspectData.class);
                                GradeVersion gradeVersion = gradeVersionService.findTopByStatusAndRegion(EnumValuesGrade.GradeVersionStatus.已生效.getKey(), EnumValuesGrade.Region.圆棒.getKey());
                                if (null == gradeVersion) {
                                    throw new RuntimeException("不存在已生效圆棒评级规则！");
                                }
                                //处理返切不复测
                                Boolean oxygenBackCuttingFlag = false;
                                GradeRule gradeRuleOxygenBackCutting = gradeRuleService.findTopByGradeVersionIdAndDopantAndSpecificationsAndGradeLike(gradeVersion.getId(), ybInspectData.getDopant(), ybInspectData.getProductTypeSecond(), "%返切不复测");
                                if (null != gradeRuleOxygenBackCutting) {
                                    oxygenBackCuttingFlag = gradeRuleService.execGradeRule(gradeVersion.getId(), gradeRuleOxygenBackCutting.getName(), EnumValuesGrade.Region.圆棒.getKey(), inspectMap);
                                }
                                if (oxygenBackCuttingFlag){
                                    ybInspectData.setOxygenContentHead(NumberUtil.Object2BigDecimal(defaultSample.getOxygenCenterHead(), null));
                                    ybInspectData.setCarbonContentHead(NumberUtil.Object2BigDecimal(defaultSample.getCarbonCenterHead(), null));
                                }else {
                                    ybInspectData.setOxygenContentHead(BigDecimal.ZERO);
                                    ybInspectData.setCarbonContentHead(BigDecimal.ZERO);
                                }
                            }
                        }
                    }
                } else {
                    ybInspectData.setOxygenContentHead(BigDecimal.ZERO);
                    ybInspectData.setCarbonContentHead(BigDecimal.ZERO);
                }
            }
        }
        if (StringUtils.isNotBlank(sectionNoDetail.getPieceNoEnd())) {
            PieceCheck pieceCheckEnd = pieceCheckService.getByPieceNo(sectionNoDetail.getPieceNoEnd());
            if (null != pieceCheckEnd) {
                ybInspectData.setOxygenContentTail(pieceCheckEnd.getoContents());
                ybInspectData.setCarbonContentTail(pieceCheckEnd.getcContents());
            } else {
                ybInspectData.setOxygenContentTail(BigDecimal.ZERO);
                ybInspectData.setCarbonContentTail(BigDecimal.ZERO);
            }
        } else {
            SectionNoDetail sectionNoDetailTail = sectionNoDetailService.findByCrystalNoAndOxygenCarbonMark(ybInspectData.getCrystalNo(), 2);
            if (null != sectionNoDetailTail) {
                PieceCheck pieceCheckTail = pieceCheckService.getByPieceNo(sectionNoDetailTail.getPieceNoEnd());
                if (null != pieceCheckTail) {
                    if (!oxygenCarbonMarkTail){
                        DefaultSample defaultSample = defaultSampleService.findByDopantLikeAndSpecificationsLikeAndProductTypeLike(sectionNoDetail.getDopant(), sectionNoDetail.getSpecs(), null);
                        if (null != defaultSample) {
                            if (null != pieceCheckTail.getcContents() && NumberUtil.isNumeric(defaultSample.getCarbonCenterTail())
                                    && pieceCheckTail.getcContents().compareTo(new BigDecimal(defaultSample.getCarbonCenterTail())) <= 0) {
                                ybInspectData.setOxygenContentTail(pieceCheckTail.getoContents());
                                ybInspectData.setCarbonContentTail(pieceCheckTail.getcContents());
                            } else {
                                ybInspectData.setOxygenContentTail(BigDecimal.ZERO);
                                ybInspectData.setCarbonContentTail(BigDecimal.ZERO);
                            }
                        }
                    }
                } else {
                    ybInspectData.setOxygenContentTail(BigDecimal.ZERO);
                    ybInspectData.setCarbonContentTail(BigDecimal.ZERO);
                }
            }
        }
    }

    /**
     * 赋值头尾电阻和少子寿命
     * @param ybInspectData
     */
    private void handleResistorsAndLifetime(YbInspectData ybInspectData){
        if (null == ybInspectData){
            return;
        }
        //
        if (null != ybInspectData.getMeanResistivityA() && ybInspectData.getMeanResistivityA().compareTo(BigDecimal.ZERO) > 0) {
            ybInspectData.setTResistivity(ybInspectData.getMeanResistivityA());
        }
        if (null != ybInspectData.getMeanResistivityB() && ybInspectData.getMeanResistivityB().compareTo(BigDecimal.ZERO) > 0) {
            ybInspectData.setWResistivity(ybInspectData.getMeanResistivityB());
        }
        if (null != ybInspectData.getMeanCarrierLifetimeA() && ybInspectData.getMeanCarrierLifetimeA().compareTo(BigDecimal.ZERO) > 0) {
            ybInspectData.setTCentreLife(ybInspectData.getMeanCarrierLifetimeA());
        }
        if (null != ybInspectData.getMeanCarrierLifetimeB() && ybInspectData.getMeanCarrierLifetimeB().compareTo(BigDecimal.ZERO) > 0) {
            ybInspectData.setWLifeEdge1(ybInspectData.getMeanCarrierLifetimeB());
        }
    }

    @Override
    public Result findVerifyScrapLoss(String processName, BigDecimal lossLength, String sectionNo) {
        Assert.notNull(processName, "工序不能为空！");
        Assert.notNull(lossLength, "损耗长度不能为空！");
        Assert.notNull(sectionNo, "单晶编号不能为空！");
        if (StringUtils.equals(processName, EnumValuesFactory.WipStorageCode.毛棒截断.getValue())) {
            LongCrystal byCrystalNo = longCrystalService.findByCrystalNo(sectionNo);
            Assert.notNull(byCrystalNo, "报废长晶棒不存在，编号为：" + sectionNo);
            if (lossLength.compareTo(byCrystalNo.getLength()) < 0) {
                throw new RuntimeException("当前节点为：" + processName + "，报废长段小于晶棒长度，编号为：" + sectionNo + " 报废长度为：" + lossLength + " 长晶棒长度为：" + byCrystalNo.getLength());
            }
            return ResultGenerator.success("当前节点为：" + processName + ",是否报废当前晶棒，晶棒编号为：" + sectionNo);
        } else if (StringUtils.equals(processName, EnumValuesFactory.WipStorageCode.圆棒截断.getValue()) || StringUtils.equals(processName, EnumValuesFactory.WipStorageCode.粘圆棒.getValue()) ||
                StringUtils.equals(processName, EnumValuesFactory.WipStorageCode.圆棒检验.getValue()) || StringUtils.equals(processName, EnumValuesFactory.WipStorageCode.磨倒.getValue()) ||
                StringUtils.equals(processName, EnumValuesFactory.WipStorageCode.开方.getValue())) {
            YbInspectData bySectionNo = this.findBySectionNo(sectionNo);
            Assert.notNull(bySectionNo, "当前节点为：" + processName + ",报废圆棒检验信息不存在，编号为：" + sectionNo);
            if (lossLength.compareTo(bySectionNo.getActualLength()) < 0) {
                throw new RuntimeException("当前节点为：" + processName + "，报废长段小于晶段长度，编号为：" + sectionNo + " 报废长度为：" + lossLength + " 晶段长度为：" + bySectionNo.getActualLength());
            }
            return ResultGenerator.success("当前节点为：" + processName + ",是否报废当前晶段，晶段编号为：" + sectionNo);
        }

        return ResultGenerator.fail("当前节点为：" + processName + ",信息异常，晶段编号为：" + sectionNo);
    }

    @Override
    public BigDecimal findSumWeightByOrderNoAndIsCutBack(String orderNo, int cutBack) {
        return dao.findSumWeightByOrderNoAndIsCutBack(orderNo, cutBack);
    }

    @Override
    public Integer findLongCrystalByCrystalNo(String sectionNo) {
        return dao.findLongCrystalByCrystalNo(sectionNo);
    }

    @Override
    public List<ErrorClosePlanProcessingOrderDto> supplementaryData(List<PlanProcessingOrderDto> dtos) {
        List<ErrorClosePlanProcessingOrderDto> list = new ArrayList<>();
        if(null == dtos || dtos.size() < 1){
            return null;
        }
        for (PlanProcessingOrderDto dto : dtos) {

            ErrorClosePlanProcessingOrderDto errorClosePlanProcessingOrderDto = new ErrorClosePlanProcessingOrderDto();
//            if (dto.getRemarks() != null && dto.getRemarks().contains("划线回收料完单")) {//查不到检验数据，特殊处理下
//                errorClosePlanProcessingOrderDto.setCode(dto.getCode());
//                errorClosePlanProcessingOrderDto.setLength(dto.getLength());
//                errorClosePlanProcessingOrderDto.setWeight(dto.getWeight());
//                errorClosePlanProcessingOrderDto.setLevel(null);
//                errorClosePlanProcessingOrderDto.setWipStorage(dto.getCloseStorage());
//                errorClosePlanProcessingOrderDto.setOperationTime(dto.getUpdateTime());
//                errorClosePlanProcessingOrderDto.setOperationUser(dto.getUpdateUserName());
//                errorClosePlanProcessingOrderDto.setRemarks(dto.getRemarks());
//                list.add(errorClosePlanProcessingOrderDto);
//                continue;
//            }

            errorClosePlanProcessingOrderDto.setCode(dto.getCode());
            errorClosePlanProcessingOrderDto.setOperationTime(dto.getUpdateTime());
            errorClosePlanProcessingOrderDto.setOperationUser(dto.getUpdateUserName());
            errorClosePlanProcessingOrderDto.setWeight(dto.getWeight());
            errorClosePlanProcessingOrderDto.setWipStorage(dto.getCloseStorage());
            errorClosePlanProcessingOrderDto.setRemarks(dto.getRemarks());

            YbInspectData bySectionNo = ybInspectDataService.findBySectionNo(dto.getCode());
            if (null != bySectionNo) {
                errorClosePlanProcessingOrderDto.setLength(bySectionNo.getActualLength());
                errorClosePlanProcessingOrderDto.setLevel(bySectionNo.getProductLevel());
            }
            //如果有方棒数据以方棒数据为准
            Result<FbCheckOutData> fbCheckOutDataByFbSectionNo = fbFeignClients.findFbCheckOutDataByFbSectionNo(dto.getCode());
            if (ResultCode.SUCCESS.getCode() == fbCheckOutDataByFbSectionNo.getCode()) {
                FbCheckOutData data = fbCheckOutDataByFbSectionNo.getData();
                if (null != data) {
                    errorClosePlanProcessingOrderDto.setLength(data.getLength());
                    errorClosePlanProcessingOrderDto.setLevel(data.getProductLevelFb());
                }
            }
            list.add(errorClosePlanProcessingOrderDto);

        }
        return list;
    }

    @Override
    public List<YbInspectData> findByCrystalNo(List<String> ybCrystalNoList) {
        return dao.findByCrystalNo2(ybCrystalNoList);
    }

    @Override
    public void handleCrystalLossRecord(CrystalLossRecord crystalLossRecord) {
        if (null == crystalLossRecord){
            return;
        }
        if (StringUtils.isNotBlank(crystalLossRecord.getYbSectionNo())){
            CrystalMaterialRelation crystalMaterialRelationKf = crystalMaterialRelationService.findBySectionNo(crystalLossRecord.getYbSectionNo());
            if (null != crystalMaterialRelationKf){
                crystalLossRecord.setOrderNo(crystalMaterialRelationKf.getOrderNo());
                crystalLossRecord.setSquareMachine(crystalMaterialRelationKf.getDeviceNo());
                crystalLossRecord.setMaterialCode(crystalMaterialRelationKf.getMaterialCode());
                if (null != crystalMaterialRelationKf.getMaterialModelId()){
                    MaterialModel materialModel = materialModelService.get(crystalMaterialRelationKf.getMaterialModelId());
                    if (null != materialModel){
                        crystalLossRecord.setMaterialName(materialModel.getName());
                    }
                }
            }
            YbInspectData bySectionNo = this.findBySectionNo(crystalLossRecord.getYbSectionNo());
            if (null != bySectionNo){
                crystalLossRecord.setCrystalNo(bySectionNo.getCrystalNo());
                CrystalMaterialRelation crystalMaterialRelationJd = crystalMaterialRelationService.findBySectionNo(bySectionNo.getCrystalNo());
                if (null != crystalMaterialRelationJd){
                    crystalLossRecord.setCutMachine(crystalMaterialRelationJd.getDeviceNo());
                }
                LongCrystal longCrystal = longCrystalService.findByCrystalNo(bySectionNo.getCrystalNo());
                if (null != longCrystal){
                    FactoryModel factoryModel = factoryModelService.findByCode(longCrystal.getArea());
                    if (null != factoryModel){
                        crystalLossRecord.setWorkshop(factoryModel.getName());
                    }
                    crystalLossRecord.setArea(longCrystal.getSeries());
                    crystalLossRecord.setSimpleName(longCrystal.getSimpleName());
                }

                //处理圆棒划线数据
                ProductionPaintingLine productionPaintingLine = productionPaintingLineService.findByCrystalNo(bySectionNo.getCrystalNo());
                if (null != productionPaintingLine){
                    crystalLossRecord.setRodTime(productionPaintingLine.getEndTime());
                    crystalLossRecord.setRodInspector(productionPaintingLine.getUserName());
                }
            }else {
                if (StringUtils.isNotBlank(crystalLossRecord.getCrystalNo())){
                    //处理圆棒划线数据
                    ProductionPaintingLine productionPaintingLine = productionPaintingLineService.findByCrystalNo(crystalLossRecord.getCrystalNo());
                    if (null != productionPaintingLine){
                        crystalLossRecord.setRodTime(productionPaintingLine.getEndTime());
                        crystalLossRecord.setRodInspector(productionPaintingLine.getUserName());
                    }
                }
            }
        }else {
            //处理圆棒划线数据
            ProductionPaintingLine productionPaintingLine = productionPaintingLineService.findByCrystalNo(crystalLossRecord.getSectionNo());
            if (null != productionPaintingLine){
                crystalLossRecord.setRodTime(productionPaintingLine.getEndTime());
                crystalLossRecord.setRodInspector(productionPaintingLine.getUserName());
            }
            CrystalMaterialRelation crystalMaterialRelationJd = crystalMaterialRelationService.findBySectionNo(crystalLossRecord.getSectionNo());
            if (null == crystalMaterialRelationJd){
                if (crystalLossRecord.getSectionNo().length()>= 16){
                    String crystalNo = crystalLossRecord.getSectionNo().substring(0, 16);
                    crystalMaterialRelationJd = crystalMaterialRelationService.findBySectionNo(crystalNo);
                    crystalLossRecord.setCrystalNo(crystalNo);
                }
            }
            if (null != crystalMaterialRelationJd){
                crystalLossRecord.setOrderNo(crystalMaterialRelationJd.getOrderNo());
                crystalLossRecord.setCutMachine(crystalMaterialRelationJd.getDeviceNo());
                crystalLossRecord.setMaterialCode(crystalMaterialRelationJd.getMaterialCode());
                if (null != crystalMaterialRelationJd.getMaterialModelId()){
                    MaterialModel materialModel = materialModelService.get(crystalMaterialRelationJd.getMaterialModelId());
                    if (null != materialModel){
                        crystalLossRecord.setMaterialName(materialModel.getName());
                    }
                }
            }
        }
        crystalLossRecordService.saveOrUpdate(crystalLossRecord);
    }

    @Override
    public Result ybCheckResult(YbCheckResultDto ybCheckResultDto) {
        if (null == ybCheckResultDto){
            throw new BusinessException("入参为空，请先核对上传参数!");
        }
        if (StringUtils.isBlank(ybCheckResultDto.getSectionNo())){
            throw new BusinessException("上传单晶编号为空，请先核对单晶编号!");
        }
        String sectionNo = ybCheckResultDto.getSectionNo();
        Date date = new Date();
        Result<CurrentWipStorageStatusDto> currentWipStorageStatusDtoResult = wipStorageService.selectWipStorageResult(sectionNo);
        if (currentWipStorageStatusDtoResult.getCode() != ResultCode.SUCCESS.getCode()) {
            throw new BusinessException(currentWipStorageStatusDtoResult.getMessage());
        }
        CurrentWipStorageStatusDto currentWipStorageStatusDto = currentWipStorageStatusDtoResult.getData();
        if (currentWipStorageStatusDto == null || currentWipStorageStatusDto.getWipStorageCode() == null || currentWipStorageStatusDto.getWipStorageStatus() == null) {
            throw new BusinessException("站点信息查询失败，请检查在制品信息!");
        }

        //添加批次锁定校验
        crystalBatchOperationService.judgeCrystalNoIsLock(null, sectionNo, false);
        // 查询是否存在检验数据,不存在进行初始化数据
        YbInspectData ybInspectData = this.findBySectionNo(sectionNo);
        if (null == ybInspectData){
            ybInspectData = new YbInspectData();
            ybInspectData.setSectionNo(sectionNo);
            SectionNoDetail sectionNoDetail = sectionNoDetailService.findBySectionNo(sectionNo);
            if (null == sectionNoDetail) {
                throw new BusinessException(sectionNo + "晶段追溯信息不存在，数据异常!");
            }

            LongCrystal longCrystal = longCrystalService.get(sectionNoDetail.getCrystalId());
            if (null == longCrystal) {
                throw new BusinessException(sectionNo + "长棒信息不存在，数据异常!");
            }
            ybInspectData.setCrystalNo(longCrystal.getCrystalNo());
            ybInspectData.setPiecewiseNum(sectionNoDetail.getSegmentNum());
            initInspectData(ybInspectData, sectionNoDetail, longCrystal);
            if (sectionNoDetail.getParentId() == 0) {
                ybInspectData.setCheckoutName("一次检验");
                ybInspectData.setReCheckType("0");
            } else {
                SectionNoDetail sectionNoDetailParent = sectionNoDetailService.get(sectionNoDetail.getParentId());
                if (sectionNoDetailParent != null && sectionNoDetailParent.getId() != null) {
                    YbInspectData ybInspectDataParent = findBySectionNo(sectionNoDetailParent.getSectionNo());
                    if (ybInspectDataParent != null) {
                        if (StringUtils.isNotBlank(ybInspectDataParent.getReCheckType())) {
                            ybInspectData.setReCheckType((Integer.parseInt(ybInspectDataParent.getReCheckType()) + 1) + "");
                        }
                        ybInspectData.setCheckoutName(EnumValues.CheckoutName.返切复检.getValue());
                        ybInspectData.setOrderType(ybInspectDataParent.getOrderType());
                        ybInspectData.setHeadTailRecognition(ybInspectDataParent.getHeadTailRecognition());
                    }
                }
            }
            //赋值头尾样片信息
            setSampleData(ybInspectData, sectionNoDetail.getPieceNoHead(), sectionNoDetail.getPieceNoEnd(), sectionNoDetail.getSegmentNum());
            //handleContentInfo(ybInspectData, sectionNoDetail.getCrystalNo());
            ybInspectData.setInspector("MCS上传");
            ybInspectData.setCreateTime(date);
            //调整完结方式
            ybInspectData.setClosureIdentification(StringUtils.equals(longCrystal.getWindUp(),EnumValuesServer.FINALIDENTIFICATION) ? "是" :"否");

            //计算理论重量
            if(null == ybInspectData.getTheoryWeight() || ybInspectData.getTheoryWeight().compareTo(BigDecimal.ZERO) == 0){
                List<DictionaryItem> dictionaryItems = dictionaryItemService.findByThemeValueAndItemName(Constants.WEIGHT_RATIO, sectionNoDetail.getSpecs(), true);
                if (!CollectionUtils.isEmpty(dictionaryItems)) {
                    BigDecimal weightLossCoefficient = NumberUtil.Object2BigDecimal(dictionaryItems.get(0).getValue());
                    if (null != weightLossCoefficient && weightLossCoefficient.compareTo(BigDecimal.ONE) > 0) {
                        ybInspectData.setTheoryWeight(sectionNoDetail.getLength().divide(weightLossCoefficient, 3, RoundingMode.HALF_UP));
                    }
                }
            }
        }
        ybInspectData.setUpdateUser("MCS上传");
        ybInspectData.setUpdateTime(date);
        //处理字段数据
        if (null != ybCheckResultDto.getActualWeight()){
            ybInspectData.setActualWeight(ybCheckResultDto.getActualWeight());
        }
        if (null != ybCheckResultDto.getActualLength()){
            ybInspectData.setActualLength(ybCheckResultDto.getActualLength());
        }
        if (StringUtils.isNotBlank(ybCheckResultDto.getLineNo())){
            ybInspectData.setCheckLineNo(ybCheckResultDto.getLineNo());
        }
        // 暂时只有 少子寿命
        BigDecimal meanResistivityA = BigDecimal.ZERO;
        BigDecimal meanResistivityB = BigDecimal.ZERO;
        BigDecimal divideDecimal = new BigDecimal(3);

        BigDecimal meanCarrierLifetimeA = BigDecimal.ZERO;
        BigDecimal meanCarrierLifetimeB = BigDecimal.ZERO;

        BigDecimal carrierLifetimeOne = BigDecimal.ONE;
        if (null != ybCheckResultDto.getTCentreLife() && ybCheckResultDto.getTCentreLife().compareTo(carrierLifetimeOne) != 0){
            meanCarrierLifetimeA = meanCarrierLifetimeA.add(ybCheckResultDto.getTCentreLife());
            ybInspectData.setCarrierLifetimeAOne(ybCheckResultDto.getTCentreLife());
        }
        if (null != ybCheckResultDto.getTLifeEdge1() && ybCheckResultDto.getTLifeEdge1().compareTo(carrierLifetimeOne) != 0){
            meanCarrierLifetimeA = meanCarrierLifetimeA.add(ybCheckResultDto.getTLifeEdge1());
            ybInspectData.setCarrierLifetimeATwo(ybCheckResultDto.getTLifeEdge1());
        }
        if (null != ybCheckResultDto.getTLifeEdge2() && ybCheckResultDto.getTLifeEdge2().compareTo(carrierLifetimeOne) != 0){
            meanCarrierLifetimeA = meanCarrierLifetimeA.add(ybCheckResultDto.getTLifeEdge2());
            ybInspectData.setCarrierLifetimeAThree(ybCheckResultDto.getTLifeEdge2());
            ybInspectData.setMeanCarrierLifetimeA(ybCheckResultDto.getTLifeEdge2());
        }
       /* if (meanCarrierLifetimeA.compareTo(BigDecimal.ZERO) > 0){
            ybInspectData.setMeanCarrierLifetimeA(meanCarrierLifetimeA.divide(divideDecimal, 3, BigDecimal.ROUND_HALF_UP));
        }*/
        if (null != ybCheckResultDto.getWCentreLife() && ybCheckResultDto.getWCentreLife().compareTo(carrierLifetimeOne) != 0){
            meanCarrierLifetimeB = meanCarrierLifetimeB.add(ybCheckResultDto.getWCentreLife());
            ybInspectData.setCarrierLifetimeBOne(ybCheckResultDto.getWCentreLife());
        }
        if (null != ybCheckResultDto.getWLifeEdge1() && ybCheckResultDto.getWLifeEdge1().compareTo(carrierLifetimeOne) != 0){
            meanCarrierLifetimeB = meanCarrierLifetimeB.add(ybCheckResultDto.getWLifeEdge1());
            ybInspectData.setCarrierLifetimeBTwo(ybCheckResultDto.getWLifeEdge1());
        }
        if (null != ybCheckResultDto.getWLifeEdge2() && ybCheckResultDto.getWLifeEdge2().compareTo(carrierLifetimeOne) != 0){
            meanCarrierLifetimeB = meanCarrierLifetimeB.add(ybCheckResultDto.getWLifeEdge2());
            ybInspectData.setCarrierLifetimeBThree(ybCheckResultDto.getWLifeEdge2());
            ybInspectData.setMeanCarrierLifetimeB(ybCheckResultDto.getWLifeEdge2());
        }
       /* if (meanCarrierLifetimeB.compareTo(BigDecimal.ZERO) > 0){
            ybInspectData.setMeanCarrierLifetimeB(meanCarrierLifetimeB.divide(divideDecimal, 3, BigDecimal.ROUND_HALF_UP));
        }*/


        if (null != ybCheckResultDto.getTRadialCentre()){
            meanResistivityA = meanResistivityA.add(ybCheckResultDto.getTRadialCentre());
            ybInspectData.setResistivityAOne(ybCheckResultDto.getTRadialCentre());
        }
        if (null != ybCheckResultDto.getTRadialEdge1()){
            meanResistivityA = meanResistivityA.add(ybCheckResultDto.getTRadialEdge1());
            ybInspectData.setResistivityATwo(ybCheckResultDto.getTRadialEdge1());
        }
        if (null != ybCheckResultDto.getTRadialEdge2()){
            meanResistivityA = meanResistivityA.add(ybCheckResultDto.getTRadialEdge2());
            ybInspectData.setResistivityAThree(ybCheckResultDto.getTRadialEdge2());
        }
        if (meanResistivityA.compareTo(BigDecimal.ZERO) > 0){
            ybInspectData.setMeanResistivityA(meanResistivityA.divide(divideDecimal, 3, BigDecimal.ROUND_HALF_UP));
        }
        if (null != ybCheckResultDto.getWRadialCentre()){
            meanResistivityB = meanResistivityB.add(ybCheckResultDto.getWRadialCentre());
            ybInspectData.setResistivityBOne(ybCheckResultDto.getWRadialCentre());
        }
        if (null != ybCheckResultDto.getWRadialEdge1()){
            meanResistivityB = meanResistivityB.add(ybCheckResultDto.getWRadialEdge1());
            ybInspectData.setResistivityBTwo(ybCheckResultDto.getWRadialEdge1());
        }
        if (null != ybCheckResultDto.getWRadialEdge2()){
            meanResistivityB = meanResistivityB.add(ybCheckResultDto.getWRadialEdge2());
            ybInspectData.setResistivityBThree(ybCheckResultDto.getWRadialEdge2());
        }
        if (meanResistivityB.compareTo(BigDecimal.ZERO) > 0){
            ybInspectData.setMeanResistivityB(meanResistivityB.divide(divideDecimal, 3, BigDecimal.ROUND_HALF_UP));
        }

        if (StringUtils.isNotBlank(ybCheckResultDto.getConductiveType())){
            ybInspectData.setConductiveType(ybCheckResultDto.getConductiveType());
        }

        //触发评级
        Result<String> stringResult = this.saveDataAndGrade(ybInspectData, false);
        if (null != stringResult && stringResult.getCode().equals("400")) {
            return stringResult;
        }
        this.saveDataInspectLog(ybInspectData);
        //添加逻辑 处理是否需要还原母单晶
        this.reducedMotheCrystal(ybInspectData);

        //是否处于圆棒检验待进站状态
        boolean isStatus = currentWipStorageStatusDto.getWipStorageCode().equals(EnumValuesFactory.WipStorageCode.圆棒检验.getKey()) && currentWipStorageStatusDto.getWipStorageStatus() == EnumValuesFactory.WipStorageStatus.待进站.getKey();
        if (isStatus){
            Result result = wipStorageService.inStation(sectionNo, null, false);
            if (result.getCode() != ResultCode.SUCCESS.getCode()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
        }
        return ResultGenerator.success();
    }

    @Override
    public Result<List<YbInspectDataPdaAutomaticDto>> getInspectDataByCrystalNo(String crystalNo) {
        if (StringUtils.isBlank(crystalNo)){
            throw new BusinessException("传入单晶编号为空!");
        }
        String crystalNoNew = crystalNo;
        if (GlobalSwitch.enable(GlobalSwitchNamespace.NAMESPACE_YB_CHECK, "crystalRodSwitch", true)){
            if (crystalNo.length() > 16){
                SectionNoDetail sectionNoDetailNew = sectionNoDetailService.findBySectionNo(crystalNo);
                if (null != sectionNoDetailNew){
                    crystalNoNew = sectionNoDetailNew.getCrystalNo();
                }
            }
        }
        SectionNoDetail sectionNoDetailHead = sectionNoDetailService.findByCrystalNoAndOxygenCarbonMark(crystalNoNew, 1);
        if (null == sectionNoDetailHead){
            throw new BusinessException(crystalNo +" 不存在头段划线数据!");
        }
        String sectionNoHead = sectionNoDetailHead.getSectionNo();
        SectionNoDetail sectionNoDetailTail = sectionNoDetailService.findByCrystalNoAndOxygenCarbonMark(crystalNoNew, 2);
        if (null == sectionNoDetailTail){
            throw new BusinessException(crystalNo +" 不存在尾段划线数据!");
        }
        String sectionNoTail = sectionNoDetailTail.getSectionNo();
        List<YbInspectData> ybInspectDataList = this.getDataByCrystalNo(crystalNoNew);
        if (CollectionUtils.isEmpty(ybInspectDataList)){
            throw new BusinessException("圆棒检验数据库不存在该晶棒："+ crystalNo +" 检验数据!");
        }
        YbInspectData ybInspectDataHead = null;
        YbInspectData ybInspectDataTail = null;
        for (YbInspectData ybInspectData : ybInspectDataList){
            if (StringUtils.equals(ybInspectData.getSectionNo(),sectionNoHead)){
                ybInspectDataHead = ybInspectData;
            }
            if (StringUtils.equals(ybInspectData.getSectionNo(),sectionNoTail)){
                ybInspectDataTail = ybInspectData;
            }
        }
        GradeVersion gradeVersion = gradeVersionService.findTopByStatusAndRegion(EnumValuesGrade.GradeVersionStatus.已生效.getKey(), EnumValuesGrade.Region.圆棒.getKey());
        if (null == gradeVersion) {
            throw new RuntimeException("不存在已生效圆棒评级规则!!");
        }
        Boolean headResistanceOvertakeFlag = false;
        Boolean tailResistanceOvertakeFlag = false;
        if (null != ybInspectDataHead){
            headResistanceOvertakeFlag = this.handleResistanceReverseTangent(gradeVersion,ybInspectDataHead);
        }
        if (null != ybInspectDataTail){
            tailResistanceOvertakeFlag = this.handleResistanceReverseTangent(gradeVersion,ybInspectDataTail);
        }
        if (headResistanceOvertakeFlag && tailResistanceOvertakeFlag){
            throw new RuntimeException("头尾电阻都超标，需要返切之后才能赋值!!");
        }
        List<YbInspectDataPdaAutomaticDto> resultList = new ArrayList<>();

        for (YbInspectData ybInspectData : ybInspectDataList){
            if ((sectionNoHead.contains(ybInspectData.getSectionNo()) && !StringUtils.equals(sectionNoHead,ybInspectData.getSectionNo()))
                    || (sectionNoTail.contains(ybInspectData.getSectionNo()) && !StringUtils.equals(sectionNoTail,ybInspectData.getSectionNo()))){
                continue;
            }
            if (!headResistanceOvertakeFlag && null != ybInspectDataHead){
                ybInspectData.setResistivityAOne(ybInspectDataHead.getResistivityAOne());
                ybInspectData.setResistivityATwo(ybInspectDataHead.getResistivityATwo());
                ybInspectData.setResistivityAThree(ybInspectDataHead.getResistivityAThree());
                ybInspectData.setMeanResistivityA(ybInspectDataHead.getMeanResistivityA());
            }
            if (!tailResistanceOvertakeFlag && null != ybInspectDataTail){
                ybInspectData.setResistivityBOne(ybInspectDataTail.getResistivityBOne());
                ybInspectData.setResistivityBTwo(ybInspectDataTail.getResistivityBTwo());
                ybInspectData.setResistivityBThree(ybInspectDataTail.getResistivityBThree());
                ybInspectData.setMeanResistivityB(ybInspectDataTail.getMeanResistivityB());
            }
            resultList.add(this.handleYbInspectDataPdaAutomaticDto(ybInspectData));
        }
        resultList = resultList.stream().sorted(Comparator.comparing(YbInspectDataPdaAutomaticDto::getPiecewiseNum,
                Comparator.nullsFirst(Integer::compareTo))).collect(Collectors.toList());
        return ResultGenerator.success(resultList);
    }

    @Override
    public String assignmentResistance(List<YbInspectDataPdaAutomaticDto> ybInspectDataPdaAutomaticDtos) {
        StringBuilder result = new StringBuilder();
        if (CollectionUtils.isNotEmpty(ybInspectDataPdaAutomaticDtos)){
            Map<String, YbInspectData> execGrade = new HashMap<>();
            Date date = new Date();
            Integer updateCount = 0;
            Integer abnormalCount = 0;
            for (YbInspectDataPdaAutomaticDto ybInspectDataPdaAutomaticDto : ybInspectDataPdaAutomaticDtos){
                if (StringUtils.isBlank(ybInspectDataPdaAutomaticDto.getSectionNo())){
                    abnormalCount++;
                    log.info("传入单晶编号为空，请核对数据!");
                    continue;
                    //throw new RuntimeException("传入单晶编号为空，请核对数据！!");
                }
                YbInspectData ybInspectData = this.findBySectionNo(ybInspectDataPdaAutomaticDto.getSectionNo());
                if (null == ybInspectData){
                    abnormalCount++;
                    log.info("检验数据库不存在该单晶记录,单晶编号为：{}",ybInspectDataPdaAutomaticDto.getSectionNo());
                    continue;
                    //throw new RuntimeException("检验数据库不存在该单晶记录，请核对数据！!");
                }
                List<WipStorage> wipStorageList = wipStorageService.findByProcessingByOrderCode(ybInspectDataPdaAutomaticDto.getSectionNo());
                if (CollectionUtils.isEmpty(wipStorageList)){
                    abnormalCount++;
                    log.info("在制品记录不存在,单晶编号为：{}",ybInspectDataPdaAutomaticDto.getSectionNo());
                    continue;
                }
                String processName = wipStorageList.get(0).getProcessName();
                if ( !StringUtils.equals(processName,EnumValuesFactory.WipStorageCode.圆棒检验.getValue())){
                    abnormalCount++;
                    log.info("单晶编号为：{}，站点信息为：{}",ybInspectDataPdaAutomaticDto.getSectionNo(),processName);
                    continue;
                }
                ybInspectData.setMeanResistivityA(ybInspectDataPdaAutomaticDto.getMeanResistivityA());
                ybInspectData.setResistivityAOne(ybInspectDataPdaAutomaticDto.getResistivityAOne());
                ybInspectData.setResistivityATwo(ybInspectDataPdaAutomaticDto.getResistivityATwo());
                ybInspectData.setResistivityAThree(ybInspectDataPdaAutomaticDto.getResistivityAThree());
                ybInspectData.setMeanResistivityB(ybInspectDataPdaAutomaticDto.getMeanResistivityB());
                ybInspectData.setResistivityBOne(ybInspectDataPdaAutomaticDto.getResistivityBOne());
                ybInspectData.setResistivityBTwo(ybInspectDataPdaAutomaticDto.getResistivityBTwo());
                ybInspectData.setResistivityBThree(ybInspectDataPdaAutomaticDto.getResistivityBThree());
                ybInspectData.setUpdateTime(date);
                ybInspectData.setUpdateUser(ybInspectDataPdaAutomaticDto.getUserName());
                this.saveOrUpdate(ybInspectData);
                execGrade.put(ybInspectData.getSectionNo(), ybInspectData);
                updateCount++;
            }
            if (execGrade.size() != 0) {
                gradeService.execGrade(execGrade);
            }
            result.append("成功更新电阻率条数：【").append(updateCount).append("】，非圆棒检验站点跳过的条数：【").append(abnormalCount).append("】!");
        }
        return result.toString();
    }

    private YbInspectDataPdaAutomaticDto handleYbInspectDataPdaAutomaticDto(YbInspectData ybInspectData){
        if (null == ybInspectData){
            throw new RuntimeException("转化检验数据为空，请核对数据！!");
        }
        return modelMapper.map(ybInspectData, YbInspectDataPdaAutomaticDto.class);
    }

    private Boolean handleResistanceReverseTangent(GradeVersion gradeVersion,YbInspectData ybInspectData){
        Map<String, Object> inspectMap = BeanUtil.convertObjectToMap(ybInspectData, YbInspectData.class);
        //电阻低反切
        Boolean resistanceLowReverseTangent = false;
        GradeRule gradeRuleReverseTangent = gradeRuleService.findTopByGradeVersionIdAndDopantAndSpecificationsAndGradeLike(gradeVersion.getId(),
                ybInspectData.getDopant(), ybInspectData.getProductTypeSecond(), "%电阻低返切");
        if (null != gradeRuleReverseTangent) {
            resistanceLowReverseTangent = gradeRuleService.execGradeRule(gradeVersion.getId(), gradeRuleReverseTangent.getName(), EnumValuesGrade.Region.圆棒.getKey(), inspectMap);
        }
        //电阻高反切
        Boolean highResistanceReverseTangentFlag = false;
        GradeRule gradeRuleResistanceReverseTangent = gradeRuleService.findTopByGradeVersionIdAndDopantAndSpecificationsAndGradeLike(gradeVersion.getId(),
                ybInspectData.getDopant(), ybInspectData.getProductTypeSecond(), "%电阻高返切");
        if (null != gradeRuleResistanceReverseTangent) {
            highResistanceReverseTangentFlag = gradeRuleService.execGradeRule(gradeVersion.getId(), gradeRuleResistanceReverseTangent.getName(), EnumValuesGrade.Region.圆棒.getKey(), inspectMap);
        }
        return (resistanceLowReverseTangent || highResistanceReverseTangentFlag);
    }

    /**
     * 处理中间段数据记录过站等操作
     *
     * @param ybInspectData
     */
    private void handleAutomaticInspectMiddle(YbInspectData ybInspectData) {

        if (null == ybInspectData || StringUtils.isBlank(ybInspectData.getSectionNo()) || StringUtils.isBlank(ybInspectData.getCrystalNo()) || ybInspectData.getSectionNo().endsWith("R")) {
            return;
        }
        boolean headFlag = ybInspectData.getSectionNo().endsWith("T");
        boolean tailFlag = ybInspectData.getSectionNo().endsWith("A");
        if (headFlag) {
            ybInspectData.setOxygenCarbonMark(EnumValuesFactory.OxygenCarbonMarkStatus.HEAD_DEPEND.getKey());
        } else if (tailFlag) {
            ybInspectData.setOxygenCarbonMark(EnumValuesFactory.OxygenCarbonMarkStatus.TAIL_DEPEND.getKey());
        }
        String pieceNoHead = null;
        String pieceNoTail = null;
        String sectionNoHead = null;
        String sectionNoTail = null;
        if (headFlag || tailFlag) {
            Date date = new Date();
            String username = BaseContextHandler.getUsername();
            AutomaticInspectMiddle byCrystalNo = automaticInspectMiddleService.findByCrystalNo(ybInspectData.getCrystalNo());
            List<SectionNoDetail> sectionNoDetailList = sectionNoDetailDao.findByCrystalNo(ybInspectData.getCrystalNo());
            if (CollectionUtils.isEmpty(sectionNoDetailList)) {
                return;
            }
            //List<String> sectionNoList = sectionNoDetailList.stream().map(SectionNoDetail::getSectionNo).collect(Collectors.toList());
            List<String> sectionNoList = new ArrayList<>();
            Map<String, SectionNoDetail> tempSectionNoDetail = new HashMap<>();
            for (SectionNoDetail sectionNoDetail : sectionNoDetailList) {
                if (StringUtils.isNotBlank(sectionNoDetail.getSectionNo())) {
                    if (!(sectionNoDetail.getSectionNo().endsWith("A") || sectionNoDetail.getSectionNo().endsWith("T")) &&
                            !StringUtils.equals(sectionNoDetail.getSectionType(), EnumValuesServer.RecutYbRule.回收料.getKey())) {
                        sectionNoList.add(sectionNoDetail.getSectionNo());
                        tempSectionNoDetail.put(sectionNoDetail.getSectionNo(), sectionNoDetail);
                    }
                    if (sectionNoDetail.getSectionNo().endsWith("A")) {
                        pieceNoTail = sectionNoDetail.getPieceNoEnd();
                        sectionNoTail = sectionNoDetail.getSectionNo();
                    }
                    if (sectionNoDetail.getSectionNo().endsWith("T")) {
                        pieceNoHead = sectionNoDetail.getPieceNoHead();
                        sectionNoHead = sectionNoDetail.getSectionNo();
                    }
                }
            }
            Map<String, YbInspectData> map = new HashMap<>();
            if (CollectionUtils.isEmpty(sectionNoList)) {
                //不存在中间段时，赋值
                if (headFlag) {
                    //查尾单晶
                    if (StringUtils.isNotBlank(sectionNoTail)) {
                        YbInspectData bySectionNoTail = ybInspectDataService.findBySectionNo(sectionNoTail);
                        if (null != bySectionNoTail) {
                            //将A面赋值
                            handleYbInspectDataheadOrTail(ybInspectData, bySectionNoTail, true);
                            this.handleYbInspectDataABInfo(ybInspectData, bySectionNoTail, true);
                            //将B面赋值
                            this.handleYbInspectDataABInfo(bySectionNoTail, ybInspectData, false);
                            handleYbInspectDataheadOrTail(bySectionNoTail, ybInspectData, false);
                            map.put(ybInspectData.getSectionNo(), ybInspectData);
                            map.put(bySectionNoTail.getSectionNo(), bySectionNoTail);
                            this.saveOrUpdate(ybInspectData);
                            this.saveOrUpdate(bySectionNoTail);
                            gradeService.execGrade(map);
                        }
                    }
                } else if (tailFlag) {
                    //查头单晶
                    if (StringUtils.isNotBlank(sectionNoHead)) {
                        YbInspectData bySectionNoHead = ybInspectDataService.findBySectionNo(sectionNoHead);
                        if (null != bySectionNoHead) {
                            this.handleYbInspectDataABInfo(ybInspectData, bySectionNoHead, false);
                            this.handleYbInspectDataABInfo(bySectionNoHead, ybInspectData, true);
                            handleYbInspectDataheadOrTail(ybInspectData, bySectionNoHead, false);
                            handleYbInspectDataheadOrTail(bySectionNoHead, ybInspectData, true);
                            map.put(ybInspectData.getSectionNo(), ybInspectData);
                            map.put(bySectionNoHead.getSectionNo(), bySectionNoHead);
                            this.saveOrUpdate(ybInspectData);
                            this.saveOrUpdate(bySectionNoHead);
                            gradeService.execGrade(map);
                        }
                    }
                }
                return;
            }
            //获取已检验的数据
            List<YbInspectData> ybInspectDataList = ybInspectDataService.findBySections(sectionNoList);

            List<YbInspectData> saveYbInspectDataList = new ArrayList<>();
            List<DataInspectLog> saveDataInspectLogList = new ArrayList<>();
            if (null != byCrystalNo) {
                byCrystalNo.setGmtUpdate(date);
                if (headFlag) {
                    if (StringUtils.equals(byCrystalNo.getSectionNoHead(), ybInspectData.getSectionNo())) {
                        for (YbInspectData ybInspectDataFor : ybInspectDataList) {
                            if (StringUtils.isBlank(ybInspectDataFor.getUpdateUser()) || StringUtils.equals("自动修改", ybInspectDataFor.getUpdateUser())) {
                                ybInspectDataFor.setUpdateTime(date);
                                ybInspectDataFor.setUpdateUser("自动修改");
                                map.put(ybInspectDataFor.getSectionNo(), ybInspectDataFor);
                                handleYbInspectDataheadOrTail(ybInspectData, ybInspectDataFor, true);
                                this.saveOrUpdate(ybInspectDataFor);
                            }
                        }

                    } else {
                        byCrystalNo.setSectionNoHead(ybInspectData.getSectionNo());
                        byCrystalNo.setPieceNoHead(pieceNoHead);
                        for (YbInspectData ybInspectDataFor : ybInspectDataList) {
                            ybInspectDataFor.setUpdateTime(date);
                            ybInspectDataFor.setUpdateUser("自动修改");
                            handleYbInspectDataheadOrTail(ybInspectData, ybInspectDataFor, true);
                            map.put(ybInspectDataFor.getSectionNo(), ybInspectDataFor);
                            this.saveOrUpdate(ybInspectDataFor);
                        }
                    }
                    // 处理尾段A面数据
                    YbInspectData bySectionNoTail = this.findBySectionNo(sectionNoTail);
                    if (null != bySectionNoTail) {
                        this.handleYbInspectDataABInfo(ybInspectData, bySectionNoTail, true);
                        this.saveOrUpdate(bySectionNoTail);
                        map.put(sectionNoTail, bySectionNoTail);
                    }


                } else if (tailFlag) {
                    if (StringUtils.equals(byCrystalNo.getSectionNoTail(), ybInspectData.getSectionNo())) {
                        for (YbInspectData ybInspectDataFor : ybInspectDataList) {
                            if (StringUtils.isBlank(ybInspectDataFor.getUpdateUser()) || StringUtils.equals("自动修改", ybInspectDataFor.getUpdateUser())) {
                                ybInspectDataFor.setUpdateTime(date);
                                ybInspectDataFor.setUpdateUser("自动修改");
                                map.put(ybInspectDataFor.getSectionNo(), ybInspectDataFor);
                                handleYbInspectDataheadOrTail(ybInspectData, ybInspectDataFor, false);
                                this.saveOrUpdate(ybInspectDataFor);
                            }
                        }
                    } else {
                        byCrystalNo.setSectionNoTail(ybInspectData.getSectionNo());
                        byCrystalNo.setPieceNoTail(pieceNoTail);
                        for (YbInspectData ybInspectDataFor : ybInspectDataList) {
                            ybInspectDataFor.setUpdateTime(date);
                            ybInspectDataFor.setUpdateUser("自动修改");
                            handleYbInspectDataheadOrTail(ybInspectData, ybInspectDataFor, false);
                            map.put(ybInspectDataFor.getSectionNo(), ybInspectDataFor);
                            this.saveOrUpdate(ybInspectDataFor);
                        }
                    }
                    // 处理头段B面数据
                    YbInspectData bySectionNoHead = this.findBySectionNo(sectionNoHead);
                    if (null != bySectionNoHead) {
                        this.handleYbInspectDataABInfo(ybInspectData, bySectionNoHead, false);
                        this.saveOrUpdate(bySectionNoHead);
                        map.put(sectionNoHead, bySectionNoHead);
                    }

                }
                //this.saveAll(ybInspectDataList);
                gradeService.execGrade(map);

            } else {
                byCrystalNo = new AutomaticInspectMiddle();
                byCrystalNo.setCrystalNo(ybInspectData.getCrystalNo());
                byCrystalNo.setGmtCreate(date);
                if (headFlag) {
                    byCrystalNo.setSectionNoHead(ybInspectData.getSectionNo());
                    byCrystalNo.setPieceNoHead(pieceNoHead);
                }
                if (tailFlag) {
                    byCrystalNo.setSectionNoTail(ybInspectData.getSectionNo());
                    byCrystalNo.setPieceNoTail(pieceNoTail);
                }
                List<String> hasSectionNoList = new ArrayList<>();
                for (YbInspectData ybInspectData1 : ybInspectDataList) {
                    hasSectionNoList.add(ybInspectData1.getSectionNo());
                }
                for (String sectionNo : sectionNoList) {

                    //检验存在，不创建中间段
                    if (hasSectionNoList.contains(sectionNo)) {
                        continue;
                    }
                    YbInspectData handleYbInspectData = handleYbInspectData(ybInspectData, sectionNo, tempSectionNoDetail.get(sectionNo), headFlag);
                    handleYbInspectData.setOxygenCarbonMark(EnumValuesFactory.OxygenCarbonMarkStatus.MIDDLE_SEGMENT.getKey());
                    saveYbInspectDataList.add(handleYbInspectData);
                    DataInspectLog dataInspectLog = new DataInspectLog();
                    this.dataToLog(handleYbInspectData, dataInspectLog);
                    dataInspectLog.setOperateTime(date);
                    dataInspectLog.setOperator(username);
                    dataInspectLog.setOperateType(0);
                    dataInspectLog.setRemarks("新增");
                    saveDataInspectLogList.add(dataInspectLog);
                    //过站操作
                    wipStorageService.inStation(sectionNo, null, false);
                }
            }
            //保存自动数据
            automaticInspectMiddleService.saveOrUpdate(byCrystalNo);
            if (saveYbInspectDataList.size() != 0) {
                this.saveAll(saveYbInspectDataList);
            }
            if (saveDataInspectLogList.size() != 0) {
                dataInspectLogService.saveAll(saveDataInspectLogList);
            }
        }
    }

    /**
     * 新处理，后面在提取
     *
     * @param ybInspectData
     */
    private void handleAutomaticInspectMiddleNew(YbInspectData ybInspectData) {

        if (null == ybInspectData || StringUtils.isBlank(ybInspectData.getSectionNo()) || StringUtils.isBlank(ybInspectData.getCrystalNo()) || ybInspectData.getSectionNo().endsWith("R")) {
            return;
        }
        boolean headFlag = (null != ybInspectData.getOxygenCarbonMark() ? ybInspectData.getOxygenCarbonMark() == 1 : ybInspectData.getSectionNo().endsWith("T"));
        boolean tailFlag = (null != ybInspectData.getOxygenCarbonMark() ? ybInspectData.getOxygenCarbonMark() == 2 : ybInspectData.getSectionNo().endsWith("A"));
        String pieceNoHead = null;
        String pieceNoTail = null;
        String sectionNoHead = null;
        String sectionNoTail = null;
        if (headFlag || tailFlag) {
            Date date = new Date();
            String username = BaseContextHandler.getUsername();
            AutomaticInspectMiddle automaticInspectMiddle = automaticInspectMiddleService.findByCrystalNo(ybInspectData.getCrystalNo());
            List<SectionNoDetail> sectionNoDetailList = sectionNoDetailDao.findByCrystalNo(ybInspectData.getCrystalNo());
            if (CollectionUtils.isEmpty(sectionNoDetailList)) {
                return;
            }
            Boolean identificationTransferFlag = true;
            //处理氧碳返切测试
            GradeVersion gradeVersion = gradeVersionService.findTopByStatusAndRegion(EnumValuesGrade.GradeVersionStatus.已生效.getKey(), EnumValuesGrade.Region.圆棒.getKey());
            if (null == gradeVersion) {
                throw new RuntimeException("不存在已生效圆棒评级规则！");
            }
            Map<String, Object> inspectMap = BeanUtil.convertObjectToMap(ybInspectData, YbInspectData.class);
            StringBuilder lockReason = new StringBuilder();

            List<String> levelMonitoring = new ArrayList<>();

            //处理寿命反切
            Boolean reversalLifespanFlag = false;
            GradeRule gradeRuleReversalLifespan = gradeRuleService.findTopByGradeVersionIdAndDopantAndSpecificationsAndGradeLike(gradeVersion.getId(), ybInspectData.getDopant(),
                    ybInspectData.getProductTypeSecond(), "%寿命返切");
            if (null != gradeRuleReversalLifespan) {
                reversalLifespanFlag = gradeRuleService.execGradeRule(gradeVersion.getId(), gradeRuleReversalLifespan.getName(), EnumValuesGrade.Region.圆棒.getKey(), inspectMap);
                levelMonitoring.add(gradeRuleReversalLifespan.getGrade());
            }

            if (reversalLifespanFlag) {
                lockReason.append("寿命返切,");
                identificationTransferFlag = false;
            }

            //电阻低反切
            Boolean resistanceLowReverseTangent = false;
            GradeRule gradeRuleReverseTangent = gradeRuleService.findTopByGradeVersionIdAndDopantAndSpecificationsAndGradeLike(gradeVersion.getId(), ybInspectData.getDopant(),
                    ybInspectData.getProductTypeSecond(), "%电阻低返切");
            if (null != gradeRuleReverseTangent) {
                resistanceLowReverseTangent = gradeRuleService.execGradeRule(gradeVersion.getId(), gradeRuleReverseTangent.getName(), EnumValuesGrade.Region.圆棒.getKey(), inspectMap);
                levelMonitoring.add(gradeRuleReverseTangent.getGrade());
            }
            if (resistanceLowReverseTangent) {
                lockReason.append("电阻低返切,");
                identificationTransferFlag = false;
            }

            //电阻高反切
            Boolean highResistanceReverseTangentFlag = false;
            GradeRule gradeRuleResistanceReverseTangent = gradeRuleService.findTopByGradeVersionIdAndDopantAndSpecificationsAndGradeLike(gradeVersion.getId(), ybInspectData.getDopant(),
                    ybInspectData.getProductTypeSecond(), "%电阻高返切");
            if (null != gradeRuleResistanceReverseTangent) {
                highResistanceReverseTangentFlag = gradeRuleService.execGradeRule(gradeVersion.getId(), gradeRuleResistanceReverseTangent.getName(), EnumValuesGrade.Region.圆棒.getKey(), inspectMap);
                levelMonitoring.add(gradeRuleResistanceReverseTangent.getGrade());
            }
            if (highResistanceReverseTangentFlag) {
                lockReason.append("电阻高返切,");
                identificationTransferFlag = false;
            }
            //处理样片氧碳值
            Boolean oxygenBackcutFlag = false;
            GradeRule gradeRuleOxygenBackcut = gradeRuleService.findTopByGradeVersionIdAndDopantAndSpecificationsAndGradeLike(gradeVersion.getId(), ybInspectData.getDopant(), ybInspectData.getProductTypeSecond(), "%氧返切");
            if (null != gradeRuleOxygenBackcut) {
                oxygenBackcutFlag = gradeRuleService.execGradeRule(gradeVersion.getId(), gradeRuleOxygenBackcut.getName(), EnumValuesGrade.Region.圆棒.getKey(), inspectMap);
            }
            if (oxygenBackcutFlag) {
                lockReason.append("氧返切,");
            }

            //处理返切不复测
            Boolean oxygenBackCuttingFlag = false;
            GradeRule gradeRuleOxygenBackCutting = gradeRuleService.findTopByGradeVersionIdAndDopantAndSpecificationsAndGradeLike(gradeVersion.getId(), ybInspectData.getDopant(), ybInspectData.getProductTypeSecond(), "%返切不复测");
            if (null != gradeRuleOxygenBackCutting) {
                oxygenBackCuttingFlag = gradeRuleService.execGradeRule(gradeVersion.getId(), gradeRuleOxygenBackCutting.getName(), EnumValuesGrade.Region.圆棒.getKey(), inspectMap);
            }
            DefaultSample defaultSample = defaultSampleService.findByDopantLikeAndSpecificationsLikeAndProductTypeLike(ybInspectData.getDopant(), ybInspectData.getProductTypeSecond(), ybInspectData.getProductType());
            if (null == defaultSample) {
                throw new BusinessException(ybInspectData.getSectionNo() + ",圆棒检验中样片默认值维护不存在，请先配置样片默认值！");
            }
            Boolean backCarbonFlag = false;
            GradeRule gradeRuleBackcutCarbon = gradeRuleService.findTopByGradeVersionIdAndDopantAndSpecificationsAndGradeLike(gradeVersion.getId(), ybInspectData.getDopant(), ybInspectData.getProductTypeSecond(), "%碳返切");
            if (null != gradeRuleBackcutCarbon) {
                backCarbonFlag = gradeRuleService.execGradeRule(gradeVersion.getId(), gradeRuleBackcutCarbon.getName(), EnumValuesGrade.Region.圆棒.getKey(), inspectMap);
            }
            if (backCarbonFlag) {
                lockReason.append("碳返切,");
            }
            List<String> sectionNoList = new ArrayList<>();

            Map<String, SectionNoDetail> sectionNoDetailMap = new HashMap<>();
            String sectionNoSecond = null;

            for (SectionNoDetail sectionNoDetailFor : sectionNoDetailList) {

                //剔除查询的回收料影响
                if (null != sectionNoDetailFor.getSectionType() && StringUtils.equals(sectionNoDetailFor.getSectionType(), EnumValuesServer.RecutYbRule.回收料.getKey())) {
                    continue;
                }
                //剔除返切问题修复
                if (null != sectionNoDetailFor.getSectionPosiotion() && sectionNoDetailFor.getSectionPosiotion() == 2) {
                    sectionNoSecond = sectionNoDetailFor.getSectionNo();
                }
                // 剔除空影响更新其它值
                if (null == sectionNoDetailFor.getOxygenCarbonMark()) {
                    continue;
                }
                //剔除报废的单晶数据
                if (null != sectionNoDetailFor.getInspectionScrap() && sectionNoDetailFor.getInspectionScrap() == 1){
                    continue;
                }

                if (sectionNoDetailFor.getOxygenCarbonMark() == 1) {
                    pieceNoHead = sectionNoDetailFor.getPieceNoHead();
                    sectionNoHead = sectionNoDetailFor.getSectionNo();
                    if (tailFlag && null != automaticInspectMiddle){
                        sectionNoList.add(sectionNoDetailFor.getSectionNo());
                    }
                } else if (sectionNoDetailFor.getOxygenCarbonMark() == 2) {
                    pieceNoTail = sectionNoDetailFor.getPieceNoEnd();
                    sectionNoTail = sectionNoDetailFor.getSectionNo();
                    if (headFlag && null != automaticInspectMiddle){
                        sectionNoList.add(sectionNoDetailFor.getSectionNo());
                    }
                } else {
                    sectionNoList.add(sectionNoDetailFor.getSectionNo());
                }
                sectionNoDetailMap.put(sectionNoDetailFor.getSectionNo(), sectionNoDetailFor);
            }

            //备注不为0，锁定三段单晶
            //需求修改，检验不自动锁定
            Boolean inspectionBatchLockingMark = GlobalSwitch.enable(GlobalSwitchNamespace.NAMESPACE_YB_CHECK, "inspectionBatchLockingMark", true);
            if (lockReason.length() != 0 && inspectionBatchLockingMark) {
                CrystalBatchOperation crystalBatchOperationNew = crystalBatchOperationService.findBySectionNo(ybInspectData.getSectionNo());
                if (null == crystalBatchOperationNew) {
                    crystalBatchOperationNew = new CrystalBatchOperation();
                    crystalBatchOperationNew.setSectionNo(ybInspectData.getSectionNo());
                    crystalBatchOperationNew.setCrystalNo(ybInspectData.getCrystalNo());
                    crystalBatchOperationNew.setPosition(EnumValuesFactory.WipStorageCode.圆棒检验.getValue());
                    crystalBatchOperationNew.setSiteStatus(1);
                    crystalBatchOperationNew.setConductiveType(ybInspectData.getConductiveType());
                    crystalBatchOperationNew.setSpecs(ybInspectData.getProductTypeSecond());
                    crystalBatchOperationNew.setDopant(ybInspectData.getDopant());
                    crystalBatchOperationNew.setAbbreviation(ybInspectData.getAbbreviation());
                    crystalBatchOperationNew.setLevelCode(ybInspectData.getLevelCode());
                    crystalBatchOperationNew.setProductLevel(ybInspectData.getProductLevel());
                    crystalBatchOperationNew.setRecipeName(ybInspectData.getFormulation());
                    CrystalMaterialRelation crystalMaterialRelation = crystalMaterialRelationService.findBySectionNo(ybInspectData.getSectionNo());
                    if (null != crystalMaterialRelation) {
                        crystalBatchOperationNew.setMaterialCode(crystalMaterialRelation.getMaterialCode());
                        if (null != crystalMaterialRelation.getMaterialModelId()) {
                            MaterialModel materialModel = materialModelService.get(crystalMaterialRelation.getMaterialModelId());
                            if (null != materialModel) {
                                crystalBatchOperationNew.setMaterialName(materialModel.getName());
                            }
                        }
                    }
                }
                crystalBatchOperationNew.setLockReason(lockReason.toString());
                crystalBatchOperationNew.setLockUser(BaseContextHandler.getUsername());
                crystalBatchOperationNew.setLockTime(new Date());
                crystalBatchOperationNew.setLockRemark(lockReason.toString());
                crystalBatchOperationNew.setStatus(EnumValuesFactory.BatchOperationStatus.LOCK_STATUS.getKey());
                crystalBatchOperationService.saveOrUpdate(crystalBatchOperationNew);

                //锁定第二段
                CrystalBatchOperation crystalBatchOperationSecond = crystalBatchOperationService.findBySectionNo(sectionNoSecond);
                if (null == crystalBatchOperationSecond) {
                    crystalBatchOperationSecond = new CrystalBatchOperation();
                    BeanUtil.copyProperties(crystalBatchOperationNew, crystalBatchOperationSecond, "id");
                    crystalBatchOperationSecond.setSectionNo(sectionNoSecond);
                } else {
                    crystalBatchOperationSecond.setLockReason(lockReason.toString());
                    crystalBatchOperationSecond.setLockUser(BaseContextHandler.getUsername());
                    crystalBatchOperationSecond.setLockTime(new Date());
                    crystalBatchOperationSecond.setLockRemark(lockReason.toString());
                    crystalBatchOperationSecond.setStatus(EnumValuesFactory.BatchOperationStatus.LOCK_STATUS.getKey());
                }
                crystalBatchOperationService.saveOrUpdate(crystalBatchOperationSecond);
                //锁定相反的另外一段
                CrystalBatchOperation lockOpposite = null;
                if (headFlag) {
                    lockOpposite = crystalBatchOperationService.findBySectionNo(sectionNoTail);
                } else if (tailFlag) {
                    lockOpposite = crystalBatchOperationService.findBySectionNo(sectionNoHead);
                }
                if (null == lockOpposite) {
                    lockOpposite = new CrystalBatchOperation();
                    BeanUtil.copyProperties(crystalBatchOperationNew, lockOpposite, "id");
                    if (headFlag) {
                        lockOpposite.setSectionNo(sectionNoTail);
                    } else if (tailFlag) {
                        lockOpposite.setSectionNo(sectionNoHead);
                    }
                } else {
                    lockOpposite.setLockReason(lockReason.toString());
                    lockOpposite.setLockUser(BaseContextHandler.getUsername());
                    lockOpposite.setLockTime(new Date());
                    lockOpposite.setLockRemark(lockReason.toString());
                    lockOpposite.setStatus(EnumValuesFactory.BatchOperationStatus.LOCK_STATUS.getKey());
                }
                crystalBatchOperationService.saveOrUpdate(lockOpposite);

            }
            List<YbInspectData> saveYbInspectDataList = new ArrayList<>();
            List<DataInspectLog> saveDataInspectLogList = new ArrayList<>();
            //不存在，直接创建
            if (null != automaticInspectMiddle) {
                if (!identificationTransferFlag) {
                    return;
                }
                /*if (headFlag) {
                    sectionNoList.add(sectionNoTail);
                } else if (tailFlag) {
                    sectionNoList.add(sectionNoHead);
                }*/

                //查询存在的单晶
                List<YbInspectData> ybInspectDataList = ybInspectDataService.findBySections(sectionNoList);
                Map<String, YbInspectData> execGrade = new HashMap<>();
                automaticInspectMiddle.setGmtUpdate(date);

                for (YbInspectData ybInspectDataFor : ybInspectDataList) {
                    //处理判断尾部是否存在
                    if (headFlag && (null != ybInspectDataFor.getOxygenCarbonMark() && ybInspectDataFor.getOxygenCarbonMark() == 2)) {
                        if (null != ybInspectDataFor.getMeanCarrierLifetimeA() && ybInspectDataFor.getMeanCarrierLifetimeA().compareTo(BigDecimal.ZERO) > 0) {
                            continue;
                        }
                    } else if (tailFlag && (null != ybInspectDataFor.getOxygenCarbonMark() && ybInspectDataFor.getOxygenCarbonMark() == 1)) {
                        if (null != ybInspectDataFor.getMeanCarrierLifetimeB() && ybInspectDataFor.getMeanCarrierLifetimeB().compareTo(BigDecimal.ZERO) > 0) {
                            continue;
                        }
                    } else {
                        if (null != ybInspectDataFor.getUpdateUser() && !StringUtils.equals("自动修改", ybInspectDataFor.getUpdateUser())) {
                            continue;
                        }
                    }

                    ybInspectDataFor.setUpdateTime(date);
                    if (StringUtils.isBlank(ybInspectDataFor.getUpdateUser())){
                        ybInspectDataFor.setUpdateUser("自动修改");
                    }
                    //剔除存在改监控级别的单晶
                    if (levelMonitoring.contains(ybInspectDataFor.getProductLevel())) {
                        continue;
                    }

                    if (headFlag) {
                        if (oxygenBackCuttingFlag) {
                            ybInspectDataFor.setOxygenContentHead(NumberUtil.Object2BigDecimal(defaultSample.getOxygenCenterHead(), null));
                        }
                        handleYbInspectDataheadOrTail(ybInspectData, ybInspectDataFor, true);
                    } else if (tailFlag) {
                        handleYbInspectDataheadOrTail(ybInspectData, ybInspectDataFor, false);
                    } else {
                        continue;
                    }
                    if (oxygenBackcutFlag) {
                        ybInspectDataFor.setOxygenContentHead(BigDecimal.ZERO);
                    }
                    if (backCarbonFlag) {
                        ybInspectDataFor.setCarbonContentTail(BigDecimal.ZERO);
                    }
                    execGrade.put(ybInspectDataFor.getSectionNo(), ybInspectDataFor);
                    this.saveOrUpdate(ybInspectDataFor);
                }
                if (execGrade.size() != 0) {
                    gradeService.execGrade(execGrade);
                }
            } else {
                //查询存在的单晶
                List<YbInspectData> ybInspectDataList = ybInspectDataService.findBySections(sectionNoList);
                BigDecimal weight = BigDecimal.ZERO;
                List<DictionaryItem> dictionaryItems = dictionaryItemService.findByThemeValueAndItemName(Constants.WEIGHT_RATIO, ybInspectData.getProductTypeSecond(), true);
                automaticInspectMiddle = new AutomaticInspectMiddle();
                automaticInspectMiddle.setCrystalNo(ybInspectData.getCrystalNo());
                automaticInspectMiddle.setGmtCreate(date);
                automaticInspectMiddle.setPieceNoHead(pieceNoHead);
                automaticInspectMiddle.setPieceNoTail(pieceNoTail);
                automaticInspectMiddle.setSectionNoHead(sectionNoHead);
                automaticInspectMiddle.setSectionNoTail(sectionNoTail);
                List<String> hasSectionNoList = new ArrayList<>();
                for (YbInspectData ybInspectData1 : ybInspectDataList) {
                    hasSectionNoList.add(ybInspectData1.getSectionNo());
                }
                for (String sectionNo : sectionNoList) {
                    //检验存在，不创建中间段
                    if (hasSectionNoList.contains(sectionNo)) {
                        continue;
                    }
                    YbInspectData ybInspectDataNew = new YbInspectData();
                    if (headFlag) {
                        if (identificationTransferFlag) {
                            BeanUtil.copyProperties(ybInspectData, ybInspectDataNew, "id", "productLevel", "checkReback",
                                    "reCheckType", "reduceCrystalLength", "materialLoss", "meanResistivityB", "meanCarrierLifetimeB", "resistivityBOne",
                                    "resistivityBTwo", "resistivityBThree", "carrierLifetimeBOne", "carrierLifetimeBTwo", "carrierLifetimeBThree");
                        } else {
                            BeanUtil.copyProperties(ybInspectData, ybInspectDataNew, "id", "productLevel", "checkReback",
                                    "reCheckType", "reduceCrystalLength", "materialLoss", "meanResistivityB", "meanCarrierLifetimeB", "resistivityBOne",
                                    "resistivityBTwo", "resistivityBThree", "carrierLifetimeBOne", "carrierLifetimeBTwo", "carrierLifetimeBThree",
                                    "meanResistivityA", "meanCarrierLifetimeA", "resistivityAOne", "resistivityATwo", "resistivityAThree",
                                    "carrierLifetimeAOne", "carrierLifetimeATwo", "carrierLifetimeAThree");
                        }
                    } else {
                        if (identificationTransferFlag) {
                            BeanUtil.copyProperties(ybInspectData, ybInspectDataNew, "id", "productLevel", "checkReback",
                                    "reCheckType", "reduceCrystalLength", "materialLoss", "meanResistivityA", "meanCarrierLifetimeA", "resistivityAOne",
                                    "resistivityATwo", "resistivityAThree", "carrierLifetimeAOne", "carrierLifetimeATwo", "carrierLifetimeAThree");
                        } else {
                            BeanUtil.copyProperties(ybInspectData, ybInspectDataNew, "id", "productLevel", "checkReback",
                                    "reCheckType", "reduceCrystalLength", "materialLoss", "meanResistivityA", "meanCarrierLifetimeA", "resistivityAOne",
                                    "resistivityATwo", "resistivityAThree", "carrierLifetimeAOne", "carrierLifetimeATwo", "carrierLifetimeAThree",
                                    "meanResistivityB", "meanCarrierLifetimeB", "resistivityBOne", "resistivityBTwo", "resistivityBThree", "carrierLifetimeBOne",
                                    "carrierLifetimeBTwo", "carrierLifetimeBThree");
                        }
                    }
                    //处理字段数据
                    ybInspectDataNew.setId(null);
                    if (oxygenBackcutFlag) {
                        ybInspectDataNew.setOxygenContentHead(BigDecimal.ZERO);
                    }
                    if (backCarbonFlag) {
                        ybInspectDataNew.setCarbonContentTail(BigDecimal.ZERO);
                    }
                    ybInspectDataNew.setSectionNo(sectionNo);
                    SectionNoDetail sectionNoDetailGet = sectionNoDetailMap.get(sectionNo);
                    ybInspectDataNew.setActualLength(sectionNoDetailGet.getLength());
                    if (CollectionUtils.isNotEmpty(dictionaryItems)) {
                        BigDecimal weightLossCoefficient = NumberUtil.Object2BigDecimal(dictionaryItems.get(0).getValue());
                        if (null != weightLossCoefficient && weightLossCoefficient.compareTo(BigDecimal.ONE) > 0) {
                            weight = sectionNoDetailGet.getLength().divide(weightLossCoefficient, 3, RoundingMode.HALF_UP);
                        }
                    }
                    ybInspectDataNew.setTheoryWeight(weight);
                    ybInspectDataNew.setActualWeight(weight);
                    ybInspectDataNew.setPiecewiseNum(sectionNoDetailGet.getSectionPosiotion());
                    ybInspectDataNew.setReCheckType("0");
                    ybInspectDataNew.setCheckoutName("一次检验");
                    ybInspectDataNew.setSticksCount(1);

                    if (oxygenBackCuttingFlag) {
                        ybInspectDataNew.setOxygenContentHead(NumberUtil.Object2BigDecimal(defaultSample.getOxygenCenterHead(), null));
                    }
                    if (sectionNoDetailGet.getOxygenCarbonMark() == 1) {
                        ybInspectDataNew.setHeadTailRecognition("T段");
                    } else if (sectionNoDetailGet.getOxygenCarbonMark() == 2) {
                        ybInspectDataNew.setHeadTailRecognition("W段");
                    } else {
                        ybInspectDataNew.setHeadTailRecognition("Z段");
                    }
                    ybInspectDataNew.setLevel(null);
                    ybInspectDataNew.setSectionType(null);

                    ybInspectDataNew.setOxygenCarbonMark(sectionNoDetailGet.getOxygenCarbonMark());
                    saveYbInspectDataList.add(ybInspectDataNew);
                    DataInspectLog dataInspectLog = new DataInspectLog();
                    this.dataToLog(ybInspectDataNew, dataInspectLog);
                    dataInspectLog.setOperateType(0);
                    dataInspectLog.setRemarks("新增");
                    dataInspectLog.setOperateTime(date);
                    dataInspectLog.setOperator(username);
                    saveDataInspectLogList.add(dataInspectLog);
                    //过站操作
                    wipStorageService.inStation(sectionNo, null, false);
                }
            }
            //保存自动数据
            automaticInspectMiddleService.saveOrUpdate(automaticInspectMiddle);
            if (saveYbInspectDataList.size() != 0) {
                this.saveAll(saveYbInspectDataList);
            }
            if (saveDataInspectLogList.size() != 0) {
                dataInspectLogService.saveAll(saveDataInspectLogList);
            }
        }
    }

    private void handleYbInspectDataABInfo(YbInspectData ybInspectData, YbInspectData bySectionNoNew, Boolean headFlag) {
        if (null == ybInspectData || null == bySectionNoNew) {
            return;
        }
        if (headFlag) {
            if (null != bySectionNoNew.getMeanCarrierLifetimeA() && bySectionNoNew.getMeanCarrierLifetimeA().compareTo(BigDecimal.ZERO) == 0) {
                bySectionNoNew.setMeanCarrierLifetimeA(ybInspectData.getMeanCarrierLifetimeA());
            }
            if (null != bySectionNoNew.getCarrierLifetimeAOne() && bySectionNoNew.getCarrierLifetimeAOne().compareTo(BigDecimal.ZERO) == 0) {
                bySectionNoNew.setCarrierLifetimeAOne(ybInspectData.getCarrierLifetimeAOne());
            }
            if (null != bySectionNoNew.getCarrierLifetimeATwo() && bySectionNoNew.getCarrierLifetimeATwo().compareTo(BigDecimal.ZERO) == 0) {
                bySectionNoNew.setCarrierLifetimeATwo(ybInspectData.getCarrierLifetimeATwo());
            }
            if (null != bySectionNoNew.getCarrierLifetimeAThree() && bySectionNoNew.getCarrierLifetimeAThree().compareTo(BigDecimal.ZERO) == 0) {
                bySectionNoNew.setCarrierLifetimeAThree(ybInspectData.getCarrierLifetimeAThree());
            }
            if (null != bySectionNoNew.getMeanResistivityA() && bySectionNoNew.getMeanResistivityA().compareTo(BigDecimal.ZERO) == 0) {
                bySectionNoNew.setMeanResistivityA(ybInspectData.getMeanResistivityA());
            }
            if (null != bySectionNoNew.getResistivityAOne() && bySectionNoNew.getResistivityAOne().compareTo(BigDecimal.ZERO) == 0) {
                bySectionNoNew.setResistivityAOne(ybInspectData.getResistivityAOne());
            }
            if (null != bySectionNoNew.getResistivityATwo() && bySectionNoNew.getResistivityATwo().compareTo(BigDecimal.ZERO) == 0) {
                bySectionNoNew.setResistivityATwo(ybInspectData.getResistivityATwo());
            }
            if (null != bySectionNoNew.getResistivityAThree() && bySectionNoNew.getResistivityAThree().compareTo(BigDecimal.ZERO) == 0) {
                bySectionNoNew.setResistivityAThree(ybInspectData.getResistivityAThree());
            }
        } else {
            if (null != bySectionNoNew.getMeanCarrierLifetimeB() && bySectionNoNew.getMeanCarrierLifetimeB().compareTo(BigDecimal.ZERO) == 0) {
                bySectionNoNew.setMeanCarrierLifetimeB(ybInspectData.getMeanCarrierLifetimeB());
            }
            if (null != bySectionNoNew.getCarrierLifetimeBOne() && bySectionNoNew.getCarrierLifetimeBOne().compareTo(BigDecimal.ZERO) == 0) {
                bySectionNoNew.setCarrierLifetimeBOne(ybInspectData.getCarrierLifetimeBOne());
            }
            if (null != bySectionNoNew.getCarrierLifetimeBTwo() && bySectionNoNew.getCarrierLifetimeBTwo().compareTo(BigDecimal.ZERO) == 0) {
                bySectionNoNew.setCarrierLifetimeBTwo(ybInspectData.getCarrierLifetimeBTwo());
            }
            if (null != bySectionNoNew.getCarrierLifetimeBThree() && bySectionNoNew.getCarrierLifetimeBThree().compareTo(BigDecimal.ZERO) == 0) {
                bySectionNoNew.setCarrierLifetimeBThree(ybInspectData.getCarrierLifetimeBThree());
            }
            if (null != bySectionNoNew.getMeanResistivityB() && bySectionNoNew.getMeanResistivityB().compareTo(BigDecimal.ZERO) == 0) {
                bySectionNoNew.setMeanResistivityB(ybInspectData.getMeanResistivityB());
            }
            if (null != bySectionNoNew.getResistivityBOne() && bySectionNoNew.getResistivityBOne().compareTo(BigDecimal.ZERO) == 0) {
                bySectionNoNew.setResistivityBOne(ybInspectData.getResistivityBOne());
            }
            if (null != bySectionNoNew.getResistivityBTwo() && bySectionNoNew.getResistivityBTwo().compareTo(BigDecimal.ZERO) == 0) {
                bySectionNoNew.setResistivityBTwo(ybInspectData.getResistivityBTwo());
            }
            if (null != bySectionNoNew.getResistivityBThree() && bySectionNoNew.getResistivityBThree().compareTo(BigDecimal.ZERO) == 0) {
                bySectionNoNew.setResistivityBThree(ybInspectData.getResistivityBThree());
            }
        }
    }

    private void handleYbInspectDataheadOrTail(YbInspectData ybInspectData, YbInspectData ybInspectDataNew, Boolean headFlag) {
        if (null == ybInspectData || null == ybInspectDataNew) {
            return;
        }
        if (headFlag) {
            ybInspectDataNew.setMeanCarrierLifetimeA(ybInspectData.getMeanCarrierLifetimeA());
            ybInspectDataNew.setCarrierLifetimeAOne(ybInspectData.getCarrierLifetimeAOne());
            ybInspectDataNew.setCarrierLifetimeATwo(ybInspectData.getCarrierLifetimeATwo());
            ybInspectDataNew.setCarrierLifetimeAThree(ybInspectData.getCarrierLifetimeAThree());
            ybInspectDataNew.setMeanResistivityA(ybInspectData.getMeanResistivityA());
            ybInspectDataNew.setResistivityAOne(ybInspectData.getResistivityAOne());
            ybInspectDataNew.setResistivityATwo(ybInspectData.getResistivityATwo());
            ybInspectDataNew.setResistivityAThree(ybInspectData.getResistivityAThree());
            ybInspectDataNew.setTResistivity(ybInspectData.getMeanResistivityA());
            ybInspectDataNew.setTRadialCentre(ybInspectData.getTRadialCentre());
            ybInspectDataNew.setTRadialEdge1(ybInspectData.getTRadialEdge1());
            ybInspectDataNew.setTCentreLife(ybInspectData.getTCentreLife());
            ybInspectDataNew.setTLifeEdge1(ybInspectData.getTLifeEdge1());

        } else {
            ybInspectDataNew.setMeanCarrierLifetimeB(ybInspectData.getMeanCarrierLifetimeB());
            ybInspectDataNew.setCarrierLifetimeBOne(ybInspectData.getCarrierLifetimeBOne());
            ybInspectDataNew.setCarrierLifetimeBTwo(ybInspectData.getCarrierLifetimeBTwo());
            ybInspectDataNew.setCarrierLifetimeBThree(ybInspectData.getCarrierLifetimeBThree());
            ybInspectDataNew.setMeanResistivityB(ybInspectData.getMeanResistivityB());
            ybInspectDataNew.setResistivityBOne(ybInspectData.getResistivityBOne());
            ybInspectDataNew.setResistivityBTwo(ybInspectData.getResistivityBTwo());
            ybInspectDataNew.setResistivityBThree(ybInspectData.getResistivityBThree());
            ybInspectDataNew.setWResistivity(ybInspectData.getMeanResistivityB());
            ybInspectDataNew.setWRadialCentre(ybInspectData.getWRadialCentre());
            ybInspectDataNew.setWRadialEdge1(ybInspectData.getWRadialEdge1());
            ybInspectDataNew.setWCentreLife(ybInspectData.getWCentreLife());
            ybInspectDataNew.setWLifeEdge1(ybInspectData.getWLifeEdge1());
        }

        //更新缺失字段处理
        if (StringUtils.isBlank(ybInspectDataNew.getMaterialCode())) {
            ybInspectDataNew.setMaterialCode(ybInspectData.getMaterialCode());
        }
        if (StringUtils.isBlank(ybInspectDataNew.getOrderNo())) {
            ybInspectDataNew.setOrderNo(ybInspectData.getOrderNo());
        }
        if (StringUtils.isBlank(ybInspectDataNew.getWorkOrderNo())) {
            ybInspectDataNew.setWorkOrderNo(ybInspectData.getOrderNo());
        }

        if (StringUtils.isBlank(ybInspectDataNew.getWorkOrderType())) {
            ybInspectDataNew.setWorkOrderType(ybInspectData.getWorkOrderType());
        }
        if (StringUtils.isBlank(ybInspectDataNew.getArea())) {
            ybInspectDataNew.setArea(ybInspectData.getArea());
        }
        if (StringUtils.isBlank(ybInspectDataNew.getFactory())) {
            ybInspectDataNew.setFactory(ybInspectData.getFactory());
        }
        if (StringUtils.isBlank(ybInspectDataNew.getAbbreviation())) {
            ybInspectDataNew.setAbbreviation(ybInspectData.getAbbreviation());
        }
        if (null == ybInspectDataNew.getTheoryWeight() || ybInspectDataNew.getTheoryWeight().compareTo(BigDecimal.ZERO) <= 0) {
            List<DictionaryItem> dictionaryItems = dictionaryItemService.findByThemeValueAndItemName(Constants.WEIGHT_RATIO, ybInspectDataNew.getProductTypeSecond(), true);
            if (CollectionUtils.isNotEmpty(dictionaryItems)) {
                BigDecimal weightLossCoefficient = NumberUtil.Object2BigDecimal(dictionaryItems.get(0).getValue());
                if (null != weightLossCoefficient && weightLossCoefficient.compareTo(BigDecimal.ONE) > 0) {
                    ybInspectDataNew.setTheoryWeight(ybInspectDataNew.getActualLength().divide(weightLossCoefficient, 3,  RoundingMode.HALF_UP));
                }
            }
        }


        if (null != ybInspectDataNew.getPiecewiseNum() && ybInspectDataNew.getPiecewiseNum() != 2) {
            if (StringUtils.isNotBlank(ybInspectData.getMaterialCode())) {
                ybInspectDataNew.setMaterialCode(ybInspectData.getMaterialCode());
            }
            this.handleOxygenContentAndCarbonContent(ybInspectDataNew, ybInspectData, headFlag);
        }
    }


    private YbInspectData handleYbInspectData(YbInspectData ybInspectData, String sectionNo, SectionNoDetail sectionNoDetail, Boolean headFlag) {
        if (null == ybInspectData || null == sectionNoDetail || StringUtils.isBlank(sectionNo)) {
            return null;
        }
        YbInspectData ybInspectDataNew = new YbInspectData();
        if (headFlag) {
            BeanUtil.copyProperties(ybInspectData, ybInspectDataNew, "id", "productLevel", "checkReback",
                    "reCheckType", "reduceCrystalLength", "materialLoss", "meanResistivityB", "meanCarrierLifetimeB", "resistivityBOne",
                    "resistivityBTwo", "resistivityBThree", "carrierLifetimeBOne", "carrierLifetimeBTwo", "carrierLifetimeBThree");
        } else {
            BeanUtil.copyProperties(ybInspectData, ybInspectDataNew, "id", "productLevel", "checkReback",
                    "reCheckType", "reduceCrystalLength", "materialLoss", "meanResistivityA", "meanCarrierLifetimeA", "resistivityAOne",
                    "resistivityATwo", "resistivityAThree", "carrierLifetimeAOne", "carrierLifetimeATwo", "carrierLifetimeAThree");
        }
        //处理字段数据
        ybInspectDataNew.setId(null);
        ybInspectDataNew.setSectionNo(sectionNo);
        ybInspectDataNew.setActualLength(sectionNoDetail.getLength());
        if (StringUtils.isNotBlank(ybInspectData.getMaterialCode())) {
            ybInspectDataNew.setMaterialCode(ybInspectData.getMaterialCode());
        }
        BigDecimal weight = BigDecimal.ZERO;
        List<DictionaryItem> dictionaryItems = dictionaryItemService.findByThemeValueAndItemName(Constants.WEIGHT_RATIO, sectionNoDetail.getSpecs(), true);
        if (CollectionUtils.isNotEmpty(dictionaryItems)) {
            BigDecimal weightLossCoefficient = NumberUtil.Object2BigDecimal(dictionaryItems.get(0).getValue());
            if (null != weightLossCoefficient && weightLossCoefficient.compareTo(BigDecimal.ONE) > 0) {
                weight = sectionNoDetail.getLength().divide(weightLossCoefficient, 3, RoundingMode.HALF_UP);
            }
        }
        ybInspectDataNew.setTheoryWeight(weight);
        ybInspectDataNew.setActualWeight(weight);
        ybInspectDataNew.setPiecewiseNum(sectionNoDetail.getSectionPosiotion());
        ybInspectDataNew.setReCheckType("0");
        ybInspectDataNew.setCheckoutName("一次检验");
        ybInspectDataNew.setSticksCount(1);
        ybInspectDataNew.setHeadTailRecognition("Z段");
        ybInspectDataNew.setLevel(null);
        ybInspectDataNew.setSectionType(null);
        if (null != sectionNoDetail.getSectionPosiotion() && sectionNoDetail.getSectionPosiotion() != 2) {
            this.handleOxygenContentAndCarbonContent(ybInspectDataNew, ybInspectData, headFlag);
        }
        return ybInspectDataNew;
    }

    private void handleOxygenContentAndCarbonContent(YbInspectData ybInspectDataNew, YbInspectData ybInspectData, Boolean headFlag) {
        if (null == ybInspectDataNew) {
            return;
        }
        Boolean gradeTypeFlag = StringUtils.equals("取片", ybInspectData.getGradeType());
        //T氧含量中心
        if (null == ybInspectDataNew.getOxygenContentHead()) {
            ybInspectDataNew.setOxygenContentHead(BigDecimal.ZERO);
        } else if (headFlag) {
            if (gradeTypeFlag) {
                ybInspectDataNew.setOxygenContentHead(BigDecimal.ZERO);
            }
        }
        //T碳含量中心
        if (null == ybInspectDataNew.getCarbonContentHead()) {
            ybInspectDataNew.setCarbonContentHead(BigDecimal.ZERO);
        } else if (headFlag) {
            if (gradeTypeFlag) {
                ybInspectDataNew.setCarbonContentHead(BigDecimal.ZERO);
            }
        }
        //W氧含量中心
        if (null == ybInspectDataNew.getOxygenContentTail()) {
            ybInspectDataNew.setOxygenContentTail(BigDecimal.ZERO);
        } else if (!headFlag) {
            if (gradeTypeFlag) {
                ybInspectDataNew.setOxygenContentTail(BigDecimal.ZERO);
            }
        }
        //W碳含量中心
        if (null == ybInspectDataNew.getCarbonContentTail()) {
            ybInspectDataNew.setCarbonContentTail(BigDecimal.ZERO);
        } else if (!headFlag) {
            if (gradeTypeFlag) {
                ybInspectDataNew.setCarbonContentTail(BigDecimal.ZERO);
            }
        }
    }

    private String handlePieceNo(String sectionNo, Boolean headFlag) {
        if (StringUtils.isNotBlank(sectionNo)) {
            SectionNoDetail sectionNoDetail = sectionNoDetailService.findBySectionNo(sectionNo);
            if (null != sectionNoDetail) {
                if (headFlag) {
                    return sectionNoDetail.getPieceNoHead();
                } else {
                    return sectionNoDetail.getPieceNoEnd();
                }
            }
        }

        return null;
    }

    @Override
    public void saveDataInspectLog(YbInspectData ybInspectDataOld) {

        DataInspectLog dataInspectLog = new DataInspectLog();

        dataToLog(ybInspectDataOld, dataInspectLog);

        if (ybInspectDataOld.getId() != null) {
            dataInspectLog.setOperateType(1);
            dataInspectLog.setRemarks("修改");
        } else {
            dataInspectLog.setOperateType(0);
            dataInspectLog.setRemarks("新增");
        }
        dataInspectLog.setOperateTime(new Date());
        dataInspectLog.setOperator(BaseContextHandler.getUsername());

        dataInspectLogService.saveOrUpdate(dataInspectLog);
    }

    @Override
    public String getResistanceLevel(BigDecimal tRadialCentre) {
        if (tRadialCentre == null) {
            return "-1";
        }
        //电阻档位判断
        List<DictionaryItem> resistanceLevel = dictionaryItemService.findByThemeValueAndEnableOrderByPriority("resistanceLevel", true);
        String resLevel = null;
        int i = 0;
        for (DictionaryItem dictionaryItem : resistanceLevel) {
            i++;
            String value = dictionaryItem.getValue();
            String[] split = value.split("-");
            if (split.length > 1) {
                if (tRadialCentre.compareTo(new BigDecimal(split[0])) > 0 && tRadialCentre.compareTo(new BigDecimal(split[1])) <= 0) {
                    resLevel = dictionaryItem.getName();
                    break;
                }
            } else if (i == 1 && tRadialCentre.compareTo(new BigDecimal(dictionaryItem.getValue())) <= 0) {
                resLevel = dictionaryItem.getName();
                break;
            } else if (tRadialCentre.compareTo(new BigDecimal(dictionaryItem.getValue())) > 0) {
                resLevel = dictionaryItem.getName();
                break;
            }
        }
        return resLevel;
    }

    @Override
    public List<YbInspectData> findByLotNoAndAgainNum(String lotNo, Integer againNum) {
        return dao.findByLotNoAndAgainNum(lotNo, againNum);
    }

    @Override
    public void verificationManagement(Map<String, Object> bySectionNoMap) {
        if (null == bySectionNoMap || bySectionNoMap.size() == 0) {
            return;
        }
        String sectionNo = String.valueOf(bySectionNoMap.get("section_no"));
        if (null == bySectionNoMap.get("product_type_second")) {
            return;
        }
        String productTypeSecond = String.valueOf(bySectionNoMap.get("product_type_second"));
        if (null == bySectionNoMap.get("dopant")) {
            return;
        }
        String deviceNo = "";
        String lotNo = "";
        Integer againNum = 0;

        SectionNoDetail sectionNoDetailHead = sectionNoDetailService.findBySectionNo(sectionNo);
        LongCrystal byCrystalNo = null;
        if (null != sectionNoDetailHead && StringUtils.isNotBlank(sectionNoDetailHead.getCrystalNo())) {
            byCrystalNo = longCrystalService.findByCrystalNo(sectionNoDetailHead.getCrystalNo());
            deviceNo = byCrystalNo.getEquipmentCode();
            lotNo = byCrystalNo.getLotNo();
            againNum = byCrystalNo.getAgainNum();
        }
        String dopant = String.valueOf(bySectionNoMap.get("dopant"));

        List<WarningRuleConfiguration> warningRuleConfigurationList = warningRuleConfigurationService.findByDopantAndSpecificationAndStatusAndRestrictedReporting(dopant, productTypeSecond, 1, null);

        List<FieldPool> fieldPools = fieldPoolService.findByRegion(EnumValuesGrade.Region.圆棒.getKey());
        Map<String, FieldPool> fieldPoolMap = new HashMap<>();
        for (FieldPool fieldPool : fieldPools) {
            fieldPoolMap.put(fieldPool.getName(), fieldPool);
        }
        Date date = new Date();

        if (CollectionUtils.isNotEmpty(warningRuleConfigurationList)) {
            for (WarningRuleConfiguration warningRuleConfiguration : warningRuleConfigurationList) {
                if (StringUtils.isNotBlank(warningRuleConfiguration.getConditionsShow())) {
                    List<Map<String, String>> listConditions = JSON.parseObject(warningRuleConfiguration.getConditionsShow(), List.class);
                    StringBuilder sqlStr = new StringBuilder();
                    sqlStr.append("SELECT ");
                    StringBuilder actualValue = new StringBuilder();
                    for (Map<String, String> condition : listConditions) {
                        String[] ruleTextArr = condition.get("text").split(" ");
                        for (String text : ruleTextArr) {
                            if (text.startsWith("@")) {
                                String replaceKey = text.replace("@", "").trim();
                                if (!fieldPoolMap.containsKey(replaceKey)) {
                                    return;
                                }
                                FieldPool fieldPool = fieldPoolMap.get(replaceKey);
                                Object field = bySectionNoMap.get(fieldPool.getCode());
                                actualValue.append(fieldPool.getName()).append(":").append(field).append("; ");
                                if (null == field) {
                                    return;
                                }
                                sqlStr.append(" ").append(field).append(" ");
                            } else {
                                sqlStr.append(" ").append(text).append(" ");
                            }
                        }
                        sqlStr.append(" AND ");
                    }
                    String sql = sqlStr.substring(0, sqlStr.length() - 5);
                    Map<String, Object> result = this.handCheck(sql);
                    log.info("执行SQL：{}",sql);

                    if (null != result) {
                        for (Map.Entry<String, Object> entry : result.entrySet()) {
                            if (null != entry.getValue()) {
                                Integer value = NumberUtil.Object2Integer(entry.getValue(), null);
                                if (value == 1 && warningRuleConfiguration.getManageStatus() == 1) {
                                    EarlyWarningManagement earlyWarningManagement = new EarlyWarningManagement();
                                    earlyWarningManagement.setConditions(warningRuleConfiguration.getConditions().replace("~", ""));
                                    earlyWarningManagement.setSectionNo(sectionNo);
                                    earlyWarningManagement.setName(warningRuleConfiguration.getName());
                                    earlyWarningManagement.setActualValue(actualValue.toString());
                                    earlyWarningManagement.setDeviceNo(deviceNo);
                                    earlyWarningManagement.setGmtCreate(date);
                                    earlyWarningManagement.setStatus(0);
                                    earlyWarningManagement.setLotNo(lotNo);
                                    earlyWarningManagement.setAgainNum(againNum);
                                    earlyWarningManagement.setUserCreate(BaseContextHandler.getUsername());
                                    earlyWarningManagementService.saveOrUpdate(earlyWarningManagement);

                                    //下发晶彩数据
                                    try {
                                        this.pushEarlyWarningManagement(earlyWarningManagement,bySectionNoMap,sectionNoDetailHead,byCrystalNo);
                                    }catch (Exception e){
                                        log.info(e.getMessage());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

    }

    private void pushEarlyWarningManagement(EarlyWarningManagement earlyWarningManagement,Map<String, Object> bySectionNoMap,SectionNoDetail sectionNoDetailHead,LongCrystal longCrystal){
        if(null == bySectionNoMap || null == bySectionNoMap.get("head_tail_recognition")){
            return;
        }
        String headTailRecognition = String.valueOf(bySectionNoMap.get("head_tail_recognition"));
        if (StringUtils.isBlank(headTailRecognition) || StringUtils.equals("W段",headTailRecognition) || StringUtils.equals("Z段",headTailRecognition)){
            return;
        }
        String groupName = "品质预警";
        String source = "品质预警";
        StringBuffer content = new StringBuffer();
        Equipment equipment = equipmentService.findByCode(earlyWarningManagement.getDeviceNo());
        content.append(". [MES推送]品质预警:").append("\n");
        content.append(". 片区 ");
        if (null != equipment){
            if (null != equipment.getFactoryModel()){
                content.append(equipment.getFactoryModel().getName()).append("\n");
            }
        }
        BigDecimal carrierLifetimeA = null;
        if (null != bySectionNoMap.get("mean_carrier_lifetime_a")){
            carrierLifetimeA = (BigDecimal) bySectionNoMap.get("mean_carrier_lifetime_a");
        }
        if (null == carrierLifetimeA || carrierLifetimeA.compareTo(BigDecimal.ZERO) == 0){
            return;
        }
        BigDecimal meanResistivityA = null;
        if (null != bySectionNoMap.get("mean_resistivity_a")){
            meanResistivityA = (BigDecimal) bySectionNoMap.get("mean_resistivity_a");
        }
        BigDecimal oxygenContentHead = null;
        if (null != bySectionNoMap.get("oxygen_content_head")){
            oxygenContentHead = (BigDecimal) bySectionNoMap.get("oxygen_content_head");
        }
        BigDecimal carbonContentTail = null;
        if (null != bySectionNoMap.get("carbon_content_tail")){
            carbonContentTail = (BigDecimal) bySectionNoMap.get("carbon_content_tail");
        }
        content.append(".炉次号 ").append(earlyWarningManagement.getLotNo()).append("\n");
        content.append(".").append(earlyWarningManagement.getName()).append("\n");
        content.append(".").append(earlyWarningManagement.getSectionNo()).append("\n");
        content.append(".头少子 ").append(carrierLifetimeA).append(";  电阻 ").append(meanResistivityA).append("\n");
        content.append(".氧含量 ").append(oxygenContentHead).append(";  碳含量 ").append(carbonContentTail).append("\n");
        if (null != sectionNoDetailHead){
            ProductionPaintingLine byCrystalNo = productionPaintingLineService.findByCrystalNo(sectionNoDetailHead.getCrystalNo());
            if (null != byCrystalNo){
                content.append(".总长度 ").append(byCrystalNo.getSubmitLength()).append("\n");
                content.append(".可用长度 ").append(byCrystalNo.getValidLength()).append("\n");
            }
            CrystalMaterialRelation crystalMaterialRelation = crystalMaterialRelationService.findBySectionNo(sectionNoDetailHead.getCrystalNo());
            if (null != crystalMaterialRelation){
                content.append(".截断机 ").append(crystalMaterialRelation.getDeviceNo()).append("\n");
                content.append(".用料批次 ").append(crystalMaterialRelation.getBatchNo()).append("\n");
            }
        }

        content.append(".比值异常 ").append("\n");
        content.append(".").append(earlyWarningManagement.getSectionNo()).append("\n");
        content.append(".头少子 ").append(carrierLifetimeA).append(";  电阻 ").append(meanResistivityA).append("\n");
        content.append(".氧含量 ").append(oxygenContentHead).append(";  碳含量 ").append(carbonContentTail).append("\n");
        //获取设备的上一炉次
        NumberFormat percent = NumberFormat.getPercentInstance();
        percent.setMaximumFractionDigits(2);
        if (null != longCrystal){
            LongCrystal deviceNoAndCreateTime = longCrystalService.findDeviceNoAndCreateTime(longCrystal.getEquipmentCode(), longCrystal.getGmtCreate(),EnumValuesFactory.CrystalStatus.已划线.getKey());
            if (null != deviceNoAndCreateTime){
                //获取检验数据
                YbInspectData ybInspectDataHead = this.findByCrystalNoAndOxygenCarbonMark(deviceNoAndCreateTime.getCrystalNo(), EnumValuesFactory.OxygenCarbonMarkStatus.HEAD_DEPEND.getKey());
                if (null != ybInspectDataHead){
                    content.append(".上一棒：").append(ybInspectDataHead.getSectionNo()).append("\n");
                    content.append(".头少子 ").append(ybInspectDataHead.getMeanCarrierLifetimeA()).append(";  电阻 ").append(ybInspectDataHead.getMeanResistivityA()).append("\n");
                    content.append(".氧含量 ").append(ybInspectDataHead.getOxygenContentHead()).append(";  碳含量 ").append(ybInspectDataHead.getCarbonContentTail()).append("\n");
                    content.append(".下降幅度：");
                    if (null != carrierLifetimeA && null != ybInspectDataHead.getMeanCarrierLifetimeA() && ybInspectDataHead.getMeanCarrierLifetimeA().compareTo(BigDecimal.ZERO) != 0){
                        BigDecimal divideLife = ybInspectDataHead.getMeanCarrierLifetimeA().subtract(carrierLifetimeA).divide(ybInspectDataHead.getMeanCarrierLifetimeA(), 4, BigDecimal.ROUND_HALF_UP);
                       /* if (divideLife.abs().compareTo(new BigDecimal(6)) < 0){
                            return;
                        }*/
                        content.append("头少子 ").append(percent.format(divideLife));
                    }
                    if (null != meanResistivityA && null != ybInspectDataHead.getMeanResistivityA() && ybInspectDataHead.getMeanResistivityA().compareTo(BigDecimal.ZERO) != 0){
                        BigDecimal divideResistivity = ybInspectDataHead.getMeanResistivityA().subtract(meanResistivityA).divide(ybInspectDataHead.getMeanResistivityA(), 4, BigDecimal.ROUND_HALF_UP);
                        content.append("; 电阻 ").append(percent.format(divideResistivity));
                    }
                    if (null != oxygenContentHead && null != ybInspectDataHead.getOxygenContentHead() && ybInspectDataHead.getOxygenContentHead().compareTo(BigDecimal.ZERO) != 0){
                        BigDecimal divideOxygen = ybInspectDataHead.getOxygenContentHead().subtract(oxygenContentHead).divide(ybInspectDataHead.getOxygenContentHead(), 4, BigDecimal.ROUND_HALF_UP);
                        content.append("; 氧含量 ").append(percent.format(divideOxygen));
                    }
                    if (null != carbonContentTail && null != ybInspectDataHead.getCarbonContentTail() && ybInspectDataHead.getCarbonContentTail().compareTo(BigDecimal.ZERO) != 0){
                        BigDecimal divideCarbon = ybInspectDataHead.getCarbonContentTail().subtract(carbonContentTail).divide(ybInspectDataHead.getCarbonContentTail(), 4, BigDecimal.ROUND_HALF_UP);
                        content.append("; 碳含量 ").append(percent.format(divideCarbon));
                    }
                }else {
                    YbInspectData ybInspectDataTail= this.findByCrystalNoAndOxygenCarbonMark(deviceNoAndCreateTime.getCrystalNo(), EnumValuesFactory.OxygenCarbonMarkStatus.TAIL_DEPEND.getKey());
                    if (null != ybInspectDataTail){
                        content.append(".上一棒：").append(ybInspectDataTail.getSectionNo()).append("\n");
                        content.append(".头少子 ").append(ybInspectDataTail.getMeanCarrierLifetimeA()).append(";  电阻 ").append(ybInspectDataTail.getMeanResistivityA()).append("\n");
                        content.append(".氧含量 ").append(ybInspectDataTail.getOxygenContentHead()).append(";  碳含量 ").append(ybInspectDataTail.getCarbonContentTail()).append("\n");
                        content.append(".下降幅度：");
                        if (null != carrierLifetimeA && null != ybInspectDataTail.getMeanCarrierLifetimeA() && ybInspectDataTail.getMeanCarrierLifetimeA().compareTo(BigDecimal.ZERO) != 0){
                            BigDecimal divideLife = ybInspectDataTail.getMeanCarrierLifetimeA().subtract(carrierLifetimeA).divide(ybInspectDataTail.getMeanCarrierLifetimeA(), 4, BigDecimal.ROUND_HALF_UP);
                            if (divideLife.abs().compareTo(new BigDecimal(6)) < 0){
                                return;
                            }
                            content.append("头少子 ").append(percent.format(divideLife));
                        }
                        if (null != meanResistivityA && null != ybInspectDataTail.getMeanResistivityA() && ybInspectDataTail.getMeanResistivityA().compareTo(BigDecimal.ZERO) != 0){
                            BigDecimal divideResistivity = ybInspectDataTail.getMeanResistivityA().subtract(meanResistivityA).divide(ybInspectDataTail.getMeanResistivityA(), 4, BigDecimal.ROUND_HALF_UP);
                            content.append("; 电阻 ").append(percent.format(divideResistivity));
                        }
                        if (null != oxygenContentHead && null != ybInspectDataTail.getOxygenContentHead() && ybInspectDataTail.getOxygenContentHead().compareTo(BigDecimal.ZERO) != 0){
                            BigDecimal divideOxygen = ybInspectDataTail.getOxygenContentHead().subtract(oxygenContentHead).divide(ybInspectDataTail.getOxygenContentHead(), 4, BigDecimal.ROUND_HALF_UP);
                            content.append("; 氧含量 ").append(percent.format(divideOxygen));
                        }
                        if (null != carbonContentTail && null != ybInspectDataTail.getCarbonContentTail() && ybInspectDataTail.getCarbonContentTail().compareTo(BigDecimal.ZERO) != 0){
                            BigDecimal divideCarbon = ybInspectDataTail.getCarbonContentTail().subtract(carbonContentTail).divide(ybInspectDataTail.getCarbonContentTail(), 4, BigDecimal.ROUND_HALF_UP);
                            content.append("; 碳含量 ").append(percent.format(divideCarbon));
                        }
                    }
                }
            }
        }


        log.info("发送数据为：{}",content);
        try {
            ArrayList<String> sceneList = new ArrayList<>();
            ArrayList<String> groupNameList = new ArrayList<>();
            sceneList.add("prod");
            groupNameList.add(groupName);
            dingTalkService.robotSeedMessage(String.valueOf(content), groupNameList, source, sceneList, SeedMassageEnum.GROUP);

//            SeedMassageDto seedMassageDto = new SeedMassageDto();
//            seedMassageDto.setContent(content.toString());
//            seedMassageDto.setScene(sceneList);
//            seedMassageDto.setGroupName(groupNameList);
//            seedMassageDto.setStatus(SeedMassageEnum.GROUP);
//            seedMassageDto.setSource(source);
//            dingTalkService.seedMassage(seedMassageDto);
        } catch (Exception e) {
            log.error("error_in_sendEapSignal", e);
        }
    }

    @Override
    public void sendSquareRodInfo(String fbSectionNo, String ybSectionNo, BigDecimal weight, String userName) {
        sendSap(fbSectionNo, ybSectionNo, weight, userName, "101");
    }

    @Override
    public void sendSquareRodInfoList(List<PushSapDto> list) {
        if (null != list && list.size() > 0) {
            sendSapList(list, list.get(0).getBwart());
        }
    }

    public Result sendSap(String fbSectionNo, String ybSectionNo, BigDecimal weight, String userName, String bwart) {
        Date date = new Date();
        log.info("触发上报单晶编号：{},圆棒编号：{},重量为：{}", fbSectionNo, ybSectionNo, weight);
        if (StringUtils.isNotBlank(ybSectionNo)) {
            YbInspectData bySectionNo = this.findBySectionNo(ybSectionNo);
            if (null == bySectionNo || StringUtils.isBlank(bySectionNo.getCrystalNo())) {
                return ResultGenerator.fail("不存在圆棒检验数据{}", ybSectionNo);
            }
            ReportSapGoodsmvt byCrystalNoAndBwart = reportSapGoodsmvtService.findByCrystalNoAndBwartAndProcName(fbSectionNo, bwart, "刀剖收货");
            if (null != byCrystalNoAndBwart) {
                log.info("该方棒单晶上报过，不在上报，单晶编号为：{}", fbSectionNo);
                return ResultGenerator.fail("该方棒单晶上报过，不在上报，单晶编号为：{}", fbSectionNo);
            }
            //处理是否上报过
            List<String> detailByCrystalNo = productionPaintingLineDetailService.findDetailByCrystalNo(ybSectionNo);
            for (String sectionNo : detailByCrystalNo) {
                ReportSapGoodsmvt sapGoodsmvt = reportSapGoodsmvtService.findByCrystalNoAndBwartAndProcName(sectionNo, bwart, "刀剖收货");
                if (null != sapGoodsmvt) {
                    log.info("该方棒单晶上报过，不在上报，单晶编号为：{}", fbSectionNo);
                    return ResultGenerator.fail("该方棒单晶上报过，不在上报，单晶编号为：{}", fbSectionNo);
                }
            }
            LongCrystal byCrystalNo = longCrystalService.findByCrystalNo(bySectionNo.getCrystalNo());
            if (null == byCrystalNo) {
                log.info("未关联到长晶棒记录，请先核对长晶棒记录，单晶编号为：{}", ybSectionNo);
                throw new RuntimeException("未关联到长晶棒记录，请先核对长晶棒记录，单晶编号为：" + ybSectionNo);
            }
            CrystalMaterialRelation crystalMaterialRelation = crystalMaterialRelationService.findBySectionNo(ybSectionNo);
            if (null == crystalMaterialRelation) {
                log.info("未关联刀刨排程记录，请先核对刀刨记录，单晶编号为：{}", ybSectionNo);
                throw new RuntimeException("未关联刀刨排程记录，请先核对刀刨记录，单晶编号为：" + ybSectionNo);
            }
            String umlgo = null;
            String warehouseCode = "";
            Equipment byCode = equipmentService.findByCode(crystalMaterialRelation.getDeviceNo());
            if (null != byCode) {
                DictionaryItem warehouseLocation = dictionaryItemService.findByThemeValueAndNameAndValueAndEnable("WarehouseLocation", byCode.getArea(), byCode.getSeries(), true);
                if (null != warehouseLocation) {
                    warehouseCode = warehouseLocation.getExtendValue1();
                    umlgo = warehouseLocation.getExtendValue2();
                }
            }

            String batchNo = byCrystalNo.getBatchNo();
            if (StringUtils.isNotBlank(batchNo) && batchNo.startsWith("TCN") && batchNo.length() >= 10) {
                batchNo = batchNo.substring(0, 1) + "J" + batchNo.substring(2, 10);
            }
            if (bwart.equals("101")) {
                WarehouseInputBillBo warehouseInputBillBo = new WarehouseInputBillBo();
                warehouseInputBillBo.setCreateUserName(userName);
                //warehouseInputBillBo.setCreateUserId(BaseContextHandler.getUserID());
                warehouseInputBillBo.setType(InputBillStatusEnum.开方入库.getValue());
                warehouseInputBillBo.setRemark(fbSectionNo);
                warehouseInputBillBo.setAutomaticOut(true);
                warehouseInputBillBo.setAutoAudit(true);
                if (StringUtils.isBlank(crystalMaterialRelation.getMaterialCode())) {
                    throw new RuntimeException("料号为空！");
                }
                MaterialModel materialModel = null;
                if (null != crystalMaterialRelation && null != crystalMaterialRelation.getMaterialModelId()) {
                    materialModel = materialModelService.get(crystalMaterialRelation.getMaterialModelId());
                }
                if (null == materialModel) {
                    throw new RuntimeException("方棒上报物料主数据为空！");
                }
                List<WarehouseInputBillDetailBo> inputBillDetails = new ArrayList<>();
                WarehouseInputBillDetailBo warehouseInputBillDetailBo = new WarehouseInputBillDetailBo();
                warehouseInputBillDetailBo.setCount(weight);
                warehouseInputBillDetailBo.setWarehouseCode(warehouseCode);
                warehouseInputBillDetailBo.setWarehouseName(warehouseCode);
                warehouseInputBillDetailBo.setMaterialModelId(Long.valueOf(materialModel.getId()));
                warehouseInputBillDetailBo.setMaterialModelCode(materialModel.getCode());
                Result<WarehouseModelDto> codeResult = storeFeignClients.getCode(warehouseCode);
                if (codeResult.getCode() == ResultCode.SUCCESS.getCode()) {
                    warehouseInputBillDetailBo.setWarehouseId(codeResult.getData().getId());
                }
                warehouseInputBillDetailBo.setWeight(weight);
                warehouseInputBillDetailBo.setMaterialModelName(materialModel.getName());
                if (null != materialModel.getMaterialType()) {
                    warehouseInputBillDetailBo.setMaterialTypeName(materialModel.getMaterialType().getName());
                }
                if (null != materialModel.getUnit()) {
                    warehouseInputBillDetailBo.setUnitName(materialModel.getUnit().getName());
                }
                warehouseInputBillDetailBo.setSpecification(materialModel.getSpecification());
                warehouseInputBillDetailBo.setMaterialTh(materialModel.getNumberOfDrawings());
                warehouseInputBillDetailBo.setSupplier(materialModel.getSupplier());
                warehouseInputBillDetailBo.setBatchNo(batchNo);
                inputBillDetails.add(warehouseInputBillDetailBo);
                warehouseInputBillBo.setInputBillDetails(inputBillDetails);
                WarehouseAllotBillDto warehouseAllotBillDto = new WarehouseAllotBillDto();
                warehouseAllotBillDto.setCreateUserId(BaseContextHandler.getUserID());
                List<WarehouseAllotBillDetailDto> allotBillDetailDtos = new ArrayList<>();
                WarehouseAllotBillDetailDto warehouseAllotBillDetailDto = new WarehouseAllotBillDetailDto();
                BeanUtil.copyBeanPropWithNullValue(warehouseAllotBillDetailDto, warehouseInputBillDetailBo, "id");
                warehouseAllotBillDetailDto.setAllotWarehouseName(umlgo);
                warehouseAllotBillDetailDto.setAllotWarehouseCode(umlgo);
                warehouseAllotBillDto.setCreateUserName(userName);
                warehouseAllotBillDto.setRemark(fbSectionNo);
                Result<WarehouseModelDto> umlgoResult = storeFeignClients.getCode(umlgo);
                if (umlgoResult.getCode() == ResultCode.SUCCESS.getCode()) {
                    warehouseAllotBillDetailDto.setAllotWarehouseId(umlgoResult.getData().getId());
                }
                allotBillDetailDtos.add(warehouseAllotBillDetailDto);
                warehouseAllotBillDto.setAutoAudit(true);
                warehouseAllotBillDto.setAllotBillDetailDtos(allotBillDetailDtos);
                StoreDto storeDto = new StoreDto();
                //storeDto.setWarehouseAllotBillDto(warehouseAllotBillDto);
                storeDto.setInputBillBo(warehouseInputBillBo);
                Result inputAndAllotAndOut = storeFeignClients.inputApply(warehouseInputBillBo);

                if (inputAndAllotAndOut.getCode() != ResultCode.SUCCESS.getCode()) {
                    log.info("线边仓入库调拨失败:{}", inputAndAllotAndOut.getMessage());
                    throw new RuntimeException("线边仓入库调拨失败！异常为：" + inputAndAllotAndOut.getMessage());
                }
            }
            wipStorageYbService.sendReportSapGoodsmvt(bwart, byCode.getSeries(), crystalMaterialRelation.getOrderNo(), crystalMaterialRelation.getMaterialCode(),
                    batchNo, weight.toString(), "KG", "5041", warehouseCode, fbSectionNo, umlgo, "方棒检验", crystalMaterialRelation.getDeviceNo(),null);

            ReportSapGoodsmvt reportSapGoodsmvt = reportSapGoodsmvtService.findByCrystalNoAndBwart(ybSectionNo, "261");
            if (null != reportSapGoodsmvt) {
                //报工时
                ReportSapWorkinghours reportSapWorkinghours = new ReportSapWorkinghours();
                String cnfTime = "0.00";
                if (null != reportSapGoodsmvt.getBldat()) {
                    cnfTime = new BigDecimal((date.getTime() - reportSapGoodsmvt.getBldat().getTime()) / 3600000).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                }
                reportSapWorkinghours.setCnfTime(cnfTime);
                reportSapWorkinghours.setCnfTimeUom("H");
                reportSapWorkinghours.setStatus(false);
                reportSapWorkinghours.setCnfQty1(weight.toString());
                reportSapWorkinghours.setProductionOrderId(reportSapGoodsmvt.getAufnr());
                reportSapWorkinghours.setRecordId(reportSapGoodsmvt.getCharg());
                reportSapWorkinghours.setPlant("5041");
                reportSapWorkinghoursService.saveOrUpdate(reportSapWorkinghours);
            }
        }
        return ResultGenerator.success();
    }

    public Result sendSapList(List<PushSapDto> list, String bwart) {
        List<WarehouseInputBillDetailBo> inputBillDetails = new ArrayList<>();
        List<SendReportSapGoodsmvtDto> reportSapGoodsmvtDtos = new ArrayList<>();
        List<String> sectionNoList = new ArrayList<>();

        WarehouseInputBillBo warehouseInputBillBo = new WarehouseInputBillBo();
        warehouseInputBillBo.setCreateUserName(list.get(0).getUserName());
        warehouseInputBillBo.setType(InputBillStatusEnum.开方入库.getValue());
        warehouseInputBillBo.setAutomaticOut(true);
        warehouseInputBillBo.setAutoAudit(true);

        for (PushSapDto pushSapDto : list) {
            String fbSectionNo = pushSapDto.getFbSectionNo();
            String ybSectionNo = pushSapDto.getYbSectionNo();
            String userName = pushSapDto.getUserName();
            BigDecimal weight = pushSapDto.getWeight();
            String batchNo = pushSapDto.getBatchNo();
            log.info("触发上报单晶编号：{},圆棒编号：{},重量为：{}", fbSectionNo, ybSectionNo, weight);
            if (StringUtils.isNotBlank(ybSectionNo)) {
//                YbInspectData bySectionNo = this.findBySectionNo(ybSectionNo);
//                if (null == bySectionNo || StringUtils.isBlank(bySectionNo.getCrystalNo())) {
//                    return ResultGenerator.fail("不存在圆棒检验数据{}",ybSectionNo);
//                }
//                ReportSapGoodsmvt byCrystalNoAndBwart = reportSapGoodsmvtService.findByCrystalNoAndBwartAndProcName1(fbSectionNo, "刀剖收货");
//                if (null != byCrystalNoAndBwart && byCrystalNoAndBwart.getBwart().equals("101") && pushSapDto.getBwart().equals("101")) {
//                    log.info("该方棒单晶上报过，不在上报，单晶编号为：{}", fbSectionNo);
//                    return ResultGenerator.fail("该方棒单晶上报过，不在上报，单晶编号为：{}", fbSectionNo);
//                }
                //处理是否上报过
//                List<String> detailByCrystalNo = productionPaintingLineDetailService.findDetailByCrystalNo(ybSectionNo);
//                for (String sectionNo : detailByCrystalNo){
//                    ReportSapGoodsmvt sapGoodsmvt = reportSapGoodsmvtService.findByCrystalNoAndBwartAndProcName(sectionNo, bwart, "刀剖收货");
//                    if (null != sapGoodsmvt){
//                        log.info("该方棒单晶上报过，不在上报，单晶编号为：{}", fbSectionNo);
//                        return ResultGenerator.fail("该方棒单晶上报过，不在上报，单晶编号为：{}", fbSectionNo);
//                    }
//                }
//                LongCrystal byCrystalNo = longCrystalService.findByCrystalNo(bySectionNo.getCrystalNo());
//                if (null == byCrystalNo) {
//                    log.info("未关联到长晶棒记录，请先核对长晶棒记录，单晶编号为：{}", ybSectionNo);
//                    throw new RuntimeException("未关联到长晶棒记录，请先核对长晶棒记录，单晶编号为：" + ybSectionNo);
//                }
                CrystalMaterialRelation crystalMaterialRelation = crystalMaterialRelationService.findBySectionNo(ybSectionNo);
                if (null == crystalMaterialRelation) {
                    log.info("未关联刀刨排程记录，请先核对刀刨记录，单晶编号为：{}", ybSectionNo);
                    throw new RuntimeException("未关联刀刨排程记录，请先核对刀刨记录，单晶编号为：" + ybSectionNo);
                }
                String umlgo = null;
                String warehouseCode = "";
                Equipment byCode = equipmentService.findByCode(crystalMaterialRelation.getDeviceNo());
                if (null != byCode) {
                    DictionaryItem warehouseLocation = dictionaryItemService.findByThemeValueAndNameAndValueAndEnable("WarehouseLocation", byCode.getArea(), byCode.getSeries(), true);
                    if (null != warehouseLocation) {
                        warehouseCode = warehouseLocation.getExtendValue1();
                        umlgo = warehouseLocation.getExtendValue2();
                    }
                }

                if (null != bwart && (bwart.equals("101") || bwart.equals("531"))) {
//
//                    if (StringUtils.isBlank(crystalMaterialRelation.getMaterialCode())) {
//                        throw new RuntimeException("料号为空！");
//                    }
//                    MaterialModel materialModel = null;
//                    if (null != crystalMaterialRelation && null != crystalMaterialRelation.getMaterialModelId()) {
//                        materialModel = materialModelService.get(crystalMaterialRelation.getMaterialModelId());
//                    }
//                    if (null == materialModel) {
//                        throw new RuntimeException("方棒上报物料主数据为空！");
//                    }
                    WarehouseInputBillDetailBo warehouseInputBillDetailBo = new WarehouseInputBillDetailBo();
                    warehouseInputBillDetailBo.setCount(weight);
                    warehouseInputBillDetailBo.setWarehouseCode(warehouseCode);
                    warehouseInputBillDetailBo.setWarehouseName(warehouseCode);

                    MaterialModel materialModel1 = materialModelService.findByCode(pushSapDto.getFbMatnr());
                    warehouseInputBillDetailBo.setMaterialModelId(Long.valueOf(materialModel1.getId()));
                    warehouseInputBillDetailBo.setMaterialModelCode(materialModel1.getCode());

                    Result<WarehouseModelDto> codeResult = storeFeignClients.getCode(warehouseCode);
                    if (codeResult.getCode() == ResultCode.SUCCESS.getCode()) {
                        warehouseInputBillDetailBo.setWarehouseId(codeResult.getData().getId());
                    }
                    warehouseInputBillDetailBo.setWeight(weight);
                    warehouseInputBillDetailBo.setMaterialModelName(materialModel1.getName());
                    if (null != materialModel1.getMaterialType()) {
                        warehouseInputBillDetailBo.setMaterialTypeName(materialModel1.getMaterialType().getName());
                    }
                    if (null != materialModel1.getUnit()) {
                        warehouseInputBillDetailBo.setUnitName(materialModel1.getUnit().getName());
                    }
                    warehouseInputBillDetailBo.setSpecification(materialModel1.getSpecification());
                    warehouseInputBillDetailBo.setMaterialTh(materialModel1.getNumberOfDrawings());
                    warehouseInputBillDetailBo.setSupplier(materialModel1.getSupplier());

                    warehouseInputBillDetailBo.setBatchNo(batchNo);
                    warehouseInputBillDetailBo.setCrystalNo(fbSectionNo);
                    inputBillDetails.add(warehouseInputBillDetailBo);
                    warehouseInputBillBo.setInputBillDetails(inputBillDetails);
                }

                SendReportSapGoodsmvtDto sendReportSapGoodsmvtDto = new SendReportSapGoodsmvtDto();
                sendReportSapGoodsmvtDto.setBwart(bwart);
                sendReportSapGoodsmvtDto.setSeries(byCode.getSeries());
                //订单及料号：直接从方棒检验数据库取值
                sendReportSapGoodsmvtDto.setOrderNo(pushSapDto.getFbOrderNo());
                sendReportSapGoodsmvtDto.setMaterialCode(pushSapDto.getFbMatnr());

                sendReportSapGoodsmvtDto.setBatchNo(batchNo);
                sendReportSapGoodsmvtDto.setWeight(weight.toString());
                sendReportSapGoodsmvtDto.setMeins("KG");
                sendReportSapGoodsmvtDto.setWerks("5041");
                sendReportSapGoodsmvtDto.setLgort(warehouseCode);
                sendReportSapGoodsmvtDto.setCrystalNo(fbSectionNo);
                sendReportSapGoodsmvtDto.setUmlgo(umlgo);
                sendReportSapGoodsmvtDto.setProcName("方棒检验");
                sendReportSapGoodsmvtDto.setDeviceNo(crystalMaterialRelation.getDeviceNo());
                reportSapGoodsmvtDtos.add(sendReportSapGoodsmvtDto);
            }
            sectionNoList.add(fbSectionNo);
        }
        log.info("上报SAP数据：" + reportSapGoodsmvtDtos);

        //线边仓入库
        if ("101".equals(bwart) || "531".equals(bwart)) {
            Result inputAndAllotAndOut = storeFeignClients.inputApply(warehouseInputBillBo);
            if (inputAndAllotAndOut.getCode() != ResultCode.SUCCESS.getCode()) {
                log.info("线边仓入库调拨失败:{}", inputAndAllotAndOut.getMessage());
                throw new RuntimeException("线边仓入库调拨失败！异常为：" + inputAndAllotAndOut.getMessage());
            }
        }
        //上报到ReportSapGoodsmvt
        wipStorageYbService.sendReportSapGoodsmvtList(reportSapGoodsmvtDtos);
        //报工时
//        sendReportSapWorkinghours(reportSapGoodsmvtDtos);
        return ResultGenerator.success();
    }

    //todo 工时只报一次
    public void sendReportSapWorkinghours(List<SendReportSapGoodsmvtDto> reportSapGoodsmvtDtos) {
        if (null != reportSapGoodsmvtDtos && reportSapGoodsmvtDtos.size() > 0) {
            for (SendReportSapGoodsmvtDto reportSapGoodsmvtDto : reportSapGoodsmvtDtos) {
                ReportSapGoodsmvt reportSapGoodsmvt = reportSapGoodsmvtService.findByCrystalNoAndBwart(reportSapGoodsmvtDto.getCrystalNo(), "261");
                if (null != reportSapGoodsmvt) {
                    //报工时
                    ReportSapWorkinghours reportSapWorkinghours = new ReportSapWorkinghours();
                    String cnfTime = "0.00";
                    if (null != reportSapGoodsmvt.getBldat()) {
                        cnfTime = new BigDecimal((new Date().getTime() - reportSapGoodsmvt.getBldat().getTime()) / 3600000).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                    }
                    reportSapWorkinghours.setCnfTime(cnfTime);
                    reportSapWorkinghours.setCnfTimeUom("H");
                    reportSapWorkinghours.setStatus(false);
                    reportSapWorkinghours.setCnfQty1(reportSapGoodsmvtDto.getWeight());
                    reportSapWorkinghours.setProductionOrderId(reportSapGoodsmvt.getAufnr());
                    reportSapWorkinghours.setRecordId(reportSapGoodsmvt.getCharg());
                    reportSapWorkinghours.setPlant("5041");
                    reportSapWorkinghoursService.saveOrUpdate(reportSapWorkinghours);
                }
            }
        }
    }

    @Override
    public Result sendSquareWriteOffAccounts(List<PushSapDto> list, WarehouseOutputBillBo warehouseOutputBillBo) {
        Result<String> stringResult = storeFeignClients.outputApply(warehouseOutputBillBo);
        if (ResultCode.SUCCESS.getCode() != stringResult.getCode()) {
            throw new RuntimeException("SAP产出上报失败，异常信息为：" + stringResult.getMessage());
        }
        if (null != list && list.size() > 0) {
            sendSapList(list, list.get(0).getBwart());
        }
        return ResultGenerator.success();
    }

    @Override
    public YbInspectData findByCrystalNoAndOxygenCarbonMark(String crystalNo, Integer oxygenCarbonMark) {
        if (StringUtils.isNotBlank(crystalNo) && null != oxygenCarbonMark) {
            if (oxygenCarbonMark == 1) {
                return dao.findByCrystalNoAndOxygenCarbonMarkDescd(crystalNo, oxygenCarbonMark);
            } else {
                return dao.findByCrystalNoAndOxygenCarbonMarkAsc(crystalNo, oxygenCarbonMark);
            }
        }
        return null;
    }


    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Map<String, Object> handCheck(String sql) {
        try {
            return getMapResult(sql);
        } catch (Exception e) {
            return null;
        }
    }


    private void dataToLog(YbInspectData ybInspectDataOld, DataInspectLog dataInspectLog) {

        dataInspectLog.setCrystalNo(ybInspectDataOld.getCrystalNo());
        dataInspectLog.setSectionNo(ybInspectDataOld.getSectionNo());
        dataInspectLog.setSectionType(ybInspectDataOld.getSectionType());
        dataInspectLog.setAgainNum(ybInspectDataOld.getAgainNum());
        dataInspectLog.setAgainPiece(ybInspectDataOld.getAgainPiece());
        dataInspectLog.setDopant(ybInspectDataOld.getDopant());
        dataInspectLog.setPullType(ybInspectDataOld.getPullType());
//        dataInspectLog.setKube();
        dataInspectLog.setIsCutBack(ybInspectDataOld.getIsCutBack());
        dataInspectLog.setCheckoutName(ybInspectDataOld.getCheckoutName());
        dataInspectLog.setReCheckType(ybInspectDataOld.getReCheckType());
        dataInspectLog.setProductTypeSecond(ybInspectDataOld.getProductTypeSecond());
        dataInspectLog.setIsChangeSpecs(ybInspectDataOld.getIsChangeSpecs());
//        dataInspectLog.setWareHouseLength();
        dataInspectLog.setActualLength(ybInspectDataOld.getActualLength());
        dataInspectLog.setActualWeight(ybInspectDataOld.getActualWeight());
        dataInspectLog.setTheoryWeight(ybInspectDataOld.getTheoryWeight());
        dataInspectLog.setHeadTailRecognition(ybInspectDataOld.getHeadTailRecognition());
        dataInspectLog.setDiameterMin(ybInspectDataOld.getDiameterMin());
        dataInspectLog.setDiameterMax(ybInspectDataOld.getDiameterMax());
//        dataInspectLog.setDiamDecide();
//        dataInspectLog.setFineDiameter();
//        dataInspectLog.setFineCutLength();
        dataInspectLog.setEdgeBark(ybInspectDataOld.getEdgeBark());
        dataInspectLog.setCollapseLine(ybInspectDataOld.getCollapseLine());
        dataInspectLog.setIsBevel(ybInspectDataOld.getIsBevel());
//        dataInspectLog.setIsFork();
//        dataInspectLog.setColorful();
        dataInspectLog.setCrack(ybInspectDataOld.getCrack());
//        dataInspectLog.setIsTwinCrystal();
//        dataInspectLog.setTwinLength();
//        dataInspectLog.setHeadSlope();
//        dataInspectLog.setTailSlope();
//        dataInspectLog.setDistortionBig();
        dataInspectLog.setDistortion(ybInspectDataOld.getDistortion());
        dataInspectLog.setProductLevel(ybInspectDataOld.getProductLevel());
        dataInspectLog.setProductLevelExperiment(ybInspectDataOld.getProductLevelExperiment());
        dataInspectLog.setLevelTime(ybInspectDataOld.getLevelTime());
        dataInspectLog.setRemark(ybInspectDataOld.getRemark());
        dataInspectLog.setLevel(ybInspectDataOld.getLevel());
        dataInspectLog.setExperiLevel(ybInspectDataOld.getExperiLevel());
        dataInspectLog.setConductiveType(ybInspectDataOld.getConductiveType());
//        dataInspectLog.setResistivityMin();
//        dataInspectLog.setResistivityMax();
//        dataInspectLog.setTLifeMin();
        dataInspectLog.setWLifeMin(ybInspectDataOld.getWLifeMin());
        dataInspectLog.setTRadialCentre(ybInspectDataOld.getTRadialCentre());
        dataInspectLog.setTRadialEdge1(ybInspectDataOld.getTRadialEdge1());
        dataInspectLog.setTRadialEdge2(ybInspectDataOld.getTRadialEdge2());
        dataInspectLog.setTRadialEdge3(ybInspectDataOld.getTRadialEdge3());
        dataInspectLog.setTRadialEdge4(ybInspectDataOld.getTRadialEdge4());
        dataInspectLog.setTRadialEdge5(ybInspectDataOld.getTRadialEdge5());
        dataInspectLog.setTRadialEdge6(ybInspectDataOld.getTRadialEdge6());
        dataInspectLog.setTRadialEdge7(ybInspectDataOld.getTRadialEdge7());
        dataInspectLog.setTRadialEdge8(ybInspectDataOld.getTRadialEdge8());
        dataInspectLog.setWRadialCentre(ybInspectDataOld.getWRadialCentre());
        dataInspectLog.setWRadialEdge1(ybInspectDataOld.getWRadialEdge1());
        dataInspectLog.setWRadialEdge2(ybInspectDataOld.getWRadialEdge2());
        dataInspectLog.setWRadialEdge3(ybInspectDataOld.getWRadialEdge3());
        dataInspectLog.setWRadialEdge4(ybInspectDataOld.getWRadialEdge4());
        dataInspectLog.setWRadialEdge5(ybInspectDataOld.getWRadialEdge5());
        dataInspectLog.setWRadialEdge6(ybInspectDataOld.getWRadialEdge6());
        dataInspectLog.setWRadialEdge7(ybInspectDataOld.getWRadialEdge7());
        dataInspectLog.setWRadialEdge8(ybInspectDataOld.getWRadialEdge8());
//        dataInspectLog.setEndCentreEdgeAvg4();
//        dataInspectLog.setTopCentreEdgeAvg();
//        dataInspectLog.setEndCentreEdgeAvg();
        dataInspectLog.setResistivityTopAvg(ybInspectDataOld.getResistivityTopAvg());
//        dataInspectLog.setResistivityEndAvg();
//        dataInspectLog.setSellResistivity();
//        dataInspectLog.setResistivityConclusion();
//        dataInspectLog.setIsSeeBottom();
//        dataInspectLog.setResistivityWarping();
        dataInspectLog.setTCentreLife(ybInspectDataOld.getTCentreLife());
        dataInspectLog.setTLifeEdge1(ybInspectDataOld.getTLifeEdge1());
        dataInspectLog.setTLifeEdge2(ybInspectDataOld.getTLifeEdge2());
        dataInspectLog.setTLifeEdge3(ybInspectDataOld.getTLifeEdge3());
        dataInspectLog.setTLifeEdge4(ybInspectDataOld.getTLifeEdge4());
        dataInspectLog.setWCentreLife(ybInspectDataOld.getWCentreLife());
        dataInspectLog.setWLifeEdge1(ybInspectDataOld.getWLifeEdge1());
        dataInspectLog.setWLifeEdge2(ybInspectDataOld.getWLifeEdge2());
        dataInspectLog.setWLifeEdge3(ybInspectDataOld.getWLifeEdge3());
        dataInspectLog.setWLifeEdge4(ybInspectDataOld.getWLifeEdge4());
        dataInspectLog.setReduceCrystalLength(ybInspectDataOld.getReduceCrystalLength());
        dataInspectLog.setCrystalWorkshop(ybInspectDataOld.getCrystalWorkshop());
        dataInspectLog.setOxygenContentHead(ybInspectDataOld.getOxygenContentHead());
//        dataInspectLog.setOxygenContentBorder();
        dataInspectLog.setCarbonContentHead(ybInspectDataOld.getCarbonContentHead());
//        dataInspectLog.setCarbonContentBorder();
        dataInspectLog.setOxygenContentTail(ybInspectDataOld.getOxygenContentTail());
//        dataInspectLog.setOxygenContentBorderTail();
        dataInspectLog.setCarbonContentTail(ybInspectDataOld.getCarbonContentTail());
//        dataInspectLog.setCarbonContentBorderTail();
//        dataInspectLog.setHeadDefectGrade();
//        dataInspectLog.setTailDefect();
//        dataInspectLog.setIsMalpositionHead();
//        dataInspectLog.setIsMalpositionTail();
//        dataInspectLog.setTCenterAnneal();
//        dataInspectLog.setWcenterAnneal();
//        dataInspectLog.setTBorderAnneal();
//        dataInspectLog.setWBorderAnneal();
//        dataInspectLog.setAnomaly();
        dataInspectLog.setInspector(ybInspectDataOld.getInspector());
//        dataInspectLog.setHasGone();
        dataInspectLog.setOrderNo(ybInspectDataOld.getOrderNo());
        dataInspectLog.setPlanSpecs(ybInspectDataOld.getPlanSpecs());
//        dataInspectLog.setPlanMaterialCode();
        dataInspectLog.setOrderType(ybInspectDataOld.getOrderType());
        dataInspectLog.setFurnaceType(ybInspectDataOld.getFurnaceType());
        dataInspectLog.setDeviceNo(ybInspectDataOld.getDeviceNo());
//        dataInspectLog.setSeries();
        dataInspectLog.setLotNo(ybInspectDataOld.getLotNo());
//        dataInspectLog.setMaterialCount();
//        dataInspectLog.setSintonCenter();
//        dataInspectLog.setSintonTail();
//        dataInspectLog.setLifeSpanw1();
//        dataInspectLog.setResistivityw1();
//        dataInspectLog.setLifeSpant2();
//        dataInspectLog.setResistivityt2();
        dataInspectLog.setPiecewiseNum(ybInspectDataOld.getPiecewiseNum());
        dataInspectLog.setCreateTime(ybInspectDataOld.getCreateTime());
        dataInspectLog.setUpdateTime(ybInspectDataOld.getUpdateTime());
//        dataInspectLog.setDrawLine();
        dataInspectLog.setCrystalAbnormal(ybInspectDataOld.getCrystalAbnormal());
        dataInspectLog.setSectionCompose(ybInspectDataOld.getSectionCompose());
        dataInspectLog.setSticksCount(ybInspectDataOld.getSticksCount());
        dataInspectLog.setFactory(ybInspectDataOld.getFactory());
//        dataInspectLog.setHeadLevel();
//        dataInspectLog.setTailLevel();
//        dataInspectLog.setGradeName();
        dataInspectLog.setGradeVersion(ybInspectDataOld.getGradeVersion());
//        dataInspectLog.setPlanGradeName();
//        dataInspectLog.setPlanGradeVersion();
        dataInspectLog.setCheckReback(ybInspectDataOld.getCheckReback());
        dataInspectLog.setCheckLineNo(ybInspectDataOld.getCheckLineNo());
//        dataInspectLog.setTTempRadialCentreTheory();
//        dataInspectLog.setTTempRadialEdgeTheory1();
//        dataInspectLog.setWTempRadialCentreTheory();
//        dataInspectLog.setWTempRadialEdgeTheory1();
//        dataInspectLog.setTTempRadialCentre();
//        dataInspectLog.setTTempRadialEdge1();
//        dataInspectLog.setTTempRadialEdge2();
//        dataInspectLog.setTTempRadialEdge3();
//        dataInspectLog.setTTempRadialEdge4();
//        dataInspectLog.setTTempRadialEdge5();
//        dataInspectLog.setTTempRadialEdge6();
//        dataInspectLog.setTTempRadialEdge7();
//        dataInspectLog.setTTempRadialEdge8();
//        dataInspectLog.setWTempRadialCentre();
//        dataInspectLog.setWTempRadialEdge1();
//        dataInspectLog.setWTempRadialEdge2();
//        dataInspectLog.setWTempRadialEdge3();
//        dataInspectLog.setWTempRadialEdge4();
//        dataInspectLog.setWTempRadialEdge5();
//        dataInspectLog.setWTempRadialEdge6();
//        dataInspectLog.setWTempRadialEdge7();
//        dataInspectLog.setWTempRadialEdge8();
        dataInspectLog.setCrystalDirection(ybInspectDataOld.getCrystalDirection());
        dataInspectLog.setGradeData(ybInspectDataOld.getGradeData());
//        dataInspectLog.setPlanOrderNo();
        dataInspectLog.setMaterialCode(ybInspectDataOld.getMaterialCode());
//        dataInspectLog.setTemperature();
//        dataInspectLog.setTemperatureEnd();
//        dataInspectLog.setDemcMax();
//        dataInspectLog.setDiameterMinusBig();
//        dataInspectLog.setPlanOrderType();
//        dataInspectLog.setPlanStickCount();
//        dataInspectLog.setPlanLenRange();
        dataInspectLog.setPlanDopant(ybInspectDataOld.getPlanDopant());
        dataInspectLog.setPlanConductiveType(ybInspectDataOld.getPlanConductiveType());
        dataInspectLog.setPlanGrade(ybInspectDataOld.getPlanGrade());
        dataInspectLog.setSpellBarLength(ybInspectDataOld.getSpellBarLength());
//        dataInspectLog.setAvgDiameter();
//        dataInspectLog.setAllAvgDiameter();
//        dataInspectLog.setLineMarking();
        dataInspectLog.setGradeType(ybInspectDataOld.getGradeType());
//        dataInspectLog.setOperator();
//        dataInspectLog.setOperateTime();
//        dataInspectLog.setOperateType();
//        dataInspectLog.setRemarks();
//        dataInspectLog.setCompensateResistivityw1();
//        dataInspectLog.setCompensateResistivityt2();
//        dataInspectLog.setHeadTailChange();
//        dataInspectLog.setRetestNum();
    }

    @Override
    public void initInspectData(YbInspectData ybInspectDataOld, SectionNoDetail sectionNoDetail, LongCrystal longCrystal) {
        // 查询短棒棒属性值 只在新增时候赋值
        setSectionNoDetailData(ybInspectDataOld, sectionNoDetail);
        // 查询长晶棒属性值 只在新增时候赋值
        setLongCryStalData(ybInspectDataOld, longCrystal);

        //处理单晶是否是试加工
        if (StringUtils.isBlank(ybInspectDataOld.getProductPattern())) {
            String crystalNo = ybInspectDataOld.getCrystalNo();
            if (StringUtils.isBlank(crystalNo)) {
                if (null != sectionNoDetail) {
                    crystalNo = sectionNoDetail.getCrystalNo();
                }
            }
            if (StringUtils.isBlank(crystalNo)) {
                if (null != longCrystal) {
                    crystalNo = longCrystal.getCrystalNo();
                }
            }

            if (StringUtils.isNotBlank(crystalNo)) {
                ProductionPaintingLine byCrystalNo = productionPaintingLineService.findByCrystalNo(crystalNo);
                if (null != byCrystalNo && null != byCrystalNo.getTrialProcess() && byCrystalNo.getTrialProcess() == 1) {
                    ybInspectDataOld.setProductPattern(Constants.TRIAL_PROCESS);
                }
            }

            if (StringUtils.isNotBlank(longCrystal.getLotNo()) && null != longCrystal.getAgainNum()){
                AlloyMasterAlloy alloyMasterAlloy = alloyMasterAlloyService.findByLotNoAndAddTime(longCrystal.getLotNo(), String.valueOf(longCrystal.getAgainNum()));
                if (null != alloyMasterAlloy){
                    ybInspectDataOld.setFormulation(alloyMasterAlloy.getRecipeName());
                }
            }
        }
    }

    /**
     * 给检验数据赋值长棒信息
     *
     * @param ybInspectData 检验数据
     * @param longCrystal   长棒信息
     */
    public void setLongCryStalData(YbInspectData ybInspectData, LongCrystal longCrystal) {
        //长棒订单
        if (longCrystal != null) {
            ybInspectData.setCrystalNo(longCrystal.getCrystalNo());
            // 单晶拉制异常
            if (StringUtils.isNotBlank(longCrystal.getCrystalErrorLevelOne())
                    && StringUtils.isNotBlank(longCrystal.getCrystalErrorLevelTwo())) {
                ybInspectData.setCrystalAbnormal("3");
            } else if (StringUtils.isNotBlank(longCrystal.getCrystalErrorLevelOne())) {
                ybInspectData.setCrystalAbnormal("1");
            } else if (StringUtils.isNotBlank(longCrystal.getCrystalErrorLevelTwo())) {
                ybInspectData.setCrystalAbnormal("2");
            }
            ybInspectData.setProductType(longCrystal.getProductType());
            ybInspectData.setAgainNum(longCrystal.getAgainNum());
            ybInspectData.setAgainPiece(longCrystal.getCrystalNum());
            ybInspectData.setDopant(longCrystal.getDopant());
            ybInspectData.setPullType(longCrystal.getWindUp());
            ybInspectData.setCrystalWorkshop(longCrystal.getArea());
            ybInspectData.setFurnaceType(longCrystal.getFurnaceType());
            ybInspectData.setDeviceNo(longCrystal.getEquipmentCode());
            ybInspectData.setLotNo(longCrystal.getLotNo());
            ybInspectData.setDiameterMax(longCrystal.getMaxDiam());
            ybInspectData.setDiameterMin(longCrystal.getMinDiam());
            ybInspectData.setBatchNo(longCrystal.getBatchNo());
            //多边距字段赋值
            ybInspectData.setSideLengthRange(longCrystal.getSideLengthRange());
            //赋值长棒计划订单信息
            if (longCrystal.getOrderId() != null) {
                //计划产品评级
                ybInspectData.setPlanGrade(longCrystal.getProductGrade());
                // 计划产品规格
                ybInspectData.setPlanSpecs(longCrystal.getSpecs());
                // 计划掺杂剂
                ybInspectData.setPlanDopant(longCrystal.getDopant());
                ybInspectData.setDopant(longCrystal.getDopant());
                // 计划导电类型
                ybInspectData.setPlanConductiveType(longCrystal.getConductiveType());
                ybInspectData.setConductiveType(longCrystal.getConductiveType());
                ybInspectData.setProductTypeSecond(longCrystal.getSpecs());

                String productTypeSecond = ybInspectData.getProductTypeSecond();
                BigDecimal actualLength = ybInspectData.getActualLength();
                if (StringUtils.isEmpty(productTypeSecond)) {
                    throw new BusinessException("晶编【" + ybInspectData.getSectionNo() + "】的规格异常");
                }
                if (null == actualLength) {
                    throw new BusinessException("晶编【" + ybInspectData.getSectionNo() + "】的实际长度异常");
                }
                  /*  移植代码注释
                  List<DictionaryItem> dictionaryItems = dictionaryItemService.findByThemeValueAndItemName(Constants.WEIGHT_RATIO, productTypeSecond, true);
                    if (dictionaryItems.size() == 0) {
                        throw new BusinessException("请配置【" + productTypeSecond + "】规格的理论重量系数");
                    }
                    BigDecimal weightLossCoefficient = NumberUtil.Object2BigDecimal(dictionaryItems.get(0).getValue());
                    // 计算理论重量
                    ybInspectData.setTheoryWeight(actualLength.divide(weightLossCoefficient, 2, RoundingMode.CEILING));*/

                // 订单类型
//                ybInspectData.setOrderType(longCrystal.getOrderType());
//                // 计划订单号
//                ybInspectData.setOrderNo(longCrystal.getOrderNo());
                //ybInspectData.setMaterialCode(productionOrder.getMatnr());
               /* if (productionOrder != null && productionOrder.getProductModel() != null) {
                    //计划产品评级
                    ybInspectData.setPlanGrade(productionOrder.getProductModel().getProductGrade());
                    // 计划产品规格
                    ybInspectData.setPlanSpecs(productionOrder.getProductModel().getSpecs());
                    // 计划掺杂剂
                    ybInspectData.setPlanDopant(productionOrder.getProductModel().getDopant());
                    ybInspectData.setDopant(productionOrder.getProductModel().getDopant());
                    // 计划导电类型
                    ybInspectData.setPlanConductiveType(productionOrder.getProductModel().getConductionType());
                    ybInspectData.setConductiveType(productionOrder.getProductModel().getConductionType());
                    ybInspectData.setProductTypeSecond(longCrystal.getSpecs());

                    String productTypeSecond = ybInspectData.getProductTypeSecond();
                    BigDecimal actualLength = ybInspectData.getActualLength();
                    if(StringUtils.isEmpty(productTypeSecond)){
                        throw new BusinessException("晶编【" + ybInspectData.getSectionNo() + "】的规格异常");
                    }
                    if(null == actualLength){
                        throw new BusinessException("晶编【" + ybInspectData.getSectionNo() + "】的实际长度异常");
                    }
                  *//*  移植代码注释
                  List<DictionaryItem> dictionaryItems = dictionaryItemService.findByThemeValueAndItemName(Constants.WEIGHT_RATIO, productTypeSecond, true);
                    if (dictionaryItems.size() == 0) {
                        throw new BusinessException("请配置【" + productTypeSecond + "】规格的理论重量系数");
                    }
                    BigDecimal weightLossCoefficient = NumberUtil.Object2BigDecimal(dictionaryItems.get(0).getValue());
                    // 计算理论重量
                    ybInspectData.setTheoryWeight(actualLength.divide(weightLossCoefficient, 2, RoundingMode.CEILING));*//*

                    // 订单类型
                    ybInspectData.setOrderType(productionOrder.getAuart());
                    // 计划订单号
                    ybInspectData.setOrderNo(productionOrder.getAufnr());
                    //ybInspectData.setMaterialCode(productionOrder.getMatnr());
                }*/
            }
            //处理料号
            CrystalMaterialRelation bySectionNo = crystalMaterialRelationService.findBySectionNo(longCrystal.getCrystalNo());
            if (null != bySectionNo) {
                ybInspectData.setMaterialCode(bySectionNo.getMaterialCode());
                ybInspectData.setOrderNo(bySectionNo.getOrderNo());
                ybInspectData.setWorkOrderNo(bySectionNo.getOrderNo());
                //ybInspectData.setWorkOrderType(longCrystal.getOrderType());
                //处理定向标识
                if (StringUtils.isNotBlank(bySectionNo.getOrderNo())){
                    ProductionOrder productionOrder = productionOrderService.findByAufnr(bySectionNo.getOrderNo());
                    if (null != productionOrder){
                        ybInspectData.setZorientationind(productionOrder.getZorientationind());
                    }
                }
            }
            ybInspectData.setArea(longCrystal.getSeries());
            ybInspectData.setFactory(longCrystal.getArea());
            ybInspectData.setAbbreviation(longCrystal.getSimpleName());

            //完结方式传递
            ybInspectData.setClosureIdentification(StringUtils.equals(longCrystal.getWindUp(),EnumValuesServer.FINALIDENTIFICATION) ? "是" :"否");
            //产品配方
            //ybInspectData.setFormulation(longCrystal.getProductName());
        }
    }

    @Override
    @ServiceLogs(description = "圆棒检验数据系数计算寿命")
    public YbInspectDataCUDto coefficient(YbInspectDataCUDto ybInspectDataCuDto) {
        if (null != ybInspectDataCuDto.getConductiveType()) {
            List<DictionaryItem> dictionaryItemList = dictionaryItemService.findByThemeValueAndItemName("life_coefficient", ybInspectDataCuDto.getConductiveType(), true);
            if (dictionaryItemList.isEmpty()) {
                return ybInspectDataCuDto;
            }
            DictionaryItem dictionaryItem = dictionaryItemList.get(0);
            String value = dictionaryItem.getValue();
            String extendValue = dictionaryItem.getExtendValue();
            if (StringUtils.isEmpty(value) || StringUtils.isEmpty(extendValue)) {
                return ybInspectDataCuDto;
            }
            double coefficient = 1D;
            double constant = 0D;
            try {
                coefficient = Double.parseDouble(value);
                constant = Double.parseDouble(extendValue);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 导电型号为p型, 需*系数    (sz * 1.801)+0.0658
            if (null != ybInspectDataCuDto.getTCentreLife()) {
                BigDecimal bigDecimal = MathUtils.keepDecimalDigis(ybInspectDataCuDto.getTCentreLife().doubleValue() * coefficient + constant);
                ybInspectDataCuDto.setTCentreLife(bigDecimal);
            }
            if (null != ybInspectDataCuDto.getTLifeEdge1()) {
                BigDecimal bigDecimal = MathUtils.keepDecimalDigis(ybInspectDataCuDto.getTLifeEdge1().doubleValue() * coefficient + constant);
                ybInspectDataCuDto.setTLifeEdge1(bigDecimal);
            }
            if (null != ybInspectDataCuDto.getTLifeEdge2()) {
                BigDecimal bigDecimal = MathUtils.keepDecimalDigis(ybInspectDataCuDto.getTLifeEdge2().doubleValue() * coefficient + constant);
                ybInspectDataCuDto.setTLifeEdge2(bigDecimal);
            }
            if (null != ybInspectDataCuDto.getWCentreLife()) {
                BigDecimal bigDecimal = MathUtils.keepDecimalDigis(ybInspectDataCuDto.getWCentreLife().doubleValue() * coefficient + constant);
                ybInspectDataCuDto.setWCentreLife(bigDecimal);
            }
            if (null != ybInspectDataCuDto.getWLifeEdge1()) {
                BigDecimal bigDecimal = MathUtils.keepDecimalDigis(ybInspectDataCuDto.getWLifeEdge1().doubleValue() * coefficient + constant);
                ybInspectDataCuDto.setWLifeEdge1(bigDecimal);
            }
            if (null != ybInspectDataCuDto.getWLifeEdge2()) {
                BigDecimal bigDecimal = MathUtils.keepDecimalDigis(ybInspectDataCuDto.getWLifeEdge2().doubleValue() * coefficient + constant);
                ybInspectDataCuDto.setWLifeEdge2(bigDecimal);
            }
        }
        return ybInspectDataCuDto;
    }

    private void setSectionNoDetailData(YbInspectData ybInspectData, SectionNoDetail sectionNoDetail) {
        ybInspectData.setPiecewiseNum(sectionNoDetail.getSegmentNum());
        ybInspectData.setSectionType(sectionNoDetail.getSectionType());
//        ybInspectData.setTheoryWeight(sectionNoDetail.getWeight());
        ybInspectData.setActualLength(sectionNoDetail.getLength());
        if (StringUtils.isNotBlank(sectionNoDetail.getSectionNo())) {
            if (sectionNoDetail.getSectionNo().endsWith("T")) {
                ybInspectData.setHeadTailRecognition("T段");
                ybInspectData.setTResistivity(ybInspectData.getMeanResistivityA());
            } else if (sectionNoDetail.getSectionNo().endsWith("A")) {
                ybInspectData.setHeadTailRecognition("W段");
                ybInspectData.setWResistivity(ybInspectData.getMeanResistivityB());
            } else {
                ybInspectData.setHeadTailRecognition("Z段");
            }
            Integer segmentNum = sectionNoDetailService.findSegmentNumByNo(sectionNoDetail.getCrystalNo());
            if (null != segmentNum && segmentNum == 1) {
                ybInspectData.setHeadTailRecognition("T段W段");
            }
        }
        ybInspectData.setFacadeFrequency(sectionNoDetail.getFacadeFrequency());
        ybInspectData.setBehaviorFrequency(sectionNoDetail.getBehaviorFrequency());

        //获取外发标识
        ybInspectData.setOutGoing(0);
        OutgoMarkOperate byCrystalNoAndStatus = outgoMarkOperateService.findByCrystalNoAndStatus(sectionNoDetail.getCrystalNo(), 0);
        //毛棒已标识外发
        if (null != byCrystalNoAndStatus) {
            ybInspectData.setOutGoing(1);
        } else {
            OutgoMarkOperate bySectionNoAndStatus = outgoMarkOperateService.findBySectionNoAndStatus(ybInspectData.getSectionNo(), 0);
            if (null != bySectionNoAndStatus) {
                ybInspectData.setOutGoing(1);
            }
        }
        ybInspectData.setOxygenCarbonMark(sectionNoDetail.getOxygenCarbonMark());
        //处理头片氧，尾片碳数据
        ybInspectData.setCrystalNo(sectionNoDetail.getCrystalNo());
        handleContentInfo(ybInspectData, sectionNoDetail.getCrystalNo());
        if (null != ybInspectData.getActualLength()) {
            String specs = sectionNoDetail.getSpecs();
            ybInspectData.setProductTypeSecond(specs);
            List<DictionaryItem> dictionaryItems = dictionaryItemService.findByThemeValueAndItemName(Constants.WEIGHT_RATIO, specs, true);
            if (CollectionUtils.isNotEmpty(dictionaryItems)) {
                BigDecimal weightLossCoefficient = NumberUtil.Object2BigDecimal(dictionaryItems.get(0).getValue());
                if (null != weightLossCoefficient && weightLossCoefficient.compareTo(BigDecimal.ONE) > 0) {
                    ybInspectData.setTheoryWeight(sectionNoDetail.getLength().divide(weightLossCoefficient, 3, RoundingMode.HALF_UP));
                }
            }
        }

       /* Integer segmentNum = sectionNoDetailService.findSegmentNumByNo(sectionNoDetail.getCrystalNo());
        if (sectionNoDetail.getSegmentNum() != null) {
            if (sectionNoDetail.getSegmentNum() == 1 && segmentNum == 1) {
                ybInspectData.setHeadTailRecognition("T段W段");
            } else if (sectionNoDetail.getSegmentNum() == 1) {
                ybInspectData.setHeadTailRecognition("T段");
            } else if (sectionNoDetail.getSegmentNum().equals(segmentNum)) {
                ybInspectData.setHeadTailRecognition("W段");
            } else {
                ybInspectData.setHeadTailRecognition("Z段");
            }
        } else {
            ybInspectData.setHeadTailRecognition("未知");
        }*/
    }

    private void handleContentInfo(YbInspectData ybInspectData, String crystalNoTemp) {
        SectionNoDetail sectionNoDetailHead = null;
        Boolean individualFlag = false;
        if (StringUtils.isNotBlank(ybInspectData.getSectionNo()) && ybInspectData.getSectionNo().endsWith("R")) {
            sectionNoDetailHead = sectionNoDetailService.findBySectionNo(ybInspectData.getSectionNo());
            individualFlag = true;
        } else {
            sectionNoDetailHead = sectionNoDetailService.findBySectionNo(crystalNoTemp + "T");
        }


        // 调整业务，查询头段是否正常
        if (StringUtils.isNotBlank(crystalNoTemp)) {
            String headSectionNo = crystalNoTemp + "T";
            YbInspectData bySectionNo = this.findBySectionNo(headSectionNo);
            if (null != bySectionNo && !StringUtils.equals(headSectionNo, ybInspectData.getSectionNo())) {
                if (StringUtils.isNotBlank(bySectionNo.getProductLevel()) && StringUtils.isNotBlank(bySectionNo.getGradeType())) {
                    if (bySectionNo.getProductLevel().contains("返切不复测")) {
                        DefaultSample defaultSample = defaultSampleService.findByDopantLikeAndSpecificationsLikeAndProductTypeLike(bySectionNo.getDopant(), bySectionNo.getProductTypeSecond(), bySectionNo.getProductType());
                        ybInspectData.setOxygenContentHead(NumberUtil.Object2BigDecimal(defaultSample.getOxygenCenterHead(), null));
                        //注释W氧含量中心 赋默认值
                        // ybInspectData.setOxygenContentTail(NumberUtil.Object2BigDecimal(defaultSample.getOxygenCenterTail(), null));
                    } else {
                        if (StringUtils.equals(bySectionNo.getGradeType(), "正常")) {
                            //T氧含量中心
                            ybInspectData.setOxygenContentHead(bySectionNo.getOxygenContentHead());
                            //T碳含量中心
                            ybInspectData.setCarbonContentHead(bySectionNo.getCarbonContentHead());
                        } else if (StringUtils.equals(bySectionNo.getGradeType(), "反切")) {

                            YbInspectData headInspectData = dao.findBySectionNoLike(headSectionNo);
                            if (null != headInspectData && !StringUtils.equals(headInspectData.getSectionNo(), bySectionNo.getSectionNo())) {
                                //T氧含量中心
                                ybInspectData.setOxygenContentHead(headInspectData.getOxygenContentHead());
                                //T碳含量中心
                                ybInspectData.setCarbonContentHead(headInspectData.getCarbonContentHead());
                            } else {
                                //T氧含量中心
                                ybInspectData.setOxygenContentHead(BigDecimal.ZERO);
                                //T碳含量中心
                                ybInspectData.setCarbonContentHead(BigDecimal.ZERO);
                            }
                        }
                    }
                } else {
                    //T氧含量中心
                    ybInspectData.setOxygenContentHead(bySectionNo.getOxygenContentHead());
                    //T碳含量中心
                    ybInspectData.setCarbonContentHead(bySectionNo.getCarbonContentHead());
                }
            } else {
                if (null != sectionNoDetailHead && StringUtils.isNotBlank(sectionNoDetailHead.getPieceNoHead())) {
                    PieceCheck pieceCheckHead = pieceCheckService.getByPieceNo(sectionNoDetailHead.getPieceNoHead());
                    if (null != pieceCheckHead) {
                        //T氧含量中心
                        ybInspectData.setOxygenContentHead(pieceCheckHead.getoContents());
                        //T碳含量中心
                        ybInspectData.setCarbonContentHead(pieceCheckHead.getcContents());
                    }

                }
            }
        }
        SectionNoDetail sectionNoDetailTail = null;
        if (individualFlag) {
            sectionNoDetailTail = sectionNoDetailHead;
        } else {
            sectionNoDetailTail = sectionNoDetailService.findBySectionNo(crystalNoTemp + "A");
        }
        if (null != sectionNoDetailTail && StringUtils.isNotBlank(sectionNoDetailTail.getPieceNoEnd())) {
            PieceCheck pieceCheckTail = pieceCheckService.getByPieceNo(sectionNoDetailTail.getPieceNoEnd());
            if (null != pieceCheckTail) {
                //W氧含量中心
                ybInspectData.setOxygenContentTail(pieceCheckTail.getoContents());
                //W碳含量中心
                ybInspectData.setCarbonContentTail(pieceCheckTail.getcContents());
            } else {
                ybInspectData.setOxygenContentTail(BigDecimal.ZERO);
                ybInspectData.setCarbonContentTail(BigDecimal.ZERO);
            }
        }

        //添加卡控，中间段单晶需要等待头尾两段检测之后才能流转
        if (StringUtils.isNotBlank(ybInspectData.getSectionNo())) {
            if (individualFlag) {
                this.handleResistivityAndLife(ybInspectData, ybInspectData, true);
                this.handleResistivityAndLife(ybInspectData, ybInspectData, false);
            } else {
                if (ybInspectData.getSectionNo().endsWith("A")) {
                    this.handleResistivityAndLife(ybInspectData, ybInspectData, false);
                    //查询头段
                    YbInspectData headInspectData = dao.findBySectionNoLike(crystalNoTemp + "T");
                    this.handleResistivityAndLife(ybInspectData, headInspectData, true);
                } else if (ybInspectData.getSectionNo().endsWith("T")) {
                    this.handleResistivityAndLife(ybInspectData, ybInspectData, true);
                    //查询尾段
                    YbInspectData tailInspectData = dao.findBySectionNoLike(crystalNoTemp + "A");
                    this.handleResistivityAndLife(ybInspectData, tailInspectData, false);
                } else {
                    YbInspectData headInspectData = dao.findBySectionNoLike(crystalNoTemp + "T");
               /* if (null == headInspectData){
                    throw new BusinessException("头段电阻率和少子寿命未测量完成出，请先检测头段晶段电阻率和少子寿命!");
                }*/
                    this.handleResistivityAndLife(ybInspectData, headInspectData, true);
                    YbInspectData tailInspectData = dao.findBySectionNoLike(crystalNoTemp + "A");
               /* if (null == tailInspectData){
                    throw new BusinessException("尾段电阻率和少子寿命未测量完成出，请先检测尾段晶段电阻率和少子寿命!");
                }*/
                    this.handleResistivityAndLife(ybInspectData, tailInspectData, false);
                }
            }
        }


    }

    private void handleResistivityAndLife(YbInspectData ybInspectData, YbInspectData ybInspectDataQuote, Boolean headFlag) {
        if (null == ybInspectData || null == ybInspectDataQuote) {
            return;
        }
        if (headFlag) {
            //头段A电阻率均值
            ybInspectData.setTRadialCentre(ybInspectDataQuote.getMeanResistivityA());
            //头段B电阻率均值
            ybInspectData.setTRadialEdge1(ybInspectDataQuote.getMeanResistivityB());
            //头段A少子寿命均值
            ybInspectData.setTCentreLife(ybInspectDataQuote.getMeanCarrierLifetimeA());
            //头段B少子寿命均值
            ybInspectData.setTLifeEdge1(ybInspectDataQuote.getMeanCarrierLifetimeB());
        } else {
            //尾段A电阻率均值
            ybInspectData.setWRadialCentre(ybInspectDataQuote.getMeanResistivityA());
            //尾段B电阻率均值
            ybInspectData.setWRadialEdge1(ybInspectDataQuote.getMeanResistivityB());
            //尾段A少子寿命均值
            ybInspectData.setWCentreLife(ybInspectDataQuote.getMeanCarrierLifetimeA());
            //尾段B少子寿命均值
            ybInspectData.setWLifeEdge1(ybInspectDataQuote.getMeanCarrierLifetimeB());
        }
    }

    /**
     * 执行圆棒检验数据修改
     *
     * @param ybInspectDataCdto 本次上传的检验数据
     * @param ybInspectDataOld  该晶段的历史数据
     * @param isStatus          当前在制品状态是否满足 圆棒检验[待进站]
     * @return 是否成功
     */
    private Result execUpdateYbInspectData(YbInspectDataCUDto ybInspectDataCdto, YbInspectData ybInspectDataOld, boolean isStatus) {
        // 如果是人工上传数据
        if (ybInspectDataCdto.getId() != -1) {
            // 待进站状态，不允许修改数据
            if (isStatus) {
                return ResultGenerator.fail("圆棒检验[待进站]状态，不允许修改检验数据");
            }
            //人工上传数据时，如果
            if ((ybInspectDataOld == null || !ybInspectDataCdto.getId().equals(ybInspectDataOld.getId()))) {
                return ResultGenerator.fail("检验数据异常");
            }
        }
        //获取晶段属性
        String sectionType = defaultCrystalAttrService.getDefaultCrystalAttrOneTimes(ybInspectDataOld.getDopant(), ybInspectDataOld.getProductTypeSecond(), ybInspectDataOld.getProductLevel(), ybInspectDataOld.getSticksCount() != null && ybInspectDataOld.getSticksCount() > 1 ? ybInspectDataOld.getSpellBarLength() : ybInspectDataOld.getActualLength());
        // 更新本次数据
        BeanUtil.copyBeanPropWithOutNullValue(ybInspectDataOld, ybInspectDataCdto, "id");
        ybInspectDataOld.setUpdateTime(new Date());
        ybInspectDataOld.setUpdateUser(BaseContextHandler.getUsername());
        // 判断晶段类型
        ybInspectDataOld.setSectionType(sectionType);
        this.handleContentInfo(ybInspectDataOld, ybInspectDataOld.getCrystalNo());

        // 完结尾查询完结头氧值
        try {
            LongCrystal longCrystal = longCrystalService.findByCrystalNo(ybInspectDataOld.getCrystalNo());

            //更新缺失字段处理
            if (null != longCrystal) {
                //处理料号
                if (StringUtils.isBlank(ybInspectDataOld.getMaterialCode())) {
                    CrystalMaterialRelation bySectionNo = crystalMaterialRelationService.findBySectionNo(longCrystal.getCrystalNo());
                    if (null != bySectionNo) {
                        ybInspectDataOld.setMaterialCode(bySectionNo.getMaterialCode());
                        ybInspectDataOld.setOrderNo(bySectionNo.getOrderNo());
                        ybInspectDataOld.setWorkOrderNo(bySectionNo.getOrderNo());
                    }
                }
                ybInspectDataOld.setWorkOrderType(longCrystal.getOrderType());
                ybInspectDataOld.setArea(longCrystal.getSeries());
                ybInspectDataOld.setFactory(longCrystal.getArea());
                ybInspectDataOld.setAbbreviation(longCrystal.getSimpleName());
                //产品配方
                //ybInspectData.setFormulation(longCrystal.getProductName());
                //调整完结方式
                ybInspectDataOld.setClosureIdentification(StringUtils.equals(longCrystal.getWindUp(),EnumValuesServer.FINALIDENTIFICATION) ? "是" :"否");
            }
            if (null != longCrystal.getClosureIdentification() && longCrystal.getClosureIdentification().equals(EnumValuesServer.FINALIDENTIFICATION)) {
                setEndOxygenAndCarbon(ybInspectDataOld, longCrystal);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //处理
        Boolean ratedFlage = false;
        String sectionNo = ybInspectDataOld.getSectionNo();
        if (StringUtils.isNotBlank(sectionNo)) {
            Boolean individualFlage = sectionNo.endsWith("R");
            SectionNoDetail sectionNoDetail = sectionNoDetailService.findBySectionNo(sectionNo);
            if (null != sectionNoDetail && (sectionNo.endsWith("A") || sectionNo.endsWith("T")
                    || (null != sectionNoDetail.getSectionPosiotion() && sectionNoDetail.getSectionPosiotion() == 2) || individualFlage)) {
                String pieceNoHead = null;
                String pieceNoEnd = null;
                if (individualFlage) {
                    pieceNoHead = sectionNoDetail.getPieceNoHead();
                    pieceNoEnd = sectionNoDetail.getPieceNoEnd();
                } else {
                    pieceNoHead = this.handlePieceNo(sectionNoDetail.getCrystalNo() + "T", true);
                    pieceNoEnd = this.handlePieceNo(sectionNoDetail.getCrystalNo() + "A", false);
                }


                if (StringUtils.isNotBlank(pieceNoHead)) {
                    PieceCheck byPieceNo = pieceCheckService.getByPieceNo(pieceNoHead);
                    if (null == byPieceNo) {
                        ratedFlage = true;
                    } else {
                        ybInspectDataOld.setCarbonContentHead(byPieceNo.getcContents());
                        ybInspectDataOld.setOxygenContentHead(byPieceNo.getoContents());
                    }
                }
                if (StringUtils.isNotBlank(pieceNoEnd)) {
                    PieceCheck byPieceNoEnd = pieceCheckService.getByPieceNo(pieceNoEnd);
                    if (null == byPieceNoEnd) {
                        ratedFlage = true;
                    } else {
                        ybInspectDataOld.setCarbonContentTail(byPieceNoEnd.getcContents());
                        ybInspectDataOld.setOxygenContentTail(byPieceNoEnd.getoContents());
                    }
                }
            }

        }

        handleContentInfo(ybInspectDataOld, ybInspectDataOld.getCrystalNo());
        //需求修改，处理返切未检验数据
        if (GlobalSwitch.enable(GlobalSwitchNamespace.NAMESPACE_YB_CHECK, "AutomaticRoundBackCut", true)) {
            this.handleDefaultOxygenAndCarbonNew(ybInspectDataOld);
        }else {
            this.handleDefaultOxygenAndCarbon(ybInspectDataOld);
        }
        //卡控放在评级规则中
        ratedFlage = false;
        if (!ratedFlage) {
            Result<String> stringResult = saveDataAndGrade(ybInspectDataOld, false);
            if (null != stringResult && stringResult.getCode().equals("400")) {
                return stringResult;
            }
        } else {
            saveOrUpdate(ybInspectDataOld);
            PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCodeAndOrderType(sectionNo, EnumValuesFactory.PlanProcessingOrderOrderType.晶段.getKey());
            if (planProcessingOrder == null) {
                throw new BusinessException("工单不存在，请联系管理员!");
            }
            // 满足不能评级条件，直接创建评级记录
            createRuleTest(sectionNo, "等待样片检验数据不再触发评级!");
        }
        saveDataInspectLog(ybInspectDataOld);//保存圆棒检验记录表

        //添加逻辑 处理是否需要还原母单晶
        this.reducedMotheCrystal(ybInspectDataOld);
        //处理评级
        if (GlobalSwitch.enable(GlobalSwitchNamespace.NAMESPACE_YB_CHECK, "automaticInspectMiddleNew", true)) {
            this.handleAutomaticInspectMiddleNew(ybInspectDataOld);
        } else {
            this.handleAutomaticInspectMiddle(ybInspectDataOld);
        }
        return ResultGenerator.success();
    }


    /**
     * 给晶段赋值样片信息
     *
     * @param ybInspectData 检验数据
     * @param pieNoHead     头样片编号
     * @param pieNoEnd      尾样片编号
     */
    private void setSampleData(YbInspectData ybInspectData, String pieNoHead, String pieNoEnd, Integer segmentNum) {
       /* DefaultSample sample = defaultSampleService.findByDopantLikeAndSpecificationsLike(ybInspectData.getDopant(), ybInspectData.getProductTypeSecond());
        if (sample == null) {
            throw new BusinessException("[" + ybInspectData.getDopant() + "]/[" + ybInspectData.getProductTypeSecond() + "]该规格的样片没有设置默认值");
        }*/
        // 头片信息
        if (StringUtils.isNotBlank(pieNoHead)) {
            List<PieceCheck> pieceChecks = pieceCheckDAO.findByPieceNo(pieNoHead);
            if (pieceChecks.size() > 0 && pieceChecks.get(0) != null) {
                // 氧含量中心不找默认值
                ybInspectData.setOxygenContentHead(pieceChecks.get(0).getoContents());
                // 碳含量中心不找默认值
                ybInspectData.setCarbonContentHead(pieceChecks.get(0).getcContents());
            }
        }/* else {
            ybInspectData.setOxygenContentHead(NumberUtil.Object2BigDecimal(sample.getOxygenCenter(), null));
            ybInspectData.setCarbonContentHead(NumberUtil.Object2BigDecimal(sample.getCarbonCenter(), null));
        }*/

        // 尾片信息
        //有样片信息
        if (StringUtils.isNotBlank(pieNoEnd)) {
            List<PieceCheck> pieces = pieceCheckDAO.findByPieceNo(pieNoEnd);
            if (!pieces.isEmpty() && pieces.get(0) != null) {
                // 氧含量中心不找默认值
                ybInspectData.setOxygenContentTail(pieces.get(0).getoContents());
                // 碳含量中心不找默认值
                ybInspectData.setCarbonContentTail(pieces.get(0).getcContents());
            }
        }/* else {
            // 无样片信息则使用默认值
            ybInspectData.setOxygenContentTail(NumberUtil.Object2BigDecimal(sample.getOxygenCenter()));
            ybInspectData.setCarbonContentTail(NumberUtil.Object2BigDecimal(sample.getCarbonCenter()));
        }*/

        // 寻找首段碳氧含量
        if (StringUtils.isBlank(pieNoHead)) {
            SectionNoDetail sectionNoDetails = sectionNoDetailService.findByCrystalNoAndSegmentNumLessThan(ybInspectData.getCrystalNo(), segmentNum);
            if (sectionNoDetails != null) {
                String pieNo = StringUtils.isNotBlank(sectionNoDetails.getPieceNoEnd()) ? sectionNoDetails.getPieceNoEnd() : sectionNoDetails.getPieceNoHead();
                List<PieceCheck> pieceChecks = pieceCheckDAO.findByPieceNo(pieNo);
                if (!pieceChecks.isEmpty() && pieceChecks.get(0) != null) {
                    ybInspectData.setOxygenContentFirsta(pieceChecks.get(0).getoContents());
                    ybInspectData.setCarbonContentFirsta(pieceChecks.get(0).getcContents());
                }
            }
        }

        // 寻找尾段段碳氧含量
        if (StringUtils.isBlank(pieNoEnd)) {
            SectionNoDetail sectionNoDetails = sectionNoDetailService.findByCrystalNoAndSegmentNumGreaterThan(ybInspectData.getCrystalNo(), segmentNum);
            if (sectionNoDetails != null) {
                String pieNo = StringUtils.isNotBlank(sectionNoDetails.getPieceNoHead()) ? sectionNoDetails.getPieceNoHead() : sectionNoDetails.getPieceNoEnd();
                List<PieceCheck> pieceChecks = pieceCheckDAO.findByPieceNo(pieNo);
                if (!pieceChecks.isEmpty() && pieceChecks.get(0) != null) {
                    ybInspectData.setOxygenContentEndb(pieceChecks.get(0).getoContents());
                    ybInspectData.setCarbonContentEndb(pieceChecks.get(0).getcContents());
                }
            }
        }
    }

    private void setEndOxygenAndCarbon(YbInspectData ybInspectDataOld, LongCrystal longCrystal) {
        List<PieceCheck> piece = pieceCheckDAO.findCountByMotherCrystalNo(longCrystal.getCrystalNo());
        piece.sort(Comparator.comparing(PieceCheck::getCheckTime2).reversed());
        if (CollectionUtils.isNotEmpty(piece)) {
            for (PieceCheck pieceCheck : piece) {
                if (pieceCheck.getPieceNo().endsWith("TP")) {
                    ybInspectDataOld.setEndCarbonContentHead(pieceCheck.getcContents());
                    ybInspectDataOld.setEndOxygenContentHead(pieceCheck.getoContents());
                    break;
                }
            }
            for (PieceCheck pieceCheck : piece) {
                if (pieceCheck.getPieceNo().endsWith("WP")) {
                    ybInspectDataOld.setEndCarbonContentTail(pieceCheck.getcContents());
                    ybInspectDataOld.setEndOxygenContentTail(pieceCheck.getoContents());
                    break;
                }
            }
        }
        if (ybInspectDataOld.getEndCarbonContentTail().compareTo(new BigDecimal(0)) == 0) {
            ybInspectDataOld.setEndCarbonContentTail(ybInspectDataOld.getCarbonContentTail());
        }
        if (ybInspectDataOld.getEndOxygenContentTail().compareTo(new BigDecimal(0)) == 0) {
            ybInspectDataOld.setEndOxygenContentTail(ybInspectDataOld.getOxygenContentTail());
        }
    }

    @Override
    public void saveDataAndGrade(YbInspectData ybInspectData) {
        saveDataAndGrade(ybInspectData, false);
    }

    @Override
    public Result<String> saveDataAndGrade(YbInspectData ybInspectData, boolean mandatoryTrigger) {
        Result<String> stringResult = null;
        saveOrUpdate(ybInspectData);

        PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCodeAndOrderType(ybInspectData.getSectionNo(), EnumValuesFactory.PlanProcessingOrderOrderType.晶段.getKey());
        if (planProcessingOrder == null) {
            throw new BusinessException("工单不存在，请联系管理员");
        }
        String message = getGradeStatus(ybInspectData.getSticksCount(), planProcessingOrder);
        // 满足不能评级条件，直接创建评级记录
        if (message != null && !mandatoryTrigger) {
            createRuleTest(ybInspectData.getSectionNo(), message + "不再触发评级");
        }
        //执行评级
        else {
            Map<String, YbInspectData> map = new HashMap<>();
            map.put(ybInspectData.getSectionNo(), ybInspectData);
            gradeService.execGrade(map);
            ybInspectData = map.get(ybInspectData.getSectionNo());
            //处理是否需要反切， 晶段去找对应的评级返切规则,自动生成返切画线记录
            stringResult = productionRecutService.execProductionBackCuttingRecord(ybInspectData);
            //调整逻辑，添加触发点，评级为返切不复测时，后面段都给默认值
            if (StringUtils.isNotBlank(ybInspectData.getProductLevel()) && ybInspectData.getProductLevel().contains("返切不复测")) {
                this.handleRecutSectionNo(ybInspectData);
            }
        }
        //修改工单重量与长度
        updatePlanProcessingOrderInfo(ybInspectData.getTheoryWeight(), ybInspectData.getActualLength(), planProcessingOrder);
        //重新计算直径平均值
        dao.recalculateAllAvgDiameter(ybInspectData.getCrystalNo());
        //异步发送检验信息变动mq消息
        inspectDataBaseChangeAsync.inspectDataBaseChange(ybInspectData);
        return stringResult;
    }

    /**
     * 处理返切不复测专用方法
     *
     * @param ybInspectData
     */
    private void handleRecutSectionNo(YbInspectData ybInspectData) {

        log.info("==处理返切不复测专用方法==={}", JSONObject.toJSONString(ybInspectData));
        if (null == ybInspectData || StringUtils.isBlank(ybInspectData.getCrystalNo()) || null == ybInspectData.getPiecewiseNum()) {
            return;
        }
        List<SectionNoDetail> byCrystalNoAndSectionPosiotion = sectionNoDetailService.findByCrystalNoAndSectionPosiotion(ybInspectData.getCrystalNo(), ybInspectData.getPiecewiseNum());
        if (null != byCrystalNoAndSectionPosiotion) {
            List<String> sectionNolist = new ArrayList<>();
            for (SectionNoDetail sectionNoDetail : byCrystalNoAndSectionPosiotion) {
                sectionNolist.add(sectionNoDetail.getSectionNo());
            }
            if (sectionNolist.size() != 0) {

                List<YbInspectData> bySections = this.findBySections(sectionNolist);
                if (CollectionUtils.isNotEmpty(bySections)) {
                    DefaultSample defaultSample = defaultSampleService.findByDopantLikeAndSpecificationsLikeAndProductTypeLike(ybInspectData.getDopant(), ybInspectData.getProductTypeSecond(), ybInspectData.getProductType());
                    Map<String, YbInspectData> map = new HashMap<>();

                    for (YbInspectData ybInspectData1 : bySections) {
                        ybInspectData1.setOxygenContentHead(NumberUtil.Object2BigDecimal(defaultSample.getOxygenCenterHead(), null));
                        //注释W氧含量中心 赋默认值
                        //ybInspectData1.setOxygenContentTail(NumberUtil.Object2BigDecimal(defaultSample.getOxygenCenterTail(), null));
                        //先保存
                        this.saveOrUpdate(ybInspectData1);
                        //添加判断，站点在检验需要评级
                        List<WipStorage> wipStorageList = wipStorageService.findByProcessingByOrderCode(ybInspectData1.getSectionNo());
                        if (!org.springframework.util.CollectionUtils.isEmpty(wipStorageList)) {
                            WipStorage wipStorage = wipStorageList.get(0);
                            if (org.apache.commons.lang3.StringUtils.equals(wipStorage.getProcessName(), EnumValuesFactory.WipStorageCode.圆棒检验.getValue())) {
                                map.put(ybInspectData1.getSectionNo(), ybInspectData1);
                            }
                        }
                    }
                    gradeService.execGrade(map);
                }
            }
        }
    }

    @Override
    public void saveAndLog(YbInspectData inspectDataBase, DataInspectLog dataInspectLog) {
        dataInspectLogService.saveOrUpdate(dataInspectLog);
        dao.save(inspectDataBase);
    }

    @Override
    public String getGradeStatus(Integer sticksCount, PlanProcessingOrder planProcessingOrder) {
        String message = null;
        // 1.不是加工中状态，不再触发评级
        if (planProcessingOrder.getStatus() != EnumValuesFactory.PlanProcessingOrderStatus.加工中.getKey()) {
            message = "当前工单状态为：" + EnumValuesFactory.PlanProcessingOrderStatus.getText(planProcessingOrder.getStatus()) + "，不是加工中状态；";
        }
        // 2.已经是拼棒，不再触发评级
        if (sticksCount != null && sticksCount > 1) {
            message = "已经是拼棒；";
        }
        // 3.在制品站点不满足，不进行评级
        //   不在圆棒检验，并且不在截断待进站，就不进行评级
        if (planProcessingOrder.getWipStorage() != null) {
            FactoryModel factoryModel = wipStorageService.getFactoryModel(planProcessingOrder.getWipStorage().getProcessId(), planProcessingOrder.getWipStorage().getProcessName());
            //不在圆棒检验，并且不在截断待进站，就不进行评级
            boolean isGrade = !EnumValuesFactory.WipStorageCode.圆棒检验.getKey().equals(factoryModel.getCode()) && !(planProcessingOrder.getMaterialType() == EnumValuesFactory.MaterialType.圆棒.getKey() && EnumValuesFactory.WipStorageCode.圆棒截断.getKey().equals(factoryModel.getCode()) && planProcessingOrder.getWipStorage().getStatus() == EnumValuesFactory.WipStorageStatus.待进站.getKey());
            if (isGrade) {
                message = "当前站点为：" + EnumValuesFactory.WipStorageCode.getText(factoryModel.getCode()) + EnumValuesFactory.WipStorageStatus.getText(planProcessingOrder.getWipStorage().getStatus()) + "，不在圆棒检验和圆棒截断待进站；";
            }
        }
        return message;
    }

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

    /**
     * 满足不能评级条件，直接创建评级记录
     *
     * @param sectionNo 晶段编号
     * @param message   不能评级备注
     */
    private void createRuleTest(String sectionNo, String message) {
        RuleTest ruleTest = new RuleTest();
        ruleTest.setGradeVersion(null);
        ruleTest.setGmtUpdate(new Date());
        ruleTest.setUserUpdate(BaseContextHandler.getUsername());
        ruleTest.setRemarks("正常评级-检验数据变动");
        ruleTestService.saveOrUpdate(ruleTest);
        List<RuleTestData> ruleTestDatas = new LinkedList<>();
        RuleTestData ruleTestData = new RuleTestData();
        ruleTestData.setGmtUpdate(new Date());
        ruleTestData.setUserUpdate(BaseContextHandler.getUsername());
        ruleTestData.setRuleTestId(ruleTest.getId());
        ruleTestData.setSectionNo(sectionNo);
        gradeService.setRuleTestData(ruleTestData, message);
        ruleTestDatas.add(ruleTestData);
        ruleTestDataService.saveAll(ruleTestDatas);
    }

    @Override
    public List<String> findByAllSectionNo() {
        return dao.findByAllSectionNo();
    }

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

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

    @Override
    public void updateOrderNoBySectionNo(String sectionNo, String orderNo) {
        dao.updateOrderNoBySectionNo(sectionNo, orderNo);
    }

    @Override
    public void updateOrderNoAndModelCodeBySectionNo(String sectionNo, String orderNo, String materialCode) {
        dao.updateOrderNoAndModelCodeBySectionNo(sectionNo, orderNo, materialCode);
    }

    @Override
    public void updateSticksCountFbSectionNoListFromYb(List<String> sectionNos, int i, Object o, String
            sectionType, Object o1) {
        dao.updateSticksCountFbSectionNoListFromYb(sectionNos, 1, null, sectionType, null);
    }

    @Override
    public Result<GetFbInfoDto> findInfoByYbNo(String sectionNoYb) {
        GetFbInfoDto getFbInfoDto = new GetFbInfoDto();
        List<SectionNoDetail> bySectionNo = this.sectionNoDetailDao.findBySectionNo(sectionNoYb);
        if (bySectionNo != null && bySectionNo.size() > 0) {
            SectionNoDetail sectionNoDetail = bySectionNo.get(0);
            if (!sectionNoYb.startsWith("B") && sectionNoDetail.getCrystalId() != null) {
                LongCrystal longCrystal = this.longCrystalService.get(sectionNoDetail.getCrystalId());
                getFbInfoDto.setOrderType(longCrystal.getOrderType());
                getFbInfoDto.setCrystalNo(longCrystal.getCrystalNo());
                getFbInfoDto.setPlanOrderType(longCrystal.getOrderType());
                getFbInfoDto.setPlanGrade(longCrystal.getProductGrade());
                getFbInfoDto.setPlanOrderNo(longCrystal.getOrderNo());
                getFbInfoDto.setSideLengthRange(longCrystal.getSideLengthRange());
                getFbInfoDto.setBatchNo(longCrystal.getBatchNo());
                getFbInfoDto.setMaterialCode(longCrystal.getProductCode());
            }
            if (StringUtils.isBlank(getFbInfoDto.getBatchNo())) {
                LongCrystal byCrystalNo = longCrystalService.findByCrystalNo(sectionNoDetail.getCrystalNo());
                getFbInfoDto.setBatchNo(byCrystalNo.getBatchNo());
                getFbInfoDto.setMaterialCode(byCrystalNo.getProductCode());
            }
        }
        //从长晶棒拿方棒边长属性
        if (null != sectionNoYb && sectionNoYb.length() > 12) {

            String fromMark = sectionNoYb.substring(SectionIndexRangeEnum.基地追溯产品类型.getBeginIndex(), SectionIndexRangeEnum.基地追溯产品类型.getEndIndex());
            LongCrystal byCrystalNo = null;
            if (fromMark.matches("[A-Z]+")) {
                byCrystalNo = longCrystalService.findByCrystalNo(sectionNoYb.substring(SectionIndexRangeEnum.毛棒范围.getBeginIndex(), SectionIndexRangeEnum.毛棒范围.getEndIndex()));
                if (null != byCrystalNo && null != byCrystalNo.getSideLengthRange()) {
                    getFbInfoDto.setSideLengthRange(byCrystalNo.getSideLengthRange());
                }
            } else {
                byCrystalNo = longCrystalService.findByCrystalNo(sectionNoYb.substring(0, 12));
                if (null != byCrystalNo && null != byCrystalNo.getSideLengthRange()) {
                    getFbInfoDto.setSideLengthRange(byCrystalNo.getSideLengthRange());
                }
            }
        }
        YbInspectData ybInspectData = findBySectionNo(sectionNoYb);
        if (ybInspectData == null) {
            return ResultGenerator.success(getFbInfoDto);
        }
        getFbInfoDto.setConductionType(ybInspectData.getConductiveType());
//        getFbInfoDto.setInstoreLengthYb(ybInspectData.getWareHouseLength());
        getFbInfoDto.setLength(ybInspectData.getActualLength());
        getFbInfoDto.setProductLevel(ybInspectData.getProductLevel());
        getFbInfoDto.setDopant(ybInspectData.getDopant());
        getFbInfoDto.setOrderNo(ybInspectData.getOrderNo());
        getFbInfoDto.setYbExperiLevel(ybInspectData.getExperiLevel());
        getFbInfoDto.setYbSectionNo(ybInspectData.getSectionNo());
//        getFbInfoDto.setDiamDecide(ybInspectData.getDiamDecide());
//        getFbInfoDto.setFineDiameter(ybInspectData.getFineDiameter());
//        getFbInfoDto.setFineCutLength(ybInspectData.getFineCutLength());
        getFbInfoDto.setProductTypeSecond(ybInspectData.getProductTypeSecond());
        getFbInfoDto.setSectionCompose(ybInspectData.getSectionCompose());
        getFbInfoDto.setProductLevelExperiment(ybInspectData.getProductLevelExperiment());
        getFbInfoDto.setSticksCount(ybInspectData.getSticksCount());
        getFbInfoDto.setSpellBarLength(ybInspectData.getSpellBarLength());
        getFbInfoDto.setStickCount(ybInspectData.getSticksCount());
        getFbInfoDto.setProductType(ybInspectData.getProductType());
        getFbInfoDto.setPiecewiseNum(ybInspectData.getPiecewiseNum());
        getFbInfoDto.setHeadTailRecognition(ybInspectData.getHeadTailRecognition());
        if (null != ybInspectData.getSideLengthRange()) {
            getFbInfoDto.setSideLengthRange(ybInspectData.getSideLengthRange());
        }
        if (null != ybInspectData.getMaterialCode()) {
            getFbInfoDto.setMaterialCode(ybInspectData.getMaterialCode());
        }
        getFbInfoDto.setCarbonContentHead(ybInspectData.getCarbonContentHead());
        getFbInfoDto.setCarbonContentTail(ybInspectData.getCarbonContentTail());
        getFbInfoDto.setMeanResistivityA(ybInspectData.getMeanResistivityA());
        getFbInfoDto.setMeanResistivityB(ybInspectData.getMeanResistivityB());
        getFbInfoDto.setMeanCarrierLifetimeA(ybInspectData.getMeanCarrierLifetimeA());
        getFbInfoDto.setMeanCarrierLifetimeB(ybInspectData.getMeanCarrierLifetimeB());
        getFbInfoDto.setTCarrierLifetime(ybInspectData.getTCentreLife());
        getFbInfoDto.setWCentreLife(ybInspectData.getWCentreLife());
        getFbInfoDto.setTResistivity(ybInspectData.getTResistivity());
        getFbInfoDto.setWResistivity(ybInspectData.getWResistivity());
        getFbInfoDto.setTLifeEdge1(ybInspectData.getTLifeEdge1());
        getFbInfoDto.setWCarrierLifetime(ybInspectData.getWLifeEdge1());
        getFbInfoDto.setAbbreviation(ybInspectData.getAbbreviation());
        getFbInfoDto.setFormulation(ybInspectData.getFormulation());
        getFbInfoDto.setOxygenContentHead(ybInspectData.getOxygenContentHead());
        getFbInfoDto.setOxygenContentTail(ybInspectData.getOxygenContentTail());
        getFbInfoDto.setCarbonContentHead(ybInspectData.getCarbonContentHead());
        getFbInfoDto.setCarbonContentTail(ybInspectData.getCarbonContentTail());
        getFbInfoDto.setResistivityAOne(ybInspectData.getResistivityAOne());
        getFbInfoDto.setResistivityATwo(ybInspectData.getResistivityATwo());
        getFbInfoDto.setResistivityAThree(ybInspectData.getResistivityAThree());
        getFbInfoDto.setResistivityBOne(ybInspectData.getResistivityBOne());
        getFbInfoDto.setResistivityBTwo(ybInspectData.getResistivityBTwo());
        getFbInfoDto.setResistivityBThree(ybInspectData.getResistivityBThree());

        getFbInfoDto.setCarrierLifetimeAOne(ybInspectData.getCarrierLifetimeAOne());
        getFbInfoDto.setCarrierLifetimeATwo(ybInspectData.getCarrierLifetimeATwo());
        getFbInfoDto.setCarrierLifetimeAThree(ybInspectData.getCarrierLifetimeAThree());
        getFbInfoDto.setCarrierLifetimeBOne(ybInspectData.getCarrierLifetimeBOne());
        getFbInfoDto.setCarrierLifetimeBTwo(ybInspectData.getCarrierLifetimeBTwo());
        getFbInfoDto.setCarrierLifetimeBThree(ybInspectData.getCarrierLifetimeBThree());
        //导电型号
        getFbInfoDto.setConductionType(ybInspectData.getConductiveType());
        //规格
        getFbInfoDto.setSpecification(ybInspectData.getProductTypeSecond());
        getFbInfoDto.setOutGoing(ybInspectData.getOutGoing());
        getFbInfoDto.setRatingTime(ybInspectData.getLevelTime());
        getFbInfoDto.setCheckDate(ybInspectData.getInspectionDate());

        //圆棒长度
        getFbInfoDto.setInstoreLengthYb(ybInspectData.getActualLength());
        getFbInfoDto.setSectionType(ybInspectData.getSectionType());
        getFbInfoDto.setLevelCode(ybInspectData.getLevelCode());
        getFbInfoDto.setClosureIdentification(ybInspectData.getClosureIdentification());
        getFbInfoDto.setCrystalWorkshop(ybInspectData.getCrystalWorkshop());
        getFbInfoDto.setArea(ybInspectData.getArea());
        getFbInfoDto.setFurnaceType(ybInspectData.getFurnaceType());
        getFbInfoDto.setFactory(ybInspectData.getFactory());
        getFbInfoDto.setLotNo(ybInspectData.getLotNo());
        getFbInfoDto.setGradeVersion(ybInspectData.getGradeVersion());
        getFbInfoDto.setCheckUserName(ybInspectData.getCheckoutName());
        // 新增检验数据
        getFbInfoDto.setOxygenContentFirsta(ybInspectData.getOxygenContentFirsta());
        getFbInfoDto.setCarbonContentFirsta(ybInspectData.getCarbonContentFirsta());
        getFbInfoDto.setOxygenContentEndb(ybInspectData.getOxygenContentEndb());
        getFbInfoDto.setCarbonContentEndb(ybInspectData.getCarbonContentEndb());
        return ResultGenerator.success(getFbInfoDto);
    }

    @Override
    public YbInspectDataToMcsDto getPinKuData(YbInspectData inspectDataBase, RankResultDto rankResultDto) {
        YbInspectDataToMcsDto ybInspectDataToMcsDto = new YbInspectDataToMcsDto();
        if (null != inspectDataBase) {
//            BeanUtil.copyBeanPropWithNullValue(ybInspectDataToMcsDto, inspectDataBase, "id");

            ybInspectDataToMcsDto.setSectionNo(inspectDataBase.getSectionNo());
            ybInspectDataToMcsDto.setProductTypeSecond(inspectDataBase.getProductTypeSecond());
            ybInspectDataToMcsDto.setActualLength(inspectDataBase.getActualLength());
            ybInspectDataToMcsDto.setProductType(inspectDataBase.getProductType());
            ybInspectDataToMcsDto.setConductiveType(inspectDataBase.getConductiveType());
            ybInspectDataToMcsDto.setOrderNo(inspectDataBase.getOrderNo());
            ybInspectDataToMcsDto.setProductLevel(inspectDataBase.getProductLevel());
            ybInspectDataToMcsDto.setGradeType(inspectDataBase.getGradeType());
            ybInspectDataToMcsDto.setPullType(inspectDataBase.getPullType());

            ybInspectDataToMcsDto.setTradialCentre(NumberUtil.object2String(inspectDataBase.getTRadialCentre(), null));
            ybInspectDataToMcsDto.setWradialCentre(NumberUtil.object2String(inspectDataBase.getWRadialCentre(), null));
            ybInspectDataToMcsDto.setTcentreLife(NumberUtil.object2String(inspectDataBase.getTCentreLife(), null));
            ybInspectDataToMcsDto.setWcentreLife(NumberUtil.object2String(inspectDataBase.getWCentreLife(), null));
            ybInspectDataToMcsDto.setOxygenContentHead(NumberUtil.object2String(inspectDataBase.getOxygenContentHead(), null));
            ybInspectDataToMcsDto.setOxygenContentTail(NumberUtil.object2String(inspectDataBase.getOxygenContentTail(), null));
            ybInspectDataToMcsDto.setCarbonContentHead(NumberUtil.object2String(inspectDataBase.getCarbonContentHead(), null));
            ybInspectDataToMcsDto.setCarbonContentTail(NumberUtil.object2String(inspectDataBase.getCarbonContentTail(), null));

            if (null != rankResultDto) {
                ybInspectDataToMcsDto.setProductLevel(rankResultDto.getProductRank());
                ybInspectDataToMcsDto.setProductTypeSecond(rankResultDto.getSpecs());
                ybInspectDataToMcsDto.setSectionNo(rankResultDto.getSectionNo());
                if (null != rankResultDto.getLength()) {
                    ybInspectDataToMcsDto.setActualLength(rankResultDto.getLength());
                }
                ybInspectDataToMcsDto.setGradeType(rankResultDto.getGradeType());
            }
            //todo    if(!StringUtils.isBlank(ybInspectDataToMcsDto.getProductLevel()) && (ybInspectDataToMcsDto.getProductLevel().equals("A1") || ybInspectDataToMcsDto.getProductLevel().equals("晶昇A2"))){
            if (!StringUtils.isBlank(ybInspectDataToMcsDto.getProductLevel()) && (ybInspectDataToMcsDto.getProductLevel().equals("A1") || ybInspectDataToMcsDto.getProductLevel().equals("A2"))) {
                ybInspectDataToMcsDto.setCarbonContentHead("合格");
                ybInspectDataToMcsDto.setCarbonContentTail("合格");
                ybInspectDataToMcsDto.setOxygenContentHead("合格");
                ybInspectDataToMcsDto.setOxygenContentTail("合格");
                ybInspectDataToMcsDto.setTradialCentre("合格");
                ybInspectDataToMcsDto.setWradialCentre("合格");
                ybInspectDataToMcsDto.setTcentreLife("合格");
                ybInspectDataToMcsDto.setWcentreLife("合格");
            } else if (!StringUtils.isBlank(ybInspectDataToMcsDto.getProductLevel())) {
                ybInspectDataToMcsDto.setCarbonContentHead("不合格");
                ybInspectDataToMcsDto.setCarbonContentTail("不合格");
                ybInspectDataToMcsDto.setOxygenContentHead("不合格");
                ybInspectDataToMcsDto.setOxygenContentTail("不合格");
                ybInspectDataToMcsDto.setTradialCentre("不合格");
                ybInspectDataToMcsDto.setWradialCentre("不合格");
                ybInspectDataToMcsDto.setTcentreLife("不合格");
                ybInspectDataToMcsDto.setWcentreLife("不合格");
            } else {
                ybInspectDataToMcsDto.setCarbonContentHead("");
                ybInspectDataToMcsDto.setCarbonContentTail("");
                ybInspectDataToMcsDto.setOxygenContentHead("");
                ybInspectDataToMcsDto.setOxygenContentTail("");
                ybInspectDataToMcsDto.setTradialCentre("");
                ybInspectDataToMcsDto.setWradialCentre("");
                ybInspectDataToMcsDto.setTcentreLife("");
                ybInspectDataToMcsDto.setWcentreLife("");
            }
//            if(!StringUtils.isBlank(ybInspectDataToMcsDto.getGradeType())){
//                List<CodingRecord> codingRecordBySectionNo = codingRecordService.getCodingRecordBySectionNo(ybInspectDataToMcsDto.getSectionNo());
//                //todo    if(null != codingRecordBySectionNo && codingRecordBySectionNo.size() > 0 && ybInspectDataToMcsDto.getProductLevel().equals("晶昇A2")){
//                if(null != codingRecordBySectionNo && codingRecordBySectionNo.size() > 0 && ybInspectDataToMcsDto.getProductLevel().equals("A2")){
//                    if(codingRecordBySectionNo.size() == 1 && (ybInspectDataToMcsDto.getGradeType().equals("正常") || ybInspectDataToMcsDto.getGradeType().equals("转规格"))){
//                        ybInspectDataToMcsDto.setGradeType("复测");
//                    }
//                }
//            }
            if (StringUtils.isBlank(ybInspectDataToMcsDto.getGradeType())) {
                ybInspectDataToMcsDto.setGradeType(null);
            }
        }
        return ybInspectDataToMcsDto;
    }

    @Override
    public List<YbInspectData> getDataByCrystalNo(String crystalNo) {
        return dao.findByCrystalNo1(crystalNo);
    }

    @Override
    @Transactional
    public Result readResultsImportMk(MultipartFile file) throws Exception {
        Map<String, List<Map<String, Object>>> excelMap;
        try {
            excelMap = ExcelUtil.getExcelInfo(file);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("文件导入异常！" + e.getMessage());
        }

        if (!excelMap.isEmpty()) {
            Collection<List<Map<String, Object>>> collection = excelMap.values();
            Iterator<List<Map<String, Object>>> iterator = collection.iterator();
            //遍历excel文件的内容
            while (iterator.hasNext()) {
                List<Map<String, Object>> list = iterator.next();
                for (Map<String, Object> map : list) {
                    YbInspectDataCUDto ybInspectDataCUDto = new YbInspectDataCUDto();
                    YbInspectData ybInspectData = new YbInspectData();
                    //1对单晶条码编号的校验
                    String ybSectionNo = StringUtils.valueOf(map.get("晶段编号")).toUpperCase();
                    if (StringUtils.isBlank(ybSectionNo)) {
                        throw new Exception("请输入晶段编号！");
                    }
                    ybInspectData.setSectionNo(ybSectionNo);

                    //电阻率T中心点
                    String headRadiaCentre = StringUtils.valueOf(map.get("电阻率T中心点"));
                    if (StringUtils.isBlank(headRadiaCentre)) {
                        throw new Exception("请输入电阻率T中心点！");
                    }
                    ybInspectData.setTRadialCentre(new BigDecimal(headRadiaCentre));
                    //电阻率T边缘1
                    String radiaCentreEdge1 = StringUtils.valueOf(map.get("电阻率T边缘1")).toUpperCase();
                    if (StringUtils.isBlank(radiaCentreEdge1)) {
                        throw new Exception("请输入电阻率T边缘1！");
                    }
                    ybInspectData.setTRadialEdge1(new BigDecimal(radiaCentreEdge1));
                    //电阻率T边缘2
                    String radiaCentreEdge2 = StringUtils.valueOf(map.get("电阻率T边缘2")).toUpperCase();
                    if (StringUtils.isBlank(radiaCentreEdge2)) {
                        throw new Exception("请输入电阻率T边缘2！");
                    }
                    ybInspectData.setTRadialEdge2(new BigDecimal(radiaCentreEdge2));
                    //电阻率W中心点
                    String tailRadiaCentre = StringUtils.valueOf(map.get("电阻率W中心点")).toUpperCase();
                    if (StringUtils.isBlank(tailRadiaCentre)) {
                        throw new Exception("请输入电阻率W中心点！");
                    }
                    ybInspectData.setWRadialCentre(new BigDecimal(tailRadiaCentre));
                    //电阻率W边缘1
                    String tailCentreEdge1 = StringUtils.valueOf(map.get("电阻率W边缘1")).toUpperCase();
                    if (StringUtils.isBlank(tailCentreEdge1)) {
                        throw new Exception("请输入电阻率W边缘1！");
                    }
                    ybInspectData.setWRadialEdge1(new BigDecimal(tailCentreEdge1));
                    //电阻率W边缘2
                    String tailCentreEdge2 = StringUtils.valueOf(map.get("电阻率W边缘2")).toUpperCase();
                    if (StringUtils.isBlank(tailCentreEdge2)) {
                        throw new Exception("请输入电阻率W边缘2！");
                    }
                    ybInspectData.setWRadialEdge2(new BigDecimal(tailCentreEdge2));
                    //T中心寿命
                    String headLifeCentre = StringUtils.valueOf(map.get("T中心寿命")).toUpperCase();
                    if (StringUtils.isBlank(headLifeCentre)) {
                        throw new Exception("请输入T中心寿命！");
                    }
                    ybInspectData.setTCentreLife(new BigDecimal(headLifeCentre));
                    //T边缘寿命1
                    String headLifeEdge1 = StringUtils.valueOf(map.get("T边缘寿命1")).toUpperCase();
                    if (StringUtils.isBlank(headLifeEdge1)) {
                        throw new Exception("请输入T边缘寿命1！");
                    }
                    ybInspectData.setTLifeEdge1(new BigDecimal(headLifeEdge1));
                    //T边缘寿命2
                    String headLifeEdge2 = StringUtils.valueOf(map.get("T边缘寿命2")).toUpperCase();
                    if (StringUtils.isBlank(headLifeEdge2)) {
                        throw new Exception("请输入T边缘寿命2！");
                    }
                    ybInspectData.setTLifeEdge2(new BigDecimal(headLifeEdge2));
                    //W中心寿命
                    String tailLifeCentre = StringUtils.valueOf(map.get("W中心寿命")).toUpperCase();
                    if (StringUtils.isBlank(tailLifeCentre)) {
                        throw new Exception("请输入W中心寿命！");
                    }
                    ybInspectData.setWCentreLife(new BigDecimal(tailLifeCentre));
                    //T边缘寿命1
                    String tailLifeEdge1 = StringUtils.valueOf(map.get("W边缘寿命1")).toUpperCase();
                    if (StringUtils.isBlank(tailLifeEdge1)) {
                        throw new Exception("请输入W边缘寿命1！");
                    }
                    ybInspectData.setWLifeEdge1(new BigDecimal(tailLifeEdge1));
                    //T边缘寿命2
                    String tailLifeEdge2 = StringUtils.valueOf(map.get("W边缘寿命2")).toUpperCase();
                    if (StringUtils.isBlank(tailLifeEdge2)) {
                        throw new Exception("请输入W边缘寿命2！");
                    }
                    ybInspectData.setWLifeEdge2(new BigDecimal(tailLifeEdge2));
                    //外观检验返切
                    String recut = StringUtils.valueOf(map.get("外观检验返切")).toUpperCase();
                    if (StringUtils.isBlank(recut)) {
                        throw new Exception("请输入外观检验返切！");
                    }
                    ybInspectData.setCheckReback(recut);
                    // 检验数据提交判断是否在圆棒检验待进站状态
                    wipStorageService.selectWipStorage(ybSectionNo, EnumValuesFactory.WipStorageCode.圆棒检验.getKey(), false);

                    ProductionPaintingLineDetail bySegmentNo = productionPaintingLineDetailService.findBySegmentNo(ybSectionNo);
                    if (bySegmentNo == null) {
                        throw new Exception("该圆棒单晶编号：" + bySegmentNo + "划线记录不存在");
                    }
                    YbInspectData no = findBySectionNo(ybSectionNo);
                    if (no != null) {
                        throw new Exception("该圆棒单晶编号：" + ybSectionNo + "圆棒检验数据已存在");
                    }
                    ybInspectData.setSectionNo(ybSectionNo);
                    if (null == no) {
                        // 通过圆棒编号 去追溯表判断晶段是否存在
                        SectionNoDetail sectionNoDetail = sectionNoDetailService.findBySectionNo(ybSectionNo);
                        if (sectionNoDetail == null) {
                            return ResultGenerator.fail(ybSectionNo + "晶段信息不存在，数据异常");
                        }
                        LongCrystal longCrystal = longCrystalService.get(sectionNoDetail.getCrystalId());
                        if (longCrystal == null) {
                            return ResultGenerator.fail(ybSectionNo + "长棒信息不存在，数据异常");
                        }
                        ybInspectData.setClosureIdentification(StringUtils.equals(longCrystal.getWindUp(),EnumValuesServer.FINALIDENTIFICATION) ? "是" :"否");
                        ybInspectData.setDiameterMax(longCrystal.getMaxDiam());
                        ybInspectData.setDiameterMin(longCrystal.getMinDiam());
                        initInspectData(ybInspectData, sectionNoDetail, longCrystal);
                    }

                    String fromMark = ybSectionNo.substring(SectionIndexRangeEnum.基地追溯产品类型.getBeginIndex(), SectionIndexRangeEnum.基地追溯产品类型.getEndIndex());
                    if (fromMark.matches("[A-Z]+")) {
                        ybInspectData.setCrystalNo(ybSectionNo.substring(SectionIndexRangeEnum.毛棒范围.getBeginIndex(), SectionIndexRangeEnum.毛棒范围.getEndIndex()));
                    } else {
                        ybInspectData.setCrystalNo(ybSectionNo.substring(0, 12));
                    }
                    ybInspectData.setInspector(BaseContextHandler.getUsername());
                    ybInspectData.setCreateTime(new Date());
                    //实测重量
                    ybInspectData.setActualWeight(ybInspectData.getActualLength());

                    BeanUtils.copyProperties(ybInspectData, ybInspectDataCUDto);
                    saveYbInspectData(ybInspectDataCUDto);
                }
            }
            return ResultGenerator.success();
        }
        return ResultGenerator.fail("数据有误，导入失败");
    }
}
