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

import com.alibaba.fastjson.JSON;
import com.sw.mes.base.factory.product.entity.FbProductModel;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.core.api.system.YbFeignClients;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.mes.pc.yb.YbInspectDataDto;
import com.sw.mes.core.entity.FbCheckOutData;
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.fb.checkout.service.FbCheckOutDataService;
import com.sw.mes.fls.entity.ProductionBindingTray;
import com.sw.mes.fls.service.ProductionBindingTrayService;
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.RuleTestDataService;
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.mcs.enent.EventPublishService;
import com.sw.mes.mcs.enent.SquareRankEvent;
import com.sw.mes.mcs.service.MesToMcsService;
import com.sw.mes.plan.dto.MatchOrderInfo;
import com.sw.mes.plan.service.FbProductionOrderService;
import com.sw.mes.wms.dto.FbRatingResultDto;
import com.sw.mes.wms.dto.FbRatingResultOfDto;
import com.sw.mes.wms.dto.SquareResultDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class GradeImpl implements GradeService {
    @Autowired
    private GradeVersionService gradeVersionService;
    @Autowired
    private RuleTestService ruleTestService;
    @Autowired
    private RuleTestDataService ruleTestDataService;
    @Autowired
    private RuleTestDataDao ruleTestDataDao;
    @Autowired
    private FieldPoolService fieldPoolService;

    @Autowired
    private GradeRuleService gradeRuleService;

    @Autowired
    private GradeTypeService gradeTypeService;

    //    zhxx_Cheate_check_out_data
    @Autowired
    private FbCheckOutDataService fbCheckOutDataService;

    @Autowired
    private FbProductionOrderService fbProductionOrderService;

    @Autowired
    @Qualifier("eventPublishService")
    private EventPublishService publishService;

    @Autowired
    private YbFeignClients ybFeignClients;

    @Autowired
    private ProductionBindingTrayService productionBindingTrayService;

    @Autowired
    private MesToMcsService mesToMcsService;

    @Autowired
    private DictionaryItemService dictionaryItemService;

    @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, FbCheckOutData> fbCheckOutDataMap) {
        GradeVersion gradeVersion = gradeVersionService.findTopByStatusAndRegion(EnumValuesGrade.GradeVersionStatus.已生效.getKey(), EnumValuesGrade.Region.方棒.getKey());
        if (gradeVersion == null) {
            return;
        }
        if (fbCheckOutDataMap != null && fbCheckOutDataMap.size() > 0) {
            //指定晶段评级
            testGradeVersion(gradeVersion, fbCheckOutDataMap, false, "正常评级-检验数据变动");
        } else {
            //全部可评级晶段评级
        }
    }


