package com.app.framework.core.log.task;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.app.framework.core.log.intercept.LogInterceptCenter;
import com.app.framework.core.log.result.LogResult;
import org.aspectj.lang.JoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

public class LogResultTask {
    Logger logger = LoggerFactory.getLogger(LogResultTask.class.getName());

    public LogResult logResult(JoinPoint jp){
        LogResult logResult = null;
        //获取拦截方法信息
        String targetMethodName = jp.getSignature().getName(); // 拦截方法名
        Class<?> targetClass = jp.getTarget().getClass(); // 拦截class
        Object[] args = jp.getArgs(); // 拦截参数
        // 匹配interceptClass
        Class<?> interceptClass = LogInterceptCenter.getHandler(targetClass);
        if (interceptClass == null) {
            logger.warn(String.format("don't find interceptClass, targetClass:[%s]", targetClass));
            return logResult;
        }
        // 从容器中获取拦截器实例
        Object interceptObject = SpringUtil.getBean(interceptClass);
        if (interceptObject == null){
            logger.warn("interceptObject is null");
            return logResult;
        }
        // 利用反射从拦截器中取得对应的日志处理函数
        Method findMethod = ReflectUtil.getMethod(interceptClass, targetMethodName, ClassUtil.getClasses(args));
        if (findMethod == null) {
//    			logger.warn(String.format("class : [%s], paramTypes : [%s] find method : [%s] failure", interceptClass, Arrays.toString(paramsTypes), targetMethodName));
            logger.warn(String.format("class : [%s] find method : [%s] failure", interceptClass, targetMethodName));
            return logResult;
        }
        // 处理具体日志方法
        Object resultObject = null;
        try {
            // 具体日志处理方法
            resultObject = findMethod.invoke(interceptObject, args);
        } catch (Exception e) {
            logger.error(String.format("[%s] invoke method : [%s] failure", interceptClass, targetMethodName), e);
        }
        // 处理和解析对象输出日志
        if (resultObject != null) {
            logResult = (LogResult) resultObject;
        }
        return logResult;
    }

}
