package com.crm.ib.task.configuration;

import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.service.RedisService;
import com.crm.rely.backend.util.UUIDUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
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;

/**
 * Created by max on 2020/6/17.
 */
@Configuration
public class FeignConfiguration implements RequestInterceptor {

    @Autowired
    private RedisService redisService;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null != attributes) {

            String feignToken = UUIDUtil.getUUID();

            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader(Constants.ACCESS_TOKEN);
            String language = request.getHeader(Constants.Language);
            requestTemplate.header(Constants.ACCESS_TOKEN, token);
            requestTemplate.header(Constants.Feign_Token, feignToken);
            requestTemplate.header(Constants.Language, language);

            try {
                redisService.saveObject(feignToken, token, Constants.Feign_Token_TIME);
            } catch (ServiceException e) {
                e.printStackTrace();
            }
        }
    }
}
