package cn.common.page.response;

import java.sql.Date;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import org.springframework.web.context.request.ServletRequestAttributes;

/**在返回数据类型中添加需要的数据*/
public class ResBodyInterceptor implements ResponseBodyAdvice<Object> 
{
    @SuppressWarnings("rawtypes")
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }
 
    @SuppressWarnings("rawtypes")
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
 
        //通过RequestContextHolder获取request
        HttpServletRequest httpServletRequest =
            ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
       
         //添加请求时间和返回时间，计算接口总耗时
        if(body instanceof Result){
            String reqTime = httpServletRequest.getAttribute("reqTime").toString();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            ((Result) body).setReqTime(sdf.format(new Date(Long.valueOf(reqTime))));
            long respTime = System.currentTimeMillis();
            ((Result) body).setRespTime(sdf.format(new Date(respTime)));
        }
        return body;
    }
}
