package com.prolog.rdc.tms.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author hongbo.pan
 * @date 2023/4/13
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    @Around(value = "@within(org.springframework.stereotype.Controller) || @within(org.springframework.web.bind.annotation.RestController)")
    public Object aroundMethod(ProceedingJoinPoint jp) throws Throwable {
        long beginTime = System.currentTimeMillis();
        Object obj = jp.proceed();
        long time = System.currentTimeMillis() - beginTime;
        try {
            MethodSignature signature = (MethodSignature) jp.getSignature();
            // 参数值
            Object[] args = jp.getArgs();
            String[] argNames = signature.getParameterNames();
            Map<String, Object> paramsMap = Maps.newHashMap();
            if (args != null && args.length > 0) {
                for (int i = 0; i < args.length; i++) {
                    Object o = args[i];
                    if (!(o instanceof HttpServletRequest) && !(o instanceof HttpServletResponse)) {
                        paramsMap.put(argNames[i], args[i]);
                    }
                }
            }
            String request = JSON.toJSONString(paramsMap);
            String response = StrUtil.EMPTY;
            if (ObjectUtil.isNotNull(obj)) {
                response = JSON.toJSONString(obj);
            }
            log.info("耗时={}ms,topic={},title={},request={},response={}", time, jp.getTarget().getClass().getSimpleName(),
                    signature.getMethod().getName(), request, response);
        } catch (Exception e) {
            log.warn("切面日志打印异常！", e);
        }
        return obj;
    }

}
