package com.bcxin.ins.third.tyx.renbao;

import com.bcxin.ins.third.gzzrx.renbao.util.Md5Util;
import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.util.DateUtil;
import com.bcxin.ins.util.FileHelp;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.util.http.RequestUtil;
import com.bcxin.ins.vo.*;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import com.google.common.collect.Lists;
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.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * <b> 人保-雇主责任险各接口请求数据组装 </b>
 * @author ZXF
 * @create 2018/05/24 0024 9:50
 * @version
 * @注意事项 </b>
 */
public class PackageMessageRB {
	protected Document requestDocument;
	protected Element rootElement;

	void PackageMessageRB(){

	}

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

	public static void main(String[] args) {
		/*String result = "200#TZBV201835020000000673#投保单TZBV201835020000000673自动核保通过，需见费转保单!交费通知单号为：3502180531900004,微信交费链接为：weixin://wxpay/bizpayurl?pr=nr798xV";
		String[] strs = result.split("#");
		String payNo = strs[2].split(",")[0].split("：")[1];
		String payPath = strs[2].split(",")[1].split("：")[1];
		System.out.println("payNo:"+payNo+",payPath:"+payPath);*/
//		String ph = "http://47.98.105.202:9003/api/downloadPolicy?policyNo=5CC38E3460C38DC392C3A74E151CC2AAC2BC0071C38AC3954EC29FC3B41354C3BC03C3AF3F0EC2932C7D75C29DC398&group=0";
//		String pno = "";
//		unloading_bd(pno, ph);
//		test1();
		String msg = "<ReturnInfo>\n" +
				"  <responsehead>\n" +
				"    <request_type>01020233</request_type>\n" +
				"    <uuid>4d63b859-f936-4558-8ac4-041c3be7ec10</uuid>\n" +
				"    <sender>0102</sender>\n" +
				"    <server_version>00000000</server_version>\n" +
				"    <response_code>1</response_code>\n" +
				"    <error_message></error_message>\n" +
				"    <timestamp>2018-08-29 18:04:42</timestamp>\n" +
				"  </responsehead>\n" +
				"  <policyInfoReturns>\n" +
				"    <PolicyInfoReturn>\n" +
				"      <serialNo>1</serialNo>\n" +
				"      <proposalNo>DEAC201835020000003979</proposalNo>\n" +
				"      <result>1</result>\n" +
				"      <message>二次批文保存成功且批单申请号为DEAC201835020000003979自动核批成功</message>\n" +
				"      <chgSumPremium>-0.42</chgSumPremium>\n" +
				"    </PolicyInfoReturn>\n" +
				"  </policyInfoReturns>\n" +
				"</ReturnInfo>";
		PackageMessageRB rb = new PackageMessageRB();
		String r = rb.getRBPDResult(msg);
		System.out.println(r);
	}

