package cn.iocoder.yudao.module.iot.framework.util;

import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;

import java.util.Map;


public class FormulaCalculator {

	public static String calFormula(String formula){
		ExpressRunner runner = new ExpressRunner();
		DefaultContext<String, Object> context = new DefaultContext<String, Object>();
		try {
			Object result = runner.execute(formula, context, null, false, false);
			return result.toString();
		} catch (Exception e) {
			System.out.println("---计算出错！："+formula);
		}
		return "";
	}
	public static String calFormula(String formula,String key,String value){
		formula = formula.replace(key,value);
		return calFormula(formula);
	}
	public static String calFormula(String formula, Map<String,String> map){
		for (String key: map.keySet()){
			formula = formula.replaceAll(key, map.get(key));
		}
		return calFormula(formula);
	}
	public static Boolean calFormulaBoolean(String formula,String key,String value)  {
		formula = formula.replace(key,value);
		String result = calFormula(formula);
		if("true".equals(result))
			return true;
		return false;
	}
	public static Boolean calFormulaBoolean(String formula, Map<String,String> map)  {
		for (String key: map.keySet()){
			formula = formula.replaceAll(key, map.get(key));
		}
		String result = calFormula(formula);
		if("true".equals(result))
			return true;
		return false;
	}

	public static void main(String[] args) throws Exception {
		String formula = "2 == 1";
		ExpressRunner runner = new ExpressRunner();
		DefaultContext<String, Object> context = new DefaultContext<String, Object>();
		context.put("a", 1);
		context.put("b", 2);
		context.put("c", 3);
		//下面五个参数意义分别是 表达式，上下文，errorList，是否缓存，是否输出日志
		Object result = runner.execute("a+b+c", context, null, true, false);
		System.out.println("a+b+c=" + result);
		//下面五个参数意义分别是 表达式，上下文，errorList，是否缓存，是否输出日志
		Object result2 = runner.execute(formula, context, null, true, false);
		System.out.println("formula=" + result2);

		//下面五个参数意义分别是 表达式，上下文，errorList，是否缓存，是否输出日志
		DefaultContext<String, Object> context3 = new DefaultContext<String, Object>();
		context3.put("a", "1");
		context3.put("b", "2");
		context3.put("c", "3");
		Object result3 = runner.execute("1+2+3==6", context3, null, true, false);
		System.out.println("a+b+c=" + result3);
	}
}
