package org.dromara.settlement.common.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
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.conn.ConnectTimeoutException;
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.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.security.*;
import java.security.cert.CertificateException;


public class HttpUtil {

	/**
     * 微信退款
     * 发送xml请求到server端
     * @param url xml请求数据地址
     * @param xmlString 发送的xml数据流
     * @return null发送失败，否则返回响应内容
     * @throws KeyStoreException
     * @throws NoSuchAlgorithmException
     * @throws UnrecoverableKeyException
     * @throws KeyManagementException
     * @throws IOException
     * @throws CertificateException
     */
    public static String httpXMLRefundPost(String url,String xmlString,String matchid) throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException{

    	//指定读取证书格式为PKCS12
    	KeyStore keyStore = KeyStore.getInstance("PKCS12");
    	//读取本机存放的PKCS12证书文件
    	InputStream instream =  HttpUtil.class.getResourceAsStream("/config/apiclient_cert.p12");
    	try {
    	//指定PKCS12的密码(商户ID)
    	keyStore.load(instream,matchid.toCharArray());
    	} finally {
    	instream.close();
    	}
    	SSLContext sslcontext = SSLContexts.custom()
    	.loadKeyMaterial(keyStore, matchid.toCharArray()).build();
    	//指定TLS版本
    	SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
    	sslcontext,new String[] { "TLSv1" },null,
    	SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    	HttpPost httpPost = null;
        StringBuilder reponseXml = new StringBuilder();
    	try {
            // 定义HttpPost请求
            httpPost = new HttpPost(url);
            // 定义请求实体
            HttpEntity requestEntity = new StringEntity(xmlString, "UTF-8");
            httpPost.setEntity(requestEntity);

            // 定义HttpClient
          //设置httpclient的SSLSocketFactory
        	CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();



            // 以post方式发送Http请求
            HttpResponse httpResponse = httpclient.execute(httpPost);

            // 获取响应实体
            HttpEntity responsetEntity = httpResponse.getEntity();
            InputStream inputStream = responsetEntity.getContent();


            byte[] b = new byte[2048];
            int length = 0;
            while ((length = inputStream.read(b)) != -1) {
                reponseXml.append(new String(b, 0, length));
            }
            System.out.println(reponseXml);
        } catch (Exception e) {
            //释放请求的连接
            if(httpPost!=null){
                httpPost.abort();
            }

            if(SocketTimeoutException.class.isInstance(e)){
                throw new RuntimeException("Http请求响应超时",e);
            }
            else if(ConnectTimeoutException.class.isInstance(e)){
                throw new RuntimeException("Http请求连接超时", e);
            }
            else if(ConnectException.class.isInstance(e)){
                throw new RuntimeException("Http请求异常", e);
            }else{
                throw new RuntimeException("其他异常", e);
            }
        }

    	return reponseXml.toString();
    }


    /**
     * post请求（用于请求json格式的参数）
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, String params) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                return jsonString;
            }
            else{

            }
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * get请求（用于请求json格式的参数）
     * @param url
     * @param params
     * @return
     */
    public static String doGet(String url)
    {
    	CloseableHttpClient httpclient = HttpClients.createDefault();
    	HttpGet httpGet = new HttpGet(url);// 创建HttpGet
    	httpGet.setHeader("Accept", "application/json");
        httpGet.setHeader("Content-Type", "application/json");
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                return jsonString;
            }
        }
        catch(Exception e)
        {
        	e.printStackTrace();
        }
        finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
