package com.xxfc.platform.universal.weixin.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.protocol.HttpContext;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;


@Slf4j
public class HTTPUtils{
	
	private static PoolingHttpClientConnectionManager connManager;  
    private static RequestConfig requestConfig;  
    private static final int MAX_TIMEOUT = 10 * 1000;  
    
    static {  
        // 设置连接池 
    	connManager = new PoolingHttpClientConnectionManager();  
        // 设置连接池大小  
    	connManager.setMaxTotal(100);  
    	connManager.setDefaultMaxPerRoute(connManager.getMaxTotal());  
    	// 在提交请求之前 测试连接是否可用  
    	connManager.setValidateAfterInactivity(3600);  
  
        RequestConfig.Builder configBuilder = RequestConfig.custom();  
        // 设置连接超时  
        configBuilder.setConnectTimeout(MAX_TIMEOUT);  
        // 设置读取超时  
        configBuilder.setSocketTimeout(MAX_TIMEOUT);  
        // 设置从连接池获取连接实例的超时  
        configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);  
       
        requestConfig = configBuilder.build();  
    }  
    
    /**
     * 发送 GET 请求（HTTP），不带输入数据 
     * @param url
     * @return
     */
    public static String doGet(String url) {  
        return doGet(url, new LinkedHashMap<String, Object>());  
    } 
    
    public static String getParams(String url,Map<String,Object> params)
    {
    	if(StringUtils.isBlank(url)) return null;
    	 StringBuilder param = new StringBuilder();  
         int i = 0;  
         for (String key : params.keySet()) {  
             if (i == 0)  
                 param.append("?");  
             else  
                 param.append("&");  
             param.append(key).append("=").append(params.get(key));  
             i++;  
         }  
         url += param; 
         return url;
    }
    
    /**
     * 发送 GET 请求（HTTP），K-V形式 
     * @param url
     * @param params
     * @return
     */
    public static String doGet(String url, Map<String, Object> params) {  
    	if(StringUtils.isBlank(url)) return null;
        StringBuilder param = new StringBuilder();  
        int i = 0;  
       /* for (String key : params.keySet()) {  
            if (i == 0)  
                param.append("?");  
            else  
                param.append("&");
            
            
            param.append(key).append("=").append(params.get(key));  
            i++;  
        }*/  
        
		for (Entry<String, Object> entry : params.entrySet()) {
			String key = entry.getKey();
			Object value = entry.getValue();
			if(value==null)
				continue;
			if (i == 0)  
                param.append("?");  
            else  
                param.append("&");
			param.append(key).append("=").append(value);  
	        i++;  
		}
        
        
        
        url += param;  
        String result = null;  
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {  
            HttpGet httpPost = new HttpGet(url);  
            HttpResponse response = httpclient.execute(httpPost);  
            int statusCode = response.getStatusLine().getStatusCode();  
  
           // System.out.println("执行状态码 : " + statusCode);  
  
            HttpEntity entity = response.getEntity();  
            if (entity != null) {  
                InputStream instream = entity.getContent();  
                result = IOUtils.toString(instream, "UTF-8");  
            }  
        } catch (Exception e) {  
        	log.error(e.getMessage());
        } 
        return result;  
    }
    
    private static HttpGet setJsonHeader(HttpGet httpGet){
    	httpGet.setHeader("Content-Type", "application/json");
    	httpGet.setHeader("Accept", "application/json");
    	httpGet.setHeader("charset", "utf-8");
    	return httpGet;
    }
    
    public static String doGetJson(String url, Map<String, Object> params) {  
    	if(StringUtils.isBlank(url)) return null;
        StringBuilder param = new StringBuilder();  
        int i = 0;
        if(params != null){
        	for (String key : params.keySet()) {  
                if (i == 0)  
                    param.append("?");  
                else  
                    param.append("&");  
                param.append(key).append("=").append(params.get(key));  
                i++;  
            }  
            url += param;
        }          
        String result = null;  
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {  
            HttpGet httpGet = new HttpGet(url); 
            //httpGet = setJsonHeader(httpGet);
            HttpResponse response = httpclient.execute(httpGet);  
            int statusCode = response.getStatusLine().getStatusCode();  
  
           // System.out.println("执行状态码 : " + statusCode);  
  
            File file = new File("D:\\t.txt");
            HttpEntity entity = response.getEntity();  
            if (entity != null) {  
                InputStream instream = entity.getContent();  
                FileOutputStream fips = new FileOutputStream(file);
                result = IOUtils.toString(instream, "UTF-8");  
                fips.write(result.getBytes());
            }  
        } catch (Exception e) {  
        	log.error(e.getMessage());
        } 
        return result;  
    }
    
    /**
     * 发送 POST 请求（HTTP），不带输入数据 
     * @param url
     * @return
     */
    public static String doPost(String url) {  
        return doPost(url, new LinkedHashMap<String, Object>());  
    }  
    
    /**
     * 发送 POST 请求（HTTP），K-V形式 
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, Map<String, Object> params) {  
    	if(StringUtils.isBlank(url)) return null;
    	
        CloseableHttpClient httpClient = HttpClients.createDefault();  
        String result = null;  
        HttpPost httpPost = new HttpPost(url);  
        CloseableHttpResponse response = null;  
  
        try {  
            httpPost.setConfig(requestConfig);
            
            List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());  
            for (Entry<String, Object> entry : params.entrySet()) {
                NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());  
                pairList.add(pair);  
            }  
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));  
            
            response = httpClient.execute(httpPost);  
            
            HttpEntity entity = response.getEntity();  
            result = EntityUtils.toString(entity, "UTF-8");  
            
        } catch (Exception e) {  
        	log.error(e.getMessage());
        } finally {  
            if (response != null) {  
                try {  
                    EntityUtils.consume(response.getEntity());  
                } catch (Exception e) {  
                	log.error(e.getMessage());
                }  
            }  
        }  
        return result;  
    }  
    
    /**
     * 发送 POST 请求（HTTP），K-V形式 
     * @param url
     * @param data
     * @return
     */
    public static String doPost(String url, String data) {  
    	if(StringUtils.isBlank(url)) return null;
    	
        CloseableHttpClient httpClient = HttpClients.createDefault();  
        String result = null;  
        HttpPost httpPost = new HttpPost(url);  
        CloseableHttpResponse response = null;  

        try {  
            httpPost.setConfig(requestConfig);
            
            StringEntity entiry = new StringEntity(data, "UTF-8");
            httpPost.setEntity(entiry);  
            
            response = httpClient.execute(httpPost);  
            
            HttpEntity entity = response.getEntity();  
            result = EntityUtils.toString(entity, "UTF-8");  
            
        } catch (Exception e) {  
        	log.error(e.getMessage());
        } finally {  
            if (response != null) {  
                try {  
                    EntityUtils.consume(response.getEntity());  
                } catch (Exception e) {  
                	log.error(e.getMessage());
                }  
            }  
        }  
        return result;  
    }  
    
    /**
     * 
     * @Description: get方法获取字节流
     * @param url
     * @return
     * @throws Exception
     * @throws
     */
    public static ByteBuffer getImageFromUrl(String url) throws Exception {
    	CloseableHttpClient httpclient = HttpClients.createDefault();
    	ByteBuffer buffer = null;
        try {  
            HttpGet httpGet = new HttpGet(url);  
            CloseableHttpResponse response = httpclient.execute(httpGet);  
            try {  
                HttpEntity entity = response.getEntity();  
                InputStream inStream = entity.getContent();  
                buffer = ByteBuffer.allocate(inStream.available());  
                
                int b = inStream.read();  
                while (b != -1) {  
                	buffer.put((byte)b);
                    b = inStream.read(); 
                }  
                System.out.println("length="+buffer.array().length);
                EntityUtils.consume(entity);  
            } finally {  
                response.close();  
            }  
        }finally {  
            httpclient.close();  
        }  
        return buffer;
    }
    
    
    public static ByteBuffer download(String _url) throws Exception{

    	ByteBuffer buffer = null;
    	try { 
    	// 构造URL  
    	       URL url = new URL(_url);  
    	       // 打开连接  
    	       URLConnection con = url.openConnection();  
    	       //设置请求超时为5s  
    	       con.setConnectTimeout(5*1000);  
    	       // 输入流  
    	       InputStream inStream = con.getInputStream();  
    	       buffer = ByteBuffer.allocate(inStream.available()); 
    	       
    	       int b = inStream.read();  
               String tempStr = "";
               int ii = 0;
               while (b != -1) {  
               	buffer.put((byte)b);
                   b = inStream.read(); 
                   tempStr += b;
                   ii++;
               }  
               inStream.close();  
               System.out.println("tempStr="+ii);

    	} catch (IOException e) {

    	}
		return buffer;        
    	}


    /**
     * post请求提交数据, 例如xml, json
     * @param uri
     * @param data
     * @param miniType
     * @param charset
     * @param cookie
     * @param refer
     * @return
     */
	public static String post(String uri, String data, String miniType, String charset, String cookie, String refer) {
		CloseableHttpClient httpClient = HttpClients.createDefault();

		HttpPost httpPost = new HttpPost(uri);
		if (charset!=null&&!"".equals(charset)) {
			httpPost.setHeader("Content-Type", miniType);
		}

		if (data!=null&&!"".equals(data)) {
			StringEntity stringEntity = null;
			try {
				if (charset != null) {
					stringEntity = new StringEntity(data, charset);
				} else {
					stringEntity = new StringEntity(data);
				}
			} catch (Exception e) {
				log.error(e.getMessage(), e);;
				return "failure";
			}

			httpPost.setEntity(stringEntity);
		}
		if (cookie!=null&&!"".equals(cookie)) {
			httpPost.setHeader("Cookie", cookie);
		}
		if (refer!=null&&!"".equals(refer)) {
			httpPost.setHeader("Refer", refer);
		}

		CloseableHttpResponse httpResponse = null;
		HttpContext httContext = HttpClientContext.create();
		try {
			httpResponse = httpClient.execute(httpPost, httContext);
		} catch (Exception e) {
			log.error(e.getMessage(), e);;
			return "failure";
		}

		HttpEntity httpEntity = null;
		try {
			httpEntity = httpResponse.getEntity();
		} catch (Exception e) {
			log.error(e.getMessage(), e);;
			return "failure";
		}

		String response_body = null;
		try {
			response_body = EntityUtils.toString(httpEntity, "utf-8");
		} catch (Exception e) {
			log.error(e.getMessage(), e);;
			return "failure";
		}

		try {
			httpResponse.close();
		} catch (Exception e) {
			log.error(e.getMessage(), e);;
		}

		return response_body;
	}

}
