package org.jeecg.modules.stm.utils;

import io.lettuce.core.dynamic.annotation.Value;
import org.jeecg.modules.stm.metric.entity.MetricMonitorSet;

import javax.naming.Context;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import net.objecthunter.exp4j.Expression;
import net.objecthunter.exp4j.ExpressionBuilder;


public class CommonUtil {

    public static Double jsEavl(String strFormula) {
        try {
            // 清理表达式中的空格
            strFormula = strFormula.replaceAll("\\s+", "");

            // 直接构建表达式，exp4j 默认支持基本数学函数
            Expression expression = new ExpressionBuilder(strFormula).build();

            double result = expression.evaluate();
            return result;
        } catch (IllegalArgumentException e) {
            System.out.println("Expression parse error: " + e.getMessage());
        } catch (ArithmeticException e) {
            System.out.println("Math error (e.g., division by zero): " + e.getMessage());
        } catch (Exception e) {
            System.out.println("Unexpected error: " + e.getMessage());
            e.printStackTrace();
        }
        return 0d;
    }
    public static String DoubleToStr(Double val,Integer blen) {
        if(blen==null) blen = 2;
        StringBuffer sb = new StringBuffer();
        sb.append("#.");
        for(int i=0;i<blen;i++) {
            sb.append("#");
        }
        DecimalFormat df = new DecimalFormat(sb.toString());
        df.setRoundingMode(RoundingMode.HALF_UP); // 设置四舍五入模式
        return df.format(val);
    }

    public static int computeRiskLevel(Double fillVal, MetricMonitorSet mms) {
        Float stToVal = mms.getStTolVal();
        Float toVal = mms.getTolVal();
        Float warnVal = mms.getWarnVal();
        Float intvVal = mms.getIntvVal();
        int riskLevel = 0;
        if(fillVal==null) {
            return riskLevel;
        }
        if(toVal==null||warnVal==null) {
            return riskLevel;
        }
        boolean flag = toVal<warnVal?true:false;
        if (flag) {
            if (fillVal.floatValue() <= toVal.floatValue()) {
                riskLevel = 1;
            } else if (fillVal.floatValue() < warnVal.floatValue()) {
                riskLevel = 2;
            } else {
                riskLevel = 3;
            }
        } else {
            if (fillVal.floatValue() >= toVal.floatValue()) {
                riskLevel = 1;
            } else if (fillVal.floatValue() > warnVal.floatValue()) {
                riskLevel = 2;
            } else {
                riskLevel = 3;
            }
        }
        return riskLevel;
    }

    public static String replaceSpecialChar(String strVal) {
        if(strVal==null||strVal.isEmpty()) return "";
        String result = strVal.replaceAll("<[^>]*>", "").trim();
        return result;
    }

}

