package com.sw.mes.yb.check.service.impl;

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.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.service.DefaultSampleService;
import com.sw.mes.base.factory.utils.PageUtils;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.system.service.DictionaryThemeService;
import com.sw.mes.base.workinprocess.entity.WipStorage;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.config.rabbit.InspectDataBaseChangeAsync;
import com.sw.mes.core.api.system.FbFeignClients;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.OxygenCarbonDto;
import com.sw.mes.core.dto.PieceCheckDto;
import com.sw.mes.core.entity.SearchFilter;
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.utils.*;
import com.sw.mes.dingTalk.service.DingTalkService;
import com.sw.mes.enumvalue.EnumValuesServer;
import com.sw.mes.grade.service.GradeService;
import com.sw.mes.gread.common.EnumValuesGrade;
import com.sw.mes.gread.entity.GradeRule;
import com.sw.mes.gread.entity.GradeVersion;
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.entity.YbInspectData;
import com.sw.mes.inspect.service.YbInspectDataService;
import com.sw.mes.utils.ExcelUtil;
import com.sw.mes.yb.check.dao.PieceCheckDAO;
import com.sw.mes.yb.check.entity.OxygenReversalLog;
import com.sw.mes.yb.check.entity.PieceCheck;
import com.sw.mes.yb.check.event.ProductOxygenRealErrorEvent;
import com.sw.mes.yb.check.service.OxygenReversalLogService;
import com.sw.mes.yb.check.service.PieceCheckService;
import com.sw.mes.yb.check.service.UpdateService;
import com.sw.mes.yb.pad.dao.SectionNoDetailDao;
import com.sw.mes.yb.pad.entity.*;
import com.sw.mes.yb.pad.service.*;
import com.sw.mes.yb.production.dao.LongCrystalDao;
import com.sw.mes.yb.production.entity.LongCrystal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;

@Slf4j
@Service
@Transactional
public class PieceCheckServiceImpl extends BaseServiceImpl<PieceCheck> implements PieceCheckService {

    PieceCheckDAO pieceCheckDAO;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private DictionaryThemeService dictionaryThemeService;


    @Autowired
    private LongCrystalDao longCrystalDao;

    @Autowired
    private SectionNoDetailDao sectionNoDetailDao;


    @Autowired
    private YbInspectDataDao inspectDataBaseDao;

    @Autowired
    private YbInspectDataService inspectDataBaseService;

    @Autowired
    private DefaultSampleService defaultSampleService;

    @Autowired
    private InspectDataBaseChangeAsync inspectDataBaseChangeAsync;

    @Autowired
    private YbInspectDataService ybInspectDataService;

    @Autowired
    FbFeignClients fbFeignClients;

    @Autowired
    private UpdateService updateService;

    @Autowired
    private ProductionRecutService productionRecutService;

    @Autowired
    private ProductionPaintingLineService productionPaintingLineService;

    @Autowired
    private ProductionPaintingLineDetailService productionPaintingLineDetailService;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private GradeService gradeService;

    @Autowired
    private GradeRuleService gradeRuleService;

    @Autowired
    private GradeVersionService gradeVersionService;

    @Autowired
    private DingTalkService dingTalkService;

    @Autowired
    public void setDao(PieceCheckDAO pieceCheckDAO) {
        this.pieceCheckDAO = pieceCheckDAO;
        super.setBaseDao(pieceCheckDAO);
    }

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private DictionaryItemService dictionaryItemService;

    @Override
    public List<PieceCheck> findByExample(Specification<PieceCheck> specification, RequestPage page) {
        org.springframework.data.domain.Page<PieceCheck> springDataPage = pieceCheckDAO.findAll(specification, PageUtils.createPageable(page));
        page.setTotal(springDataPage.getTotalElements());
        return springDataPage.getContent();
    }

    @Override
    public PieceCheck getByPieceNo(String pieceNo) {

        List<PieceCheck> pieceChecks = pieceCheckDAO.findByPieceNo(pieceNo);
        if (pieceChecks != null && pieceChecks.size() > 0) {
            return pieceChecks.get(0);
        }
        return null;
    }

    @Autowired
    private PieceDetailService pieceDetailService;

    @Autowired
    private RecutDetailService recutDetailService;

    @Autowired
    private OxygenReversalLogService oxygenReversalLogService;

    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private FactoryModelService factoryModelService;

