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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.third.gzx.huatai.HttpUtil;
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.mybatisplus.toolkit.StringUtils;
import com.google.common.collect.Maps;
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 org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

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

	protected Document requestDocument;
	protected Element rootElement;

	void GZZRX_PackageMessageZhongHua(){

	}

	private static String jsonString = "{\"publicOrderVo\": {\"policyApplicantVo\": {\"appAddr\": \"\",\"appBirthday\": \"\",\"appContact\": \"\",\"appEmail\": \"\",\"appGender\": \"\",\"appName\": \"\",\"appNum\": \"\",\"appType\": \"\",\"appidType\": \"\",\"apptelNum\": \"\",\"bankAccount\": \"\",\"depositBank\": \"\",\"exclArea\": \"\",\"exclPhone\": \"\",\"taxCertifi\": \"\",\"visaType\": \"\"},\"policyBeneficiaryVos\": [{\"benefitIdType\": \"\",\"benefitListNum\": 0,\"benefitName\": \"\",\"benefitNum\": \"\",\"benefitRelation\": \"\",\"benefitTelNum\": \"\",\"insuredNo\": 0,\"share\": \"\"}],\"policyDynamicVos\": [{\"dynamicId\": \"\",\"dynamicKey\": \"\",\"dynamicMean\": \"\",\"dynamicValue\": \"\",\"insuredNo\": 0,\"itemNo\": 0}],\"policyInsuredVos\": [{\"contactsName\": \"\",\"contactsPhon\": \"\",\"identifyValidEndDate\": \"\",\"identifyValidStartDate\": \"\",\"insuredAddr\": \"\",\"insuredBirthday\": \"\",\"insuredEmail\": \"\",\"insuredGender\": \"\",\"insuredIdType\": \"\",\"insuredName\": \"\",\"insuredNo\": 0,\"insuredNum\": \"\",\"insuredPremium\": 0,\"insuredTelNum\": \"\",\"insuredType\": \"\",\"isHolder\": \"\",\"islegal\": \"\",\"itemNo\": 0,\"relationship\": \"\"}],\"policyMainVo\": {\"amount\": 0,\"amtCur\": \"\",\"chlCode\": \"\",\"chlName\": \"\",\"chlOrderNo\": \"\",\"chlUserCode\": \"\",\"chlUserOffice\": \"\",\"copy\": 0,\"dataProducer\": \"\",\"effectiveTm\": \"\",\"openId\": \"\",\"paymentWayCode\": \"\",\"premium\": 0,\"prmCur\": \"\",\"proTm\": \"\",\"productCode\": \"\",\"terminalTm\": \"\"},\"policyProgrammeVos\": [{\"isAutorenewal\": \"\",\"isRenewal\": \"\",\"srcPlyNo\": \"\",\"policyPaymentPlanVos\": [{\"payOrderNo\": \"\",\"payType\": \"\",\"periodNo\": 0,\"rdSeq\": \"\",\"realPayDate\": \"\",\"realPayPremium\": 0,\"shouldPayDate\": \"\",\"shouldPayPremium\": 0}],\"policyRdrCategoryVos\": [{\"itemNo\": 0,\"personDecimal\": \"\",\"plan\": \"\",\"policyRdrVos\": [{\"itemNo\": 1,\"rdrAmount\": \"\",\"rdrCode\": \"\",\"rdrName\": \"\"}]}]}]},\"requestHeadVo\": {\"channelCode\": \"\",\"requestType\": \"\",\"migrationChannelCode\": \"\",\"chnlDptCode\": \"\",\"thirdTransId\": \"\"}}";
	private static String payJsonString = "{\"paysigningVo\":{\"appId\":\"\",\"browserLogo\":\"\",\"chlCde\":\"\",\"contractInfoList\":[{\"contractNo\":\"\",\"periodNo\":0}],\"openId\":\"\",\"payAmount\":0,\"remark\":\"\",\"settleMode\":\"\",\"successfulJumpAddress\":\"\"},\"requestHeadVo\":{\"channelCode\":\"\",\"requestType\":\"\",\"thirdTransId\":\"\"}}";
	private static String fpJsonString = "{\"policyNo\":\"\",\"invoiceTitle\":\"\",\"creditCode\":\"\",\"companyAddress\":\"\",\"companyPhone\":\"\",\"bankName\":\"\",\"bankAccount\":\"\",\"telephone\":\"\",\"email\":\"\",\"periodNo\":\"1\",\"applicantDate\":\"\"}";
	//人员信息批改审核算费接口
	private static String edrReviewPremiumJsonString = "{\"plyInsuredVos\":[],\"plyInfoVo\":{\"plyNo\":\"保单号\",\"edrType\":\"批改类型\",\"chlCode\":\"渠道代码\",\"edrTime\":\"批改生效时间\"}}";
	//批改确认信息受理接口
	private static String edrConfirmJsonString = "{\"plyNo\": \"保单号\",\"orderNo\": \"订单号\",\"edrTime\": \"批改申请时间\"}";


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

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

	private static String getToken(){
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return request.getParameter("ACCESS_TOKEN");
	}
	public static void main(String[] args) {
		String originalJson = "{\n" +
				"\"guaranteeUrl\": \"\",\n" +
				"\"orderNo\": \"123\",\n" +
				"\"policyNo\": \"321\",\n" +
				"\"policyUrl\": \"111\"\n" +
				"}\n";
		Map<String, String> map = HttpUtil.getMapValue(originalJson);
		System.out.println("200#"+map.get("orderNo")+"#"+map.get("policyNo")+"#"+map.get("policyUrl"));
//		JSONObject jsonObject = JSON.parseObject(jsonString);
//		JSONObject publicOrderVo = jsonObject.getJSONObject("publicOrderVo");
//		JSONObject policyApplicantVo = publicOrderVo.getJSONObject("policyApplicantVo");
//		policyApplicantVo.put("appNum", "1000");
//		policyApplicantVo.put("appBirthday", "2023-11-22");
//		System.out.println(jsonObject.toJSONString());

		/*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(GMRPolicyVo vo, OrderFormVo dto, String transType, InsPreservationRecordVo iprVo){
		String result = ConstProp.BLANK_CHAR;
		try {
			if(TransTypeEnum.HB.getValue().equals(transType)){//核保
				JSONObject jsonObject = JSON.parseObject(jsonString);
				JSONObject publicOrderVo = jsonObject.getJSONObject("publicOrderVo");
				RoleSubjectVo rpApplicant=vo.getRoleSubjectList().get(0);
				JSONObject policyApplicantVo = publicOrderVo.getJSONObject("policyApplicantVo");//投保人信息
				policyApplicantVo.put("appAddr",RegionUtils.getRegionNameByALLCode(rpApplicant.getReg_province(),rpApplicant.getReg_city(),rpApplicant.getReg_district())+rpApplicant.getReg_address());//投保人地址
				policyApplicantVo.put("appBirthday", "");//投保人生日（投保人为团体时可不传）
				policyApplicantVo.put("appContact", rpApplicant.getLink_name());//投保人联系人
				policyApplicantVo.put("appEmail", rpApplicant.getLink_email());//投保人邮箱
				policyApplicantVo.put("appGender", "");//投保人性别；可用值:1:男,2:女,9:未说明 （投保人为团体时可不传）
				policyApplicantVo.put("appName", rpApplicant.getName_cn());//投保人姓名
				policyApplicantVo.put("appNum", rpApplicant.getOrganization_code());//投保人证件号码
				policyApplicantVo.put("appType", "2");//投保人类型；可用值:1:个人,2:团体人姓名
				if("2".equals(rpApplicant.getId_type())){
					policyApplicantVo.put("appidType", "97");// 投保人证件类型2-三证合一统一信用代码
				} else {
					policyApplicantVo.put("appidType", "99");// 投保人证件类型99-其它
				}
				policyApplicantVo.put("apptelNum", rpApplicant.getLink_tel());//投保人电话号/投保人联系人电话

				if(vo.getMailPolicyVo()!=null&& Constant.POLICY_NEED_RECEIPT.equals(vo.getMailPolicyVo().getNeed_receipt())){
					//增值税
					if(Constant.POLICY_INVOICE_TYPE_TWO.equals(vo.getMailPolicyVo().getInvoice_type())){
						String TaxNumber = StringUtils.isEmpty(vo.getMailPolicyVo().getTaxpayer_number_invoice())?"":vo.getMailPolicyVo().getTaxpayer_number_invoice();
						String TaxRegistAddress = StringUtils.isEmpty(vo.getMailPolicyVo().getRegister_address_invoice())?"":vo.getMailPolicyVo().getRegister_address_invoice();
						String Bank = StringUtils.isEmpty(vo.getMailPolicyVo().getBank_invoice())?"":vo.getMailPolicyVo().getBank_invoice();
						String Account = StringUtils.isEmpty(vo.getMailPolicyVo().getBank_account_invoice())?"":vo.getMailPolicyVo().getBank_account_invoice();
						policyApplicantVo.put("bankAccount", Account);//银行账户
						policyApplicantVo.put("depositBank", Bank);//开户银行
						policyApplicantVo.put("exclArea", TaxRegistAddress);//专票地址
						policyApplicantVo.put("exclPhone",  vo.getMailPolicyVo().getReceipt_phone());//专票电话
						policyApplicantVo.put("taxCertifi", TaxNumber);//纳税人识别号
					}
					policyApplicantVo.put("visaType", ConstProp.DIGIT_ZERO.equals(vo.getMailPolicyVo().getInvoice_type())?"2":"3");//发票类型,可用值:1普票,2电子发票,3专票
				}

				publicOrderVo.put("policyBeneficiaryVos", new JSONArray());

				JSONArray policyInsuredVos = new JSONArray();//被保险人信息
				JSONObject policyInsuredVo;
				int count=1;
				for(RoleSubjectVo rpInsured : vo.getRoleSubjectList()){
					if("1".equals(rpInsured.getKind())){
						continue;
					}
					policyInsuredVo = new JSONObject();
					policyInsuredVo.put("contactsName", "");//联系人姓名
					policyInsuredVo.put("contactsPhon", "");//联系人电话
					policyInsuredVo.put("identifyValidEndDate", "");//被保人证件有效止期
					policyInsuredVo.put("identifyValidStartDate", "");//被保人证件有效起期
					policyInsuredVo.put("insuredAddr", "");//被保人地址
					policyInsuredVo.put("insuredBirthday", DateUtil.formatDate(DateUtil.convertStringToDate(rpInsured.getBirth_date()),"yyyy-MM-dd"));//被保人生日YYYY-MM-DD （被保险人为团体时可不传）
					policyInsuredVo.put("insuredEmail", "");//被保人邮箱 若传递，验证邮箱格式
					policyInsuredVo.put("insuredGender", rpInsured.getSex());//被保人性别;可用值:1:男,2:女,9未说明 （被保险人为团体时可不传）
					policyInsuredVo.put("insuredIdType", "01");// 证件类型01居民身份证
					policyInsuredVo.put("insuredName", rpInsured.getName_cn());//被保人姓名
					policyInsuredVo.put("insuredNo", count);//被保险人序号
					policyInsuredVo.put("insuredNum", rpInsured.getOrganization_code());//被保人证件号
					policyInsuredVo.put("insuredTelNum", rpInsured.getLink_tel());//被保人电话号
					policyInsuredVo.put("insuredType", "1");//被保人类型;可用值:1:个人,2:团体
					policyInsuredVo.put("isHolder", "0");//是否同投保人,可用值:1:是,0:否
					policyInsuredVo.put("islegal", "1");//（默认是）是否法定受益人，如是则无需传递受益人详细信息,可用值:0:否,1:是
					policyInsuredVo.put("itemNo", 1);//标的序号
					policyInsuredVo.put("relationship", "99");//被保人与投保人关系,可用值:00:本人，01:配偶，02:父母，03子女
					policyInsuredVo.put("creditLevel", "HT3001244");//职业类别（码表见职业风险类别，具体产品以联调时提供为准）算费因子为职业类别时必传
					policyInsuredVo.put("occupationCodeName", ConstProp.DIGIT_ONE.equals(rpInsured.getMajor_group())?"内勤人员":ConstProp.DIGIT_TWO.equals(rpInsured.getMajor_group())?"保安人员":ConstProp.DIGIT_THREE.equals(rpInsured.getMajor_group())?"武装押运人员":"保洁人员");//工种说明
					policyInsuredVos.add(policyInsuredVo);
					count++;
				}
				publicOrderVo.put("policyInsuredVos", policyInsuredVos);

				JSONObject policyMainVo = publicOrderVo.getJSONObject("policyMainVo");//主信息
				policyMainVo.put("productCode", getActivityName(dto.getProduct_code()).substring(0,4));//销售产品代码 TODO
				policyMainVo.put("amount", dto.getInsured_amount());//总保额
				policyMainVo.put("amtCur", "01");//保额币种
				policyMainVo.put("chlCode", GlobalResources.HT_TYX_CHANNELCODE);//渠道编码
				policyMainVo.put("chlName", "百川信（北京）信息服务有限公司");//渠道名称
				policyMainVo.put("chlOrderNo", dto.getTrade_serial_number());//渠道方订单号
				policyMainVo.put("chlUserCode", "");//操作人员工号
				policyMainVo.put("chlUserOffice", "");//渠道公司操作人员所在营业部代码（项目公司编码）
				policyMainVo.put("copy", "1");//份数 默认1份
				policyMainVo.put("dataProducer", "AP");//数据系统来源 华泰与渠道方协商定义,可用值:AP ：接口对接
				policyMainVo.put("effectiveTm", dto.getInception_date()+" 00:00:00");//保险起期（YYYY-MM-DD HH:ss:mm)
				policyMainVo.put("openId", "");//微信申请所传openid
				policyMainVo.put("paymentWayCode", "1");//缴费方式代码,可用值:1:趸缴,2:分期
				policyMainVo.put("premium", dto.getGross_premium());//实收总保费
				policyMainVo.put("prmCur", "01");//保费币种
				policyMainVo.put("proTm", dto.getStart_time());//投保时间
				policyMainVo.put("terminalTm", dto.getPlanned_end_date()+" 23:59:59");//保险止期

				JSONArray policyDynamicVos = new JSONArray();

				SpecialExhibitionVo seVo = vo.getSpecialExhibitionVo();
				JSONObject policyDynamicVo1 = new JSONObject();
				policyDynamicVo1.put("dynamicKey", "activityName");//特殊字段代码
				policyDynamicVo1.put("dynamicId", "1");//序号从1开始
				policyDynamicVo1.put("itemNo", 1);//标的序号（无多标的默认传1）
				policyDynamicVo1.put("dynamicValue", seVo.getName());//特殊字段值 (根据具体产品传对应字段，联调时确认) 现有可以动态字段列表
				policyDynamicVo1.put("dynamicMean", "活动名称");//特殊字段含义,列如：航班号
				policyDynamicVos.add(policyDynamicVo1);

				JSONObject policyDynamicVo2 = new JSONObject();
				policyDynamicVo2.put("dynamicKey", "activityAddress");//特殊字段代码
				policyDynamicVo2.put("dynamicId", "2");//序号从1开始
				policyDynamicVo2.put("itemNo", 1);//标的序号（无多标的默认传1）
				policyDynamicVo2.put("dynamicValue", RegionUtils.getRegionNameByALLCode(seVo.getEx_province(),seVo.getEx_city(),seVo.getEx_county())+seVo.getEx_address());//特殊字段值 (根据具体产品传对应字段，联调时确认) 现有可以动态字段列表
				policyDynamicVo2.put("dynamicMean", "活动地址");//特殊字段含义,列如：航班号
				policyDynamicVos.add(policyDynamicVo2);

				JSONObject policyDynamicVo3 = new JSONObject();
				policyDynamicVo3.put("dynamicKey", "activityStartTm");//特殊字段代码
				policyDynamicVo3.put("dynamicId", "3");//序号从1开始
				policyDynamicVo3.put("itemNo", 1);//标的序号（无多标的默认传1）
				policyDynamicVo3.put("dynamicValue", seVo.getStar_time());//特殊字段值 (根据具体产品传对应字段，联调时确认) 现有可以动态字段列表
				policyDynamicVo3.put("dynamicMean", "活动开始日期");//特殊字段含义,列如：航班号
				policyDynamicVos.add(policyDynamicVo3);

				JSONObject policyDynamicVo4 = new JSONObject();
				policyDynamicVo4.put("dynamicKey", "activityEndTm");//特殊字段代码
				policyDynamicVo4.put("dynamicId", "4");//序号从1开始
				policyDynamicVo4.put("itemNo", 1);//标的序号（无多标的默认传1）
				policyDynamicVo4.put("dynamicValue", seVo.getEnd_time());//特殊字段值 (根据具体产品传对应字段，联调时确认) 现有可以动态字段列表
				policyDynamicVo4.put("dynamicMean", "活动结束日期");//特殊字段含义,列如：航班号
				policyDynamicVos.add(policyDynamicVo4);
				publicOrderVo.put("policyDynamicVos",policyDynamicVos);

				JSONArray policyProgrammeVos = publicOrderVo.getJSONArray("policyProgrammeVos");
				JSONObject policyProgrammeVo = (JSONObject)policyProgrammeVos.get(0);
				policyProgrammeVo.put("copy", "1");//
				policyProgrammeVo.put("itemNo", "1");//

				policyProgrammeVo.put("policyPaymentPlanVos", new JSONArray());

				JSONArray policyRdrCategoryVos = new JSONArray();
				JSONObject policyRdrCategoryVo = new JSONObject();
				policyRdrCategoryVo.put("itemNo","1");
				policyRdrCategoryVo.put("personDecimal",(vo.getRoleSubjectList().size()-1));
				policyRdrCategoryVo.put("plan",getActivityName(dto.getProduct_code()));
				policyRdrCategoryVos.add(policyRdrCategoryVo);
				policyProgrammeVo.put("policyRdrCategoryVos", policyRdrCategoryVos);


				JSONArray policyItemVos = new JSONArray();//财产险方案分类
//				JSONObject policyItemVo = new JSONObject();
//				policyItemVo.put("itemNo", "1");//标的序号
//				policyItemVo.put("plan", getActivityName(dto.getProduct_code()));//款别
//				policyItemVo.put("bldArea", seVo.getEx_acreage());//营业面积
//				policyItemVo.put("address", RegionUtils.getRegionNameByALLCode(seVo.getEx_province(),seVo.getEx_city(),seVo.getEx_county())+seVo.getEx_address()+" "+seVo.getEx_no());//标的物详细地址
//				policyItemVo.put("itmeName", seVo.getName());//标的名称
//				String insNature = StringUtils.isEmpty(rpInsured.getNature_two())?NatureLinkage.get(rpInsured.getCom_nature()).getName():NatureLinkage.get(rpInsured.getNature_two()).getName();
//				policyItemVo.put("natureBusiness", insNature);//营业性质
//				policyItemVos.add(policyItemVo);
				policyProgrammeVo.put("policyItemVos", policyItemVos);

				JSONObject requestHeadVo = jsonObject.getJSONObject("requestHeadVo");
				requestHeadVo.put("channelCode", GlobalResources.HT_TYX_CHANNELCODE);//渠道代码
				requestHeadVo.put("requestType", "HTIC010");//HTIC002
				requestHeadVo.put("migrationChannelCode", "");//第三方序列号
				requestHeadVo.put("chnlDptCode", "");//燃气公司编码
				requestHeadVo.put("thirdTransId", "");//外部渠道编码


				result = jsonObject.toJSONString();
			}else if(TransTypeEnum.TOB.getValue().equals(transType)){//投保
				JSONObject jsonObject = JSON.parseObject(jsonString);
				JSONObject publicOrderVo = jsonObject.getJSONObject("publicOrderVo");
				RoleSubjectVo rpApplicant=vo.getRoleSubjectList().get(0);
				JSONObject policyApplicantVo = publicOrderVo.getJSONObject("policyApplicantVo");//投保人信息
				policyApplicantVo.put("appAddr",RegionUtils.getRegionNameByALLCode(rpApplicant.getReg_province(),rpApplicant.getReg_city(),rpApplicant.getReg_district())+rpApplicant.getReg_address());//投保人地址
				policyApplicantVo.put("appBirthday", "");//投保人生日（投保人为团体时可不传）
				policyApplicantVo.put("appContact", rpApplicant.getLink_name());//投保人联系人
				policyApplicantVo.put("appEmail", rpApplicant.getLink_email());//投保人邮箱
				policyApplicantVo.put("appGender", "");//投保人性别；可用值:1:男,2:女,9:未说明 （投保人为团体时可不传）
				policyApplicantVo.put("appName", rpApplicant.getName_cn());//投保人姓名
				policyApplicantVo.put("appNum", rpApplicant.getOrganization_code());//投保人证件号码
				policyApplicantVo.put("appType", "2");//投保人类型；可用值:1:个人,2:团体人姓名
				if("2".equals(rpApplicant.getId_type())){
					policyApplicantVo.put("appidType", "97");// 投保人证件类型2-三证合一统一信用代码
				} else {
					policyApplicantVo.put("appidType", "99");// 投保人证件类型99-其它
				}
				policyApplicantVo.put("apptelNum", rpApplicant.getLink_tel());//投保人电话号/投保人联系人电话

				if(vo.getMailPolicyVo()!=null&& Constant.POLICY_NEED_RECEIPT.equals(vo.getMailPolicyVo().getNeed_receipt())){
					//增值税
					if(Constant.POLICY_INVOICE_TYPE_TWO.equals(vo.getMailPolicyVo().getInvoice_type())){
						String TaxNumber = StringUtils.isEmpty(vo.getMailPolicyVo().getTaxpayer_number_invoice())?"":vo.getMailPolicyVo().getTaxpayer_number_invoice();
						String TaxRegistAddress = StringUtils.isEmpty(vo.getMailPolicyVo().getRegister_address_invoice())?"":vo.getMailPolicyVo().getRegister_address_invoice();
						String Bank = StringUtils.isEmpty(vo.getMailPolicyVo().getBank_invoice())?"":vo.getMailPolicyVo().getBank_invoice();
						String Account = StringUtils.isEmpty(vo.getMailPolicyVo().getBank_account_invoice())?"":vo.getMailPolicyVo().getBank_account_invoice();
						policyApplicantVo.put("bankAccount", Account);//银行账户
						policyApplicantVo.put("depositBank", Bank);//开户银行
						policyApplicantVo.put("exclArea", TaxRegistAddress);//专票地址
						policyApplicantVo.put("exclPhone",  vo.getMailPolicyVo().getReceipt_phone());//专票电话
						policyApplicantVo.put("taxCertifi", TaxNumber);//纳税人识别号
					}
					policyApplicantVo.put("visaType", ConstProp.DIGIT_ZERO.equals(vo.getMailPolicyVo().getInvoice_type())?"2":"3");//发票类型,可用值:1普票,2电子发票,3专票
				}

				publicOrderVo.put("policyBeneficiaryVos", new JSONArray());
				JSONArray policyInsuredVos = new JSONArray();//被保险人信息
				JSONObject policyInsuredVo;
				int count=1;
				for(RoleSubjectVo rpInsured : vo.getRoleSubjectList()){
					if("1".equals(rpInsured.getKind())){
						continue;
					}
					policyInsuredVo = new JSONObject();
					policyInsuredVo.put("contactsName", "");//联系人姓名
					policyInsuredVo.put("contactsPhon", "");//联系人电话
					policyInsuredVo.put("identifyValidEndDate", "");//被保人证件有效止期
					policyInsuredVo.put("identifyValidStartDate", "");//被保人证件有效起期
					policyInsuredVo.put("insuredAddr", "");//被保人地址
					policyInsuredVo.put("insuredBirthday", DateUtil.formatDate(DateUtil.convertStringToDate(rpInsured.getBirth_date()),"yyyy-MM-dd"));//被保人生日YYYY-MM-DD （被保险人为团体时可不传）
					policyInsuredVo.put("insuredEmail", "");//被保人邮箱 若传递，验证邮箱格式
					policyInsuredVo.put("insuredGender", rpInsured.getSex());//被保人性别;可用值:1:男,2:女,9未说明 （被保险人为团体时可不传）
					policyInsuredVo.put("insuredIdType", "01");// 证件类型01居民身份证
					policyInsuredVo.put("insuredName", rpInsured.getName_cn());//被保人姓名
					policyInsuredVo.put("insuredNo", count);//被保险人序号
					policyInsuredVo.put("insuredNum", rpInsured.getOrganization_code());//被保人证件号
					policyInsuredVo.put("insuredTelNum", rpInsured.getLink_tel());//被保人电话号
					policyInsuredVo.put("insuredType", "1");//被保人类型;可用值:1:个人,2:团体
					policyInsuredVo.put("isHolder", "0");//是否同投保人,可用值:1:是,0:否
					policyInsuredVo.put("islegal", "1");//（默认是）是否法定受益人，如是则无需传递受益人详细信息,可用值:0:否,1:是
					policyInsuredVo.put("itemNo", 1);//标的序号
					policyInsuredVo.put("relationship", "99");//被保人与投保人关系,可用值:00:本人，01:配偶，02:父母，03子女
					policyInsuredVo.put("creditLevel", "HT3001244");//职业类别（码表见职业风险类别，具体产品以联调时提供为准）算费因子为职业类别时必传
					policyInsuredVo.put("occupationCodeName", ConstProp.DIGIT_ONE.equals(rpInsured.getMajor_group())?"内勤人员":ConstProp.DIGIT_TWO.equals(rpInsured.getMajor_group())?"保安人员":ConstProp.DIGIT_THREE.equals(rpInsured.getMajor_group())?"武装押运人员":"保洁人员");//工种说明
					policyInsuredVos.add(policyInsuredVo);
					count++;
				}
				publicOrderVo.put("policyInsuredVos", policyInsuredVos);

				JSONObject policyMainVo = publicOrderVo.getJSONObject("policyMainVo");//主信息
				policyMainVo.put("productCode", getActivityName(dto.getProduct_code()).substring(0,4));//销售产品代码 TODO
				policyMainVo.put("amount", dto.getInsured_amount());//总保额
				policyMainVo.put("amtCur", "01");//保额币种
				policyMainVo.put("chlCode", GlobalResources.HT_TYX_CHANNELCODE);//渠道编码
				policyMainVo.put("chlName", "百川信（北京）信息服务有限公司");//渠道名称
				policyMainVo.put("chlOrderNo", dto.getTrade_serial_number());//渠道方订单号
				policyMainVo.put("chlUserCode", "");//操作人员工号
				policyMainVo.put("chlUserOffice", "");//渠道公司操作人员所在营业部代码（项目公司编码）
				policyMainVo.put("copy", "1");//份数 默认1份
				policyMainVo.put("dataProducer", "AP");//数据系统来源 华泰与渠道方协商定义,可用值:AP ：接口对接
				policyMainVo.put("effectiveTm", dto.getInception_date()+" 00:00:00");//保险起期（YYYY-MM-DD HH:ss:mm)
				policyMainVo.put("openId", "");//微信申请所传openid
				policyMainVo.put("paymentWayCode", "1");//缴费方式代码,可用值:1:趸缴,2:分期
				policyMainVo.put("premium", dto.getGross_premium());//实收总保费
				policyMainVo.put("prmCur", "01");//保费币种
				policyMainVo.put("proTm", dto.getStart_time());//投保时间
				policyMainVo.put("terminalTm", dto.getPlanned_end_date()+" 23:59:59");//保险止期

				JSONArray policyDynamicVos = new JSONArray();
				SpecialExhibitionVo seVo = vo.getSpecialExhibitionVo();
				JSONObject policyDynamicVo1 = new JSONObject();
				policyDynamicVo1.put("dynamicKey", "activityName");//特殊字段代码
				policyDynamicVo1.put("dynamicId", "1");//序号从1开始
				policyDynamicVo1.put("itemNo", 1);//标的序号（无多标的默认传1）
				policyDynamicVo1.put("dynamicValue", seVo.getName());//特殊字段值 (根据具体产品传对应字段，联调时确认) 现有可以动态字段列表
				policyDynamicVo1.put("dynamicMean", "活动名称");//特殊字段含义,列如：航班号
				policyDynamicVos.add(policyDynamicVo1);

				JSONObject policyDynamicVo2 = new JSONObject();
				policyDynamicVo2.put("dynamicKey", "activityAddress");//特殊字段代码
				policyDynamicVo2.put("dynamicId", "2");//序号从1开始
				policyDynamicVo2.put("itemNo", 1);//标的序号（无多标的默认传1）
				policyDynamicVo2.put("dynamicValue", RegionUtils.getRegionNameByALLCode(seVo.getEx_province(),seVo.getEx_city(),seVo.getEx_county())+seVo.getEx_address());//特殊字段值 (根据具体产品传对应字段，联调时确认) 现有可以动态字段列表
				policyDynamicVo2.put("dynamicMean", "活动地址");//特殊字段含义,列如：航班号
				policyDynamicVos.add(policyDynamicVo2);

				JSONObject policyDynamicVo3 = new JSONObject();
				policyDynamicVo3.put("dynamicKey", "activityStartTm");//特殊字段代码
				policyDynamicVo3.put("dynamicId", "3");//序号从1开始
				policyDynamicVo3.put("itemNo", 1);//标的序号（无多标的默认传1）
				policyDynamicVo3.put("dynamicValue", seVo.getStar_time());//特殊字段值 (根据具体产品传对应字段，联调时确认) 现有可以动态字段列表
				policyDynamicVo3.put("dynamicMean", "活动开始日期");//特殊字段含义,列如：航班号
				policyDynamicVos.add(policyDynamicVo3);

				JSONObject policyDynamicVo4 = new JSONObject();
				policyDynamicVo4.put("dynamicKey", "activityEndTm");//特殊字段代码
				policyDynamicVo4.put("dynamicId", "4");//序号从1开始
				policyDynamicVo4.put("itemNo", 1);//标的序号（无多标的默认传1）
				policyDynamicVo4.put("dynamicValue", seVo.getEnd_time());//特殊字段值 (根据具体产品传对应字段，联调时确认) 现有可以动态字段列表
				policyDynamicVo4.put("dynamicMean", "活动结束日期");//特殊字段含义,列如：航班号
				policyDynamicVos.add(policyDynamicVo4);
				publicOrderVo.put("policyDynamicVos",policyDynamicVos);

				JSONArray policyProgrammeVos = publicOrderVo.getJSONArray("policyProgrammeVos");
				JSONObject policyProgrammeVo = (JSONObject)policyProgrammeVos.get(0);
				policyProgrammeVo.put("copy", "1");//
				policyProgrammeVo.put("itemNo", "1");//

				policyProgrammeVo.put("policyPaymentPlanVos", new JSONArray());

				JSONArray policyRdrCategoryVos = new JSONArray();
				JSONObject policyRdrCategoryVo = new JSONObject();
				policyRdrCategoryVo.put("itemNo","1");
				policyRdrCategoryVo.put("personDecimal",(vo.getRoleSubjectList().size()-1));
				policyRdrCategoryVo.put("plan",getActivityName(dto.getProduct_code()));
				policyRdrCategoryVos.add(policyRdrCategoryVo);
				policyProgrammeVo.put("policyRdrCategoryVos", policyRdrCategoryVos);


				JSONArray policyItemVos = new JSONArray();//财产险方案分类
//				JSONObject policyItemVo = new JSONObject();
//				policyItemVo.put("itemNo", "1");//标的序号
//				policyItemVo.put("plan", getActivityName(dto.getProduct_code()));//款别
//				policyItemVo.put("bldArea", seVo.getEx_acreage());//营业面积
//				policyItemVo.put("address", RegionUtils.getRegionNameByALLCode(seVo.getEx_province(),seVo.getEx_city(),seVo.getEx_county())+seVo.getEx_address()+" "+seVo.getEx_no());//标的物详细地址
//				policyItemVo.put("itmeName", seVo.getName());//标的名称
//				String insNature = StringUtils.isEmpty(rpApplicant.getNature_two())?NatureLinkage.get(rpApplicant.getCom_nature()).getName():NatureLinkage.get(rpApplicant.getNature_two()).getName();
//				policyItemVo.put("natureBusiness", insNature);//营业性质
//				policyItemVos.add(policyItemVo);
				policyProgrammeVo.put("policyItemVos", policyItemVos);

				JSONObject requestHeadVo = jsonObject.getJSONObject("requestHeadVo");
				requestHeadVo.put("channelCode", GlobalResources.HT_TYX_CHANNELCODE);//渠道代码
				requestHeadVo.put("requestType", "HTIC002");//HTIC002
				requestHeadVo.put("migrationChannelCode", "");//第三方序列号
				requestHeadVo.put("chnlDptCode", "");//燃气公司编码
				requestHeadVo.put("thirdTransId", "");//外部渠道编码


				result = jsonObject.toJSONString();
			}else if(TransTypeEnum.ZFDZ.getValue().equals(transType)){//获取支付地址
				JSONObject jsonObject = JSONObject.parseObject(payJsonString);
				JSONObject paysigningVo = jsonObject.getJSONObject("paysigningVo");
				paysigningVo.put("appId", "");//当支付类型为微信APP时，传APP应用ID；当支付方式为微信小程序时，传小程序ID，微信
				paysigningVo.put("browserLogo", "2");//浏览器标识 1 手机 2 电脑,可用值:1-手机,2-电脑
				paysigningVo.put("chlCde", "");//渠道号
				paysigningVo.put("openId", "");//微信openId，当支付类型为微信小程序支付时，必填
				paysigningVo.put("payAmount", dto.getGross_premium());//金额
				paysigningVo.put("remark", "");//交易备注
				paysigningVo.put("settleMode", "WXNative,ZFBNative,ENETPAYCOST");//支付类型-手机必填,可用值:WXNative:微信,ZFBNative：支付宝，WXJSAPI:微信公众号（手机），WXWap:h5微信（手机），WXMiniProg:微信小程序，ZFBJSAPI：支付宝浏览器ZFBWap：支付宝H5
				paysigningVo.put("successfulJumpAddress", GlobalResources.WEB_PRO_URL+"/insurance/tyx/transaction/syntony-service/"+dto.getOid()+"?ACCESS_TOKEN="+getToken());//支付同步回调地址（前端支付完成跳转地址）
				JSONArray contractInfoList = paysigningVo.getJSONArray("contractInfoList");//支付签约List
				JSONObject contractInfo = (JSONObject)contractInfoList.get(0);
				contractInfo.put("contractNo", dto.getPolicy_serial_number());//订单号 （投保返回订单号）
				contractInfo.put("periodNo", "1");//期次号
				paysigningVo.put("contractInfoList", contractInfoList);//

				JSONObject requestHeadVo = jsonObject.getJSONObject("requestHeadVo");
				requestHeadVo.put("channelCode", GlobalResources.HT_TYX_CHANNELCODE);//渠道代码
				requestHeadVo.put("requestType", "HTIC031");//HTIC031
				requestHeadVo.put("thirdTransId", "");//第三方序列号

				result = jsonObject.toJSONString();
			}else if(TransTypeEnum.PDZF.getValue().equals(transType)){//获取支付地址 PDZF
				JSONObject jsonObject = JSONObject.parseObject(payJsonString);
				JSONObject paysigningVo = jsonObject.getJSONObject("paysigningVo");
				paysigningVo.put("appId", "");//当支付类型为微信APP时，传APP应用ID；当支付方式为微信小程序时，传小程序ID，微信
				paysigningVo.put("browserLogo", "2");//浏览器标识 1 手机 2 电脑,可用值:1-手机,2-电脑
				paysigningVo.put("chlCde", "");//渠道号
				paysigningVo.put("openId", "");//微信openId，当支付类型为微信小程序支付时，必填
//				paysigningVo.put("payAmount", iprVo.getTotal_amount());//金额
				paysigningVo.put("payAmount", "6");//金额
				paysigningVo.put("remark", "");//交易备注
				paysigningVo.put("settleMode", "WXNative,ZFBNative,ENETPAYCOST");//支付类型-手机必填,可用值:WXNative:微信,ZFBNative：支付宝，WXJSAPI:微信公众号（手机），WXWap:h5微信（手机），WXMiniProg:微信小程序，ZFBJSAPI：支付宝浏览器ZFBWap：支付宝H5
				paysigningVo.put("successfulJumpAddress", GlobalResources.WEB_PRO_URL+"/insurance/tyx/transaction/syntony-service/"+dto.getOid()+"?ACCESS_TOKEN="+getToken());//支付同步回调地址（前端支付完成跳转地址）
				JSONArray contractInfoList = paysigningVo.getJSONArray("contractInfoList");//支付签约List
				JSONObject contractInfo = (JSONObject)contractInfoList.get(0);
				contractInfo.put("contractNo", iprVo.getRevise_serial_number());//订单号 （投保返回订单号）
				contractInfo.put("periodNo", "1");//期次号
				paysigningVo.put("contractInfoList", contractInfoList);//

				JSONObject requestHeadVo = jsonObject.getJSONObject("requestHeadVo");
				requestHeadVo.put("channelCode", GlobalResources.HT_TYX_CHANNELCODE);//渠道代码
				requestHeadVo.put("requestType", "HTIC031");//HTIC031
				requestHeadVo.put("thirdTransId", "");//第三方序列号

				result = jsonObject.toJSONString();
			}else if(TransTypeEnum.DZFP.getValue().equals(transType)){//申请电子发票请求报文节点组装
				RoleSubjectVo rpApplicant=vo.getRoleSubjectList().get(0);
				MailPolicyVo mvo = vo.getMailPolicyVo();
				JSONObject jsonObject = JSONObject.parseObject(fpJsonString);
				jsonObject.put("policyNo", dto.getExternal_reference());//保单号
				jsonObject.put("invoiceTitle", mvo.getReceipt_head());//发票抬头
				jsonObject.put("creditCode", mvo.getTaxpayer_number_invoice());//纳税人识别号/统一社会信用代码
				jsonObject.put("companyAddress", mvo.getTaker_address_detail());//地址（电子发票上显示的）
				jsonObject.put("companyPhone", mvo.getTaker_phone());//电话（电子发票上显示的）
				jsonObject.put("bankName", mvo.getBank_invoice());//银行名
				jsonObject.put("bankAccount", mvo.getBank_account_invoice());//开户行账户
				jsonObject.put("telephone", mvo.getTaker_mobile());//联系手机
				//发票固定发送到投保人联系人邮箱
				jsonObject.put("email", rpApplicant.getLink_email());//电子邮箱
				jsonObject.put("applicantDate", DateUtil.getCurrentDateTime());//申请时间

				result = jsonObject.toJSONString();
			}else if(TransTypeEnum.PD.getValue().equals(transType)){//批单
				JSONObject jsonObject = JSONObject.parseObject(edrReviewPremiumJsonString);
				JSONObject plyInfoVo = jsonObject.getJSONObject("plyInfoVo");
//				String type = conventPType(iprVo.getRevise_type());
				plyInfoVo.put("plyNo",dto.getExternal_reference());//保单号
				plyInfoVo.put("edrType","2");//批改类型（一次申请只能有一个批改类型）1:批改投保人信息 2:批改被保人信息 3:批改受益人信息
				plyInfoVo.put("chlCode",GlobalResources.HT_TYX_CHANNELCODE);//渠道代码
				plyInfoVo.put("edrTime",iprVo.getInception_date()+ConstProp.DAY_00);//生效日期，格式为yyyy-MM-dd
				JSONArray plyInsuredVos = jsonObject.getJSONArray("plyInsuredVos");
				doRiskPersonList(iprVo,dto,plyInsuredVos);
				result = jsonObject.toJSONString();
			}else if(TransTypeEnum.PDQR.getValue().equals(transType)){//批单确认
//				String edrTime = DateUtil.getCurrentDateTime();
//				iprVo.setRelease_time(edrTime);
				JSONObject jsonObject = JSONObject.parseObject(edrConfirmJsonString);
				jsonObject.put("plyNo",dto.getExternal_reference());//保单号
				jsonObject.put("orderNo",iprVo.getRevise_serial_number());//订单号
				jsonObject.put("edrTime",iprVo.getInception_date()+ConstProp.DAY_00);//批改申请时间
				result = jsonObject.toJSONString();
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}

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

	//人标的列表,批改被保人，修改被保人时必传
	private static void doRiskPersonList(InsPreservationRecordVo vo, OrderFormVo dto,JSONArray arr){
		JSONObject plyInsuredVo;
		String type;
		for(InsPreservationDetailVo ipdVo : vo.getInsPreservationDetailVoList()){
			plyInsuredVo = new JSONObject();
			type = conventPType(vo.getRevise_type());
			plyInsuredVo.put("operation",type);// 更改方式1：新增； 2：修改； 3：删除；
			plyInsuredVo.put("edrInsuredName",ipdVo.getName());//[非空]新雇员姓名
			plyInsuredVo.put("edrInsuredNum",ipdVo.getId_card());// [非空]证件号码
			plyInsuredVo.put("edrInsuredBirthday",DateUtil.formatDate(DateUtil.convertStringToDate(ipdVo.getBirthday()),"yyyy-MM-dd"));// 批改后生日
			plyInsuredVo.put("edrInsuredIdType","01"); //[选择性非空]status为D可空,证件类型，见附录1
			plyInsuredVo.put("edrOccupationCode","");//批改后职业工种
			plyInsuredVo.put("edrCreditLevel","HT3001244");//批改后职业风险等级
			if(("2".equals(type)||"3".equals(type))&&ipdVo.getBusiness_vo()!=null){
				plyInsuredVo.put("insuredName",ipdVo.getBusiness_vo().getName());//原雇员姓名
				plyInsuredVo.put("insuredIdType","01");//原证件类型
				plyInsuredVo.put("insuredNum",ipdVo.getBusiness_vo().getId_card());//[选择性非空]原被保人证件号码，status为U或C时非空
			}
			arr.add(plyInsuredVo);
		}

	}

	private static String getActivityName(String str){
		if(str.indexOf("HT-DQ-1")!=-1){//计划一
			return "08280001";
		}else if(str.indexOf("HT-DQ-2")!=-1){//计划二
			return "08280002";
		}else if(str.indexOf("HT-DQ-3")!=-1){//计划三
			return "08280003";
		}else if(str.indexOf("HT-DQ-4")!=-1){//计划三
			return "08280004";
		}else if(str.indexOf("HT-DQ-5")!=-1){//计划三
			return "08280005";
		}
		return "";
	}

	public static String riskfactors(String fireFight,String whether){
		if ( "ACCEPTANCE".equals(fireFight) && "HAVE".equals(whether)) {
			return "02";
		} else if ( "ACCEPTANCE".equals(fireFight) && "WITHOUT".equals(whether)) {
			return "01";
		} else if ( "EXTINGUISHER".equals(fireFight) && "HAVE".equals(whether)) {
			return "04";
		} else if ( "EXTINGUISHER".equals(fireFight) && "WITHOUT".equals(whether)) {
			return "03";
		}
		return null;
	}

	public static String venueMode(String local){
		if ( "INDOOR".equals(local) ) {
			return "01";
		} else if ( "OPEN".equals(local)) {
			return "02";
		} else if ( "OUTDOOR".equals(local)) {
			return "03";
		}
		return null;
	}

	public static String industry(){
		return "SX51022801";
	}

	/**
	 * <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 originalJson
	 * @return
	 * @throws DocumentException
	 */
	private String getHBResult(String originalJson) {
		JSONObject json = JSONObject.parseObject(originalJson);
		if("0".equals(json.get("status")+"")){
			JSONObject data = (JSONObject)json.get("data");
			String ruleResult = (String)data.get("ruleResult");
			if("1".equals(ruleResult)){
				return "200#";
			}
			return "300#"+ ("2".equals(ruleResult)?"核保失败，请线下人工投保":data.get("ruleInfo"));
		}else{
			return "300#"+json.get("statusText");
		}
	}


	/**
	 * 获得投保接口返回报文解析
	 * @param originalJson
	 * @return
	 * @throws DocumentException
	 */
	private String getTOBResult(String originalJson) {
		if(StringUtils.isEmpty(originalJson)){
			return "300#无返回信息";
		}
		JSONObject json = JSONObject.parseObject(originalJson);
		if("0".equals(json.get("status")+"")){
			JSONObject data = (JSONObject)json.get("data");
			JSONArray arr = (JSONArray)data.get("contractMainList");
			JSONObject contractMain = (JSONObject)arr.get(0);
			return "200#"+contractMain.get("orderNo")+"#"+contractMain.get("guaranteeUrl")+"#"+contractMain.get("policyUrl")+"#"+contractMain.get("policyNo")+"#"+contractMain.get("premium");
		}else{
			return "300#"+json.get("statusText");
		}
	}

	/**
	 * <b> 批单报文解析 </b>
	 * @author ZXF
	 * @create 2019/10/22 0022 14:52
	 * @version
	 * @注意事项 </b>
	 */
	private String getPDResult(String originalJson) {
		JSONObject json = JSONObject.parseObject(originalJson);
		if("0".equals(json.get("status")+"")){
			JSONObject data = (JSONObject)json.get("data");
			String checkResult = data.get("checkResult").toString();
			if("4".equals(checkResult)){
				return "300#批单申请不通过";
			}
			//200#保单号#订单号#保费
			return "200#"+data.get("plyNo")+"#"+data.get("orderNo")+"#"+data.get("edrPremium");
		}else{
			return "300#"+json.get("statusText");
		}
	}

	/**
	 * <b> 批单确认报文解析 </b>
	 * @author ZXF
	 * @create 2019/10/22 0022 14:52
	 * @version
	 * @注意事项 </b>
	 */
	private String getPDQRResult(String originalJson) {
		JSONObject json = JSONObject.parseObject(originalJson);
		if("0".equals(json.get("status")+"")){
			JSONObject data = (JSONObject)json.get("data");
			String checkResult = data.get("resultCode").toString();
			if("02".equals(checkResult)){
				return "300#受理失败";
			}
			//200#保单号#批单申请号
			return "200#"+data.get("plyNo")+"#"+data.get("orderNo");
		}else{
			return "300#"+json.get("statusText");
		}
	}

	/**
	 * <b> 电子发票申请返回报文解析 </b>
	 * @author ZXF
	 * @create 2019/09/29 0029 10:25
	 * @version
	 * @注意事项 </b>
	 */
	private String getFPResult(String originalJson) {

		if(StringUtils.isEmpty(originalJson)){
			return "300#无返回信息";
		}
		JSONObject json = JSONObject.parseObject(originalJson);
		if("0".equals(json.get("status")+"")){
			JSONObject data = (JSONObject)json.get("data");
			JSONArray arr = (JSONArray)data.get("contractMainList");
			JSONObject contractMain = (JSONObject)arr.get(0);
			return "200#"+contractMain.get("plyNo")+"#"+contractMain.get("shortLink");
		}else{
			return "300#"+json.get("statusText");
		}
	}

	/**
	 * 获得支付信息回调报文解析
	 * @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 originalJson
	 * @return
	 * @throws
	 */
	private String getZFDZResult(String originalJson) {
		JSONObject json = JSONObject.parseObject(originalJson);
		if("0".equals(json.get("status")+"")){
			JSONObject data = (JSONObject)json.get("data");
			JSONArray arr = (JSONArray)data.get("OUT");
			JSONObject contractMain = (JSONObject)arr.get(0);
			return "200#"+contractMain.get("PayURL");
		}else{
			return "300#"+json.get("statusText");
		}
	}

	/**
	 * 获得投保回调报文解析
	 * @param originalJson
	 * @return
	 * @throws
	 */
	private String getHDCBResult(String originalJson) {
		JSONObject json = JSONObject.parseObject(originalJson);
		JSONArray contractMainList = (JSONArray)json.get("contractMainList");
		JSONObject contractMain = (JSONObject)contractMainList.get(0);
		JSONArray premiumDetailVos = (JSONArray)json.get("premiumDetailVos");
		JSONObject premiumDetailVo = (JSONObject)premiumDetailVos.get(0);
		//200#订单号#保单号#保单地址#支付订单号#支付时间（时间戳）#支付方式
		return "200#"+contractMain.get("orderNo")+"#"+contractMain.get("policyNo")+"#"+contractMain.get("policyUrl")+"#"+premiumDetailVo.get("payOrderNo")+"#"+premiumDetailVo.get("shouldPayDate")+"#"+premiumDetailVo.get("payType");
	}

	/**
	 *	核保接口返回字符串解析
	 * @return
	 */
	public String returnAnalysisXML(String json, String transType){
		if(TransTypeEnum.HB.getValue().equals(transType)) {//核保
			return getHBResult(json);
		}else if(TransTypeEnum.TOB.getValue().equals(transType)) {//核保
			return getTOBResult(json);
		}else if(TransTypeEnum.ZFDZ.getValue().equals(transType)) {//获取支付地址
			return getZFDZResult(json);
		}else if(TransTypeEnum.HDCB.getValue().equals(transType)) {//获取回调承保信息
			return getHDCBResult(json);
		}else if(TransTypeEnum.ZFJG.getValue().equals(transType)) {//获取支付结果（不解析返回）
			return json;
		}else if(TransTypeEnum.DZFP.getValue().equals(transType)) {//获取电子发票申请结果
			return getFPResult(json);
		}else if(TransTypeEnum.PD.getValue().equals(transType)) {//批单
			return getPDResult(json);
		}else if(TransTypeEnum.PDQR.getValue().equals(transType)) {//批单确认
			return getPDQRResult(json);
		}
		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;
	}
}
