package com.xingxi.api.configuration;

import com.xingxi.api.common.ResponseDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.io.Resource;
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.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;


@Slf4j
@ControllerAdvice("com.xingxi.store.controller")
@RequiredArgsConstructor
class RequestResultWrapperResponseAdvice implements ResponseBodyAdvice<Object> {
    private final ObjectMapper objectMapper;
//    private final OperLogService operLogService;

    @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) {

        HttpServletRequest servletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String requestId = (String) servletRequest.getAttribute("X-REQUEST-ID");

        ResponseDTO<Object> apiResultDTO = new ResponseDTO<>(body);
        apiResultDTO.setRequestId(requestId);
        if (body instanceof String) {
            try {
                log.info("ResponseBodyAdvice body:{}", body);
                return objectMapper.writeValueAsString(apiResultDTO);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }

        if ((body instanceof Resource) || (body instanceof ResponseDTO)) {
            log.info("ResponseBodyAdvice body:{}", body);
            return body;
        }
        log.info("apiResultDTO:{}", apiResultDTO);
//        operLogService.handleAfterLog(apiResultDTO, servletRequest);

        return apiResultDTO;
    }
}
