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

import com.alibaba.fastjson.JSON;
import com.sw.mes.base.factory.inspect.entity.LevelCodeMaintenance;
import com.sw.mes.base.factory.inspect.service.DefaultCrystalAttrService;
import com.sw.mes.base.factory.inspect.service.LevelCodeMaintenanceService;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.RankResultDto;
import com.sw.mes.core.dto.YbInspectDataToMcsDto;
import com.sw.mes.core.enums.EnumValues;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.BeanUtil;
import com.sw.mes.core.utils.DateUtil;
import com.sw.mes.core.utils.NumberUtil;
import com.sw.mes.grade.dao.RuleTestDataDao;
import com.sw.mes.grade.dto.GradeResultDto;
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.RuleTestService;
import com.sw.mes.gread.common.EnumValuesGrade;
import com.sw.mes.gread.dto.CalculationResultDto;
import com.sw.mes.gread.dto.CalculationResultIfDto;
import com.sw.mes.gread.entity.FieldPool;
import com.sw.mes.gread.entity.GradeRule;
import com.sw.mes.gread.entity.GradeType;
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.GradeTypeService;
import com.sw.mes.gread.service.GradeVersionService;
import com.sw.mes.inspect.entity.YbInspectData;
import com.sw.mes.inspect.service.YbInspectDataService;
import com.sw.mes.yb.mcs.service.PublishRankResultService;
import com.sw.mes.yb.pc.entity.Section;
import com.sw.mes.yb.pc.service.SectionService;
import com.sw.mes.yb.plan.entity.YbProductionOrder;
import com.sw.mes.yb.plan.service.ProductionOrderService;
import com.sw.mes.yb.plan.service.YbProductionOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

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

@Slf4j
@Service
@Transactional
public class GradeImpl implements GradeService {
    @Autowired
    private GradeVersionService gradeVersionService;
    @Autowired
    private RuleTestService ruleTestService;
    @Autowired
    private RuleTestDataDao ruleTestDataDao;
    @Autowired
    private FieldPoolService fieldPoolService;
    @Autowired
    private GradeRuleService gradeRuleService;
    @Autowired
    private GradeTypeService gradeTypeService;
    @Autowired
    private YbInspectDataService inspectDataBaseService;
    @Autowired
    private ProductionOrderService productionOrderService;

    @Autowired
    private PublishRankResultService publishRankResultService;

    @Autowired
    private YbProductionOrderService ybProductionOrderService;

    @Autowired
    private SectionService sectionService;
    @Autowired
    private DefaultCrystalAttrService defaultCrystalAttrService;

    @Autowired
    private YbInspectDataService ybInspectDataService;

    @Autowired
    private LevelCodeMaintenanceService levelCodeMaintenanceService;

    @Override
    public void pushGradeVersion(GradeVersion gradeVersion, String remarks) {
        try {
            gradeVersionService.pushGradeVersion(gradeVersion, remarks);
        } catch (Exception e) {
            //手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException("评级版本状态修改失败：" + e.getMessage());
        }
        //重新评级
    }

    @Override
    public void execGrade(Map<String, YbInspectData> inspectMaps) {
        GradeVersion gradeVersion = gradeVersionService.findTopByStatusAndRegion(EnumValuesGrade.GradeVersionStatus.已生效.getKey(), EnumValuesGrade.Region.圆棒.getKey());
        if (gradeVersion == null) {
            return;
        }
        if (inspectMaps != null && inspectMaps.size() > 0) {
            //指定晶段评级
            this.testGradeVersion(gradeVersion, inspectMaps, false, null, null, EnumValues.ExecType.圆棒触发.getKey(), "正常评级-检验数据变动");
        } else {
            //全部可评级晶段评级
        }
    }

