package com.zfire.jiasm.syncdata.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zfire.jiasm.syncdata.helper.GreeResponseHelperOther;
import com.zfire.jiasm.syncdata.helper.ResponseHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.web.client.HttpStatusCodeException;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpUtil {

    private static PoolingHttpClientConnectionManager connectionManager = null;
    private static HttpClientBuilder httpBuilder = null;
    private static RequestConfig requestConfig = null;

    /**
     * 最大连接连接数量
     */
    private static int MAX_CONNECTION = 100;
    /**
     * 最大并发请求数量
     */
    private static int DEFAULT_MAX_CONNECTION = 50;

    static {
        //设置http的状态参数
        requestConfig = RequestConfig.custom()
                .setSocketTimeout(10000)
                .setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000)
                .build();

        connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(MAX_CONNECTION);
        connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTION);
        httpBuilder = HttpClients.custom();
        httpBuilder.setConnectionManager(connectionManager);
    }

    /**
     * 获取http客户端连接
     *
     * @return http客户端连接
     */
    public static CloseableHttpClient getConnection() {
        return httpBuilder.build();
    }

    /**
     * http post请求，利用http请求池
     *
     * @param url       请求url
     * @param paramsMap 请求参数
     * @return 请求结果
     * @throws Exception 异常
     */
    public static String httpPost(String url, Map<String, String> paramsMap) throws Exception {
        List<NameValuePair> params = new ArrayList<>();

        for (Map.Entry<String, String> e : paramsMap.entrySet()) {
            NameValuePair pair = new BasicNameValuePair(e.getKey(), e.getValue());
            params.add(pair);
        }

        HttpUriRequest postMethod = RequestBuilder.post().setUri(url)
                .addParameters(params.toArray(new BasicNameValuePair[params.size()]))
                .setConfig(requestConfig).build();

        HttpResponse response = getConnection().execute(postMethod);

        return EntityUtils.toString(response.getEntity());
    }

    /**
     * http post请求，利用http请求池
     *
     * @param url     请求url
     * @param jsonStr json字符串
     * @return 请求结果
     * @throws Exception 异常
     */
    public static String httpPostJson(String url, String jsonStr) throws Exception {

        HttpUriRequest postMethod = RequestBuilder.post().setUri(url)
                .setHeader("Content-Type", "application/json;charset=utf-8")
                .setHeader("Accept", "application/json")
                .setEntity(new StringEntity(jsonStr, Charset.forName("UTF-8")))
                .setConfig(requestConfig).build();
        HttpResponse response = getConnection().execute(postMethod);

        return EntityUtils.toString(response.getEntity());
    }

    /**
     * http get请求，利用http请求池
     *
     * @param url 请求url
     * @return 请求结果
     * @throws Exception 异常
     */
    public static Map<String, Object> httpGet(String url) throws Exception {
        HttpUriRequest getMethod = RequestBuilder.get().setUri(url)
                .setConfig(requestConfig).build();

        log.info("url :{}" + url);

        HttpResponse response = getConnection().execute(getMethod);
        Map<String, Object> result = JSON.parseObject(EntityUtils.toString(response.getEntity()));
        log.info("httpGet result :" + response.getEntity());
        return result;
    }


    public static GreeResponseHelperOther httpGetInfo(String url,String token) throws Exception {
        try {
            HttpUriRequest getMethod = RequestBuilder.get().setUri(url)
                    .setHeader("authorization","Bearer "+token)
                    .setConfig(requestConfig).build();
            HttpResponse response = getConnection().execute(getMethod);
            String body = EntityUtils.toString(response.getEntity());
            return JSONObject.parseObject(body, GreeResponseHelperOther.class);
        }catch(HttpStatusCodeException ex) {
            log.error("rawStatusCode = {}",ex.getRawStatusCode());
            GreeResponseHelperOther greeResponseHelper = new GreeResponseHelperOther();
            greeResponseHelper.setStatusCode(ex.getRawStatusCode());
            greeResponseHelper.setMessage(ex.getMessage());
            ex.printStackTrace();
            return greeResponseHelper;
        }catch(Exception e){
            GreeResponseHelperOther greeResponseHelper = new GreeResponseHelperOther();
            greeResponseHelper.setStatusCode(ResponseHelper.ResponseCode_COMMON);
            greeResponseHelper.setMessage("非法请求");
            e.printStackTrace();
            return greeResponseHelper;
        }
    }

    public static GreeResponseHelperOther sendData(String url, String token) {
        CloseableHttpClient httpClient;
        HttpPost httpPost = null;
        org.apache.http.HttpEntity entity;
        long interval = System.currentTimeMillis();
        String resStr="";
        JSONObject json = new JSONObject();
        try {
            httpClient = HttpClients.createDefault();
            httpPost = new HttpPost(url);
            RequestConfig reqconfig = RequestConfig.custom()
                    .setConnectTimeout(60 * 1000)
                    .setConnectionRequestTimeout(60 * 1000)
                    .setSocketTimeout(60 * 1000).build();
            httpPost.setConfig(reqconfig);
            httpPost.setHeader("authorization","Bearer "+token);
            log.info("url :{}" + url);
            CloseableHttpResponse response =  httpClient.execute(httpPost);
            entity = response.getEntity();
            resStr = EntityUtils.toString(entity).trim();
            EntityUtils.consume(entity);
            response.close();
            return JSONObject.parseObject(resStr, GreeResponseHelperOther.class);
        }catch(HttpStatusCodeException ex) {
            log.error("rawStatusCode = {}",ex.getRawStatusCode());
            GreeResponseHelperOther greeResponseHelper = new GreeResponseHelperOther();
            greeResponseHelper.setStatusCode(ex.getRawStatusCode());
            greeResponseHelper.setMessage(ex.getMessage());
            ex.printStackTrace();
            return greeResponseHelper;
        }catch(Exception e){
            GreeResponseHelperOther greeResponseHelper = new GreeResponseHelperOther();
            greeResponseHelper.setStatusCode(ResponseHelper.ResponseCode_COMMON);
            greeResponseHelper.setMessage("非法请求");
            e.printStackTrace();
            return greeResponseHelper;
        } finally {
            if (httpPost != null)
                httpPost.releaseConnection();
        }
    }

    /**
     * http get请求，利用http请求池
     *
     * @param url       请求url
     * @param paramsMap 请求参数
     * @return 请求结果
     * @throws Exception 异常
     */
    public static String httpGet(String url, Map<String, String> paramsMap) throws Exception {
        List<NameValuePair> params = new ArrayList<>();

        for (Map.Entry<String, String> e : paramsMap.entrySet()) {
            NameValuePair pair = new BasicNameValuePair(e.getKey(), e.getValue());
            params.add(pair);
        }

        HttpUriRequest getMethod = RequestBuilder.get().setUri(url)
                .addParameters(params.toArray(new BasicNameValuePair[params.size()]))
                .setConfig(requestConfig).build();

        HttpResponse response = getConnection().execute(getMethod);

        return EntityUtils.toString(response.getEntity());
    }

    /**
     * http post 请求,每次创建请求客户端
     *
     * @param url    url
     * @param params 请求参数
     * @return 请求返回值
     */
    public static String httpPostNoPool(String url, Map<String, String> params) {
        CloseableHttpClient closeableHttpClient = null;
        try {
            HttpPost httpPost = new HttpPost(url);

            if (params != null) {
                List<NameValuePair> form = new ArrayList<>();

                for (String name : params.keySet()) {
                    form.add(new BasicNameValuePair(name, params.get(name)));
                }

                httpPost.setEntity(new UrlEncodedFormEntity(form, HTTP.UTF_8));
            }

            closeableHttpClient = HttpClients.createDefault();
            CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpPost);
            HttpEntity entry = httpResponse.getEntity();
            return EntityUtils.toString(entry);
        } catch (Exception e) {
            log.error("HttpUtil.httpPost failed!", e);
        } finally {
            if (null != closeableHttpClient) {
                try {
                    closeableHttpClient.close();
                } catch (IOException e) {
                    log.error("closeableHttpClient.close failed!", e);
                }
            }
        }
        return null;
    }

}
