package com.hotent.portal.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.json.JSONObject;
import com.hotent.base.util.StringUtil;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.hotent.base.util.BeanUtils;
import com.hotent.base.util.JsonUtil;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.HttpEntity;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


/**
 * 封装一个http请求的工具类
 */
public class HttpClientUtil {
    
    public static ObjectNode executeRestfulApi(String restApi,JsonNode params) throws Exception{
    	ObjectMapper mapper = JsonUtil.getMapper();
    	ObjectNode responseMsg = mapper.createObjectNode();
    	try {
    		if(BeanUtils.isNotEmpty(params)){
    			postHttp(restApi,params);
    		}else{
    			responseMsg = getHttp(restApi);
    		}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return (ObjectNode) JsonUtil.toJsonNode(responseMsg);
    }
    
    /**
     * get方式
     * @param url
     * @return
     * @throws Exception 
     */
    public static ObjectNode getHttp(String url) throws Exception {
        String responseMsg = "";
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
        try {
            httpClient.executeMethod(getMethod);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream in = getMethod.getResponseBodyAsStream();
            int len = 0;
            byte[] buf = new byte[1024];
            while((len=in.read(buf))!=-1){
                out.write(buf, 0, len);
            }
            responseMsg = out.toString("UTF-8");
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放连接
            getMethod.releaseConnection();
        }
        return (ObjectNode)JsonUtil.toJsonNode(responseMsg);
    }

    /**
     * post方式
     * @param url
     * @param code
     * @param type
     * @return
     * @throws Exception 
     */
    public static JsonNode postHttp(String url,JsonNode params) throws Exception {
        String responseMsg = "";
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setContentCharset("GBK");
        PostMethod postMethod = new PostMethod(url);
        try {
        	if(BeanUtils.isNotEmpty(params)){
        		ObjectMapper mapper = JsonUtil.getMapper();
            	ObjectNode obj = mapper.createObjectNode();
        		for (Object object : params) {
        			JsonNode jsonObj = JsonUtil.toJsonNode(object);
        			obj.put(jsonObj.get("name").asText(), jsonObj.get("value").asText());
        			//postMethod.addParameter((String)jsonObj.get("name"),(String) jsonObj.get("value"));
        		}
        		postMethod.setRequestEntity(new StringRequestEntity(obj.toString(), "application/json", "UTF-8"));
        	}
            httpClient.executeMethod(postMethod);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream in = postMethod.getResponseBodyAsStream();
            int len = 0;
            byte[] buf = new byte[1024];
            while((len=in.read(buf))!=-1){
                out.write(buf, 0, len);
            }
            responseMsg = out.toString("UTF-8");
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();
        }
        
        return (JsonNode)JsonUtil.toJsonNode(responseMsg);
    }


    public static JSONObject useDingApiPost(String url,String params1,String token)throws Exception{
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        JSONObject jsonObject = new JSONObject();
        try {
            httpClient = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-Type","application/json;charset=UTF-8");
            post.setHeader("x-acs-dingtalk-access-token",token);
            List<NameValuePair> params=new ArrayList<>();
            System.out.println(params.toString());
            StringEntity se = new StringEntity(params1,"utf-8");
            post.setEntity(se);
            response = httpClient.execute(post);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                String result = EntityUtils.toString(responseEntity); // responseEntity只能取一次
                System.out.println(result);
                jsonObject.put("code", "200");
                jsonObject.put("msg","获取成功" );
                jsonObject.put("data",result);
                return jsonObject;
                //{"agentId":2976081667,"appKey":"dingmwv7h7yud2msjd6j","appSecret":"gBtwyWzqKVzQxVs9zGOACqnbmQVj0QmM1Zstp0j41BRXgZ5Y5qSxwNQJUdcwf2V2"}

            }
        } catch (Exception e) {
            e.printStackTrace();
            e.printStackTrace();
            String tmp = e.getMessage();
            jsonObject.put("code", "-1");
            jsonObject.put("tasked", "");
            jsonObject.put("msg", tmp.length()<=100? tmp: tmp.substring(0, 100));
            jsonObject.put("data", tmp.length()<=100? tmp: tmp.substring(0, 100));
            return jsonObject;
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    public static JSONObject useDingApiGet(String url,String params1,String token)throws Exception{
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        JSONObject jsonObject = new JSONObject();
        try {
            httpClient = HttpClientBuilder.create().build();
            HttpGet post = new HttpGet(url);
            post.setHeader("Content-Type","application/json;charset=UTF-8");
            post.setHeader("x-acs-dingtalk-access-token",token);
            response = httpClient.execute(post);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                String result = EntityUtils.toString(responseEntity); // responseEntity只能取一次
                System.out.println(result);
                jsonObject.put("code", "200");
                jsonObject.put("msg","获取成功" );
                jsonObject.put("data",result);
                return jsonObject;
            }
        } catch (Exception e) {
            e.printStackTrace();
            e.printStackTrace();
            String tmp = e.getMessage();
            jsonObject.put("code", "-1");
            jsonObject.put("tasked", "");
            jsonObject.put("msg", tmp.length()<=100? tmp: tmp.substring(0, 100));
            jsonObject.put("data", tmp.length()<=100? tmp: tmp.substring(0, 100));
            return jsonObject;
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

}
