package com.qunzhixinxi.hnqz.common.ding.utils;

import com.qunzhixinxi.hnqz.common.ding.entity.CommonRequest;
import com.qunzhixinxi.hnqz.common.ding.sign.AccessSign;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
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.utils.URIBuilder;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * http工具类
 *
 * @author zhangwt
 * @since 1.0
 */
@Slf4j
public class HttpClientUtils {
    private HttpClientUtils() {
    }

    private static final int RESPONSE_OK = 200;
    private static final String CHARSET_HTTP = "UTF-8";
    private static final String CHARSET_STREAM = "ISO-8859-1";

    /**
     * get请求
     *
     * @param
     * @return
     * @author zhangwt
     * @since 1.0
     */
    public static String doGet(String url, Map<String, String> params) {
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = null;
        try {
            List<NameValuePair> entity = buildParams(params);

            // 创建一个get对象
            URIBuilder builder = new URIBuilder(url);
            builder.setParameters(entity);
            HttpGet get = new HttpGet(builder.build());

            // 执行get请求
            response = httpClient.execute(get);

            // 网关调用成功
            if (response.getStatusLine().getStatusCode() == RESPONSE_OK) {
                result = fromStream(response.getEntity().getContent(), CHARSET_HTTP);
                log.info("httpClient Get请求结果：{}", result);
            }
        } catch (Exception e) {
            log.error("httpClient Get请求失败", e);
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                log.error("httpClient Get关闭异常", e);
            }
        }

        return result;
    }

    /**
     * post请求
     *
     * @param
     * @return
     * @author zhangwt
     * @since 1.0
     */
    public static String doPost(CommonRequest request) {
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = null;
        try {
			// 创建一个post对象
			HttpPost post = new HttpPost(request.getQueryUrl());

			AccessSign sign = request.getSign();
			// 增加header
			post.setHeader("app-id",sign.getAppId());
			post.setHeader("signature",sign.getSign());

			// 增加body
			StringEntity entity = new StringEntity(request.getBody(), CHARSET_HTTP);
			entity.setContentEncoding(CHARSET_HTTP);
			entity.setContentType("application/json");
			post.setEntity(entity);

			// 执行post请求
			response = httpClient.execute(post);

			// 网关调用成功
			if (response.getStatusLine().getStatusCode() == RESPONSE_OK) {
				result = fromStream(response.getEntity().getContent(), CHARSET_HTTP);
				log.info("httpClient Post请求结果：{}", result);
			}
        } catch (Exception e) {
            log.error("httpClient Post请求失败", e);
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                log.error("httpClient Post关闭异常", e);
            }
        }

        return result;
    }

    private static List<NameValuePair> buildParams(Map<String, String> params) {
        if (params == null || params.size() == 0) {
            return null;
        }

        List<NameValuePair> results = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            results.add(new BasicNameValuePair(key, value));
        }

        return results;
    }

    private static String fromStream(InputStream is, String charset) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(is, CHARSET_STREAM));
        StringBuffer buffer = new StringBuffer();

        String line = "";
        while ((line = in.readLine()) != null) {
            buffer.append(line);
        }

        return new String(buffer.toString().getBytes(CHARSET_STREAM), charset);
    }
}
