package com.artfess.base.conf;

import com.artfess.base.annotation.IgnoreOnAssembly;
import com.artfess.base.jwt.JwtTokenHandler;
import com.artfess.base.util.AppUtil;
import com.artfess.base.util.HttpUtil;
import com.artfess.base.util.StringUtil;
import feign.Contract;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.openfeign.support.SpringMvcContract;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 
 * @author liyg
 * @Date 2018-08-14
 */
@Configuration
@IgnoreOnAssembly
public class FeignConfig{

	@Value("${feign.encry.key:feignCallEncry}")
	private String encryKey;

	// Feign调用失败时是否抛出异常
	@Value("${feign.fallback.default.exception:true}")
	private boolean fallbackException = true;
	
	public boolean isFallbackException() {
		return fallbackException;
	}
	
	@Bean
	public Contract feignContract(){
		return new SpringMvcContract();
	}

	/**
	 * 从请求中获取 Authorization设置到feign请求中
	 * @return
	 */
	@Bean
	public RequestInterceptor requestTokenBearerInterceptor() {
		return new RequestInterceptor() {
			@Override	
			public void apply(RequestTemplate requestTemplate) {
				String token ="";
				JwtTokenHandler jwtTokenHandler = AppUtil.getBean(JwtTokenHandler.class);
				String proxyToken = "Bearer " + jwtTokenHandler.generateFeignToken();
				// 标记该请求是通过feign过来的
				requestTemplate.header("Proxy-Authorization", proxyToken);
				try {
					token = HttpUtil.getRequest().getHeader("Authorization");
				} catch (Exception e) {}
				// 1.请求中有token信息时复制过来
				if(StringUtil.isNotEmpty(token)){
					requestTemplate.header("Authorization", token);
				}
				// 2.没有token时使用默认token。
				else {
					requestTemplate.header("Authorization", proxyToken);
				}
			}
		};
	}

}
