package com.ruoyi.framework.config;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.ruoyi.common.annotation.IgnoreResponse;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;


/**
 * <pre>
 * - 统一结果返回
 * Author : J.L.Zhou
 * E-Mail : 2233875735@qq.com
 * Tel : 151 1104 7708
 * Date : 2021-5-28 12:12:32
 * Version : 1.0
 * Copyright 2021 jlzhou.top Inc. All rights reserved.
 * Warning: this content is only for internal circulation of the company.
 *          It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 */
@SuppressWarnings("rawtypes")
@RestControllerAdvice
@Slf4j
public class CommonResponseBodyAdvice implements ResponseBodyAdvice {


	@Override
	public boolean supports(MethodParameter returnType, Class converterType) {
		//方法上被标注，也不拦截
		if (returnType.getMethod().isAnnotationPresent(IgnoreResponse.class)) {
			return false;
		}
    HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
//    log.debug("uri:{}",request.getRequestURI());
    if(request.getRequestURI().startsWith("/actuator")) {
      return false;
    }
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
		if(null == body ){
			return R.ok();
		}else if(body instanceof R || body instanceof TableDataInfo){
			return body;
		}else{
			return R.ok().setData(body);
		}
	}


}
