package com.zfire.jiasm.syncdata.utils;


import com.alibaba.fastjson.JSONObject;
import com.zfire.jiasm.syncdata.data.Token;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Set;

@Slf4j
public class HttpUtil {

	public static JSONObject httpRequestGetPgid(String requestUrl, String requestMethod,
												Token sign, String downloadBatchNo, String outputStr) throws Exception{
		JSONObject jsonresult = null;
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection httpUrlConn = null;
		try {
			trustAllHttpsCertificates();
			HostnameVerifier hv = new HostnameVerifier() {
				public boolean verify(String urlHostName, SSLSession session) {
					return true;
				}
			};
			HttpsURLConnection.setDefaultHostnameVerifier(hv);

			URL url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			httpUrlConn.setConnectTimeout(30000);
			httpUrlConn.setReadTimeout(30000);
			httpUrlConn.setRequestProperty("Authorization", "Bearer "+sign.getAccessToken());
			httpUrlConn.setRequestProperty("Accept", "*/*");
			httpUrlConn.setRequestProperty("Content-Type", "application/json");
			httpUrlConn.setRequestMethod(requestMethod);
			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// log.info("url[" + url + "],downloadBatchNo["+downloadBatchNo+"],send[" + outputStr + "]");

			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			InputStream inputStream;
			if (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				inputStream = httpUrlConn.getInputStream();
			} else {
				inputStream = httpUrlConn.getErrorStream();
			}

			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			httpUrlConn.disconnect();
			String result = buffer.toString();
			// log.info("downloadBatchNo["+downloadBatchNo+"],receive[" + result + "],url[" + url + "],send[" + outputStr + "]");
			jsonresult = JSONObject.parseObject(result);
		} catch (ConnectException ce) {
			log.error("发生错误", ce);
			throw ce;
		} catch (Exception e) {
			log.error("发生错误", e);
			throw e;
		} finally {
			try {
				httpUrlConn.disconnect();
			} catch (Exception e) {
				log.error("发生错误", e);
			}
		}
		return jsonresult;
	}

	public static JSONObject httpRequestGetPgidGD(String requestUrl, String requestMethod,String outputStr) throws Exception{
		JSONObject jsonresult = null;
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection httpUrlConn = null;
		try {
			trustAllHttpsCertificates();
			HostnameVerifier hv = new HostnameVerifier() {
				public boolean verify(String urlHostName, SSLSession session) {
					return true;
				}
			};
			HttpsURLConnection.setDefaultHostnameVerifier(hv);

			URL url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			httpUrlConn.setConnectTimeout(30000);
			httpUrlConn.setReadTimeout(30000);
			httpUrlConn.setRequestProperty("Authorization", "Bearer 1234");
			httpUrlConn.setRequestProperty("Accept", "*/*");
			httpUrlConn.setRequestProperty("Content-Type", "application/json");
			httpUrlConn.setRequestMethod(requestMethod);
			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			InputStream inputStream;
			if (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				inputStream = httpUrlConn.getInputStream();
			} else {
				inputStream = httpUrlConn.getErrorStream();
			}

			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			httpUrlConn.disconnect();
			String result = buffer.toString();
			jsonresult = JSONObject.parseObject(result);
		} catch (ConnectException ce) {
			log.error("发生错误", ce);
			throw ce;
		} catch (Exception e) {
			log.error("发生错误", e);
			throw e;
		} finally {
			try {
				httpUrlConn.disconnect();
			} catch (Exception e) {
				log.error("发生错误", e);
			}
		}
		return jsonresult;
	}


	public static JSONObject httpRequestGetPgidt(String requestUrl, String requestMethod,
												 String accessToken, String downloadBatchNo, String outputStr) throws Exception{
		JSONObject jsonresult = null;
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection httpUrlConn = null;
		try {
			trustAllHttpsCertificates();
			HostnameVerifier hv = new HostnameVerifier() {
				public boolean verify(String urlHostName, SSLSession session) {
					return true;
				}
			};
			HttpsURLConnection.setDefaultHostnameVerifier(hv);

			URL url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			httpUrlConn.setConnectTimeout(30000);
			httpUrlConn.setReadTimeout(30000);
			httpUrlConn.setRequestProperty("Authorization", "Bearer "+accessToken);
			httpUrlConn.setRequestProperty("Accept", "*/*");
			httpUrlConn.setRequestProperty("Content-Type", "application/json");
			httpUrlConn.setRequestMethod(requestMethod);
			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// log.info("url[" + url + "],downloadBatchNo["+downloadBatchNo+"],send[" + outputStr + "]");

			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			InputStream inputStream;
			if (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				inputStream = httpUrlConn.getInputStream();
			} else {
				inputStream = httpUrlConn.getErrorStream();
			}

			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			httpUrlConn.disconnect();
			String result = buffer.toString();
			// log.info("downloadBatchNo["+downloadBatchNo+"],receive[" + result + "],url[" + url + "],send[" + outputStr + "]");
			jsonresult = JSONObject.parseObject(result);
		} catch (ConnectException ce) {
			log.error("发生错误", ce);
			throw ce;
		} catch (Exception e) {
			log.error("发生错误", e);
			throw e;
		} finally {
			try {
				httpUrlConn.disconnect();
			} catch (Exception e) {
				log.error("发生错误", e);
			}
		}
		return jsonresult;
	}