    @Override
    public Result testGradeVersion(GradeVersion gradeVersion, Map<String, YbInspectData> inspectMaps, boolean isTest, String specificationsA, BigDecimal length, int execType, String remarks) {
        RuleTest ruleTest = new RuleTest();
        ruleTest.setGradeVersion(gradeVersion);
        ruleTest.setGmtUpdate(new Date());
        ruleTest.setUserUpdate(BaseContextHandler.getUsername());
        ruleTest.setRemarks(remarks);
        ruleTestService.saveOrUpdate(ruleTest);

        GradeType gradeTypeOne = gradeTypeService.findByNameAndGradeVersionId("一次评级", gradeVersion.getId());
        Long gradeTypeOneId = gradeTypeOne == null ? null : gradeTypeOne.getId();
        GradeType gradeType = gradeTypeService.findByNameAndGradeVersionId("实验等级", gradeVersion.getId());
        Long gradeTypeId = gradeType == null ? -1 : gradeType.getId();
        // 普通评级规则
        List<GradeRule> gradeRules;
        if (execType == EnumValues.ExecType.圆棒触发.getKey()) {
            gradeRules = gradeRuleService.findByGradeVersionIdAndGradeTypeIdNotOrderByPriority(gradeVersion.getId(), gradeTypeId);
        } else {
            gradeRules = gradeRuleService.findByGradeVersionIdAndGradeTypeIdAndGradeTypeOrderByPriority(gradeVersion.getId(), gradeTypeOneId, "正常");
        }
        List<FieldPool> fieldPools = fieldPoolService.findByRegion(EnumValuesGrade.Region.圆棒.getKey());
        Map<String, FieldPool> fieldPoolMap = new HashMap<>();
        for (FieldPool fieldPool : fieldPools) {
            fieldPoolMap.put(fieldPool.getName(), fieldPool);
        }

        List<RuleTestData> ruleTestDatas = new LinkedList<>();
        for (Map.Entry<String, YbInspectData> inspectMapItem : inspectMaps.entrySet()) {
            Map<String, Object> inspectMap;
            inspectMap = BeanUtil.convertObjectToMap(inspectMapItem.getValue(), YbInspectData.class);
            if (inspectMap == null) {
                Map<String, Object> inspectMapData = inspectDataBaseService.findBySectionNoMap(inspectMapItem.getKey());
                if (inspectMapData != null && inspectMapData.size() > 0) {
                    inspectMap = new HashMap<>(inspectMapData);
                }
            }
            RuleTestData ruleTestData = new RuleTestData();
            ruleTestData.setGmtUpdate(new Date());
            ruleTestData.setUserUpdate(BaseContextHandler.getUsername());
            ruleTestData.setRuleTestId(ruleTest.getId());
            ruleTestData.setSectionNo(inspectMapItem.getKey());
            if (inspectMap == null) {
                setRuleTestData(ruleTestData, "检验数据不存在");
                ruleTestDatas.add(ruleTestData);
                continue;
            }
            ruleTestData.setGradeOld(NumberUtil.object2String(inspectMap.get("product_level"), null) + "，" + NumberUtil.object2String(inspectMap.get("product_level_experiment"), null));
            //是否指定规格评级
            if (StringUtils.isNotBlank(specificationsA)) {
                inspectMap.put("product_type_second", specificationsA);
            }
            //是否指定长度评级
            if (length != null) {
                inspectMap.put("length", length);
            }
            Object dopantObj = inspectMap.get("dopant");
            Object specificationsObj = inspectMap.get("product_type_second");
            String dopant = dopantObj == null ? null : dopantObj.toString();

            String specificationsFinal = specificationsObj == null ? null : specificationsObj.toString();
            if (StringUtils.isBlank(dopant)) {
                setRuleTestData(ruleTestData, "掺杂剂，数据为空，无法评级");
                ruleTestDatas.add(ruleTestData);
                continue;
            }
            if (StringUtils.isBlank(specificationsFinal)) {
                setRuleTestData(ruleTestData, "规格，数据为空，无法评级");
                ruleTestDatas.add(ruleTestData);
                continue;
            }
            List<GradeRule> gradeRulesThis = getRradeRulesData(gradeRules, dopant, specificationsFinal);
            // 没有评级规则
            if (gradeRulesThis.size() == 0) {
                setRuleTestData(ruleTestData, "版本【" + gradeVersion.getVersion() + "】中，掺杂剂【" + dopant + "】" + "规格【" + specificationsFinal + "】没有评级规则");
                ruleTestDatas.add(ruleTestData);
                if (!isTest && execType == EnumValues.ExecType.圆棒触发.getKey()) {
                    //计算公式，计算结果
                    Map<String, String> resultMap = new HashMap<>();
                    calculationFormula(inspectMap, resultMap, fieldPools, null);
                    // 计算并保存公式结果
                    this.saveGrade(inspectMap, resultMap);
                    YbInspectData inspectDataBase = JSON.parseObject(JSON.toJSONString(inspectMap), YbInspectData.class);
                    inspectMapItem.setValue(inspectDataBase);
                }
                continue;
            }
            Map<String, CalculationResultDto> combinedField = new HashMap<>();
            GradeResultDto gradeResultDto = refreshGrade(inspectMap, gradeRulesThis, fieldPoolMap, combinedField, gradeTypeOneId, gradeTypeId, gradeVersion, dopant, specificationsFinal);
            ruleTestData.setGrade(NumberUtil.object2String(gradeResultDto.getGrade(), ""));
            ruleTestData.setStatus(gradeResultDto.getGradeStatus() ? 1 : 0);
            List<CalculationResultIfDto> calculationResultIfDtos = gradeResultDto.getCalculationResultIfDtos();
            ruleTestData.setProcess(JSON.toJSONString(calculationResultIfDtos));
            ruleTestData.setGradeData(gradeResultDto.getGradeData());
            ruleTestDatas.add(ruleTestData);

            //获取最终规格
            String specifications;
            //将评级结果存至圆棒检验数据库，计算并保存公式结果
            //2022-02-15 修改，方棒重新触发评级，不将评级结果保存在圆棒检验数据库，只返回评级结果
            if (!isTest && execType == EnumValues.ExecType.圆棒触发.getKey()) {
                //拼棒
                Integer sticksCount = NumberUtil.Object2Integer(inspectMap.get("sticks_count"), 1);
                //获取晶棒长度，如果拼棒则获取拼棒长度
                BigDecimal actualLength = (sticksCount != null && sticksCount.compareTo(1) > 0) ? NumberUtil.Object2BigDecimal(inspectMap.get("spell_bar_length"))
                        : NumberUtil.Object2BigDecimal(inspectMap.get("actual_length"));

                Map<String, String> resultMap = new HashMap<>();
                resultMap.put("grade_version", gradeVersion.getVersion().toString());
                //是否转规格
                if (StringUtils.isNotBlank(gradeResultDto.getSpecifications())) {
                    resultMap.put("product_type_second", gradeResultDto.getSpecifications());
                    specifications = gradeResultDto.getSpecifications();
                } else {
                    specifications = NumberUtil.object2String(inspectMap.get("product_type_second"), null);
                }
                //处理评级结果
                execGradeResult(ruleTestData, gradeResultDto, resultMap);
                //获取评级
                String grade = resultMap.get("product_level"), testRank = resultMap.get("product_level_experiment");

                //等级码处理
                LevelCodeMaintenance levelCodeMaintenance = levelCodeMaintenanceService.findByModelAndSpecificationAndProductLevel(dopant, specifications, grade);
                if (null != levelCodeMaintenance){
                    resultMap.put("level_code",levelCodeMaintenance.getLevelCode());
                }else {
                    resultMap.put("level_code",null);
                }
                // 新的规格判断晶段类型
                resultMap.put("section_type", defaultCrystalAttrService.getDefaultCrystalAttrOneTimes(dopant, specifications, grade, actualLength));

                resultMap.put("grade_data", gradeResultDto.getGradeData());
                //导电型号
                String conductiveType = NumberUtil.object2String(inspectMap.get("conductive_type"), null);
                //计算公式，计算结果
                calculationFormula(inspectMap, resultMap, fieldPools, combinedField);
                String sectionType = NumberUtil.object2String(inspectMap.get("section_type"), null);
                // 评级成功，匹配订单
                // 产品等级、规格、型号、掺杂剂、拼接、长度范围
                if (gradeResultDto.getGradeStatus()) {
                    //如果为正常，则匹配订单与料号
                   /* if ("正常".equals(gradeResultDto.getGradeRule().getGradeType())) {
                        //匹配料号
                        String productModelCode = productionOrderService.matchProductModel(inspectMapItem.getKey(), resultMap.get("diam_decide"), grade, specifications, conductiveType, dopant, sticksCount, actualLength, sectionType);
                        resultMap.put("material_code", productModelCode);
                        YbProductionOrder ybProductionOrder = ybProductionOrderService.getYbProductionOrderByMk(inspectMap, productModelCode);
                        if (ybProductionOrder != null) {
                            resultMap.put("order_no", ybProductionOrder.getAufnr());
                        }
                    }*/
                    //评级成功，下发评级结果
                    RankResultDto rankResultDto = new RankResultDto();
                    rankResultDto.setProductRank(grade);
                    rankResultDto.setTestRank(testRank);
                    rankResultDto.setSectionNo(inspectMapItem.getKey());
                    //掺杂剂
                    rankResultDto.setDopant(dopant);
                    //单晶规格
                    rankResultDto.setSpecs(specifications);
                    //导电型号
                    rankResultDto.setConductiveType(conductiveType);
                    //单晶总长
                    rankResultDto.setLength(actualLength);
                    rankResultDto.setType(sectionType);
                    rankResultDto.setGradeType(gradeResultDto.getGradeRule().getGradeType());
                    if (StringUtils.equals("反切",gradeResultDto.getGradeRule().getGradeType())){
                        resultMap.put("back_cut","1");
                    }
                    rankResultDto.setSticksCount(sticksCount);
                    rankResultDto.setData(sectionType);
                    YbInspectDataToMcsDto pinKuData = ybInspectDataService.getPinKuData(inspectMapItem.getValue(), rankResultDto);
                    rankResultDto.setYbInspectDataToMcsDto(pinKuData);
                    setRankResultDto(rankResultDto, inspectMap);
                }
                // 保存评级结果，计算公式结果
                this.saveGrade(inspectMap, resultMap);
                // 将计算公式算完的检验信息赋值到参数map中，调用方有用到
                YbInspectData inspectDataBase = JSON.parseObject(JSON.toJSONString(inspectMap), YbInspectData.class);
                inspectMapItem.setValue(inspectDataBase);
            }
        }

        ruleTestDataDao.saveAll(ruleTestDatas);
        if (execType == EnumValues.ExecType.圆棒触发.getKey()) {
            return ResultGenerator.success(ruleTest.getId());
        } else {
            if (ruleTestDatas.get(0).getStatus() == 1) {
                return ResultGenerator.success(ruleTestDatas.get(0).getGrade());
            } else {
                return ResultGenerator.fail("评级失败");
            }
        }
    }

