package com.yeejoin.amos.boot.module.jcs.biz.config;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class ElasticSearchClientConfig {
 
	@Value("${spring.elasticsearch.rest.uris}")
    private String uris;

	@Value("${elasticsearch.username}")
	private String username;

	@Value("${elasticsearch.password}")
	private String password;
	 
	@Bean
	@Qualifier("highLevelClient")

	public RestHighLevelClient restHighLevelClient() {
			final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
			credentialsProvider.setCredentials(AuthScope.ANY,
					new UsernamePasswordCredentials(username, password));

			try {
        	String url = uris.replace("http://", "");
        	final String[] parts = StringUtils.split(url, ":");
        	HttpHost httpHost = new HttpHost(parts[0], Integer.parseInt(parts[1]), "http");
        	RestClientBuilder builder = RestClient.builder(httpHost);
        	builder.setHttpClientConfigCallback(httpClientBuilder -> {
				httpClientBuilder.disableAuthCaching();
				return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
			});
        	builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
				// 该方法接收一个RequestConfig.Builder对象，对该对象进行修改后然后返回。
				@Override
				public RequestConfig.Builder customizeRequestConfig(
						RequestConfig.Builder requestConfigBuilder) {
					return requestConfigBuilder.setConnectTimeout(5000 * 1000) // 连接超时（默认为1秒）
							.setSocketTimeout(6000 * 1000);// 套接字超时（默认为30秒）//更改客户端的超时限制默认30秒现在改为100*1000分钟
				}

			});// 调整最大重试超时时间（默认为30秒）.setMaxRetryTimeoutMillis(60000);

        	
        	return new RestHighLevelClient(builder);
        } catch (Exception e) {
        	throw new IllegalStateException("Invalid ES nodes " + "property '" + uris + "'", e);
        }
	}
}
