package com.engine.tjyh.xc.util;

import com.alibaba.fastjson.JSONObject;
import com.weaver.file.Prop;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HttpRequestUtil extends BaseBean {
    private static HttpRequestUtil httpRequestUtil;
    private String charset = "utf-8";

    /**
     * constructor
     */
    private HttpRequestUtil() {
    }

    /**
     * 获取实例
     *
     * @return
     */
    public static HttpRequestUtil getInstance() {
        return new HttpRequestUtil();
    }

    /**
     * 获取HttpClient
     *
     * @return
     */
    public DefaultHttpClient getClient() {
        DefaultHttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
        //超时设置
        int timeOut = Util.getIntValue(60000);
        client.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, timeOut);

        client = HttpClientWrapper.wrapClient(client);      //先绕过证书，不验证证书
        
        proxyConfig(client);
        
        return client;
    }

    /**
     * 代理的设置
     *
     * @param client
     */
    private void proxyConfig(DefaultHttpClient client) {
        writeLog("================proxyConfig==================s");
        boolean isAgent = true;
        if (isAgent) {   //开启了代理
            String host =  Prop.getPropValue("tjyhxcjc","host");
            int port = Util.getIntValue(Prop.getPropValue("tjyhxcjc","port"));
            String userName = Prop.getPropValue("tjyhxcjc","userName");
            String password = Prop.getPropValue("tjyhxcjc","password");

            writeLog(host);
            writeLog(port);
            writeLog(userName);
            writeLog(password);

            client.getCredentialsProvider().setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(userName, password));

            HttpHost httpHost = new HttpHost(host, port);
            client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, httpHost);
        }
        writeLog("================proxyConfig==================e");
    }

    /**
     * post请求方式,json数据格式
     *
     * @param url
     * @param params
     * @return
     */
    public String doPostJson(String url, Map params) {
        String json = JSONObject.toJSONString(params);
        return doPostJson(url, json);
    }


    public String doPostJson(String url, String json) {
        String response = "";
        HttpClient client = getClient();
        HttpPost post = null;

        String exceptionmsg = "";

        String timeformat = "yyyy-MM-dd HH:mm:ss.SSS";
        String currentTime = TimeUtil.getFormartString(Calendar.getInstance(), timeformat);
//        if (!"".equals(url)) {
//            url = ctripConfig.correctUrl(url);
//        }
        try {
            post = new HttpPost(url);
            post.setHeader(HTTP.CONTENT_TYPE, "application/json");   //请求数据的格式为json
            post.setHeader(HTTP.CONN_DIRECTIVE, "Keep-Alive");  //长连接
            post.setHeader(HTTP.CONTENT_ENCODING, charset);
            post.setHeader("accept", "*/*");
            post.setHeader(HTTP.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(8000)
                    .setSocketTimeout(8000).setConnectTimeout(8000).build();
            post.setConfig(requestConfig);

            StringEntity entity = new StringEntity(json, charset);
            post.setEntity(entity);
            HttpResponse httpResponse = client.execute(post);

            int httpCode = httpResponse.getStatusLine().getStatusCode();
            if (httpCode == HttpStatus.SC_OK) {
                response = EntityUtils.toString(httpResponse.getEntity(), charset);
            } else {
                writeLog("WebUtil.doPostJson httpCode:" + httpCode);
            }
        } catch (UnsupportedEncodingException e) {
            writeLog("WebUtil.doPostJson catch a  UnsupportedEncodingException exception:" + e.getMessage());
            writeLog(e);
            exceptionmsg = "WebUtil.doPostJson catch a  UnsupportedEncodingException exception:" + e.getMessage();
        } catch (ClientProtocolException e) {
            writeLog("WebUtil.doPostJson catch a ClientProtocolException exception:" + e.getMessage());
            writeLog(e);
            exceptionmsg = "WebUtil.doPostJson catch a ClientProtocolException exception:" + e.getMessage();
        } catch (IOException e) {
            writeLog("WebUtil.doPostJson catch a  IOException exception:" + e.getMessage());
            writeLog(e);
            exceptionmsg = "WebUtil.doPostJson catch a  IOException exception:" + e.getMessage();
        } finally {
            if (post != null) {
                post.releaseConnection();
            }
        }

//        String sql = "insert into ctrip_allrequest_logs (requesturl,requestjson,responsejson,exceptionmsg,logtime) values (?, ?, ?, ?,?)";

//        ConnStatement connStatement = null;
//
//        try {
//            connStatement = new ConnStatement();
//            connStatement.setStatementSql(sql);
//            connStatement.setString(1, url);
//            connStatement.setString(2, json);
//            connStatement.setString(3, response);
//            connStatement.setString(4, exceptionmsg);
//            connStatement.setString(5, currentTime);
//            connStatement.executeUpdate();
//            connStatement.close();
//        } catch (SQLException e) {
//            writeLog("WebUtil.doPostJson catch a SQLException:" + e.getMessage());
//            writeLog(e);
//        } catch (Exception e) {
//            writeLog("WebUtil.doPostJson catch a Exception:" + e.getMessage());
//            writeLog(e);
//        } finally {
//            if (connStatement != null) {
//                connStatement.close();
//            }
//        }

        return response;
    }

    /**
     * post请求，form数据格式
     *
     * @param url
     * @param params
     * @return
     */
    public String doPostForm(String url, Map<String, String> params) {
        String response = "";
        HttpClient client = getClient();
        HttpPost post = null;

        post = new HttpPost(url);
        post.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
        post.setHeader(HTTP.CONN_DIRECTIVE, "Keep-Alive");  //长连接
        post.setHeader(HTTP.CONTENT_ENCODING, charset);

        String json = JSONObject.toJSONString(params);

        try {
            List<NameValuePair> pairList = new ArrayList<NameValuePair>();
            for (Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator(); iterator.hasNext(); ) {
                Map.Entry<String, String> entry = iterator.next();
                String key = entry.getKey();
                String value = entry.getValue();
                NameValuePair nameValuePair = new BasicNameValuePair(key, value);
                pairList.add(nameValuePair);
            }

            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairList, charset);
            post.setEntity(formEntity);
            HttpResponse httpResponse = client.execute(post);

            int httpCode = httpResponse.getStatusLine().getStatusCode();
            if (httpCode == HttpStatus.SC_OK) {
                response = EntityUtils.toString(httpResponse.getEntity(), charset);
            } else {
                writeLog("WebUtil.doPostForm httpCode:" + httpCode);
            }
        } catch (UnsupportedEncodingException e) {
            writeLog("WebUtil.doPostForm catch a  UnsupportedEncodingException exception:" + e.getMessage());
            writeLog(e);
        } catch (ClientProtocolException e) {
            writeLog("WebUtil.doPostForm catch a ClientProtocolException exception:" + e.getMessage());
            writeLog(e);
        } catch (IOException e) {
            writeLog("WebUtil.doPostForm catch a  IOException exception:" + e.getMessage());
            writeLog(e);
        } finally {
            if (post != null) {
                post.releaseConnection();
            }
        }
        return response;
    }


    /**
     * 将unicode编码的中文解码
     *
     * @param unicodeStr
     * @return
     */
    public String decode(String unicodeStr) {
        /**
         * unicode编码的正则表达式
         */
        Pattern reUnicode = Pattern.compile("\\\\u([0-9a-zA-Z]{4})");

        Matcher m = reUnicode.matcher(unicodeStr);
        StringBuffer sb = new StringBuffer(unicodeStr.length());
        while (m.find()) {
            m.appendReplacement(sb,
                    Character.toString((char) Integer.parseInt(m.group(1), 16)));
        }
        m.appendTail(sb);
        return sb.toString();
    }

    /**
     * 将请求中的中文unicode编码
     *
     * @param s
     * @return
     */
    public String encode(String s) {
        StringBuilder sb = new StringBuilder(s.length() * 3);
        for (char c : s.toCharArray()) {
            if (c < 256) {
                sb.append(c);
            } else {
                sb.append("\\u");
                sb.append(Character.forDigit((c >>> 12) & 0xf, 16));
                sb.append(Character.forDigit((c >>> 8) & 0xf, 16));
                sb.append(Character.forDigit((c >>> 4) & 0xf, 16));
                sb.append(Character.forDigit((c) & 0xf, 16));
            }
        }
        return sb.toString();
    }
}
