package com.leanwo.activiti.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import com.leanwo.activiti.exception.AuthorizeException;
import com.leanwo.activiti.util.LoginContext;
import com.leanwo.activiti.util.LoginContextUtil;
import com.leanwo.activiti.util.StringUtil;
import com.leanwo.activiti.util.TokenUtil;

import feign.RequestInterceptor;
import feign.RequestTemplate;


/**
 * Feign配置
 * 使用FeignClient进行服务间调用，传递headers信息
 */
@Configuration
public class FeignConfig implements RequestInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(FeignConfig.class.getName());
    
    @Override
    public void apply(RequestTemplate requestTemplate) {
    	LoginContext loginContext = LoginContextUtil.getLoginContext();

        if (loginContext == null) {
            throw new AuthorizeException("您没有权限调用业务服务器。");
        }
        String token = TokenUtil.getToken();
        logger.info("jwtToken:" + token);
        if (StringUtil.isNotEmpty(token)) {
            // header里面添加jwt-token
            requestTemplate.header("token", token);
            requestTemplate.header("account", loginContext.getAccountId().toString());
            logger.info("header:" + requestTemplate.headers());
        }
        if(loginContext.getAccountId() != null) {
        	requestTemplate.header("account", loginContext.getAccountId().toString());
        	logger.info("account:" + loginContext.getAccountId());
        }
    }
}