package com.copy.trade.handler;


import com.copy.trade.core.ErrorResult;
import com.copy.trade.core.R;
import com.copy.trade.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
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;

import java.util.HashMap;
import java.util.Map;
/**
 *
 */
@ControllerAdvice(basePackages = "com.copy.trade")
public class ResponseHandler implements ResponseBodyAdvice<Object> {

    private static final Logger log = LoggerFactory.getLogger(ResponseHandler.class);

    /**
     * 是否支持advice功能
     * treu=支持，false=不支持
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        //Method method = methodParameter.getMethod();
        //NotJson notJson = method.getAnnotation(NotJson.class);
        return !methodParameter.getDeclaringClass().getName().contains("springfox");
    }

    /**
     * 处理response的具体业务方法
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        // 兼容原来已经处理的
        if (body instanceof ErrorResult) {
            ErrorResult err = (ErrorResult) body;
            Map<String, Object> map = new HashMap<>(2);
            //map.put("code", err.getCode());
            map.put("code", 500);
            map.put("msg", err.getMsg());
            return map;
        }

        if (body instanceof String) {
            response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            return JsonUtil.object2Json(R.ok(body));
        }

        return R.ok(body);
    }
}

