package org.dromara.utils;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import org.apache.camel.Exchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class GroovyUtils {
    private final static Logger logger = LoggerFactory.getLogger(GroovyUtils.class);
    public  static Object runjs(String js, Map<String,Object> datap){
        try{
            if(js==null) return "";

            Binding binding = new Binding();
            if(datap.size()>0){
                datap.keySet().forEach(key->{
                    binding.setProperty(key, datap.get(key));
                });
            }
            GroovyShell groovyShell = new GroovyShell(binding);
            String script = js;

            Object result = groovyShell.evaluate(script);
            return result;
        }catch (Exception e){
            System.out.println(e.getMessage());
            GroovyUtils.logger.error(e.getMessage());
        }
        return "";
    }

    public static void setExchange(Exchange exchange){

    }

//    public static void main(String[] args) {
//
//       System.out.println(JSUtils.runjs("function run(){ var c=[{  status:2,log:'{\"aa\":[\"21\",\"22\"]}'},{  status:1,log:'{\"aa\":[\"11\",\"12\"]}'}];return JSON.parse(c.filter(function(i){return i.status==2})[0].log).aa[0]  }"));
//    }
}
