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

import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.service.order.ComTaskUnSeeFeeRecordAPIService;
import com.bcxin.ins.spring.util.SpringContextHolder;
import com.bcxin.ins.util.*;
import com.bcxin.ins.vo.*;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.util.*;

/**
 * <b> 中华-雇主责任险各接口请求数据组装 </b>
 * @author ZXF
 * @create 2019/02/18 0024 9:50
 * @version
 * @注意事项 </b>
 */
public class GZZRX_PackageMessageZhongHua {

	private static ComTaskUnSeeFeeRecordAPIService comTaskUnSeeFeeRecordAPIService = SpringContextHolder.getBean(ComTaskUnSeeFeeRecordAPIService.class);

	protected Document requestDocument;
	protected Element rootElement;

	void GZZRX_PackageMessageZhongHua(){

	}

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

	private static String PARTNERCODE = "BCXWL";
	private static String PARTNERSUBCODE = "BCXWL";

	public static void main(String[] args) {
		/*String a = "<ReturnInfo>\n" +
				"  <responsehead>\n" +
				"    <uuid>d1d0feca-7c13-42c7-b5a6-20d45dd987e6</uuid>\n" +
				"    <timestamp>2018-08-02 14:28:45</timestamp>\n" +
				"    <request__type>01020233</request__type>\n" +
				"    <response__code>1</response__code>\n" +
				"    <server__version>00000000</server__version>\n" +
				"    <sender>0102</sender>\n" +
				"    <error__message></error__message>\n" +
				"  </responsehead>\n" +
				"  <policyInfoReturns>\n" +
				"    <PolicyInfoReturn>\n" +
				"      <serialNo>1</serialNo>\n" +
				"      <proposalNo>DZBV201835020000003720</proposalNo>\n" +
				"      <result>1</result>\n" +
				"      <message>批单申请号为DZBV201835020000003720自动核批成功,批单号为：EZBV201835020000003569</message>\n" +
				"      <chgSumPremium>-66.00</chgSumPremium>\n" +
				"    </PolicyInfoReturn>\n" +
				"  </policyInfoReturns>\n" +
				"</ReturnInfo>";
		String r = "批单申请号为DZBV201835020000003720自动核批成功,批单号为：EZBV201835020000003569";
		System.out.println(r.split("：")[1]);*/

	}