	public static String test1(){
		GMRPolicyVo vo = new GMRPolicyVo();
		vo.getRoleSubjectList();
		List<RoleSubjectVo> roleSubjectList = new ArrayList<RoleSubjectVo>();
		for(int i=0;i<2;i++){
			RoleSubjectVo rvo = new RoleSubjectVo();
			rvo.setName_cn("毒贩夫妇鼓捣鼓捣");
			rvo.setId_type("01");
			rvo.setOrganization_code("12345678-9");
			rvo.setLink_email("3840@qq.com");
			rvo.setLink_tel("18965192886");
			roleSubjectList.add(rvo);
		}
		List<HirelingVo> hirelingVoList = new ArrayList<HirelingVo>();
		for(int i=0;i<3;i++){
			HirelingVo hvo = new HirelingVo();
			hvo.setName("水电费");
			hvo.setId_type("01");
			hvo.setId_card("350625192212345612");
			hvo.setSex("1");
			hvo.setAge("22");
			hirelingVoList.add(hvo);
		}
		vo.setRoleSubjectList(roleSubjectList);
		OrderFormVo dto = new OrderFormVo();
		dto.setStart_time("2018-06-13 15:31:10");
		dto.setInception_date("2018-06-15");
		dto.setPlanned_end_date("2019-06-14");
		dto.setTrade_serial_number("887143801477525504");
		dto.setInsured_amount("300000");
		dto.setGross_premium("3000");

		dto.setExternal_reference("40088652");
		dto.setProduct_code("GZZRX-RB-1");

		InsPreservationRecordVo iprVo = new InsPreservationRecordVo();
		iprVo.setStart_time("2017-02-22");
		iprVo.setInception_date("2017-02-22");
		iprVo.setTotal_premium("50000");
		iprVo.setRevise_type("1");

		List<InsPreservationDetailVo> list = Lists.newArrayList();
		for(int i=0;i<3;i++){
			InsPreservationDetailVo ipdVo = new InsPreservationDetailVo();
			ipdVo.setName("哈哈哈");
			ipdVo.setSex("2");
			ipdVo.setBirthday("01-22");
			ipdVo.setId_card("350582199601313524");
			ipdVo.setId_type("4");
			list.add(ipdVo);
		}
		iprVo.setInsPreservationDetailVoList(list);

		String result = marshal(vo, dto, "1",null);
		System.out.println(result);
		return result;
	}
	private static String setMd5Value(String jsonData) throws Exception {
		Document doc = DocumentHelper.parseText(jsonData);
		Element rootElt = doc.getRootElement(); // 获取根节点
		Element generalInfo = rootElt.element("GeneralInfo");
		String uuid = generalInfo.elementText("UUID");
		String policyInfos=jsonData.substring(jsonData.indexOf("<PolicyInfo>"),jsonData.indexOf("</PolicyInfos>"));
		policyInfos = policyInfos.replaceAll ("\\r\\n", "").replaceAll(" ","").replaceAll ("\\n", "");
		String salt =  uuid.substring(uuid.length()-8,uuid.length());
		String key="$ohr619LVb6IrwG";
		//第一次加密
		String  MD5Dense = Md5Util.digestByMd5(policyInfos,key);
		//第二次加密
		String MD5salt = Md5Util.digestByMd5( MD5Dense,salt);
		System.out.println("MD5salt:"+MD5salt);
		String value =jsonData.substring(jsonData.indexOf("<Md5Value>")+10,jsonData.indexOf("</Md5Value>"));
		String result = jsonData.replace(value, MD5salt);
		System.out.println("result:"+result);
		return result;
	}