    @Override
    public void saveOrUpdateInBatch(List<PieceCheck> pieceChecks, String type) {
        Assert.isTrue(!pieceChecks.isEmpty(), "至少上传一个样片");
        saveAll(pieceChecks);
        for (PieceCheck pieceCheck : pieceChecks) {
            // 同步更新晶段检验样片信息
            saveInspectDataBaseInfo(pieceCheck.getPieceNo());
            //氧反翘预警推送
            //更新明细表
            ThreadManager.getThreadPollProxy().execute(() -> {
                try {
                    pushOxygenReversal(pieceCheck);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }
        // 2024-03-06 赵文杰增加，样片修改时，同步更新晶段检验的样片信息
       /* pieceChecks.forEach(pieceCheck -> {
            // 判断是不是头片
            boolean isPieceNoHead;
            PieceDetail pieceDetails = pieceDetailService.findByPieceNo(pieceCheck.getPieceNo());
            List<SectionNoDetail> sectionNoDetails;
            if (pieceDetails.getType() == 0) {
                // 同步更新晶段检验样片信息
                sectionNoDetails = sectionNoDetailDao.findSegmentNoBypieceNo(pieceCheck.getPieceNo(), EnumValuesServer.LineType.回收料.getValue());
                Assert.isTrue(!sectionNoDetails.isEmpty(), "未找到该样片绑定的晶段信息");
                isPieceNoHead = StringUtils.equals(sectionNoDetails.get(0).getPieceNoHead(), pieceCheck.getPieceNo());
            } else {
                List<RecutDetail> recutDetail = recutDetailService.findByPieceNo(pieceCheck.getPieceNo());
                Assert.isTrue(!recutDetail.isEmpty(), "未找到该样片绑定的晶段信息");
                isPieceNoHead = StringUtils.equals(recutDetail.get(0).getPieceNoHead(), pieceCheck.getPieceNo());
                sectionNoDetails = sectionNoDetailDao.findBySectionNo(recutDetail.get(0).getSectionNo());
            }
            SectionNoDetail sectionNoDetail = sectionNoDetails.get(0);
            saveSectionNoDetailPieceCheck(sectionNoDetail, pieceCheck, isPieceNoHead);

            List<SectionNoDetail> sectionNoDetails1 = sectionNoDetailDao.findByCrystalNo(sectionNoDetail.getCrystalNo());
            // 排除本身关联的晶段
            sectionNoDetails1.stream().filter(sectionNoDetail1 -> !StringUtils.equals(sectionNoDetail1.getSectionNo(), sectionNoDetail.getSectionNo()))
                    .forEach(sectionNoDetail1 -> {
                        // 判断是不是头样片
                        if (isPieceNoHead) {
                            if (sectionNoDetail1.getSegmentNum() > sectionNoDetails.get(0).getSegmentNum()) {
                                YbInspectData ybInspectData1 = ybInspectDataService.findBySectionNo(sectionNoDetail1.getSectionNo());
                                if (ybInspectData1 != null) {
                                    // 首段A面氧含量
                                    ybInspectData1.setOxygenContentFirsta(pieceCheck.getoContents());
                                    // 首段A面碳含量
                                    ybInspectData1.setCarbonContentFirsta(pieceCheck.getcContents());
                                    inspectDataBaseService.saveDataAndGrade(ybInspectData1);
                                    // 同步方棒检验数据库
                                    PieceCheckDto pieceCheckDto = new PieceCheckDto();
                                    // 首段A面氧含量
                                    pieceCheckDto.setOxygenContentFirsta(pieceCheck.getoContents());
                                    // 首段A面碳含量
                                    pieceCheckDto.setCarbonContentFirsta(pieceCheck.getcContents());
                                    updatePieceCheckData(sectionNoDetail1.getSectionNo(), pieceCheckDto);
                                }
                            }
                        } else {
                            if (sectionNoDetail1.getSegmentNum() < sectionNoDetails.get(0).getSegmentNum()) {
                                YbInspectData ybInspectData1 = ybInspectDataService.findBySectionNo(sectionNoDetail1.getSectionNo());
                                if (ybInspectData1 != null) {
                                    // 尾段B面氧含量
                                    ybInspectData1.setOxygenContentEndb(pieceCheck.getoContents());
                                    // 尾段B面氧含量
                                    ybInspectData1.setCarbonContentEndb(pieceCheck.getcContents());
                                    inspectDataBaseService.saveDataAndGrade(ybInspectData1);
                                    PieceCheckDto pieceCheckDto = new PieceCheckDto();
                                    // 尾段B面氧含量
                                    pieceCheckDto.setOxygenContentEndb(pieceCheck.getoContents());
                                    // 尾段B面氧含量
                                    pieceCheckDto.setCarbonContentEndb(pieceCheck.getcContents());
                                    // 同步方棒检验数据库
                                    updatePieceCheckData(sectionNoDetail1.getSectionNo(), pieceCheckDto);
                                }
                            }
                        }
                    });
        });*/
    }

    private void pushOxygenReversal(PieceCheck pieceCheck){

        boolean result = pieceCheck.getBackCut().equals("否");

        BigDecimal headOContents = new BigDecimal(0);
        BigDecimal tailOContents = new BigDecimal(0);


        if(result){
            LongCrystal byPieceNo = longCrystalDao.findByPieceNo(pieceCheck.getPieceNo());
            List<ProductionPaintingLineDetail> byOperateReversecutDrawIdAndCrystalIdAndType = productionPaintingLineDetailService.findByOperateReversecutDrawIdAndCrystalIdAndType(0L, byPieceNo.getId(), 1);
            String tailNo = byOperateReversecutDrawIdAndCrystalIdAndType.get(0).getNo();
            String headNo = byOperateReversecutDrawIdAndCrystalIdAndType.get(byOperateReversecutDrawIdAndCrystalIdAndType.size() - 1).getNo();
            if(pieceCheck.getPieceNo().equals(tailNo)){
                tailOContents = pieceCheck.getoContents();
                List<PieceCheck> byPieceNo1 = pieceCheckDAO.findByPieceNo(headNo);
                if(byPieceNo1.size() > 0){
                    headOContents = byPieceNo1.get(0).getoContents();
                } else {
                    return;
                }
            }

            if(pieceCheck.getPieceNo().equals(headNo)){
                headOContents = pieceCheck.getoContents();
                List<PieceCheck> byPieceNo1 = pieceCheckDAO.findByPieceNo(tailNo);
                if(byPieceNo1.size() > 0){
                    tailOContents = byPieceNo1.get(0).getoContents();
                } else {
                    return;
                }
            }

            if(tailOContents.compareTo(headOContents) >= 0){

                //直接记录氧反翘数据；推送数据在记录表查询即可
                OxygenReversalLog oxygenReversalLog = new OxygenReversalLog();
                oxygenReversalLog.setCheckTime(new Date());
                String deviceNo = pieceCheck.getDeviceNo();
                oxygenReversalLog.setArea(deviceNo.substring(0, 2));
                oxygenReversalLog.setLotNo(pieceCheck.getLotNo());
                oxygenReversalLog.setMotherCrystalNo(pieceCheck.getMotherCrystalNo());
                Equipment byCode = equipmentService.findByCode(deviceNo);
                FactoryModel byCode1 = factoryModelService.findByCode(byCode.getArea());
                oxygenReversalLog.setWorkShop(byCode1.getName());
                oxygenReversalLog.setHeadOxyenContents(headOContents);
                oxygenReversalLog.setTailOxyenContents(tailOContents);
                oxygenReversalLogService.saveOrUpdate(oxygenReversalLog);

                String groupName = "氧反翘推送";
                String source = "氧反翘推送";
                StringBuffer content = new StringBuffer();
                content.append(". [MES推送]氧反翘:").append("\n");
                content.append(". 晶棒编号： ");
                content.append(byPieceNo.getCrystalNo()).append("\n");
                content.append(". T氧含量： ");
                content.append(headOContents).append("\n");
                content.append(". W氧含量： ");
                content.append(tailOContents).append("\n");

                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);
                } catch (Exception e) {
                    log.error("error_in_sendEapSignal", e);
                }
            }
        }
    }

    private void updatePieceCheckData(String sectionNo, PieceCheckDto pieceCheckDto) {
        List<RecutDetail> recutDetails = recutDetailService.findBySectionNo(sectionNo);
        recutDetails.forEach(recutDetail -> {
            pieceCheckDto.setSectionNoFb(recutDetail.getSectionNoFb());
            fbFeignClients.updatePieceCheckData(pieceCheckDto);
        });
    }

    public void saveSectionNoDetailPieceCheck(SectionNoDetail sectionNoDetail, PieceCheck pieceCheck, boolean isPieceNoHead) {
        YbInspectData ybInspectData = ybInspectDataService.findBySectionNo(sectionNoDetail.getSectionNo());
        PieceCheckDto pieceCheckDto = new PieceCheckDto();
        // 判断是不是有检验数据
        if (ybInspectData != null) {
            if (isPieceNoHead) {
                // 首段A面氧含量
                ybInspectData.setOxygenContentFirsta(pieceCheck.getoContents());
                // 首段A面碳含量
                ybInspectData.setCarbonContentFirsta(pieceCheck.getcContents());
                // T氧含量中心
                ybInspectData.setOxygenContentHead(pieceCheck.getoContents());
                // T碳含量中心
                ybInspectData.setCarbonContentHead(pieceCheck.getcContents());

                // 首段A面氧含量
                pieceCheckDto.setOxygenContentFirsta(pieceCheck.getoContents());
                // 首段A面碳含量
                pieceCheckDto.setCarbonContentFirsta(pieceCheck.getcContents());
                // T氧含量中心
                pieceCheckDto.setOxygenContentHead(pieceCheck.getoContents());
                // T碳含量中心
                pieceCheckDto.setCarbonContentHead(pieceCheck.getcContents());
            } else {
                // 尾段B面氧含量
                ybInspectData.setOxygenContentEndb(pieceCheck.getoContents());
                // 尾段B面氧含量
                ybInspectData.setCarbonContentEndb(pieceCheck.getcContents());
                // W氧含量中心
                ybInspectData.setOxygenContentTail(pieceCheck.getoContents());
                // W碳含量中心
                ybInspectData.setCarbonContentTail(pieceCheck.getcContents());

                // 尾段B面氧含量
                pieceCheckDto.setOxygenContentEndb(pieceCheck.getoContents());
                // 尾段B面氧含量
                pieceCheckDto.setCarbonContentEndb(pieceCheck.getcContents());
                // W氧含量中心
                pieceCheckDto.setOxygenContentTail(pieceCheck.getoContents());
                // W碳含量中心
                pieceCheckDto.setCarbonContentTail(pieceCheck.getcContents());
            }
            inspectDataBaseService.saveDataAndGrade(ybInspectData);
            // 同步方棒检验数据库
            updatePieceCheckData(sectionNoDetail.getSectionNo(), pieceCheckDto);
        }
    }

    @Override
    public List<PieceCheck> findAll(Specification<PieceCheck> specification) {
        return pieceCheckDAO.findAll(specification);
    }

    @Override
    public int findCountByPieceNo(List<String> samples) {
        return pieceCheckDAO.findCountByPieceNo(samples);
    }

    @Override
    public List<PieceCheck> findByMotherCrystalNo(String samples) {
        return pieceCheckDAO.findCountByMotherCrystalNo(samples);
    }

    @Override
    public List<PieceCheck> findPieceNosByPieceNo(List<String> samples) {
        return pieceCheckDAO.findPieceNosByPieceNo(samples);
    }

    /*

     * 评级
     *
     * @param
     */
// @Override
//    public List<InspectData> grandInspect(List<PieceCheck> pieceChecks) {
//        List<InspectData> list=new ArrayList<>();
//
//        for (PieceCheck pieceCheck : pieceChecks) {
//            if (pieceCheck.getCheckTime1() != null && pieceCheck.getCheckTime2() != null) {
//
////                Map<String, List<String>> sectionNos = sectionDetailService.findSectionNosNew(pieceCheck.getPieceNo());
//                Map<String, List<String>> sectionNos = sectionDetailService.getSectionNosByPieceNo(pieceCheck.getPieceNo());
//                if (sectionNos != null && sectionNos.size() > 0) {
//                    List<InspectData> inspects = new ArrayList<>();
//                    List<String> heads = sectionNos.get("heads");
//                    List<String> tails = sectionNos.get("tails");
//                    List<String> nos = new ArrayList<>();
//                    nos.addAll(heads);
//                    nos.addAll(tails);
//
//                    List<WipState> wipStates = wipStateService.findBySnIn(nos);
//                    Map<String, WipState> map = new HashMap<>();
//                    for (WipState item: wipStates) {
//                        map.put(item.getSn(), item);
//                    }
//
//                    if (heads.size() > 0) {
//                        List<InspectData> headInspects = inspectService.findBySectionNoIn(heads);
//                        if (headInspects != null && headInspects.size() > 0) {
//                            for (InspectData inspect : headInspects) {
//
//                                // 已入库申请，不进行 赋值、评级
//                                if (map.containsKey(inspect.getSectionNo())) {
//                                    WipState wipState = map.get(inspect.getSectionNo());
//                                    if (WipStateEnum.方棒.getKey().equals(wipState.getState())) {
//                                        continue;
//                                    }
//                                }
//
//                                inspect.setPieceNoTail(pieceCheck.getPieceNo());
//                                inspect.setPassivationLifeTail(pieceCheck.getLifeTime());
//                                inspect.setMicrodefectTail(pieceCheck.getMicroDefect());
//                                inspect.setDislocationTail(pieceCheck.getLineDefect());
//                                inspect.setOxygenContentTail(pieceCheck.getoContents());
//                                inspect.setOxygenContentBorderTail(pieceCheck.getoBorderContents());
//                                inspect.setCarbonContentTail(pieceCheck.getcContents());
//                                inspect.setCarbonContentBorderTail(pieceCheck.getcBorderContents());
//                                inspect.setAnnealTailCenter(pieceCheck.getCenterAnneal());
//                                inspect.setAnnealTailBorder(pieceCheck.getBorderAnneal());
////                              inspect.setStickLifeTail(pieceCheck.getLifeTime());
//
//                                try {
//                                    inspectService.judgeExcel(inspect);
//                                } catch (Exception e) {
//                                    logger.error("logger-----样片检验评级异常信息[" + inspect.getSectionNo() + "]:" + e.getMessage());
//                                }
//                                inspects.add(inspect);
//                            }
//
//                        }
//                    }
//
//                    if (tails.size() > 0) {
//                        List<InspectData> tailInspects = inspectService.findBySectionNoIn(tails);
//                        if (tailInspects != null && tailInspects.size() > 0) {
//                            for (InspectData inspect : tailInspects) {
//
//                                // 已入库申请，不进行 赋值、评级
//                                if (map.containsKey(inspect.getSectionNo())) {
//                                    WipState wipState = map.get(inspect.getSectionNo());
//                                    if (WipStateEnum.方棒.getKey().equals(wipState.getState())) {
//                                        continue;
//                                    }
//                                }
//
//                                inspect.setPieceNoHead(pieceCheck.getPieceNo());
//                                inspect.setPassivationLifeHead(pieceCheck.getLifeTime());
//                                inspect.setMicrodefectHead(pieceCheck.getMicroDefect());
//                                inspect.setDislocationHead(pieceCheck.getLineDefect());
//                                inspect.setOxygenContentHead(pieceCheck.getoContents());
//                                inspect.setOxygenContentBorderHead(pieceCheck.getoBorderContents());
//                                inspect.setCarbonContentHead(pieceCheck.getcContents());
//                                inspect.setCarbonContentBorderHead(pieceCheck.getcBorderContents());
//                                inspect.setAnnealHeadCenter(pieceCheck.getCenterAnneal());
//                                inspect.setAnnealHeadBorder(pieceCheck.getBorderAnneal());
////                              inspect.setStickLifeHead(pieceCheck.getLifeTime());
//
//                               try {
//                                    inspectService.judgeExcel(inspect);
//                                } catch (Exception e) {
//                                    logger.error("logger-----样片检验评级异常信息[" + inspect.getSectionNo() + "]:" + e.getMessage());
//                                }
//                                inspects.add(inspect);
//                            }
//
//                        }
//                    }
//
//                    if (inspects.size() > 0) {
//                        inspectService.updateInBatch(inspects);
//                        list.addAll(inspects);
//                    }
//                }
//
//            }
//        }
//        return list;
//    }

    @Override
    public void readExcelFile(MultipartFile file) throws Exception {
        Map<String, List<Map<String, Object>>> excelMap = null;
        List<PieceCheck> pieceChecks = new ArrayList<PieceCheck>();
        Date date = new Date();
        try {
            excelMap = ExcelUtil.getExcelInfo(file);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("文件导入异常！" + e.getMessage());
        }
        List<String> pieceNos = new ArrayList<>();
        if (excelMap != null && !excelMap.isEmpty()) {
            Collection<List<Map<String, Object>>> collection = excelMap.values();
            Iterator<List<Map<String, Object>>> iterator = collection.iterator();

            //判断该Excel是否包含相同编号的样片
            Map<String, PieceCheck> pieceCheckMap = new HashMap<>();

            while (iterator.hasNext()) {
                List<Map<String, Object>> list = iterator.next();
                if (list.size() > 10000) {
                    throw new Exception("每批次导入限制[10000]，该批次为：" + list.size());
                }
                for (Map<String, Object> map : list) {
                    PieceCheck pieceCheck = null;
                    String no = String.valueOf(map.get("序号")).trim();
                    String pieceNo = String.valueOf(map.get("样片编号")).trim();
                    LongCrystal byCrystalNo = longCrystalDao.findByCrystalNo(pieceNo);
                    if (null != byCrystalNo) {
                        throw new Exception("【" + pieceNo + "】编号为长晶棒编号，非样片编号");
                    }
                    if ("null".equals(pieceNo) || StringUtils.isBlank(pieceNo)) {
                        continue;
                    }
                    //查看样片检验是否存在该样片检验数据
                    pieceCheck = getByPieceNo(pieceNo);
                    if (pieceCheck == null) {
                        if (pieceCheckMap.containsKey(pieceNo)) {
                            pieceCheck = pieceCheckMap.get(pieceNo);
                        } else {
                            pieceCheck = new PieceCheck();
                            pieceCheck.setPieceNo(pieceNo);
                            pieceCheckMap.put(pieceNo, pieceCheck);
                        }
                    }
                    //载具编号 [新加]
                    String batchNo = String.valueOf(map.get("载具编号")).trim();
                    if (!StringUtils.isBlank(batchNo)) {
                        pieceCheck.setBatchNo(batchNo);
                    }

                    //母单晶编号 [新加]
                    String motherCrystalNo = String.valueOf(map.get("母单晶编号")).trim();
                    if (!StringUtils.isBlank(motherCrystalNo)) {
                        pieceCheck.setMotherCrystalNo(motherCrystalNo);
                    }

                    //炉次号 [新加]
                    String lotNo = String.valueOf(map.get("炉次号")).trim();
                    if (!StringUtils.isBlank(lotNo)) {
                        pieceCheck.setLotNo(lotNo);
                    }

                    //设备编号 [新加]
                    String deviceNo = String.valueOf(map.get("设备编号")).trim();
                    if (!StringUtils.isBlank(deviceNo)) {
                        pieceCheck.setDeviceNo(deviceNo);
                    }


//                    //车间
//                    String workShop = String.valueOf(map.get("车间")).trim();
//                    if (!StringUtils.isBlank(workShop)) {
//                        pieceCheck.setWorkshop(workShop);
//                    }
//                    //微缺陷
//                    String microDefect = String.valueOf(map.get("微缺陷")).trim();
//                    if (StringUtils.isBlank(microDefect)) {
//                        pieceCheck.setMicroDefect("无");
//                    } else {
//                        pieceCheck.setMicroDefect(microDefect);
//                    }
//                    //位错
//                    String lineDefect = String.valueOf(map.get("位错")).trim();
//                    if (StringUtils.isBlank(lineDefect)) {
//                        pieceCheck.setLineDefect("无");
//                    } else {
//                        pieceCheck.setLineDefect(lineDefect);
//                    }

                    //备注1
                    String remark1 = String.valueOf(map.get("备注1")).trim();
                    if (!StringUtils.isBlank(remark1)) {
                        pieceCheck.setRemark1(remark1);
                    }

                    //碳氧含量检验时间【检验时间1】
                    String checkTime1Str = String.valueOf(map.get("检验时间1")).trim();
                    if (!StringUtils.isBlank(checkTime1Str)) {
                        try {
                            Date checkTime1 = DateUtil.toDate(checkTime1Str, "yyyy-MM-dd HH:mm:ss");
                            pieceCheck.setCheckTime1(checkTime1);
                        } catch (Exception e) {
                            throw new Exception("序号：" + no + " 检验时间1格式错误！");
                        }
                    }
//                    else {
//                        pieceCheck.setCheckTime1(date);
//                    }

                    //碳含量中心
                    String cContents = String.valueOf(map.get("碳含量中心")).trim();
                    if (!StringUtils.isBlank(cContents)) {
                        try {
                            BigDecimal decimalC = new BigDecimal(cContents);
                            pieceCheck.setcContents(decimalC);
                        } catch (Exception e) {
                            throw new Exception("序号：" + no + " 碳含量中心格式错误！");
                        }
                    } else {
                        throw new Exception("序号：" + no + "请输入碳含量中心！");
                    }

//                    //缺陷位错备注
//                    String remark1 = String.valueOf(map.get("缺陷位错备注")).trim();
//                    if (!StringUtils.isBlank(lineDefect)) {
//                        pieceCheck.setRemark1(remark1);
//                    }

                    //}

                    //氧含量中心
                    String oContents = String.valueOf(map.get("氧含量中心")).trim();
                    if (!StringUtils.isBlank(oContents)) {
                        try {
                            BigDecimal decimalO = new BigDecimal(oContents);
                            pieceCheck.setoContents(decimalO);
                        } catch (Exception e) {
                            throw new Exception("序号：" + no + " 氧含量中心格式错误！");
                        }
                    } else {
                        throw new Exception("序号：" + no + " 请输入氧含量中心！");

                    }

                    //样片厚度
                    String thickness = String.valueOf(map.get("样片厚度")).trim();
                    if (!StringUtils.isBlank(thickness)) {
                        try {
                            BigDecimal thicknessZ = new BigDecimal(thickness);
                            pieceCheck.setThickness(thicknessZ);
                        } catch (Exception e) {
                            throw new Exception("序号：" + no + " 样片厚度格式错误！");
                        }
                    } else {
                        throw new Exception("序号：" + no + " 请输入样片厚度！");

                    }

                    //碳氧含量备注
                    String remark2 = String.valueOf(map.get("备注2")).trim();
                    if (!StringUtils.isBlank(remark2)) {
                        pieceCheck.setRemark2(remark2);
                    }

                    //缺陷位错检验人【检验人1】
                    String userName1 = String.valueOf(map.get("检验人1")).trim();
                    if (!StringUtils.isBlank(userName1)) {//
                        pieceCheck.setUserName1(userName1);
                    }

                    //碳氧含量检验时间【检验时间2】
                    String checkTime2Str = String.valueOf(map.get("检验时间2")).trim();
                    if (!StringUtils.isBlank(checkTime2Str)) {
                        try {
                            Date checkTime2 = DateUtil.toDate(checkTime2Str, "yyyy-MM-dd HH:mm:ss");
                            pieceCheck.setCheckTime2(checkTime2);
                        } catch (Exception e) {
                            throw new Exception("序号：" + no + " 检验时间2格式错误！");
                        }
                    } else {
                        //pieceCheck.setCheckTime2(date);
                        throw new Exception("序号：" + no + " 请输入检验时间2！");
                    }

                    //寿命
//                    String life = String.valueOf(map.get("寿命")).trim();
//                    if (!StringUtils.isBlank(life)) {
//                        try {
//                            BigDecimal decimalLife = new BigDecimal(life);
//                            pieceCheck.setLifeTime(decimalLife);
//                        } catch (Exception e) {
//                            throw new Exception("序号：" + no + " 寿命格式错误！");
//                        }
//                    }

                    //碳氧含量检验人【检验人2】
                    pieceCheck.setUserName2(BaseContextHandler.getUsername());
//                    String userName2 = String.valueOf(map.get("检验人2")).trim();
//                    if (!StringUtils.isBlank(userName2)) {
//                        pieceCheck.setUserName2(userName2);
//                    }
//                    //碳氧含量检验时间
//                    String checkTime2Str = String.valueOf(map.get("碳氧含量检验时间")).trim();
//                    if (!StringUtils.isBlank(checkTime2Str)) {
//                        try {
//                            Date checkTime2 = DateUtil.toDate(checkTime2Str, "yyyy-MM-dd HH:mm:ss");
//                            pieceCheck.setCheckTime2(checkTime2);
//                        } catch (Exception e) {
//                            throw new Exception("序号：" + no + " 碳氧含量检验时间格式错误！");
//                        }
//                    } else {
//                        pieceCheck.setCheckTime2(date);
//                    }
//                    //辅助测试人员
////                    String receiveUser = String.valueOf(map.get("辅助测试人员")).trim();
////                    if (!StringUtils.isBlank(receiveUser)) {
////                        pieceCheck.setReceiveUser(receiveUser);
////                    }
                    //检验时间1，检验时间2
//                    pieceCheck.setCheckTime1(date);
//                    pieceCheck.setCheckTime2(date);
                    //中心退火电阻率
                    String centerAnneal = String.valueOf(map.get("中心退火电阻率")).trim();
                    if (!StringUtils.isBlank(centerAnneal)) {
                        try {
                            BigDecimal decimalCenterAnneal = new BigDecimal(centerAnneal);
                            pieceCheck.setCenterAnneal(decimalCenterAnneal);
                        } catch (Exception e) {
                            throw new Exception("序号：" + no + " 中心退火电阻率格式错误！");
                        }
                    }
                    //边缘退火电阻率
                    String borderAnneal = String.valueOf(map.get("边缘退火电阻率")).trim();
                    if (!StringUtils.isBlank(borderAnneal)) {
                        try {
                            BigDecimal decimalBorderAnneal = new BigDecimal(borderAnneal);
                            pieceCheck.setBorderAnneal(decimalBorderAnneal);
                        } catch (Exception e) {
                            throw new Exception("序号：" + no + " 边缘退火电阻率格式错误！");
                        }
                    }

                    //Todo 数据字典配置圆棒检验PN规则，后面必填会变的
//                    DictionaryTheme dictionaryTheme = dictionaryThemeService.findByValue("nTypeRules");
//                    if (dictionaryTheme == null) {
//                        throw new Exception("请在数据字典配置圆棒检验PN型判断规则！");
//                    }
//                    String sec3 = pieceNo.substring(2, 3);//样片编号第三位
//                    DictionaryItem dictionaryItem = dictionaryItemService.findByNameAndThemeId(sec3, dictionaryTheme.getId());
//                    if (dictionaryItem == null) {
//                        throw new Exception("序号：" + no + " 没有圆棒检验PN型！");
//                    }


                    //碳含量边缘
                    //String ccs = String.valueOf(map.get("碳含量边缘")).trim();
                    //氧含量边缘
                    //String ocs = String.valueOf(map.get("氧含量边缘")).trim();
                    //Todo 也是后期需要修改
                    //if ("N".equals(dictionaryItem.getValue())) {
//                    if (!StringUtils.isBlank(ccs)) {
//                        try {
//                            BigDecimal cBorderContents = new BigDecimal(ccs);
//                            pieceCheck.setcBorderContents(cBorderContents);
//                        } catch (Exception e) {
//                            throw new Exception("序号：" + no + " 碳含量边缘格式错误！");
//                        }
//                    }
//
//                    if (!StringUtils.isBlank(ocs)) {
//                        try {
//                            BigDecimal oBorderContents = new BigDecimal(ocs);
//                            pieceCheck.setoBorderContents(oBorderContents);
//                        } catch (Exception e) {
//                            throw new Exception("序号：" + no + " 氧含量边缘格式错误！");
//                        }
//                    }
                    //                   }
//                else if ("P".equals(dictionaryItem.getValue())) {
//                        if (!StringUtils.isBlank(ccs)) {
//                            try {
//                                BigDecimal cBorderContents = new BigDecimal(ccs);
//                                pieceCheck.setcBorderContents(cBorderContents);
//                            } catch (Exception e) {
//                                throw new Exception("序号：" + no + " 碳含量边缘格式错误！");
//                            }
//                        }
//
//                        if (!StringUtils.isBlank(ocs)) {
//                            try {
//                                BigDecimal oBorderContents = new BigDecimal(ocs);
//                                pieceCheck.setoBorderContents(oBorderContents);
//                            } catch (Exception e) {
//                                throw new Exception("序号：" + no + " 氧含量边缘格式错误！");
//                            }
//                        }
//
//                    } else {
//                        throw new Exception("序号：" + no + " 不是P/N类型！");
//                    }

                    //退火电阻率检验人[检验人3]
                    String annealUser = String.valueOf(map.get("检验人3")).trim();
                    if (!StringUtils.isBlank(annealUser)) {
                        pieceCheck.setAnnealUser(annealUser);
                    }

                    //退火电阻率检验备注【备注3】
                    String annealRemark = String.valueOf(map.get("备注3")).trim();
                    if (!StringUtils.isBlank(annealRemark)) {
                        pieceCheck.setAnnealRemark(annealRemark);
                    }

                    //退火电阻率检验时间【检验时间3】
                    String checkTime3Str = String.valueOf(map.get("检验时间3")).trim();
                    if (!StringUtils.isBlank(checkTime3Str)) {
                        try {
                            Date checkTime3 = DateUtil.toDate(checkTime3Str, "yyyy-MM-dd HH:mm:ss");
                            pieceCheck.setAnnealTime(checkTime3);
                        } catch (Exception e) {
                            throw new Exception("序号：" + no + " 检验时间3格式错误！");
                        }
                    }
//                    else {
//                        pieceCheck.setAnnealTime(date);
//                    }
                    pieceChecks.add(pieceCheck);
                }
            }
            //对晶棒数据表，和样片检验表数据进行保存以及评级
            if (pieceChecks.size() > 0) {
                saveAll(pieceChecks);

                for (PieceCheck pieceCheck : pieceChecks) {
                    // 同步更新晶段检验样片信息
                    this.saveInspectDataBaseInfo(pieceCheck.getPieceNo());
                    String fromMark = pieceCheck.getPieceNo().substring(SectionIndexRangeEnum.基地追溯产品类型.getBeginIndex(), SectionIndexRangeEnum.基地追溯产品类型.getEndIndex());
                    if (fromMark.matches("[A-Z]+")) {
                        pieceNos.add(pieceCheck.getPieceNo().substring(SectionIndexRangeEnum.毛棒范围.getBeginIndex(), SectionIndexRangeEnum.毛棒范围.getEndIndex()));
                    } else {
                        pieceNos.add(pieceCheck.getPieceNo().substring(0, 12));
                    }
//                    ThreadManager.getThreadPollProxy().execute(() -> {
//                        try {
//                            fbFeignClients.synchronousUpdate(pieceCheck.getPieceNo().substring(0, 11));
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    });
                }
//                final List<PieceCheck> grandInspects = pieceChecks;
//                Thread thread = new Thread(() -> {
//                    //grandInspect(grandInspects);
//                });
//                thread.start();
            }
        }
        updateService.updates(pieceNos);
    }

    @Override
    public Integer countByPieceNo(String pieceNo) {
        return pieceCheckDAO.countByPieceNoLike(pieceNo + "%");
    }

    @Override
    public List<PieceCheck> findByTime(Date beginTime, Date endTime) {
        Specification<PieceCheck> specification = DynamicSpecifications.bySearchFilter(PieceCheck.class,
                new SearchFilter("checkTime1", SearchFilter.Operator.GT, beginTime),
                new SearchFilter("checkTime1", SearchFilter.Operator.LT, endTime));
        List<PieceCheck> pieceCheckList = findByExampleSort(specification, null);
        return pieceCheckList;
    }

    @Override
    public List<String> findPieceCheckLotNoList(Date beginTime, Date endTime) {
        return pieceCheckDAO.findPieceCheckLotNoList(beginTime, endTime);
    }

    @Override
    public List<PieceCheck> findByLotNo(String lotNo) {
        Specification<PieceCheck> specification = DynamicSpecifications.bySearchFilter(PieceCheck.class,
                new SearchFilter("lotNo", SearchFilter.Operator.EQ, lotNo));
        List<PieceCheck> pieceCheckList = findByExampleSort(specification, null);
        return pieceCheckList;
    }

    @Override
    public void saveOrUpdateLineData(List<PieceCheck> pieceChecks) {
        saveAll(pieceChecks);

        final List<PieceCheck> finalJsonString = pieceChecks;

/*
        Thread thread = new Thread(() -> {
            grandInspectNew(finalJsonString);
        });
        thread.start();
*/

    }


    @Override
    public List<PieceCheck> getpieceCheck(String param, String series, String deviceNo, String lotNo, String motherCrystalNo, String startTime, String endTime, Sort sort) {
        Set<SearchFilter> searchSet = new HashSet<>(7);
        if (!StringUtils.isBlank(series)) {
            searchSet.add(new SearchFilter("deviceNo", SearchFilter.Operator.LIKE, series));
        }
        if (!StringUtils.isBlank(deviceNo)) {
            searchSet.add(new SearchFilter("deviceNo", SearchFilter.Operator.EQ, deviceNo));
        }
        if (!StringUtils.isBlank(lotNo)) {
            searchSet.add(new SearchFilter("lotNo", SearchFilter.Operator.EQ, lotNo));
        }
        if (!StringUtils.isBlank(motherCrystalNo)) {
            searchSet.add(new SearchFilter("motherCrystalNo", SearchFilter.Operator.EQ, motherCrystalNo));
        }
        if (!StringUtils.isBlank(startTime)) {
            searchSet.add(new SearchFilter("checkTime1", SearchFilter.Operator.GT, startTime));
        }
        if (!StringUtils.isBlank(endTime)) {
            searchSet.add(new SearchFilter("checkTime1", SearchFilter.Operator.LT, endTime));
        }
        // 氧含量不为空
        searchSet.add(new SearchFilter("oContents", SearchFilter.Operator.ISNOTNULL, ""));
        Specification<PieceCheck> specification = DynamicSpecifications.bySearchFilter(PieceCheck.class, searchSet);
        List<PieceCheck> pieceCheckList = findByExampleSort(specification, sort);
        return pieceCheckList;
    }

    @Override
    public void saveAll(List<PieceCheck> pieceChecks) {
        pieceCheckDAO.saveAll(pieceChecks);
        // spc异步监听
        applicationContext.publishEvent(new ProductOxygenRealErrorEvent(pieceChecks));
        inspectDataBaseChangeAsync.pieceCheckDataBaseChange(pieceChecks);
    }

    @Override
    public void saveOrUpdate(PieceCheck pieceCheck) {
        super.saveOrUpdate(pieceCheck);
        // spc异步监听
        List<PieceCheck> pieceCheckList = new ArrayList<>();
        pieceCheckList.add(pieceCheck);
        applicationContext.publishEvent(new ProductOxygenRealErrorEvent(pieceCheckList));
        inspectDataBaseChangeAsync.pieceCheckDataBaseChange(pieceCheckList);
    }

    @Override
    public void createPieceCheck(List<String> samples, String batchNo, String receiveUser, String workshop) {

        Map<String, SectionDetail> map = new HashMap<>();
        /*List<SectionDetail> details = sectionDetailService.findBySectionNos(samples);
        if (details != null && details.size() > 0) {
            for (SectionDetail detail : details) {
                map.put(detail.getSectionNo(), detail);
            }
        }*/

        List<PieceCheck> pieceChecks = new ArrayList<>();
        SectionDetail sectionDetail;
        for (String sample : samples) {
            PieceCheck pieceCheck = new PieceCheck();
            pieceCheck.setPieceNo(sample);
            pieceCheck.setBatchNo(batchNo);
            pieceCheck.setReceiveUser(receiveUser);
            pieceCheck.setWorkshop(workshop);

            if (map.containsKey(sample)) {
                sectionDetail = map.get(sample);
                if (sectionDetail != null) {
                    pieceCheck.setDeviceNo(sectionDetail.getDeviceNo());
                    pieceCheck.setMotherCrystalNo(sectionDetail.getCrystalNo());
                    pieceCheck.setLotNo(sectionDetail.getLotNo());
                }
            }
            pieceChecks.add(pieceCheck);
        }
        if (pieceChecks.size() > 0) {
            saveAll(pieceChecks);
        }

    }

    @Override
    public void saveInspectDataBaseInfo(String pieceNo) {
        PieceCheck pieceCheck = null;
        // 找到样片检验的数据
        List<PieceCheck> PieceNo = pieceCheckDAO.findByPieceNo(pieceNo);
        if (PieceNo != null && PieceNo.size() > 0) {
            pieceCheck = PieceNo.get(0);
        }

        // 通过样片编号找到晶段信息
        List<SectionNoDetail> sectionNoDetailList = sectionNoDetailDao.findSegmentNoBypieceNo(pieceNo, EnumValuesServer.LineType.回收料.getValue());

        if (!CollectionUtils.isEmpty(sectionNoDetailList)) {
            SectionNoDetail sectionNoDetail = sectionNoDetailList.get(0);
            if (StringUtils.isNotBlank(sectionNoDetail.getSectionNo()) && sectionNoDetail.getSectionNo().endsWith("R")) {
                if (StringUtils.equals(pieceNo, sectionNoDetail.getPieceNoHead())) {
                    this.handleContent(pieceCheck, sectionNoDetail, true);
                } else if (StringUtils.equals(pieceNo, sectionNoDetail.getPieceNoEnd())) {
                    this.handleContent(pieceCheck, sectionNoDetail, false);
                }

            } else {
                //新调整业务
                if (null != sectionNoDetail.getOxygenCarbonMark() && sectionNoDetail.getOxygenCarbonMark() >= 1) {
                    this.handleOxygenContentAndCarbonContentRate(sectionNoDetail, pieceCheck, pieceNo);
                } else {
                    this.handleSectionNoInfo(sectionNoDetail, pieceCheck, pieceNo);
                }
            }
        }
       /* SectionNoDetail sectionNoDetail = sectionNoDetailList.get(0);
        LongCrystal byCrystalNo = longCrystalDao.findByCrystalNo(sectionNoDetail.getCrystalNo());
        if (byCrystalNo.getClosureIdentification().equals(EnumValuesServer.FINALIDENTIFICATION)) {
            List<YbInspectData> inspectData1 = new ArrayList<>();
            for (SectionNoDetail noDetail : sectionNoDetailList) {
                inspectData1 = inspectDataBaseDao.findBySectionNo(noDetail.getSectionNo());
            }

            //查询划线记录
//            ProductionPaintingLine byCrystalNo1 = productionPaintingLineService.findByCrystalNo(byCrystalNo.getCrystalNo());
            List<ProductionPaintingLineDetail> byOperateDrawIdAndAndType = productionPaintingLineDetailService.findByOperateDrawIdAndAndType(byCrystalNo.getId(), 0);
            for (ProductionPaintingLineDetail productionPaintingLineDetail : byOperateDrawIdAndAndType) {
                List<YbInspectData> inspectData = inspectDataBaseDao.findBySectionNo(productionPaintingLineDetail.getNo());
                inspectData.addAll(inspectData1);
                if (inspectData.size() > 0) {
//                    YbInspectData inspectDataBase = inspectData.get(0);
                    for (YbInspectData inspectDataBase : inspectData) {
                        if(inspectDataBase.getIsCutBack() != 0){
                            continue;
                        }
                        List<ProductionBackCuttingRecord> allBySegmentNo = productionRecutService.findAllBySegmentNo(inspectDataBase.getSectionNo());
                        if (!CollectionUtils.isEmpty(allBySegmentNo)) {
                            continue;
                        }
                        // 头片
                        if (sectionNoDetail.getPieceNoHead() != null && sectionNoDetail.getPieceNoHead().equals(pieceNo)) {
                            if (pieceCheck != null) {
                                if (pieceCheck.getoContents() != null) {
                                    inspectDataBase.setEndOxygenContentHead(pieceCheck.getoContents());
                                }
                                if (pieceCheck.getcContents() != null) {
                                    inspectDataBase.setEndCarbonContentHead(pieceCheck.getcContents());
                                }
                                // 更新检验数据库头片信息
                                this.inspectDataBaseService.saveDataAndGrade(inspectDataBase);
                                try {
                                    //保存圆棒检验记录表
                                    ybInspectDataService.saveDataInspectLog(inspectDataBase);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            //尾片
                        } else if (sectionNoDetail.getPieceNoEnd() != null && sectionNoDetail.getPieceNoEnd().equals(pieceNo)) {
                            if (pieceCheck != null) {
                                if (pieceCheck.getoContents() != null) {
                                    inspectDataBase.setEndOxygenContentTail(pieceCheck.getoContents());
                                }

                                if (pieceCheck.getcContents() != null) {
                                    inspectDataBase.setEndCarbonContentTail(pieceCheck.getcContents());
                                }

                                // 更新检验数据库尾片信息
                                this.inspectDataBaseService.saveDataAndGrade(inspectDataBase);

                                try {
                                    ybInspectDataService.saveDataInspectLog(inspectDataBase);//保存圆棒检验记录表
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        }
                    }
                }
            }

        }
        supplementaryData(pieceNo, pieceCheck, sectionNoDetailList);*/
    }

    @Override
    public void saveInspectDataBaseInfoNew(PieceCheck pieceCheck) {
        if (null == pieceCheck || StringUtils.isBlank(pieceCheck.getPieceNo())) {
            return;
        }

        // 通过样片编号找到晶段信息
        List<SectionNoDetail> sectionNoDetailList = sectionNoDetailDao.findSegmentNoBypieceNo(pieceCheck.getPieceNo(), EnumValuesServer.LineType.回收料.getValue());
        if (!CollectionUtils.isEmpty(sectionNoDetailList)) {
            SectionNoDetail sectionNoDetail = sectionNoDetailList.get(0);
            if (StringUtils.isNotBlank(sectionNoDetail.getSectionNo()) && (sectionNoDetail.getSectionNo().endsWith("R") || sectionNoDetail.getSectionNo().endsWith("R1"))) {
                if (StringUtils.equals(pieceCheck.getPieceNo(), sectionNoDetail.getPieceNoHead())) {
                    this.handleContent(pieceCheck, sectionNoDetail, true);
                } else if (StringUtils.equals(pieceCheck.getPieceNo(), sectionNoDetail.getPieceNoEnd())) {
                    this.handleContent(pieceCheck, sectionNoDetail, false);
                }

            } else {
                //新调整业务
                if (null != sectionNoDetail.getOxygenCarbonMark() && sectionNoDetail.getOxygenCarbonMark() >= 1) {
                    this.handleOxygenContentAndCarbonContentRate(sectionNoDetail, pieceCheck, pieceCheck.getPieceNo());
                } else {
                    this.handleSectionNoInfo(sectionNoDetail, pieceCheck, pieceCheck.getPieceNo());
                }
            }
        }

    }

    private void handleOxygenContentAndCarbonContentRate(SectionNoDetail sectionNoDetail, PieceCheck pieceCheck, String pieceNo) {
        if (null == sectionNoDetail || null == pieceCheck || StringUtils.isBlank(pieceNo) || StringUtils.isBlank(sectionNoDetail.getSectionNo())) {
            return;
        }
        List<YbInspectData> verificationList = new ArrayList<>();
        Boolean oContentFlag = false;
        Boolean cContentFlag = false;
        YbInspectData ybInspectData = ybInspectDataService.findBySectionNo(sectionNoDetail.getSectionNo());
        Integer oxygenCarbonMark = sectionNoDetail.getOxygenCarbonMark();
        DefaultSample defaultSample = defaultSampleService.findByDopantLikeAndSpecificationsLikeAndProductTypeLike(sectionNoDetail.getDopant(), sectionNoDetail.getSpecs(), null);
        if (null == ybInspectData) {
            //处理未检验数据的情况赋值问题，先写死值
            if (null != defaultSample) {
                if (null != sectionNoDetail.getOxygenCarbonMark()) {
                    if (sectionNoDetail.getOxygenCarbonMark() == 1 && null != pieceCheck.getoContents() && NumberUtil.isNumeric(defaultSample.getOxygenCenterHead())
                            && pieceCheck.getoContents().compareTo(new BigDecimal(defaultSample.getOxygenCenterHead())) <= 0) {
                        //氧含量正常
                        oContentFlag = true;
                    }
                    if (sectionNoDetail.getOxygenCarbonMark() == 2 && null != pieceCheck.getcContents() && NumberUtil.isNumeric(defaultSample.getCarbonCenterTail())
                            && pieceCheck.getcContents().compareTo(new BigDecimal(defaultSample.getOxygenCenterHead())) <= 0) {
                        //碳含量正常
                        cContentFlag = true;
                    }
                    List<SectionNoDetail> byCrystalNoNew = sectionNoDetailDao.findByCrystalNo(sectionNoDetail.getCrystalNo());
                    Map<String, YbInspectData> inspectMapsNew = new HashMap<>();
                    for (SectionNoDetail sectionNoDetailNew : byCrystalNoNew) {

                        YbInspectData ybInspectDataNew = ybInspectDataService.findBySectionNo(sectionNoDetailNew.getSectionNo());
                        if (null != ybInspectDataNew) {
                            if (oContentFlag) {
                                //已存在数据不覆盖
                                if (null != ybInspectDataNew.getOxygenContentHead() && ybInspectDataNew.getOxygenContentHead().compareTo(BigDecimal.ZERO) > 0) {
                                    continue;
                                }
                                //T氧含量中心
                                ybInspectDataNew.setOxygenContentHead(pieceCheck.getoContents());
                                //T碳含量中心
                                ybInspectDataNew.setCarbonContentHead(pieceCheck.getcContents());
                            } else if (cContentFlag) {
                                //已存在数据不覆盖
                                if (null != ybInspectDataNew.getCarbonContentTail() && ybInspectDataNew.getCarbonContentTail().compareTo(BigDecimal.ZERO) > 0) {
                                    continue;
                                }
                                //W碳含量中心
                                ybInspectDataNew.setCarbonContentTail(pieceCheck.getcContents());
                                //W氧含量中心
                                ybInspectDataNew.setOxygenContentTail(pieceCheck.getoContents());
                            } else {
                                continue;
                            }
                            //添加判断，站点在检验需要评级
                            List<WipStorage> wipStorageList = wipStorageService.findByProcessingByOrderCode(ybInspectDataNew.getSectionNo());
                            if (!CollectionUtils.isEmpty(wipStorageList)) {
                                WipStorage wipStorage = wipStorageList.get(0);
                                if (StringUtils.equals(wipStorage.getProcessName(), EnumValuesFactory.WipStorageCode.圆棒检验.getValue())) {
                                    inspectMapsNew.put(ybInspectDataNew.getSectionNo(), ybInspectDataNew);
                                }
                            }

                            //保存数据
                            ybInspectDataService.saveOrUpdate(ybInspectDataNew);
                            verificationList.add(ybInspectDataNew);
                        }
                    }
                    //在圆棒站触发评级
                    if (inspectMapsNew.size() != 0) {
                        gradeService.execGrade(inspectMapsNew);
                    }
                    return;
                }
            } else {
                return;
            }
        }
        if (null != oxygenCarbonMark) {
            Boolean gradeFlag = false;
            Boolean headFlag = false;
            List<String> sectionNoList = new ArrayList<>();
            sectionNoList.add(sectionNoDetail.getSectionNo());
            boolean execGradeRule = false;
            //处理氧碳返切测试
            GradeVersion gradeVersion = gradeVersionService.findTopByStatusAndRegion(EnumValuesGrade.GradeVersionStatus.已生效.getKey(), EnumValuesGrade.Region.圆棒.getKey());
            if (null == gradeVersion) {
                throw new RuntimeException("不存在已生效圆棒评级规则！");
            }
            String level = null;
            Boolean gradeRuleBackFlag = false;
            //头依赖
            if (oxygenCarbonMark == 1) {
                //T氧含量中心
                ybInspectData.setOxygenContentHead(pieceCheck.getoContents());
                //T碳含量中心
                ybInspectData.setCarbonContentHead(pieceCheck.getcContents());
                Map<String, Object> inspectMap = BeanUtil.convertObjectToMap(ybInspectData, YbInspectData.class);
                headFlag = true;
                gradeFlag = true;
                GradeRule gradeRule = gradeRuleService.findTopByGradeVersionIdAndDopantAndSpecificationsAndGradeLike(gradeVersion.getId(), ybInspectData.getDopant(), ybInspectData.getProductTypeSecond(), "%氧返切");
                if (null != gradeRule) {
                    execGradeRule = gradeRuleService.execGradeRule(gradeVersion.getId(), gradeRule.getName(), EnumValuesGrade.Region.圆棒.getKey(), inspectMap);
                    level = gradeRule.getGrade();
                }
                GradeRule gradeRuleBack = gradeRuleService.findTopByGradeVersionIdAndDopantAndSpecificationsAndGradeLike(gradeVersion.getId(), ybInspectData.getDopant(), ybInspectData.getProductTypeSecond(), "%返切不复测");
                if (null != gradeRuleBack) {
                    gradeRuleBackFlag = gradeRuleService.execGradeRule(gradeVersion.getId(), gradeRuleBack.getName(), EnumValuesGrade.Region.圆棒.getKey(), inspectMap);
                }


            } else if (oxygenCarbonMark == 2) {
                //W氧含量中心
                ybInspectData.setOxygenContentTail(pieceCheck.getoContents());
                //W碳含量中心
                ybInspectData.setCarbonContentTail(pieceCheck.getcContents());
                Map<String, Object> inspectMap = BeanUtil.convertObjectToMap(ybInspectData, YbInspectData.class);
                gradeFlag = true;
              /*  //处理T氧含量中心
                this.handelDefaultContent(ybInspectData,false,sectionNoDetail);*/
                GradeRule gradeRule = gradeRuleService.findTopByGradeVersionIdAndDopantAndSpecificationsAndGradeLike(gradeVersion.getId(), ybInspectData.getDopant(), ybInspectData.getProductTypeSecond(), "%碳返切");
                if (null != gradeRule) {
                    execGradeRule = gradeRuleService.execGradeRule(gradeVersion.getId(), gradeRule.getName(), EnumValuesGrade.Region.圆棒.getKey(), inspectMap);
                    level = gradeRule.getGrade();
                }
            }
            if (gradeFlag) {
                ybInspectDataService.saveDataAndGrade(ybInspectData);
                Boolean gradeTypeFlag = StringUtils.equals("取片", ybInspectData.getGradeType());
                if (!gradeTypeFlag && StringUtils.isNotBlank(ybInspectData.getProductLevel()) || !execGradeRule) {
                    List<SectionNoDetail> byCrystalNo = sectionNoDetailDao.findByCrystalNo(sectionNoDetail.getCrystalNo());
                    Map<String, YbInspectData> inspectMaps = new HashMap<>();
                    for (SectionNoDetail sectionNoDetailNew : byCrystalNo) {
                        if (StringUtils.equals(sectionNoDetailNew.getSectionNo(),ybInspectData.getSectionNo())){
                            continue;
                        }
                        YbInspectData ybInspectDataDetail = ybInspectDataService.findBySectionNo(sectionNoDetailNew.getSectionNo());
                        if (null == ybInspectDataDetail) {
                            continue;
                        }
                        if (StringUtils.isNotBlank(level) && StringUtils.equals(ybInspectDataDetail.getProductLevel(), level)) {
                            continue;
                        }
                        if (headFlag) {
                           /* //已存在数据不覆盖
                            if (null != ybInspectDataDetail.getOxygenContentHead() && ybInspectDataDetail.getOxygenContentHead().compareTo(BigDecimal.ZERO) > 0) {
                                continue;
                            }*/
                            if (!execGradeRule){
                                //T氧含量中心
                                ybInspectDataDetail.setOxygenContentHead(pieceCheck.getoContents());
                                //T碳含量中心
                                ybInspectDataDetail.setCarbonContentHead(pieceCheck.getcContents());
                            }else {
                                if (null != sectionNoDetailNew.getSectionPosiotion() && null != sectionNoDetail.getSectionPosiotion() && sectionNoDetailNew.getSectionPosiotion() > sectionNoDetail.getSectionPosiotion()){
                                    //T氧含量中心
                                    ybInspectDataDetail.setOxygenContentHead(BigDecimal.ZERO);
                                    //T碳含量中心
                                    ybInspectDataDetail.setCarbonContentHead(BigDecimal.ZERO);
                                }
                            }
                            if (gradeRuleBackFlag){
                                //T氧含量中心
                                ybInspectDataDetail.setOxygenContentHead(NumberUtil.Object2BigDecimal(defaultSample.getOxygenCenterHead(), null));
                            }

                        } else {
                          /*  //已存在数据不覆盖
                            if (null != ybInspectDataDetail.getCarbonContentTail() && ybInspectDataDetail.getCarbonContentTail().compareTo(BigDecimal.ZERO) > 0) {
                                continue;
                            }*/
                            if (!execGradeRule){
                                //W碳含量中心
                                ybInspectDataDetail.setCarbonContentTail(pieceCheck.getcContents());
                                //W氧含量中心
                                ybInspectDataDetail.setOxygenContentTail(pieceCheck.getoContents());
                            }
                        }
                        sectionNoList.add(sectionNoDetailNew.getSectionNo());
                        //添加判断，站点在检验需要评级
                        List<WipStorage> wipStorageList = wipStorageService.findByProcessingByOrderCode(ybInspectDataDetail.getSectionNo());
                        if (!CollectionUtils.isEmpty(wipStorageList)) {
                            WipStorage wipStorage = wipStorageList.get(0);
                            if (StringUtils.equals(wipStorage.getProcessName(), EnumValuesFactory.WipStorageCode.圆棒检验.getValue())) {
                                inspectMaps.put(ybInspectDataDetail.getSectionNo(), ybInspectDataDetail);
                            }
                        }
                        verificationList.add(ybInspectDataDetail);
                        //保存数据
                        ybInspectDataService.saveOrUpdate(ybInspectDataDetail);
                    }
                    //在圆棒站触发评级
                    if (inspectMaps.size() != 0) {
                        gradeService.execGrade(inspectMaps);
                    }

                    //触发方棒头氧值赋值
                    if (sectionNoList.size() != 0) {
                        OxygenCarbonDto oxygenCarbonDto = new OxygenCarbonDto();
                        oxygenCarbonDto.setCContents(pieceCheck.getcContents());
                        oxygenCarbonDto.setOContents(pieceCheck.getoContents());
                        oxygenCarbonDto.setSectionNoList(sectionNoList);
                        oxygenCarbonDto.setHeadFlag(headFlag);
                        fbFeignClients.updateOxygenCarbonByYbSectionNoList(oxygenCarbonDto);
                    }
                }
            }
            this.verificationManagement(verificationList);
        }
    }

    private void handelDefaultContent(YbInspectData ybInspectData, Boolean headFlag, SectionNoDetail sectionNoDetail) {
        if (null == ybInspectData || StringUtils.isBlank(ybInspectData.getCrystalNo())) {
            return;
        }
        if (headFlag) {
            if (null == ybInspectData.getOxygenContentTail()) {
                if (StringUtils.isNotBlank(sectionNoDetail.getPieceNoEnd())) {
                    PieceCheck byPieceNo = this.getByPieceNo(sectionNoDetail.getPieceNoEnd());
                    if (null != byPieceNo) {
                        ybInspectData.setOxygenContentTail(byPieceNo.getoContents());
                        ybInspectData.setCarbonContentTail(byPieceNo.getcContents());
                    }
                } else {
                    //先查询尾段
                    YbInspectData bySectionNoTail = inspectDataBaseService.findByCrystalNoAndOxygenCarbonMark(ybInspectData.getCrystalNo(), 2);
                    if (null == bySectionNoTail || null == ybInspectData.getOxygenContentTail()) {
                        DefaultSample defaultSample = defaultSampleService.findByDopantLikeAndSpecificationsLikeAndProductTypeLike(ybInspectData.getDopant(), ybInspectData.getProductTypeSecond(), ybInspectData.getProductType());
                        ybInspectData.setOxygenContentTail(NumberUtil.Object2BigDecimal(defaultSample.getOxygenCenterTail(), null));
                        ybInspectData.setCarbonContentTail(NumberUtil.Object2BigDecimal(defaultSample.getCarbonCenterTail(), null));
                    } else {
                        ybInspectData.setOxygenContentTail(bySectionNoTail.getOxygenContentTail());
                        ybInspectData.setCarbonContentTail(bySectionNoTail.getCarbonContentTail());
                    }
                }

            }

        } else {
            if (null == ybInspectData.getOxygenContentHead()) {
                if (StringUtils.isNotBlank(sectionNoDetail.getPieceNoHead())) {
                    PieceCheck byPieceNoHead = this.getByPieceNo(sectionNoDetail.getPieceNoHead());
                    if (null != byPieceNoHead) {
                        ybInspectData.setOxygenContentHead(byPieceNoHead.getoContents());
                        ybInspectData.setCarbonContentHead(byPieceNoHead.getcContents());
                    }
                } else {
                    //先查询尾段
                    YbInspectData bySectionNoHead = inspectDataBaseService.findByCrystalNoAndOxygenCarbonMark(ybInspectData.getCrystalNo(), 1);
                    if (null == bySectionNoHead || null == ybInspectData.getOxygenContentHead()) {
                        DefaultSample defaultSample = defaultSampleService.findByDopantLikeAndSpecificationsLikeAndProductTypeLike(ybInspectData.getDopant(), ybInspectData.getProductTypeSecond(), ybInspectData.getProductType());
                        ybInspectData.setOxygenContentHead(NumberUtil.Object2BigDecimal(defaultSample.getOxygenCenterHead(), null));
                        ybInspectData.setCarbonContentHead(NumberUtil.Object2BigDecimal(defaultSample.getCarbonCenterHead(), null));
                    } else {
                        ybInspectData.setOxygenContentHead(bySectionNoHead.getOxygenContentHead());
                        ybInspectData.setCarbonContentHead(bySectionNoHead.getCarbonContentHead());
                    }
                }
            }
        }

    }

    private void handleSectionNoInfo(SectionNoDetail sectionNoDetail, PieceCheck pieceCheck, String pieceNo) {
        if (null == sectionNoDetail || null == pieceCheck || StringUtils.isBlank(pieceNo)) {
            return;
        }

        if (StringUtils.equals(pieceNo, sectionNoDetail.getPieceNoHead())) {
            if (sectionNoDetail.getSectionPosiotion() == 1) {
                List<SectionNoDetail> byCrystalNo = sectionNoDetailDao.findByCrystalNo(sectionNoDetail.getCrystalNo());
                for (SectionNoDetail sectionNoDetail1 : byCrystalNo) {
                    this.handleContent(pieceCheck, sectionNoDetail1, true);
                }
            } else {
                this.handleContent(pieceCheck, sectionNoDetail, true);
            }
            return;
        }

        if (StringUtils.equals(pieceNo, sectionNoDetail.getPieceNoEnd())) {
            String sampleTail = pieceNo.substring(2, 3);
            if (StringUtils.equals(sampleTail, "T")) {
                List<SectionNoDetail> byCrystalNo = sectionNoDetailDao.findByCrystalNo(sectionNoDetail.getCrystalNo());
                for (SectionNoDetail sectionNoDetail2 : byCrystalNo) {
                    this.handleContent(pieceCheck, sectionNoDetail2, false);
                }
            } else {
                this.handleContent(pieceCheck, sectionNoDetail, false);
            }
            return;
        }
    }

    private void handleContent(PieceCheck pieceCheck, SectionNoDetail sectionNoDetail, Boolean headFlag) {
        if (null == pieceCheck || null == sectionNoDetail) {
            return;
        }
        List<YbInspectData> verificationList = new ArrayList<>();
        YbInspectData ybInspectData = inspectDataBaseService.findBySectionNo(sectionNoDetail.getSectionNo());
        if (null == ybInspectData) {
            return;
        }
        if (headFlag) {
            //T氧含量中心
            ybInspectData.setOxygenContentHead(pieceCheck.getoContents());
            //T碳含量中心
            ybInspectData.setCarbonContentHead(pieceCheck.getcContents());
        } else {
            //W氧含量中心
            ybInspectData.setOxygenContentTail(pieceCheck.getoContents());
            //W碳含量中心
            ybInspectData.setCarbonContentTail(pieceCheck.getcContents());
        }
        verificationList.add(ybInspectData);
        this.inspectDataBaseService.saveDataAndGrade(ybInspectData);
       /* if (ybInspectData.getSectionNo().endsWith("T") || ybInspectData.getSectionNo().endsWith("A") || (null != sectionNoDetail.getSectionPosiotion() && sectionNoDetail.getSectionPosiotion() == 2)){
            this.inspectDataBaseService.saveDataAndGrade(ybInspectData);
        }else {
            inspectDataBaseService.saveOrUpdate(ybInspectData);
        }*/

        this.verificationManagement(verificationList);
    }

    private void verificationManagement(List<YbInspectData> list){
        ThreadManager.getThreadPollProxy().execute(() -> {
            for(YbInspectData ybInspectData : list){
                Map<String, Object> bySectionNoMap = BeanUtil.convertObjectToMap(ybInspectData, YbInspectData.class);
                //处理预警机制
                ybInspectDataService.verificationManagement(bySectionNoMap);
            }
        });
    }


    private void supplementaryData(String pieceNo, PieceCheck pieceCheck, List<SectionNoDetail> sectionNoDetailList) {
        for (SectionNoDetail sectionNoDetail : sectionNoDetailList) {
            // 查询该晶段是否已经有检验数据
            List<YbInspectData> inspectData = inspectDataBaseDao.findBySectionNo(sectionNoDetail.getSectionNo());
            if (inspectData.size() > 0) {
                YbInspectData inspectDataBase = inspectData.get(0);
                List<ProductionBackCuttingRecord> allBySegmentNo = productionRecutService.findAllBySegmentNo(inspectDataBase.getSectionNo());
                if (!CollectionUtils.isEmpty(allBySegmentNo)) {
                    continue;
                }
                // 如果是头片
                if (sectionNoDetail.getPieceNoHead() != null && sectionNoDetail.getPieceNoHead().equals(pieceNo)) {
                    if (pieceCheck != null) {
                        if (pieceCheck.getoContents() != null) {
                            inspectDataBase.setOxygenContentHead(pieceCheck.getoContents());
                        }
//                        if (pieceCheck.getoBorderContents() != null) {//氧含量 边缘
//                            inspectDataBase.setOxygenContentBorder(pieceCheck.getoBorderContents());
//                        }
//                        else {
//                            // 改为空则引用默认值
//                            DefaultSample sample = this.defaultSampleService.findByDopantLikeAndSpecificationsLike(inspectDataBase.getDopant(), byCrystalNo.getSpecs());
//                            if (sample != null) {
//                                if (sample.getOxygenEdge().equals("/")) {
//                                    inspectDataBase.setOxygenContentBorder(null);
//                                } else {
//                                    inspectDataBase.setOxygenContentBorder(new BigDecimal(sample.getOxygenEdge()));
//                                }
//                            }
//                        }
                        if (pieceCheck.getcContents() != null) {
                            inspectDataBase.setCarbonContentHead(pieceCheck.getcContents());
                        }
//                        if (pieceCheck.getcBorderContents() != null) {// 边缘碳含量
//                            inspectDataBase.setCarbonContentBorder(pieceCheck.getcBorderContents());
//                        }
//                        else {
//                            // 改为空则引用默认值
//                            DefaultSample sample = this.defaultSampleService.findByDopantLikeAndSpecificationsLike(inspectDataBase.getDopant(), byCrystalNo.getSpecs());
//                            if (sample != null) {
//                                if (sample.getCarbonEdge().equals("/")) {
//                                    inspectDataBase.setCarbonContentBorder(null);
//                                } else {
//                                    inspectDataBase.setCarbonContentBorder(new BigDecimal(sample.getCarbonEdge()));
//                                }
//                            }
//                        }
                        if (pieceCheck.getCenterAnneal() != null) {
//                            inspectDataBase.setTCenterAnneal(pieceCheck.getCenterAnneal());
                        }
                        if (pieceCheck.getBorderAnneal() != null) {
//                            inspectDataBase.setTBorderAnneal(pieceCheck.getBorderAnneal());
                        }


                        // inspectDataBase.setHeadDefectGrade(pieceCheck.getMicroDefect());// 微缺陷一直用默认值
//                            if (com.sw.mes.common.utils.StringUtils.isNotBlank(pieceCheck.getLineDefect()) && pieceCheck.getLineDefect().contains("有")) {
//                                inspectDataBase.setIsMalposition(1);// 位错一直用默认值
//                            } else {
//                                inspectDataBase.setIsMalposition(0);
//                            }
                        // 导电型号是N才赋值
                        if (inspectDataBase.getConductiveType() != null && inspectDataBase.getConductiveType().equals("N") && pieceCheck.getCenterAnneal() != null) {
//                            // 中心退火电阻率
//                            inspectDataBase.setTCenterAnneal(pieceCheck.getCenterAnneal());
//                            // 边缘退火电阻率
//                            inspectDataBase.setTBorderAnneal(pieceCheck.getBorderAnneal());
                        }
                        // 更新检验数据库头片信息
                        this.inspectDataBaseService.saveDataAndGrade(inspectDataBase);


                        try {
                            ybInspectDataService.saveDataInspectLog(inspectDataBase);//保存圆棒检验记录表
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    //尾片
                } else if (sectionNoDetail.getPieceNoEnd() != null && sectionNoDetail.getPieceNoEnd().equals(pieceNo)) {
                    if (pieceCheck != null) {
                        if (pieceCheck.getoContents() != null) {
                            inspectDataBase.setOxygenContentTail(pieceCheck.getoContents());
                        }
//                        if (pieceCheck.getoBorderContents() != null) {//氧含量 边缘
//                            inspectDataBase.setOxygenContentBorderTail(pieceCheck.getoBorderContents());
//                        }
//                            else {
//                            // 改为空则引用默认值
//                            DefaultSample sample = this.defaultSampleService.findByDopantLikeAndSpecificationsLike(inspectDataBase.getDopant(), byCrystalNo.getSpecs());
//                            // 氧含量边缘
//                            if (sample != null) {
//                                if (sample.getOxygenEdge().equals("/")) {
//                                    inspectDataBase.setOxygenContentBorderTail(null);
//                                } else {
//                                    inspectDataBase.setOxygenContentBorderTail(new BigDecimal(sample.getOxygenEdge()));
//                                }
//                            }
//                       }
                        if (pieceCheck.getcContents() != null) {
                            inspectDataBase.setCarbonContentTail(pieceCheck.getcContents());
                        }
//                        if (pieceCheck.getcBorderContents() != null) {// 边缘碳含量
//                            inspectDataBase.setCarbonContentBorderTail(pieceCheck.getcBorderContents());
//                        }
//                        else {
//                            // 改为空则引用默认值
//                            DefaultSample sample = this.defaultSampleService.findByDopantLikeAndSpecificationsLike(inspectDataBase.getDopant(), byCrystalNo.getSpecs());
//                            if (sample != null) {
//                                if (sample.getCarbonEdge().equals("/")) {
//                                    inspectDataBase.setCarbonContentBorderTail(null);
//                                } else {
//                                    inspectDataBase.setCarbonContentBorderTail(new BigDecimal(sample.getCarbonEdge()));
//                                }
//                            }
//                        }
//                        if (pieceCheck.getCenterAnneal() != null) {
//                            inspectDataBase.setWcenterAnneal(pieceCheck.getCenterAnneal());
//                        }
//                        if (pieceCheck.getBorderAnneal() != null) {
//                            inspectDataBase.setWBorderAnneal(pieceCheck.getBorderAnneal());
//                        }


                        // inspectDataBase.setTailDefect(pieceCheck.getMicroDefect());// 微缺陷一直用默认值


//                            if (com.sw.mes.common.utils.StringUtils.isNotBlank(pieceCheck.getLineDefect()) && pieceCheck.getLineDefect().contains("有")) {
//                                inspectDataBase.setIsMalposition(1);// 位错一直用默认值
//                            } else {
//                                inspectDataBase.setIsMalposition(0);
//                            }
                        // 导电型号是N才赋值
                        if (inspectDataBase.getConductiveType() != null && inspectDataBase.getConductiveType().equals("N") && pieceCheck.getCenterAnneal() != null) {
//                            // 中心退火电阻率
//                            inspectDataBase.setWcenterAnneal(pieceCheck.getCenterAnneal());
//                            // 边缘退火电阻率
//                            inspectDataBase.setWBorderAnneal(pieceCheck.getBorderAnneal());
                        }
                        // 更新检验数据库尾片信息
                        this.inspectDataBaseService.saveDataAndGrade(inspectDataBase);

                        try {
                            ybInspectDataService.saveDataInspectLog(inspectDataBase);//保存圆棒检验记录表
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        }
    }

    @Override
    public void savePieceCheck(List<PieceCheck> pieceChecks) {
        if (pieceChecks.size() > 0) {
            saveOrUpdateInBatch(pieceChecks, "样片检验-新增");
        }
    }

    @Override
    public void synchronizationPieceCheck(List<PieceCheck> pieceChecks) {
        saveOrUpdateInBatch(pieceChecks, "样片检验-新增");
        for (PieceCheck pieceCheck : pieceChecks) {
            // 同步更新晶段检验样片信息
            saveInspectDataBaseInfoNew(pieceCheck);
        }
    }
}
