package com.wx.application.filter;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSON;
import com.wx.application.configuration.annotation.AspectOff;
import com.wx.application.constant.CONSTANT;
import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;

@Slf4j
@Order(5)
@ControllerAdvice()
public class GlobalRequestBodyAdvice implements RequestBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return !methodParameter.getMethod().isAnnotationPresent(AspectOff.class);
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        return new HttpInputMessage() {
            @SneakyThrows
            @Override
            public InputStream getBody() {
                // 获取 json 字符串
                @Cleanup ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                IoUtil.copy(httpInputMessage.getBody(), byteArrayOutputStream);
                String bodyStr = new String(byteArrayOutputStream.toByteArray());
                log.info("请求信息: url: {} header: {} , body: {}", MDC.get(CONSTANT.REQUEST_URL), JSON.toJSONString(httpInputMessage.getHeaders().entrySet()), bodyStr);
                return IoUtil.toStream(byteArrayOutputStream.toByteArray());
            }

            @Override
            public HttpHeaders getHeaders() {
                return httpInputMessage.getHeaders();
            }
        };
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }
}
