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

import com.qunzhixinxi.hnqz.common.qcc.entity.EmployeeGetListRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
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(EmployeeGetListRequest request) {
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = null;
        try {
            List<NameValuePair> entity = buildParams(request.getParams());

            // 创建一个get对象
            URIBuilder builder = new URIBuilder(request.getQueryUrl());
            builder.setParameters(entity);
            HttpGet get = new HttpGet(builder.build());
			get.setHeader("Token", request.getToken());
			get.setHeader("Timespan", request.getTimestamp());


            // 执行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;
    }



    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);
    }
}
