package com.hzya.frame.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.web.exception.BaseSystemException;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Groovy脚本执行工具类
 * @author 👻👻👻👻👻👻👻👻👻👻 gjh
 * @version 1.0
 * @content
 * @date 2024-05-16 13:44
 */
public class GroovyUtil {
    private static final Logger logger = LoggerFactory.getLogger(GroovyUtil.class);



    public  static  Object  execute(JSONObject reqData) {
        JSONObject jsonObject = JSON.parseObject(reqData.getString("jsonStr"));
        //JSON参数
        String parameterJson = jsonObject.getString("parameterJson");
        String methodStr = jsonObject.getString("methodStr");
        //TODO 后续根据存储的数据库编码拼接生成
        String className = jsonObject.getString("className");
        //组装GroovyClassScript
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(" class ");
        stringBuffer.append(className);
        stringBuffer.append(" {");
        stringBuffer.append(" String execute (String jsonStr){");
        stringBuffer.append(methodStr);
        stringBuffer.append(" }");
        stringBuffer.append(" }");
        logger.info("Groovy Class 组装结果 "+ stringBuffer.toString());
        // 创建GroovyClassLoader实例
        GroovyClassLoader groovyClassLoader = new GroovyClassLoader();

        // 动态编译和加载Groovy脚本
        Class<?> groovyClass = groovyClassLoader.parseClass(stringBuffer.toString());
        // 创建Groovy类的实例
        GroovyObject groovyObject = null;
        try {
            groovyObject = (GroovyObject) groovyClass.newInstance();

        }catch (Exception e){
            logger.info("创建newInstance失败:"+ e);
            throw new BaseSystemException(e);
        }
         Object  returnObj = groovyObject.invokeMethod("execute",parameterJson);
        logger.info("执行脚本结束:"+returnObj);
        return returnObj;
    }
}