	/**
	 * 核保数据组装
	 * @param vo 投保详细信息
	 * @param dto 订单基本信息
	 * @param transType 接口类型
	 * @param iprVo 保全申请单
	 * @return
	 */
	public static String marshal(SpecialHirelingVo vo, OrderFormVo dto, String transType, InsPreservationRecordVo iprVo){
		String result = ConstProp.BLANK_CHAR;
		Document requestDocument = DocumentHelper.createDocument();
		requestDocument.setXMLEncoding("GBK");//设置该XML文件的Encoding = "GBK"
		Element insureq_info_element = requestDocument.addElement("INSUREQ");
		try {
			if(TransTypeEnum.HB.getValue().equals(transType)){//核保
				//头
				Element head_info_element = insureq_info_element.addElement("HEAD");
				head(head_info_element, dto);
				//主
				Element main_info_element = insureq_info_element.addElement("MAIN");
				setTaxpayerNumber(vo);
				main(main_info_element, dto, vo.getMailPolicyVo());
				//内容列
				Element body_infos_element = insureq_info_element.addElement("BODY");
				//基本信息
				Element base_info_element = body_infos_element.addElement("BASE");
				baseInfo(base_info_element, vo, dto);
				//标的信息
				Element tgt_info_element = body_infos_element.addElement("TGT");
				//投保人数
				tgt_info_element.addElement("INSURANCE").setText(String.valueOf(vo.getHirelingVoList().size()));
				//清单信息
				Element tgtobj_info_element = body_infos_element.addElement("TGTOBJ");
				employees(tgtobj_info_element, vo.getHirelingVoList(), vo.getRoleSubjectList().get(0));
				//险别信息
				Element rdr_info_element = body_infos_element.addElement("RDR");
				rdr(rdr_info_element, vo);

				result = requestDocument.asXML();
			}else if(TransTypeEnum.ZFDZ.getValue().equals(transType)){//获取支付地址
				//头
				Element head_info_element = insureq_info_element.addElement("HEAD");
				head_info_element.addElement("TRANSRNO").setText("1000");//交易码 支付申请
				head_info_element.addElement("PARTNERCODE").setText(PARTNERCODE);//合作伙伴代码
				head_info_element.addElement("PARTNERSUBCODE").setText(PARTNERSUBCODE);//合作伙伴子机构代码
				//主
				Element main_info_element = insureq_info_element.addElement("MAIN");
				//基本信息
				Element base_info_element = main_info_element.addElement("BASE");
				base_info_element.addElement("SERIALNUMBER").setText("ZHPAY"+String.valueOf(dto.getTrade_serial_number()));//交易流水号
				DateFormat dateFormatAll = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				base_info_element.addElement("TRANSDATE").setText(dateFormatAll.format(new Date()));//交易时间
				base_info_element.addElement("PAYTYPE").setText("pc");//支付类型
				String returnUrl = GlobalResources.DONOW_PATH+"api/gzzrx/syntony-service/"+dto.getOid();
				if(ConstProp.BLB.equals(dto.getWeb_type())){
					returnUrl = GlobalResources.WEB_URL+"/insurance/gzzrx/transaction/syntony-service/"+dto.getOid();
				}
				base_info_element.addElement("PAGERETURL").setText(returnUrl);//网页回调地址
				base_info_element.addElement("TOTALPREMIUN").setText(dto.getGross_premium());//总保费
				base_info_element.addElement("SYSTYPE").setText("");//应用类型
				//基本信息
				Element policylist_info_element = main_info_element.addElement("POLICYLIST");
				Element policy_info_element = policylist_info_element.addElement("POLICY");
				policy_info_element.addElement("APPNO").setText(dto.getPolicy_serial_number());//投保单号
				result = requestDocument.asXML();
			}else if(TransTypeEnum.ZFJG.getValue().equals(transType)){//获取结果获取
				//头
				Element head_info_element = insureq_info_element.addElement("HEAD");
				head_info_element.addElement("TRANSRNO").setText("1001");//交易码 支付申请
				head_info_element.addElement("PARTNERCODE").setText(PARTNERCODE);//合作伙伴代码
				head_info_element.addElement("PARTNERSUBCODE").setText(PARTNERSUBCODE);//合作伙伴子机构代码
				//主
				Element main_info_element = insureq_info_element.addElement("MAIN");
				//基本信息
				Element base_info_element = main_info_element.addElement("BASE");
				base_info_element.addElement("SERIALNUMBER").setText("ZHPAY"+String.valueOf(dto.getTrade_serial_number()));//交易流水号
				DateFormat dateFormatAll = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				base_info_element.addElement("TRANSDATE").setText(dateFormatAll.format(new Date()));//交易时间
				base_info_element.addElement("PAYID").setText(dto.getNotice_no());//支付id
				result = requestDocument.asXML();
			}else if(TransTypeEnum.PD.getValue().equals(transType)){//保单批改
				//头
				Element head_info_element = insureq_info_element.addElement("HEAD");
				head_info_element.addElement("TRANSRNO").setText("2014");//交易码
				head_info_element.addElement("PARTNERCODE").setText(PARTNERCODE);//合作伙伴代码
				head_info_element.addElement("PARTNERSUBCODE").setText(PARTNERSUBCODE);//合作伙伴子机构代码
				//主
				Element main_info_element = insureq_info_element.addElement("MAIN");
				pd_main(main_info_element,iprVo,dto);
				//清单信息
				Element tgtobj_element = main_info_element.addElement("TGTOBJ");
				pd_employees(tgtobj_element,iprVo,dto);
				//清单信息
				Element tgt_element = main_info_element.addElement("TGT");
				tgt_element.addElement("INSURANCE").setText(String.valueOf(iprVo.getInsPreservationDetailVoList().size()));//投保人数
				result = requestDocument.asXML();
			}else if(TransTypeEnum.DZFP.getValue().equals(transType)){//申请电子发票请求报文节点组装
				//头
				Element head_info_element = insureq_info_element.addElement("HEAD");
				head_info_element.addElement("TRANSRNO").setText("PS009");//交易码 支付申请
				head_info_element.addElement("PARTNERCODE").setText(PARTNERCODE);//合作伙伴代码
//				head_info_element.addElement("PARTNERSUBCODE").setText(PARTNERSUBCODE);//合作伙伴子机构代码
				//主
				Element main_info_element = insureq_info_element.addElement("MAIN");
				MailPolicyVo mvo = vo.getMailPolicyVo();
				IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
				main_info_element.addElement("SERIALNUMBER").setText("ZHFP"+String.valueOf(idWorker.nextId()));//交易流水号
				DateFormat dateFormatAll = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				main_info_element.addElement("TRANSRDATE").setText(dateFormatAll.format(new Date()));//交易时间
				main_info_element.addElement("POLNO").setText(dto.getExternal_reference());//保单号
				main_info_element.addElement("BUYERNAME").setText(mvo.getReceipt_head());//开票对象名称
				main_info_element.addElement("BUYERNO").setText(mvo.getTaxpayer_number_invoice());//税号
				main_info_element.addElement("MOBILE").setText(mvo.getTaker_mobile());//手机号
				result = requestDocument.asXML();
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * <b> 设置发票税号为空就默认取企业证件号 </b>
	 * @author ZXF
	 * @create 2020/09/29 0029 17:23
	 * @version
	 * @注意事项 </b>
	 */
	private static void setTaxpayerNumber(SpecialHirelingVo vo) {
		if(StringUtils.isNotEmpty(vo.getMailPolicyVo().getTaxpayer_number_invoice())){
			return;
		}
		try{
			String organizationCode = vo.getRoleSubjectList().get(0).getOrganization_code();
			if(StringUtils.isNotEmpty(organizationCode) && ConstProp.DIGIT_ONE.equals(vo.getRoleSubjectList().get(0).getId_type())){
				if(organizationCode.contains(ConstProp.MINUS)){
					organizationCode = organizationCode.split(ConstProp.MINUS)[0]+organizationCode.split(ConstProp.MINUS)[1];
				}
			}
			vo.getMailPolicyVo().setTaxpayer_number_invoice(organizationCode);
		}catch (Exception e){

		}
	}

	//头信息
	private static void head(Element underwrite, OrderFormVo dto) {
		//交易码
		underwrite.addElement("TRANSRNO").setText("2011");//投保接口
		//合作伙伴代码
		underwrite.addElement("PARTNERCODE").setText(PARTNERCODE);
		//合作伙伴子机构代码
		underwrite.addElement("PARTNERSUBCODE").setText(PARTNERSUBCODE);
		//是否异步模式
		underwrite.addElement("ASYNC").setText("0");
	}

	//主信息
	private static void main(Element underwrite, OrderFormVo dto,MailPolicyVo mvo) {
		//投保方案类别
		underwrite.addElement("PRODTYPE").setText("043U");
		//方案代码
		underwrite.addElement("PRODUCTCODE").setText(getProductCode(dto.getProduct_code()));
		//交易流水号
		underwrite.addElement("SERIALNUMBER").setText(dto.getTrade_serial_number());
		//交易时间
		DateFormat dateFormatAll = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		underwrite.addElement("TRANSRDATE").setText(dateFormatAll.format(new Date()));
		//是否电子发票 0.否；1.是
		underwrite.addElement("IS_SEND_EINVOICE").setText(StringUtils.isEmpty(mvo.getIs_send_einvoice())?"0":mvo.getIs_send_einvoice());
		//购买方纳税人识别号
		underwrite.addElement("C_BUYER_NO").setText(StringUtils.isNotEmpty(mvo.getTaxpayer_number_invoice())?mvo.getTaxpayer_number_invoice():"");
	}

	private static String getProductCode(String code){
		if("GZZRX-ZH-1".equals(code)){
			return "B0469";
		}else if("GZZRX-ZH-2".equals(code)){
			return "B0470";
		}else if("GZZRX-ZH-3".equals(code)){
			return "B0471";
		}else if("GZZRX-ZH-4".equals(code)){
			return "B0472";
		}else if("GZZRX-ZH-5".equals(code)){
			return "B0473";
		}else if("GZZRX-ZH-6".equals(code)){
			return "B0474";
		}else if("GZZRX-ZH-7".equals(code)){
			return "B0475";
		}else if("GZZRX-ZH-8".equals(code)){
			return "B0476";
		}else if("GZZRX-ZH-9".equals(code)){
			return "B0477";
		}else{
			return "";
		}
	}

	//险别信息
	private static void rdr(Element underwrite, SpecialHirelingVo vo) {
		boolean icr = "1".equals(vo.getIs_contain_repo());//是否含三者
		Element element_0 = underwrite.addElement("RDR_LIST");
		element_0.addElement("RISKCODE").setText("043U01");//险别代码，基础
		Element element_1 = underwrite.addElement("RDR_LIST");
		element_1.addElement("RISKCODE").setText("043U12");//
		Element element_2 = underwrite.addElement("RDR_LIST");
		element_2.addElement("RISKCODE").setText("043U14");//
		if(icr){
			Element element_3 = underwrite.addElement("RDR_LIST");
			element_3.addElement("RISKCODE").setText("043U11");//险别代码，含三者
		}
	}

	//基本信息 policyInfo
	private static void baseInfo(Element policyInfo, SpecialHirelingVo vo, OrderFormVo dto){
		RoleSubjectVo roleSubjectVo = vo.getRoleSubjectList().get(0);
//		HirelingVo hirelingVo = vo.getHirelingVoList().get(0);
		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];
			}
		}
		policyInfo.addElement("TBRNAME").setText(roleSubjectVo.getName_cn());//公司名称 否
		policyInfo.addElement("TBRIDTYPE").setText(changeCTypeCom(roleSubjectVo.getId_type()));//证件类型，
		policyInfo.addElement("TBRIDNO").setText(organizationCode);//证件号码
		policyInfo.addElement("TBRTEL").setText(roleSubjectVo.getLink_tel());//投保人联系人电话
		String address = RegionUtils.getRegionNameByALLCode(roleSubjectVo.getReg_province(),roleSubjectVo.getReg_city(),roleSubjectVo.getReg_district())+roleSubjectVo.getReg_address();
		policyInfo.addElement("TBRADDR").setText(address);//投保人地址
		policyInfo.addElement("TBREMAIL").setText(roleSubjectVo.getLink_email());//投保人邮箱
		policyInfo.addElement("BBRNAME").setText(roleSubjectVo.getName_cn());//被保险人姓名
		policyInfo.addElement("BBRIDTYPE").setText(changeCTypePer(roleSubjectVo.getId_type()));//被保人证件类型
		policyInfo.addElement("BBRIDNO").setText(organizationCode);//被保人证件号码
		policyInfo.addElement("BBRADDR").setText(address);//被保险人地址
		policyInfo.addElement("BBRTEL").setText(roleSubjectVo.getLink_tel());//被保险人联系人电话
		policyInfo.addElement("EFFDATE").setText(dto.getInception_date()+" 00:00:00");//起保日期
		policyInfo.addElement("TERMDATE").setText(dto.getPlanned_end_date()+" 23:59:59");//终保日期
		policyInfo.addElement("PREMIUM").setText(dto.getGross_premium());//总保费
	}

