package com.yeejoin.equipmanage.utils;

import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleBindings;

public class FormulaCalculator {
 
		private static final ScriptEngine engine = 
            new ScriptEngineManager().getEngineByName("js");
        private static final Map<String, CompiledScript> compiledCache = 
            new ConcurrentHashMap<>();

        public static synchronized Object calculate(String formula, 
                Map<String, Object> variables) throws ScriptException {
            try {
                // 类型安全转换
                variables.replaceAll((k, v) -> 
                    v instanceof String ? new BigDecimal((String)v) : v);
                    
                CompiledScript script = compiledCache.computeIfAbsent(
                    formula, f -> {
						try {
							return ((Compilable)engine).compile(f);
						} catch (ScriptException e) {
							e.printStackTrace();
							// TODO Auto-generated catch block
							 throw new IllegalArgumentException("输入值格式错误");
						
						}
					}
                );
                return script.eval(new SimpleBindings(variables));
            } catch (ClassCastException e) {
                throw new IllegalArgumentException("输入值格式错误");
            }
        }
}
