package com.chaozhanggui.common.system.config;

import cn.hutool.json.JSONUtil;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice {
    private static Logger logger = LoggerFactory.getLogger(MyResponseBodyAdvice.class);

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        logger.info(ToStringBuilder.reflectionToString(body));
        if (selectedConverterType == MappingJackson2HttpMessageConverter.class
                && !(body instanceof RespBody)) {
            Class<?> parameterType = returnType.getParameterType();
            if (parameterType == ResponseEntity.class) {//对于路径错误的请求。
                return body;
            } else if (parameterType == void.class || parameterType == Void.class) {
                return new RespBody();
            } else {
                return new RespBody(body);
            }
        } else {
            return body;
        }
    }
}
