package com.jy.framework.config;

import com.jy.framework.model.annotation.FormatIgnore;
import com.jy.framework.model.base.R;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
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.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * 做统一格式返回
 */
@Slf4j
@RestController
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
        return Objects.isNull(returnType.getAnnotatedElement().getAnnotation(FormatIgnore.class));
    }

    @Override
    public R beforeBodyWrite(Object body,
                             @NonNull MethodParameter returnType,
                             @NonNull MediaType selectedContentType,
                             @NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
                             @NonNull ServerHttpRequest request,
                             @NonNull ServerHttpResponse response) {
        if (body instanceof R) {
            return (R) body;
        }
        return R.success(body);
    }

}