package com.ximai.mes.config;

import com.ximai.mes.remote.config.CustomResponseEntityDecoder;
import com.ximai.system.service.ISysConfigService;
import feign.Logger;
import feign.Request;
import feign.RequestInterceptor;
import feign.Retryer;
import feign.codec.Decoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;

import java.util.Base64;

public class FooConfiguration {
    @Autowired
    private ISysConfigService configService;

    @Bean
    public RequestInterceptor headerInterceptor() {
        return template -> {
            String userName = configService.selectConfigByKey("sap.username");
            String passWord = configService.selectConfigByKey("sap.password");
            template.header("Content-type", "application/json;charset=utf-8");
            String usernameAndPassword = userName + ":" + passWord;
            template.header("Authorization", "Basic " + Base64.getEncoder().encodeToString(usernameAndPassword.getBytes()));
        };
    }

    @Bean
    @ConditionalOnMissingBean //这里如果不加@ConditionalOnMissingBean那么独立配置是无法生效的，原理在后面补充
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    @Bean
    Request.Options feignOptions() {
        // 设置连接超时时间为2秒，设置读取超时时间为5秒
        return new Request.Options(20 * 1000, 50 * 1000);
    }

    @Bean
    public Retryer feignRetryer() {
        //最大请求次数为5，初始间隔时间为100ms，下次间隔时间1.5倍递增，重试间最大间隔时间为1s，
        return new Retryer.Default();
    }

    @Bean
    public Decoder decoder(ObjectFactory<HttpMessageConverters> messageConverters){
        return new CustomResponseEntityDecoder(messageConverters);
    }
}

