package com.yeejoin.amos.supervision.business.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.typroject.tyboot.core.foundation.context.RequestContext;

import javax.servlet.http.HttpServletRequest;

public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {


    public FeignBasicAuthRequestInterceptor() {

    }

    @Override
    public void apply(RequestTemplate template) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            template.header("token", RequestContext.getToken());
            template.header("product", RequestContext.getProduct());
            template.header("appKey", RequestContext.getAppKey());
            return;
        }
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = attributes.getRequest();

        //设置header
        String token = request.getHeader("token");
        if (token == null) {
            token = request.getHeader("X-Access-Token");
        }
        String product = request.getHeader("product");
        String appKey = request.getHeader("appKey");
        template.header("bizType",request.getContextPath().substring(1));
        template.header("token", token);
        template.header("product", product);
        template.header("appKey", appKey);
        template.header("clientType","feignClient");
    }

}
