package com.neusoft.smart.pos.payment.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.SecureRandom;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class HttpClientUtils {

    public static final String CONTENT_TYPE_XML = "application/xml";
    public static final String DEFAULT_CONTENT_TYPE = "application/json";
    public static final String DEFAULT_CHARSET = "UTF-8";

    public static String postXMLData(String url, String data){
        return postData(url,data,CONTENT_TYPE_XML);
    }

    public static String postData(String url, String data){
        return postData(url,data,DEFAULT_CONTENT_TYPE);
    }

    /**
     * 发送xml格式数据请求方法
     * @param url
     * @param data
     * @return
     */
    public static String postData(String url, String data,String contentType){
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        StringEntity requestEntity = new StringEntity(data, DEFAULT_CHARSET);
        httpPost.addHeader("Content-Type", contentType);
        httpPost.setEntity(requestEntity);
        String result = null;
        try {
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            result = EntityUtils.toString(responseEntity, DEFAULT_CHARSET);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 发送xml格式数据还header头的请求方法
     * @param url
     * @param data
     * @param header
     * @return
     */
    public static String postDataWithHeader(String url, String data,String header){
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        StringEntity requestEntity = new StringEntity(data, DEFAULT_CHARSET);
        httpPost.addHeader("Content-Type", DEFAULT_CONTENT_TYPE);
        httpPost.addHeader("Authorization", header);
        httpPost.setEntity(requestEntity);
        String result = null;
        try {
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            result = EntityUtils.toString(responseEntity, DEFAULT_CHARSET);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送xml格式数据请求方法
     * @param url
     * @param data
     * @return
     */
    public static String postXmlDataWithCert(String url, String data,String password,InputStream certInstream){
        try {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            keyStore.load(certInstream,password.toCharArray());

            // 实例化密钥库 & 初始化密钥工厂
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(keyStore, password.toCharArray());

            // 创建 SSLContext
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());

            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                    sslContext,
                    new String[]{"TLSv1"},
                    null,
                    new DefaultHostnameVerifier());
            CloseableHttpClient httpclient = HttpClients.custom()
                    .setSSLSocketFactory(sslConnectionSocketFactory).build();

            HttpPost httpPost = new HttpPost(url);
            StringEntity requestEntity = new StringEntity(data, DEFAULT_CHARSET);
            httpPost.addHeader("Content-Type", CONTENT_TYPE_XML);
            httpPost.setEntity(requestEntity);
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            String result = EntityUtils.toString(responseEntity, DEFAULT_CHARSET);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据request对象获取数据信息
     * @param request
     * @return
     */
    public static String getStringDataFromRequest(HttpServletRequest request){
        String dataString = null;
        try {
            BufferedReader reader = request.getReader();
            String line;
            StringBuffer inputString = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            dataString = inputString.toString();
            request.getReader().close();
        } catch (IOException e) {
            e.printStackTrace();
            return dataString;
        }
        return dataString;
    }

    /**
     * 获取请求参数中所有的信息
     *
     * @param request
     * @return
     */
    public static Map<String, String> getUnionPayDataFromRequest(final HttpServletRequest request) {
        Map<String, String> res = new HashMap<String, String>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                res.put(en, value);
                //在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
                //System.out.println("ServletUtil类247行  temp数据的键=="+en+"     值==="+value);
                if (null == res.get(en) || "".equals(res.get(en))) {
                    res.remove(en);
                }
            }
        }
        return res;
    }
}