	//雇员信息列信息  employees
	private static void employees(Element employees, List<HirelingVo> hvoList, RoleSubjectVo appliVo){
		for(HirelingVo vo : hvoList){
			Element employee = employees.addElement("TGTOBJ_LIST");
			employee.addElement("NAME").setText(vo.getName());//名称 否
			employee.addElement("IDNO").setText(vo.getId_card());//证件号码
			employee.addElement("SEX").setText(vo.getSex());//性别
		}
	}

	//企业证件类型编码转换
	private static String changeCTypeCom(String c_t){
		if("1".equals(c_t)){//组织机构代码
			return "464004";
		}else if("2".equals(c_t)){//统一社会代码
			return "464007";
		}else{//其它
			return "464003";
		}
	}

	//个人证件类型编码转换
	private static String changeCTypePer(String c_t){
		if("0".equals(c_t)){//身份证
			return "464001";
		}else if("3".equals(c_t)){//护照
			return "464002";
		}else{//其它
			return "464003";
		}
	}

	private static void setPrp(Element underwrite, InsPreservationDetailVo ipdVo, String tp, String sn){
		Element prp_cname_element = underwrite.addElement("PrpCname");
		Element id_element = prp_cname_element.addElement("id");
		//序列号
		id_element.addElement("serialNo").setText(sn);
		//雇员姓名
		prp_cname_element.addElement("employeeName").setText(ipdVo.getName());
		//性别
		prp_cname_element.addElement("sex").setText(ipdVo.getSex());
		//职业代码
		prp_cname_element.addElement("jobCode").setText("026");
		//证件号码
		prp_cname_element.addElement("identifyNumber").setText(ipdVo.getId_card());
		//批改标志（I:表示批增，U表示修改，D:表示批减）
		prp_cname_element.addElement("flag").setText(tp);
		//证件类型
		prp_cname_element.addElement("kindName").setText(changeCTypePer(ipdVo.getId_type()));
	}

