package com.xinxincaravan.caravan.vehicle.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.util.Map;


public class JSUtil {

    public static final ScriptEngineManager manager = new ScriptEngineManager();
    public static final ThreadLocal<ScriptEngine> engine = new ThreadLocal<ScriptEngine>() {
        @Override
        protected ScriptEngine initialValue() {
            return manager.getEngineByName("javascript");
        }
    };

    public static final Logger logger = LoggerFactory.getLogger(Object.class);



    /**
     * 执行js函数（注意，js的脚本引擎不是线程安全的，不要使用全局变量）
     * @param functionCode 函数代码，只包含块中内容
     * @param params 参数params
     * @return
     */
    public static Object evalJsFunction(String functionName,String functionCode,Map<String,Object> params){
        try{
            engine.get().eval("function "+functionName +"(params){" +
                    functionCode +
                    "};");
            if (engine.get() instanceof Invocable) {
                Invocable in = (Invocable) engine.get();
                return in.invokeFunction(functionName,params);
            }
        }catch(Exception e){
            logger.error(e.getMessage());
        }
        return null;
    }



    /**
     * 执行js表达式
     * @param jsExpression js表达式
     * @param params 参数，供表达式调用
     * @return
     */
    public static Object eval(String jsExpression, Map<String,Object> params){
        try{
            engine.get().eval("function evalJSExpression(params){" +
                    "return eval(\""+ jsExpression +"\");" +
                    "}");
            if (engine.get() instanceof Invocable) {
                Invocable in = (Invocable) engine.get();
                return in.invokeFunction("evalJSExpression",params);
            }
        }catch(Exception e){
            logger.error(e.getMessage());
        }
        return null;
    }

}