	/**
	 * 核保数据组装
	 * @param vo 投保详细信息
	 * @param dto 订单基本信息
	 * @param transType 接口类型
	 * @param iprVo 保全申请单
	 * @return
	 */
	public static String marshal(GMRPolicyVo vo, OrderFormVo dto, String transType, InsPreservationRecordVo iprVo){
		String result = ConstProp.BLANK_CHAR;
		Document requestDocument = DocumentHelper.createDocument();
		requestDocument.setXMLEncoding("GBK");
		Element apply_info_element = requestDocument.addElement("ApplyInfo");
		try {
			if(TransTypeEnum.HB.getValue().equals(transType)){//核保
				//头
				Element general_info_element = apply_info_element.addElement("GeneralInfo");
				head(general_info_element, dto);
				//内容列
				Element policy_infos_element = apply_info_element.addElement("PolicyInfos");
				//内容
				Element policy_info_element = policy_infos_element.addElement("PolicyInfo");
				policyInfo(policy_info_element, vo, dto);

				//方案代码
				Element ration_plan_element = policy_info_element.addElement("RationPlan");
				rationPlan(ration_plan_element, dto, vo);
				//投保人
				Element applicant_element = policy_info_element.addElement("Applicant");
				applicant(applicant_element, vo.getRoleSubjectList().get(0));
				//被保险人
				Element insureds_element = policy_info_element.addElement("Insureds");
				insured(insureds_element, vo.getRoleSubjectList());
				//雇员
				Element employees_element = policy_info_element.addElement("Employees");
				employees(employees_element, vo.getRoleSubjectList());

				result = setMd5Value(requestDocument.asXML());
			}else if(TransTypeEnum.PD.getValue().equals(transType)){//批单
				//头
				Element request_head_element = apply_info_element.addElement("requesthead");
				request_head(request_head_element, dto);
				//内容列
				Element policy_infos_element = apply_info_element.addElement("policyInfos");
				//内容
				Element policy_info_element = policy_infos_element.addElement("PolicyInfo");
				policy_info(policy_info_element, iprVo, dto);
				//自定义报文列
				Element prp_ptexts_element = policy_info_element.addElement("prpPtexts");
				//自定义报文
				Element prp_ptext_element = prp_ptexts_element.addElement("PrpPtext");
				prp_ptext(prp_ptext_element, iprVo, dto);
				//雇员信息批改
				Element prp_pinsured_idv_lists_element = policy_info_element.addElement("prpPinsuredIdvLists");
				prp_cname(prp_pinsured_idv_lists_element, iprVo, dto);
				//内容列
				Element prp_ppayee_accounts_element = policy_info_element.addElement("prpPpayeeAccounts");
				prp_ppayee_account(prp_ppayee_accounts_element, iprVo, dto);
				result = requestDocument.asXML();
			}


			logger.info("人保接口报文数据组装--getHBOrder："+result);
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}

	//头信息
	private static void head(Element underwrite, OrderFormVo dto) {
		//该值用于报文数据设置后替换成加密后的字符串，这里不能没有值且保证值在报文中唯一，否则之后的替换会出错
		underwrite.addElement("Md5Value").setText("74e3e47a31e0b1de3f0484fd67f931dd");
		//公司名称缩写（拼音或英文）+流水号
		underwrite.addElement("PlateformCode").setText("ECP00008");
		//报文唯一性约束（长度别超过32位，各位开发人员添加uuid密等校验
		underwrite.addElement("UUID").setText(UUID.randomUUID().toString());

	}

	//方案信息
	private static void rationPlan(Element underwrite, OrderFormVo dto, GMRPolicyVo vo) {
		//方案标识
		underwrite.addElement("RationType").setText(getPlan(dto.getProduct_code(),vo.getIs_contain_repo()));
		//
		underwrite.addElement("quantity").setText(String.valueOf(vo.getRoleSubjectList().size()-1));
	}

	private static String getPlan(String product_code, String is_contain_repo){
		String code = "";
		if("TYX-RB-1".equals(product_code)){
			code = "EAC350200m";
		}else if("TYX-RB-2".equals(product_code)){
			code = "EAC350200n";
		}else if("TYX-RB-3".equals(product_code)){
			if(ConstProp.DIGIT_ONE.equals(is_contain_repo)){
				code = "EAC3502005";
			}else if(ConstProp.DIGIT_TWO.equals(is_contain_repo)){
				code = "EAC3502006";
			}else if(ConstProp.DIGIT_THREE.equals(is_contain_repo)){
				code = "EAC350200l";
			}else{//is_contain_repo=0,只有必选方案，不包含任何可选
				code = "EAC3502004";
			}
		}else if("TYX-RB-4".equals(product_code)){
			if(ConstProp.DIGIT_ONE.equals(is_contain_repo)){
				code = "EAC350200p";
			}else if(ConstProp.DIGIT_TWO.equals(is_contain_repo)){
				code = "EAC350200q";
			}else if(ConstProp.DIGIT_THREE.equals(is_contain_repo)){
				code = "EAC350200r";
			}else{//is_contain_repo=0,只有必选方案，不包含任何可选
				code = "EAC350200o";
			}
		}else if("TYX-RB-5".equals(product_code)){
			if(ConstProp.DIGIT_ONE.equals(is_contain_repo)){
				code = "EAC350200t";
			}else if(ConstProp.DIGIT_TWO.equals(is_contain_repo)){
				code = "EAC350200u";
			}else if(ConstProp.DIGIT_THREE.equals(is_contain_repo)){
				code = "EAC350200v";
			}else{//is_contain_repo=0,只有必选方案，不包含任何可选
				code = "EAC350200s";
			}
		}else if("TYX-RB-6".equals(product_code)){
			if(ConstProp.DIGIT_ONE.equals(is_contain_repo)){
				code = "EAC350200x";
			}else if(ConstProp.DIGIT_TWO.equals(is_contain_repo)){
				code = "EAC350200y";
			}else if(ConstProp.DIGIT_THREE.equals(is_contain_repo)){
				code = "EAC350200z";
			}else{//is_contain_repo=0,只有必选方案，不包含任何可选
				code = "EAC350200w";
			}
		}
		return code;
	}

	//保单主信息 policyInfo
	private static void policyInfo(Element policyInfo, GMRPolicyVo vo, OrderFormVo dto){
		policyInfo.addElement("SerialNo").setText("1");//请求序列号
		policyInfo.addElement("RiskCode").setText("EAC");//险种代码
		policyInfo.addElement("OperateTimes").setText(dto.getStart_time());//售出保险时间
		policyInfo.addElement("StartDate").setText(dto.getInception_date());//起保日期
		policyInfo.addElement("EndDate").setText(dto.getPlanned_end_date());//终保日期
		policyInfo.addElement("StartHour").setText("0");//起保小时
		policyInfo.addElement("EndHour").setText("24");//终保小时
		policyInfo.addElement("SumAmount").setText(dto.getInsured_amount());//保单总保险金额
		policyInfo.addElement("SumPremium").setText(dto.getGross_premium());//保单总保险费
		policyInfo.addElement("ArguSolution").setText("1");//
		policyInfo.addElement("PersonNum").setText(String.valueOf(vo.getRoleSubjectList().size()-1));//
		policyInfo.addElement("Quantity").setText("1");//
	}


	//投保人信息  applicant
	private static void applicant(Element holder, RoleSubjectVo roleSubjectVo){
		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("AppliName").setText(roleSubjectVo.getName_cn());//公司名称 否
		holder.addElement("AppliIdType").setText(changeCTypeCom(roleSubjectVo.getId_type()));//证件类型，
		holder.addElement("AppliIdNo").setText(organizationCode);//证件号码
		holder.addElement("AppliIdEmail").setText(roleSubjectVo.getLink_email());//邮箱
		holder.addElement("AppliIdMobile").setText(roleSubjectVo.getLink_tel());//手机
	}

	//被保险人信息  insured
	private static void insured(Element insureds, List<RoleSubjectVo> roleSubjectVoList){
		for(RoleSubjectVo vo : roleSubjectVoList){
			if("2".equals(vo.getKind())){
				Element insured = insureds.addElement("Insured");
				insured.addElement("InsuredName").setText(vo.getName_cn());//公司名称 否
				insured.addElement("InsuredIdType").setText(changeCTypePer(vo.getId_type()));//证件类型，
				insured.addElement("InsuredIdNo").setText(vo.getOrganization_code());//证件号码
				insured.addElement("InsuredIdMobile").setText(vo.getMobile());//手机
				insured.addElement("InsuredSex").setText(vo.getSex());//性别
				insured.addElement("InsuredBirthday").setText(vo.getBirth_date());//性别
				break;
			}
		}
	}

	//扩展信息  exendInfo
	private static void exendInfo(Element insured, int count){
		insured.addElement("serialNo").setText("1");//序号
		insured.addElement("Eexts5").setText("99");//
		insured.addElement("Eexts6").setText(String.valueOf(count));//
		insured.addElement("Eexts7").setText("083");//
	}

	//雇员信息列信息  employees
	private static void employees(Element employees, List<RoleSubjectVo> roleList){
		int count = 1;
		int num = 0;
		for(RoleSubjectVo vo : roleList){
			if(!"2".equals(vo.getKind())) {
				continue;
			}
			if(num != 0){
				Element employee = employees.addElement("Employee");
				employee.addElement("serialNo").setText(String.valueOf(count));//序号
				employee.addElement("modeCode").setText(String.valueOf("1"));//组别
				employee.addElement("occupationCode").setText("保安");//职业代码
				employee.addElement("insuredName").setText(vo.getName_cn());//公司名称 否
				employee.addElement("identifyType").setText(changeCTypePer(vo.getId_type()));//证件类型，
				employee.addElement("identifyNumber").setText(vo.getOrganization_code());//证件号码
				employee.addElement("sex").setText(vo.getSex());//性别
				employee.addElement("birthday").setText(vo.getBirth_date());//性别
				/*int age;
				try {
					age = DateUtil.getAge(vo.getBirth_date());
				} catch (Exception e) {
					age = 0;
				}1800010
				employee.addElement("age").setText(String.valueOf(age));//年龄*/
				employee.addElement("jobTitle").setText("保安");//工种
				count++;
			}else{
				num ++;
			}
		}
	}

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

	//个人证件类型编码转换
	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 if("4".equals(c_t)){//台胞证
			return "26";
		}else{//其它
			return "99";
		}
	}

