package com.kym.common.handler;

import com.kym.common.R;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 返回信息处理
 *
 * @author skyline
 */
@RestControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // String 返回类型由 StringHttpMessageConverter 处理，不能包装为 R，否则 ClassCastException
        return converterType != StringHttpMessageConverter.class;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        // 响应微信的信息不做处理
        if (body instanceof R<?> || body instanceof ResponseEntity) {
            return body;
        } else if (body == null) {
            return R.success();
        } else {
            return R.success(body);
        }
        // 失败返回在公共异常处理中
    }
}