	/**
	 * <b> 批单主体信息 </b>
	 * @author ZXF
	 * @create 2019/09/25 0025 15:49
	 * @version
	 * @注意事项 </b>
	 */
	private static void pd_main(Element underwrite, InsPreservationRecordVo iprVo, OrderFormVo dto){
		underwrite.addElement("SERIALNUMBER").setText(iprVo.getRevise_serial_number());//交易流水号
		underwrite.addElement("TRANSRDATE").setText(iprVo.getStart_time());//交易时间 yyyy-mm-dd hh:mm:ss
		underwrite.addElement("POLNO").setText(dto.getExternal_reference());//保单号
		underwrite.addElement("PREMIUM").setText(iprVo.getTotal_premium());//总保费
		underwrite.addElement("PRODTYPE").setText("043U");//产品类型
		underwrite.addElement("JYLX").setText("14");//交易类型 0：保单注销；1：保单退保；4：一般批改；14：清单批改；99：综合批改；不传或为空都为保单注销
		/*
		* 00：批减清单信息；01：批增清单信息；02：批换清单信息 （当批改类型为14，且需要批增批减清单时，必传）
		* 当批改原因子项为：00-批减清单信息时，则被保险人人员清单数量减少；
		* 当批改原因子项为：01-批增清单信息时，则被保险人人员清单数量增加。
		* */
		underwrite.addElement("JYLXZX").setText(getReviseType(iprVo.getRevise_type()));//交易类型子项
	}

