package com.kym.common.handler;

import com.kym.common.R;
import com.kym.entity.platform.response.PlatformResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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 {


    /**
     * 判断是否执行beforeBodyWrite
     *
     * @param returnType    the return type
     * @param converterType the selected converter type
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

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

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