package com.brilliance.isc.common.validator.es.support.impl;

import com.brilliance.isc.common.validator.es.support.IJavaCallback;
import com.brilliance.isc.common.validator.es.utils.EsSpringUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author fukai
 * 支持调用静态类、bean名称、Java实例的函数
 */
@Component
public class InvokeBeanCallback implements IJavaCallback {

    private static Logger logger = LoggerFactory.getLogger(InvokeBeanCallback.class);

    /**
     * 调用方法
     * @param args 第一个参数：类名/bean名称/java实例，第二个参数方法名
     * @return
     */
    @Override
    public Object callback(Object... args) {
        Object nameOrInstance = args[0];
        String method = (String)args[1];
        Object bean = nameOrInstance;
        Class staticClazz = null;
        boolean isStatic = false;
        try {
            if(nameOrInstance instanceof String) {
                String name = (String)nameOrInstance;
                if(!name.contains(".")) {
                    bean = EsSpringUtils.getBean((String) nameOrInstance);
                }else {
                    //静态函数模式
                    isStatic = true;
                    staticClazz = Class.forName(name);
                }
            }
            if (args.length > 2) {
                Object[] copy = new Object[args.length - 2];
                System.arraycopy(args, 2, copy, 0, copy.length);
                if(!isStatic) {
                    return MethodUtils.invokeMethod(bean, method, copy);
                }else {
                    return MethodUtils.invokeStaticMethod(staticClazz, method, copy);
                }
            } else {
                if(!isStatic) {
                    return MethodUtils.invokeMethod(bean, method);
                }else{
                    return MethodUtils.invokeStaticMethod(staticClazz, method);
                }
            }
        }catch (Exception e){
            logger.error("invoke javabean method error:{}",e);
            throw new RuntimeException("invoke javabean method error",e);
        }
    }
}
