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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.third.build.taibao.SimplePathResultXMLProcesser;
import com.bcxin.ins.third.gzzrx.taibao.util.TBRegion;
import com.bcxin.ins.third.gzzrx.taibao.util.TransType;
import com.bcxin.ins.util.*;
import com.bcxin.ins.vo.*;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.ins.vo.report_pac.InsClaimInformationVo;
import com.bcxin.ins.vo.report_pac.InsCommonReportVo;
import com.bcxin.ins.vo.report_pac.InsPaymentInfoVo;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.sf.json.JSONObject;
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.math.BigDecimal;
import java.text.DateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import static com.bcxin.ins.utils.FeeUtils.calcAmount;
import static com.bcxin.ins.utils.FeeUtils.calcPremium;
import static org.joda.time.Days.daysBetween;

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

	protected Document requestDocument;
	protected Element rootElement;
	private static Logger logger = LoggerFactory.getLogger(GZZRX_PackageMessageTaiBao.class);

	private static final String FORMAT = "json";
	private static final String SIGNTYPE = "md5";
	private static final String CHARSET = "utf-8";
	private static String DEPARTMENTCODE;
	private static String BUSINESSCHANNELCODE;
	static {
		if(GlobalResources.IS_TEST_ENVI){
			DEPARTMENTCODE = "20162";
			BUSINESSCHANNELCODE = "91350200302969730N1709019717887926648";//中佳
		}else{
			DEPARTMENTCODE = "20126";
			BUSINESSCHANNELCODE = "91350200302969730N1750908284385410061";//亚太
		}
	}
	private static final String PARTNERCODE = "91350200302969730N";
	private static final String TBUSER = "91350200302969730N";
	private static final String TBPASS = "jfx9IkYjYeFgrfeQL+0YjvrXkJDBL735Ft4Hc5Wkcbk=";
	private static final String TBPRODPASS = "gb7ajRJaIR5jTjCV7tNxI+sgzWdvILIKpEiJXc4DMlw=";
	private static final String BRANCH_CODE = "1010100";

	private static final Map<String,Map<String,String>> PLAN_CODE = Maps.newHashMap();
	private static final String planCodeKey = "planCode";
	private static final String planGroupCodeKey = "planGroupCode";
	private static final String CONTAIN_REPO = "+";
	static {

		HashMap<String, String> p1 = Maps.newHashMap();
		p1.put(planCodeKey,"PL1307030024A10000066");
		p1.put(planGroupCodeKey,"PDL20240227A00004928PG001");

		HashMap<String, String> p2 = Maps.newHashMap();
		p2.put(planCodeKey,"PL1307030024A10000058");
		p2.put(planGroupCodeKey,"PDL20240227A00004928PG002");

		HashMap<String, String> p3 = Maps.newHashMap();
		p3.put(planCodeKey,"PL1307030024A10000067");
		p3.put(planGroupCodeKey,"PDL20240227A00004928PG003");

		HashMap<String, String> p4 = Maps.newHashMap();
		p4.put(planCodeKey,"PL1307030024A10000068");
		p4.put(planGroupCodeKey,"PDL20240227A00004928PG004");

		HashMap<String, String> p5 = Maps.newHashMap();
		p5.put(planCodeKey,"PL1307030024A10000069");
		p5.put(planGroupCodeKey,"PDL20240227A00004928PG005");

		HashMap<String, String> p6 = Maps.newHashMap();
		p6.put(planCodeKey,"PL1307030024A10000070");
		p6.put(planGroupCodeKey,"PDL20240227A00004928PG006");

		HashMap<String, String> p7 = Maps.newHashMap();
		p7.put(planCodeKey,"PL1307030024A10000088");
		p7.put(planGroupCodeKey,"PDL20240329A00006243PG007");

		HashMap<String, String> p8 = Maps.newHashMap();
		p8.put(planCodeKey,"PL1307030024A10000089");
		p8.put(planGroupCodeKey,"PDL20240329A00006243PG008");

		HashMap<String, String> p9 = Maps.newHashMap();
		p9.put(planCodeKey,"PL1307030024A10000090");
		p9.put(planGroupCodeKey,"PDL20240329A00006243PG009");

		HashMap<String, String> p10 = Maps.newHashMap();
		p10.put(planCodeKey,"PL1307030024A10000091");
		p10.put(planGroupCodeKey,"PDL20240329A00006243PG010");
		PLAN_CODE.put("GZZRX-TB-1",p1);
		PLAN_CODE.put("GZZRX-TB-1"+CONTAIN_REPO,p2);
		PLAN_CODE.put("GZZRX-TB-2",p3);
		PLAN_CODE.put("GZZRX-TB-2"+CONTAIN_REPO,p4);
		PLAN_CODE.put("GZZRX-TB-3",p5);
		PLAN_CODE.put("GZZRX-TB-3"+CONTAIN_REPO,p6);
		PLAN_CODE.put("GZZRX-TB-4",p7);
		PLAN_CODE.put("GZZRX-TB-4"+CONTAIN_REPO,p8);
		PLAN_CODE.put("GZZRX-TB-5",p9);
		PLAN_CODE.put("GZZRX-TB-5"+CONTAIN_REPO,p10);
	}
	public static String marshalReport(SpecialHirelingVo shVo,String reportDetail, InsCommonReportVo vo, String transType) throws Exception {

		Document requestDocument = DocumentHelper.createDocument();
		requestDocument.setXMLEncoding("UTF-8");
		Element rootElement = requestDocument.addElement("request");
		IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
		String buiNo = String.valueOf(idWorker.getId());

		try {
			//头
			Element headElement = rootElement.addElement("head");
			marshalReportHead(buiNo, headElement,transType);

			//内容
			Element bodyElement = rootElement.addElement("body");
			Element entityElement = bodyElement.addElement("entity");
			if ( TransType.EPIC_BA.equals(transType) ) {

				//保单信息
				Element plcBase = entityElement.addElement("plcBase");
				RoleSubjectVo roleSubjectVo = shVo.getRoleSubjectList().get(1);
				String organizationCode = roleSubjectVo.getOrganization_code();
				String isrdCretType = "5";
				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];
						isrdCretType = "4";
					}
				}
				plcBase.addElement("dateSource").setText("1");//业务来源 1：雇主责任险 2：健康险理赔 3：意外险理赔
				plcBase.addElement("branchCode").setText("3030100");//分公司代码 3030100
				plcBase.addElement("isAutomaticClm").setText("0");//自动理赔标识
				plcBase.addElement("plcNo").setText(vo.getPolicy_no());//保单号
				plcBase.addElement("isrdName").setText(roleSubjectVo.getName_cn());//被保险人姓名
				plcBase.addElement("isrdCretType").setText(isrdCretType);//被保险人证件类型 "1 身份证 2 护照 3 个人其他 4 组织机构代码 5 营业证号(纳税人识别号) 6 团体其他 7 军官证 8 军官退休证 9 居民户口簿 A 士兵证 B 学生证 C 驾驶证 D 台胞证 E 少儿证 F 香港居民身份证 J 澳门居民身份证 G 法人证书 H 企业代码 I 内部编码 h 港澳台居民居住证"
				plcBase.addElement("isrdCretCode").setText(organizationCode);//被保险人证件号码