    private void execGradeResult(RuleTestData ruleTestData, GradeResultDto gradeResultDto, Map<String, String> resultMap) {
        if (gradeResultDto.getGradeStatus()) {
            resultMap.put("grade_type", gradeResultDto.getGradeRule().getGradeType());
            if (ruleTestData.getGrade() != null) {
                String[] radeArr = ruleTestData.getGrade().split("，");
                if (radeArr.length > 0) {
                    //评级
                    resultMap.put("product_level", radeArr[0]);
                } else {
                    resultMap.put("product_level", null);
                }
                if (radeArr.length > 1 && !"未匹配到实验等级".equals(radeArr[1])) {
                    //实验等级
                    resultMap.put("product_level_experiment", radeArr[1]);
                } else {
                    resultMap.put("product_level_experiment", null);
                }
            }
        } else {
            resultMap.put("product_level", null);
            resultMap.put("product_level_experiment", null);
            resultMap.put("grade_type", "");
        }
    }

    /**
     * 下发评级结果至wms,mcs
     *
     * @param rankResultDto
     * @param inspectMap
     */
    private void setRankResultDto(RankResultDto rankResultDto, Map<String, Object> inspectMap) {
        //下发wms需要字段
        //实际重量
        BigDecimal actualWeight = NumberUtil.Object2BigDecimal(inspectMap.get("actual_weight"));
        //理论重量
        BigDecimal theoryWeight = NumberUtil.Object2BigDecimal(inspectMap.get("theory_weight"));
        if (rankResultDto.getSticksCount() != null && rankResultDto.getSticksCount().compareTo(1) > 0) {
            //查询粘圆棒整棒信息
            Section section = sectionService.findBySectionNo(rankResultDto.getSectionNo());
            if (section != null) {
                actualWeight = section.getActualWeight();
                theoryWeight = section.getTheoryWeight();
            }
        }
        rankResultDto.setActualLength(NumberUtil.Object2BigDecimal(inspectMap.get("actual_length")));
        rankResultDto.setCrystalNo(NumberUtil.object2String(inspectMap.get("crystal_no"), null));
        rankResultDto.setWareHouseLength(NumberUtil.Object2BigDecimal(inspectMap.get("ware_house_length")));
        rankResultDto.setActualWeight(actualWeight);
        rankResultDto.setTheoryWeight(theoryWeight);
        rankResultDto.setSideLengthRange(NumberUtil.object2String(inspectMap.get("side_length_range"), null));
        rankResultDto.setDiameterMin(NumberUtil.Object2BigDecimal(inspectMap.get("diameter_min")));
        rankResultDto.setDiameterMax(NumberUtil.Object2BigDecimal(inspectMap.get("diameter_max")));
        rankResultDto.setDiameterJudge(NumberUtil.object2String(inspectMap.get("diam_decide"), ""));
        rankResultDto.setDistortion(NumberUtil.Object2BigDecimal(inspectMap.get("distortion")));
        rankResultDto.setIsBevel(NumberUtil.object2String(inspectMap.get("is_bevel"), null));
        rankResultDto.setFineDiameter(NumberUtil.Object2BigDecimal(inspectMap.get("fine_diameter")));
        rankResultDto.setFineCutLength(NumberUtil.Object2BigDecimal(inspectMap.get("fine_cut_length")));
        rankResultDto.setPiecewiseNum(NumberUtil.Object2Integer(inspectMap.get("piecewise_num"), 1));

        rankResultDto.setAgainNum(NumberUtil.Object2Integer(inspectMap.get("again_num"), 1));
        rankResultDto.setHeadTailRecognition(NumberUtil.object2String(inspectMap.get("head_tail_recognition"), null));
        rankResultDto.setIsSeeBottom(NumberUtil.Object2Integer(inspectMap.get("is_see_bottom"), 0));
        rankResultDto.setLineMarking(NumberUtil.object2String(inspectMap.get("line_marking"), null));
        rankResultDto.setIsCutBack(NumberUtil.Object2Integer(inspectMap.get("is_cut_back"), 0));
        // 圆棒评级下发
        publishRankResultService.publishRankResult(rankResultDto);
    }