	//头信息
	private static void request_head(Element underwrite, OrderFormVo dto) {
		//该值用于报文数据设置后替换成加密后的字符串，这里不能没有值且保证值在报文中唯一，否则之后的替换会出错
//		underwrite.addElement("Md5Value").setText("74e3e47a31e0b1de3f0484fd67f931dd");
		//公司名称缩写（拼音或英文）+流水号
		underwrite.addElement("plateformcode").setText("ECP00008");
		//报文唯一性约束（长度别超过32位，各位开发人员添加uuid密等校验
		underwrite.addElement("uuid").setText(UUID.randomUUID().toString());
		//时间戳，记录当前时间，精确到毫秒
		underwrite.addElement("flowintime").setText(DateUtil.getCurrentDateTime());
		//0102非车险承保
		underwrite.addElement("user").setText("0102");
		//在接口管理系统中可查
		underwrite.addElement("request_type").setText("01020233");
		//供后台验证发送者身份用，使用方在接口管理系统中通过申请后获得的申请码
//		underwrite.addElement("password").setText("");
		//服务提供方接口版本号，以接口管理系统中版本为准
		underwrite.addElement("server_version").setText("00000000");
		//使用方系统编号，接口管理系统可查
		underwrite.addElement("sender").setText("0102");
	}