	/**
	 * <b> 匹配批改类型编码 </b>
	 * @author ZXF
	 * @create 2019/09/25 0025 16:14
	 * @version
	 * @注意事项 </b>
	 */
	private static String getReviseType(String type){
		if(DictConst.REVISE_TYPE_Z.equals(type)){
			return "01";
		}else if(DictConst.REVISE_TYPE_J.equals(type)){
			return "00";
		}else if(DictConst.REVISE_TYPE_T.equals(type)){
			return "02";
		}else{
			return "";
		}
	}

	/**
	 * <b> 批单人员清单 </b>
	 * @author ZXF
	 * @create 2019/09/25 0025 15:52
	 * @version
	 * @注意事项 </b>
	 */
	private static void pd_employees(Element underwrite, InsPreservationRecordVo vo, OrderFormVo dto){
		int count = 1;
		for(InsPreservationDetailVo ipdVo : vo.getInsPreservationDetailVoList()){
			if(ConstProp.DIGIT_THREE.equals(vo.getRevise_type())){//替换(将记录拆成2份，一增一减)
				setPrp_043U( underwrite, ipdVo.getName(), ipdVo.getId_card(),ipdVo.getBusiness_vo().getId_card(), ipdVo.getSex(), String.valueOf(count));
			}else{
				setPrp_043U( underwrite, ipdVo.getName(), ipdVo.getId_card(),ConstProp.BLANK_CHAR, ipdVo.getSex(), String.valueOf(count));
			}
			count ++;
		}
	}

	private static void setPrp_043U(Element underwrite, String name, String nIdCard, String oIdCard, String sex, String sn){
		Element employee = underwrite.addElement("TGTOBJ_LIST");
//		employee.addElement("NSEQNO").setText(sn);//序号
		employee.addElement("NAME").setText(name);//名称
		employee.addElement("IDNO").setText(nIdCard);//证件号码
		if(StringUtils.isNotEmpty(oIdCard)){
			employee.addElement("OLDIDNO").setText(oIdCard);//原证件号码
		}
		employee.addElement("SEX").setText(sex);//性别
	}

