package cn.axzo.msg.center.notices.client.interceptor;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.lang.reflect.Type;

/**
 * 请求对象打印日志
 *
 * @author zhaoyong_sh
 * @see LoggerRequestBodyAdvice
 * @since 2021-05-19 10:31
 */
@Slf4j
//@ControllerAdvice
public class LoggerRequestBodyAdvice extends RequestBodyAdviceAdapter {

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        return methodParameter.hasParameterAnnotation(RequestBody.class);
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                Class<? extends HttpMessageConverter<?>> converterType) {
        String simpleClassName = parameter.getDeclaringClass().getSimpleName();
        String methodName = parameter.getMethod().getName();
        log.info(simpleClassName + "#" + methodName + " request body is {}", JSON.toJSONString(body));
        return body;
    }
}