	//保全信息
	private static void policy_info(Element underwrite, InsPreservationRecordVo vo, OrderFormVo dto) {
		//保单号/批单申请号
		underwrite.addElement("modeid").setText(dto.getExternal_reference());
		//
		underwrite.addElement("modeType").setText("2");
		//
		underwrite.addElement("clientIp").setText(GlobalResources.map.get("RB_TYX_PD_IP"));
		//批改日期 yyyy-MM-dd
		underwrite.addElement("endorDate").setText(vo.getStart_time());
		//批改生效日期 yyyy-MM-dd
		underwrite.addElement("validDate").setText(vo.getInception_date());
		//自定义批文标志（1:表示自定义批文 0：采用系统生成批文 （如果值1但是未传自定义批文，则采用系统生成的批文））
		underwrite.addElement("isPtextFlag").setText("1");
		//是否见费标志（1：表示送见费 0：表示不送见费 （只有在批增业务情况下，该标志位有效。不传则认为送见费））
		underwrite.addElement("sendJfeeFlag").setText("1");
		//是否自动核保通过（1:表示自动核保通过 0：表示人工核保通过 （该标志位为空时，则认为人工核保通过））
		underwrite.addElement("autoUndWrtFlag").setText("1");
		String pn;
		if(ConstProp.DIGIT_THREE.equals(vo.getRevise_type())){
			pn = String.valueOf(vo.getInsPreservationDetailVoList().size()*2);
		}else{
			pn = String.valueOf(vo.getInsPreservationDetailVoList().size());
		}
		//保全人数
		underwrite.addElement("personNum").setText(pn);
	}

	//自定义报文
	private static void prp_ptext(Element underwrite, InsPreservationRecordVo vo, OrderFormVo dto) {
		//保单号
		underwrite.addElement("policyNo").setText(dto.getExternal_reference());
		//批文内容
		underwrite.addElement("endorseText").setText("正常批改");
	}
	//雇员信息批改
	private static void prp_cname(Element underwrite, InsPreservationRecordVo vo, OrderFormVo dto) {
		int count = 1;
		for(InsPreservationDetailVo ipdVo : vo.getInsPreservationDetailVoList()){

			if(ConstProp.DIGIT_THREE.equals(vo.getRevise_type())){//替换(将记录拆成2份，一增一减)
				setPrp( underwrite, ipdVo, conventPType("1"), String.valueOf(count));
				count ++;
				setPrp( underwrite, ipdVo.getBusiness_vo(), conventPType("2"), String.valueOf(count));
			}else{
				setPrp( underwrite, ipdVo, conventPType(vo.getRevise_type()), String.valueOf(count));
			}
			count ++;
		}
	}

	private static void setPrp(Element underwrite, InsPreservationDetailVo ipdVo, String tp, String sn){
		Element prp_cname_element = underwrite.addElement("PrpPinsuredIdvList");
		Element id = prp_cname_element.addElement("id");
		//序列号
		id.addElement("serialNo").setText(sn);
		//批改标志（I:表示批增，U表示修改，D:表示批减）
		prp_cname_element.addElement("flag").setText(tp);
		//组别
		prp_cname_element.addElement("groupNo").setText(String.valueOf("1"));
		//保费
		prp_cname_element.addElement("personPremium").setText(String.valueOf(""));
		//姓名
		prp_cname_element.addElement("insuredCName").setText(ipdVo.getName());
		//性别
		prp_cname_element.addElement("sex").setText(ipdVo.getSex());
		//出生日期
		prp_cname_element.addElement("birthday").setText(ipdVo.getBirthday());
		//职业代码
		prp_cname_element.addElement("occupationCode").setText(String.valueOf("保安"));
		//证件号码
		prp_cname_element.addElement("identifyNumber").setText(ipdVo.getId_card());
		//证件类型
		prp_cname_element.addElement("identifyType").setText(changeCTypePer(ipdVo.getId_type()));
	}

