package com.wx.application.filter;

import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
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 com.fasterxml.jackson.databind.ObjectMapper;
import com.wx.application.base.ResponseData;
import com.wx.application.configuration.annotation.AspectOff;
import com.wx.application.constant.CONSTANT;

import lombok.SneakyThrows;

@Order(5)
@ControllerAdvice
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    @Autowired
    ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return !methodParameter.getMethod().isAnnotationPresent(AspectOff.class);
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        //log.info("返回信息: header: {} , body: {}", JSON.toJSONString(serverHttpResponse.getHeaders().entrySet()), objectMapper.writeValueAsString(o));
        serverHttpResponse.getHeaders().add(CONSTANT.X_REQ_ID, MDC.get(CONSTANT.REQUEST_ID_KEY));
        if (o instanceof ResponseData) {
            //统一回填header信息
            ResponseData responseData = (ResponseData) o;
            responseData.setRequestId(MDC.get(CONSTANT.REQUEST_ID_KEY));
            MDC.clear();
            return responseData;
        }
        MDC.clear();
        return o;
    }
}
