package com.trade.admin.handle;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.trade.common.core.domain.R;
import com.trade.common.core.domain.ResponseResult;
import com.trade.common.core.page.GridPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 javax.annotation.Resource;

/**
 * @description:
 * @Author: wanglang
 * @Date: 2023/7/28 15:08
 * @Version: 1.0
 */
@RestControllerAdvice("com.trade.admin.system.controller")
public class GlobalResponseBodyAdviceHandle implements ResponseBodyAdvice<Object> {

    private static final Logger log = LoggerFactory.getLogger(GlobalResponseBodyAdviceHandle.class);
    @Resource
    private ObjectMapper 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) {
        if (body instanceof String) {
            // 当响应体是String类型时，使用ObjectMapper转换，因为Spring默认使用StringHttpMessageConverter处理字符串，不会将字符串识别为JSON
            try {
                return objectMapper.writeValueAsString(ResponseResult.success(body));
            } catch (JsonProcessingException e) {
                log.error("Json Processing Exception:", e);
            }
        }
        // 分页还是不包装了吧
        // 已经包装过的结果无需再次包装
        if (body instanceof GridPage<?> || body instanceof ResponseResult<?>) {
            return body;
        }
        // 对响应体进行包装
        return ResponseResult.success(body);
    }
}
