package com.bcxin.ins.third.build.dubang;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bcxin.ins.util.*;
import com.bcxin.ins.util.IdWorker;
import com.bcxin.ins.vo.*;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.mybatisplus.toolkit.*;
import org.dom4j.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 *
 * <b>都邦-投标保证保险各接口请求数据组装</b>
 *
 * @author zxf
 * @date 2017年10月11日 上午10:29:46
 * @注意事项 </b>
 * <b>
 */
public class Build_PackageMessageDuBang {
	protected Document requestDocument;
	protected Element rootElement;

	void Build_PackageMessageDuBang(){

	}

	private static Logger logger = LoggerFactory.getLogger(Build_PackageMessageDuBang.class);

	/**
	 * 支付接口组装支付需要的数据根据商户订单编号获取二维码支付
	 * @param vo
	 * @param dto
	 * @return
	 */
	public static String getPayQRCode(SpecialBidVo vo, OrderFormVo dto, Map<String,String> map){
		String result = ConstProp.BLANK_CHAR;
		Document requestDocument = DocumentHelper.createDocument();
		requestDocument.setXMLEncoding("GBK");
		Element reqElement = requestDocument.addElement("PACKET");
		reqElement.addAttribute("type","REQUEST");
		reqElement.addAttribute("version",DBProp.VERSION);
		try {
			//头
			Element headElement = reqElement.addElement("HEAD");
			qRCodeHead(headElement, dto);
			//内容
			Element bodyElement = reqElement.addElement("BODY");
			Element orderInfoElement = bodyElement.addElement("ORDERINFO");
			qRCodeOrderInfo(orderInfoElement, dto, map);
			Element goodsListElement = bodyElement.addElement("GOODSLIST");
			Element goodsElement = goodsListElement.addElement("GOODS");
			qRCodeGoods(goodsElement, dto);
			Element signInfoElement = bodyElement.addElement("SIGNINFO");
			String signBuild = "BUSINESSSOURCE=00003&SOURCEORDER="+dto.getTrade_serial_number()+"&SUMPAYFEE="+dto.getGross_premium()+"&OPERATECODE=231000107&BUSINESSTYPE=P&ORDERNO="+map.get("ORDERNO")+"&CERTINO="+dto.getExternal_reference()+"&KEY="+GlobalResources.DB_INS_KEY;
			logger.info("signBuild（243）:"+signBuild);
			String sign= MD5Util.md5(signBuild.trim()).toUpperCase();//加密
			logger.info("sign（243）:"+sign);
			signInfoElement.addElement("SIGN").setText(sign);
			result = requestDocument.asXML();
			logger.info("都邦获取二维码时支付数据组装报文--getPayQRCode（243）："+result);
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}

	private static void qRCodeHead(Element underwrite, OrderFormVo dto) {
		//
		underwrite.addElement("REQUEST_TYPE").setText("243");
		//
		underwrite.addElement("USERCODE").setText("200000018");
		//
		underwrite.addElement("COMCODE").setText("2000000000");

	}

	private static void qRCodeOrderInfo(Element underwrite, OrderFormVo dto, Map<String,String> map) {
		// 订单来源代码
		underwrite.addElement("BUSINESSSOURCE").setText("00003");
		// 外部订单编号
		underwrite.addElement("SOURCEORDER").setText(dto.getTrade_serial_number());
		// 订单总金额
		underwrite.addElement("SUMPAYFEE").setText(dto.getGross_premium());
		// 出单员
		underwrite.addElement("OPERATECODE").setText("231000107");
		// 业务类型 T投保 P保单
		underwrite.addElement("BUSINESSTYPE").setText("P");
		// 支付单号
		underwrite.addElement("ORDERNO").setText(map.get("ORDERNO"));
		// 支付成功后回调标志
		underwrite.addElement("CALLBACKFLAG").setText("1");
		String  return_url=GlobalResources.DONOW_PATH+"/DB-API/Build/callbackPay";
		// 回调地址
		underwrite.addElement("CALLBACKURL").setText(return_url);
	}

	private static void qRCodeGoods(Element underwrite, OrderFormVo dto) {
		// 业务单号
		underwrite.addElement("CERTINO").setText(dto.getExternal_reference());
		// 险种代码
		underwrite.addElement("RISKCODE").setText("2899");
		// 归属机构
		underwrite.addElement("COMCODE").setText("2210200604");
		// 应付金额
		underwrite.addElement("CERTIFEE").setText(dto.getGross_premium());

	}

	/**
	 * 支付接口组装支付需要的数据用于获取商户订单编号
	 * @param vo
	 * @param dto
	 * @return
	 */
	public static String getPayOrder(SpecialBidVo vo, OrderFormVo dto){
		String result = ConstProp.BLANK_CHAR;
		Document requestDocument = DocumentHelper.createDocument();
		requestDocument.setXMLEncoding("GBK");
		Element reqElement = requestDocument.addElement("PACKET");
		reqElement.addAttribute("type","REQUEST");
		reqElement.addAttribute("version",DBProp.VERSION);
		try {
			//头
			Element headElement = reqElement.addElement("HEAD");
			payHead(headElement, dto);

			//内容
			Element bodyElement = reqElement.addElement("BODY");
			Element orderInfoElement = bodyElement.addElement("ORDERINFO");
			payOrderInfo(orderInfoElement, dto);
			Element goodsListElement = bodyElement.addElement("GOODSLIST");
			Element goodsElement = goodsListElement.addElement("GOODS");
			payGoods(goodsElement, dto);
			Element signInfoElement = bodyElement.addElement("SIGNINFO");
			String signBuild = "BUSINESSSOURCE=00003&SOURCEORDER="+dto.getTrade_serial_number()+"&SUMPAYFEE="+dto.getGross_premium()+"&OPERATECODE=231000107&BUSINESSTYPE=P&CERTINO="+dto.getExternal_reference()+"&KEY="+GlobalResources.DB_INS_KEY;
			System.out.println("signBuild（241）:"+signBuild);
			String sign= MD5Util.md5(signBuild.trim()).toUpperCase();//加密
			System.out.println("sign（241）:"+sign);
			signInfoElement.addElement("SIGN").setText(sign);
			result = requestDocument.asXML();
			logger.info("都邦获取二维码时支付数据组装报文--getPayQRCode（241）："+result);
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}

	private static void payHead(Element underwrite, OrderFormVo dto) {
		//
		underwrite.addElement("REQUEST_TYPE").setText("241");
		//
		underwrite.addElement("USERCODE").setText("200000018");
		//
		underwrite.addElement("COMCODE").setText("2000000000");

	}

	private static void payOrderInfo(Element underwrite, OrderFormVo dto) {
		// 订单来源代码
		underwrite.addElement("BUSINESSSOURCE").setText("00003");
		// 外部订单编号
		underwrite.addElement("SOURCEORDER").setText(dto.getTrade_serial_number());
		// 订单总金额
		underwrite.addElement("SUMPAYFEE").setText(dto.getGross_premium());
		// 出单员
		underwrite.addElement("OPERATECODE").setText("231000107");
		// 业务类型 T投保 P保单
		underwrite.addElement("BUSINESSTYPE").setText("P");

	}

	private static void payGoods(Element underwrite, OrderFormVo dto) {
		// 业务单号
		underwrite.addElement("CERTINO").setText(dto.getExternal_reference());
		// 险种代码
		underwrite.addElement("RISKCODE").setText("2899");
		// 归属机构
		underwrite.addElement("COMCODE").setText("2210200604");
		// 应付金额
		underwrite.addElement("CERTIFEE").setText(dto.getGross_premium());

	}

	public static String test_941(){
		String result = ConstProp.BLANK_CHAR;
		Document requestDocument = DocumentHelper.createDocument();
		requestDocument.setXMLEncoding("GBK");
		Element reqElement = requestDocument.addElement("PACKET");
		reqElement.addAttribute("type","REQUEST");
		reqElement.addAttribute("version",DBProp.VERSION);
		try {
			//内容
			Element bodyElement = reqElement.addElement("BODY");
			bodyElement.addElement("REQUEST_TYPE").setText("941");
			Element sendInfoElement = bodyElement.addElement("SENDINFO");
			sendInfoElement.addElement("OUTORDERNO").setText("992017011710015100001");
			sendInfoElement.addElement("AMOUNT").setText("0.01");
			sendInfoElement.addElement("PAYSTATUS").setText("2");
			sendInfoElement.addElement("PAYTIME").setText("2017-03-27 14:53:47");
			sendInfoElement.addElement("ORDERSOURCE").setText("00003");
			String sign = "REQUEST_TYPE=941&OUTORDERNO=992017011710015100001&AMOUNT=0.01&PAYSTATUS=2&PAYTIME=2017-03-27 14:53:47&ORDERSOURCE=00003&KEY="+GlobalResources.DB_INS_KEY;
			sign= MD5Util.md5(sign.trim()).toUpperCase();//加密
			Element signInfoElement = bodyElement.addElement("SIGNINFO");
			signInfoElement.addElement("SIGN").setText(sign);
			result = requestDocument.asXML();
			logger.info("推送核保通过以及生效的保单信息返回数据组装报文--test_941（941）："+result);
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}
	public static String test_942(){
		String result = ConstProp.BLANK_CHAR;
		Document requestDocument = DocumentHelper.createDocument();
		requestDocument.setXMLEncoding("GBK");
		Element reqElement = requestDocument.addElement("PACKET");
		reqElement.addAttribute("type","REQUEST");
		reqElement.addAttribute("version",DBProp.VERSION);
		try {
			//内容
			Element bodyElement = reqElement.addElement("BODY");
			bodyElement.addElement("REQUEST_TYPE").setText("942");
			Element sendInfoElement = bodyElement.addElement("SENDINFO");
			sendInfoElement.addElement("POLICYNO").setText("20508232020015000022");
			sendInfoElement.addElement("PROPOSALNO").setText("10508232020015000025");
			sendInfoElement.addElement("CERTITYPE").setText("U");
			sendInfoElement.addElement("OPERATETIME").setText("2017-03-31 18:47:37");
			sendInfoElement.addElement("INPUTSYSCODE").setText("A1");
			String sign = "REQUEST_TYPE=942&POLICYNO=20508232020015000022&PROPOSALNO=10508232020015000025&CERTITYPE=U&OPERATETIME=2017-03-31 18:47:37&INPUTSYSCODE=A1&KEY="+GlobalResources.DB_INS_KEY;
			sign= MD5Util.md5(sign.trim()).toUpperCase();//加密
			Element signInfoElement = bodyElement.addElement("SIGNINFO");
			signInfoElement.addElement("SIGN").setText(sign);
			result = requestDocument.asXML();
			logger.info("推送核保通过以及生效的保单信息返回数据组装报文--test_941（941）："+result);
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 941接口返回报文
	 * @param status 推送是否成功1-成功 0-失败
	 * @param outOrderNo 第三方订单号
	 * @return
	 */
	public static String returnSuccessInfo(String status, String outOrderNo){
		String result = ConstProp.BLANK_CHAR;
		Document requestDocument = DocumentHelper.createDocument();
		requestDocument.setXMLEncoding("GBK");
		Element reqElement = requestDocument.addElement("PACKET");
		reqElement.addAttribute("type","REQUEST");
		reqElement.addAttribute("version",DBProp.VERSION);
		try {
			//头
			Element headElement = reqElement.addElement("HEAD");
			// 第三方订单号
			headElement.addElement("OUTORDERNO").setText(outOrderNo);
			// 推送是否成功1-成功 0-失败
			headElement.addElement("RESPONSE_CODE").setText(status);
			result = requestDocument.asXML();
			logger.info("推送订单支付成功信息返回数据组装报文--returnSuccessInfo（941）："+result);
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 942接口返回报文
	 * @param status 推送是否成功1-成功 0-失败
	 * @param certiType 保单状态标志 CERTITYPE的值直接从请求报文里取
	 * @return
	 */
	public static String returnPolicyStatus(String status, String certiType){
		String result = ConstProp.BLANK_CHAR;
		Document requestDocument = DocumentHelper.createDocument();
		requestDocument.setXMLEncoding("GBK");
		Element reqElement = requestDocument.addElement("PACKET");
		reqElement.addAttribute("type","REQUEST");
		reqElement.addAttribute("version",DBProp.VERSION);
		try {
			//头
			Element headElement = reqElement.addElement("HEAD");
			// 保单状态标志
			headElement.addElement("CERTITYPE").setText(certiType);
			// 推送是否成功1-成功 0-失败
			headElement.addElement("RESPONSE_CODE").setText(status);
			result = requestDocument.asXML();
			logger.info("推送核保通过以及生效的保单信息返回数据组装报文--returnPolicyStatus（942）："+result);
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}

	public static String marshal(SpecialBidVo vo, OrderFormVo dto){
		String result = ConstProp.BLANK_CHAR;
		Document requestDocument = DocumentHelper.createDocument();
		requestDocument.setXMLEncoding(ConstProp.ENCODE_UTF8);
		Element reqElement = requestDocument.addElement("request");
		try {
			//头
			Element headElement = reqElement.addElement("header");
			marshalHead(headElement, dto);

			//内容
			Element bodyElement = reqElement.addElement("body");

			Element policyInfoElement = bodyElement.addElement("policyInfo");//4.1.1.2.保单主信息
			marshalPolicyInfo(vo, dto, policyInfoElement);
			Element engageItemListElement = bodyElement.addElement("engageItemList");//4.1.1.3.特别约定信息
			marshalEngageItemList(vo, dto, engageItemListElement);
			Element holderElement = bodyElement.addElement("holder");//4.1.1.4.投保人信息
			marshalHolder(vo, dto, holderElement);
			Element insuredsElement = bodyElement.addElement("insureds");//4.1.1.5.被保险人信息
			Element insuredElement = insuredsElement.addElement("insured");//4.1.1.5.被保险人信息
			marshalInsureds(vo, dto, insuredElement);
			Element coverageListElement = bodyElement.addElement("coverageList");//4.1.1.7.承保险别信息
			Element coverageItemElement = coverageListElement.addElement("coverageItem");//4.1.1.7.承保险别信息
			marshalCoverageList(vo, dto, coverageItemElement);
			result = requestDocument.asXML();
			logger.info("都邦请求核保时数据组装报文--marshal："+result);
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}

	//4.1.1.1.请求头信息
	private static void marshalHead(Element underwrite, OrderFormVo dto) {
		//请求的接口类型代码
		underwrite.addElement("msgId").setText("srv0001");
		//时间戳格式为YYYYMMDDHHmmSS
		underwrite.addElement("timestamp").setText(DateUtil.generatorRadomNumberForDate());
		//版本号，默认为1.0
		underwrite.addElement("version").setText(DBProp.VERSION);
		//绑定出单机器ip
		underwrite.addElement("ipaddress").setText(GlobalResources.DB_INS_IP);//测环境:10.4.29.8,开发:10.4.29.8,生产:47.94.176.255
		//默认为1
		underwrite.addElement("actionCode").setText("1");

	}

	//4.1.1.2.保单主信息 policyInfo
	private static void marshalPolicyInfo(SpecialBidVo vo, OrderFormVo dto, Element policyInfo){
		IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
		policyInfo.addElement("applicationId").setText(String.valueOf(idWorker.nextId()));//随机流水号
		policyInfo.addElement("serialNumber").setText(dto.getTrade_serial_number());//订单编码
		policyInfo.addElement("planCode").setText("700100011");//产品代码
		policyInfo.addElement("amount").setText(dto.getInsured_amount());//保险金额
		policyInfo.addElement("premium").setText(dto.getGross_premium());//保费
		policyInfo.addElement("startDate").setText(DateUtil.convertDateToString(DateUtil.convertStringToDate(dto.getInception_date()),DateUtil.FORMAT6));//生效日期
		policyInfo.addElement("startHour").setText(ConstProp.DIGIT_ZERO);
		policyInfo.addElement("endDate").setText(DateUtil.convertDateToString(DateUtil.convertStringToDate(dto.getPlanned_end_date()),DateUtil.FORMAT6));
		policyInfo.addElement("endHour").setText("24");
		policyInfo.addElement("instonyInputDate").setText(DateUtil.convertDateToString(DateUtil.convertStringToDate(dto.getStart_time()),DateUtil.FORMAT1_2));//下单日期
		policyInfo.addElement("provincecode").setText(vo.getProvince());
		policyInfo.addElement("citycode").setText(vo.getCity());
		policyInfo.addElement("addressCode").setText(vo.getArea_code());
		policyInfo.addElement("addressName").setText(vo.getAddress());
		policyInfo.addElement("constructionGrade").setText(vo.getOffice_type());//建筑行业资质等级
		policyInfo.addElement("projectNature").setText(getProjectNature(vo.getAptitude_level().trim()));//项目性质
	}

	private static String getConstructionGrade(String value){//建筑行业资质等级
		if("1".equals(value)){//楼宇
			return "0007";
		}else if("2".equals(value)){//工程企业建设
			return "0002";
		}else if("3".equals(value)){//管线工程
			return "0003";
		}else if("4".equals(value)){//陆上交通建设工程
			return "0004";
		}else if("5".equals(value)){//涉水工程
			return "0005";
		}else if("6".equals(value)){//其他工程
			return "0006";
		}else{//市政工程
			return "0001";
		}
	}

	private static String getProjectNature(String value){//项目性质
		if("1".equals(value)){//特级
			return "0001";
		}else if("2".equals(value)){//一级
			return "0002";
		}else if("3".equals(value)){//二级
			return "0003";
		}else if("4".equals(value)){//三级
			return "0004";
		}else if("5".equals(value)){//三级
			return "0005";
		}else{//其它
			return "";
		}
	}

	//4.1.1.3.特别约定信息 extendGroupInfoList
	private static void marshalEngageItemList(SpecialBidVo vo, OrderFormVo dto,Element engageItemList){
		engageItemList.addElement("engageCode").setText("T9999");//特别约定代码，针对不同的险种有不同的特约
		engageItemList.addElement("engageTitle").setText("项目工程信息");//特别约定标题，同特别约定代码
		String engage = dto.getInsured_role()+"（以下简称“被保险人”）接受"+dto.getApplicant_name()+"（以下称“投保人”）于"+DateUtil.fomData(dto.getInception_date())+"参加"+dto.getInception_date().split(ConstProp.MINUS)[0]+"年"+vo.getProject_name()+"（项目编号"+vo.getInvitation_code()+"）施工的投标，并向我方投保工程建设项目投标保证保险，保险金额人民币"+dto.getInsured_amount()+"元。";
		engageItemList.addElement("engage").setText(engage);//特别约定内容，系统采用分段存储，理论上可以存很多字符
	}

	//4.1.1.4.投保人信息  marshalHolder
	private static void marshalHolder(SpecialBidVo vo, OrderFormVo dto,Element holder){

		for(RoleSubjectVo roleSubjectVo : vo.getRoleSubjectList()){
			if(!"1".equals(roleSubjectVo.getKind())){
				continue;
			}
			String organizationCode = roleSubjectVo.getOrganization_code();
			if(StringUtils.isNotEmpty(organizationCode) && ConstProp.DIGIT_ONE.equals(roleSubjectVo.getId_type())){
				if(organizationCode.contains(ConstProp.MINUS)){
					organizationCode = organizationCode.split(ConstProp.MINUS)[0]+organizationCode.split(ConstProp.MINUS)[1];
				}
			}
			holder.addElement("name").setText(roleSubjectVo.getName_cn());//公司名称 否
			holder.addElement("idType").setText("99");//证件类型，
			holder.addElement("idNo").setText(organizationCode);//证件号码
			holder.addElement("sex").setText("9");//性别
			holder.addElement("birthday").setText("19900101");//生日
			holder.addElement("relaToInsured").setText("01");//与被保险人的关系
			holder.addElement("email").setText(roleSubjectVo.getLink_email());//邮箱
			holder.addElement("mobile").setText(roleSubjectVo.getLink_tel());//被保险人手机
		}
	}

	//4.1.1.5.被保险人信息  marshalInsureds
	private static void marshalInsureds(SpecialBidVo vo, OrderFormVo dto,Element insured){

		for(RoleSubjectVo roleSubjectVo : vo.getRoleSubjectList()){
			if(!"2".equals(roleSubjectVo.getKind())){
				continue;
			}
			String organizationCode = roleSubjectVo.getOrganization_code();
			if(StringUtils.isNotEmpty(organizationCode) && ConstProp.DIGIT_ONE.equals(roleSubjectVo.getId_type())){
				if(organizationCode.contains(ConstProp.MINUS)){
					organizationCode = organizationCode.split(ConstProp.MINUS)[0]+organizationCode.split(ConstProp.MINUS)[1];
				}
			}
			insured.addElement("name").setText(roleSubjectVo.getName_cn());//公司名称 否
			insured.addElement("idType").setText("99");//证件类型，
			insured.addElement("idNo").setText(organizationCode);//证件号码
			insured.addElement("sex").setText("9");//性别
			insured.addElement("birthday").setText("19900101");//生日
			insured.addElement("relaToInsured").setText("01");//与被保险人的关系
//				insureds.addElement("email",roleSubjectVo.getLink_email());//邮箱
			insured.addElement("mobile").setText(roleSubjectVo.getLink_tel());//被保险人手机
			insured.addElement("mult").setText("1");//投保份数
//				insured.addElement("beneficiarys").setText("");//受益人
		}
	}

	//4.1.1.7.承保险别信息 marshalCoverageList
	private static void marshalCoverageList(SpecialBidVo vo, OrderFormVo dto,Element coverageItem){
		coverageItem.addElement("coverageCode").setText("004");//承保险别代码
		coverageItem.addElement("itemCode").setText("0");//标的物代码
		coverageItem.addElement("itemDetailName").setText(vo.getProject_name()+"（项目编号"+vo.getInvitation_code()+"）");//标的物物明细名称
		coverageItem.addElement("sumLimit").setText(dto.getInsured_amount());//险别保额
		coverageItem.addElement("premuim").setText(dto.getGross_premium());//实收保费
	}

	/**
	 *	接口支付接口返回字符串解析（解析transType=2 返回商户订单编码，transType=3 返回微信支付二维码）
	 * @return
	 */
	public String returnPayAnalysisXML(String xml, String  transType){
		String result = "300#（APP-PAC-001.1）数据处理失败！";
		String msgCode = getDBPayMsgCode(xml);
		if( "000000".equals(msgCode) ? true : false ){
			if(transType.equals(ConstProp.DIGIT_TWO)) {//支付接口步骤一，获取商户订单编号
				//200#商户订单编号#订单总金额
				return "200#"+getDBPayResult(xml);
			}else if(transType.equals(ConstProp.DIGIT_THREE)) {//支付接口步骤二，获取微信支付二维码
				//200#二维码字符流
				return "200#"+getDBPayCode(xml);
			}
		}else{
			if(StringUtils.isNotEmpty(xml)){
				result = "300#（APP-DB-"+msgCode+"）"+getDBPayFailMsg(xml);
			}else{
				result = "300#（APP-DB-001）未获取到返回数据！";
			}
		}
		return result;
	}

	/**
	 * 获得都邦支付相关接口报文解析
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getDBPayResult(String originalXML) {
		String repCode = ConstProp.BLANK_CHAR;
		String prm = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);
			rootElement = requestDocument.getRootElement();
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){
				Element node = (Element) i.next();
				if(!"BODY".equals(node.getName())){
					continue;
				}
				for(Iterator n = node.elementIterator(); n.hasNext();){
					Element node_n = (Element) n.next();
					if(!"ORDERINFO".equals(node_n.getName())){
						continue;
					}
					for(Iterator r = node_n.elementIterator(); r.hasNext();){
						Element node_r = (Element) r.next();
						if("ORDERNO".equals(node_r.getName())){
							repCode = node_r.getText();
						}
						if("SUMPAYFEE".equals(node_r.getName())){
							prm = node_r.getText();
						}
					}
				}
			}
		}catch (Exception e){
			logger.info("isDBPayResult:"+e.getMessage());
		}
		return repCode+ConstProp.POUND_SIGN+prm;
	}
	/**
	 * 获得都邦支付相关接口报文解析
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getDBPayCode(String originalXML) {
		String repCode = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);
			rootElement = requestDocument.getRootElement();
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){
				Element node = (Element) i.next();
				if(!"BODY".equals(node.getName())){
					continue;
				}
				for(Iterator n = node.elementIterator(); n.hasNext();){
					Element node_n = (Element) n.next();
					if(!"ORDERINFO".equals(node_n.getName())){
						continue;
					}
					for(Iterator r = node_n.elementIterator(); r.hasNext();){
						Element node_r = (Element) r.next();
						if("CODEURLBASE64".equals(node_r.getName())){
							repCode = node_r.getText();
							break;
						}
					}
				}
			}
		}catch (Exception e){
			logger.info("isDBPayCode:"+e.getMessage());
		}
		return repCode;
	}

	/**
	 * 获得都邦返回报文是否成功
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getDBPayMsgCode(String originalXML) {
		String repCode = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);
			rootElement = requestDocument.getRootElement();
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){
				Element node = (Element) i.next();
				if(!"HEAD".equals(node.getName())){
					continue;
				}
				for(Iterator n = node.elementIterator(); n.hasNext();){
					Element node_n = (Element) n.next();
					if("ERROR_CODE".equals(node_n.getName())){
						repCode = node_n.getText().replace("<![CDATA[","").replace("]]>","").trim();
						break;
					}
				}
			}
		}catch (Exception e){
			logger.info("isDBPaySuccess:"+e.getMessage());
		}
		return repCode;
	}

	/**
	 * 获得都邦返回失败的消息
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getDBPayFailMsg(String originalXML) {
		String repCode = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);
			rootElement = requestDocument.getRootElement();
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){
				Element node = (Element) i.next();
				if(!"HEAD".equals(node.getName())){
					continue;
				}
				for(Iterator n = node.elementIterator(); n.hasNext();){
					Element node_n = (Element) n.next();
					if("ERROR_MESSAGE".equals(node_n.getName())){
						repCode = node_n.getText().replace("<![CDATA[","").replace("]]>","").trim();
						break;
					}
				}
			}
		}catch (Exception e){
			logger.info("getDBPayFailMsg:"+e.getMessage());
		}
		return repCode;
	}

	/**
	 *	接口返回字符串解析
	 * @return
	 */
	public String returnAnalysisXML(String xml, String  transType){
		String result = "300#（APP-PAC-001.1）数据处理失败！";
		String msgCode = getDBMsgCode(xml);
		if( !ConstProp.DIGIT_ZERO.equals(msgCode)){
			if(StringUtils.isNotEmpty(xml)){
				return "300#（APP-DB-"+msgCode+"）"+getDBFailMsg(xml);
			}else{
				return "300#（APP-DB-001）未获取到返回数据！";
			}
		}
		if(transType.equals(ConstProp.DIGIT_ONE)) {
			//核保，承保统一一个接口
			//200#投保单号#保单号
			return getDBResult(xml);
		}else if(transType.equals(ConstProp.DIGIT_THREE)) {
			//获取电子保单文件流   返回值
			String filePath = uploadFile("文件字符流","/build-db/");
			if(StringUtils.isNotEmpty(filePath)){
				return "200#"+filePath;
			}else{
				return "300#（APP-DB-002）电子保单打印文件流解析失败！";
			}
		}
		return result;
	}

	/**
	 * 获得都邦返回报文是否成功
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getDBMsgCode(String originalXML) {
		String repCode = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);
			rootElement = requestDocument.getRootElement();
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){
				Element node = (Element) i.next();
				if(!"body".equals(node.getName())){
					continue;
				}
				for(Iterator n = node.elementIterator(); n.hasNext();){
					Element node_n = (Element) n.next();
					if("resultcode".equals(node_n.getName())){
						repCode = node_n.getText();
						break;
					}
				}
			}
		}catch (Exception e){
			logger.info("isDBSuccess:"+e.getMessage());
		}
		return repCode;
	}

	/**
	 * 获得都邦返回核保成功的报文信息，200#投保单号#保单号
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getDBResult(String originalXML) {
		String repCode = "200#";
		String policyno = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);
			rootElement = requestDocument.getRootElement();
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){
				Element node = (Element) i.next();
				if(!"body".equals(node.getName())){
					continue;
				}
				for(Iterator n = node.elementIterator(); n.hasNext();){
					Element node_n = (Element) n.next();
					if("policyInfo".equals(node_n.getName())){
						for(Iterator r = node_n.elementIterator(); r.hasNext();) {
							Element node_r = (Element) r.next();
							if ("serialNumber".equals(node_r.getName())) {
								repCode = repCode + node_r.getText() + ConstProp.POUND_SIGN;
								break;
							}
						}
					}
					if ("policyno".equals(node_n.getName())) {
						policyno = node_n.getText();
					}
				}
			}
		}catch (Exception e){
			logger.info("isDBSuccess:"+e.getMessage());
		}
		return repCode+policyno;
	}

	/**
	 * 获得都邦返回失败的消息
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getDBFailMsg(String originalXML) {
		String repCode = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);
			rootElement = requestDocument.getRootElement();
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){
				Element node = (Element) i.next();
				if("body".equals(node.getName())){
					for(Iterator n = node.elementIterator(); n.hasNext();){
						Element node_n = (Element) n.next();
						if("errordesc".equals(node_n.getName())){
							repCode = node_n.getText();
							System.out.println(repCode);
							break;
						}
					}
				}
			}
		}catch (Exception e){
			logger.info("getDBFailMsg:"+e.getMessage());
		}
		return repCode;
	}




	/**
	 * 文件上传并返回下载地址
	 * @param fileStr 字符串文件流
	 * @param savePath 文件要保存的文件夹地址（/zzx-pac/）
	 * @return /getResource?path=/policy/1231231.jpg
	 */
	public static String uploadFile(String fileStr, String savePath){
		String result = "";
		if (StringUtils.isNotEmpty(fileStr)) {
			try {
				byte[] bytes = BASE64Util.decryptBASE64Byte(fileStr);
				String files = DateUtil.generatorRadomNumber() + ".pdf";
				result = savePath + files;
				String path = GlobalResources.COM_IMG_RE+savePath;
				FileHelp.byteFile(bytes, path, files);
				result = "/getResource?path="+result;
			} catch (Exception e) {
				e.printStackTrace();
				result = "";
			}
		}
		return result;
	}









	public static void main(String[] args){

		doResultCheDan();

	}

	private static void doResultCheDan() {
		//        String  resultMsg= "{\"header\":{\"transactionCode\":\"TCEGISNBUAPC001\",\"partnerId\":\"PCXM001\",\"requestId\":\"1493874890537\",\"code\":\"NBUERROR_0008\",\"message\":\"{\\\"ReturnFlag\\\":1,\\\"ResponseMsg\\\":\\\"系统生成保益保费之和510元与总单保费390元不符;\\\"}\"},\"body\":null}";
		String   resultMsg="{\"header\":{\"transactionCode\":\"TCEGISNBUWD001\",\"partnerId\":\"PCXM001\",\"requestId\":\"1493865755617\",\"code\":\"CRIGHT_0000\",\"message\":null},\"body\":\"\\\"{\\\\\\\"errorMessage\\\\\\\":\\\\\\\"fail\\\\\\\",\\\\\\\"rcptnoList\\\\\\\":[{\\\\\\\"message\\\\\\\":\\\\\\\"条形码9041K009837424的业务状态不允许进行撤件\\\\\\\",\\\\\\\"no\\\\\\\":\\\\\\\"30000070075776495\\\\\\\"}],\\\\\\\"resultFlag\\\\\\\":\\\\\\\"-1\\\\\\\"}\\\"\"}";
		Map<String, Object> map = null;
		try{
			map = JSON.parseObject(resultMsg,Map.class);
			Map<String, Object> header = JSON.parseObject( map.get("header").toString(),Map.class);
			if(header.get("code").equals("CRIGHT_0000")){
				//返回成功
				String  bodyStr= map.get("body").toString();
				bodyStr=bodyStr.replaceFirst("\"",ConstProp.BLANK_CHAR);
				bodyStr=bodyStr.substring(ConstProp.INT_NUMBER_ZERO,bodyStr.lastIndexOf('"'));
				bodyStr = bodyStr.replace("\\", ConstProp.BLANK_CHAR);
				Map<String, Object> body = JSON.parseObject(bodyStr,Map.class);
				if(body.get("resultFlag").toString().equals(ConstProp.DIGIT_ZERO)){
					String errorMessage=body.get("errorMessage").toString();
					logger.info("200#"+errorMessage);
				}else{
				   JSONArray array= JSON.parseArray(body.get("rcptnoList").toString());
					String  result =ConstProp.BLANK_CHAR;
					for(int i=ConstProp.INT_NUMBER_ZERO;i<array.size();i++){
						com.alibaba.fastjson.JSONObject object = (com.alibaba.fastjson.JSONObject) array.get(i);
						result=result+ConstProp.POUND_SIGN+object.get("message")+ConstProp.POUND_SIGN+object.get("no");
					}
					String   errorMessage =body.get("resultFlag").toString();
					logger.info("300"+result);
				}
			}else{
				logger.info("300#撤单失败");
			}
		}catch(Exception e){

			e.printStackTrace();
		}
 	}

}
