package com.muyu.rule.server.execution;

import com.muyu.rule.server.pool.container.EngineContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Author：张承志
 * @Package：com.muyu.rule.server
 * @Project：cloud-etl-rule
 * @name：EngineExecution
 * @Date：2024/8/22 23:31
 */
public class EngineExecution {

    private static final Logger log = LoggerFactory.getLogger(EngineExecution.class);

    public static Object engineExe(String engineKey, Map<String, Object> params) {
        Object instance = EngineContainer.getInstanceMap(engineKey);
        List<String> methodEngineParams = EngineContainer.getMethodEngineParamMap(engineKey);
        Method method = EngineContainer.getMethodMap(engineKey);

        try {
            int methodEngineParamsLength = methodEngineParams.size();
            Object[] objects = new Object[methodEngineParamsLength];
            for (int i = 0; i < methodEngineParamsLength; i++) {
                objects[i] = params.get(methodEngineParams.get(i));
            }
            log.info("规则引擎 [{}] 调用参数 [{}]", engineKey, Arrays.toString(objects));
            Object invoke = method.invoke(instance, objects);
            log.info("规则引擎 [{}] 调用结果,[{}]", engineKey, invoke);

            return invoke;
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}