//				plcBase.addElement("isrdGender").setText("");//被保险人性别
//				plcBase.addElement("isrdAge").setText("");//被保险人年龄
				plcBase.addElement("sectionCode").setText("080");//科室代码
				plcBase.addElement("deptCode").setText("014");//部门代码
				plcBase.addElement("deptGroupCode").setText("330100");//部门组代码
				plcBase.addElement("Opreator").setText("EAJ034");//操作员
				plcBase.addElement("OpreatorbranchCode").setText("3030100");//报案操作员所属分公司代码
				plcBase.addElement("OpreatordeptCode").setText("014");//报案操作员所属部门代码
				plcBase.addElement("OpreatordeptGroupCode").setText("330100");//报案操作员所属部门组代码
				plcBase.addElement("OpreatorsectionCode").setText("080");//报案操作员所属科室代码

				//出险信息节点
				Element claim = entityElement.addElement("claim");
				claim.addElement("claimTime").setText(DateUtil.convertDateToString(DateUtil.parseDate(vo.getAccident_date()),DateUtil.FORMAT1_2));//出险时间
				claim.addElement("claimReason").setText("1100");//出险原因
				claim.addElement("claimlocation").setText(RegionUtils.getRegionNameByALLCode(vo.getAccident_province_code(),vo.getAccident_city_code(),vo.getAccident_county_code())+vo.getAccident_place());//出险地点
				claim.addElement("claimState").setText("");//出险状态
				claim.addElement("claimProcess").setText(vo.getAccident_process());//出险经过

				//报案信息节点
				Element report = entityElement.addElement("report");
				report.addElement("reportTime").setText(DateUtil.getCurrentDateTime(DateUtil.FORMAT1_2));//报案日期
				report.addElement("reportType").setText("1");//报案方式
				report.addElement("reportName").setText(roleSubjectVo.getName_cn());//报案人姓名
				report.addElement("reportTel").setText(roleSubjectVo.getLink_tel());//报案人联系电话
				report.addElement("reportCretType").setText(isrdCretType);//报案人证件类型
				report.addElement("reportCretCode").setText(organizationCode);//报案人证件号码
				report.addElement("ybbxrgx").setText("6");//报案人与出险人关系
				InsPaymentInfoVo pvo = vo.getInsPaymentInfoVo();
				report.addElement("remark").setText(pvo.getClient_bank_name()+pvo.getClient_bank_account()+pvo.getClient_name());//报案备注 备注，放银行信息：总行名称+账号+账户名称

				//雇主专属信息
				Element cEmployee = entityElement.addElement("cEmployee");
				cEmployee.addElement("name").setText(reportDetail.split("#")[0]);//出险员工姓名
				cEmployee.addElement("idtype").setText("1");//出险员工证件类型
				cEmployee.addElement("idno").setText(reportDetail.split("#")[1]);//出险员工证件号

				//文件信息
				Element fileBaseList = entityElement.addElement("fileBaseList");
				List<InsClaimInformationVo> list = vo.getClaimInformationVoList();
				for (InsClaimInformationVo cvo:list) {
					Element fileBase = fileBaseList.addElement("fileBase");
					fileBase.addElement("fileName").setText(cvo.getFile_name());//文件名
					fileBase.addElement("fileAddress").setText(cvo.getFile_path());//文件地址
					/*
					雇主：
					报案人信息(CIBS0003)==对应人瑞证件照片
					支付材料(ZJYX004)==对应人瑞银行卡照片
					索赔清单(CIBS0010)==对应人瑞发票、病例、费用明细、检查报告
					鉴定报告(NVC139)==对应人瑞其他材料
					 */
					String code = StringUtils.isNotEmpty(cvo.getShort_group_code())?cvo.getShort_group_code():cvo.getBig_group_code();
					fileBase.addElement("fileType").setText(fileTypeCov(code));//文件类别
				}

				//赔付银行信息
				Element PayBankInfo = entityElement.addElement("PayBankInfo");
				PayBankInfo.addElement("payMode").setText("1");//支付方式 1主动支付(银行转账)
				PayBankInfo.addElement("payObj").setText("0");//支付对象 0对公 1对私 雇主对公，产健对私
				PayBankInfo.addElement("payAmout").setText(vo.getReport_loss_sum());//支付金额
				PayBankInfo.addElement("payType").setText("1");//收款人类别 收款人类别，1 同名，2例外 （一定要有例外原因）

			} else if( TransType.EPIC_AJCX.equals(transType) ){//案件查询
				entityElement.addElement("dateSource").setText("1");//业务来源 1：雇主责任险 2：健康险理赔 3：意外险理赔
				entityElement.addElement("unitcode").setText("3030100");//分公司代码
				entityElement.addElement("registerno").setText(vo.getReport_no());//报案号

			} else if( TransType.EPIC_YXSC.equals(transType) ){//影像上传
				//保单信息
				Element plcBase = entityElement.addElement("plcBase");
				plcBase.addElement("businessNo").setText(buiNo);//业务号(订单号)
				plcBase.addElement("policyNo").setText(vo.getPolicy_no());//保单号
				plcBase.addElement("reportNo").setText(vo.getReport_no());//报案号
				plcBase.addElement("appCode").setText("CL_CIBS");//业务类型代码

				//文件信息
				Element fileBaseList = entityElement.addElement("fileBaseList");
				List<InsClaimInformationVo> list = vo.getClaimInformationVoList();
				for (InsClaimInformationVo cvo:list) {
					Element fileBase = fileBaseList.addElement("fileBase");
					fileBase.addElement("fileName").setText(cvo.getFile_name());//文件名
					fileBase.addElement("fileAddress").setText(cvo.getFile_path());//文件地址
					/*
					雇主：
					报案人信息(CIBS0003)==对应人瑞证件照片
					支付材料(ZJYX004)==对应人瑞银行卡照片
					索赔清单(CIBS0010)==对应人瑞发票、病例、费用明细、检查报告
					鉴定报告(NVC139)==对应人瑞其他材料
					 */
					String code = StringUtils.isNotEmpty(cvo.getShort_group_code())?cvo.getShort_group_code():cvo.getBig_group_code();
					fileBase.addElement("fileType").setText(fileTypeCov(code));//文件类别
				}
			}
			String requestMsg = requestDocument.asXML();

			return requestMsg;

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
	private static String fileTypeCov(String code) {
		String name = "";
		if("001000".equals(code)){
			name = "CIBS0010";
		}else if("007003".equals(code)){
			name = "CIBS0010";
		}else if("003019".equals(code)){
			name = "NVC139";
		}else if("003007".equals(code)){
			name = "CIBS0003";
		}else if("004005".equals(code)){
			name = "CIBS0010";
		}else if("004006".equals(code)){
			name = "CIBS0010";
		}else if("004006".equals(code)){
			name = "CIBS0010";
		}else if("003012".equals(code)){
			name = "NVC139";
		}else if("006004".equals(code)){
			name = "CIBS0003";
		}else if("003001".equals(code)){
			name = "NVC139";
		}else if("003007".equals(code)){
			name = "NVC139";
		}else if("005000".equals(code)){
			name = "NVC139";
		}else if("006005".equals(code)){
			name = "CIBS0003";
		}
		return name;
	}
	private static void marshalReportHead(String tsNumber, Element underwrite, String transType) {
		// 合作方编码，必传
		underwrite.addElement("partnerCode").setText(PARTNERCODE);
		// 业务交易码，必传
		underwrite.addElement("transactionCode").setText(transType);
		// 交易流水号，必传
		underwrite.addElement("messageId").setText(tsNumber);
		// 交易时间，必传yyyy-MM-dd HH:mm:ss
		DateFormat dateFormatAll = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		underwrite.addElement("transactionEffectiveDate").setText(dateFormatAll.format(new Date()));
		// 合作方用户，必传
		underwrite.addElement("user").setText(TBUSER);
		// 用户密码，必传
		underwrite.addElement("password").setText(tbPass());

	}

	private static String tbPass(){
		return GlobalResources.IS_TEST_ENVI?TBPASS:TBPRODPASS;
	}

	public static String marshal(SpecialHirelingVo vo, OrderFormVo dto, String transType, InsPreservationRecordVo iprVo) throws Exception {

		IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
		String buiNo = String.valueOf(idWorker.getId());
		JSONObject jsonHead = new JSONObject();
		jsonHead.put("partnerCode",PARTNERCODE);//合作方编码
		jsonHead.put("messageId",buiNo);//交易流水号，每次提交必须唯一(用于验证重复提交)
		jsonHead.put("transactionEffectiveDate",DateUtil.getCurrentDateTime());//交易时间
		jsonHead.put("user",TBUSER);//合作方用户
		jsonHead.put("password",tbPass());//用户密码
		//头信息
		if(TransTypeEnum.HB.getValue().equals(transType)){//核保
			jsonHead.put("transactionCode","300001");//业务交易码
			String activitiesCode = "GZZRX-TB-4,GZZRX-TB-5".contains(dto.getProduct_code())?"HL20240329A00041260":"HL20240227A00034925";
			//投保信息
			JSONObject jsonContract = new JSONObject();
			jsonContract.put("activitiesCode",activitiesCode);//活动代码
			//jsonContract.put("activitiesVersion","");//活动版本号
			jsonContract.put("branchCode",BRANCH_CODE);//分公司代码
			jsonContract.put("businessChannelCode",BUSINESSCHANNELCODE);//业务类型 1:产险 中佳91350200302969730N1709019717887926648
			jsonContract.put("plcBusinessNo",buiNo);//业务(订单)交易流水号
			jsonContract.put("plcOrderNo",dto.getTrade_serial_number());//业务号(订单号)
			jsonContract.put("plcInuredType","1");//出单方式 1见费出单
			//jsonContract.put("plcAmount",dto.getInsured_amount());//保额
			//jsonContract.put("plcPremium",dto.getGross_premium());//保费
			//jsonContract.put("plcCurrency","01");//币种
			//jsonContract.put("plcCalcPolicyFlag","0");//承保操作类型
			//jsonContract.put("insuredTime",dto.getStart_time());//投保时间
			String isPolicyBeforePayFee = dto.getIs_policy_before_pay_fee();
			jsonContract.put("paymentWay","0".equals(isPolicyBeforePayFee)? "9":"7");//支付渠道 7财猫pc版（6移动版，8小程序，9线下）
			//jsonContract.put("isReturnPolicyUrl","1");//是否返回电子保单链接
			jsonContract.put("isMoreEmployeeAndFloat","1");//是否多工种/浮动利率
			jsonContract.put("payforbackurl",GlobalResources.WEB_URL+"TB-API/GZZRX/callback-policy");//支付回调地址
			String returnUrl = GlobalResources.WEB_URL+"api/gzzrx/syntony-service/"+dto.getOid();
			if(ConstProp.BLB.equals(dto.getWeb_type())){
				returnUrl = GlobalResources.WEB_URL+"insurance/gzzrx/transaction/syntony-service/"+dto.getOid();
			}
			jsonContract.put("successUrl",returnUrl);//支付成功跳转页面
			//产品信息节点循环开始
			JSONArray productList = new JSONArray();
			JSONObject product = new JSONObject();
			String msbProductCode = "GZZRX-TB-4,GZZRX-TB-5".contains(dto.getProduct_code())?"PDL20240329A00006243":"PDL20240227A00004928";
			product.put("msbProductCode",msbProductCode);//产品代码（融e保/码上保）
			//product.put("msbProductVersion","");//产品版本号（融e保/码上保）

			//承保方案组信息节点循环开始
			JSONArray planGroupList = new JSONArray();
			JSONObject planGroup = new JSONObject();
			String containRepo = "1".equals(vo.getIs_contain_repo())? CONTAIN_REPO :"";
			planGroup.put("plangroupcode",PLAN_CODE.get(dto.getProduct_code()+containRepo).get(planGroupCodeKey));//承保方案组代码

			RoleSubjectVo roleSubjectVo = vo.getRoleSubjectList().get(0);
			//承保方案组信息节点循环开始
			JSONArray planList = new JSONArray();
			JSONObject plan = new JSONObject();
			JSONObject plnBase = new JSONObject();
			//TODO 高保额的承保方案代码？
			plnBase.put("plnPlanCode",PLAN_CODE.get(dto.getProduct_code()+containRepo).get(planCodeKey));//承保方案代码
			//plnBase.put("plnPlanVersion","");//承保方案版本号
			plnBase.put("plnStartDate",dto.getInception_date()+ConstProp.DAY_00);//保险起期
			plnBase.put("plnEndDate",LocalDate.parse(dto.getPlanned_end_date()).plusDays(1).toString()+ConstProp.DAY_00);//保险止期
			plnBase.put("plnCopies",1);//承保份数
			plnBase.put("groupInsuranceFlag","2");//保单性质 1 个单 2团单 3个团均可
			//plnBase.put("plnAmount",dto.getInsured_amount());//保额
			//plnBase.put("plnPremium",dto.getGross_premium());//保费
			//plnBase.put("plnAuditFlag","0");//核保类型
			plnBase.put("plnElcFlag","01");//打印方式
			plnBase.put("elcMsgFlag","0");//短信发送标志
			String elcEmlFlag = "0";
			String elcEmail = "";
			if(StringUtils.isNotEmpty(roleSubjectVo.getLink_email())){
				elcEmlFlag = "1";
				elcEmail = roleSubjectVo.getLink_email();
			}
			plnBase.put("elcEmlFlag",elcEmlFlag);//邮件发送标志
			plnBase.put("elcEmail",elcEmail);//邮件发送标志
			plnBase.put("recordWay","001");//录入方式 正常录入
			plnBase.put("loadPolicyFlag","1");//保单落地标志(1-落地投保单,2-落地保单)
			plnBase.put("effectiveDate",dto.getInception_date()+ConstProp.DAY_00);//
			plan.put("plnBase",plnBase);

			//投保人
			JSONArray applicantList = new JSONArray();
			JSONObject applicant = new JSONObject();
			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];
				}
			}
			applicant.put("appntType","02");//投保人类别
			applicant.put("apltName",roleSubjectVo.getName_cn());//投保人名称
			applicant.put("apltCretType",changeCTypeCom(roleSubjectVo.getId_type()));//投保人证件类型
			applicant.put("apltCretCode",organizationCode);//投保人证件号码
			//applicant.put("apltBirthday",roleSubjectVo.getId_star_date());//生日
			applicant.put("apltCretStartDate",roleSubjectVo.getId_star_date());//证件有效起期
			applicant.put("apltCretEndDate",roleSubjectVo.getId_end_date());//证件有效止期
			String apltProvinceCode = "";
			String apltCityCode = "";
			String apltAreaCode = "";
			String alias = TBRegion.getAlias(roleSubjectVo.getReg_district());
			int isCity = 0;
			if(StringUtils.isEmpty(alias)){
				alias = TBRegion.getAlias(roleSubjectVo.getReg_city());
				isCity = 1;
			}
			if(StringUtils.isNotEmpty(alias)){
				String[] regions = alias.split(",");
				apltProvinceCode = regions[0];
				apltCityCode = regions[1];
				if(isCity != 1){
					apltAreaCode = regions[2];
				}
			}
			applicant.put("apltProvinceCode",apltProvinceCode);//省代码
			applicant.put("apltCityCode",apltCityCode);//市代码
			applicant.put("apltAreaCode",apltAreaCode);//区县代码
			applicant.put("apltDistrictCode","");//省市区国标代码
			applicant.put("apltDistrictName",RegionUtils.getRegionNameByALLCode(roleSubjectVo.getReg_province(),roleSubjectVo.getReg_city(),roleSubjectVo.getReg_district()));//省市区名称
			String address = RegionUtils.getRegionNameByALLCode(roleSubjectVo.getReg_province(),roleSubjectVo.getReg_city(),roleSubjectVo.getReg_district())+roleSubjectVo.getReg_address();
			applicant.put("apltAddress",address);//投保人地址信息
			applicant.put("apltEmail",roleSubjectVo.getLink_email());//投保人email
			applicant.put("apltCntactName",roleSubjectVo.getLink_name());//组织联系人员姓名
			applicant.put("apltTelNumber",roleSubjectVo.getLink_tel());//投保人电话

			applicantList.add(applicant);

			plan.put("applicantList",applicantList);

			//投保人
			JSONArray drawerList = new JSONArray();
			JSONObject drawer = new JSONObject();
			drawer.put("draNo","1");//序号
			drawer.put("draCustomerType","02");//开票人类别 02团体 01个人
			drawer.put("draCustomerName",roleSubjectVo.getName_cn());//客户名称（共同投保人名称）
			drawer.put("draCertType",changeCTypeCom(roleSubjectVo.getId_type()));//客户证件类型（共同投保人证件类型）
			drawer.put("draCertNo",organizationCode);//客户证件号码（共同投保人证件号码）

			drawerList.add(drawer);

			plan.put("drawerList",drawerList);

			//被保险人
			JSONArray insuredList = new JSONArray();
			JSONObject insured = new JSONObject();
			RoleSubjectVo insuredVo = vo.getRoleSubjectList().get(1);
			organizationCode = insuredVo.getOrganization_code();
			if(StringUtils.isNotEmpty(organizationCode) && ConstProp.DIGIT_ONE.equals(insuredVo.getId_type())){
				if(organizationCode.contains(ConstProp.MINUS)){
					organizationCode = organizationCode.split(ConstProp.MINUS)[0]+organizationCode.split(ConstProp.MINUS)[1];
				}
			}
			insured.put("isrdIfMainInsured","1");//是否主被保险人
			insured.put("insuredType","02");//类别
			insured.put("isrdNo","1");//被保险人序号
			insured.put("isrdName",insuredVo.getName_cn());//名称
			insured.put("isrdCretType",changeCTypeCom(insuredVo.getId_type()));//证件类型
			insured.put("isrdCretCode",organizationCode);//证件号码
			insured.put("isrdCretStartDate",insuredVo.getId_star_date());//证件有效起期
			insured.put("isrdCretEndDate",insuredVo.getId_end_date());//证件有效止期
			String isrdProvinceCode = "";
			String isrdCityCode = "";
			String isrdAreaCode = "";
			alias = TBRegion.getAlias(insuredVo.getReg_district());
			isCity = 0;
			if(StringUtils.isEmpty(alias)){
				alias = TBRegion.getAlias(insuredVo.getReg_city());
				isCity = 1;
			}
			if(StringUtils.isNotEmpty(alias)){
				String[] regions = alias.split(",");
				isrdProvinceCode = regions[0];
				isrdCityCode = regions[1];
				if(isCity != 1){
					isrdAreaCode = regions[2];
				}
			}
			insured.put("isrdProvinceCode",isrdProvinceCode);//省代码
			insured.put("isrdCityCode",isrdCityCode);//市代码
			insured.put("isrdAreaCode",isrdAreaCode);//区县代码
			insured.put("isrdDistrictCode","");//省市区国标代码
			insured.put("isrdRelationshipWithApplicant","98");//与投保人关系 06 雇主 07 雇员 98未知 00本人 99其他
			insured.put("isrdBenefitWay","002");//受益方式 002法定 001其他
			String nature = ConstProp.BLANK_CHAR.equals(insuredVo.getNature_two()) ? natureLinkageSet(insuredVo.getCom_nature()) : natureLinkageSet(insuredVo.getNature_two());
			insured.put("enterpriseTypeCode",nature);//企业性质代码
			insured.put("isrdDistrictName",RegionUtils.getRegionNameByALLCode(insuredVo.getReg_province(),insuredVo.getReg_city(),insuredVo.getReg_district()));//省市区名称
			address = RegionUtils.getRegionNameByALLCode(insuredVo.getReg_province(),insuredVo.getReg_city(),insuredVo.getReg_district())+insuredVo.getReg_address();
			insured.put("isrdAddress",address);//投保人地址信息
			//insured.put("isrdBirthday",);//投保人生日
			insured.put("isrdEmail",insuredVo.getLink_email());//投保人email
			insured.put("isrdTelNumber",insuredVo.getLink_tel());//投保人电话
			insuredList.add(insured);

			plan.put("insuredList",insuredList);

			//人员清单
			JSONArray peopleDetailList = new JSONArray();
			List<HirelingVo> hirelingVoList = vo.getHirelingVoList();
			if (hirelingVoList!=null && hirelingVoList.size()>0){
				for (HirelingVo hirelingVo : hirelingVoList){
					JSONObject peopleDetail = new JSONObject();
					peopleDetail.put("code",hirelingVo.getId_card());//证件类型
					peopleDetail.put("value",hirelingVo.getName());//证件号码
					peopleDetailList.add(peopleDetail);
				}
				JSONArray s = new JSONArray();
				s.add(peopleDetailList);
				plan.put("peopleDetailList",s);
			}

			putProductFeatureInfoList(plan);
			putSubjectWrapperList(plan, dto, hirelingVoList);
			
			planList.add(plan);
			planGroup.put("planList",planList);

			planGroupList.add(planGroup);
			product.put("planGroupList",planGroupList);

			productList.add(product);
			jsonContract.put("productList",productList);

			jsonHead.put("requestBody",jsonContract);
		}
		else if (TransTypeEnum.TB.getValue().equals(transType)){//退保

			jsonHead.put("transactionCode","300003");//业务交易码
			JSONObject jsonContract = new JSONObject();
			jsonContract.put("type","1");//1-全额退保
			jsonContract.put("policyNo",dto.getExternal_reference());//保单号、批单号或者其他生成规则
			jsonContract.put("applyNo",dto.getPolicy_serial_number());//投保单号
			jsonContract.put("endorsePrintType","01");//01-电子批单
			jsonContract.put("endorseReason","退保");//批改原因 TODO 雪峰确认
			jsonHead.put("requestBody",jsonContract);
		}
		else if(TransTypeEnum.DZBD.getValue().equals(transType)){//电子保单打印
			RoleSubjectVo roleSubjectVo = vo.getRoleSubjectList().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];
				}
			}
			jsonHead.put("transactionCode","300007");//业务交易码
			JSONObject jsonContract = new JSONObject();
			jsonContract.put("policyNumber",dto.getExternal_reference());//保单号、批单号或者其他生成规则
			jsonContract.put("idNumber",organizationCode);//投保人证件号或者其他生成规则
			jsonContract.put("type","0");//1-BASE64文件流,0-返回下载链接，不传默认0
			jsonHead.put("requestBody",jsonContract);

		}
		else if(TransTypeEnum.DZFP.getValue().equals(transType)){//电子发票申请
			jsonHead.put("transactionCode","300008");//业务交易码
			JSONObject jsonContract = new JSONObject();
			String InvoiceType = "A";
			InvoiceType = ConstProp.DIGIT_ZERO.equals(vo.getMailPolicyVo().getInvoice_type()) ? InvoiceType : "B";
			jsonContract.put("invoiceType","B".equals(InvoiceType)?"2":"1");//1-电子普票,2-纸质专票
			jsonContract.put("madeOutRequire","3");//1-电子普票,3-数电普票，默认电子
			jsonContract.put("policyNo",dto.getExternal_reference());//保单号
			jsonContract.put("applyNo",dto.getPolicy_serial_number());//投保单号
			if(iprVo != null){
				jsonContract.put("pdh",iprVo.getRevise_serial_num_ins());//批单号
			}
			if("B".equals(InvoiceType)){
				RoleSubjectVo roleSubjectVo = vo.getRoleSubjectList().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];
					}
				}
				String customerName = StringUtils.isEmpty(vo.getMailPolicyVo().getReceipt_head())?"":vo.getMailPolicyVo().getReceipt_head();
				String taxPlayerRegNum = StringUtils.isEmpty(vo.getMailPolicyVo().getTaxpayer_number_invoice())?"":vo.getMailPolicyVo().getTaxpayer_number_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();
				String addressee = StringUtils.isEmpty(vo.getMailPolicyVo().getTaker_name())?"":vo.getMailPolicyVo().getTaker_name();
				String mobilePhoneNo = StringUtils.isEmpty(vo.getMailPolicyVo().getTaker_mobile())?"":vo.getMailPolicyVo().getTaker_mobile();
				String taxPlayerTelNum = StringUtils.isEmpty(vo.getMailPolicyVo().getReceipt_phone())?"":vo.getMailPolicyVo().getReceipt_phone();
				String address = StringUtils.isEmpty(vo.getMailPolicyVo().getTaker_address_detail())?"":vo.getMailPolicyVo().getTaker_address_detail();
				String taxPlayerAddress = RegionUtils.getRegionNameByALLCode(roleSubjectVo.getReg_province(),roleSubjectVo.getReg_city(),roleSubjectVo.getReg_district())+roleSubjectVo.getReg_address();
				jsonContract.put("customerName",customerName);//客户名称
				jsonContract.put("taxPlayerType","1");//纳税人类型
				jsonContract.put("taxPlayerRegNum",taxPlayerRegNum);//纳税人识别号
				jsonContract.put("customerNo",organizationCode);//客户编码
				jsonContract.put("taxPlayerAddress",taxPlayerAddress);//纳税人地址
				jsonContract.put("taxPlayerTelNum",taxPlayerTelNum);//纳税人电话
				jsonContract.put("taxPlayerBank",Bank);//纳税人开户银行
				jsonContract.put("taxPlayerBankAccountNum",Account);//纳税人开户银行账号
				jsonContract.put("emailAddress",roleSubjectVo.getLink_email());//电子邮箱
				jsonContract.put("mobilePhoneNo",mobilePhoneNo);//手机号码
				jsonContract.put("addressee",addressee);//收件人
				jsonContract.put("address",address);//收件地址
			}
			jsonHead.put("requestBody",jsonContract);
		}
		else if(TransTypeEnum.DZFPXZ.getValue().equals(transType)){//电子发票下载（开具电子普票）
			/*jsonHead.put("transactionCode","300009");//业务交易码
			JSONObject jsonContract = new JSONObject();
			jsonContract.put("ywbz","1");//0-发票查询业务,1-PDF下载,2-IMG下载,6-xml下载,type传2，不传默认1
			jsonContract.put("type","0");//1-BASE64文件流,0-下载链接，2-xml，不传默认0
			jsonContract.put("policyNo",dto.getExternal_reference());//保单号
			if(iprVo != null){
				jsonContract.put("pdh",iprVo.getRevise_serial_num_ins());//批单号
			}
			jsonHead.put("requestBody",jsonContract);*/
			jsonHead.put("transactionCode","300008");//业务交易码
			JSONObject jsonContract = new JSONObject();
			jsonContract.put("invoiceType","1");//1-电子普票,2-纸质专票
			jsonContract.put("madeOutRequire","3");//1-电子普票,3-数电普票，默认电子
			jsonContract.put("policyNo",dto.getExternal_reference());//保单号
			jsonContract.put("applyNo",dto.getPolicy_serial_number());//投保单号
			if(iprVo != null){
				jsonContract.put("pdh",iprVo.getRevise_serial_num_ins());//批单号
			}
			jsonHead.put("requestBody",jsonContract);
		}
		else if(TransTypeEnum.PD.getValue().equals(transType)){//批单
			RoleSubjectVo roleSubjectVo = vo.getRoleSubjectList().get(0);
			String organizationCode = roleSubjectVo.getOrganization_code().toUpperCase();
			jsonHead.put("transactionCode","300005");//业务交易码
			JSONObject jsonContract = new JSONObject();
			jsonContract.put("classesCode","13070300");//险种代码
			jsonContract.put("isReturnPolicyUrl","1");//是否返回电子批单链接
			//如果归属白名单的投保人，则支付渠道为线下转账
			if(StringUtils.isNotEmpty(GlobalResources.TB_GZ_RECORD_WHITE) && GlobalResources.TB_GZ_RECORD_WHITE.contains(organizationCode)){
				jsonContract.put("paymentWay","9");//支付渠道 7 pc版支付 9 线下转账
				jsonContract.put("payBeforeFlag","0");//是否见费批改
			}else if(DictConst.REVISE_TYPE_Z.equals(iprVo.getRevise_type())){
				jsonContract.put("paymentWay","7");//支付渠道 7 pc版支付 9 线下转账
				jsonContract.put("payBeforeFlag","1");//是否见费批改
				jsonContract.put("payForBackUrl",GlobalResources.WEB_URL+"TB-API/GZZRX/callback-record");//支付回传地址
				String returnUrl = GlobalResources.WEB_URL+"api/gzzrx/syntony-service-record/"+dto.getOid();
				if(ConstProp.BLB.equals(dto.getWeb_type())){
					returnUrl = GlobalResources.WEB_URL+"insurance/gzzrx/transaction/syntony-service-record/"+dto.getOid();
				}
				jsonContract.put("successUrl",returnUrl);//支付成功跳转地址
			}else{
				jsonContract.put("paymentWay","9");//支付渠道 7 pc版支付 9 线下转账
				jsonContract.put("payBeforeFlag","0");//是否见费批改
			}

			JSONObject endorseInfo = new JSONObject();

			JSONObject employeeAutoEndorseBase = new JSONObject();
			employeeAutoEndorseBase.put("operateType",iprVo.getRevise_type());//操作类型 1-加人,2-减人,3-换人
			employeeAutoEndorseBase.put("count",iprVo.getInsPreservationDetailVoList().size());//人数
			employeeAutoEndorseBase.put("policyNo",dto.getExternal_reference());//保单号 ABEJ60037124FN00001A
			employeeAutoEndorseBase.put("branchCode",BRANCH_CODE);//分公司
			employeeAutoEndorseBase.put("mborderNo",iprVo.getRevise_serial_number());//批改订单号

			endorseInfo.put("employeeAutoEndorseBase",employeeAutoEndorseBase);//

			JSONObject publicFee = new JSONObject();
			publicFee.put("currencyCode","01");//币种
			publicFee.put("amount",new BigDecimal(iprVo.getTotal_amount()));//保额
			publicFee.put("amountChange",new BigDecimal(iprVo.getTotal_amount()));//保额变化值
			publicFee.put("premium",new BigDecimal(iprVo.getTotal_premium()));//保费
			publicFee.put("premiumChange",new BigDecimal(iprVo.getTotal_premium()));//保费变化值

			endorseInfo.put("publicFee",publicFee);//

			JSONObject publicFeeDetail = new JSONObject();
			publicFeeDetail.put("currencyCode","01");//币种
			publicFeeDetail.put("amount",new BigDecimal(iprVo.getTotal_amount()));//保额
			publicFeeDetail.put("amountChange",new BigDecimal(iprVo.getTotal_amount()));//保额变化值
			publicFeeDetail.put("premium",new BigDecimal(iprVo.getTotal_premium()));//保费
			publicFeeDetail.put("premiumChange",new BigDecimal(iprVo.getTotal_premium()));//保费变化值
			endorseInfo.put("publicFeeDetail",publicFeeDetail);//

			JSONObject publicCoverage = new JSONObject();
			//TODO 雪峰确认 加减人赔偿限额计算
			publicCoverage.put("currencyCode","01");//币种
			publicCoverage.put("limitSumAmount",new BigDecimal(iprVo.getTotal_amount()));//累计赔偿限额
			publicCoverage.put("limitTimeAmount",new BigDecimal(iprVo.getTotal_amount()));//每次赔偿限额
			publicCoverage.put("premium",new BigDecimal(iprVo.getTotal_premium()));//保费
			publicCoverage.put("premiumChange",new BigDecimal(iprVo.getTotal_premium()));//保费变化值
			endorseInfo.put("publicCoverage",publicCoverage);//

			JSONArray employeeAutoEndorseDetailList = new JSONArray();
			doEmployeeAutoEndorseDetailList(iprVo,dto,employeeAutoEndorseDetailList);
			endorseInfo.put("employeeAutoEndorseDetailList",employeeAutoEndorseDetailList);//
			//减员才需要退款信息
			if(DictConst.REVISE_TYPE_J.equals(iprVo.getRevise_type())){
				JSONObject refundPay = new JSONObject();
				//TODO 雪峰确认
				Map<String, String> bnkMap = iprVo.getBankMap();
				refundPay.put("payAmount",iprVo.getTotal_premium());//支付金额
				refundPay.put("currencyCode","01");//币种
				refundPay.put("paymentMethod","1");//支付方式 0-主动支付,1-柜面领款,2-柜面领款（非现金）
				refundPay.put("payeeType","0");//收款人类别 0-同名,1-例外
				refundPay.put("accountName",roleSubjectVo.getAccount_name());//收款人户名
				refundPay.put("payObjType","1".equals(roleSubjectVo.getBank_pub_pri())?"0":"1");//支付对象性质 0-对公,1-对私
				refundPay.put("openingBankCode",bnkMap.get("code"));//开户行代码
				refundPay.put("bankCode",bnkMap.get("openingCode"));//银行代码
				refundPay.put("accountProvinceCode",bnkMap.get("province"));//开户行省代码
				refundPay.put("accountCityCode",bnkMap.get("city"));//开户行市代码
				refundPay.put("accountNo",roleSubjectVo.getBank_account());//收款账号
				endorseInfo.put("refundPay",refundPay);//
			}

			jsonContract.put("endorseInfo",endorseInfo);//
			jsonHead.put("requestBody",jsonContract);
		} else if(TransTypeEnum.PDZFCX.getValue().equals(transType)){//批单
			jsonHead.put("transactionCode","300006");//业务交易码
			JSONObject jsonContract = new JSONObject();
			jsonContract.put("classesCode","13070300");//险种代码

			JSONObject endorseInfo = new JSONObject();
			endorseInfo.put("unitcode","1010100");//分公司代码
			endorseInfo.put("applyno",dto.getPolicy_serial_number());//投保单号
			endorseInfo.put("applyendorseno",iprVo.getRevise_serial_number());//批单申请号
			jsonContract.put("endorseInfo",endorseInfo);//
			jsonHead.put("requestBody",jsonContract);
		}
		else if(TransTypeEnum.DZPD.getValue().equals(transType)){//电子批单打印

			RoleSubjectVo roleSubjectVo = vo.getRoleSubjectList().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];
				}
			}
			jsonHead.put("transactionCode","300007");//业务交易码
			JSONObject jsonContract = new JSONObject();
			jsonContract.put("policyNumber",iprVo.getRevise_serial_num_ins());//保单号、批单号或者其他生成规则
			jsonContract.put("idNumber",organizationCode);//投保人证件号或者其他生成规则
			jsonContract.put("type","0");//1-BASE64文件流,0-返回下载链接，不传默认0
			jsonHead.put("requestBody",jsonContract);
		}
		else if(TransTypeEnum.ZFDZ.getValue().equals(transType)){//支付地址获取

			jsonHead.put("transactionCode","300010");//业务交易码
			JSONObject jsonContract = new JSONObject();
			jsonContract.put("totalPolicyPremium",dto.getGross_premium());//总支付保费
			jsonContract.put("paymentWay","7");//支付方式 6-财猫移动端 7-财猫PC端 8-小程序 9-线下转账
			jsonContract.put("payForBackUrl",GlobalResources.WEB_URL+"/TB-API/GZZRX/callback-policy");//回调支付链接
			JSONArray applyPolicyList = new JSONArray();
			JSONObject applyPolicy = new JSONObject();
			applyPolicy.put("plcApplyNo",dto.getPolicy_serial_number());//投保单号
			applyPolicyList.add(applyPolicy);
			jsonContract.put("applyPolicyList",applyPolicyList);//
			jsonHead.put("requestBody",jsonContract);
		}

		return jsonHead.toString();
	}
	private static String idType(String idType) {// 0 身份证 3 护照 4 台胞证 5回乡证
		if(ConstProp.DIGIT_ZERO.equals(idType)){
			return "111";
		}else if(ConstProp.DIGIT_THREE.equals(idType)){
			return "414";
		}else if(ConstProp.DIGIT_FOUR.equals(idType)){
			return "1123";
		}else if(ConstProp.DIGIT_FIVE.equals(idType)){
			return "516";
		}else {
			return "990";//个人其他
		}
	}

	private static void employeeGroup(JSONArray employeeGroupList,int sNo,String ewType,String wType,int q){
		JSONObject serialNo = new JSONObject();
		serialNo.put("code","serialNo");
		serialNo.put("value",sNo);
		JSONObject employerWorkType = new JSONObject();
		employerWorkType.put("code","employerWorkType");
		employerWorkType.put("value",ewType);
		JSONObject workType = new JSONObject();
		workType.put("code","workType");
		workType.put("value",wType);
		JSONObject quantity = new JSONObject();
		quantity.put("code","quantity");
		quantity.put("value",q);
		JSONObject currencyCode = new JSONObject();
		currencyCode.put("code","currencyCode");
		currencyCode.put("value","01");
		JSONArray w = new JSONArray();
		w.add(serialNo);
		w.add(employerWorkType);
		w.add(workType);
		w.add(quantity);
		w.add(currencyCode);
		employeeGroupList.add(w);
	}

	private static void putSubjectWrapperList(JSONObject plan, OrderFormVo dto, List<HirelingVo> hirelingVoList) {
		int count = 0;
		int count2 = 0;
		for (HirelingVo vo:hirelingVoList) {
			if(ConstProp.DIGIT_TWO.equals(vo.getCareer())){
				count++;
			}
			if(ConstProp.DIGIT_FOUR.equals(vo.getCareer())){
				count2++;
			}
		}
		JSONArray subjectWrapperList = new JSONArray();
		JSONObject subjectWrapper = new JSONObject();
		subjectWrapper.put("subjectType","B01");
		subjectWrapper.put("constraintLevel","employeeGroupList#1");
		JSONArray employeeGroupList = new JSONArray();
		employeeGroup(employeeGroupList,1,"650302","保安人员",count);
		employeeGroup(employeeGroupList,2,"520203","一般内勤人员",(hirelingVoList.size()-count-count2));
		employeeGroup(employeeGroupList,3,"840703","一般清洁工",count2);

		subjectWrapper.put("employeeGroupList",employeeGroupList);

		JSONArray employeeDetailList = new JSONArray();
		int i = 0;
		for(HirelingVo vo : hirelingVoList){
			i = i+1;
			JSONObject groupNo = new JSONObject();
			groupNo.put("code","groupNo");
			groupNo.put("value",ConstProp.DIGIT_TWO.equals(vo.getCareer())?1:ConstProp.DIGIT_FOUR.equals(vo.getCareer())?3:2);
			JSONObject serialNo2 = new JSONObject();
			serialNo2.put("code","serialNo");
			serialNo2.put("value",i);
			JSONObject workerName = new JSONObject();
			workerName.put("code","workerName");
			workerName.put("value",vo.getName());
			JSONObject certType = new JSONObject();
			certType.put("code","certType");
			certType.put("value",idType(vo.getId_type()));
			JSONObject certNo = new JSONObject();
			certNo.put("code","certNo");
			certNo.put("value",vo.getId_card());
			JSONObject startTime = new JSONObject();
			startTime.put("code","startTime");
			startTime.put("value",dto.getInception_date()+ConstProp.DAY_00);
			JSONObject endTime = new JSONObject();
			endTime.put("code","endTime");
			endTime.put("value",LocalDate.parse(dto.getPlanned_end_date()).plusDays(1).toString()+ConstProp.DAY_00);

			JSONArray w2 = new JSONArray();
			w2.add(groupNo);
			w2.add(serialNo2);
			w2.add(workerName);
			w2.add(certType);
			w2.add(certNo);
			w2.add(startTime);
			w2.add(endTime);
			employeeDetailList.add(w2);
		}
		subjectWrapper.put("employeeDetailList",employeeDetailList);

		subjectWrapperList.add(subjectWrapper);
		plan.put("subjectWrapperList",subjectWrapperList);
	}

	private static void putProductFeatureInfoList(JSONObject plan) {
		JSONArray productFeatureInfoList = new JSONArray();
		JSONObject featureInfo = new JSONObject();
		featureInfo.put("productFeatureType","liability");
		JSONArray baseInfo = new JSONArray();
		JSONObject calFeeType = new JSONObject();
		calFeeType.put("code","calFeeType");
		calFeeType.put("value","1");
		JSONObject ifRegistered = new JSONObject();
		ifRegistered.put("code","ifRegistered");
		ifRegistered.put("value","1");
		JSONObject ifInjury = new JSONObject();
		ifInjury.put("code","ifInjury");
		ifInjury.put("value","0");
		JSONObject ifHighRisk = new JSONObject();
		ifHighRisk.put("code","ifHighRisk");
		ifHighRisk.put("value","0");
		JSONObject riskKind = new JSONObject();
		riskKind.put("code","riskKind");
		riskKind.put("value","PT");
		JSONObject businessCode = new JSONObject();
		businessCode.put("code","businessCode");
		businessCode.put("value","L727");
		JSONObject businessName = new JSONObject();
		businessName.put("code","businessName");
		businessName.put("value","保安服务");
		JSONObject ifPrintMainClause = new JSONObject();
		ifPrintMainClause.put("code","ifPrintMainClause");
		ifPrintMainClause.put("value","1");
		baseInfo.add(calFeeType);
		baseInfo.add(ifRegistered);
		baseInfo.add(ifInjury);
		baseInfo.add(ifHighRisk);
		baseInfo.add(riskKind);
		baseInfo.add(businessCode);
		baseInfo.add(businessName);
		baseInfo.add(ifPrintMainClause);
		featureInfo.put("productFeatureBaseInfo",baseInfo);//产品特征值
		productFeatureInfoList.add(featureInfo);
		plan.put("productFeatureInfoList",productFeatureInfoList);
	}

	private static String changeCTypeCom(String c_t){
		//输入 1 组织机构代码 2 统一社会代码 6税务登记证 7 工商登记号 数据库注释：7营业执照、8税务登记证、9组织机构代码证 TODO 雪峰检查证件类型
		//输出 1 组织机构代码 2 企业代码 3 营业执照 9 统一社会信用代码证 11 其他证件
		if("1".equals(c_t)){//组织机构代码
			return "1";//"2170010001";
		}else if("2".equals(c_t)){//统一社会代码
			return "9";//"2170010004";
		}else if("6".equals(c_t)){//税务登记证件号
			return "9";//"2170010004";
		}else if("7".equals(c_t)){//工商登记号
			return "3";//"2170010004";
		}else if("8".equals(c_t)){
			return "9";
		}else if("9".equals(c_t)){
			return "1";
		}else{//其它
			return "11";//"2170010004";
		}
	}

	private static String natureLinkageSet(String value){//单位性质
		if ( "0".equals(value) ) {
			return "002";
		} else if ("1".equals(value)) {
			return "002";
		}else if ("2".equals(value)) {
			return "002";
		}else if ("3".equals(value)) {
			return "001";
		}else if ("4".equals(value)) {
			return "003";
		}else if ("5".equals(value)) {
			return "007";
		}else if ("6".equals(value)) {
			return "001";
		}else if ("7".equals(value)) {
			return "001";
		}else if ("8".equals(value)) {
			return "001";
		}else if ("9".equals(value)) {
			return "004";
		}else if ("10".equals(value)) {
			return "002";
		}else if ("11".equals(value)) {
			return "003";
		}else if ("12".equals(value)) {
			return "007";
		}else if ("13".equals(value)) {
			return "007";
		}else if ("14".equals(value)) {
			return "007";
		}
		return "007";
	}

	private static String signInfo_sha256(String policyNo, String productCode, String printTime){
		return PAC_MD5Util.sha256Hex(policyNo+productCode+printTime);
	}
	private static String signMsg_sha256(OrderFormVo dto, String productCode){
		return PAC_MD5Util.sha256Hex(PARTNERCODE+productCode+dto.getApplicant_name()+dto.getGross_premium()+dto.getNotice_no());
	}

	//人标的列表,批改被保人，修改被保人时必传
	private static void doEmployeeAutoEndorseDetailList(InsPreservationRecordVo vo, OrderFormVo dto,JSONArray arr){
		JSONObject riskPerson;
		for(InsPreservationDetailVo ipdVo : vo.getInsPreservationDetailVoList()){
			riskPerson = new JSONObject();
			if(DictConst.REVISE_TYPE_T.equals(vo.getRevise_type())){
				riskPerson.put("name",ipdVo.getBusiness_vo().getName());//原被保人名字
				riskPerson.put("certType",idType(ipdVo.getBusiness_vo().getId_type()));//原被保人证件类型
				riskPerson.put("certNo",ipdVo.getBusiness_vo().getId_card());//原被保人证件号码
				riskPerson.put("displaceName",ipdVo.getName());//替换人名字
				riskPerson.put("displaceCertType",idType(ipdVo.getId_type()));//替换人证件类型
				riskPerson.put("displaceCertNo",ipdVo.getId_card());//替换人证件号码
				riskPerson.put("startTime",vo.getInception_date()+ConstProp.DAY_00);//开始日期
				riskPerson.put("endTime",LocalDate.parse(dto.getPlanned_end_date()).plusDays(1).toString()+ConstProp.DAY_00);//结束日期
				riskPerson.put("limitSumAmount","0");//累计赔偿限额
			}else if(DictConst.REVISE_TYPE_Z.equals(vo.getRevise_type())){
				riskPerson.put("startTime",vo.getInception_date()+ConstProp.DAY_00);//开始日期
				riskPerson.put("endTime",LocalDate.parse(dto.getPlanned_end_date()).plusDays(1).toString()+ConstProp.DAY_00);//结束日期
				riskPerson.put("limitSumAmount",vo.getTotal_amount());//累计赔偿限额
				riskPerson.put("name",ipdVo.getName());
				riskPerson.put("certType",idType(ipdVo.getId_type()));
				riskPerson.put("certNo",ipdVo.getId_card());
			}else {
				riskPerson.put("startTime",ipdVo.getBusiness_inception_date()+ConstProp.DAY_00);//开始日期
				riskPerson.put("endTime",vo.getInception_date()+ConstProp.DAY_00);//结束日期
//				riskPerson.put("startTime",vo.getInception_date()+ConstProp.DAY_00);//开始日期
//				riskPerson.put("endTime",LocalDate.parse(dto.getPlanned_end_date()).plusDays(1).toString()+ConstProp.DAY_00);//结束日期
				riskPerson.put("limitSumAmount",vo.getTotal_amount());//累计赔偿限额
				riskPerson.put("name",ipdVo.getName());
				riskPerson.put("certType",idType(ipdVo.getId_type()));
				riskPerson.put("certNo",ipdVo.getId_card());
			}

			riskPerson.put("serialNo",getCareerClass(ipdVo.getCareer()));////工种序号
			riskPerson.put("itemCode","a1");//责任代码
			riskPerson.put("currencyCode","01");//币种
			arr.add(riskPerson);
		}

	}

	private static String getCareerClass(String career){
		String cla = ConstProp.BLANK_CHAR;
		if(ConstProp.DIGIT_ONE.equals(career)){//内勤人员
			cla = "2";
		}else if(ConstProp.DIGIT_TWO.equals(career)){//保安人员
			cla = "1";
		}else if(ConstProp.DIGIT_FOUR.equals(career)){//保洁人员
			cla = "3";
		}/*else if(ConstProp.DIGIT_THREE.equals(career)){//武装押运人员
			cla = "56";
		}*/
		return cla;
	}

	/**
	 * 根据我们的证件类型获取平安的证件类型
	 * @param cardType
	 * @return
	 */
	private static String getCard(String cardType){
		/*
		01	身份证 ,如果身份证中有字母x,必须为大写
		02	护照
		03	军人证
		06	港澳回乡证或台胞证
		*/
		if ( "0".equals(cardType) ) {
			return "1170010001";
		}else if ("3".equals(cardType)) {
			return "1170010002";
		}else if ("4".equals(cardType)) {
			return "1170010057";
		}else {
			return "";
		}
	}

	private static String idTypeSet(String value){
		if ("1".equals(value)) {//组装机构代码
			return "01";
		}else if ("2".equals(value)) {//三证合一统一信用代码
			return "03";
		}else if ("6".equals(value)) {//税务登记证
			return "02";
		}else if ("7".equals(value)) {//营业执照
			return "04";
		}
		return "";
	}

	/**
	 *	接口返回字符串解析
	 * @return
	 */
	public static String returnAnalysisJson(String json, String  transType){
		Map map  = JSON.parseObject(json,Map.class);
		if(!"000000".equals(map.get("code"))){
			return "300#（APP-TB-"+map.get("code")+"）"+map.get("message");
		}
		if(TransTypeEnum.HB.getValue().equals(transType)) {//核保
			if(map.get("subPolicyList") != null){
				List<Map> list = JSONArray.parseArray(map.get("subPolicyList").toString(),Map.class);
				if(list.size()<=0){
					return "300#（APP-TB-003）投保信息获取异常！";
				}
				map = list.get(0);
				//200#投保单号#保单号#保费#保额#支付申请号#支付地址
				//{"subPolicyList":[{"plcSumInsured":1500000,"payApplyNo":"702405198651","plcApplyNo":"ABEJ60037124FM00001C","plcStatus":"08","plcType":"A","payUrl":"https://mpaysit.cpic.com.cn/mpayweb/payWebPc?6c5e645e45042d0ca00090e047c44b1bd5ce60ca9712cecef7299a8755b82892ac37b5968676320ec2e87faa6aa057dfb79335c4c105d00129cb8b1d31fcdb1630feb7b806198d27ac6d1796368091ca38abc55bc1a4947d45d4ee8fb4c5bd133a69c6f9e84dcdb87087bb2c9cddc19687f63578f13e0dd73580dc510245b22a848050db8c84c806feb091c885ce5c7c0487f987e1ec0b6ca92bc5ab84ba37760b8af964e6b2b7d654cfa6ba1e6ce9ff9bb7795d0f8fe77fb185f3b15943c371717af3500254f470986aa81e7b045682dbd23a24bb02af5a409d1ff6f2dd9093b531e432fa7fde6d0af5abce78dc14af8f342b091ddf55a2c2383235a6184a537d4cb18ec13445505f15ce4ac336b7b43ae485f5633e399940848e40901ce9396f71f9d4ecd46b0afb215d0fe1c61663692c3aa8e71cbf245ec5df40d9b7dbcf39c4961633822cebbbf5f14af4d39e65","plcPremium":885.00,"plcPolicyNo":""}],"message":"处理成功","plcOrderNo":"1762043301424394240","plcBusinessNo":"1773519583030931456","code":"000000"}
				return "200#"+map.get("plcApplyNo")+ConstProp.POUND_SIGN+map.get("plcPolicyNo")+ConstProp.POUND_SIGN+map.get("plcPremium")+ConstProp.POUND_SIGN+map.get("plcSumInsured")+ConstProp.POUND_SIGN+map.get("payApplyNo")+ConstProp.POUND_SIGN+map.get("payUrl");
			}else{
				return "300#（APP-TB-003.1）投保信息获取异常！";
			}
		}else if(TransTypeEnum.TB.getValue().equals(transType)) {//退保
			return "200#"+map.get("endorsementNo");
		}else if(TransTypeEnum.DZBD.getValue().equals(transType)) {//下载电子保单文件
			//String filePath = FileHelp.downloadFileAndSave(String.valueOf(map.get("fileUrl")),GlobalResources.COM_IMG_RE, DateUtil.generatorRadomNumber(),".pdf");
			if(StringUtils.isNotEmpty(String.valueOf(map.get("fileUrl")))){
				return "200#"+ map.get("fileUrl");
			}else{
				return "300#（APP-TB-002）电子保单解析失败！";
			}
		}else if(TransTypeEnum.DZPD.getValue().equals(transType)) {//下载电子批单文件
			//String filePath = FileHelp.downloadFileAndSave(String.valueOf(map.get("fileUrl")),GlobalResources.COM_IMG_RE, DateUtil.generatorRadomNumber(),".pdf");
			if(StringUtils.isNotEmpty(String.valueOf(map.get("fileUrl")))){
				return "200#"+ map.get("fileUrl");
			}else{
				return "300#（APP-TB-002）电子批单解析失败！";
			}
		}else if(TransTypeEnum.PD.getValue().equals(transType)) {//下载保单批改
			//String filePath = FileHelp.downloadFileAndSave(String.valueOf(map.get("policyUrl")),GlobalResources.COM_IMG_RE, DateUtil.generatorRadomNumber(),".pdf");
			//200#保单号#批单号#保费#批单申请号#电子批单#支付链接 没有返回保费
			//{"message":"成功","endorsePolicyNo":"BBEJ60037124QAAAAA9Q","policyUrl":"https://jttpitxsit.cpic.com.cn/jttpitx/externalpartner/link?C6mu7lNNzxC+Vj9mcnhVBRmmtjGt8BZzzjxARU3p0gvNPb/B0YNemss0xRV/5SoP%7C91350200302969730N","endorseApplyNo":"BBEJ60037124PAAAAAQB","code":"000000"}
			return "200#"+map.get("endorsePolicyNo")
					+ConstProp.POUND_SIGN+map.get("endorsePolicyNo")
					+ConstProp.POUND_SIGN+""
					+ConstProp.POUND_SIGN+map.get("endorseApplyNo")
					+ConstProp.POUND_SIGN+map.get("policyUrl")
					+ConstProp.POUND_SIGN+map.get("payUrl");
//			return "200#"+map.get("endorsePolicyNo")+ConstProp.POUND_SIGN+map.get("endorseApplyNo")+ConstProp.POUND_SIGN+""+ConstProp.POUND_SIGN+""+ConstProp.POUND_SIGN+map.get("policyUrl");
		}else if(TransTypeEnum.DZFP.getValue().equals(transType)) {//电子发票申请
			//String filePath = FileHelp.downloadFileAndSave(String.valueOf(map.get("pdfUrl")),GlobalResources.COM_IMG_RE, DateUtil.generatorRadomNumber(),".pdf");
			if(map.get("pdfUrl") == null){
				return "200#1";
			}
			return "200#"+ map.get("pdfUrl");
		}else if(TransTypeEnum.DZFPXZ.getValue().equals(transType)) {//下载电子发票文件
			//String filePath = FileHelp.downloadFileAndSave(String.valueOf(map.get("pdfUrl")),GlobalResources.COM_IMG_RE, DateUtil.generatorRadomNumber(),".pdf");
			if(map.get("pdfUrl") == null){
				return "200#1";
			}
			return "200#"+ map.get("pdfUrl");
		}else if(TransTypeEnum.ZFDZ.getValue().equals(transType)) {//支付地址获取
			//200#支付申请号#支付地址
			return "200#"+map.get("payApplyNo")+ConstProp.POUND_SIGN+map.get("payUrl");
		}else if(TransTypeEnum.PDZFCX.getValue().equals(transType)) {//批单支付撤销
			//200#撤销成功
			return "200#"+map.get("message");
		}
		return "300#（APP-TB-001.1）数据处理失败！";
	}

	/**
	 *	理赔接口返回字符串解析
	 * @return
	 */
	public static String returnAnalysisXml_LP(String xml, String  transType){
		SimplePathResultXMLProcesser xmlProcesser = new SimplePathResultXMLProcesser();
		try {
			if(TransType.EPIC_BA.getValue().equals(transType)) {
				return xmlProcesser.gzzrx_report_ba_ret(xml);
			}else if(TransType.EPIC_AJCX.getValue().equals(transType)) {
				return xmlProcesser.gzzrx_report_ajcx_ret(xml);
			}else if(TransType.EPIC_YXSC.getValue().equals(transType)) {
				return xmlProcesser.gzzrx_report_yxsc_ret(xml);
			}
		} catch (DocumentException e) {
			return "300#（APP-TB-000）"+e.getMessage();
		}
		return "300#（APP-TB-001）未获取到返回数据！";
	}

	public static void main(String[] args) {
		System.out.println(TBRegion.getAlias("110114"));
//		String a = "{\"ret\":\"0\",\"msg\":\"\",\"requestId\":\"null\",\"data\":{\"result\":{\"resultCode\":\"Y\",\"resultMessage\":\"查询信息成功\"},\"data\":{\"caseInfoList\":[{\"accidentCauseLevel2\":\"N0250\",\"accidentCauseLevel3\":\"\",\"caseStatus\":\"0\",\"withdrawReason\":\"\",\"caseScheduleList\":[],\"policyNo\":\"10162003900158627229\",\"remark\":\"\",\"accidentPlace\":\"思明区嘉禾路124号\",\"claimPhone\":\"15960004680\",\"reporterName\":\"还好\",\"caseStatus2\":\"赔款已到账\",\"productName\":\"雇主责任险A版\",\"accidentProvince\":\"福建省\",\"accidentCauseLevel1\":\"A01\",\"accidentCauseLevelName3\":\"\",\"injuryNameList\":[{\"demiseList\":[],\"outpatientList\":[],\"maimList\":[\"还好\"]}],\"caseStatus1\":\"待归档\",\"accidentCauseLevelName1\":\"意外伤害事故\",\"accidentCauseLevelName2\":\"上下班途中\",\"reportDate\":\"2019-11-26 10:45\",\"accidentProcess\":\"被撞了\",\"caseTimes\":\"1\",\"accidentDistrict\":\"\",\"isSelfCase\":\"Y\",\"paymentItemList\":[{\"clientBankAccount\":\"***************8815\",\"clientBankName\":\"v菲达环保\",\"payDate\":\"2019-11-26 17:45:51\"}],\"insuredName\":\"百川信（厦门）网络信息服务有限公司\",\"reportNo\":\"90162004100002020655\",\"indemnityConclusion\":\"1\",\"accidentCity\":\"厦门市\",\"accidentDate\":\"2019-11-26 10:11\",\"claimName\":\"闵锐\",\"orderNo\":\"\",\"endCaseDate\":\"2019-11-26 17:26\",\"caseNo\":\"40162004100003464887\",\"userId\":\"BCX00001\",\"endCaseAmountSum\":\"600\",\"productCode\":\"MP07110009\",\"currencyCode\":\"01\"}],\"details\":[]}}}";
//		String b = returnAnalysisJson_LP(a, TransTypeEnum.AJCX.getValue());
//		String n = "百川信（北京）信息服务有限公司";
//		System.out.println(n.replace("（","(").replace("）",")"));
	}

	public static String marshalReportJson(SpecialHirelingVo shVo, String reportDetail, InsCommonReportVo vo, String transType, OrderFormVo orderFormVo) {
		IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
		String buiNo = String.valueOf(idWorker.getId());
		JSONObject jsonHead = new JSONObject();
		jsonHead.put("partnerCode",PARTNERCODE);//合作方编码
		jsonHead.put("messageId",buiNo);//交易流水号，每次提交必须唯一(用于验证重复提交)
		jsonHead.put("transactionEffectiveDate",DateUtil.getCurrentDateTime());//交易时间
		jsonHead.put("user",TBUSER);//合作方用户
		jsonHead.put("password",tbPass());//用户密码


		RoleSubjectVo roleSubjectVo = shVo.getRoleSubjectList().get(1);
		JSONObject requestBody = new JSONObject();
		String containRepo = "1".equals(orderFormVo.getIs_contain_repo())? CONTAIN_REPO :"";
		requestBody.put("classCode", PLAN_CODE.get(orderFormVo.getProduct_code()+containRepo).get(planCodeKey));
		JSONObject registInfo = new JSONObject();

		registInfo.put("healthInsuranceFlag", "2");//1-意健险,2-非意健险
		registInfo.put("policyNo", vo.getPolicy_no());
		registInfo.put("registTime", DateUtil.getCurrentDateTime());
		registInfo.put("registWay", "1");//01-上门,02-电话,03-微信
		registInfo.put("registAddress", RegionUtils.getRegionNameByALLCode(vo.getAccident_province_code(),vo.getAccident_city_code(),vo.getAccident_county_code())+vo.getAccident_place());
		registInfo.put("branchCode", BRANCH_CODE);
		registInfo.put("departCode", "014");
		registInfo.put("departGroupCode", "330100");
		registInfo.put("departmentCode", "080");
		registInfo.put("reporter", roleSubjectVo.getName_cn());
		registInfo.put("reporterTelephone", roleSubjectVo.getLink_tel());


		JSONObject accidentInfo = new JSONObject();
		accidentInfo.put("accidentTime", vo.getAccident_date());
		accidentInfo.put("lossType", "01");
		accidentInfo.put("accidentReason", "1100");
		accidentInfo.put("accidentAddress", RegionUtils.getRegionNameByALLCode(vo.getAccident_province_code(),vo.getAccident_city_code(),vo.getAccident_county_code())+vo.getAccident_place());
		accidentInfo.put("accidentDesc", vo.getAccident_process());
		accidentInfo.put("reportCurrency", "01");
		accidentInfo.put("reportAmount", "");
		registInfo.put("accidentInfo", accidentInfo);

		JSONObject insuredInfo = new JSONObject();
		insuredInfo.put("insurantName", vo.getInsPaymentInfoVo().getClient_name());
		insuredInfo.put("insurantCertType", idType(vo.getInsPaymentInfoVo().getClient_certificate_type()));
		insuredInfo.put("insurantCertNo", vo.getInsPaymentInfoVo().getClient_certificate_no());
		registInfo.put("insuredInfo", insuredInfo);

		requestBody.put("registInfo", registInfo);

		jsonHead.put("transactionCode","300017");//业务交易码
		jsonHead.put("requestBody",requestBody);//业务交易码
		return jsonHead.toString();//TODO 雪峰确认参数
	}

	public String returnAnalysisReportJson(String json, String transType) {
		//报案/理赔返回：返回报文：{"message":"成功","code":"000000","registerNo":"DBEJ6003712400000010"}
		Map map  = JSON.parseObject(json,Map.class);
		if(!"000000".equals(map.get("code"))){
			return "300#（APP-TB-"+map.get("code")+"）"+map.get("message");
		}
		String registerNo = map.get("registerNo").toString();

		return "200#"+registerNo;//TODO 分析报案/理赔返回结果
	}
}
