package com.hz.pm.api.common.handler;

import com.ningdatech.basic.model.ApiResponse;
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.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * <p>
 * GlobalResponseHandler
 * </p>
 *
 * @author WendyYang
 * @since 10:29 2023/12/29
 */
@RestControllerAdvice(basePackages = {
        "com.hz.pm.api.fiscal.controller",
        "com.hz.pm.api.organization.controller",
        "com.hz.pm.api.projectdeclared.controller",
        "com.hz.pm.api.projectlib.controller",
        "com.hz.pm.api.sys.controller",
        "com.hz.pm.api.todocenter.controller",
        "com.hz.pm.api.user.controller",
        "com.hz.pm.api.meeting.controller",
        "com.hz.pm.api.expert.controller",
        "com.hz.pm.api.sms.controller",
        "com.hz.pm.api.workbench.controller",
        "com.hz.pm.api.ding.controller",
        "com.hz.pm.api.filemanage.controller",
        "com.hz.pm.api.performance.controller",
        "com.hz.pm.api.irs.controller",
        "com.hz.pm.api.safety.controller",
        "com.hz.pm.api.portrait.controller",
        "com.hz.pm.api.irs.controller",
        "com.hz.pm.api.gov.controller",
        "com.hz.pm.api.dashboard.controller",
        "com.hz.pm.api.wps.controller",
        "com.hz.pm.api.external.controller",
        "com.hz.pm.api.gov.controller"
})
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {

    private static final String SWAGGER_CLASS_PREFIX = "springfox.documentation";

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return filter(methodParameter);
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        return ApiResponse.ofSuccess(o);
    }

    private Boolean filter(MethodParameter methodParameter) {
        Class<?> declaringClass = methodParameter.getDeclaringClass();
        // swagger中的所有返回不进行统一封装
        if (declaringClass.getName().contains(SWAGGER_CLASS_PREFIX)) {
            return false;
        }
        if (methodParameter.hasMethodAnnotation(ExceptionHandler.class)) {
            return false;
        }
        // 如果本身就是使用ApiResponse返回，则不需要进行格式化
        return !methodParameter.getParameterType().equals(ApiResponse.class);
    }
}
