package com.gic.haoban.manage.web.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.gic.haoban.common.utils.HaobanResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
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;

import java.lang.reflect.Method;

/**
 * Created 2019/2/20.
 *
 * @author hua
 */
@ControllerAdvice
public class ResponseInterceptor implements ResponseBodyAdvice<Object> {

    private Logger logger = LoggerFactory.getLogger(ResponseInterceptor.class);

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        Method method = methodParameter.getMethod();
        String name = method.getName();
        logger.info("method：{}", name);
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object haobanResponse, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        String response = JSONObject.toJSONString(haobanResponse);
        logger.info("response:{}", response);
        return haobanResponse;
    }
}
