package com.docus.server.common;

import com.docus.infrastructure.web.api.CommonResult;
import com.docus.infrastructure.web.exception.ApiException;
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.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

//统一controller输出格式，和抛出的异常
@RestControllerAdvice
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    private static final Logger logger = LoggerFactory.getLogger(GlobalResponseBodyAdvice.class);

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return !CommonResult.class.isAssignableFrom(methodParameter.getParameterType());
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        String path = request.getURI().getPath();
        // 跟swagger冲突，跳出response包装
        if (path.contains("swagger") || path.contains("api-docs") || path.contains("error") || path.contains("/monitor/url-mappings")) {
            return body;
        }

        //springBootAdmin获取服务信息
        if (path.startsWith("/actuator")) {
            return body;
        }

        return CommonResult.success(body);
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Object defaultErrorHandler(HttpServletRequest req, Exception ex) {
        if (ex instanceof ApiException) {
            logger.info("{} 错误 ,code:{}, message:{}", req.getRequestURL(), ((ApiException) ex).getCode(), ex.getMessage());
            return CommonResult.failed(ex.getMessage());
        } else if (ex instanceof NoHandlerFoundException) {
            logger.info("{} 错误 ,code:{}, message:{}", req.getRequestURL(), 404, ex.getMessage());
        }
        return CommonResult.failed("系统出错");
    }
}
