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

import com.alibaba.fastjson.JSON;
import com.bcxin.ins.entity.policy_core.InsTransaction;
import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.third.gyx.changan.ca_enum.CraftType;
import com.bcxin.ins.third.xyx.yb_enum.YB_City;
import com.bcxin.ins.util.*;
import com.bcxin.ins.util.enums.NatureLinkage;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.ins.vo.*;
import com.bcxin.ins.vo.report_pac.InsClaimInformationVo;
import com.bcxin.ins.vo.report_pac.InsCommonReportVo;
import com.bcxin.ins.vo.report_pac.ReportCodeVo;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.dom4j.Document;
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.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <b> 长安-雇主责任险各接口请求数据组装 </b>
 * @author ZXF
 * @create 2021/02/26 0026 13:59
 * @version
 * @注意事项 </b>
 */
public class GYX_PackageMessageChangAn {
	protected Document requestDocument;
	protected Element rootElement;

	void GYX_PackageMessageRenBao(){

	}

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

	/**
	 * <b> 报案 </b>
	 * @param vo 报案信息
	 * @param transType
	 * @author ZXF
	 * @create 2021/03/30 0030 16:02
	 * @version
	 * @注意事项 </b>
	 */
	public static String marshalReport(InsCommonReportVo vo, String transType){
		String result = ConstProp.BLANK_CHAR;
		Document requestDocument = DocumentHelper.createDocument();
		requestDocument.setXMLEncoding("GBK");//设置该XML文件的Encoding = "GBK"
		try {
			IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
			String uid = String.valueOf(idWorker.nextId());
			Element PACKET = requestDocument.addElement("Packet");
			//渠道信息
			Element CHANNEL = PACKET.addElement("channel");
			CHANNEL.addElement("channelCode").setText("BaiChuanXin");
			CHANNEL.addElement("channelTradeSerialNo").setText(uid);
			if(TransTypeEnum.BASL.getValue().equals(transType)) {//报案
				CHANNEL.addElement("channelTradeCode").setText("0102");
				//内容列
				Element RegistInfo = PACKET.addElement("RegistInfo");
				RegistInfo.addElement("BusinessType").setText("BaiChuanXin");
				RegistInfo.addElement("PolicyNo").setText(vo.getPolicy_no());//
				RegistInfo.addElement("ReportName").setText(vo.getReporter_name());//报案人姓名
				RegistInfo.addElement("ReportDate").setText(vo.getReport_date());//报案时间
				RegistInfo.addElement("LinkerName").setText(vo.getReporter_name());//联系人姓名
				RegistInfo.addElement("PhoneNumber").setText(vo.getReporter_tel());//联系人电话
				RegistInfo.addElement("DamageDate").setText(vo.getAccident_date());//出险时间
				ReportCodeVo rcVo = new ReportCodeVo("CA");
				RegistInfo.addElement("DamageCode").setText(vo.getAccident_cause_level_1());//出险原因代码
				RegistInfo.addElement("DamageName").setText(rcVo.getCxyyName(vo.getAccident_cause_level_1()));//出险原因名称
				RegistInfo.addElement("DistrictCode1").setText(vo.getAccident_province_code());//省
				RegistInfo.addElement("DistrictCode2").setText(vo.getAccident_city_code());//市
				RegistInfo.addElement("DistrictCode3").setText(vo.getAccident_county_code());//区代码
				RegistInfo.addElement("DamageAddress").setText(vo.getAccident_place());//详细地址
				RegistInfo.addElement("EstiMateLoss").setText("0");//报损金额
				RegistInfo.addElement("EstiCurrency").setText("CNY");//
				String LossName = "";
				if(StringUtils.isNotEmpty(vo.getOutpatient_list())){
					LossName = "门诊："+vo.getOutpatient_list()+"；";
				}
				if(StringUtils.isNotEmpty(vo.getMaim_list())){
					LossName += "住院："+vo.getMaim_list()+"；";
				}
				if(StringUtils.isNotEmpty(vo.getDemise_list())){
					LossName += "死亡："+vo.getDemise_list();
				}
				RegistInfo.addElement("LossName").setText(LossName);//受损标的
				RegistInfo.addElement("AccidentText").setText(vo.getAccident_process());//事故描述
			}else if(TransTypeEnum.CLSC.getValue().equals(transType)) {//材料上传
				CHANNEL.addElement("channelTradeCode").setText("0104");
				//内容列
				Element RegistInfo = PACKET.addElement("ImageInfo");
				RegistInfo.addElement("BusinessType").setText("BaiChuanXin");
				RegistInfo.addElement("ReportNo").setText(vo.getReport_no());
				Element ImageList = RegistInfo.addElement("ImageList");
				ImageList(ImageList,vo.getClaimInformationVoList());
			}
			result = requestDocument.asXML();
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}

	//上传附件
	private static void ImageList(Element ImageList, List<InsClaimInformationVo> list) {
		for(InsClaimInformationVo vo : list){
			if(ConstProp.DIGIT_ZERO.equals(vo.getStatus())){
				Element ImageData = ImageList.addElement("ImageData");
				int len = vo.getIns_claim_information_id().length();
				String sign = vo.getIns_claim_information_id().substring(len-3,len);
				ImageData.addElement("ImageIndex").setText(vo.getShort_group_code()+sign);//序号
				ImageData.addElement("PicName").setText(vo.getFile_name());//图片名称
				Map<String, String> map = FileHelp.httpFileToBase64(vo.getFile_path());
				ImageData.addElement("PicData").setText(map.get("base64"));//图片转码BASE64后的字符串
				ImageData.addElement("PicSize").setText(map.get("size"));//图片大小
				ImageData.addElement("PicRemark").setText("");//备注
			}
		}
	}

	/**
	 * <b> 理赔查询 </b>
	 * @param policyNo 保单号
	 * @param reportNo 报案号
	 * @author ZXF
	 * @create 2021/03/30 0030 16:02
	 * @version
	 * @注意事项 </b>
	 */
	public static String marshalFindReport(String policyNo, String reportNo,int pageNo){
		String result = ConstProp.BLANK_CHAR;
		Document requestDocument = DocumentHelper.createDocument();
		requestDocument.setXMLEncoding("GBK");//设置该XML文件的Encoding = "GBK"
		try {
			IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
			String uid = String.valueOf(idWorker.nextId());
			Element PACKET = requestDocument.addElement("Packet");
			//渠道信息
			Element CHANNEL = PACKET.addElement("channel");
			CHANNEL.addElement("channelCode").setText("BaiChuanXin");
			CHANNEL.addElement("channelTradeCode").setText("0105");
			CHANNEL.addElement("channelTradeSerialNo").setText(uid);

			//内容列
			Element BODY = PACKET.addElement("Body");
			BODY.addElement("BusinessType").setText("BaiChuanXin");
			BODY.addElement("RegistNo").setText(reportNo);
			BODY.addElement("PolicyNo").setText(policyNo);
			BODY.addElement("PageNo").setText(String.valueOf(pageNo));
			result = requestDocument.asXML();
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}

	public static String mail(SpecialHirelingVo vo, OrderFormVo dto, String transType, String certino, String kpStar, String kpEnd){
		String result = ConstProp.BLANK_CHAR;
		Document requestDocument = DocumentHelper.createDocument();
		requestDocument.setXMLEncoding("GBK");//设置该XML文件的Encoding = "GBK"
		IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
		try {
			if(TransTypeEnum.DZFP.getValue().equals(transType)) {//保单电子发票查询
				//渠道信息
				Element Root = requestDocument.addElement("Root");
				Element CHANNEL = Root.addElement("channel");
				CHANNEL.addElement("channelCode").setText("000160");
				CHANNEL.addElement("channelComCode").setText("430000");
				CHANNEL.addElement("channelProductCode").setText("1516");
				CHANNEL.addElement("channelTradeCode").setText("invoiceQuery");
				CHANNEL.addElement("channelTradeSerialNo").setText(String.valueOf(idWorker.nextId()));
				CHANNEL.addElement("channelAreaCode").setText("430000");
				CHANNEL.addElement("channelTradeDate").setText(DateUtil.getCurrentDateTime());
				Element INFO = Root.addElement("info");
				RoleSubjectVo role = vo.getRoleSubjectList().get(0);
				String TaxNumber = role.getOrganization_code();
				String TaxName = role.getName_cn();
				if(!ConstProp.DIGIT_ZERO.equals(vo.getMailPolicyVo().getNeed_receipt())||!ConstProp.DIGIT_ZERO.equals(vo.getMailPolicyVo().getIs_send_einvoice())){
					TaxNumber = StringUtils.isEmpty(vo.getMailPolicyVo().getTaxpayer_number_invoice())?"":vo.getMailPolicyVo().getTaxpayer_number_invoice();
					TaxName = StringUtils.isEmpty(vo.getMailPolicyVo().getReceipt_head())?"":vo.getMailPolicyVo().getReceipt_head();
				}
				INFO.addElement("buyername").setText(TaxName);//发票抬头
				INFO.addElement("buyerno").setText(TaxNumber);//纳税人识别号
				INFO.addElement("policyno").setText(dto.getExternal_reference());//保单号
			}else if(TransTypeEnum.PDDZFP.getValue().equals(transType)) {//批单电子发票查询
				//渠道信息
				Element Root = requestDocument.addElement("Root");
				Element CHANNEL = Root.addElement("CHANNEL");
				CHANNEL.addElement("ChannelCode").setText("000160");
				CHANNEL.addElement("ChannelComCode").setText("430000");
				CHANNEL.addElement("channelProductCode").setText("1516");
				CHANNEL.addElement("ChannelTradeCode").setText("endorsementInvoiceQuery");
				CHANNEL.addElement("ChannelTradeSerialNo").setText(String.valueOf(idWorker.nextId()));
				CHANNEL.addElement("ChannelAreaCode").setText("430000");
				CHANNEL.addElement("ChannelTradeDate").setText(DateUtil.getCurrentDateTime());
				Element INFO = Root.addElement("INFO");
				INFO.addElement("CertinoList").setText(certino);//批单号 单号之间用逗号隔开
				INFO.addElement("PrintDate1").setText(kpStar);//开票起期 yyyy-MM-dd(包含传入日期)
				INFO.addElement("PrintDate2").setText(kpEnd);//开票止期 yyyy-MM-dd(包含传入日期)
			}
			result = requestDocument.asXML();
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 核保数据组装
	 * @return
	 */
	public static String marshal(GYXPolicyVo policy, OrderFormVo orderVo, String transType, String payType){
		String result = ConstProp.BLANK_CHAR;
		Document requestDocument = DocumentHelper.createDocument();
		requestDocument.setXMLEncoding("GBK");//设置该XML文件的Encoding = "GBK"
		try {
			if(TransTypeEnum.HB.getValue().equals(transType)){//核保
				Element root = requestDocument.addElement("root");
				//渠道信息
				Element CHANNEL = root.addElement("channel");
				CHANNEL(CHANNEL,orderVo,"2701");

				Element main = root.addElement("main");
				main(main,orderVo);

				Element applicant = root.addElement("applicant");
				applicant(applicant,orderVo,policy);

				Element insureds = root.addElement("insureds");
				insureds(insureds,orderVo,policy);

				result = requestDocument.asXML();
			}else if(TransTypeEnum.ZFDZ.getValue().equals(transType)){//获取支付地址
				Element request = requestDocument.addElement("request");
				IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
				String uid = String.valueOf(idWorker.nextId());
				Element requestHead = request.addElement("requestHead");
				requestHead(requestHead, orderVo, uid);
				Element requestBody = request.addElement("requestBody");
				requestBody(requestBody, orderVo);
				result = requestDocument.asXML();
			}else if(TransTypeEnum.CBQR.getValue().equals(transType)){//承保确认接口
				Element root = requestDocument.addElement("root");
				//渠道信息
				Element CHANNEL = root.addElement("channel");
				CHANNEL(CHANNEL,orderVo,"0001");

				Element main = root.addElement("main");
				main.addElement("proposalNo").setText(orderVo.getPolicy_serial_number());
				result = requestDocument.asXML();
			}else if(TransTypeEnum.TB.getValue().equals(transType)){//保单退保接口
				Element root = requestDocument.addElement("root");
				//渠道信息
				Element CHANNEL = root.addElement("channel");
				CHANNEL(CHANNEL,orderVo,"1103");

				Element main = root.addElement("main");
				main.addElement("proposalNo").setText(orderVo.getPolicy_serial_number());
				main.addElement("policyNo").setText(orderVo.getExternal_reference());
				main.addElement("endorseType").setText("04");
				result = requestDocument.asXML();
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}

	//渠道信息
	private static void CHANNEL(Element underwrite, OrderFormVo dto, String ChannelTradeCode) {
		//渠道代码
		underwrite.addElement("channelCode").setText("000160");
		//渠道机构代码
		underwrite.addElement("channelComCode").setText("430000");
		//渠道产品代码
		underwrite.addElement("channelProductCode").setText("");
		//渠道交易代码
		underwrite.addElement("channelTradeCode").setText(ChannelTradeCode);
		//渠道交易流水号（一次交易标识）
		underwrite.addElement("channelTradeSerialNo").setText(dto.getTrade_serial_number());
		//渠道区域代码
		underwrite.addElement("channelAreaCode").setText("430000");
		//渠道交易日期,格式:yyyy-MM-dd HH:mm:ss
		underwrite.addElement("channelTradeDate").setText(dto.getStart_time());
	}

	//投保人信息
	private static void applicant(Element underwrite, OrderFormVo dto, GYXPolicyVo vo) {

		RoleSubjectVo appli = vo.getRoleSubjectList().get(0);
		underwrite.addElement("appliName").setText(appli.getName_cn());//投保人名称
		underwrite.addElement("identifyType").setText("99");//证件类型
		underwrite.addElement("identifyNumber").setText(appli.getOrganization_code());//证件号码
		underwrite.addElement("birthDay").setText(appli.getBirth_date());//出生日期
		underwrite.addElement("sex").setText(appli.getSex());//性别（代码）1:男；2:女；9:未说明
		int age = 0;
		try {
			age = DateUtil.getAge(appli.getBirth_date());
		} catch (Exception e) {
			e.printStackTrace();
		}
		underwrite.addElement("age").setText(String.valueOf(age));//年龄
		underwrite.addElement("insuredIdentity").setText("01");//与被保险人关系
		com.bcxin.ins.third.tyx.changan.ca_enum.CraftType career = com.bcxin.ins.third.tyx.changan.ca_enum.CraftType.getByCareer(appli.getMajor_group());
		underwrite.addElement("occupationCode").setText(career.getCode());//
		underwrite.addElement("occupationType").setText(career.getLevel());//职业类别风险等级代码
		underwrite.addElement("mobile").setText(appli.getLink_tel());//移动电话
		underwrite.addElement("appliType").setText("1");//投保人类型1-个人，2-单位
		underwrite.addElement("taxInfoFlag").setText("1");//开票信息传输标记		0-不传开票信息，1-传开票信息
		Element taxInfo = underwrite.addElement("taxInfo");
		taxInfo.addElement("taxpayerType").setText("4");//纳税人类型	Y	1-一般纳税人，2-小规模纳税人，3-非增值税纳税人，4-个人
		taxInfo.addElement("invoiceType").setText("3");//发票类型	Y	1-增值税专用发票，2-增值税普通发票，3-电子发票
	}

	//根据城市代码获取邮编
	public static String getZipCode(String cityCode){
		YB_City yc = YB_City.fromYBCity(cityCode);
		String result = "";
		if(yc != null){
			result = String.valueOf(yc).split("_")[1];
		}
		return result;
	}

	//被保险人信息
	private static void insureds(Element insureds, OrderFormVo dto, GYXPolicyVo vo) {
		Element underwrite = insureds.addElement("insured");
		RoleSubjectVo insured = vo.getRoleSubjectList().get(1);
		underwrite.addElement("insuredName").setText(insured.getName_cn());//投保人名称
		underwrite.addElement("appliIdentity").setText("01");//与投保人关系
		underwrite.addElement("identifyType").setText("99");//证件类型
		underwrite.addElement("identifyNumber").setText(insured.getOrganization_code());//证件号码
		underwrite.addElement("mobile").setText(insured.getLink_tel());//移动电话
		underwrite.addElement("phoneNumber").setText(insured.getLink_tel());//联系电话
		underwrite.addElement("email").setText(insured.getLink_email());//投保人邮箱
		underwrite.addElement("postCode").setText("");//被保险人邮编
		underwrite.addElement("health").setText(insured.getHealth());//健康状况（见转义）
		underwrite.addElement("healthFlag").setText(insured.getHealth_flag());//是否参加医疗
		underwrite.addElement("birthDay").setText(insured.getBirth_date());//出生日期
		underwrite.addElement("sex").setText(insured.getSex());//性别（代码）1:男；2:女；9:未说明
		int age = 0;
		try {
			age = DateUtil.getAge(insured.getBirth_date());
		} catch (Exception e) {
			e.printStackTrace();
		}
		underwrite.addElement("age").setText(String.valueOf(age));//年龄
		underwrite.addElement("insuredType").setText("1");//关系人类型 1.个人/2.单位和关系人性质随动
	}

	//投保基本信息
	private static void main(Element underwrite, OrderFormVo dto) {
		underwrite.addElement("StartDate").setText(dto.getInception_date());//起保日期
		underwrite.addElement("EndDate").setText(dto.getPlanned_end_date());//终保日期
		underwrite.addElement("StartHour").setText("0");//起保小时
		underwrite.addElement("EndHour").setText("24");//终保小时
		underwrite.addElement("sumQuantity").setText("1");//保险份数
		underwrite.addElement("insuredCount").setText("1");//投保人数
		underwrite.addElement("SumAmount").setText(dto.getInsured_amount());//保单总保险金额
		underwrite.addElement("SumPremium").setText(dto.getGross_premium());//保单总保险费
	}

	private static String conventPType(String revise_type){
		String rt = ConstProp.BLANK_CHAR;
		if(ConstProp.DIGIT_ONE.equals(revise_type)){//增员
			rt = "3";
		}else if(ConstProp.DIGIT_TWO.equals(revise_type)){//减员
			rt = "2";
		}else if(ConstProp.DIGIT_THREE.equals(revise_type)){//替换
			rt = "1";
		}
		return rt;
	}

	//个人证件类型编码转换
	private static String changeCTypePer(String c_t){
		if("0".equals(c_t)){//身份证
			return "01";
		}else if("3".equals(c_t)){//护照
			return "03";
		}else if("5".equals(c_t)){//返乡证
			return "06";
		}else{//其它
			return "99";
		}
	}

	//获取支付地址
	private static void requestHead(Element underwrite, OrderFormVo dto, String consumerSeqNo) {
		//交易流水号（服务消费方）
		underwrite.addElement("consumerSeqNo").setText(consumerSeqNo);
		//第三方渠道编码，由服务方提供
		underwrite.addElement("consumerID").setText("000160");
		//服务请求类型
		underwrite.addElement("requestType").setText("QueryPayUrl");
		//交易密码，MD5加密，根据约定是否必传
		underwrite.addElement("passWord").setText("");
		underwrite.addElement("channelType").setText("01");
		//产品代码
		underwrite.addElement("productCode").setText("");
		//地区
		underwrite.addElement("regionCode").setText("430000");
	}

	//获取支付地址
	private static void requestBody(Element underwrite, OrderFormVo dto) {
		//请求方
		underwrite.addElement("parterId").setText("baichuanxin");
		//地区
		underwrite.addElement("regionCode").setText("430000");
		//订单类型 01-车险，02-非车人身险，03-非车核心
		underwrite.addElement("orderType").setText("02");
		//投保单号
		underwrite.addElement("orderNo").setText(dto.getPolicy_serial_number());
		//订单金额
		underwrite.addElement("orderFee").setText(dto.getGross_premium().replace(".00","")+"00");
		//请求来源 01 代表app/ 02代表pc端
		underwrite.addElement("orderSource").setText("02");
		String timeExpire = DateUtil.getTomorrow()+" 23:59:00";
		try {
			timeExpire = DateUtil.dateAdd(7, DateUtil.getCurrentDateTime(), 1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//支付有效期止期
		underwrite.addElement("timeExpire").setText(timeExpire);
		String cHttp = GlobalResources.WEB_URL.replace("https","http");
		//回调地址
//		支付成功后渠道平台会使用http + post方式调用该链接，并且支付相关信息通过URL参数形式返回
//		订单号：orderNo
//		支付方式：payType
//		刷卡流水号：cardSerialNo
//		支付时间：payTime
//		请求方：parterId
//		订单类型：orderType
//		校验码：passWord
		underwrite.addElement("callBack").setText(cHttp+"CA-API/GYX/Policy-Opinion");
		//支付二维码请求 None,Wechat,Alipay(如果获取支付URL可不传，如果获取二维码必传）
		underwrite.addElement("qrType").setText("None");
		underwrite.addElement("payNo").setText("");//支付号
		underwrite.addElement("proposalNoBI").setText("");//商业险投保单号
		underwrite.addElement("proposalNoCI").setText("");//交强险投保单号
	}

	/**
	 * <b> 报案解析 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:12
	 * @version
	 * @注意事项 </b>
	 */
	private String getCABASLResult(String originalXML) {
		String ReportNo = ConstProp.BLANK_CHAR;
		String Msg = ConstProp.BLANK_CHAR;
		String ReportStatus = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			for(Iterator u = rootElement.elementIterator(); u.hasNext();){
				Element node_u = (Element) u.next();
				if("ReportStatus".equals(node_u.getName())){
					ReportStatus = node_u.getText();
				}
				if("ReportNo".equals(node_u.getName())){
					ReportNo = node_u.getText();
				}
				if("Msg".equals(node_u.getName())){
					Msg = node_u.getText();
				}
			}
			if(!"1".equals(ReportStatus)){
				if(StringUtils.isEmpty(Msg)){
					Msg = "业务处理失败！";
				}
				return "300#"+Msg;
			}
			return "200#"+ ReportNo;
		}catch (Exception e){
			logger.info("getCAAJCXResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 上传文件解析 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:12
	 * @version
	 * @注意事项 </b>
	 */
	private String getCACLSCResult(String originalXML) {
		String Msg = ConstProp.BLANK_CHAR;
		String UpLoadStatus = ConstProp.BLANK_CHAR;
		String ImageIndex = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			for(Iterator r = rootElement.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("UpLoadStatus".equals(node_r.getName())){
					UpLoadStatus = node_r.getText();
				}
				if("ErrorList".equals(node_r.getName())){
					for(Iterator m = node_r.elementIterator(); m.hasNext();){
						Element node_m = (Element) m.next();
						if("ErrorData".equals(node_m.getName())){
							for(Iterator n = node_m.elementIterator(); n.hasNext();){
								Element node_n = (Element) n.next();
								if("UpLoadFlag".equals(node_n.getName())&&!"0".equals(node_n.getText())){
									continue;
								}
								if("ImageIndex".equals(node_n.getName())){
									ImageIndex = ImageIndex+node_n.getText()+",";
								}
								if(StringUtils.isEmpty(Msg)&&"ErrorMsg".equals(node_n.getName())){
									Msg = node_n.getText();
								}
							}
						}
					}
				}
			}
			if(!"1".equals(UpLoadStatus)){
				if(StringUtils.isEmpty(Msg)){
					Msg = "业务处理失败！";
				}
				return "300#"+ImageIndex+"#"+Msg;
			}
			return "200#";
		}catch (Exception e){
			logger.info("getCAAJCXResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 案件查询解析 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:12
	 * @version
	 * @注意事项 </b>
	 */
	private String getCAAJCXResult(String originalXML) {
		String ResponseCode = ConstProp.BLANK_CHAR;
		String ErrorMessage = ConstProp.BLANK_CHAR;
		String TotalCount = ConstProp.BLANK_CHAR;
		String TotalPage = ConstProp.BLANK_CHAR;
		String ThisPageNo = ConstProp.BLANK_CHAR;
		List<Map<String,String>> list = Lists.newArrayList();
		Map<String,String> map = null;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			for(Iterator u = rootElement.elementIterator(); u.hasNext();){
				Element node_u = (Element) u.next();
				if("Head".equals(node_u.getName())){
					for(Iterator r = node_u.elementIterator(); r.hasNext();){
						Element node_r = (Element) r.next();
						if("ResponseCode".equals(node_r.getName())){
							ResponseCode = node_r.getText();
						}
						if("Message".equals(node_r.getName())){
							ErrorMessage = node_r.getText();
						}
					}
					if(!"1".equals(ResponseCode)){
						if(StringUtils.isEmpty(ErrorMessage)){
							ErrorMessage = "业务处理失败！";
						}
						return "300#"+ErrorMessage;
					}
				}
				if("Body".equals(node_u.getName())){
					for(Iterator r = node_u.elementIterator(); r.hasNext();){
						Element node_r = (Element) r.next();
						if("TotalCount".equals(node_r.getName())){
							TotalCount = node_r.getText();
						}
						if("TotalPage".equals(node_r.getName())){
							TotalPage = node_r.getText();
						}
						if("ThisPageNo".equals(node_r.getName())){
							ThisPageNo = node_r.getText();
						}
						if("RegistInfoList".equals(node_r.getName())){
							for(Iterator e = node_r.elementIterator(); e.hasNext();){
								Element node_e = (Element) e.next();
								if("RegistInfo".equals(node_e.getName())){
									map = Maps.newHashMap();
									for(Iterator m = node_e.elementIterator(); m.hasNext();){
										Element node_m = (Element) m.next();
										if("RegistNo".equals(node_m.getName())){
											map.put("RegistNo",node_m.getText());
										}
										if("PolicyNo".equals(node_m.getName())){
											map.put("PolicyNo",node_m.getText());
										}
										if("DamageTime".equals(node_m.getName())){
											//出险时间（yyyy-MM-dd HH:mm:ss）
											map.put("DamageTime",node_m.getText());
										}
										if("ReportTime".equals(node_m.getName())){
											//报案时间（yyyy-MM-dd HH:mm:ss）
											map.put("ReportTime",node_m.getText());
										}
										if("RiskName".equals(node_m.getName())){
											//险种名称
											map.put("RiskName",node_m.getText());
										}
										if("ReportName".equals(node_m.getName())){
											//报案人名称
											map.put("ReportName",node_m.getText());
										}
										if("PhoneNumber".equals(node_m.getName())){
											//报案人电话
											map.put("PhoneNumber",node_m.getText());
										}
										if("DistrictCode1".equals(node_m.getName())){
											//事故地点省编码
											map.put("DistrictCode1",node_m.getText());
										}
										if("DistrictCode2".equals(node_m.getName())){
											//事故地点市编码
											map.put("DistrictCode2",node_m.getText());
										}
										if("DistrictCode3".equals(node_m.getName())){
											//事故地点县编码
											map.put("DistrictCode3",node_m.getText());
										}
										if("DamageAddress".equals(node_m.getName())){
											//事故地点详细地址
											map.put("DamageAddress",node_m.getText());
										}
										if("DamageCode".equals(node_m.getName())){
											//出险原因代码
											map.put("DamageCode",node_m.getText());
										}
										if("context".equals(node_m.getName())){
											//
											map.put("context",node_m.getText());
										}
										if("AccidentText".equals(node_m.getName())){
											//事故经过
											map.put("AccidentText",node_m.getText());
										}
										if("CaseStatusCode".equals(node_m.getName())){
											//案件状态编码
											map.put("CaseStatusCode",node_m.getText());
										}
										if("CaseStatusName".equals(node_m.getName())){
											//案件状态名称
											map.put("CaseStatusName",node_m.getText());
										}
										if("RecireverList".equals(node_m.getName())) {
											String rs = "";
											String pm = "";
											for (Iterator s = node_m.elementIterator(); s.hasNext(); ) {
												Element node_s = (Element) s.next();
												if("RecireverInfo".equals(node_s.getName())) {
													String AcciPerson = "";
													String AcciIdentifyNumber = "";
													String PersonLossType = "";
													String AccountType = "";
													String AccountName = "";
													String IdentifyNumber = "";
													String BankName = "";
													String BankAreaProvince = "";
													String BankArea = "";
													String Account = "";
													for (Iterator d = node_s.elementIterator(); d.hasNext(); ) {
														Element node_d = (Element) d.next();
														if("AcciPerson".equals(node_d.getName())){
															AcciPerson = node_d.getText();
														}
														if("AcciIdentifyNumber".equals(node_d.getName())){
															AcciIdentifyNumber = node_d.getText();
														}
														if("PersonLossType".equals(node_d.getName())){
															PersonLossType = node_d.getText();
														}
														if("AccountType".equals(node_d.getName())){
															AccountType = node_d.getText();
														}
														if("AccountName".equals(node_d.getName())){
															AccountName = node_d.getText();
														}
														if("IdentifyNumber".equals(node_d.getName())){
															IdentifyNumber = node_d.getText();
														}
														if("BankName".equals(node_d.getName())){
															BankName = node_d.getText();
														}
														if("BankAreaProvince".equals(node_d.getName())){
															BankAreaProvince = node_d.getText();
														}
														if("BankArea".equals(node_d.getName())){
															BankArea = node_d.getText();
														}
														if("Account".equals(node_d.getName())){
															Account = node_d.getText();
														}
													}
													rs =rs + AcciPerson+"("+AcciIdentifyNumber+")|"+PersonLossType+";";
													pm =pm + AccountName+"|"+IdentifyNumber+"|"+BankName+"|"+Account+"|"+BankAreaProvince+"|"+BankArea+"|"+AccountType+";";
												}
											}
											//出险人信息
											map.put("rs",rs);
											map.put("pm",pm);
										}
									}
									list.add(map);
								}
							}

						}
						map = Maps.newHashMap();
						map.put("TotalCount",TotalCount);
						map.put("TotalPage",TotalPage);
						map.put("ThisPageNo",ThisPageNo);
						map.put("ReportInfo",JSON.toJSONString(list));
					}
				}
			}
			return "200#"+ JSON.toJSONString(map);
		}catch (Exception e){
			logger.info("getCAAJCXResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 核保确认解析 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:12
	 * @version
	 * @注意事项 </b>
	 */
	private String getCAHBResult(String originalXML) {
		String ResponseCode = ConstProp.BLANK_CHAR;
		String ErrorMessage = ConstProp.BLANK_CHAR;
		String CertiNo = ConstProp.BLANK_CHAR;//投保单号
		String SumAmount = ConstProp.BLANK_CHAR;//保额
		String SumPremium = ConstProp.BLANK_CHAR;//保费
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			Element root = rootElement.element("root");
			Element responseStatus = root.element("responseStatus");
			for(Iterator r = responseStatus.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("responseCode".equals(node_r.getName())){
					ResponseCode = node_r.getText();
				}
				if("responseMessage".equals(node_r.getName())){
					ErrorMessage = node_r.getText();
				}
			}
			if(!"00".equals(ResponseCode)){
				if(StringUtils.isEmpty(ErrorMessage)){
					ErrorMessage = "业务处理失败！";
				}
				return "300#"+ErrorMessage;
			}
			Element main = root.element("main");
			for(Iterator r = main.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("proposalNo".equals(node_r.getName())){
					CertiNo = node_r.getText();
				}
				if("premium".equals(node_r.getName())){
					SumPremium = node_r.getText();
				}
				if("amount".equals(node_r.getName())){
					SumAmount = node_r.getText();
				}

			}
			return "200#"+CertiNo+"#"+SumAmount+"#"+SumPremium;
		}catch (Exception e){
			logger.info("getCAHBResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 承保确认解析 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:12
	 * @version
	 * @注意事项 </b>
	 */
	private String getCACBQRResult(String originalXML) {
		String ResponseCode = ConstProp.BLANK_CHAR;
		String ErrorMessage = ConstProp.BLANK_CHAR;
		String CertiNo = ConstProp.BLANK_CHAR;//保单号
		String EndorseNo = ConstProp.BLANK_CHAR;//批单号
		String ProposalNo = ConstProp.BLANK_CHAR;//投单号
		String Epolicy = ConstProp.BLANK_CHAR;//电子保单下载地址
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			Element root = rootElement.element("root");
			Element responseStatus = root.element("responseStatus");
			for(Iterator r = responseStatus.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("responseCode".equals(node_r.getName())){
					ResponseCode = node_r.getText();
				}
				if("responseMessage".equals(node_r.getName())){
					ErrorMessage = node_r.getText();
				}
			}
			if(!"00".equals(ResponseCode)){
				if(StringUtils.isEmpty(ErrorMessage)){
					ErrorMessage = "业务处理失败！";
				}
				return "300#"+ErrorMessage;
			}
			Element main = root.element("main");
			for(Iterator r = main.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("policyNo".equals(node_r.getName())){
					CertiNo = node_r.getText();
				}
				if("proposalNo".equals(node_r.getName())){
					ProposalNo = node_r.getText();
				}
				if("ePolicy".equals(node_r.getName())){
					Epolicy = node_r.getText();
				}

			}

			return "200#"+CertiNo+"#"+ProposalNo+"#"+Epolicy;
		}catch (Exception e){
			logger.info("getCACBQRResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 保单电子发票解析 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:12
	 * @version
	 * @注意事项 </b>
	 */
	private String getBDDZFPResult(String originalXML) {
		String ResponseCode = ConstProp.BLANK_CHAR;
		String ErrorMessage;
		String CertiNo = ConstProp.BLANK_CHAR;//保单号
		String eshortlink = ConstProp.BLANK_CHAR;//电子发票下载地址
		try {
			originalXML = originalXML.replace("&","&amp;");
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
//			Element IfResponse = rootElement.element("IfResponse");
			Element IfResult = rootElement.element("IfResult");
//			Element IfWarning = IfResponse.element("IfWarning");
			Element IfError = rootElement.element("IfError");
//			Element IfErrorStack = IfResponse.element("IfErrorStack");
			ErrorMessage = IfError.getText();
			if(!"0".equals(IfResult.getText())){
				if(StringUtils.isEmpty(ErrorMessage)){
					ErrorMessage = "业务处理失败！";
				}
				return "300#"+ErrorMessage;
			}
			Element IfResultInfo = rootElement.element("IfResultInfo");
			Element request = IfResultInfo.element("request");
			Element main = request.element("main");
			for(Iterator r = main.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("status".equals(node_r.getName())){
					ResponseCode = node_r.getText();
				}
				if("msg".equals(node_r.getName())){
					ErrorMessage = node_r.getText();
				}
				if("policyno".equals(node_r.getName())){
					CertiNo = node_r.getText();
				}
				if("eshortlink".equals(node_r.getName())){
					eshortlink = node_r.getText();
				}

			}
			if(!"01".equals(ResponseCode)){
				if(StringUtils.isEmpty(ErrorMessage)){
					ErrorMessage = "业务处理失败！";
				}
				return "300#"+ErrorMessage;
			}
			eshortlink = eshortlink.replace("&amp;","&");
			return "200#"+unloading_fp(eshortlink);
		}catch (Exception e){
			logger.info("getBDDZFPResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b>
	 *     根据保险公司电子发票下载地址转存成自己平台的下载地址
	 * </b>
	 * @param rb_url 电子保单下载地址
	 * @author ZXF
	 * @create 2018/06/07 0007 11:01
	 * @version
	 * @注意事项 </b>
	 */
	public static String unloading_fp(String rb_url){
		String result = rb_url;
		if (StringUtils.isEmpty(rb_url)) {
			return result;
		}
		String pno = "CAFP"+DateUtil.generatorRadomNumber();
		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 = GlobalResources.WEB_URL+"/getResource?path="+result;
		} catch (Exception e) {
//			e.printStackTrace();
			logger.error(e.getMessage());
			return rb_url;
		} finally {
			if (inStream != null) {
				try {
					inStream.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return result;
	}

	/**
	 * <b> 批单电子发票解析 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:12
	 * @version
	 * @注意事项 </b>
	 */
	private String getPDDZFPResult(String originalXML) {
		String ResultCode = ConstProp.BLANK_CHAR;
		String ResultFlag = ConstProp.BLANK_CHAR;
		String ResultMessage = ConstProp.BLANK_CHAR;
		String InvoiceUrl = ConstProp.BLANK_CHAR;//批单电子发票下载地址
		try {
			originalXML = originalXML.replace("&","&amp;");
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
//			Element ResponseBody = rootElement.element("ResponseBody");
			for(Iterator r = rootElement.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("ResultCode".equals(node_r.getName())){
					ResultCode = node_r.getText();
				}
				if("ResultFlag".equals(node_r.getName())){
					ResultFlag = node_r.getText();
				}
				if("ResultMessage".equals(node_r.getName())){
					ResultMessage = node_r.getText();
				}
				if("InvoiceUrlList".equals(node_r.getName())){
					for(Iterator m = node_r.elementIterator(); m.hasNext();) {
						Element node_m = (Element) m.next();
						if("InvoiceUrl".equals(node_m.getName())){
							InvoiceUrl = node_m.getText();
							break;
						}
					}
				}
			}
			if(!"0000".equals(ResultCode)){
				if(StringUtils.isEmpty(ResultMessage)){
					ResultMessage = "业务处理失败！";
				}
				return "300#"+ResultMessage;
			}
			if(StringUtils.isEmpty(InvoiceUrl)){
				return "300#未查询到有效发票";
			}
			InvoiceUrl = InvoiceUrl.replace("&amp;","&");
			return "200#"+unloading_fp(InvoiceUrl);
		}catch (Exception e){
			logger.info("getPDDZFPResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 承保信息解析 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:12
	 * @version
	 * @注意事项 </b>
	 */
	private String getCACBXXResult(String originalXML) {
		String ResponseCode = ConstProp.BLANK_CHAR;
		String ErrorMessage = ConstProp.BLANK_CHAR;
		String CertiNo = ConstProp.BLANK_CHAR;//保单号
		String SumAmount = ConstProp.BLANK_CHAR;//批单号
		String ProposalNo = ConstProp.BLANK_CHAR;//投单号
		String Epolicy = ConstProp.BLANK_CHAR;//电子保单下载地址
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			Element HEAD = rootElement.element("HEAD");
			for(Iterator r = HEAD.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("ResponseCode".equals(node_r.getName())){
					ResponseCode = node_r.getText();
				}
				if("ErrorMessage".equals(node_r.getName())){
					ErrorMessage = node_r.getText();
				}
			}
			if(!"1".equals(ResponseCode)){
				if(StringUtils.isEmpty(ErrorMessage)){
					ErrorMessage = "业务处理失败！";
				}
				return "300#"+ErrorMessage;
			}
			Element BODY = rootElement.element("BODY");
			Element PrpCmainDto = BODY.element("PrpCmainDto");
			for(Iterator r = PrpCmainDto.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("CertiNo".equals(node_r.getName())){
					CertiNo = node_r.getText();
				}
				if("ProposalNo".equals(node_r.getName())){
					ProposalNo = node_r.getText();
				}
				if("SumAmount".equals(node_r.getName())){
					SumAmount = node_r.getText();
				}
				if("Epolicy".equals(node_r.getName())){
					Epolicy = node_r.getText();
				}
			}
			return "200#"+CertiNo+"#"+ProposalNo+"#"+SumAmount+"#"+Epolicy;
		}catch (Exception e){
			logger.info("getCACBXXResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 批单生成接口解析 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:12
	 * @version
	 * @注意事项 </b>
	 */
	private String getCAPDResult_1(String originalXML) {
		String ResponseCode = ConstProp.BLANK_CHAR;
		String ErrorMessage = ConstProp.BLANK_CHAR;
		String CertiNo = ConstProp.BLANK_CHAR;//暂存单号
		String UnderWriteFlag = ConstProp.BLANK_CHAR;//核保状态 0-初始化；1-核保通过；3-自核通过；5-人工预核保；6-自动预核保
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			Element HEAD = rootElement.element("HEAD");
			Element AffirmPropsalResultDto = HEAD.element("AffirmEndorseResultDto");
			for(Iterator r = AffirmPropsalResultDto.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("CertiNo".equals(node_r.getName())){
					CertiNo = node_r.getText();
				}
				if("UnderWriteFlag".equals(node_r.getName())){
					UnderWriteFlag = node_r.getText();
				}
				if("ReturnMessageDto".equals(node_r.getName())){
					for(Iterator m = node_r.elementIterator(); m.hasNext();){
						Element node_m = (Element) m.next();
						if("ResponseCode".equals(node_m.getName())){
							ResponseCode = node_m.getText();
						}
						if("ErrorMessage".equals(node_m.getName())){
							ErrorMessage = node_m.getText();
						}
					}
					if(!"1".equals(ResponseCode)){
						if(StringUtils.isEmpty(ErrorMessage)){
							ErrorMessage = "业务处理失败！";
						}
						return "300#"+ErrorMessage;
					}
				}
			}
			return "200#"+CertiNo+"#"+UnderWriteFlag;
		}catch (Exception e){
			logger.info("getCAHBResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 批单生成实时接口解析 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:12
	 * @version
	 * @注意事项 </b>
	 */
	private String getCAPDResult(String originalXML) {
		String ResponseCode = ConstProp.BLANK_CHAR;
		String ErrorMessage = ConstProp.BLANK_CHAR;
		String CertiNo = ConstProp.BLANK_CHAR;//批单号
		String UnderWriteFlag = ConstProp.BLANK_CHAR;//核保状态 0-初始化；1-核保通过；3-自核通过；5-人工预核保；6-自动预核保
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			Element HEAD = rootElement.element("HEAD");
			Element AffirmPropsalResultDto = HEAD.element("AffirmEndorseResultDto");
			for(Iterator r = AffirmPropsalResultDto.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("CertiNo".equals(node_r.getName())){
					CertiNo = node_r.getText();
				}
				if("UnderWriteFlag".equals(node_r.getName())){
					UnderWriteFlag = node_r.getText();
				}
			}
			Element ReturnMessageDto = HEAD.element("ReturnMessageDto");
			for(Iterator r = ReturnMessageDto.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("ResponseCode".equals(node_r.getName())){
					ResponseCode = node_r.getText();
				}
				if("ErrorMessage".equals(node_r.getName())){
					ErrorMessage = node_r.getText();
				}
			}
			if(!"1".equals(ResponseCode)){
				if(StringUtils.isEmpty(ErrorMessage)){
					ErrorMessage = "业务处理失败！";
				}
				return "300#"+ErrorMessage;
			}
			return "200#"+CertiNo/*+"#"+UnderWriteFlag*/;
		}catch (Exception e){
			logger.info("getCAHBResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 批单确认报文解析 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:12
	 * @version
	 * @注意事项 </b>
	 */
	private String getCAPDQRResult(String originalXML) {
		String underwriteFlag = ConstProp.BLANK_CHAR;
		String underwriteOpinion = ConstProp.BLANK_CHAR;
		String endorNo = ConstProp.BLANK_CHAR;//批单号
		String timestamp = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			Element HEAD = rootElement.element("requestHead");
			for(Iterator r = HEAD.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("endorNo".equals(node_r.getName())){
					endorNo = node_r.getText();
				}
				if("timestamp".equals(node_r.getName())){
					timestamp = node_r.getText();
				}
				if("underwriteFlag".equals(node_r.getName())){
					underwriteFlag = node_r.getText();
				}
				if("underwriteOpinion".equals(node_r.getName())){
					underwriteOpinion = node_r.getText();
				}
			}

			if(!"1".equals(underwriteFlag)){
				if(StringUtils.isEmpty(underwriteOpinion)){
					underwriteOpinion = "业务处理失败！";
				}
				return "300#"+endorNo+"#"+timestamp+"#"+underwriteOpinion;
			}
			return "200#"+endorNo+"#"+timestamp;
		}catch (Exception e){
			logger.info("getCAHBResult:"+e.getMessage());
		}
		return "301#数据解析失败";
	}

	/**
	 * <b> 批单状态查询结果解析 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:12
	 * @version
	 * @注意事项 </b>
	 */
	private String getCAPDJGResult(String originalXML) {
		String ResponseCode = ConstProp.BLANK_CHAR;
		String ErrorMessage = ConstProp.BLANK_CHAR;
		String EndorseNo = ConstProp.BLANK_CHAR;//批单号/保单号
		String Flag = ConstProp.BLANK_CHAR;//批单状态（0-初始值;1-通过;2-不通过;3-无需核保;9-待核保;5-人工预核保;6-自动预核保）
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			Element HEAD = rootElement.element("HEAD");
			for(Iterator r = HEAD.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("ResponseCode".equals(node_r.getName())){
					ResponseCode = node_r.getText();
				}
				if("ErrorMessage".equals(node_r.getName())){
					ErrorMessage = node_r.getText();
				}
			}
			if(!"1".equals(ResponseCode)){
				if(StringUtils.isEmpty(ErrorMessage)){
					ErrorMessage = "业务处理失败！";
				}
				return "300#"+ErrorMessage;
			}
			Element BODY = rootElement.element("BODY");
			for(Iterator r = BODY.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				for(Iterator m = node_r.elementIterator(); r.hasNext();){
					Element node_m = (Element) m.next();
					if("EndorseNo".equals(node_m.getName())){
						EndorseNo = node_m.getText();
					}
					if("Flag".equals(node_m.getName())){
						Flag = node_m.getText();
					}
				}

			}
			return "200#"+EndorseNo+"#"+Flag;
		}catch (Exception e){
			logger.info("getCACBXXResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 线下承保结果回调 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:12
	 * @version
	 * @注意事项 </b>
	 */
	private String getCAXXCBResult(String originalXML) {
		String ResponseCode = ConstProp.BLANK_CHAR;
		String ErrorMessage = ConstProp.BLANK_CHAR;
		String PolicyNo = ConstProp.BLANK_CHAR;//保单号
		String ProposalNo = ConstProp.BLANK_CHAR;//投保单号
		String Epolicy = ConstProp.BLANK_CHAR;//电子保单链接
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			Element RequestBody = rootElement.element("RequestBody");
			for(Iterator r = RequestBody.elementIterator(); r.hasNext();){
				Element node_n = (Element) r.next();
				if("PayState".equals(node_n.getName())){
					ResponseCode = node_n.getText();
				}
				if("Message".equals(node_n.getName())){
					ErrorMessage = node_n.getText();
				}
				if("ProposalNo".equals(node_n.getName())){
					ProposalNo = node_n.getText();
				}
				if("Epolicy".equals(node_n.getName())){
					Epolicy = node_n.getText();
				}
				if("PolicyNo".equals(node_n.getName())){
					PolicyNo = node_n.getText();
				}
			}
			if(!"true".equals(ResponseCode)){
				if(StringUtils.isEmpty(ErrorMessage)){
					ErrorMessage = "业务处理失败！";
				}
				return "300#"+ErrorMessage;
			}

			return "200#"+ProposalNo+"#"+PolicyNo+"#"+Epolicy;
		}catch (Exception e){
			logger.info("getCAXXCBResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 支付地址解析 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:12
	 * @version
	 * @注意事项 </b>
	 */
	private String getCAZFDZResult(String originalXML) {
		String status = ConstProp.BLANK_CHAR;
		String appMessage = ConstProp.BLANK_CHAR;
		String ResponseCode = ConstProp.BLANK_CHAR;
		String ErrorMessage = ConstProp.BLANK_CHAR;
		String payNo = ConstProp.BLANK_CHAR;
		String payUrl = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			Element responseHead = rootElement.element("responseHead");
			for(Iterator r = responseHead.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("status".equals(node_r.getName())){
					status = node_r.getText();
				}
				if("esbCode".equals(node_r.getName())){
					ResponseCode = node_r.getText();
				}
				if("esbMessage".equals(node_r.getName())){
					ErrorMessage = node_r.getText();
				}
				if("appMessage".equals(node_r.getName())){
					appMessage = node_r.getText();
				}
			}
			if(!"00".equals(ResponseCode)||!"0".equals(status)){
				if(StringUtils.isEmpty(ErrorMessage)){
					ErrorMessage = "业务处理失败！";
					if(StringUtils.isNotEmpty(appMessage)){
						ErrorMessage = appMessage;
					}
				}
				return "300#"+ErrorMessage;
			}
			Element responseBody = rootElement.element("responseBody");
			for(Iterator r = responseBody.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("payNo".equals(node_r.getName())){
					payNo = node_r.getText();
				}
				if("payUrl".equals(node_r.getName())){
					payUrl = node_r.getText();
				}
			}
			return "200#"+payNo+"#"+payUrl;
		}catch (Exception e){
			logger.info("getCAZFDZResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 支付结果解析 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:12
	 * @version
	 * @注意事项 </b>
	 */
	private String getCAZFJGResult(String originalXML) {
		String ResponseCode = ConstProp.BLANK_CHAR;
		String ErrorMessage = ConstProp.BLANK_CHAR;
		String payNo = ConstProp.BLANK_CHAR;
		String payResult = ConstProp.BLANK_CHAR;//0未支付，1支付成功，2，无效
		String payType = ConstProp.BLANK_CHAR;//wechat微信支付,Alipay支付宝支付,yeepay易宝支付,unionPay银联支付
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			Element responseHead = rootElement.element("responseHead");
			for(Iterator r = responseHead.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("esbCode".equals(node_r.getName())){
					ResponseCode = node_r.getText();
				}
				if("esbMessage".equals(node_r.getName())){
					ErrorMessage = node_r.getText();
				}
			}
			if(!"00".equals(ResponseCode)){
				if(StringUtils.isEmpty(ErrorMessage)){
					ErrorMessage = "业务处理失败！";
				}
				return "300#"+ErrorMessage;
			}
			Element responseBody = rootElement.element("responseBody");
			for(Iterator r = responseBody.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("payNo".equals(node_r.getName())){
					payNo = node_r.getText();
				}
				if("payResult".equals(node_r.getName())){
					payResult = node_r.getText();
				}
				if("payType".equals(node_r.getName())){
					payType = node_r.getText();
				}
			}
			return "200#"+payNo+"#"+payResult+"#"+payType;
		}catch (Exception e){
			logger.info("getCAZFJGResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 保单落地反向通知报文解析 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:12
	 * @version
	 * @注意事项 </b>
	 */
	public String getHDBDResult(String originalXML) {
		String proposalNo = ConstProp.BLANK_CHAR;//投保单号
		String policyNo = ConstProp.BLANK_CHAR;//保单号
		String ePolicy = ConstProp.BLANK_CHAR;//电子保单下载地址
		String eGpolicy = ConstProp.BLANK_CHAR;//保函链接地址
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			Element UNDWRTRESULTNOTICE = rootElement.element("UNDWRTRESULTNOTICE");
			for(Iterator r = UNDWRTRESULTNOTICE.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("proposalNo".equals(node_r.getName())){
					proposalNo = node_r.getText();
				}
				if("policyNo".equals(node_r.getName())){
					policyNo = node_r.getText();
				}
				if("ePolicy".equals(node_r.getName())){
					ePolicy = node_r.getText();
				}
				if("eGpolicy".equals(node_r.getName())){
					eGpolicy = node_r.getText();
				}
			}
			return "200#"+proposalNo+"#"+policyNo+"#"+ePolicy+"#"+eGpolicy;
		}catch (Exception e){
			logger.info("getHDBDResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 批单落地反向通知报文解析 </b>
	 * @author ZXF
	 * @create 2021/03/01 0001 16:12
	 * @version
	 * @注意事项 </b>
	 */
	public String getHDPDResult(String originalXML) {
		String CertiNo = ConstProp.BLANK_CHAR;//暂存单号
		String EndorNo = ConstProp.BLANK_CHAR;//批单号
		String UnderwriteFlag = ConstProp.BLANK_CHAR;//核保标识 0-初始值;1-通过;2-不通过;3-无需核保;9-待核保;5-人工预核保;6-自动预核保
		String UnderwriteOpinion = ConstProp.BLANK_CHAR;//核保结果
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			Element UNDWRTRESULTNOTICE = rootElement.element("UNDWRTRESULTNOTICE");
			for(Iterator r = UNDWRTRESULTNOTICE.elementIterator(); r.hasNext();){
				Element node_r = (Element) r.next();
				if("CertiNo".equals(node_r.getName())){
					CertiNo = node_r.getText();
				}
				if("EndorNo".equals(node_r.getName())){
					EndorNo = node_r.getText();
				}
				if("UnderwriteFlag".equals(node_r.getName())){
					UnderwriteFlag = node_r.getText();
				}
				if("UnderwriteOpinion".equals(node_r.getName())){
					UnderwriteOpinion = node_r.getText();
				}
			}
			return "200#"+CertiNo+"#"+EndorNo+"#"+UnderwriteFlag+"#"+UnderwriteOpinion;
		}catch (Exception e){
			logger.info("getHDBDResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 *	核保接口返回字符串解析
	 * @return
	 */
	public String returnAnalysisXML(String xml, String transType){
		if(TransTypeEnum.HB.getValue().equals(transType)) {
			//核保
			return getCAHBResult(xml);
		}else if(TransTypeEnum.CBQR.getValue().equals(transType)) {
			return getCACBQRResult(xml);
		}else if(TransTypeEnum.ZFDZ.getValue().equals(transType)) {
			//获取支付地址
			return getCAZFDZResult(xml);
		}else if(TransTypeEnum.BASL.getValue().equals(transType)) {
			//报案
			return getCABASLResult(xml);
		}else if(TransTypeEnum.CLSC.getValue().equals(transType)) {
			//上传文件
			return getCACLSCResult(xml);
		}else if(TransTypeEnum.AJCX.getValue().equals(transType)) {
			//案件查询
			return getCAAJCXResult(xml);
		}else if(TransTypeEnum.XXCB.getValue().equals(transType)) {
			//线下承保回调
			return getCAXXCBResult(xml);
		}else if(TransTypeEnum.DZFP.getValue().equals(transType)) {
			//线下承保回调
			return getBDDZFPResult(xml);
		}else if(TransTypeEnum.PDDZFP.getValue().equals(transType)) {
			//线下承保回调
			return getPDDZFPResult(xml);
		}
		return ConstProp.BLANK_CHAR;
	}

	/**
	 * <b>
	 *     根据保险公司电子保单下载地址转存成自己平台的下载地址（该方法暂未用）
	 * </b>
	 * @param pno 保单号
	 * @param rb_url 电子保单下载地址
	 * @author ZXF
	 * @create 2018/06/07 0007 11:01
	 * @version
	 * @注意事项 </b>
	 */
	private 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 = "CAGZ"+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;
	}
}
