package com.css.simulation.resource.scene.common.config;

import api.common.util.ObjectUtil;
import com.css.simulation.resource.scene.common.oauth.AuthorizationHolder;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 转发 token
 */
@Configuration
public class FeignConfiguration implements RequestInterceptor {

    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String authorization = "";
        if(ObjectUtil.isNull(attributes)){
            authorization = AuthorizationHolder.getAuthorization();
            AuthorizationHolder.remove();
        }else{
            HttpServletRequest request = attributes.getRequest();
            authorization = request.getHeader("Authorization");
        }
        requestTemplate.header("Authorization", authorization);
    }
}
