package nc.bs.hz.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import nc.bs.framework.common.NCLocator;
import nc.pubitf.para.ISysInitDAO;
import nc.util.fa.httputil.BillHttpRequestUtil;
import nc.util.fa.httputil.MD5Utils;
import nc.vo.pub.BusinessException;
import nc.vo.pub.paratemp.SysinittempVO;

/**
 * 
 * @author 陈长逸 2021年12月25日
 *
 */
public class SendUtil {

	/***
	 * 设置连接主机超时（单位：毫秒）1800秒 30min
	 */
	private final static Integer Connect_Timeout = 1800000;
	/***
	 * 设置从主机读取数据超时（单位：毫秒）1800秒 min
	 */
	private final static Integer Read_Timeout = 180000;

	public static String getSysinittempValue(String initcode) throws BusinessException {
		SysinittempVO sysinittempVO = NCLocator.getInstance().lookup(ISysInitDAO.class).getSysInitTempVO(initcode);
		if (sysinittempVO != null) {
			return sysinittempVO.getDefaultvalue();
		}
		return null;
	}

	public static String getResult(JsonNode data) throws BusinessException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		ObjectNode json = mapper.createObjectNode();
		String appid = SendUtil.getSysinittempValue("appid");
		String appkey = SendUtil.getSysinittempValue("appkey");
		long time = System.currentTimeMillis();
		String token = MD5Utils.MD5Upper(appid + appkey + time);
		json.put("appid", appid);
		json.put("time", time);
		json.put("token", token);
		// String datas = Base64Util.encode(JSONObject.toJSONString(data));
		json.set("data", data);
		return mapper.writeValueAsString(json);
	}

	private static void setPostHead(HttpPost httpPost, Map<String, String> headMap) {
		if ((headMap != null) && (headMap.size() > 0)) {
			Set<String> keySet = headMap.keySet();
			for (String key : keySet) {
				httpPost.addHeader(key, (String) headMap.get(key));
			}
		}
	}

	public static String httpPost(String url, final Object content, Map<String, String> headMap) {
		String responseContent = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost httpPost = new HttpPost(url);
			setPostHead(httpPost, headMap);
			ContentProducer cp = new ContentProducer() {
				public void writeTo(OutputStream outstream) throws IOException {
					Writer writer = new OutputStreamWriter(outstream, "UTF-8");
					writer.write(String.valueOf(content));
					writer.flush();
				}

			};
			httpPost.setEntity(new EntityTemplate(cp));

			CloseableHttpResponse response = httpclient.execute(httpPost);
			try {
				System.out.println(response.getStatusLine());
				HttpEntity entity = response.getEntity();
				InputStream is = entity.getContent();
				StringBuffer strBuf = new StringBuffer();
				byte[] buffer = new byte['?'];
				int r = 0;
				while ((r = is.read(buffer)) > 0) {
					strBuf.append(new String(buffer, 0, r, "UTF-8"));
				}
				responseContent = strBuf.toString();
				EntityUtils.consume(entity);
			} finally {
				response.close();
			}

			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

			System.out.println("responseContent = " + responseContent);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return responseContent;
	}

	/**
	 * java.net实现 HTTP POST方法提交
	 * 
	 * @param url
	 * @param paramContent
	 * @return
	 * @throws Exception
	 */
	public static String submitPost(String url, String paramContent, String headers_token) throws Exception {
		String responseMessage = "";
		Map<String, String> headMap = new HashMap<String, String>();
		headMap.put("Content-Type", "application/json;charset=utf-8");
		headMap.put("Accept", "*/*");
		headMap.put("Accept-Encoding", "gzip, deflate,br");
		headMap.put("connection", "Keep-Alive");
		if (headers_token != null) {
			headMap.put("token", headers_token);
		}
		// zgvjzmqxmdgtmddlnc00otazlwe1n2qtytu5od2q5nthj
		try {
			responseMessage = httpPost(url, paramContent, headMap);
		} catch (Exception e) {
			throw e;
		}
		return responseMessage.toString();
	}

	/**
	 * java.net实现 HTTP POST方法提交
	 * 
	 * @param url
	 * @param paramContent
	 * @return
	 * @throws Exception
	 */
	public static StringBuffer submitPost(String url, String paramContent) throws Exception {
		StringBuffer responseMessage = null;
		HttpURLConnection con = null;
		java.net.URL reqUrl = null;
		OutputStreamWriter reqOut = null;
		InputStream in = null;
		BufferedReader br = null;
		String param = paramContent;
		try {

			System.out.println("url=" + url + "?" + paramContent + "\n");
			System.out.println("===========post method start=========");
			responseMessage = new StringBuffer();
			reqUrl = new java.net.URL(url);
			con = (HttpURLConnection) reqUrl.openConnection();
			con.setRequestMethod("POST");
			con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			con.setDoOutput(true);
			con.setConnectTimeout(Connect_Timeout);
			con.setReadTimeout(Read_Timeout);

			reqOut = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
			reqOut.write(param);
			reqOut.flush();
			int charCount = -1;
			in = con.getInputStream();

			br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			while ((charCount = br.read()) != -1) {
				responseMessage.append((char) charCount);
			}

			System.out.println(responseMessage);
			System.out.println("===========post method end=========");
		} catch (Exception ex) {
			System.out.println("url=" + url + "?" + paramContent + "\n e=" + ex);
			throw new Exception("发送失败", ex);
		} finally {
			try {
				in.close();
				reqOut.close();
			} catch (Exception e) {
				System.out.println("paramContent=" + paramContent + "|err=" + e);
			}

		}
		return responseMessage;
	}

	/**
	 * java.net实现 HTTP或HTTPs GET方法提交
	 * 
	 * @param strUrl 提交的地址及参数
	 * @return 返回的response信息
	 */
	public static String submitGet(String strUrl) {
		URLConnection connection = null;
		BufferedReader reader = null;
		String str = null;
		try {
			System.out.println("send getmethod=" + strUrl);
			URL url = new URL(strUrl);
			connection = url.openConnection();
			connection.setDoInput(true);
			connection.setDoOutput(false);
			connection.setConnectTimeout(Connect_Timeout);
			connection.setReadTimeout(Read_Timeout);
			// 取得输入流，并使用Reader读取
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			System.out.println("============Contents of get request===============");
			String lines;
			StringBuffer linebuff = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				linebuff.append(lines);
			}
			System.out.println(linebuff);
			System.out.println("============Contents of get request ends==========");
			str = linebuff.toString();
		} catch (Exception e) {
			System.out.println("getmethod is err=" + e);
			e.printStackTrace();
		} finally {
			try {
				if (reader != null)
					reader.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return str;
	}

	public static String unicodeToString(String str) {
		
		if(str==null)
			return "请判断该单据是否需要推ARC";

		Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
		Matcher matcher = pattern.matcher(str);
		char ch;
		while (matcher.find()) {
			ch = (char) Integer.parseInt(matcher.group(2), 16);
			str = str.replace(matcher.group(1), ch + "");
		}
		return str;
	}

}