package com.artfess.base.feign.impl;

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

import com.artfess.base.enums.ResponseErrorEnums;
import com.artfess.base.exception.BaseException;
import com.artfess.base.model.CommonResult;
import com.artfess.base.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * 代理的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() + "】服务接口调用异常！");
		}
	}

}