	//保全信息
	private static void prp_ppayee_account(Element underwrite, InsPreservationRecordVo vo, OrderFormVo dto) {
		InsPreservationDetailVo ipdVo = vo.getInsPreservationDetailVoList().get(0);
		//内容
		Element ppae = underwrite.addElement("PrpPpayeeAccount");
		//领款人类型 1 客户,2 他方（主方）,3 政府方,4 他方（主方政府）,5 联保方,6 联保方（政府）,7 共保方,8 共保方（政府）,A 续保保证金领款人,B 抵押保证金领款人C 基金委托金领款人,D 管理费领款人
		ppae.addElement("accountType").setText(String.valueOf("1"));
		//领款人名称
		ppae.addElement("accountName").setText(ipdVo.getName());
		//领款人代码
		ppae.addElement("accountCode").setText(String.valueOf("11"));
		//银行代码
		ppae.addElement("basicBankCode").setText(String.valueOf("0"));
		//银行名称
		ppae.addElement("basicBankName").setText(String.valueOf("0"));
		//银行区域代码
		ppae.addElement("recBankAreaCode").setText(String.valueOf("0"));
		//银行区域名称
		ppae.addElement("recBankAreaName").setText(String.valueOf("0"));
		//开户银行代码
		ppae.addElement("bankCode").setText(String.valueOf("0"));
		//开户银行代码名称
		ppae.addElement("bankName").setText(String.valueOf("0"));
		//领款人账号
		ppae.addElement("accountNo").setText(String.valueOf("0"));
		//联行号
		ppae.addElement("cnaps").setText(String.valueOf("0"));
		//证件类型
		ppae.addElement("identifyType").setText(changeCTypePer(ipdVo.getId_type()));
		//证件号码
		ppae.addElement("identifyNo").setText(ipdVo.getId_card());
		//领款人电话
		ppae.addElement("telephone").setText(ipdVo.getTel());
		//公私标志 1 对私,2 对公
		ppae.addElement("isPrivate").setText(String.valueOf("1"));
		//卡折标志 1 折,2 借记卡,3 贷记卡,4 准贷记卡
		ppae.addElement("cardType").setText(String.valueOf("1"));
		//是否发送短信
		ppae.addElement("sendSms").setText(String.valueOf("222"));
		//是否发送邮件
		ppae.addElement("sendMail").setText(String.valueOf("222"));
		//邮箱地址
		ppae.addElement("mailAddr").setText(String.valueOf("222"));
		//支付类型 P01 卡,P02 折,P03 对公账户,P04 支票,P05 托收,P06 其他线下转账,P07 外币支付,P08 暂挂应付款
		ppae.addElement("paymodeflag").setText(String.valueOf("P01"));
	}

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