	public static JSONResult httpRequestWithToken(String requestUrl, String requestMethod, String outputStr,
												  Token sign) throws Exception{
		JSONResult jsonresult = null;
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection httpUrlConn = null;
		try {

			trustAllHttpsCertificates();
			HostnameVerifier hv = new HostnameVerifier() {
				public boolean verify(String urlHostName, SSLSession session) {
					return true;
				}
			};
			HttpsURLConnection.setDefaultHostnameVerifier(hv);

			URL url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			httpUrlConn.setConnectTimeout(30000);
			httpUrlConn.setReadTimeout(30000);
			httpUrlConn.setRequestProperty("Authorization", "Bearer "+sign.getAccessToken());
			httpUrlConn.setRequestProperty("Accept", "*/*");
			httpUrlConn.setRequestProperty("Content-Type", "application/json");
			httpUrlConn.setRequestMethod(requestMethod);
			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			log.info("url[{}],send[{}]",url,outputStr);

			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			InputStream inputStream;
			if (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				inputStream = httpUrlConn.getInputStream();
			} else {
				inputStream = httpUrlConn.getErrorStream();
			}

			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			String result = buffer.toString();
			log.info("receive[{}],send[{}]", result,outputStr);
			jsonresult = JSONObject.parseObject(result, JSONResult.class);
		} catch (ConnectException ce) {
			log.error("发生错误", ce);
			throw ce;
		} catch (Exception e) {
			log.error("发生错误", e);
			throw e;
		} finally {
			try {
				httpUrlConn.disconnect();
			} catch (Exception e) {
				log.error("发生错误", e);
			}
		}
		return jsonresult;
	}


	public static JSONObject httpRequestWithGD(String requestUrl, String requestMethod, String outputStr) throws Exception{
		JSONObject jsonresult = null;
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection httpUrlConn = null;
		try {

			trustAllHttpsCertificates();
			HostnameVerifier hv = new HostnameVerifier() {
				public boolean verify(String urlHostName, SSLSession session) {
					return true;
				}
			};
			HttpsURLConnection.setDefaultHostnameVerifier(hv);

			URL url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			httpUrlConn.setConnectTimeout(30000);
			httpUrlConn.setReadTimeout(30000);
			httpUrlConn.setRequestProperty("Authorization", "Bearer 1234");
			httpUrlConn.setRequestProperty("Accept", "*/*");
			httpUrlConn.setRequestProperty("Content-Type", "application/json");
			httpUrlConn.setRequestMethod(requestMethod);
			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			InputStream inputStream;
			if (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				inputStream = httpUrlConn.getInputStream();
			} else {
				inputStream = httpUrlConn.getErrorStream();
			}

			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			String result = buffer.toString();
			jsonresult = JSONObject.parseObject(result);
		} catch (ConnectException ce) {
			log.error("发生错误", ce);
			throw ce;
		} catch (Exception e) {
			log.error("发生错误", e);
			throw e;
		} finally {
			try {
				httpUrlConn.disconnect();
			} catch (Exception e) {
				log.error("发生错误", e);
			}
		}
		return jsonresult;
	}

	public static JSONResult httpRequestWithTokenT(String requestUrl, String requestMethod, String outputStr,
												   String accessToken) throws Exception{
		JSONResult jsonresult = null;
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection httpUrlConn = null;
		try {

			trustAllHttpsCertificates();
			HostnameVerifier hv = new HostnameVerifier() {
				public boolean verify(String urlHostName, SSLSession session) {
					return true;
				}
			};
			HttpsURLConnection.setDefaultHostnameVerifier(hv);

			URL url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			httpUrlConn.setConnectTimeout(30000);
			httpUrlConn.setReadTimeout(30000);
			httpUrlConn.setRequestProperty("Authorization", "Bearer "+accessToken);
			httpUrlConn.setRequestProperty("Accept", "*/*");
			httpUrlConn.setRequestProperty("Content-Type", "application/json");
			httpUrlConn.setRequestMethod(requestMethod);
			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// log.debug("url[" + url + "],send[" + outputStr + "]");

			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			InputStream inputStream;
			if (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				inputStream = httpUrlConn.getInputStream();
			} else {
				inputStream = httpUrlConn.getErrorStream();
			}

			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			String result = buffer.toString();
			// log.debug("receive[" + result + "],url[" + url + "],send[" + outputStr + "]");
			jsonresult = JSONObject.parseObject(result, JSONResult.class);
		} catch (ConnectException ce) {
			log.error("发生错误", ce);
			throw ce;
		} catch (Exception e) {
			log.error("发生错误", e);
			throw e;
		} finally {
			try {
				httpUrlConn.disconnect();
			} catch (Exception e) {
				log.error("发生错误", e);
			}
		}
		return jsonresult;
	}

