package com.sckw.core.web.request;

import com.alibaba.fastjson.JSON;
import com.sckw.core.model.constant.Global;
import com.sckw.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc http请求工具类
 * @Author dengyinghui
 * @Date 2018年02月03日
 */
@Slf4j
public class HttpClientUtil {

    private static final String UTF_8 = "UTF-8";

    /**
     * POST请求
     *
     * @param url 请求地址
     * @return 返回结果
     * @Date 2018年02月03日
     */
    public static String post(String url) throws ClientProtocolException, IOException {
        return post(url, Global.EMPTY_STRING);
    }

    /**
     * POST请求
     * @param url    请求地址
     * @param params 请求参数
     * @return 返回结果
     * @Date 2018年02月03日
     */
    public static String post(String url, Map<String, Object> params) throws ClientProtocolException, IOException {
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> pairs = null;
        if (params != null && params.size() > 0) {
            pairs = covertParams2Nvps(params);
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return handlerRequest(httpPost);
    }

    /**
     * POST请求
     * @param url    请求地址
     * @param body 请求参数
     * @param headsMap 请求参数
     * @return 返回结果
     * @Date 2018年02月03日
     */
    public static String postBody(String url, String body, Map<String, Object> headsMap) {
        int successCode = 200;
        log.debug("start:");
        // 实例化httpClient
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 实例化post方法
        HttpPost httpPost = new HttpPost(url);
        //头
        httpPost.setHeader("Content-Type", "application/json");
        if (headsMap != null && !headsMap.isEmpty()) {
            for (String key : headsMap.keySet()) {
                httpPost.setHeader(key, (String) headsMap.get(key));
            }
        }
        log.debug("initheader");
        // 结果
        CloseableHttpResponse response = null;
        String content = null;
        try {
            log.debug("initbody");
            // 将参数给post方法
            if (body != null) {
                StringEntity stringEntity = new StringEntity(body, "UTF-8");
                httpPost.setEntity(stringEntity);
            }
            log.info(httpPost.toString());
            // 执行post方法
            response = httpclient.execute(httpPost);
            log.info(response.getEntity().toString());
            try {
                content = EntityUtils.toString(response.getEntity(), "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("HttpClientUtil.postBody:", e.getMessage());
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content;
    }

    /**
     * POST请求
     * @param url  请求地址
     * @param data 字符参数参数
     * @return 返回结果
     * @Date 2018年02月03日
     */
    public static String post(String url, String data) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        try {
            if (!StringUtils.validatorEmpty(data)) {
                httpPost.setEntity(new StringEntity(data, UTF_8));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        CloseableHttpResponse response = null;
        String content = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            response = httpclient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            try {
                content = EntityUtils.toString(response.getEntity(), "UTF-8");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content;
    }


    /**
     * GET请求
     * @param url 请求地址
     * @return 返回结果
     * @Date 2018年02月03日
     */
    public static String get(String url) throws ClientProtocolException, IOException {
        return get(url, null);
    }

    /**
     * GET请求
     * @param url    请求地址
     * @param params 请求参数
     * @return 返回结果
     * @Date 2018年02月03日
     */
    public static String get(String url, Map<String, Object> params) throws ClientProtocolException, HttpHostConnectException, IOException {
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);
        if (params != null && params.size() > 0) {
            List<NameValuePair> pairs = covertParams2Nvps(params);
            ub.setParameters(pairs);
        }
        HttpGet httpGet = null;
        try {
            httpGet = new HttpGet(ub.build());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return handlerRequest(httpGet);
    }

    /**
     * 封装请求参数
     * @param params 请求参数
     * @return 返回结果
     * @Date 2018年02月03日
     */
    private static List<NameValuePair> covertParams2Nvps(Map<String, Object> params) {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for (Map.Entry<String, Object> param : params.entrySet()) {
            pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
        }
        return pairs;
    }

    /**
     * 处理Http请求
     * @param httpRequestBase
     * @return 返回结果
     * @Date 2018年02月03日
     */
    private static String handlerRequest(HttpRequestBase httpRequestBase) throws ClientProtocolException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpRequestBase);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, UTF_8);
            response.close();
            return result;
        }
        return null;
    }

    public static String postBody(String url, String body) {
        int successCode = 200;
        // 实例化httpClient
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 实例化post方法
        HttpPost httpPost = new HttpPost(url);
        // 结果
        CloseableHttpResponse response = null;
        String content = null;
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("token", null);
        httpPost.setHeader("type", "pc");
        httpPost.setHeader("version", "5");
        try {
            // 将参数给post方法
            if (body != null) {
                StringEntity stringEntity = new StringEntity(body, "UTF-8");
                httpPost.setEntity(stringEntity);
            }
            // 执行post方法
            response = httpclient.execute(httpPost);
            try {
                content = EntityUtils.toString(response.getEntity(), "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("HttpClientUtil.postBody:", e.getMessage());
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content;
    }

    /**
     * GET请求
     * @param url    请求地址
     * @return 返回结果
     * @Date 2018年02月03日
     */
    public static String getBody(String url) {
        // 实例化httpClient
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 实例化post方法
        //HttpPost httpPost = new HttpPost(url);
        HttpGet httpGet = new HttpGet(url);
        // 结果
        CloseableHttpResponse response = null;
        String content = null;
        httpGet.setHeader("Content-Type", "application/json");
        try {
            // 执行post方法
            int successCode = 200;
            response = httpclient.execute(httpGet);
            try {
                content = EntityUtils.toString(response.getEntity(), "UTF-8");
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content;
    }

    /**
     * POST请求
     * @param url    请求地址
     * @param params 请求参数
     * @return 返回结果
     * @Date 2018年02月03日
     */
    public static String postByMapString(String url, Map<String, String> params) throws ClientProtocolException, IOException {
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> pairs = null;
        if (params != null && params.size() > 0) {
            pairs = new ArrayList<>();
            for (Map.Entry<String, String> param : params.entrySet()) {
                pairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
            }
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return handlerRequest(httpPost);
    }


}