package com.bcxin.ins.third.zzx.huatai;

import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.entity.common.LogBusinessrequest;
import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.service.order.LogBusinessrequestService;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.third.gzx.huatai.util.RsaUtil;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.util.http.RequestUtil;
import com.bcxin.ins.vo.*;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;


/**
 *
 * <b>华泰-展责险http接口请求业务</b>
 *
 * @author zxf
 * @date 2017年10月11日 上午10:29:46
 * @注意事项 </b>
 * <b>
 */
@Service("zZX_HTRequestService")
@Transactional
public class ZZX_HTRequestService {

	private static Logger communicatorLog =  LoggerFactory.getLogger(ZZX_HTRequestService.class);

	@Autowired
	private PolicyService policyService;
	@Autowired
	private LogBusinessrequestService logBusinessrequestService;

	private static String GW_CH_CODE = "BCXWL";//合作伙伴代码
	private static String GW_CH_USER = "BCXWL";//用户名

	/**
	 * 中华请求方法
	 * 核保测试地址：
	 * 核保生产地址：
	 *
	 * 批单测试地址：
	 * 批单生产地址：
	 *
	 * 测试地址：
	 * 正式地址：
	 *
	 * @return
	 */
	public String request_ht_zzx(Long order_id, String transType, InsPreservationRecordVo rvo) throws Exception {
		communicatorLog.info("request_ht_zzx：star-----------------------");
		communicatorLog.info("request_ht_zzx：接口编码-"+transType+",订单id-"+order_id+",RecordVo-"+(rvo != null ? rvo.toString() : "null"));
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(order_id);
		LOTEPolicyVo vo = policyService.accordingToOrderIDToGetLOTEPolicyVo(order_id);
		String result = "300#（APP-HT-ZZX-001）网络不稳定，请重新请求！";
		LogBusinessrequest lb = null;
		try {
			String json = ZZX_PackageMessageHuaTai.marshal(vo, dto, transType, rvo);
			communicatorLog.info("请求报文（明文）："+json);
			//加密
			String e_json = sign(json);
			communicatorLog.info("请求报文（密文）："+e_json);
			String url = getPath(transType);
			communicatorLog.info("请求地址："+url);
			Date bTime = new Date();
			String ret = sendPost(url, e_json);
			communicatorLog.info("返回报文（密文）："+ret);
			if(StringUtils.isEmpty(ret)){
				return "300#无返回信息";
			}
			JSONObject obj = (JSONObject)JSONObject.parse(ret);
			try {
				ret = RsaUtil.dSign(obj.get("signature")+"",GlobalResources.HT_GZX_RSA_PRIVATEKEY);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
			lb = logBusinessrequestService.initLogBusinessrequest(String.valueOf(order_id),transType,url,json,ret,bTime,new Date(), TransTypeEnum.getAlias(transType));
			communicatorLog.info("返回报文（明文）："+ret);
			ZZX_PackageMessageHuaTai gpm = new ZZX_PackageMessageHuaTai();
			result = gpm.returnAnalysisXML(ret,transType);
			communicatorLog.info("返回报文处理："+result);
			logBusinessrequestService.supplementDecAndSave(lb,result.startsWith(ConstProp.CODE_FAILURE)?1:0,ConstProp.BLANK_CHAR);
		}catch (Exception ex){
			logBusinessrequestService.supplementDecAndSave(lb,2,ex.getMessage());
			ex.printStackTrace();
		}
		communicatorLog.info("request_ht_zzx：end-----------------------");
		return result;
	}


	private static String sign(String param){
		JSONObject json = new JSONObject();
		json.put("chlCode", GlobalResources.HT_CHANNELCODE);
		try {
			json.put("signature", RsaUtil.eSign(param, GlobalResources.HT_GZX_RSA_PUBLICKEY));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return json.toJSONString();
	}

	private String getPath(String tt){
		if(TransTypeEnum.HB.getValue().equals(tt)){//投保接口
			return GlobalResources.HT_SERVICES_URL+"/htExtOrder/underWritingInterface";
		}else if(TransTypeEnum.TOB.getValue().equals(tt)){//投保接口
			return GlobalResources.HT_SERVICES_URL+"/htExtOrder/creatMonthProposal";
		}else if(TransTypeEnum.ZFDZ.getValue().equals(tt)){//支付申请地址
			return GlobalResources.HT_SERVICES_URL+"/htExtOrder/orderPay";
		}else if(TransTypeEnum.DZFP.getValue().equals(tt)){//电子发票接口地址
			return GlobalResources.HT_SERVICES_URL+"/htExtOrder/invoiceApplyUrl";
		}
		return "";
	}

	private String getCode(String tt){
		if(TransTypeEnum.HB.getValue().equals(tt)){//投保接口
			return "2011";
		}else if(TransTypeEnum.ZFJG.getValue().equals(tt)){//支付结果
			return "1001";
		}else if(TransTypeEnum.ZFDZ.getValue().equals(tt)){//支付申请地址
			return "1000";
		}else if(TransTypeEnum.PD.getValue().equals(tt)){//批单
			return "2014";
		}else if(TransTypeEnum.DZFP.getValue().equals(tt)){//电子发票
			return "PS009";
		}
		return "";
	}

	public String sendPost(String url, String param) {

		String result = "";
		try {
			result = RequestUtil.initHttp().doPost(url, param, "text/json", "UTF-8");
		} catch (Exception e) {
			communicatorLog.error("发送POST请求异常！",e);
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 *
	 * @param url
	 *            发送请求的 URL
	 * @param sign
	 * 			  签名
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public String sendPost(String url, String param, String sign, String tt) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("GW_CH_TX", getCode(tt));
			conn.setRequestProperty("GW_CH_CODE", GW_CH_CODE);
			conn.setRequestProperty("GW_CH_USER", GW_CH_USER);
			conn.setRequestProperty("GW_CH_PWD", GlobalResources.GW_CH_PWD);
			conn.setRequestProperty("GW_CH_SIGN", sign);
			conn.setRequestProperty("User-Agent", "stargate");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
			conn.setConnectTimeout(300000);
			conn.setReadTimeout(900000);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream(),"GBK"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			communicatorLog.error("发送POST请求异常！",e);
		}
		//使用finally块来关闭输出流、输入流
		finally{
			try{
				if(out!=null){
					out.close();
				}
				if(in!=null){
					in.close();
				}
			}
			catch(IOException ex){
				communicatorLog.error("发送POST关闭连接异常",ex);

			}
		}
		return result;
	}
}
