package com.hotent.base.conf;

import javax.servlet.http.HttpServletRequest;

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;

import com.hotent.base.annotation.IgnoreOnAssembly;
import com.hotent.base.constants.TenantConstant;
import com.hotent.base.context.BaseContext;
import com.hotent.base.jwt.JwtTokenHandler;
import com.hotent.base.util.AppUtil;
import com.hotent.base.util.HttpUtil;
import com.hotent.base.util.StringUtil;

import feign.Contract;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.i18n.LocaleContextHolder;

/**
 * 
 * @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 {
					HttpServletRequest request = HttpUtil.getRequest();
					if (request != null) {
						token = request.getHeader("Authorization");
					}
				} catch (Exception e) {}
				// 1.请求中有token信息时复制过来
				if(StringUtil.isNotEmpty(token)){
					requestTemplate.header("Authorization", token);
				}
				// 2.没有token时使用默认token。
				else {
					requestTemplate.header("Authorization", proxyToken);
				}
				//3.使用feign调用把上游Accept-Language传给下游服务
                requestTemplate.header("Accept-Language", LocaleContextHolder.getLocale().toLanguageTag());

				BaseContext context = AppUtil.getBean(BaseContext.class);
				String currentTenantId = context.getCurrentTenantId();
				String url = requestTemplate.url();
				if (StringUtil.isNotEmpty(currentTenantId)) {
					if (url.indexOf("?") == -1) {
						url += String.format("?%s=%s", TenantConstant.TENANT_ID_KEY,currentTenantId);
					} else if(url.indexOf(TenantConstant.TENANT_ID_KEY+"=") < 0){
						url += String.format("&%s=%s", TenantConstant.TENANT_ID_KEY,currentTenantId);
					}
				}
				requestTemplate.uri(url);
			}
		};
	}

}