	/**
	 * 获得核保接口返回报文解析
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getHBResult(String originalXML) {
		String code = ConstProp.BLANK_CHAR;
		String msg = ConstProp.BLANK_CHAR;
		String appno = ConstProp.BLANK_CHAR;
		String polno = ConstProp.BLANK_CHAR;
		String eurl = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){//遍历rootElement直到没有节点时结束
				Element node = (Element) i.next();
				if("HEAD".equals(node.getName())){
					for(Iterator r = node.elementIterator(); r.hasNext();){
						Element node_r = (Element) r.next();
						if("RESULTCODE".equals(node_r.getName())){
							code = node_r.getText();
						}
						if("ERRINFO".equals(node_r.getName())){
							msg = node_r.getText();
						}
					}
					if(!"0000".equals(code)){
						return "300#"+msg;
					}
				}
				if(!"MAIN".equals(node.getName())){
					continue;
				}
				for(Iterator r = node.elementIterator(); r.hasNext();){//遍历节点直到结束
					Element node_r = (Element) r.next();
					if("APPNO".equals(node_r.getName())){
						appno = node_r.getText();
						if(StringUtils.isEmpty(appno)){
							return "300#解析结果：缺少投保单号";
						}
					}
					if("POLNO".equals(node_r.getName())){
						polno = node_r.getText();
					}
					if("EURL".equals(node_r.getName())){
						eurl = node_r.getText();
						if(StringUtils.isNotEmpty(eurl)){
							eurl = eurl.replace("<![CDATA[","").replace("]]>","").trim();
						}
					}
				}
				if(StringUtils.isEmpty(appno)){
					continue;
				}
				if(StringUtils.isNotEmpty(polno)&&StringUtils.isNotEmpty(eurl)){
					//核保返回报文添加到未见费核保记录表
					comTaskUnSeeFeeRecordAPIService.saveComTaskUnSeeFeeRecord(appno,polno,eurl);
				}
				return "200#"+appno;
			}
		}catch (Exception e){
			logger.info("getHBResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 批单报文解析 </b>
	 * @author ZXF
	 * @create 2019/10/22 0022 14:52
	 * @version
	 * @注意事项 </b>
	 */
	private String getPDResult(String originalXML) {
		String code = ConstProp.BLANK_CHAR;
		String msg = ConstProp.BLANK_CHAR;
		String polno = ConstProp.BLANK_CHAR;//保单号
		String edrno = ConstProp.BLANK_CHAR;//批单号
		String bpremium = ConstProp.BLANK_CHAR;//变化保费
		String tbsxsj = ConstProp.BLANK_CHAR;//退保时间
		String eurl = ConstProp.BLANK_CHAR;//电子批单
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){//遍历rootElement直到没有节点时结束
				Element node = (Element) i.next();
				if("HEAD".equals(node.getName())){
					for(Iterator r = node.elementIterator(); r.hasNext();){
						Element node_r = (Element) r.next();
						if("RESULTCODE".equals(node_r.getName())){
							code = node_r.getText();
						}
						if("ERRINFO".equals(node_r.getName())){
							msg = node_r.getText();
						}
					}
					if(!"0000".equals(code)){
						return "300#"+msg;
					}
				}
				if(!"MAIN".equals(node.getName())){
					continue;
				}
				for(Iterator r = node.elementIterator(); r.hasNext();){//遍历节点直到结束
					Element node_r = (Element) r.next();
					if("POLNO".equals(node_r.getName())){
						polno = node_r.getText();
					}
					if("EDRNO".equals(node_r.getName())){
						edrno = node_r.getText();
					}
					if("BPREMIUM".equals(node_r.getName())){
						bpremium = node_r.getText();
					}
					if("TBSXSJ".equals(node_r.getName())){
						tbsxsj = node_r.getText();
					}
					if("EURL".equals(node_r.getName())){
						eurl = node_r.getText();
						if(StringUtils.isNotEmpty(eurl)){
							eurl = eurl.replace("<![CDATA[","").replace("]]>","").trim();
						}
					}
				}
				//200#保单号#批单号#保费#退保生效日期#电子批单
				return "200#"+polno+"#"+edrno+"#"+bpremium+"#"+tbsxsj+"#"+eurl;
			}
		}catch (Exception e){
			logger.info("getPDResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 电子发票申请返回报文解析 </b>
	 * @author ZXF
	 * @create 2019/09/29 0029 10:25
	 * @version
	 * @注意事项 </b>
	 */
	private String getFPResult(String originalXML) {
		String code = ConstProp.BLANK_CHAR;
		String msg = ConstProp.BLANK_CHAR;
		String serialNumber = ConstProp.BLANK_CHAR;//交易流水
		String invoiceurl = ConstProp.BLANK_CHAR;//电子发票地址
		try {
			//解析XML文件
			requestDocument = DocumentHelper.parseText(originalXML);
			//获取xml文件中的节点
			rootElement = requestDocument.getRootElement();
			//遍历rootElement直到没有节点时结束
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){
				Element node = (Element) i.next();
				if("HEAD".equals(node.getName())){
					for(Iterator r = node.elementIterator(); r.hasNext();){
						Element node_r = (Element) r.next();
						if("RESULTCODE".equals(node_r.getName())){
							code = node_r.getText();
						}
						if("ERRINFO".equals(node_r.getName())){
							msg = node_r.getText();
						}
					}
					if(!"0000".equals(code)&&!"0001".equals(code)){
						return "300#"+msg;
					}
				}
				if(!"MAIN".equals(node.getName())){
					continue;
				}
				for(Iterator r = node.elementIterator(); r.hasNext();){
					Element node_r = (Element) r.next();
					if("SERIALNUMBER".equals(node_r.getName())){//发票流水号：前4位唯一标识+订单号（订单流水号）
						serialNumber = node_r.getText();
					}
					if("INVOICEURL".equals(node_r.getName())){
						invoiceurl = node_r.getText();
						if(StringUtils.isNotEmpty(invoiceurl)){
							invoiceurl = invoiceurl.replace("<![CDATA[","").replace("]]>","").trim();
						}
					}
				}
				if(StringUtils.isNotEmpty(serialNumber)){
					//200#电子发票地址
					return "200#"+invoiceurl;
				}
				if(StringUtils.isEmpty(msg)){
					msg = "解析数据丢失";
				}
				return "300#"+msg;
			}
		}catch (Exception e){
			logger.info("getFPResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * 获得支付信息回调报文解析
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getRBHDCBResult(String originalXML) {
		String code = ConstProp.BLANK_CHAR;
		String msg = ConstProp.BLANK_CHAR;
		String proposalNo = ConstProp.BLANK_CHAR;
		String policyNo = ConstProp.BLANK_CHAR;
		String policyDownUrl = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);
			rootElement = requestDocument.getRootElement();
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){
				Element node = (Element) i.next();
				if(!"PolicyInfos".equals(node.getName())){
					continue;
				}
				for(Iterator r = node.elementIterator(); r.hasNext();){
					Element node_r = (Element) r.next();
					if(!"PolicyInfo".equals(node_r.getName())){
						continue;
					}
					for(Iterator t = node_r.elementIterator(); t.hasNext();){
						Element node_t = (Element) t.next();
						if("Result".equals(node_t.getName())){
							code = node_t.getText();
						}
						if("PolicyNo".equals(node_t.getName())){
							//保单号
							policyNo = node_t.getText();
						}
						if("Message".equals(node_t.getName())){
							msg = node_t.getText();
						}
						if("ProposalNo".equals(node_t.getName())){
							//投保单号
							proposalNo = node_t.getText();
						}
						if("PolicyDownUrl".equals(node_t.getName())){
							//电子保单地址
							policyDownUrl = node_t.getText();
						}
					}
					if(!"0".equals(code)&&!"1".equals(code)){
						if(StringUtils.isEmpty(msg)){
							msg = "解析数据丢失";
						}
						return "300#"+msg;
					}else{
						//重新保存并生成下载地址（保存原文件到我们平台，生成我们平台的访问地址）
						policyDownUrl = unloading_bd(policyNo, policyDownUrl);
						//200#投保单号#保单号#电子保单地址
						return "200#"+proposalNo+ConstProp.POUND_SIGN+policyNo+ConstProp.POUND_SIGN+policyDownUrl;
					}
				}
			}
		}catch (Exception e){
			logger.info("getRBHDCBResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * 获得支付地址报文解析
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getZFDZResult(String originalXML) {
		String code = ConstProp.BLANK_CHAR;
		String msg = ConstProp.BLANK_CHAR;
		String payLink = ConstProp.BLANK_CHAR;
		String payNo = ConstProp.BLANK_CHAR;
		try {
			//解析XML文件
			requestDocument = DocumentHelper.parseText(originalXML);
			//获取xml文件中的节点
			rootElement = requestDocument.getRootElement();
			//遍历rootElement直到没有节点时结束
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){
				Element node = (Element) i.next();
				if("HEAD".equals(node.getName())){
					for(Iterator r = node.elementIterator(); r.hasNext();){
						Element node_r = (Element) r.next();
						if("RESULTCODE".equals(node_r.getName())){
							code = node_r.getText();
						}
						if("ERRINFO".equals(node_r.getName())){
							msg = node_r.getText();
						}
					}
					if(!"0000".equals(code)){
						return "300#"+msg;
					}
				}
				if(!"MAIN".equals(node.getName())){
					continue;
				}
				for(Iterator r = node.elementIterator(); r.hasNext();){
					Element node_r = (Element) r.next();
					if(!"BASE".equals(node_r.getName())){
						continue;
					}
					for(Iterator t = node_r.elementIterator(); t.hasNext();){
						Element node_t = (Element) t.next();
						if("PAYURL".equals(node_t.getName())){
							payLink = node_t.getText();
						}
						if("PAYID".equals(node_t.getName())){
							payNo = node_t.getText();
						}
					}
					if(StringUtils.isNotEmpty(payLink)&&StringUtils.isNotEmpty(payNo)){
						return "200#"+payNo+ConstProp.POUND_SIGN+payLink;
					}
					if(StringUtils.isEmpty(msg)){
						msg = "解析数据丢失";
					}
					return "300#"+msg;
				}
			}
		}catch (Exception e){
			logger.info("getZFDZResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 *	核保接口返回字符串解析
	 * @return
	 */
	public String returnAnalysisXML(String xml, String transType){
		if(TransTypeEnum.HB.getValue().equals(transType)) {//核保
			return getHBResult(xml);
		}else if(TransTypeEnum.ZFDZ.getValue().equals(transType)) {//获取支付地址
			return getZFDZResult(xml);
		}else if(TransTypeEnum.ZFJG.getValue().equals(transType)) {//获取支付结果（不解析返回）
			return xml;
		}else if(TransTypeEnum.PD.getValue().equals(transType)) {//获取批单结果
			return getPDResult(xml);
		}else if(TransTypeEnum.DZFP.getValue().equals(transType)) {//获取电子发票申请结果
			return getFPResult(xml);
		}
		return ConstProp.BLANK_CHAR;
	}

	/**
	 * <b>
	 *     根据保险公司电子保单下载地址转存成自己平台的下载地址（该方法暂未用）
	 * </b>
	 * @param pno 保单号
	 * @param rb_url 电子保单下载地址
	 * @author ZXF
	 * @create 2018/06/07 0007 11:01
	 * @version
	 * @注意事项 </b>
	 */
	public static String unloading_bd(String pno, String rb_url){
		String result = rb_url;
		if (StringUtils.isEmpty(rb_url)) {
			return result;
		}
		if(StringUtils.isEmpty(pno)){
			pno = "ZHGZ"+System.currentTimeMillis();
		}
		InputStream inStream = null;
		try {
			URL url = new URL(rb_url);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5 * 1000);
			inStream = conn.getInputStream();//通过输入流获取图片数据
			String savePath = "/policy/";
			String files = pno + ".pdf";
			result = savePath + files;
			String path = GlobalResources.COM_IMG_RE+savePath;
			FileHelp.isFile(inStream, path, files);
			result = "/getResource?path="+result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inStream != null) {
				try {
					inStream.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return result;
	}
}
