package com.ywt.mg.core.utils;

import com.google.common.collect.Lists;
import com.ywt.mg.core.SpringContext;
import com.ywt.mg.core.utils.serializers.JsonSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author daiyihua
 * @create 2020-11-03 16:17
 * @program ywt_mg
 * @description 线程池异步执行
 **/
public class AsyncUtil {


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

    /**
     * 异步调用方法
     *
     * @param clazz       类
     * @param methodName  方法名
     * @param paramValues 参数值
     * @param paramTypes  参数类型
     * @return 执行结果
     */
    public static Object invokeMethodAsync(Class clazz, String methodName, List paramValues, Class[] paramTypes) {
        try {
            Callable myCallable = new Callable() {
                @Override
                public Object call(){
                    Object result = invokeMethod(clazz, methodName, paramValues, paramTypes);
                    logger.info("invokeMethodAsync-->call方法执行了:" + result);
                    return result;
                }
            };
            return myCallable.call();
        } catch (Exception e) {
            logger.error("invokeMethodAsync调用异常{}:{}:{}:{}:{}:{}", clazz, methodName, JsonSerializer.toJson(paramValues), e, e.getMessage());
        }
        return null;
    }

    /**
     * 调用方法
     *
     * @param clazz       类
     * @param methodName  方法名
     * @param paramValues 参数值
     * @param paramTypes  参数类型
     * @return 执行结果
     */
    private static Object invokeMethod(Class clazz, String methodName, List paramValues, Class[] paramTypes) {
        try {
            // 注：此时不能用newInstance()，需要手动获取spring容器的对象
            Object object = SpringContext.getBean(clazz);
            if (object != null) {
                Method method = clazz.getMethod(methodName, paramTypes);
                return method.invoke(object, paramValues.toArray());
            }
        } catch (Exception e) {
            logger.error("AsyncUtil调用异常{}:{}:{}:{}:{}:{}", clazz, methodName, JsonSerializer.toJson(paramValues), e, e.getMessage());
        }
        return null;
    }
}