    public void calculationFormula(Map<String, Object> inspectMap, Map<String, String> resultMap, List<FieldPool> fieldPoolsAll, Map<String, CalculationResultDto> combinedField) {
        List<FieldPool> fieldPools = new ArrayList<>();
        Map<String, FieldPool> fieldPoolsClasss1Map = new HashMap<>();
        for (FieldPool fieldPool : fieldPoolsAll) {
            if (fieldPool.getClasss() == 2 && fieldPool.getIsSaveData()) {
                fieldPools.add(fieldPool);
            } else {
                fieldPoolsClasss1Map.put(fieldPool.getName(), fieldPool);
            }
        }
        if (resultMap != null && resultMap.size() > 0) {
            inspectMap.putAll(resultMap);
        } else {
            resultMap = new HashMap<>();
        }
        if (combinedField == null) {
            combinedField = new HashMap<>();
        }
        for (FieldPool fieldPool : fieldPools) {
            if (!combinedField.containsKey(fieldPool.getCode()) || !combinedField.get(fieldPool.getCode()).getResultType()) {
                Result<String> result = fieldPoolService.exceCalculationProd(fieldPool, inspectMap, fieldPoolsClasss1Map);
                if (result.getCode() == ResultCode.SUCCESS.getCode()) {
                    resultMap.put(fieldPool.getCode(), result.getData());
                }
            } else {
                resultMap.put(fieldPool.getCode(), combinedField.get(fieldPool.getCode()).getResult().toString());
            }
            if ("is_cut_back".equals(fieldPool.getCode())) {
                resultMap.putIfAbsent("is_cut_back", "0");
            }
        }
        if (resultMap.size() > 0) {
            inspectMap.putAll(resultMap);
        }
    }

