package org.stm.utils;

import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.PolyglotException;
import org.graalvm.polyglot.Value;
import org.stm.metric.entity.MetricMonitorSet;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.math.RoundingMode;
import java.text.DecimalFormat;

public class CommonUtil {
    public static Double jsEavl(String strFormula) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");
        if (engine == null) {
            try {
                Context context = Context.create();
                Value result = context.eval("js", strFormula);
                return result.asDouble();
            } catch (PolyglotException e) {
                System.out.println("Error executing JavaScript expression: " + e.getMessage());
            }
        } else {
            try {
                Object result = engine.eval(strFormula); // 执行数学表达式
                return (Double)result;
            } catch (ScriptException e) {
                System.out.println("Error executing math expression: " + e.getMessage());
            }
        }
        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;
    }

}

