package com.bcxin.ins.third.build.yangguang.util;


import com.alibaba.fastjson.JSON;
import com.bcxin.ins.third.build.yangguang.yggc.Result;
import com.bcxin.ins.third.build.yangguang.yggc.YGGC;
import com.bcxin.ins.core.service.ComDeployConfigService;
import com.bcxin.ins.util.GlobalResources;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class ServicebusBusinessTestClient {

	@Autowired
	ComDeployConfigService comDeployConfigService;

	private static Logger logger = LoggerFactory.getLogger(ServicebusBusinessTestClient.class);
	public static void main(String[] args) throws UnsupportedEncodingException {
		ServicebusBusinessTestClient sendtoHttp = new ServicebusBusinessTestClient();
		String resultStr = null;
		try {
			resultStr = sendtoHttp.httpSend(
//					"http://testservicebus.sinosig.com/WebContent/ServicebusService.do",
					JSON.toJSONString(YGGC.getDemo()));
			System.out.println("请求返回报文为：" + resultStr);
		} catch (Exception e1) {
			logger.error("",e1);
			e1.printStackTrace();
		}
	}

	@SuppressWarnings("null")
	public String httpSend( String json) throws Exception{
		//在这里统一获取配置文件
		String url =  GlobalResources.map.get("YG_GC_URL").trim(); //请求的url
		String msg_body_key = GlobalResources.map.get("YG_GC_MSG_BODY_KEY").trim(); //
		String msg_head_key = GlobalResources.map.get("YG_GC_MSG_HEAD_KEY").trim(); //
		String server_name = GlobalResources.map.get("YG_GC_SERVER_NAME").trim(); //
		String request_method = GlobalResources.map.get("YG_GC_REQUEST_METHOD").trim(); //
		String password = GlobalResources.map.get("YG_GC_PASSWORD").trim(); //
		if(url==null|| msg_body_key==null||msg_head_key==null||server_name==null||request_method==null||password==null){
			return "本地参数配置不正确";
		}
		logger.trace("参数列表："+url);
		logger.trace("msg_body_key："+msg_body_key);
		logger.trace("msg_head_key："+msg_head_key);
		logger.trace("server_name： "+server_name);
		logger.trace("request_method： "+request_method);
		logger.trace("password：  "+password);

		Map<String, Object> map= new HashMap();
		OutputStream outputStream = null;
		ObjectOutputStream objOutputStream = null;
		InputStream inputStream = null;
		ObjectInputStream objinputStream = null;
		HttpURLConnection httpURLConnection=null;
		byte[] iXMLData = null;
		try {
			//初始化参数
//			map = this.messageToMap(map,url,json,msg_body_key,msg_head_key);
			logger.info("发送报文为：-------------------------->"+json);
			String sstrXML = Encryption.authcodeEncode(json, msg_body_key);
			logger.trace("加密后的报文：-------------------------->"+sstrXML);
			byte[] dedata = sstrXML.getBytes("GBK");
			dedata= GZipUtils.compress(dedata); //压缩报文内容
			map.put("serverName", Encryption.authcodeEncode(server_name,msg_head_key));
			map.put("requestMethod", Encryption.authcodeEncode(request_method, msg_head_key));
			map.put("sign", Encryption.authcodeEncode(server_name + password + msg_head_key, msg_head_key));
			map.put("json", dedata);


			//初始化连接
			httpURLConnection=this.initServletClient(httpURLConnection,url);
			outputStream = httpURLConnection.getOutputStream();
			objOutputStream = new ObjectOutputStream(outputStream);
			objOutputStream.writeObject(map.toString());
			objOutputStream.flush();
			objOutputStream.close();
			outputStream.flush();
			outputStream.close();
			inputStream = httpURLConnection.getInputStream();
			BufferedInputStream input = null; // 输入流,用于接收请求的数据
			byte[] buffer = new byte[2048]; // 数据缓冲区
			int count = 0; // 每个缓冲区的实际数据长度
			ByteArrayOutputStream streamXML = new ByteArrayOutputStream(); // 请求数据存放对象
			try {
				input = new BufferedInputStream(inputStream);
				while ((count = input.read(buffer)) != -1) {
					streamXML.write(buffer, 0, count);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (input != null) {
					try {
						input.close();
					} catch (Exception f) {
						f.printStackTrace();
					}
				}
			}
			iXMLData = streamXML.toByteArray(); // 得到一个byte数组,提供给平台
			httpURLConnection.disconnect();
		} catch (Exception e) {
			logger.error("阳光接口调用发生异常",e);
		}finally{
			if(inputStream!=null){
				inputStream.close();
			}
			if(outputStream!=null){
				outputStream.close();
			}
			if(objinputStream!=null){
				objinputStream.close();
			}
			if(httpURLConnection!=null){
				httpURLConnection.disconnect();
			}
		}

		byte[] resultStr = GZipUtils.decompress(iXMLData);
		String returnStr = new String(resultStr,"GBK");
		String returnStr1 = Encryption.authcodeDecode(returnStr, msg_body_key);
		Result r = JSON.parseObject(returnStr1, Result.class);
		logger.info("解析的结果为："+JSON.toJSONString(r));
		return returnStr1;
	}
//
//	private Map<String, Object> messageToMap(Map<String, Object> map, String url, String xml) throws Exception {
//		logger.info("SendtoHttp->tcpSendReceiver()->后台调http");
//		try{
//			logger.info("发送报文为：-------------------------->"+xml);
//			System.out.println("发送报文为：-------------------------->"+xml);
//			String sstrXML = Encryption.authcodeEncode(xml, "BXBHWCXBXWFVCH5LK4N1UO76BJE20ZRA3S8");
//			logger.debug("加密后的报文："+sstrXML);
////			System.out.println("加密后的报文：-------------------------->"+sstrXML);
//			byte[] dedata = sstrXML.getBytes("GBK");
//			dedata= GZipUtils.compress(dedata);
//			String key = "wtf8Y59PMv1jlaqYJgPvj254yis68P";
//			String serverName = Encryption.authcodeEncode("BXBHW",key);
//			String requestMethod = Encryption.authcodeEncode("BXBHW", key);
//			String sign = Encryption.authcodeEncode("BXBHWbxbhw123"+key, key);
//			map.put("serverName", serverName);
//			map.put("requestMethod", requestMethod);
//			map.put("sign", sign);
//			map.put("json", dedata);
//		}catch(Exception e){
//			logger.info("",e);
//			e.printStackTrace();
//		}
//		return map;
//	}

	public HttpURLConnection initServletClient(HttpURLConnection httpURLConnection,String urlStr) throws Exception{
		URL url = null;
		url = new URL(urlStr);
		//获取连接
		httpURLConnection=(HttpURLConnection) url.openConnection();
		httpURLConnection.setUseCaches(false);// 设置不能设置缓存
		httpURLConnection.setDoInput(true);// 打开读写属性，默认为false
		httpURLConnection.setDoOutput(true);// 打开读写属性，默认为false
		httpURLConnection.setRequestMethod("POST");// 设置提交方式，默认为GET
		httpURLConnection.setAllowUserInteraction(true);
		httpURLConnection.setConnectTimeout(60000);
		httpURLConnection.setReadTimeout(60000);
		return httpURLConnection;
	}

}