//    @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, InspectDataBase> inspectMaps) {
//        GradeVersion gradeVersion = gradeVersionService.findTopByStatusAndRegion(EnumValuesGrade.GradeVersionStatus.已生效.getKey(), EnumValuesGrade.Region.方棒.getKey());
//        if (gradeVersion == null) {
//            return;
//        }
//        if (inspectMaps != null && inspectMaps.size() > 0) {
//            //指定晶段评级
//            testGradeVersion(gradeVersion, inspectMaps, false, null, null, EnumValues.ExecType.圆棒触发.getKey());
//        } else {
//            //全部可评级晶段评级
//        }
//    }

    @Override
    public Result<Long> testGradeVersion(GradeVersion gradeVersion, Map<String, FbCheckOutData> fbCheckOutDataMap, boolean isTest, 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 = gradeRuleService.findByGradeVersionIdAndGradeTypeIdNotOrderByPriority(gradeVersion.getId(), gradeTypeId);

        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, FbCheckOutData> inspectMapItem : fbCheckOutDataMap.entrySet()) {
            String sectionNo = inspectMapItem.getKey();
            Map<String, Object> inspectMap;
            inspectMap = BeanUtil.convertObjectToMap(inspectMapItem.getValue(), FbCheckOutData.class);
            if (inspectMap == null) {
                Map<String, Object> inspectMapData = fbCheckOutDataService.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(sectionNo);
            if (inspectMap == null || inspectMap.size() == 0) {
                setRuleTestData(ruleTestData, "检验数据不存在");
                ruleTestDatas.add(ruleTestData);
            } else {

                // 方棒评级测试 评级结果旧字段取值逻辑变更：取上一次评级测试的结果
                RuleTestData ruleTestDataOld =  ruleTestDataDao.findBysectionNo(sectionNo);
                if (null != ruleTestDataOld){
                    ruleTestData.setGradeOld(ruleTestDataOld.getGrade());
                }
//                ruleTestData.setGradeOld(NumberUtil.object2String(inspectMap.get("product_level"), "无") + "，" +
//                        NumberUtil.object2String(inspectMap.get("product_level_experiment"), "无"));

                Object dopantObj = inspectMap.get("dopant");
                Object specificationsObj = inspectMap.get("specification");
                String dopant = dopantObj == null ? null : dopantObj.toString(), specifications = specificationsObj == null ? null : specificationsObj.toString();

                if (StringUtils.isBlank(dopant)) {
                    setRuleTestData(ruleTestData, "掺杂剂，数据为空，无法评级");
                    ruleTestDatas.add(ruleTestData);
                    continue;
                }
                if (StringUtils.isBlank(specifications)) {
                    setRuleTestData(ruleTestData, "规格，数据为空，无法评级");
                    ruleTestDatas.add(ruleTestData);
                    continue;
                }
                gradeRules = getRradeRulesData(gradeRules, dopant, specifications);
                // 没有评级规则
                if (gradeRules.size() == 0) {
                    setRuleTestData(ruleTestData, "版本【" + gradeVersion.getVersion() + "】中，掺杂剂【" + dopant + "】" + "规格【" + specifications + "】没有评级规则");
                    ruleTestDatas.add(ruleTestData);
                    // 计算并保存公式结果
                    if (!isTest) {
                        saveGrade(inspectMap, null, fieldPools, null);
                    }
                    continue;
                }
                Map<String, CalculationResultDto> combinedField = new HashMap<>();
                GradeResultDto gradeResultDto = refreshGrade(inspectMap, gradeRules, fieldPoolMap, combinedField, gradeTypeOneId, gradeTypeId, gradeVersion, dopant, specifications);
                ruleTestData.setGrade(gradeResultDto.getGrade());
                ruleTestData.setStatus(gradeResultDto.getGradeStatus() ? 1 : 0);
                List<CalculationResultIfDto> calculationResultIfDtos = gradeResultDto.getCalculationResultIfDtos();
                if (gradeResultDto.getResultMap() != null) {
                    ruleTestData.setGradeData(gradeResultDto.getResultMap().get("grade_data"));
                }
                ruleTestData.setProcess(JSON.toJSONString(calculationResultIfDtos));
                ruleTestDatas.add(ruleTestData);

                if (gradeResultDto.getResultMap() == null) {
                    gradeResultDto.setResultMap(new HashMap<>());
                }
                //将评级结果存至方棒检验数据库，计算并保存公式结果
                if (!isTest) {
                    // 执行圆棒最终评级
                    fbExceGrade(sectionNo, specifications, NumberUtil.Object2BigDecimal(inspectMap.get("length")), gradeResultDto, inspectMap);
                    // 方棒评级
                    String productLevelFb = null, fbExperiLevel = null;
                    if (gradeResultDto.getGradeStatus()) {
                        // 保存评级结果，计算公式，匹配订单结果
                        if (ruleTestData.getGrade() != null) {
                            String[] radeArr = ruleTestData.getGrade().split("，");
                            if (radeArr.length > 0) {
                                productLevelFb = radeArr[0];
                            }
                            if (radeArr.length > 1 && !"未匹配到实验等级".equals(radeArr[1])) {
                                fbExperiLevel = radeArr[1];
                            }
                        }

                        gradeResultDto.getResultMap().put("grade_type", gradeResultDto.getGradeRule().getGradeType());
                        //增加　方棒评级时间的插入
                        gradeResultDto.getResultMap().put("fb_grade_time", DateUtil.formatDate(new Date(), DateUtil.longFormat));
                        gradeResultDto.getResultMap().put("product_level_fb", productLevelFb);
                        gradeResultDto.getResultMap().put("fb_experi_level", fbExperiLevel);


                        //matchOrder(inspectMap, gradeResultDto, productLevelFb, sectionNo, "正常".equals(gradeResultDto.getGradeRule().getGradeType()));
                        inspectMap.put("grade_type", gradeResultDto.getGradeRule().getGradeType());


                    }else{
                        gradeResultDto.getResultMap().put("grade_type","");
                        gradeResultDto.getResultMap().put("grade_data","");
                        gradeResultDto.getResultMap().put("product_level_fb","");
                    }
                    // 保存评级结果，计算公式，匹配订单结果
                    saveGrade(inspectMap, gradeResultDto.getResultMap(), fieldPools, combinedField);
                    FbCheckOutData fbCheckOutData = JSON.parseObject(JSON.toJSONString(inspectMap), FbCheckOutData.class);
                    try {
                        //方棒评级结果下发MCS
//                            publishService.publishEvent(new SquareRankEvent(this, toInitDto(inspectMap)));
                        SquareResultDto squareResultDto = toInitDtoV2(inspectMap);
                        mesToMcsService.squareRankResultMcs(squareResultDto);
                        mesToMcsService.squareRankResultWms(squareResultDto);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    inspectMapItem.setValue(fbCheckOutData);
                }
            }
        }
        ruleTestDataDao.saveAll(ruleTestDatas);
        return ResultGenerator.success(ruleTest.getId());
    }

    /**
     * 执行圆棒最终评级
     *
     * @param sectionNo      单晶编号
     * @param specifications 规格
     * @param length         长度
     * @param gradeResultDto 评级结果
     * @param inspectMap
     */
    private void fbExceGrade(String sectionNo, String specifications, BigDecimal length, GradeResultDto gradeResultDto, Map<String, Object> inspectMap) {
        try {
            Result<String> ybGradeResult = ybFeignClients.fbExceGrade(sectionNo, specifications, length);
            if (ybGradeResult.getCode() == ResultCode.SUCCESS.getCode() && StringUtils.isNotBlank(ybGradeResult.getData())) {
                String[] radeArr = ybGradeResult.getData().split("，");
                if (radeArr.length > 0) {
                    gradeResultDto.getResultMap().put("yb_level", radeArr[0]);
                    inspectMap.put("yb_level", radeArr[0]);
                }
                if (radeArr.length > 1 && !"未匹配到实验等级".equals(radeArr[1]) && StringUtils.isNotBlank(NumberUtil.object2String(inspectMap.get("yb_experi_level"), null))) {
                    gradeResultDto.getResultMap().put("experi_level", radeArr[1]);
                    inspectMap.put("experi_level", radeArr[1]);
                }
            }
        } catch (Exception e) {
            log.error("方棒请求圆棒最终评级失败：" + e.getMessage());
        }
    }

    /**
     * 匹配订单：
     * 产品等级、导电型号，掺杂剂，规格、边长，电阻率
     *
     * @param inspectMap     检验数据
     * @param gradeResultDto 评级结果
     * @param productLevelFb
     */

    public void matchOrder(Map<String, Object> inspectMap, GradeResultDto gradeResultDto, String productLevelFb, String sectionNo, Boolean isMatchOrder) {
        // yb_level 圆棒最终评级
        GradeRule gradeRule = gradeResultDto.getGradeRule();

        //产品最终评级
//        Object ybLevelObject = inspectMap.get("yb_level");
//        String ybLevel = ybLevelObject == null ? null : ybLevelObject.toString();//产品等级
        String ybLevel = NumberUtil.object2String(inspectMap.get("product_level"), null);

        //导电型号
        Object conductiveTypeObject = inspectMap.get("conduction_type");
        String conductiveType = conductiveTypeObject == null ? null : conductiveTypeObject.toString();

        //订单类型
        Object orderTypeObject = inspectMap.get("order_type");
        String orderType = orderTypeObject == null ? null : orderTypeObject.toString();

        //晶段类型【标棒；非标；】
        String sectionType = NumberUtil.object2String(inspectMap.get("section_type"), null);

        //方棒边长Key
        Object  sideLengthRangeObj = inspectMap.get("side_length_range");
        String sideLengthRange = sideLengthRangeObj == null ? null : sideLengthRangeObj.toString();

        //匹配料号

        FbProductModel fbProductModel = fbProductionOrderService.matchOrderProductModel(sectionNo, ybLevel, gradeRule.getSpecifications(), conductiveType, gradeRule.getDopant(), productLevelFb, sectionType,sideLengthRange);
        if (fbProductModel != null) {
            gradeResultDto.getResultMap().put("material_number", fbProductModel.getProductNo());
            if (isMatchOrder) {
                MatchOrderInfo matchOrderInfo = fbProductionOrderService.getMatchOrderInfo(sectionNo, orderType, fbProductModel,sideLengthRange);
                gradeResultDto.getResultMap().put("order_no", matchOrderInfo.getOrderNo());
            }
        } else {
            gradeResultDto.getResultMap().put("order_no", null);
            gradeResultDto.getResultMap().put("material_number", null);
        }
    }

    @Override
    public void saveGrade(Map<String, Object> inspectMap, Map<String, String> resultMaps, 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) {
                fieldPools.add(fieldPool);
            } else {
                fieldPoolsClasss1Map.put(fieldPool.getName(), fieldPool);
            }
        }
        if (resultMaps != null && resultMaps.size() > 0) {
            inspectMap.putAll(resultMaps);
        } else {
            resultMaps = new HashMap<>();
        }
        if (combinedField == null) {
            combinedField = new HashMap<>();
        }
        for (FieldPool fieldPool : fieldPools) {
            if (fieldPool.getIsSaveData()) {
                if (!combinedField.containsKey(fieldPool.getCode()) || !combinedField.get(fieldPool.getCode()).getResultType()) {
                    Result<String> result = fieldPoolService.exceCalculationProd(fieldPool, inspectMap, fieldPoolsClasss1Map);
                    log.info("方棒编号【" + inspectMap.get("fb_section_no") + "】：计算公式【" + fieldPool.getName() + "】计算结果result：" + JSON.toJSONString(result));
                    if (result.getCode() == ResultCode.SUCCESS.getCode()) {
                        resultMaps.put(fieldPool.getCode(), result.getData());
                    }
                } else {
                    resultMaps.put(fieldPool.getCode(), combinedField.get(fieldPool.getCode()).getResult().toString());
                }
                if ("tangent_flag".equals(fieldPool.getCode())) {
                    resultMaps.putIfAbsent("tangent_flag", "0");
                }
            }
        }
        StringBuilder sql = new StringBuilder();
        sql.append("UPDATE zhxx_operate_check_out_data SET ");

        int index = 1, mapCount = resultMaps.size();
        if (resultMaps.size() > 0) {
            for (Map.Entry<String, String> entry : resultMaps.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"));
        int count = ruleTestService.excuteUpdate(sql.toString());
        if (count == 0) {
            throw new RuntimeException("保存评级结果失败，请查看日志");
        }
        inspectMap.putAll(resultMaps);
        System.out.println("执行保存：评级和计算公式结果，" + sql);
    }

    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;
        // 计算评级
        OUT:
        for (GradeRule gradeRule : gradeRules) {
            String[] conditionsArr = gradeRule.getConditions() == null ? new String[]{} : gradeRule.getConditions().split("\\[OR\\]");
            for (String conditions : conditionsArr) {
                if (conditions != null) {
                    CalculationResultIfDto result = fieldPoolService.exceGrade(conditions, inspectMap, fieldPoolMap, combinedField);
                    result.setGrade(gradeRule.getGrade());
                    System.out.println(inspectMap.get("section_no") + "-评级过程，评级状态：" + (result.getResultType() ? "成功；" : "失败；") + "评级结果：" + (result.getResult() == null || result.getResult() ? "成功" : "失败") + "评级名称【" + gradeRule.getName() + "】评级过程：" + JSON.toJSONString(result));
                    calculationResultIfDtos.add(result);
                    //评级成功，成功返回评级结果
                    if (result.getResultType()) {
                        //当前等级，评级成功
                        if (result.getResult() != null && result.getResult()) {
                            System.out.println(inspectMap.get("section_no") + "-评级结果【" + result.getGrade() + "】" + JSON.toJSONString(result));
                            gradeStatus = true;
                            gradeResultDto.setGrade(gradeRule.getGrade());
                            gradeResultDto.setGradeRule(gradeRule);
                            gradeResultDto.setGradeTypeId(gradeRule.getGradeTypeId());
                            break OUT;
                        }
                    } else { //评级失败，不继续评级
                        break OUT;
                    }
                }
            }
        }
        gradeResultDto.setGradeStatus(gradeStatus);
        gradeResultDto.setCalculationResultIfDtos(calculationResultIfDtos);
        System.out.println(inspectMap.get("section_no") + "-" + JSON.toJSONString(gradeResultDto));


        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);
                            Object length = calculationResultDto.getResult();
                            classDetailsArr[i] = classDetailsItemArr[0] + ":" + length.toString();
                        }
                    }
                    classDetails = StringUtils.join(classDetailsArr, ",");
                }
                Map<String, String> resultMap = new HashMap<>();
                if (gradeResultDto.getResultMap() == null) {
                    resultMap.put("grade_data", classDetails);
                    gradeResultDto.setResultMap(resultMap);
                } else {
                    gradeResultDto.getResultMap().put("grade_data", 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("specification", specifications);
                    combinedField = new HashMap<>();
                    GradeResultDto gradeResultDtoNew = refreshGrade(inspectNewMap, experimentalGradeRules, fieldPoolMap, combinedField, gradeTypeOneId, gradeTypeId, gradeVersion, dopant, specifications);
                    calculationResultIfDtos.addAll(gradeResultDtoNew.getCalculationResultIfDtos());
                    Map<String, String> resultMap = new HashMap<>();
                    if (gradeResultDtoNew.getGradeStatus()) {
                        if (gradeResultDto.getResultMap() == null) {
                            resultMap.put("specification", specifications);
                            gradeResultDto.setResultMap(resultMap);
                            if (gradeResultDtoNew.getResultMap() != null) {
                                gradeResultDto.getResultMap().putAll(gradeResultDtoNew.getResultMap());
                            }
                        } else {
                            gradeResultDto.getResultMap().put("specification", specifications);
                            if (gradeResultDtoNew.getResultMap() != null) {
                                gradeResultDto.getResultMap().putAll(gradeResultDtoNew.getResultMap());
                            }
                        }
                        gradeResultDto.setGrade(gradeResultDtoNew.getGrade());
                    } else { //新规格，评级失败
                        if (gradeResultDto.getResultMap() == null) {
                            resultMap.put("specification", specifications);
                            gradeResultDto.setResultMap(resultMap);
                            if (gradeResultDtoNew.getResultMap() != null) {
                                gradeResultDto.getResultMap().putAll(gradeResultDtoNew.getResultMap());
                            }
                        } else {
                            gradeResultDto.getResultMap().put("specification", specifications);
                            if (gradeResultDtoNew.getResultMap() != null) {
                                gradeResultDto.getResultMap().putAll(gradeResultDtoNew.getResultMap());
                            }
                        }
                        gradeResultDto.getCalculationResultIfDtos().addAll(gradeResultDtoNew.getCalculationResultIfDtos());
                        gradeResultDto.setGrade(null);
                        gradeResultDto.setGradeStatus(false);
                        return gradeResultDto;
                    }
                } else { //新规格，评级失败
                    Map<String, String> resultMap = new HashMap<>();
                    if (gradeResultDto.getResultMap() == null) {
                        resultMap.put("specification", specifications);
                        gradeResultDto.setResultMap(resultMap);
                    } else {
                        gradeResultDto.getResultMap().put("specification", specifications);
                    }
                    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;
                }
            }
        }else{
            //todo 增加不是反切的逻辑
        }
        return gradeResultDto;
    }

    public FbRatingResultDto toInitDto(Map<String, Object> inspectMap) {
        DecimalFormat df2 = new DecimalFormat("#.##");
        FbRatingResultDto fbRatingResultDto = new FbRatingResultDto();
        //初始封装数据
        FbCheckOutData fbCheckOutData = JSON.parseObject(JSON.toJSONString(inspectMap), FbCheckOutData.class);
        if (fbCheckOutData != null) {
            FbRatingResultOfDto fbRatingResultOfDto = new FbRatingResultOfDto();
            fbRatingResultOfDto.setFbSectionNo(NumberUtil.object2String(inspectMap.get("fb_section_no"), null));
            fbRatingResultOfDto.setSectionCompose(NumberUtil.object2String(inspectMap.get("section_compose"), null));
            fbRatingResultOfDto.setSpecification(NumberUtil.object2String(inspectMap.get("specification"), null));
            ProductionBindingTray productionBindingTray = productionBindingTrayService.getByCrystalNo(fbRatingResultOfDto.getFbSectionNo());
            if (productionBindingTray != null) {
                fbRatingResultOfDto.setTrayNo(productionBindingTray.getTrayNo());
            }
            //if (NumberUtil.object2String(inspectMap.get("section_type"), null))
            fbRatingResultOfDto.setSectionType(NumberUtil.object2String(inspectMap.get("section_type"), null));
            fbRatingResultOfDto.setLength(NumberUtil.Object2BigDecimal(inspectMap.get("length")));
            fbRatingResultOfDto.setWeight(NumberUtil.Object2BigDecimal(inspectMap.get("weight")));
            fbRatingResultOfDto.setDiameterMax(NumberUtil.Object2BigDecimal(inspectMap.get("diameter_max")));
            fbRatingResultOfDto.setDiameterMin(NumberUtil.Object2BigDecimal(inspectMap.get("diameter_min")));

            Result<YbInspectDataDto> fbInfoById = ybFeignClients.getInspectDataBaseBySectionNo(NumberUtil.object2String(inspectMap.get("yb_section_no"), null));
            if (fbInfoById != null && "200".equals(fbInfoById.getCode()) && fbInfoById.getData() != null) {
                fbRatingResultOfDto.setBevel(String.valueOf(fbInfoById.getData().getIsBevel()));
                fbRatingResultOfDto.setPn(fbInfoById.getData().getDopant());
                fbRatingResultOfDto.setDistortion(df2.format(fbInfoById.getData().getDistortion()));
            }
            fbRatingResultOfDto.setFbExperiLevel(NumberUtil.object2String(inspectMap.get("fb_experi_level"), null));

            fbRatingResultOfDto.setDirect("");
            fbRatingResultOfDto.setProductRank(NumberUtil.object2String(inspectMap.get("product_rank"), null));
            fbRatingResultOfDto.setMark("");
            fbRatingResultOfDto.setSticksCount(NumberUtil.object2String(inspectMap.get("sticks_count"), null));
            fbRatingResultOfDto.setSpellBarLength(NumberUtil.Object2BigDecimal(inspectMap.get("spell_bar_length")));
            fbRatingResultOfDto.setProductLevel(NumberUtil.object2String(inspectMap.get("product_level"), null));
            fbRatingResultOfDto.setYbLevel(NumberUtil.object2String(inspectMap.get("yb_level"), null));
            fbRatingResultOfDto.setProductLevelFb(NumberUtil.object2String(inspectMap.get("product_level_fb"), null));
            fbRatingResultOfDto.setSecond("二类".equals(NumberUtil.object2String(inspectMap.get("product_level_fb"), null)) ? "是" : "否");
            fbRatingResultOfDto.setEnterTime("");
            fbRatingResultOfDto.setReCheckType(NumberUtil.object2String(inspectMap.get("re_check_type"), null));
            fbRatingResultOfDto.setIsFbSizeCheck(BooleanUtils.toBooleanDefaultIfNull(Boolean.valueOf(inspectMap.get("is_fb_size_check").toString()),false));
            fbRatingResultOfDto.setProductType(NumberUtil.object2String(getProductType(String.valueOf(inspectMap.get("product_type"))), null));
            fbRatingResultOfDto.setConductiveType(NumberUtil.object2String(inspectMap.get("conduction_type"), null));
            fbRatingResultOfDto.setSpecification(NumberUtil.object2String(inspectMap.get("specification"), null));
            fbRatingResultOfDto.setProductGrade(NumberUtil.object2String(inspectMap.get("product_level"), null));
            fbRatingResultOfDto.setGradeType(NumberUtil.object2String(inspectMap.get("grade_type"), null));
            fbRatingResultOfDto.setSideLengthRange(NumberUtil.object2String(inspectMap.get("side_length_range"), null));

            fbRatingResultDto.setSn(NumberUtil.object2String(inspectMap.get("fb_section_no"), null));
            fbRatingResultDto.setProductId(NumberUtil.object2String(inspectMap.get("material_number"), null));
            fbRatingResultDto.setGrade(NumberUtil.object2String(inspectMap.get("product_level_fb"), null));
            fbRatingResultDto.setOrderNo(NumberUtil.object2String(inspectMap.get("order_no"), null));
            fbRatingResultDto.setResultOf(fbRatingResultOfDto);
        }
        return fbRatingResultDto;
    }
    /**
     * 规格转换
     */
    private String getProductType(String productType) {
        List<DictionaryItem> toMCSProductSpec = dictionaryItemService.findByThemeValueAndEnable("ToMCSProductSpec", true);
        Map<String, DictionaryItem> specMap = toMCSProductSpec.stream().collect(Collectors.toMap(DictionaryItem::getName, Function.identity(), (t1, t2) -> t1));
        if (specMap.containsKey(productType)) {
            return specMap.get(productType).getValue();
        } else {
            return "0";
        }
    }
    public SquareResultDto toInitDtoV2(Map<String, Object> inspectMap) {
        //初始封装数据
//        FbCheckOutData fbCheckOutData = JSON.parseObject(JSON.toJSONString(inspectMap), FbCheckOutData.class);
        SquareResultDto squareResultDto = JSON.parseObject(JSON.toJSONString(inspectMap), SquareResultDto.class);
        return squareResultDto;
    }
}

