package com.crm.manager.configuration;

import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.service.RedisService;
import com.crm.rely.backend.util.UUIDUtil;
import com.google.common.base.Strings;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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();
        String token = null;
        String language = null;
        if (null != attributes) {
            HttpServletRequest request = attributes.getRequest();
            token = request.getHeader(Constants.ACCESS_TOKEN);
            language = request.getHeader(Constants.Language);
        }

        String feignToken = UUIDUtil.getUUID();
        if (Strings.isNullOrEmpty(token)) {
            token = feignToken;
        }
        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();
        }
    }
}
