package com.seer.teach.mall.shipping.jt.http;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientManager {

    private static final HttpClientManager INSTANCE = new HttpClientManager();
    protected CloseableHttpClient httpClient;
    private ConnectionKeepAliveStrategy connectionKeepAliveStrategy = new DefaultConnectionKeepAliveStrategy();
    private PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    protected ResponseHandler<String> responseHandler = new BasicResponseHandler();

    private HttpClientManager() {
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(HttpClientConfig.CONNECT_TIME_OUT).setConnectionRequestTimeout(HttpClientConfig.CONNECTION_REQUEST_TIME_OUT).setSocketTimeout(HttpClientConfig.SOCKET_TIME_OUT).build();
        this.connectionManager.setDefaultMaxPerRoute(HttpClientConfig.MAX_PRE_ROUTE);
        this.connectionManager.setMaxTotal(HttpClientConfig.MAX_TOTAL);
        this.connectionManager.setValidateAfterInactivity(HttpClientConfig.VALIDATE_AFTER_INACTIVITY);
        this.httpClient = HttpClients.custom().setConnectionManager(this.connectionManager).setKeepAliveStrategy(this.connectionKeepAliveStrategy).setDefaultRequestConfig(requestConfig).build();
    }

    public String post(String url, String jsonContent, Map<String, String> headers) throws IOException {
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");
        if (null != headers && headers.size() > 0) {
            headers.keySet().forEach((key) -> post.addHeader(key, (String)headers.get(key)));
        }

        List<NameValuePair> nvp = new ArrayList();
        if (StringUtils.isNotEmpty(jsonContent)) {
            nvp.add(new BasicNameValuePair("bizContent", jsonContent));
        }

        post.setEntity(new UrlEncodedFormEntity(nvp, "utf-8"));
        return (String)this.httpClient.execute(post, this.responseHandler);
    }

    public static HttpClientManager getInstance() {
        return INSTANCE;
    }
}
