package com.crunii.micro.service.sysmgr.utils;

import com.alibaba.druid.support.json.JSONUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;


public class HttpClientUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public static String doPost(String url, String data) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            // 设置参数
            // 构建消息实体
            StringEntity entity = new StringEntity(data, Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            httpPost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                }
            }
        } catch (Exception ex) {
            logger.error("post请求提交失败:" + url + data);
        }
        return result;
    }

    public static String doPost(String url) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(url);

            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                }
            }
        } catch (Exception ex) {
            logger.error("post请求提交失败:" + url);
        }
        return result;
    }

    public static String doPost(String url, Map<String, Object> map) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json");
            //设置请求参数体Json字串
            StringEntity stringEntity = new StringEntity(JSONUtils.toJSONString(map), "UTF-8");
            httpPost.setEntity(stringEntity);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
//            logger.error("post请求提交失败:" + url);
        }
        return result;
    }

    public static String httpGet(String url) {
        String result = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();

            // 发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);

            /** 请求发送成功，并得到响应 **/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /** 读取服务器返回过来的字符串数据 **/
                result = EntityUtils.toString(response.getEntity());
            } else {
                logger.error("get请求提交失败:" + url);
            }
        } catch (Exception e) {
            logger.error("get请求提交失败:" + url + e);

        }

        return result;
    }

    /**
     * 发送post请求
     *
     * @param url 地址
     * @return result
     */
    public static String doPostJson(String url, String data) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            // 如果需要忽略掉HTTPS的SSL证书校验则使用此类
            httpClient = new VerifyIgnoreClient();

            httpPost = new HttpPost(url);
            // 设置参数
            // 构建消息实体
            StringEntity entity = new StringEntity(data, Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            //请求超时
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000 * 20);
            //读取超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000 * 20);
            //执行请求
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity resEntity = response.getEntity();
                    if (resEntity != null) {
                        result = EntityUtils.toString(resEntity, "UTF-8");
                    }
                } else {
                    logger.error("Response statusCode is " + response.getStatusLine().getStatusCode());
                }

            } else {
                logger.error("Response is null!" + url);
            }
        } catch (Exception ex) {
            logger.error("post请求提交失败:{}", ex);
        } finally {
            if (httpClient != null) {
                ((DefaultHttpClient) httpClient).close();
            }
        }
        return result;
    }

    /**
     * 内部类，用于调用忽略SSL证书的HTTPS接口
     */
    static class VerifyIgnoreClient extends DefaultHttpClient {
        public VerifyIgnoreClient() throws Exception {
            super();
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain,
                                               String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain,
                                               String authType) throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = this.getConnectionManager();
            SchemeRegistry sr = ccm.getSchemeRegistry();
            sr.register(new Scheme("https", 443, ssf));
        }

    }

    public static String getCheckSum(String nonce, String appSecret, String curTime) {
        return SHA1(nonce + appSecret + curTime);
    }

    private static String SHA1(String decript) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte[] messageDigest = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            logger.error("执行SHA1出错" + e);
        }
        return "";
    }

    /**
     * 生成指定长度的由字母和数字组成的随机字符串
     *
     * @param length 字符串长度
     * @return
     */
    public static String getStringRandom(int length) {
        StringBuffer val = new StringBuffer();
        SecureRandom random = new SecureRandom();
        //参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                val.append((char) (random.nextInt(26) + 97));
            } else {
                val.append(random.nextInt(10));
            }
        }
        return val.toString();
    }

    /**
     * 获取微信小程序二维码
     *
     * @param requestUrl
     * @param fileName
     */
    public static void post(String requestUrl, String paramJson, String fileName) {
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url
                    .openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            printWriter.write(paramJson);
            // flush输出流的缓冲
            printWriter.flush();
            // 开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            OutputStream os = new FileOutputStream(new File(fileName));
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
            bis.close();
        } catch (ConnectException ce) {
            ce.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) {
////        long curTime = System.currentTimeMillis();
////        System.out.println(curTime);
////        String checkSum = getCheckSum("123456", "c48faffaedf6d4cae01c6a21c11457fc118e32b0", curTime + "");
////        System.out.println(checkSum);
//
//        uploadWxCode("https://api.weixin.qq.com/cgi-bin/token", "https://api.weixin.qq.com/wxa/getwxacodeunlimit", "wxbb17703c72bf1525", "03bac4ee0b213c68e899cedd77f12a23", "D:\\tmpfile\\", "12536253");
//        System.out.println("SUCCESS");
//
//    }
}
