package com.bcxin.ins.third.gyx.taibao;

import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.entity.common.LogBusinessrequest;
import com.bcxin.ins.service.order.LogBusinessrequestService;
import com.bcxin.ins.third.gyx.taibao.util.MySecureProtocolSocketFactory;
import com.bcxin.ins.third.gyx.taibao.util.TbRsaUtils;
import com.bcxin.ins.service.order.InsTransactionAPIService;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.util.DateUtil;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.util.XMLUtil;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.ins.vo.GYXPolicyVo;
import com.bcxin.ins.vo.OrderFormVo;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;


/**
 * <b> 太保-个意险http接口请求业务 </b>
 * @author ZXF
 * @create 2018/01/30 0030 10:31
 * @version 
 * @注意事项 </b>
 */
@Service("gYX_TBRequestService")
public class GYX_TBRequestService {

	private Logger communicatorLog =  LoggerFactory.getLogger(GYX_TBRequestService.class);

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

	/**
	 * 太保请求方法
	 * 
	 * @return
	 */
	public String requestTB(Long order_id, String transType, String payType) throws Exception {
		communicatorLog.info("requestTB-GYX：star-----------------------");
		communicatorLog.info("requestTB-GYX：接口编码-"+transType+",订单id-"+order_id);
		String result = "300#（APP-TB-GYX-001）网络不稳定，请重新请求！";
		LogBusinessrequest lb = null;
		try {
			//核保报文组装
			String xml = signXml(order_id, transType, payType);
			communicatorLog.info(DateUtil.convertDateToString(new Date(),DateUtil.FORMAT1)+"请求报文：");
			communicatorLog.info(XMLUtil.formatXML(xml));
			String returnMsg = ConstProp.BLANK_CHAR;
			Date bTime = new Date();
			String url = "";
			for(int i=0;i<3;i++){
				returnMsg = syncTB(xml,transType,url);
				if(StringUtils.isNotEmpty(returnMsg)){
					break;
				}
			}
			lb = logBusinessrequestService.initLogBusinessrequest(String.valueOf(order_id),transType,url,xml,returnMsg,bTime,new Date(), TransTypeEnum.getAlias(transType));
			communicatorLog.info(DateUtil.convertDateToString(new Date(),DateUtil.FORMAT1)+"返回报文：");
			communicatorLog.info(XMLUtil.formatXML(returnMsg));
			communicatorLog.info(DateUtil.convertDateToString(new Date(),DateUtil.FORMAT1)+"返回报文结束--------------------------");
			if(StringUtils.isNotEmpty(returnMsg)){
				result = GYX_PackageMessageTaiBao.returnAnalysisXML(returnMsg,transType);
			}else{
				result = "300#网络不稳定或数据丢失！";
			}
			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("requestTB-GYX：end-----------------------");
		return result;
	}

	public String signXml(Long order_id, String transType, String payType) throws Exception {
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(order_id);
		GYXPolicyVo vo = policyService.accordingToOrderIDToGetGYXPolicyVo(order_id);
		/*InsTransaction it = null;
		if(StringUtils.isNotEmpty(dto.getOid())){
			List<InsTransaction> tList = insTransactionService.selectInsTransactionByInsOrderForm(Long.parseLong(dto.getOid()));
			if(tList==null?false:tList.size()>0?true:false){
				it = tList.get(0);
			}
		}*/
		//核保报文组装
		return TbRsaUtils.appendSign(GYX_PackageMessageTaiBao.marshal(vo, dto, transType, payType));
	}

	public String signXmlResult(OrderFormVo dto, JSONObject msgJson) throws Exception {
		//支付结果，承保结果返回报文组装
		return TbRsaUtils.appendSignResult(GYX_PackageMessageTaiBao.marshalResult(dto, msgJson));
	}

	private String syncTB(String requestXml, String tp, String purl){
		String result = ConstProp.BLANK_CHAR;
		String url = GlobalResources.CPIC_GYX_URL+ getUrl(tp);
		communicatorLog.info("request url:"+ url);
		ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
		Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
		//调用
		HttpClient client = new HttpClient();
		purl = url;
		PostMethod pm = new PostMethod(url);
		try {

			pm.setRequestEntity(new StringRequestEntity(requestXml, "text/xml", "UTF-8"));
			client.executeMethod(pm);
			result = pm.getResponseBodyAsString();
		} catch(Exception e) {
			communicatorLog.info(e.getMessage());
			e.printStackTrace();
		} finally {
			// 释放连接
			pm.releaseConnection();
		}

		return result;
	}

	/**
	 * <b>
	 *  测试环境URL如下：
	 *	投保URL：https://car.etaiping.com:6016/react/platform/portal/proposal
	 *	退保URL：https://car.etaiping.com:6016/react/platform/portal/endor
	 *	生产环境URL如下：
	 *	投保：https://nonautocloud.tpi.cntaiping.com/react/platform/portal/proposal
	 *	退保：https://nonautocloud.tpi.cntaiping.com/react/platform/portal/endor
	 * </b>
	 *
	 * @author ZXF
	 * @create 2018/03/06 0006 10:51
	 * @version
	 * @注意事项 </b>
	 */
	private String getUrl(String tp){
		String url = ConstProp.BLANK_CHAR;
		if(StringUtils.isNotEmpty(tp)){
			if(ConstProp.DIGIT_ONE.equals(tp)||ConstProp.DIGIT_FOUR.equals(tp)){
				url = "/react/platform/portal/proposal";
			}else if(ConstProp.DIGIT_TWO.equals(tp)||ConstProp.DIGIT_THREE.equals(tp)){
				url = "/react/platform/portal/pay";
			}
		}
		return url;
	}
}
