package com.ssyf.plugs.logger;

import cn.hutool.json.JSONUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class LogHelper {

    /**
     * 设置业务执行后数据
     * @param dataJson
     */
    public static void setAfterDataJson(String dataJson){
        LogInfo logInfo = LogInfoHolder.get();
        if(logInfo != null ){
            logInfo.setAfterDataJson(dataJson);
        }
    }

    /**
     * 设置业务执行前数据
     * @param dataJson
     */
    public static void setBeforeDataJson(String dataJson){
        LogInfo logInfo = LogInfoHolder.get();
        if(logInfo != null ){
            logInfo.setBeforeDataJson(dataJson);
        }
    }

    /**
     * 解析并获取参数信息
     * @param joinPoint
     * @return
     */
    static Map<String ,Object> parseParametersAndGet(ProceedingJoinPoint joinPoint){
        Map<String, Object> result = new HashMap<>();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // 请求的方法参数值
        Object[] args = joinPoint.getArgs();
        // 请求的方法参数名称
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        if (args != null && paramNames != null) {
            for (int i = 0; i < args.length; i++) {
                result.put(paramNames[i], args[i]);
            }
        }
        return result;
    }

    static String parseParametersAndGetJson(ProceedingJoinPoint proceedingJoinPoint){
        Map<String, Object> result = parseParametersAndGet(proceedingJoinPoint);
        if(result.isEmpty()){
            return "";
        }
        return JSONUtil.toJsonStr(result);
    }

    /**
     * 获取全限定名
     * @param proceedingJoinPoint
     * @return
     */
    static String parseIdentifierAndGet(ProceedingJoinPoint proceedingJoinPoint){
        return proceedingJoinPoint.getSignature().getDeclaringTypeName() + "." + proceedingJoinPoint.getSignature().getName();
    }
}
