package com.hotent.base.feign.impl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hotent.base.enums.ResponseErrorEnums;
import com.hotent.base.exception.BaseException;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.JsonUtil;

/**
 * 代理的feign失败调用处理
 * @author mikel
 *
 */
public class FallbackFeignServiceHandler implements InvocationHandler{

	private Logger logger = LoggerFactory.getLogger(FallbackFeignServiceHandler.class);

	protected String feignServiceName;
	protected Throwable fallbackError;
	
	public FallbackFeignServiceHandler(String feignServiceName, Throwable cause) {
		this.feignServiceName = feignServiceName;
		this.fallbackError = cause;
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		logger.error("Feign【" + feignServiceName + "】invoke method 【" + method.getName() + "】 failed." , fallbackError);
		logger.debug("接口参数信息：" + JsonUtil.toJsonString(args));
		Class<?> retType = method.getReturnType();
		if (retType.isAssignableFrom(CommonResult.class)) {
			String message = "服务【" + feignServiceName + "】繁忙或不可用，请稍后再试！";
			return new CommonResult<>(ResponseErrorEnums.SERVICE_INVOKE_ERROR, message);
		} else {
			throw new BaseException(ResponseErrorEnums.SERVICE_INVOKE_ERROR, "【" + feignServiceName + "." + method.getName() + "】服务接口调用异常！");
		}
	}

}