    /**
     * 将评级结果存至圆棒检验数据库
     *
     * @param inspectMap
     * @param resultMap
     */
    @Override
    public void saveGrade(Map<String, Object> inspectMap, Map<String, String> resultMap) {
        resultMap.put("level_time", DateUtil.formatDate(new Date(), DateUtil.longFormat));
        StringBuilder sql = new StringBuilder();
        sql.append("UPDATE yb_inspect_data SET ");
        int index = 1, mapCount = resultMap.size();
        for (Map.Entry<String, String> entry : resultMap.entrySet()) {
            if (entry.getValue() == null) {
                sql.append(entry.getKey()).append(" =").append(entry.getValue()).append(" ");
            } else {
                sql.append(entry.getKey()).append(" ='").append(entry.getValue()).append("' ");
            }

            if (index < mapCount) {
                sql.append(",");
            }
            index++;
        }
        sql.append(" WHERE id = ").append(inspectMap.get("id"));
        try {
            ruleTestService.excuteUpdate(sql.toString());
        } catch (Exception e) {
            log.error("保存评级结果失败，请查看日志：" + e.getMessage());
            throw new RuntimeException("保存评级结果失败，请查看日志：" + e.getMessage());
        }
        System.out.println("执行保存：评级和计算公式结果，" + sql);
    }

