


package com.jwipc.log.endpoint;

import com.jwipc.log.dto.LogDTO;
import com.jwipc.log.logic.LogAnalysisLogic;
import com.jwipc.util.RequestUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * <p>正常方法日志增强</p>
 *
 * @author BOGON
 * @version 1.0
 * @since JDK 1.8
 */
@Slf4j
@Component
@ConditionalOnBean(name = "logAnalysisLogic")
@RequiredArgsConstructor
public class LogBookInterceptor implements MethodInterceptor {
    private final LogAnalysisLogic logAnalysisLogic;

    @Override
    public Object invoke(MethodInvocation point) throws Throwable {
        Object proceed = point.proceed();
        Object target = point.getThis();
        final Class<?> targetClass = target.getClass();
        Method method = point.getMethod();
        final Object[] pointArgs = point.getArguments();
        // 取得请求参数
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String url = request.getRequestURI();
        final String userAgent = request.getHeader(HttpHeaders.USER_AGENT);
        String ipAddress = RequestUtil.getIpAddress(request);
        final LogDTO logDTO = LogDTO.buildByRequest(ipAddress, userAgent);
        logAnalysisLogic.analysis(targetClass, method, pointArgs, proceed, url, logDTO);
        return proceed;
    }
}
