package com.xisc.pm.config;


import com.xisc.boot.common.sys.UserClient;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;


/**
 * @author 纪文桃 wentao.ji01@hand-china.com
 * @date 2024/11/18 16:27
 * @description
 */
@Aspect
@Component
public class PmInterfaceLogAspect {

    @Autowired
    private UserClient userClient;

    private static final Logger LOGGER = LoggerFactory.getLogger(PmInterfaceLogAspect.class);

    @Pointcut("execution(public * com.xisc.pm.api.controller.v1.ApiController.*(..)) ")
    public void apiControllerLog() {
    }

    @Around("apiControllerLog()")
    public Object doAroundRequest(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        MDC.put("traceId", UUID.randomUUID().toString().replace("-", ""));
        MDC.put("userId", userClient.getCurrentUserId().toString());
        MDC.put("apiName", proceedingJoinPoint.getSignature().getName());

        // 获取方法签名和参数
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        String[] parameterNames = methodSignature.getParameterNames();
        Object[] args = proceedingJoinPoint.getArgs();

        // 打印参数
        StringBuilder paramsBuilder = new StringBuilder();
        for (int i = 0; i < parameterNames.length; i++) {
            paramsBuilder.append(parameterNames[i]).append("=").append(args[i]);
            if (i < parameterNames.length - 1) {
                paramsBuilder.append(", ");
            }
        }
        LOGGER.debug("interface start api=【{}】, dto = 【{}】", proceedingJoinPoint.getSignature().getName(), paramsBuilder);
        long startTime = System.currentTimeMillis();
        Object obj = proceedingJoinPoint.proceed();
        LOGGER.debug("interface end api=【{}】, execute end time=[{}]ms", proceedingJoinPoint.getSignature().getName(),
                (System.currentTimeMillis() - startTime));
        MDC.clear();
        return obj;
    }
}