    @Override
    public void setRuleTestData(RuleTestData ruleTestData, String message) {
        GradeResultDto gradeResultDto = new GradeResultDto();
        gradeResultDto.setGrade(null);
        gradeResultDto.setGradeStatus(false);
        List<CalculationResultIfDto> calculationResultIfDtos = new LinkedList<>();
        CalculationResultIfDto calculationResultIfDto = new CalculationResultIfDto();
        calculationResultIfDto.setMessage(message);
        calculationResultIfDto.setResultType(false);
        calculationResultIfDtos.add(calculationResultIfDto);
        gradeResultDto.setCalculationResultIfDtos(calculationResultIfDtos);

        ruleTestData.setGrade(null);
        ruleTestData.setProcess(JSON.toJSONString(gradeResultDto));
        ruleTestData.setStatus(0);
    }

    /**
     * 筛选评级规则
     *
     * @param gradeRules
     * @param dopant
     * @param specifications
     */
    public List<GradeRule> getRradeRulesData(List<GradeRule> gradeRules, String dopant, String specifications) {
        List<GradeRule> gradeRulesData = new LinkedList<>();
        for (GradeRule gradeRule : gradeRules) {
            if (dopant != null && specifications != null && dopant.equals(gradeRule.getDopant()) && specifications.equals(gradeRule.getSpecifications())) {
                gradeRulesData.add(gradeRule);
            }
        }
        return gradeRulesData;
    }

