package com.goafanti.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Set;

public class HttpUtils {

	/**
	 * 发送https请求
	 *
	 * @param url           url
	 * @param requestMethod 请求方式
	 * @param param         请求参数
	 * @return 返回值
	 */
	public String sendHttpsRequest(String url, String requestMethod, Map<String,Object> param) {
		StringBuilder result = new StringBuilder();
		try {
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, new TrustManager[]{
					new X509TrustManager() {
						@Override
						public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
						}

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

						@Override
						public X509Certificate[] getAcceptedIssuers() {
							return new X509Certificate[0];
						}
					}
			}, new SecureRandom());
			URL console = new URL(url);
			HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
			// GET/POST
			conn.setRequestMethod(requestMethod);
			conn.setRequestProperty("Content-Type", "application/json");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 设置证书忽略相关操作
			conn.setSSLSocketFactory(sc.getSocketFactory());
			if (null != param) {
				OutputStream outputStream = conn.getOutputStream();
				// 注意编码格式
				outputStream.write(JSON.toJSONString(param).getBytes(StandardCharsets.UTF_8));
				outputStream.close();
			}


			conn.setHostnameVerifier((s, sslSession) -> true);
			conn.connect();
			InputStream is = conn.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is,StandardCharsets.UTF_8));
			String ret = "";
			while ((ret = br.readLine()) != null) {
				if (!ret.trim().isEmpty()) {
					result.append(ret);
				}
			}
			conn.disconnect();
			br.close();
		} catch (NoSuchAlgorithmException | KeyManagementException | IOException e) {
			e.printStackTrace();
		}
        return result.toString();
	}

	// http协议访问方法
//	public String sendHttpRequest(String url, String requestMethod, String param) {
//		StringBuilder result = new StringBuilder();
//		try {
//			URL console = new URL(url);
//			HttpURLConnection conn = (HttpURLConnection) console.openConnection();
//			// GET/POST
//			conn.setRequestMethod(requestMethod);
//			conn.setRequestProperty("Content-Type", "application/json");
//			conn.setDoOutput(true);
//			conn.setDoInput(true);
//			if (null != param) {
//				OutputStream outputStream = conn.getOutputStream();
//				// 注意编码格式
//				outputStream.write(param.getBytes("UTF-8"));
//				outputStream.close();
//			}
//
//			conn.connect();
//			InputStream is = conn.getInputStream();
//			BufferedReader br = new BufferedReader(new InputStreamReader(is));
//			String ret = "";
//			while ((ret = br.readLine()) != null) {
//				if (ret != null && !ret.trim().equals("")) {
//					result.append(new String(ret.getBytes("utf-8"), "utf-8"));
//				}
//			}
//			conn.disconnect();
//			br.close();
//		} catch (IOException ioException) {
//			ioException.printStackTrace();
//		}
//		return result.toString();
//	}



	 public static JSONObject httpGet(String url) {
			JSONObject jsonResult = null;
			try {
			HttpClient client = HttpClientBuilder.create().build();//获取DefaultHttpClient请求
			HttpGet request = new HttpGet(url);
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			String strResult = EntityUtils.toString(response.getEntity(),"UTF-8");//此处设定编码格式
			jsonResult = JSON.parseObject(strResult);
			} else {
			LoggerUtils.error(HttpUtils.class,"HttpStatus异常");
			}
			} catch (IOException e) {
			e.printStackTrace();
			}
			return jsonResult;
		}


	public static JSONObject httpPost(String url,Map<String, Object>map){
		return httpPost(url,map,0);
	}
	public static JSONObject httpPostBody(String url,Map<String, Object>map){
		return httpPost(url,map,1);
	}
		 /**
		  *
		  * @param url 地址
		  * @param map 参数
		  * @param type  0 json  1body
		  * @return
		  */
		public static JSONObject httpPost(String url,Map<String, Object>map,Integer type) {
			HttpClient httpClient = HttpClientBuilder.create().build();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setHeader("Accept", "application/json");
			if (type==0){
				httpPost.addHeader("Content-type", "application/json");
				httpPost.setEntity(new StringEntity(JSON.toJSONString(map), StandardCharsets.UTF_8));
			}else{
				httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
				httpPost.setEntity(new StringEntity(ParamMap(map), StandardCharsets.UTF_8));
			}

			HttpResponse response = null;
			try {
				response = httpClient.execute(httpPost);
				if (null == response || response.getStatusLine() == null) {
					throw new Exception("Post Request For Url[{}] is not ok. Response is null");
				} else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
					throw new Exception("Post Request For Url[{}] is not ok. Response Status Code is {"+response.getStatusLine().getStatusCode()+"}");
				}
			} catch (UnknownHostException uhe) {
				LoggerUtils.error(HttpUtils.class,uhe.getMessage());
			} catch (Exception e) {
				e.printStackTrace();
			}
			String resultString=null;
			try {
                if (response != null) {
                    resultString = EntityUtils.toString(response.getEntity());
                }
            } catch (ParseException | IOException e) {
				e.printStackTrace();
			}
            return JSONObject.parseObject(resultString);
			}

	private static String ParamMap(Map<String, Object> map) {
		StringBuilder str =new StringBuilder();
		Set<String> strings = map.keySet();
		for (String string : strings) {
            str.append(string).append("=").append(map.get(string)).append("&");
        }
        return str.substring(0, str.length() - 1);
	}



}
