package com.zd.common.core.web.domain;

import com.zd.common.core.domain.R;
import com.zd.common.core.web.domain.AjaxResult;
import com.zd.common.core.web.page.TableDataInfo;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
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.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Map;

/**
 * 返回值增强器
 *
 * @Author: zhoupan
 * @Date: 2021/09/09/10:34
 * @Description:
 */
@RestControllerAdvice
@ConditionalOnMissingClass("ZdGatewayApplication")
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    static AntPathMatcher antPathMatcher = new AntPathMatcher();

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

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof TableDataInfo) return o;
        if (o instanceof AjaxResult) return o;
        if (o instanceof ResultData) return o;
        if (o instanceof R) return o;
        if (o instanceof String) return o;
        if(methodParameter.getMethod().getName().equals("error"))
        {
            return ResultData.fail(((Map<String,Object>)o).get("error").toString());
        }
        //swagger 不包装
        boolean match = antPathMatcher.match("/**/api-docs", serverHttpRequest.getURI().getPath());
        boolean match1 = antPathMatcher.match("/swagger-resources/**", serverHttpRequest.getURI().getPath());
        boolean match2 = antPathMatcher.match("/actuator/health/**", serverHttpRequest.getURI().getPath());
        boolean match3 = antPathMatcher.match("/actuator/**", serverHttpRequest.getURI().getPath());
        if (match || match1 || match2 || match3) return o;
        return ResultData.success(o);
    }
}