    /**
     * @param inspectMap
     * @param gradeRules
     * @param fieldPoolMap
     * @param combinedField
     * @param gradeTypeId
     * @param dopant
     * @param specifications
     * @return
     */
    public GradeResultDto refreshGrade(Map<String, Object> inspectMap, List<GradeRule> gradeRules, Map<String, FieldPool> fieldPoolMap, Map<String, CalculationResultDto> combinedField, Long gradeTypeOneId, Long gradeTypeId, GradeVersion gradeVersion, String dopant, String specifications) {
        GradeResultDto gradeResultDto = new GradeResultDto();
        List<CalculationResultIfDto> calculationResultIfDtos = new LinkedList<>();
        boolean gradeStatus = false;
        int index = 0, index1 = 0;
        // 计算评级
        OUT:
        for (GradeRule gradeRule : gradeRules) {
            index++;
            index1 = 0;
            String[] conditionsArr = gradeRule.getConditions() == null ? new String[]{} : gradeRule.getConditions().split("\\[OR\\]");
            for (String conditions : conditionsArr) {
                index1++;
                if (conditions != null) {
                    CalculationResultIfDto result = fieldPoolService.exceGrade(conditions, inspectMap, fieldPoolMap, combinedField);
                    result.setIndex(index + "-" + index1);
                    result.setGrade(gradeRule.getGrade());
                    calculationResultIfDtos.add(result);
                    //评级成功，成功返回评级结果
                    if (result.getResultType()) {
                        //当前等级，评级成功
                        if (result.getResult() != null && result.getResult()) {
                            gradeStatus = true;
                            gradeResultDto.setGrade(gradeRule.getGrade());
                            gradeResultDto.setGradeRule(gradeRule);
                            gradeResultDto.setGradeTypeId(gradeRule.getGradeTypeId());
                            break OUT;
                        }
                    } else { //评级失败，不继续评级
                        break OUT;
                    }
                }
            }
        }
        gradeResultDto.setGradeStatus(gradeStatus);
        gradeResultDto.setCalculationResultIfDtos(calculationResultIfDtos);
        if (gradeResultDto.getGradeStatus()) {
            //评级分类
            String gradeType = gradeResultDto.getGradeRule().getGradeType();
            //分类明细
            String classDetails = gradeResultDto.getGradeRule().getClassDetails();
            //分段 返切 取片
            if ("反切".equals(gradeType) || "分段".equals(gradeType) || "取片".equals(gradeType)) {
                if (classDetails.contains("@")) {
                    String[] classDetailsArr = classDetails.split(",");
                    for (int i = 0; i < classDetailsArr.length; i++) {
                        String classDetailsItem = classDetailsArr[i];
                        if (classDetailsItem.contains("@")) {
                            String[] classDetailsItemArr = classDetailsItem.split(":");
                            String name = classDetailsItemArr[1].replace("@", "");
                            CalculationResultDto calculationResultDto = combinedField.get(name.trim());
                            Object length = "";
                            if (null != calculationResultDto){
                                length = calculationResultDto.getResult();
                            }
//                            Object length = calculationResultDto.getResult();
                            classDetailsArr[i] = classDetailsItemArr[0] + ":" + length.toString();
                        }
                    }
                    classDetails = StringUtils.join(classDetailsArr, ",");
                }
                gradeResultDto.setGrade(gradeResultDto.getGrade() + "，未匹配到实验等级");
                gradeResultDto.setGradeData(classDetails);
                return gradeResultDto;
            }
            //转规格
            else if ("转规格".equals(gradeType)) {
                specifications = classDetails.split(":")[1];
                List<GradeRule> experimentalGradeRules = gradeRuleService.findByGradeVersionIdAndGradeTypeIdNotOrderByPriority(gradeVersion.getId(), gradeTypeId);
                experimentalGradeRules = getRradeRulesData(experimentalGradeRules, dopant, specifications);
                if (experimentalGradeRules.size() > 0) {
                    Map<String, Object> inspectNewMap = new HashMap<>(inspectMap);
                    inspectNewMap.put("product_type_second", specifications);
                    gradeResultDto.setSpecifications(specifications);
                    combinedField = new HashMap<>();
                    GradeResultDto gradeResultDtoNew = refreshGrade(inspectNewMap, experimentalGradeRules, fieldPoolMap, combinedField, gradeTypeOneId, gradeTypeId, gradeVersion, dopant, specifications);
                    calculationResultIfDtos.addAll(gradeResultDtoNew.getCalculationResultIfDtos());
                    if (gradeResultDtoNew.getGradeStatus()) {
                        gradeResultDto.setGrade(gradeResultDtoNew.getGrade());
                        gradeResultDto.setGradeData(gradeResultDtoNew.getGradeData());
                        gradeResultDto.setGradeRule(gradeResultDtoNew.getGradeRule());
                    } else { //新规格，评级失败
                        gradeResultDto.getCalculationResultIfDtos().addAll(gradeResultDtoNew.getCalculationResultIfDtos());
                        gradeResultDto.setGrade(null);
                        gradeResultDto.setGradeStatus(false);
                        return gradeResultDto;
                    }
                } else { //新规格，评级失败
                    CalculationResultIfDto calculationResultIfDto = new CalculationResultIfDto();
                    calculationResultIfDto.setMessage("版本【" + gradeVersion.getVersion() + "】中，掺杂剂【" + dopant + "】" + "规格【" + specifications + "】没有评级规则");
                    calculationResultIfDto.setResultType(false);
                    gradeResultDto.getCalculationResultIfDtos().add(calculationResultIfDto);
                    gradeResultDto.setGrade(null);
                    gradeResultDto.setGradeStatus(false);
                    return gradeResultDto;
                }
            }
            //评实验
            else if ("正常".equals(gradeType) && gradeTypeOneId != null && gradeResultDto.getGradeTypeId() != null && gradeTypeOneId.longValue() == gradeResultDto.getGradeTypeId()) {
                List<GradeRule> experimentalGradeRules = gradeRuleService.findByGradeVersionIdAndGradeTypeIdOrderByPriority(gradeVersion.getId(), gradeTypeId);
                experimentalGradeRules = getRradeRulesData(experimentalGradeRules, dopant, specifications);
                if (experimentalGradeRules.size() > 0) {
                    Map<String, Object> inspectNewMap = new HashMap<>(inspectMap);
                    inspectNewMap.put("product_level", gradeResultDto.getGrade());
                    GradeResultDto gradeResultDtoOne = refreshGrade(inspectNewMap, experimentalGradeRules, fieldPoolMap, combinedField, gradeTypeOneId, gradeTypeId, gradeVersion, dopant, specifications);
                    calculationResultIfDtos.addAll(gradeResultDtoOne.getCalculationResultIfDtos());
                    if (gradeResultDtoOne.getGradeStatus()) {
                        gradeResultDto.setGrade(gradeResultDto.getGrade() + "，" + gradeResultDtoOne.getGrade());
                    } else {
                        gradeResultDto.setGrade(gradeResultDto.getGrade() + "，未匹配到实验等级");
                    }
                }
                //实验等级，评级失败
                else {
                    CalculationResultIfDto calculationResultIfDto = new CalculationResultIfDto();
                    calculationResultIfDto.setMessage("版本【" + gradeVersion.getVersion() + "】中，掺杂剂【" + dopant + "】" + "规格【" + specifications + "】没有【实验】评级规则");
                    calculationResultIfDto.setResultType(true);
                    gradeResultDto.getCalculationResultIfDtos().add(calculationResultIfDto);
                    gradeResultDto.setGrade(gradeResultDto.getGrade() + "，未匹配到实验等级");
                    gradeResultDto.setGradeStatus(true);
                    return gradeResultDto;
                }
            }
        }
        return gradeResultDto;
    }
}