	private static String toParamString(Map<String, String> paramMap) {
		StringBuffer sb = new StringBuffer();
		Set<String> set = paramMap.keySet();
		for (String key : set) {
			if (sb.length() > 0) {
				sb.append("&");
			}
			sb.append(key + "=" + paramMap.get(key));
		}
		return sb.toString();
	}

	public static void trustAllHttpsCertificates() throws Exception {
		javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
		javax.net.ssl.TrustManager tm = new miTM();
		trustAllCerts[0] = tm;
		javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, null);
		javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
	}

	public static JSONObject httpRequest(String requestUrl, String requestMethod, Map<String, String> paramMap,
										 String contentType) throws Exception {
		JSONObject jsonresult = null;
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection httpUrlConn = null;
		try {

			trustAllHttpsCertificates();
			HostnameVerifier hv = new HostnameVerifier() {
				public boolean verify(String urlHostName, SSLSession session) {
					return true;
				}
			};
			HttpsURLConnection.setDefaultHostnameVerifier(hv);

			URL url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			httpUrlConn.setConnectTimeout(30000);
			httpUrlConn.setReadTimeout(30000);
			httpUrlConn.setRequestProperty("Accept", contentType);
			httpUrlConn.setRequestProperty("Content-Type", contentType);
			httpUrlConn.setRequestMethod(requestMethod);
			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			String outputStr = toParamString(paramMap);

			log.debug("url[" + url + "],send[" + outputStr + "]");

			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			InputStream inputStream;
			if (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				inputStream = httpUrlConn.getInputStream();
			} else {
				inputStream = httpUrlConn.getErrorStream();
			}

			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			String result = buffer.toString();
			log.debug("receive[" + result + "],url[" + url + "],send[" + outputStr + "]");

			jsonresult = JSONObject.parseObject(result);

		} catch (ConnectException ce) {
			log.error("发生错误", ce);
			throw ce;
		} catch (Exception e) {
			log.error("发生错误", e);
			throw e;
		} finally {
			try {
				httpUrlConn.disconnect();
			} catch (Exception e) {
				log.error("发生错误", e);
			}
		}
		return jsonresult;
	}

	static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return null;
		}

		public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
			return true;
		}

		public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
			return true;
		}

		public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
				throws java.security.cert.CertificateException {
			return;
		}

		public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
				throws java.security.cert.CertificateException {
			return;
		}
	}

	public static String httpRequestPostJiasm(String requestUrl, String requestMethod,String token, String outputStr) throws Exception{
		String result ="";
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection httpUrlConn = null;
		try {
			trustAllHttpsCertificates();
			HostnameVerifier hv = new HostnameVerifier() {
				public boolean verify(String urlHostName, SSLSession session) {
					return true;
				}
			};
			HttpsURLConnection.setDefaultHostnameVerifier(hv);

			URL url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			httpUrlConn.setConnectTimeout(60000);
			httpUrlConn.setReadTimeout(60000);
			httpUrlConn.setRequestProperty("x-token", token);
			httpUrlConn.setRequestProperty("Accept", "*/*");
			httpUrlConn.setRequestProperty("Content-Type", "application/json");
			httpUrlConn.setRequestMethod(requestMethod);

			// log.info("url[" + url + "],send[" + outputStr + "]");

			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			InputStream inputStream;
			if (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				inputStream = httpUrlConn.getInputStream();
			} else {
				inputStream = httpUrlConn.getErrorStream();
			}

			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			httpUrlConn.disconnect();
			result = buffer.toString();
			log.info("receive[" + result + "],url[" + url + "],send[" + outputStr + "]");
		} catch (ConnectException ce) {
			log.error("发生错误", ce);
			throw ce;
		} catch (Exception e) {
			log.error("发生错误", e);
			throw e;
		} finally {
			try {
				httpUrlConn.disconnect();
			} catch (Exception e) {
				log.error("发生错误", e);
			}
		}
		return result;
	}

}
