package com.yeejoin.equipmanage.common.exception.handle;

import com.alibaba.fastjson.JSON;
import com.yeejoin.equipmanage.common.entity.publics.CommonResponse;
import com.yeejoin.equipmanage.common.utils.ExceptionResult;
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.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.util.LinkedList;

/**
 * @description: 全局统一响应处理
 * @author: duanwei
 * @create: 2019-08-28 20:07
 **/
@RestControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {

	final static String SWAGGER_URL = "/v2/api-docs";
	final static String SWAGGER_RESOURCES = "swagger";
	final static String CSRF = "csrf";
	final static String ERROR = "error";

	static LinkedList<String> filterUrl = new LinkedList<>();

	static{
		filterUrl.add(SWAGGER_URL);
		filterUrl.add(SWAGGER_RESOURCES);
		filterUrl.add(CSRF);
	}

	/**
	 * 针对方法以及对象
	 *
	 * @param methodParameter
	 * @param aClass
	 * @return
	 */
	@Override
	public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
		// 不拦截/不需要处理返回值 的方法
		return true;
	}

	/**
	 * @param body
	 * @param returnType
	 * @param selectedContentType
	 * @param selectedConverterType
	 * @param request
	 * @param response
	 * @return
	 */
	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {
		for (String s : filterUrl) {
			if (request.getURI().toString().contains(s)) {
				return body;
			}
		}


		
		ResponseModel<Object> res = ResponseHelper.buildResponse(body);

		// 兼容原来的接口返回
		if (body instanceof CommonResponse || body instanceof ExceptionResult || body instanceof ResponseModel) {
			return body;
		}
		// 保证null情况下 对象不会转换错误
		if (null == body) {
			return res;
		}
		// 处理返回值是String的情况 对象不会转换错误
		if (body instanceof String) {
			return JSON.toJSONString(res);
		}
		return res;
	}

}
