package com.yn.bftl.thirdparty.advice;


import com.yn.bftl.thirdparty.common.vo.ResponseVO;
import com.yn.bftl.thirdparty.modules.chinaums.vo.ChinaumsCallBackVO;
import com.yn.bftl.thirdparty.modules.contract.vo.CallVo;
import com.yn.bftl.thirdparty.modules.unionpay.vo.AggregateCallBackVO;
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.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * Spring MVC 统一响应对象处理
 *
 * @author huabiao
 * @create 2020/06/19  17:44
 */
@ControllerAdvice(basePackages = "com.yn.bftl.thirdparty.modules")
public class MyResponseBodyAdvice implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object object, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if ("text".equals(mediaType.getType())) {
            return object.toString();
        }

        if (object == null) {
            object = ResponseVO.newInstance(null);
        }
        // 契约锁需要
        if (object instanceof CallVo || object instanceof ChinaumsCallBackVO) {
            return object;
        }
        // 银联聚合支付回调响应需要
        if (object instanceof AggregateCallBackVO) {
            return ((AggregateCallBackVO) object).getStatus();
        }
        if (!(object instanceof ResponseVO)) {
            object = ResponseVO.newInstance(object);
        }
        return object;
    }
}