package com.bcxin.ins.third.gzzrx.zhonghua;

import com.bcxin.ins.entity.common.LogBusinessrequest;
import com.bcxin.ins.service.order.LogBusinessrequestService;
import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.ins.vo.InsPreservationRecordVo;
import com.bcxin.ins.vo.OrderFormVo;
import com.bcxin.ins.vo.SpecialHirelingVo;
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.*;
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("gZZRX_ZHRequestService")
@Transactional
public class GZZRX_ZHRequestService {

	private static Logger communicatorLog =  LoggerFactory.getLogger(GZZRX_ZHRequestService.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_zh_gzzrx(Long order_id, String transType, InsPreservationRecordVo rvo) throws Exception {
		communicatorLog.info("request_zh_gzzrx：star-----------------------");
		communicatorLog.info("request_zh_gzzrx：接口编码-"+transType+",订单id-"+order_id+",RecordVo-"+(rvo != null ? rvo.toString() : "null"));
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(order_id);
		SpecialHirelingVo vo = policyService.accordingToOrderIDToGetSpecialHirelingVo(Long.parseLong(dto.getOid()));
		String result = "300#（APP-PAC-GZZRX-001）网络不稳定，请重新请求！";
		LogBusinessrequest lb = null;
		try {
			String xml = GZZRX_PackageMessageZhongHua.marshal(vo, dto, transType, rvo);
			communicatorLog.info("请求报文："+xml);
			String url = getPath(transType);
			communicatorLog.info("请求地址："+url);
			Date bTime = new Date();
			String ret = sendPost(url, xml, "", transType);
			lb = logBusinessrequestService.initLogBusinessrequest(String.valueOf(order_id),transType,url,xml,ret,bTime,new Date(), TransTypeEnum.getAlias(transType));
			communicatorLog.info("返回报文："+ret);
			GZZRX_PackageMessageZhongHua gpm = new GZZRX_PackageMessageZhongHua();
			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_zh_gzzrx：end-----------------------");
		return result;
	}

	private String getPath(String tt){
		if(TransTypeEnum.HB.getValue().equals(tt)){//投保接口
			return GlobalResources.ZH_GZ_INS_URL;
		}else if(TransTypeEnum.PD.getValue().equals(tt)){//批单
			return GlobalResources.ZH_GZ_INS_URL;//设置批单接口地址
		}else if(TransTypeEnum.ZFDZ.getValue().equals(tt)){//支付申请地址
			return GlobalResources.ZH_GZ_PAY_URL;
		}else if(TransTypeEnum.ZFJG.getValue().equals(tt)){//支付结果查询
			return GlobalResources.ZH_GZ_PAY_URL;
		}else if(TransTypeEnum.DZFP.getValue().equals(tt)){//电子发票接口地址
			return GlobalResources.ZH_GZ_FP_URL;
		}
		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 "";
	}

	/**
	 * 向指定 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;
	}
}
