package com.tykj.dev.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tykj.dev.misc.base.ResultObj;
import org.springframework.context.annotation.Configuration;
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.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * UnifiedReturnConfig.
 *
 * @author Matrix <xhyrzldf@gmail.com>
 * @since 2020/10/9 at 3:17 下午
 */
@Configuration
@RestControllerAdvice("com.tykj.dev.device")
public class UnifiedReturnConfig implements ResponseBodyAdvice<Object> {

    private ObjectMapper objectMapper = new ObjectMapper();

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

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        // 如果返回的是 null/ResultObj/流媒体  那么不做处理直接返回
        boolean isVoid = Objects.isNull(body);
        boolean isResultObj = body instanceof ResultObj;
        boolean isStream = selectedContentType.includes(MediaType.APPLICATION_OCTET_STREAM);
        if (isVoid || isResultObj || isStream) {
            return body;
        }

        ResultObj<Object> result = new ResultObj<>(body, "成功 :)");

        // 如果返回的是字符串，则要对其做JSON序列化
        if (body.getClass().equals(String.class)) {
            try {
                response.getHeaders().set("Content-Type", "application/json;charset=utf-8");
                return objectMapper.writeValueAsString(result);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }

        // 其他的类型直接封装返回
        return result;
    }
}