	/**
	 * 获得人保核保接口返回报文解析
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getRBHBResult(String originalXML) {
		String code = ConstProp.BLANK_CHAR;
		String msg = ConstProp.BLANK_CHAR;
		String pno = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);
			rootElement = requestDocument.getRootElement();
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){
				Element node = (Element) i.next();
				if("GeneralInfoReturn".equals(node.getName())){
					for(Iterator r = node.elementIterator(); r.hasNext();){
						Element node_r = (Element) r.next();
						if("ErrorCode".equals(node_r.getName())){
							code = node_r.getText();
						}
						if("ErrorMessage".equals(node_r.getName())){
							msg = node_r.getText();
						}
					}
					if(!"00".equals(code)){
						return "300#"+msg;
					}
				}
				if(!"PolicyInfoReturns".equals(node.getName())){
					continue;
				}
				for(Iterator r = node.elementIterator(); r.hasNext();){
					Element node_r = (Element) r.next();
					if(!"PolicyInfoReturn".equals(node_r.getName())){
						continue;
					}
					for(Iterator t = node_r.elementIterator(); t.hasNext();){
						Element node_t = (Element) t.next();
						if("SaveResult".equals(node_t.getName())){
							code = node_t.getText();
						}
						if("SaveMessage".equals(node_t.getName())){
							msg = node_t.getText();
						}
						if("ProposalNo".equals(node_t.getName())){
							pno = node_t.getText();
						}
					}
					if(!"00".equals(code)||StringUtils.isEmpty(pno)){
						if(StringUtils.isEmpty(msg)){
							msg = "解析数据丢失";
						}
						return "300#"+msg;
					}else{
						return "200#"+pno+ConstProp.POUND_SIGN+msg;
					}
				}
			}
		}catch (Exception e){
			logger.info("getRBHBResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * 获得人保批改接口返回报文解析
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getRBPDResult(String originalXML) {
		String code = ConstProp.BLANK_CHAR;
		String msg = ConstProp.BLANK_CHAR;
		String pno = ConstProp.BLANK_CHAR;
		String batchNumber = ConstProp.BLANK_CHAR;
		String premium = ConstProp.BLANK_CHAR;
		originalXML = originalXML.replace("\n","");
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取xml文件中的节点
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){//遍历文件中的节点
				Element node = (Element) i.next();
				if("responsehead".equals(node.getName())){//获取的节点为responsehead时进行
					for(Iterator r = node.elementIterator(); r.hasNext();){
						Element node_r = (Element) r.next();
						if("response_code".equals(node_r.getName())){
							code = node_r.getText();
						}
						if("error_message".equals(node_r.getName())){
							msg = node_r.getText();
						}
					}
					if(!"0".equals(code)&&!"1".equals(code)){
						return "300#"+msg;
					}
				}
				if(!"policyInfoReturns".equals(node.getName())){
					continue;
				}
				for(Iterator r = node.elementIterator(); r.hasNext();){
					Element node_r = (Element) r.next();
					if(!"PolicyInfoReturn".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("chgSumPremium".equals(node_t.getName())){
							premium = node_t.getText();
						}
						if("message".equals(node_t.getName())){
							msg = node_t.getText();
						}
						if("proposalNo".equals(node_t.getName())){
							batchNumber = getPdh(node_t.getText());
						}
					}
					if(!ConstProp.DIGIT_ZERO.equals(code)&&!ConstProp.DIGIT_ONE.equals(code)){
						if(StringUtils.isEmpty(msg)){
							msg = "解析数据丢失";
						}
						return "300#"+msg;
					}
					if(StringUtils.isNotEmpty(msg)&&msg.contains("无法再次进行批改")){
						return "300#"+msg;
					}
					if(StringUtils.isNotEmpty(msg)&&msg.contains("无法删除")){
						return "300#"+msg;
					}
					if(StringUtils.isNotEmpty(msg)&&msg.contains(",批单号为：")){
						batchNumber = msg.split(",批单号为：")[1];
					}
					//200#保单号#批单号#保费
					return "200##"+batchNumber+ConstProp.POUND_SIGN+premium;
				}
			}
		}catch (Exception e){
			logger.info("getRBPDResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 获取批单号 </b>
	 * @param pdsqh 批单申请号
	 * @author ZXF
	 * @create 2019/12/20 0020 15:05
	 * @version
	 * @注意事项 </b>
	 */
	public static String getPdh(String pdsqh){
		return RequestUtil.sendGet(GlobalResources.map.get("RB_TYX_GET_PDH_URL"),"applyno="+pdsqh);
	}

	/**
	 * 获得人保支付信息回调报文解析
	 * @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 getRBHDZFResult(String originalXML) {
		String code = ConstProp.BLANK_CHAR;
		String msg = 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("Message".equals(node_t.getName())){
							msg = node_t.getText();
						}
					}
					if(!"1".equals(code)){
						if(StringUtils.isEmpty(msg)){
							msg = "解析数据丢失";
						}
						return "300#"+msg;
					}else{
						return "200#"+msg;//200#信息
					}
				}
			}
		}catch (Exception e){
			logger.info("getRBHDCBResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 *	核保接口返回字符串解析
	 * @return
	 */
	public String returnAnalysisXML(String xml, String transType){
		if(TransTypeEnum.HB.getValue().equals(transType)) {//核保
			return getRBHBResult(xml);
		}else if(TransTypeEnum.PD.getValue().equals(transType)) {//批单
			return getRBPDResult(xml);
		}else if(TransTypeEnum.HDCB.getValue().equals(transType)) {//承保回调
			return getRBHDCBResult(xml);
		}else if(TransTypeEnum.HDZF.getValue().equals(transType)) {//批单支付回调
			return getRBHDZFResult(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.isNotEmpty(rb_url)) {
			if(StringUtils.isEmpty(pno)){
				pno = "RBGZ"+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;
	}

}
