package com.weaver.seconddev.interfaces.htjt.util;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.axis.encoding.Base64;
import javax.net.ssl.*;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.lang.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.weaver.verupgrade.general.BaseBean;

public class WebApi {

	private static final org.slf4j.Logger logger_728f7230 = LoggerFactory.getLogger(WebApi.class);

	public static String postConnection(String url, String param, String type) throws Exception {
		PrintWriter printWriter = null;
		BufferedReader bufferedReader = null;
		HttpURLConnection httpURLConnection = null;
		StringBuffer responseResult = new StringBuffer();
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			httpURLConnection = (HttpURLConnection) realUrl.openConnection();
			httpURLConnection.setConnectTimeout(30000);
			httpURLConnection.setReadTimeout(30000);
			// 设置通用的请求属性
			httpURLConnection.setRequestProperty("accept", "*/*");
			httpURLConnection.setRequestProperty("connection", "Keep-Alive");
			httpURLConnection.setRequestProperty("Content-Length", String.valueOf(param.length()));
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			httpURLConnection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
			// httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setRequestMethod(type);
			// 获取URLConnection对象对应的输出流
			// printWriter = new PrintWriter(httpURLConnection.getOutputStream());
			if ("POST".equals(type)) {
				DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
				out.write(param.toString().getBytes("UTF-8"));
				// 发送请求参数
				// printWriter.write(new String(param.toString().getBytes(), "UTF-8"));
				// flush输出流的缓冲
				out.flush();
				out.close();
			}
			// 根据ResponseCode判断连接是否成功
			int responseCode = httpURLConnection.getResponseCode();
			// System.out.println("responseCode:"+responseCode);
			if (responseCode == httpURLConnection.HTTP_OK) {
				// 定义BufferedReader输入流来读取URL的ResponseData
				bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
				String line;
				while ((line = bufferedReader.readLine()) != null) {
					responseResult.append(line);
				}
				return responseResult.toString();
			} else {
				if (httpURLConnection != null && httpURLConnection.getErrorStream() != null) {
					bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream(), "UTF-8"));
					String line;
					while ((line = bufferedReader.readLine()) != null) {
						responseResult.append(line);
					}
					logger_728f7230.error(String.valueOf("apierror:" + responseResult.toString()));
				}
			}
			return null;
		} catch (ConnectException e) {
			throw new Exception(e);
		} catch (MalformedURLException e) {
			throw new Exception(e);
		} catch (IOException e) {
			throw new Exception(e);
		} catch (Exception e) {
			throw new Exception(e);
		} finally {
			httpURLConnection.disconnect();
			try {
				if (printWriter != null) {
					printWriter.close();
				}
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

	public static String postConnectionFormData(String url, String type, Map<String, String> datamap) throws Exception {
		OkHttpClient client = new OkHttpClient().newBuilder().build();
		MediaType mediaType = MediaType.parse("text/plain");
		MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
		Iterator it = datamap.keySet().iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			String value = datamap.get(key);
			builder.addFormDataPart(key, value);
		}
		RequestBody body = builder.build();
		Request request = new Request.Builder().url(url).method(type, body).build();
		try {
			Response response = client.newCall(request).execute();
			String result = response.body().string();
			return result;
		} catch (IOException e) {
			logger_728f7230.error(String.valueOf("apierror:" + e.getMessage()));
			logger_728f7230.error(String.valueOf(e));
		}
		return "";
	}

	public static String postConnectionSSL(String url, String param, String type) throws Exception {
		PrintWriter printWriter = null;
		BufferedReader bufferedReader = null;
		HttpsURLConnection httpURLConnection = null;
		StringBuffer responseResult = new StringBuffer();
		try {
			HostnameVerifier hv = new HostnameVerifier() {

				@Override
				public boolean verify(String urlHostName, SSLSession session) {
					return true;
				}
			};
			TrustManager[] trustAllCerts = { new TrustAllTrustManager() };
			SSLContext sc = SSLContext.getInstance("SSL");
			SSLSessionContext sslsc = sc.getServerSessionContext();
			sslsc.setSessionTimeout(0);
			sc.init(null, trustAllCerts, null);
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
			URL realUrl = new URL(url);
			String soapActionString = "PostMidStoreOut";
			// 激活主机认证
			HttpsURLConnection.setDefaultHostnameVerifier(hv);
			// 打开和URL之间的连接
			httpURLConnection = (HttpsURLConnection) realUrl.openConnection();
			httpURLConnection.setConnectTimeout(30000);
			httpURLConnection.setReadTimeout(30000);
			// 设置通用的请求属性
			httpURLConnection.setRequestProperty("accept", "*/*");
			httpURLConnection.setRequestProperty("connection", "Keep-Alive");
			httpURLConnection.setRequestProperty("Content-Length", String.valueOf(param.length()));
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			httpURLConnection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
			// httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setRequestMethod(type);
			// 获取URLConnection对象对应的输出流
			// printWriter = new PrintWriter(httpURLConnection.getOutputStream());
			if ("POST".equals(type)) {
				DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
				out.write(param.toString().getBytes("UTF-8"));
				// 发送请求参数
				// printWriter.write(new String(param.toString().getBytes(), "UTF-8"));
				// flush输出流的缓冲
				out.flush();
				out.close();
			}
			// 根据ResponseCode判断连接是否成功
			int responseCode = httpURLConnection.getResponseCode();
			// System.out.println("responseCode:"+responseCode);
			if (responseCode == httpURLConnection.HTTP_OK) {
				// 定义BufferedReader输入流来读取URL的ResponseData
				bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
				String line;
				while ((line = bufferedReader.readLine()) != null) {
					responseResult.append(line);
				}
				return responseResult.toString();
			} else {
				if (httpURLConnection != null && httpURLConnection.getErrorStream() != null) {
					bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream(), "UTF-8"));
					String line;
					while ((line = bufferedReader.readLine()) != null) {
						responseResult.append(line);
					}
					logger_728f7230.error(String.valueOf("apierror:" + responseResult.toString()));
				}
			}
			return null;
		} catch (ConnectException e) {
			throw new Exception(e);
		} catch (MalformedURLException e) {
			throw new Exception(e);
		} catch (IOException e) {
			throw new Exception(e);
		} catch (Exception e) {
			throw new Exception(e);
		} finally {
			httpURLConnection.disconnect();
			try {
				if (printWriter != null) {
					printWriter.close();
				}
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

	public static String postConnectionByBasicAuth(String url, String param, String type, String username, String password) throws Exception {
		PrintWriter printWriter = null;
		BufferedReader bufferedReader = null;
		HttpURLConnection httpURLConnection = null;
		StringBuffer responseResult = new StringBuffer();
		String token = Base64.encode((username + ":" + password).getBytes());
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			httpURLConnection = (HttpURLConnection) realUrl.openConnection();
			httpURLConnection.setConnectTimeout(30000);
			httpURLConnection.setReadTimeout(30000);
			// 设置通用的请求属性
			httpURLConnection.setRequestProperty("Authorization", "Basic " + token);
			httpURLConnection.setRequestProperty("accept", "*/*");
			httpURLConnection.setRequestProperty("connection", "Keep-Alive");
			httpURLConnection.setRequestProperty("Content-Length", String.valueOf(param.length()));
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			httpURLConnection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
			// 发送POST请求必须设置如下两行
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setRequestMethod(type);
			// 获取URLConnection对象对应的输出流
			// printWriter = new PrintWriter(httpURLConnection.getOutputStream());
			if ("POST".equals(type)) {
				DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
				out.write(param.toString().getBytes("UTF-8"));
				// 发送请求参数
				// printWriter.write(new String(param.toString().getBytes(), "UTF-8"));
				// flush输出流的缓冲
				out.flush();
				out.close();
			}
			// 根据ResponseCode判断连接是否成功
			int responseCode = httpURLConnection.getResponseCode();
			// System.out.println("responseCode:"+responseCode);
			if (responseCode == httpURLConnection.HTTP_OK) {
				// 定义BufferedReader输入流来读取URL的ResponseData
				bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
				String line;
				while ((line = bufferedReader.readLine()) != null) {
					responseResult.append(line);
				}
				return responseResult.toString();
			} else {
				if (httpURLConnection != null && httpURLConnection.getErrorStream() != null) {
					bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream(), "UTF-8"));
					String line;
					while ((line = bufferedReader.readLine()) != null) {
						responseResult.append(line);
					}
					logger_728f7230.error(String.valueOf("apierror:" + responseResult.toString()));
				}
			}
			return null;
		} catch (ConnectException e) {
			throw new Exception(e);
		} catch (MalformedURLException e) {
			throw new Exception(e);
		} catch (IOException e) {
			throw new Exception(e);
		} catch (Exception e) {
			throw new Exception(e);
		} finally {
			httpURLConnection.disconnect();
			try {
				if (printWriter != null) {
					printWriter.close();
				}
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

	public static String postConnectionByAuthorization(String url, String param, String type, String Authorization) throws Exception {
		PrintWriter printWriter = null;
		BufferedReader bufferedReader = null;
		HttpURLConnection httpURLConnection = null;
		JSONObject result = new JSONObject();
		result.put("status", "E");
		StringBuffer responseResult = new StringBuffer();
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			httpURLConnection = (HttpURLConnection) realUrl.openConnection();
			httpURLConnection.setConnectTimeout(30000);
			httpURLConnection.setReadTimeout(30000);
			// 设置通用的请求属性
			httpURLConnection.setRequestProperty("Authorization", Authorization);
			httpURLConnection.setRequestProperty("accept", "*/*");
			httpURLConnection.setRequestProperty("connection", "Keep-Alive");
			httpURLConnection.setRequestProperty("Content-Length", String.valueOf(param.length()));
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			httpURLConnection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
			// 发送POST请求必须设置如下两行
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setRequestMethod(type);
			// 获取URLConnection对象对应的输出流
			// printWriter = new PrintWriter(httpURLConnection.getOutputStream());
			if ("POST".equals(type)) {
				DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
				out.write(param.toString().getBytes("UTF-8"));
				// 发送请求参数
				// printWriter.write(new String(param.toString().getBytes(), "UTF-8"));
				// flush输出流的缓冲
				out.flush();
				out.close();
			}
			// 根据ResponseCode判断连接是否成功
			int responseCode = httpURLConnection.getResponseCode();
			// System.out.println("responseCode:"+responseCode);
			if (responseCode == httpURLConnection.HTTP_OK) {
				// 定义BufferedReader输入流来读取URL的ResponseData
				bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
				String line;
				while ((line = bufferedReader.readLine()) != null) {
					responseResult.append(line);
				}
				result.put("status", "S");
				result.put("result", responseResult.toString());
				return result.toJSONString();
			} else {
				if (httpURLConnection != null && httpURLConnection.getErrorStream() != null) {
					bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream(), "UTF-8"));
					String line;
					while ((line = bufferedReader.readLine()) != null) {
						responseResult.append(line);
					}
					logger_728f7230.error(String.valueOf("apierror:" + responseResult.toString()));
					result.put("result", responseResult.toString());
					return result.toJSONString();
				}
			}
			result.put("result", "接口异常");
			return result.toJSONString();
		} catch (ConnectException e) {
			throw new Exception(e);
		} catch (MalformedURLException e) {
			throw new Exception(e);
		} catch (IOException e) {
			throw new Exception(e);
		} catch (Exception e) {
			throw new Exception(e);
		} finally {
			httpURLConnection.disconnect();
			try {
				if (printWriter != null) {
					printWriter.close();
				}
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws Exception {
		// Map<String,String> map = new HashMap<>();
		// map.put("grant_type","client_credentials");
		// map.put("client_id","mes@cxist_lims11");
		// map.put("client_secret","52179a00-bbdd-4ada-8323-cc1dad4212e3");
		// map.put("tenant_id","439795053355905024");
		// String result = WebApi.postConnectionFormData("http://222.71.165.171:8855/ids/connect/token","POST",map);
		// JSONObject tokenJson = JSON.parseObject(result);
		// if(tokenJson.containsKey("access_token")){
		// System.out.println(tokenJson.getString("access_token"));
		// }else{
		// System.out.println(result);
		// }
		// String result = WebApi.postConnectionByAuthorization("http://222.71.165.171:8855/lims/open/htoa/rollback","{\"requestId\":\"2601900\"}","POST","Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ZW5hbnRfaWQiOiI0Mzk3OTUwNTMzNTU5MDUwMjQiLCJzY29wZSI6WyJhbGwiXSwiZXhwIjoxNjk2Nzk0NzA4LCJqdGkiOiJkYzhhZGQwMS1hZWMyLTQ3M2UtYWVlZC01NjE1ZDgyYjcwNjIiLCJjbGllbnRfaWQiOiJtZXNAY3hpc3RfbGltcyJ9.Ta8DIdT_dkVruWYuupC6XP8l5cru6V9761T0EMx9KdMnI2p9p9bvPIOpdV33ulMYZEEZy4a9klPl4Htq9g5Mgr0sQofz_dA3Rxb0RzfUzcV2uzPsHzIPjqIBfml4qjiB6RcYjWVLg2mp8xvhUgvB02V6wMQXJwjJ_TZu7Wx1Bdznu-JtoMMbDIjlgn--zMLtmhIVZGIK-6KSwGmp5-xRfsv98g4a-taLKDTQACGEptiWbvbCjXt2ehJBLyKQw7B-LomYNZ7gFvihfOCdAMEgtZiaiF6vFmUhw0qK3W-Yxwckh6UPDfdhHuXaZXKNz3yHqCLZKsViDdng2IvQ_O3p6g");
		// System.out.println(result);
		// String aaa = "{\n" +
		// "  \"disposalResult\": 1,\n" +
		// "  \"oaResult\":\"aaa\",\n" +
		// "  \"flowId\": \"1686217803279446018\",\n" +
		// "  \"processStatus\": 1,\n" +
		// "  \"writeBack\":\"{}\",\n" +
		// "  \"remarks\": [\n" +
		// "    {\n" +
		// "      \"conclusion\": \"同意\",\n" +
		// "      \"name\": \"刘经理审核\",\n" +
		// "      \"reviewedBy\": \"刘经理\",\n" +
		// "      \"reviewedDate\": \"2023-08-01 23:34:34\",\n" +
		// "      \"reviewedStatus\": 0\n" +
		// "    }\n" +
		// "  ]\n" +
		// "}\n";
		// String sr = postConnectionSSL("https://10.6.24.122:82/oem/data/mss1/api/framework/v1/admin/oa/flow/examine",aaa,"POST");
		// System.out.println(sr);
		// String sr = postConnection("http://127.0.0.1:7000/api/peixun/ryxx/getlastname2?workcode=test123","","POST");
		// String usernasme = "API@opplelig01T1";
		// String password = "Ople*APi9";
		// String sr = postConnectionByBasicAuth("https://api15.sapsf.cn/odata/v2/TodoEntryV2/$count?$filter=status eq '2' and userId eq '00057664'&$format=json","","GET",usernasme,password);
		// JSONObject ticketparam = new JSONObject();
		// ticketparam.put("appKey","obk_htgd");
		// ticketparam.put("appSecurity","obk_htgd");
		// String ticketUrl="https://ct.ctrip.com/SwitchAPI/Order/Ticket";
		// String result = postConnection(ticketUrl,ticketparam.toString(),"POST");
		// System.out.println(result);
		// JSONObject ticket = new JSONObject(result);
		// if(ticket.has("Ticket") && ticket.getJSONObject("Status").getBoolean("Success")){
		// String tickettoken = ticket.getString("Ticket");
		// System.out.println("tickettoken:"+tickettoken);
		// }
	}
}
