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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.util.*;
import com.bcxin.ins.vo.*;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 *
 * <b>平安财-公责险各接口请求数据组装</b>
 *
 * @author zxf
 * @date 2017年10月11日 上午10:29:46
 * @注意事项 </b>
 * <b>
 */
public class PackageMessagePAC {


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

	private static final String FORMAT = "json";
	private static final String SIGNTYPE = "md5";
	private static final String CHARSET = "utf-8";

	private static final String PARTNERCODE = "P_BCX_GA";
	private static final String DEPARTMENTCODE = "20126";

	public static String pay_pc(OrderFormVo dto,String url) throws Exception {
		String  key="OPENAPI";

		//项目地址去掉头http:
		String returnUrl = GlobalResources.DONOW_PATH+"transaction/common-syntony/"+dto.getOid();
		if(ConstProp.BLB.equals(dto.getWeb_type())){
			returnUrl = GlobalResources.WEB_URL+"/insurance/tyx/transaction/syntony-service/"+dto.getOid();
		}
		HashMap map=new HashMap();
		map.put("dataSource","179");
		map.put("customerName",dto.getApplicant_name());
		map.put("businessNo",dto.getNotice_no());
		map.put("currencyNo","RMB");
		map.put("amount",dto.getGross_premium());
		map.put("documentNo",dto.getPolicy_serial_number());
		map.put("insuredName",dto.getInsured_role());
		map.put("key",key);
		String test = "179"+dto.getApplicant_name()+dto.getNotice_no()+"RMB"+dto.getGross_premium()+dto.getPolicy_serial_number()+key;
		String sign= PAC_MD5Util.sha256Hex(test);
		System.out.println("P-1> "+test );
		System.out.println("P-2> "+sign );
		map.put("signMsg",sign);
		map.put("callBackURL",returnUrl);//页面跳转地址
		map.put("url",url);//页面form表单地址
		map.remove("key");
		String data =JSONArray.toJSONString(map);
		System.out.println("P-3> "+data );
		return  data;
	}

	public static String pay_app(OrderFormVo dto,String url) throws Exception {
		String  key="P_BCXZR_GP";

		String return_url = GlobalResources.DONOW_PATH+"/weixin/product/pay/finish/"+dto.getOid();
		HashMap map=new HashMap();
		map.put("dataSource","179");
		map.put("customerName",dto.getApplicant_name());
		map.put("businessNo",dto.getNotice_no());
		map.put("currencyNo","RMB");
		map.put("amount",dto.getGross_premium());
		map.put("productName",dto.getProduct_name());
		map.put("callBackURL",return_url);//页面跳转地址
		String test = "179"+dto.getApplicant_name()+dto.getNotice_no()+"RMB"+dto.getGross_premium()+key;
		String sign= PAC_MD5Util.sha256Hex(test);
		System.out.println("P-1> test:"+test );
		System.out.println("P-2> sign:"+sign );
		map.put("signMsg",sign);

		map.put("url",url);//页面form表单地址
		String data =JSONArray.toJSONString(map);
		System.out.println("P-3> map:"+data );
		return  data;
	}

	/**
	 * <b> 批改确认报文组装 (在用)</b>
	 * @param policyNo 保单号
	 * @param transType 接口类型
	 * @param endorseApplyNo 批改申请单号
	 * @param actualPremiumChange 保费变化
	 * @param transSerialNo 批改申请时的流水号
	 * @author ZXF
	 * @create 2019/11/01 0001 15:48
	 * @version
	 * @注意事项 </b>
	 */
	public static String pdqr_marshal(String policyNo
			, String transType
			, String endorseApplyNo
			, String actualPremiumChange
			, String transSerialNo) throws Exception {
		JSONObject jsonHead = new JSONObject();
		if(TransTypeEnum.PDQR.getValue().equals(transType)){//批单
			IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
			jsonHead.put("requestId",String.valueOf(idWorker.nextId()));//请求标识（该值不可重复，用于定位问题）
			JSONObject moreInfo = new JSONObject();
			moreInfo.put("partnerCode",PARTNERCODE);//合作伙伴编码，平安开发提供
			moreInfo.put("edrSceneCode","18002");//批改场景编码，见附录2
			moreInfo.put("policyNo",policyNo);//保单号
			moreInfo.put("endorseApplyNo",endorseApplyNo);//批改申请单号
			moreInfo.put("actualPremiumChange",actualPremiumChange);//保费变化
			moreInfo.put("confirmEndorse","Y");//"Y"-确认进行本次批改；"N"-取消本次批改
			moreInfo.put("transSerialNo",transSerialNo);//批改申请时的流水号
			moreInfo.put("isSendElectronicEndorse","N");//是否发送电子批单（Y-发送，N-不发送）
			jsonHead.put("endorseInfo",moreInfo);//[非空]
		}

		return jsonHead.toString();
	}

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

		JSONObject jsonHead = new JSONObject();
		//头信息
		IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
		if(TransTypeEnum.HB.getValue().equals(transType)){//核保
			jsonHead.put("partnerCode",PARTNERCODE);//合作伙伴用户名（Openapi分配名称，固定值）
			jsonHead.put("transSerialNo",dto.getTrade_serial_number());//交易流水号，每次提交必须唯一(用于验证重复提交)
			jsonHead.put("departmentCode",DEPARTMENTCODE);//机构编码，咨询平安业务

			//投保信息
			JSONObject jsonContract = new JSONObject();
			//投保人
			JSONArray jsonApplicantArray = new JSONArray();
			JSONObject jsonApplicant = new JSONObject();
			doApplicantInfo(vo,dto,jsonApplicant);
			jsonApplicantArray.add(jsonApplicant);
			jsonContract.put("applicantInfoList",jsonApplicantArray);
			//保单基本信息
			JSONObject jsonBase = new JSONObject();
			doBaseInfo(vo,dto,jsonBase);
			jsonContract.put("baseInfo",jsonBase);
			//是否见费出单
			JSONObject jsonExtend = new JSONObject();
//			jsonExtend.put("isGiftInsurance","0");// [选择可空]是否赠险  1:是 0:否 默认0//长度限制：1
			jsonExtend.put("isPolicyBeforePayfee","1");// 是否是见费出单(1-是;0-否)
			jsonContract.put("extendInfo",jsonExtend);
			//[非空]方案信息 TODO
			JSONArray jsonRiskPropertyArray = new JSONArray();
			JSONObject jsonRiskProperty = new JSONObject();
			doRiskGroupInfo(vo,dto,jsonRiskProperty);
			jsonRiskPropertyArray.add(jsonRiskProperty);
			jsonContract.put("riskGroupInfoList",jsonRiskPropertyArray);
			//[可空]特约节点 TODO
//			JSONArray specialPromiseArray = new JSONArray();
//			doSpecialPromiseList(vo,dto,specialPromiseArray);
//			jsonContract.put("specialPromiseList",specialPromiseArray);
			//附件信息 TODO
//			JSONArray attachmentGroupArray = new JSONArray();
//			JSONObject attachment = new JSONObject();
//			attachment.put("documentGroupType","10"); // 附件组类型（01-投保资料；02-电子保单；03-验车附件,10-IOBS上传附件）
//			attachment.put("documentGroupId","");// IOBS上传附件是为IOBS的key，其他为影像系统附件组ID // 通过IOBS上传文件，文件名需要带后缀，小于2M
//			attachmentGroupArray.add(attachment);
//			jsonContract.put("attachmentGroupList",attachmentGroupArray);

			jsonHead.put("contract",jsonContract);

		}else if (TransTypeEnum.CBXX.getValue().equals(transType)){//承保
			jsonHead.put("applyPolicyNo",dto.getPolicy_serial_number());//投保单号
		}else if(TransTypeEnum.DZBD.getValue().equals(transType)){//电子保单打印
			String printTime = DateUtil.getCurrentDateTime();
			String productCode = getPlanCode(dto.getProduct_code());
			jsonHead.put("partnerCode",PARTNERCODE);//合作伙伴用户名（Openapi分配名称，固定值）
			jsonHead.put("departmentCode",DEPARTMENTCODE);//机构编码，咨询平安业务
			jsonHead.put("productCode",productCode);//[非空]产品编码
			jsonHead.put("policyNo",dto.getExternal_reference());//保单号（打印保单时必传）
			jsonHead.put("signInfo",signInfo_sha256(dto.getExternal_reference(),productCode,printTime));//[非空]验签码，需按SHA256方式加密，加密前明文为：policyNo + productCode + printTime，通过加密类将此字符串处理为密文。
			jsonHead.put("printTime",printTime);//[非空]打印日期（格式YYYY-MM-DD HH:MM:SS）
			jsonHead.put("documentType",ConstProp.DIGIT_ONE);//[非空]打印类型(1：保单，2：最新保单-不带章, 3：打印批单-带章, 4：打印个人凭证-带章"）
		}else if(TransTypeEnum.DZPD.getValue().equals(transType)){//电子批单打印
			String printTime = DateUtil.getCurrentDateTime();
			String productCode = getPlanCode(dto.getProduct_code());
			jsonHead.put("partnerCode",PARTNERCODE);//合作伙伴用户名（Openapi分配名称，固定值）
			jsonHead.put("departmentCode",DEPARTMENTCODE);//机构编码，咨询平安业务
			jsonHead.put("productCode",productCode);//[非空]产品编码
			jsonHead.put("policyNo",dto.getExternal_reference());//保单号（打印保单时必传）
			jsonHead.put("endorseNo",iprVo.getRevise_serial_num_ins());//批单号
			jsonHead.put("signInfo",signInfo_sha256(dto.getExternal_reference(),productCode,printTime));//[非空]验签码，需按SHA256方式加密，加密前明文为：policyNo + productCode + printTime，通过加密类将此字符串处理为密文。
			jsonHead.put("printTime",printTime);//[非空]打印日期（格式YYYY-MM-DD HH:MM:SS）
			jsonHead.put("documentType",ConstProp.DIGIT_THREE);//[非空]打印类型(1：保单，2：最新保单-不带章, 3：打印批单-带章, 4：打印个人凭证-带章"）
		}else if(TransTypeEnum.ZFDZ.getValue().equals(transType)){//支付接口
			String productCode = getPlanCode(dto.getProduct_code());
			jsonHead.put("partnerCode",PARTNERCODE);//合作伙伴用户名（Openapi分配名称，固定值）
			jsonHead.put("departmentCode",DEPARTMENTCODE);//机构编码，咨询平安业务
			jsonHead.put("tradeNo",String.valueOf(idWorker.nextId()));//[非空]流水号，要求每次唯一
			jsonHead.put("productCode",productCode);//[非空]产品编码
			jsonHead.put("noticeNo",dto.getNotice_no());//[非空]投保返回通知单号
			jsonHead.put("amount",dto.getGross_premium());//[非空]保单保费
			jsonHead.put("customerName",dto.getApplicant_name());//[非空]投保人名称
			jsonHead.put("productName",dto.getProduct_name());//[非空]产品名称
			jsonHead.put("productType","0A");//[非空]商品类别   财产险02, 意健险0A,  车险01
			jsonHead.put("signMsg",signMsg_sha256(dto,productCode));//[非空]加密密文，对partnerName+productCode+customerName+amount+noticeNo进行sha256加密，明文案例(P_XXX_GAMP070000000投保人甲100.0011080006000137712169)
			jsonHead.put("returnUrl",GlobalResources.WEB_URL);//[非空]回退地址，用于用户点击后退时展示的页面
			String returnUrl = GlobalResources.WEB_URL+"api/syntony-service/"+dto.getOid();
			if(ConstProp.BLB.equals(dto.getWeb_type())){
				returnUrl = GlobalResources.WEB_URL+"/insurance/tyx/transaction/syntony-service/"+dto.getOid();
			}
			jsonHead.put("frontNotifyUrl",returnUrl);//[非空]前台回调地址，用于支付完成后前端展示的页面
		}else if(TransTypeEnum.DZFP.getValue().equals(transType)){//电子发票打印
			jsonHead.put("partnerCode",PARTNERCODE);//合作伙伴用户名（Openapi分配名称，固定值）
			JSONArray invoiceArray = new JSONArray();
			JSONObject jsonInvoice = new JSONObject();
			doInvoice(vo,dto,jsonInvoice);
			invoiceArray.add(jsonInvoice);// [非空]发票信息列表，一次性最多开10张票
			jsonHead.put("invoiceList",invoiceArray);
		}else if(TransTypeEnum.PD.getValue().equals(transType)){//批单
			jsonHead.put("transSerialNo",iprVo.getRevise_serial_number());//[非空]交易流水,要求唯一
			jsonHead.put("partnerCode",PARTNERCODE);//合作伙伴用户名（Openapi分配名称，固定值）
			jsonHead.put("departmentCode",DEPARTMENTCODE);//机构编码，咨询平安业务
			jsonHead.put("policyNo",dto.getExternal_reference());//保单号
			jsonHead.put("edrSceneCode","18002");//[非空]批改场景号，见附录2
			jsonHead.put("requestId",DateUtil.convertDateToString(new Date(), DateUtil.FORMAT1_2));//[可空]时间戳
			JSONObject moreInfo = new JSONObject();
			moreInfo.put("isSendElectronicEndorse","N");//[非空]是否发送电子保单到投保人邮箱（Y-发送，N-不发送）
			moreInfo.put("effectiveDate",iprVo.getInception_date()+ConstProp.DAY_00);//[可空]批单生效日期，格式为yyyy-MM-dd HH:mm:ss
			moreInfo.put("isBeforePayfee","0");//[可空]批单是否见费（1-见费，0-非见费，默认取保单的是否见费标识）
			jsonHead.put("moreInfo",moreInfo);//[非空]
			JSONArray riskPersonArray = new JSONArray();
			doRiskPersonList(iprVo,dto,riskPersonArray);
			jsonHead.put("riskPersonList",riskPersonArray);//人标的列表,批改被保人，修改被保人时必传
		}

		return jsonHead.toString();
	}

	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());
	}

	//投保基本信息 doBaseInfo
	private static void doBaseInfo(GMRPolicyVo vo, OrderFormVo dto,JSONObject json){
		json.put("productCode",getPlanCode(dto.getProduct_code()));//产品编码
		json.put("businessType","2"); // [可空]单证的业务属性 默认团体属性  1-个人，2-团体
		json.put("amountCurrencyCode","01");//保额/限额币种，01人民币，02港币，03美元，04英镑，05日元，07瑞士法郎，09新加坡元，10加拿大元，12欧元，13澳大利亚元，18澳门元，19丹麦克朗，20挪威克朗，21瑞典克朗，22新西兰元，23韩元
		json.put("totalActualPremium",dto.getGross_premium());//总保费
		json.put("insuranceBeginDate",dto.getInception_date()+ConstProp.DAY_00);//保险起期 yyyy-MM-dd HH:mm:ss或yyyy/MM/dd HH:mm:ss
		json.put("insuranceEndDate",dto.getPlanned_end_date()+ConstProp.DAY_23);//保险止期 yyyy-MM-dd HH:mm:ss或yyyy/MM/dd HH:mm:ss
	}

	//电子发票信息 doInvoice
	private static void doInvoice(GMRPolicyVo vo, OrderFormVo dto,JSONObject json){
		JSONArray policyArray = new JSONArray();
		for(RoleSubjectVo roleSubjectVo : vo.getRoleSubjectList()){
			if("1".equals(roleSubjectVo.getKind())){
				String organizationCode = roleSubjectVo.getOrganization_code();
				if(StringUtils.isNotEmpty(organizationCode) && ConstProp.DIGIT_ONE.equals(roleSubjectVo.getId_type())){
					organizationCode = organizationCode.split(ConstProp.MINUS)[0]+organizationCode.split(ConstProp.MINUS)[1];
				}
				json.put("transactionNo",dto.getTrade_serial_number());//[非空]开票流水号，长度限制32位，要求唯一
				json.put("invoiceCreater",PARTNERCODE); // [非空]开票人，不可以超过15个字符
				json.put("invoiceEmail",roleSubjectVo.getLink_email());// [可空]电子发票接收邮箱
				json.put("invoicePhone",roleSubjectVo.getLink_tel());//[可空]电子发票接收联系电话
				json.put("invoiceOwner",roleSubjectVo.getName_cn());//[可空]发票抬头
				json.put("taxPayerNO",organizationCode);//[非空]发票纳税人编号，要求15、17、18或20位
				if(vo.getMailPolicyVo() != null&&ConstProp.DIGIT_ONE.equals(vo.getMailPolicyVo().getNeed_receipt())){
					json.put("taxPayerTel",vo.getMailPolicyVo().getTaker_mobile());//[可空]发票纳税人电话
					json.put("taxPayerAddress",vo.getMailPolicyVo().getRegister_address_invoice());//[可空]发票纳税人地址
					json.put("taxPayerBankName",vo.getMailPolicyVo().getBank_invoice());//[可空]发票纳税人银行
					json.put("taxPayerBankAccount",vo.getMailPolicyVo().getBank_account_invoice());// [可空]发票纳税人帐户
				}
				JSONObject policyInfo = new JSONObject();
				policyInfo.put("policyNo",dto.getExternal_reference()); //[非空]保单号
				policyInfo.put("personnelName",roleSubjectVo.getName_cn()); //[非空]投保人名称
				policyInfo.put("certificateType",idTypeSet(roleSubjectVo.getId_type())); //[非空]证件类型
				policyInfo.put("certificateNo",organizationCode); //[非空]证件号码 (最长20字节)
				policyArray.add(policyInfo);
			}
		}

		json.put("policyList",policyArray);
	}

	//人标的列表,批改被保人，修改被保人时必传
	private static void doRiskPersonList(InsPreservationRecordVo vo, OrderFormVo dto,JSONArray arr){
		int age;
		JSONObject riskPerson;
		String type;
		for(InsPreservationDetailVo ipdVo : vo.getInsPreservationDetailVoList()){
			riskPerson = new JSONObject();
			type = conventPType(vo.getRevise_type());
			riskPerson.put("status",type);// [非空]状态（A-增加，U-更新，D-删除，C-更换）,修改被保人填U，批增填A，批减填D，更换被保人填C(修改被保人不能同时更改被保人姓名和证件号码、更换被保人必须同时更改被保人姓名和证件号码)
			riskPerson.put("personnelAttribute","100");// [非空]人员属性：100（主真实被保人）、010（连带真实被保人）、200（主虚拟被保人）、020（连带虚拟被保人）
			riskPerson.put("name",ipdVo.getName());//[非空]被保人名称
			riskPerson.put("certificateNo",ipdVo.getId_card());// [非空]证件号码
			riskPerson.put("certificateType",getCard(ipdVo.getId_type())); //[选择性非空]status为D可空,证件类型，见附录1
			riskPerson.put("birthday",ipdVo.getBirthday());//[非空]出生日期,证件类型为身份证时可空
			try {
				age = DateUtil.getAge(ipdVo.getBirthday());
			} catch (Exception e) {
				age = 0;
			}
			riskPerson.put("age",String.valueOf(age));//[非空]年龄,证件类型为身份证时可空
			riskPerson.put("sexCode","1".equals(ipdVo.getSex()) ? "M" : "F");//[非空]性别（F/M）,证件类型为身份证时可空
			riskPerson.put("riskGroupName",getPlanName(dto.getProduct_code()));//[选择性非空]当status为A且原保单有多个方案时非空
			riskPerson.put("relationshipWithApplicant","6");//[选择性非空]当status为D可空,被保人与投保人关系：1-本人、2-配偶、3-父子、4-父女、5-受益人、6-被保人、7-投保人、8-转换不详、9-其他、A-母子、B-母女、C-兄弟、D-姊妹、E-兄妹、F姐弟、G-祖孙、H-雇佣、I -子女
			riskPerson.put("mobileTelephone",ipdVo.getTel());//[选择性非空]手机号码
			if("C".equals(type)&&ipdVo.getBusiness_vo()!=null){
				riskPerson.put("oldName",ipdVo.getBusiness_vo().getName());//[选择性非空]原被保人姓名，status为U或C时非空
				riskPerson.put("oldCertificateNo",ipdVo.getBusiness_vo().getId_card());//[选择性非空]原被保人证件号码，status为U或C时非空
			}
			arr.add(riskPerson);
		}

	}

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

	//[可空]特约节点 TODO
	private static void doSpecialPromiseList(GMRPolicyVo vo, OrderFormVo dto,JSONArray arr){
		JSONObject specialPromise = new JSONObject();
		specialPromise.put("businessType","true");// 是否允许自动报价
		specialPromise.put("contentType","1");// 特约分类：2-可改特约,1-不可改特约,3-可替换特约
		specialPromise.put("promiseCode","");// 特约编号
		specialPromise.put("promiseDesc","");// 特约描述
		specialPromise.put("promiseType","Y"); // 特约类型：Y-可选特约,N-固定特约 (Y为可改特约;N为固定特约;X为可选特约;B为底部特约)
		specialPromise.put("sortIndex","1");// 特约定义序号,用于特约排序
		arr.add(specialPromise);
	}

	//地址基本信息 riskGroupInfoList
	private static void doRiskGroupInfo(GMRPolicyVo gvo, OrderFormVo dto,JSONObject json){
		//标准产品节点
		JSONArray riskPackageInfoArray = new JSONArray();
		JSONObject riskPackageInfoList = new JSONObject();
		riskPackageInfoList.put("applyNum","1"); //[非空]投保份数
		riskPackageInfoList.put("productPackageCode",getProductPackageCode(dto.getProduct_code())); //[非空]套餐编码
		riskPackageInfoArray.add(riskPackageInfoList);

		//自定义产品节点
		/*JSONArray planInfoArray = new JSONArray();
		JSONObject planInfoList = new JSONObject();
		planInfoList.put("planCode",getPlanCode(dto.getProduct_code()));//[非空]险种代码
		JSONArray dutyInfoList = new JSONArray();
		JSONObject planInfo = null;
		for(int i=0;i<2;i++){
			planInfo = new JSONObject();
			planInfo.put("dutyCode","CVYA008");//[非空]责任代码
			planInfo.put("insuredAmount","100000");//责任保额
			dutyInfoList.add(planInfo);
		}
		planInfoList.put("dutyInfoList",dutyInfoList);//[非空]责任节点,一个产品可以有多个责任
		planInfoArray.add(planInfoList);*/

		//被保人信息列表
		JSONArray riskPersonInfoArray = new JSONArray();
		JSONObject riskPersonInfo;
		int age;
		List<RoleSubjectVo> roleList = gvo.getRoleSubjectList();
		for(RoleSubjectVo vo : roleList) {
			if ("2".equals(vo.getKind())) {
				riskPersonInfo = new JSONObject();
				riskPersonInfo.put("name",vo.getName_cn());//[非空]姓名
				try {
					age = DateUtil.getAge(vo.getBirth_date());
				} catch (Exception e) {
					age = 0;
				}
				riskPersonInfo.put("age",String.valueOf(age)); // [非空]年龄，证件为身份证时不用填
				riskPersonInfo.put("certificateNo",vo.getOrganization_code()); // [非空]证件号码 如果是身份证 那么出生日期及年龄,性别联动
				riskPersonInfo.put("certificateType",getCard(vo.getId_type()));// [非空]证件类型，见附录1
				riskPersonInfo.put("birthday",vo.getBirth_date());//[非空]出生日期 和 年龄联动，证件为身份证时不用填
				riskPersonInfo.put("personnelAttribute","100");// [非空]人员属性 100（主真实被保人）、200（主虚拟被保人）
				riskPersonInfo.put("sexCode","1".equals(vo.getSex()) ? "M" : "F");// [选择性非空]性别（F/M），证件为身份证时不用填
				riskPersonInfo.put("mobileTelephone",vo.getMobile()); // 手机号
				riskPersonInfo.put("professionClass","2"); // 职业类型(职业类别)
				riskPersonInfo.put("professionCode",getProfessionCode(vo.getMajor_group()));// 职业编码,内勤和保安人员统一传N010401/武装押运传N010404
				riskPersonInfo.put("relationshipWithApplicant","1");// K-业务关系 Employer,J-父母 Parents,I-子女 Children,H-雇佣或劳务 Employer,G-祖孙 Grandparents,F-姐弟 Sibling,E-兄妹 Sibling,D-姊妹 Sibling,C-兄弟 Sibling,B-母女 Parents,A-母子 Parents,9-其他 Other,8-转换不详 Other,7-投保人 Policyholder,6-被保人 Insured,5-受益人 Beneficiaries,4-父女 Parents,3-父子 Parents,2-配偶 Spouse,1-本人 Policyholder
				riskPersonInfo.put("destinationCountry","中国");//目的地国家或地区
				riskPersonInfoArray.add(riskPersonInfo);
			}
		}

//		json.put("riskGroupName","方案一");//[可空]方案名称，根据方案的索引index进行命名，"方案一"，"方案二"。。。
		json.put("riskPackageInfoList",riskPackageInfoArray);// [可空],标准产品节点,标准产品出单时[非空]
//		json.put("planInfoList",planInfoArray);//[可空]自定义产品节点,自定义产品出单时[非空]
		json.put("riskPersonInfoList",riskPersonInfoArray);//[非空]被保人信息列表
	}

	//根据职业编码获取平安财职业代码
	private static String getProfessionCode(String major_group){
		if(!GlobalResources.IS_TEST_ENVI){//生成
			return "3".equals(major_group) ? "N010404" : "N010401";
		}else{//测试
			return "3".equals(major_group) ? "0201002" : "0201002";
		}
	}

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

	//根据产品id获取对应产品代码
	private static String getPlanCode(String product_code){
		if(StringUtils.isEmpty(product_code) ? false : "TYX-PAC-1".equals(product_code)){
			return "MP18010167";
		}else if(StringUtils.isEmpty(product_code) ? false : "TYX-PAC-2".equals(product_code)){
			return "MP18010166";
		}else if(StringUtils.isEmpty(product_code) ? false : "TYX-PAC-3".equals(product_code)){
			return "MP18010168";
		}else if(StringUtils.isEmpty(product_code) ? false : "TYX-PAC-4".equals(product_code)){
			return "MP18010169";
		}else{
			return "";
		}
	}

	private static String getPlanName(String product_code){
		if(StringUtils.isEmpty(product_code) ? false : "TYX-PAC-1".equals(product_code)){
			return "方案一";
		}else if(StringUtils.isEmpty(product_code) ? false : "TYX-PAC-2".equals(product_code)){
			return "方案二";
		}else if(StringUtils.isEmpty(product_code) ? false : "TYX-PAC-3".equals(product_code)){
			return "方案三";
		}else if(StringUtils.isEmpty(product_code) ? false : "TYX-PAC-4".equals(product_code)){
			return "方案四";
		}else{
			return "";
		}
	}

	//根据产品id获取对应产品套餐代码
	private static String getProductPackageCode(String product_code){
		if(StringUtils.isEmpty(product_code) ? false : "TYX-PAC-1".equals(product_code)){
			return "PK00025205";
		}else if(StringUtils.isEmpty(product_code) ? false : "TYX-PAC-2".equals(product_code)){
			return "PK00025206";
		}else if(StringUtils.isEmpty(product_code) ? false : "TYX-PAC-3".equals(product_code)){
			return "PK00025207";
		}else if(StringUtils.isEmpty(product_code) ? false : "TYX-PAC-4".equals(product_code)){
			return "PK00025208";
		}else{
			return "";
		}
	}

	//投保人信息  applicantInfo
	private static void doApplicantInfo(GMRPolicyVo vo, OrderFormVo dto,JSONObject json){

		for(RoleSubjectVo roleSubjectVo : vo.getRoleSubjectList()){
			if("1".equals(roleSubjectVo.getKind())){
				String organizationCode = roleSubjectVo.getOrganization_code();
				if(StringUtils.isNotEmpty(organizationCode) && ConstProp.DIGIT_ONE.equals(roleSubjectVo.getId_type())){
					organizationCode = organizationCode.split(ConstProp.MINUS)[0]+organizationCode.split(ConstProp.MINUS)[1];
				}else{
				}
				json.put("name",roleSubjectVo.getName_cn().replace("（","(").replace("）",")"));//公司名称 否
				json.put("personnelType","0");//个团标志（1个人，0团体）
				json.put("certificateType",idTypeSet(roleSubjectVo.getId_type()));//证件类型
				json.put("certificateNo",organizationCode);//证件号码
				json.put("linkManName",roleSubjectVo.getLink_name());//联系人名称
				String address = RegionUtils.getRegionNameByALLCode(roleSubjectVo.getReg_province(),roleSubjectVo.getReg_city(),roleSubjectVo.getReg_district())+roleSubjectVo.getReg_address();
				json.put("address",address);//地址
				json.put("mobileTelephone",roleSubjectVo.getLink_tel());//联系人手机
				json.put("email",roleSubjectVo.getLink_email());//联系人邮箱
				//需要发票
				if(vo.getMailPolicyVo() != null&&ConstProp.DIGIT_ONE.equals(vo.getMailPolicyVo().getNeed_receipt())){
					json.put("invoicePrintType",ConstProp.DIGIT_ZERO.equals(vo.getMailPolicyVo().getInvoice_type()) ? "01" : "02");// 发票打印类型, 普通增值税发票(01)打印专用增值税发票(02)增值税电子普通发票(05)无需打印(03)
					json.put("billingAddress",vo.getMailPolicyVo().getRegister_address_invoice());//开票地址
					json.put("billingPhone",vo.getMailPolicyVo().getTaker_mobile());//开票电话
					json.put("billingDepositBank",vo.getMailPolicyVo().getBank_invoice());//开票开户银行
					json.put("billingDepositBankAccount",vo.getMailPolicyVo().getBank_account_invoice());//开票开户银行账户
					json.put("taxpayerCertificateType","02");//纳税人证件类型
					json.put("taxpayerCertificateNo",vo.getMailPolicyVo().getTaxpayer_number_invoice());//纳税人证件号码
				}else{
					json.put("invoicePrintType","03");//无需打印(03)
				}
			}
		}
	}

	//被保险人信息  doInsurantInfo
	private static void doInsurantInfo(SpecialPublicDutyVo vo, OrderFormVo dto,JSONObject json){

		for(RoleSubjectVo roleSubjectVo : vo.getRoleSubjectList()){
			if("2".equals(roleSubjectVo.getKind())){
				String organizationCode = roleSubjectVo.getOrganization_code();
				if(StringUtils.isNotEmpty(organizationCode) && ConstProp.DIGIT_ONE.equals(roleSubjectVo.getId_type())){
					organizationCode = organizationCode.split(ConstProp.MINUS)[0]+organizationCode.split(ConstProp.MINUS)[1];
				}else{
				}
				json.put("name",roleSubjectVo.getName_cn().replace("（","(").replace("）",")"));//公司名称 否
				json.put("personnelType","1");//个团标志（1个人，0团体）
				json.put("certificateType",idTypeSet(roleSubjectVo.getId_type()));//证件类型，个人(01：身份证、02：护照、03：军人证、04：港澳通行证，05：驾驶证、06：港澳回乡证或台胞证，07：临时身份证、99：其他)，团体(01：组织机构代码证、02：税务登记证、04：工商营业执照号、99：其他)"
				json.put("certificateNo",organizationCode);//证件号码
				json.put("linkManName",roleSubjectVo.getLink_name());//联系人名称
				String address = RegionUtils.getRegionNameByALLCode(roleSubjectVo.getReg_province(),roleSubjectVo.getReg_city(),roleSubjectVo.getReg_district())+roleSubjectVo.getReg_address();
				json.put("address",address);//地址
				json.put("mobileTelephone",roleSubjectVo.getLink_tel());//联系人手机
			}
		}
	}

	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){
		JSONObject jsonHead = JSONObject.fromObject(json);
		if( jsonHead == null ){
			return "300#（APP-PAC-001）未获取到返回数据！";
		}
		if(!ConstProp.DIGIT_ZERO.equals(jsonHead.get("ret"))){
			return "300#（APP-PAC-"+jsonHead.get("ret")+"）"+jsonHead.get("msg");
		}
		if(TransTypeEnum.DZFP.getValue().equals(transType)) {
			//获取电子发票文件流   返回值
			JSONArray arr  =JSONArray.parseArray(JSON.toJSONString(jsonHead.get("data")));
			JSONObject jsonDate = JSONObject.fromObject(arr.get(0));
			if(!"999999".equals(jsonDate.get("resultCode"))){
				return "300#（APP-PAC-"+jsonDate.get("resultCode")+"）"+jsonDate.get("resultMessage");
			}
			String filePath = uploadFile(String.valueOf(jsonDate.get("invoiceValue")), "pdf","/policy/");
			if(StringUtils.isNotEmpty(filePath)){
				return "200#"+filePath;
			}else{
				return "300#（APP-PAC-002）电子发票打印文件流解析失败！";
			}
		}
		JSONObject jsonDate = JSONObject.fromObject(jsonHead.get("data"));
		JSONObject resultJson = JSONObject.fromObject(jsonDate.get("result"));
		if(TransTypeEnum.HB.getValue().equals(transType)) {
			//核保
			if("999999".equals(jsonDate.get("responseCode"))){
				//200#投保单号#通知单号#保费#保额
				return "200#"+resultJson.get("applyPolicyNo")+ConstProp.POUND_SIGN+resultJson.get("noticeNo")+ConstProp.POUND_SIGN+resultJson.get("totalActualPremium")+ConstProp.POUND_SIGN+resultJson.get("totalInsuredAmount");
			}else{
				return "300#（APP-PAC-"+jsonDate.get("responseCode")+"）"+jsonDate.get("responseMsg");
			}
		}else if(TransTypeEnum.CBXX.getValue().equals(transType)) {
			//承保   返回值888888
			if("999999".equals(jsonDate.get("responseCode")) || "888888".equals(jsonDate.get("responseCode"))){
				//200#保单号#投保单号#保费
				return "200#"+resultJson.get("policyNo")+ConstProp.POUND_SIGN+resultJson.get("applyPolicyNo")+ConstProp.POUND_SIGN+resultJson.get("totalActualPremium");
			}else{
				return "300#（APP-PAC-"+jsonDate.get("responseCode")+"）"+jsonDate.get("responseMsg");
			}
		}else if(TransTypeEnum.DZBD.getValue().equals(transType)) {
			//获取电子保单文件流   返回值
			if(!"999999".equals(jsonDate.get("responseCode"))){
				return "300#（APP-PAC-"+jsonDate.get("responseCode")+"）"+jsonDate.get("responseMsg");
			}
			String filePath = uploadFile(String.valueOf(jsonDate.get("fileData")), String.valueOf(jsonDate.get("fileType")),"/policy/");
			if(StringUtils.isNotEmpty(filePath)){
				return "200#"+filePath;
			}else{
				return "300#（APP-PAC-002）电子保单打印文件流解析失败！";
			}
		}else if(TransTypeEnum.DZPD.getValue().equals(transType)) {
			//获取电子批单文件流   返回值
			if(!"999999".equals(jsonDate.get("responseCode"))){
				return "300#（APP-PAC-"+jsonDate.get("responseCode")+"）"+jsonDate.get("responseMsg");
			}
			String filePath = uploadFile(String.valueOf(jsonDate.get("fileData")), String.valueOf(jsonDate.get("fileType")),"/policy/");
			if(StringUtils.isNotEmpty(filePath)){
				return "200#"+filePath;
			}else{
				return "300#（APP-PAC-002）电子批单打印文件流解析失败！";
			}
		}else if(TransTypeEnum.ZFDZ.getValue().equals(transType)) {
			//支付接口返回
			if("SUCCESS".equals(jsonDate.get("resultCode"))){
				return "200#"+jsonDate.get("tradeNo")+ConstProp.POUND_SIGN+jsonDate.get("payUrl");
			}else{
				return "300#（APP-PAC-"+jsonDate.get("resultCode")+"）"+jsonDate.get("resultMsg");
			}
		}else if(TransTypeEnum.PD.getValue().equals(transType)) {
			//保单批改
			if("999999".equals(jsonDate.get("responseCode"))){
				//200#保单号#批单号#保费#批单申请号
				return "200#"+resultJson.get("policyNo")+ConstProp.POUND_SIGN+resultJson.get("endorseNo")+ConstProp.POUND_SIGN+resultJson.get("actualPremiumChange")+ConstProp.POUND_SIGN+resultJson.get("endorseApplyNo");
			}else{
				return "300#（APP-PAC-"+jsonDate.get("responseCode")+"）"+jsonDate.get("responseMsg");
			}
		}else if(TransTypeEnum.PDQR.getValue().equals(transType)) {
			//保单批改确认
			if("999999".equals(jsonDate.get("responseCode"))){
				//200#保单号#批单号#保费#通知单号
				return "200#"+resultJson.get("policyNo")+ConstProp.POUND_SIGN+resultJson.get("endorseNo")+ConstProp.POUND_SIGN+resultJson.get("actualPremiumChange")+ConstProp.POUND_SIGN+resultJson.get("noticeNo");
			}else{
				return "300#（APP-PAC-"+jsonDate.get("responseCode")+"）"+jsonDate.get("responseMsg");
			}
		}
		return "300#（APP-PAC-001.1）数据处理失败！";
	}

	public static void main(String[] args) {
		String a = "{\"ret\":\"0\",\"msg\":\"\",\"requestId\":\"null\",\"data\":[\n" +
				"      {\n" +
				"      \"resultCode\":\"999999\",\n" +
				"      \"resultMessage\":\"调用成功\",\n" +
				"      \"responseCode\":\"999999\",\n" +
				"      \"responseMsg\":\"调用成功\",\n" +
				"      \"transactionNo\":\"1189811087348985856\",\n" +
				"      \"invoiceNo\":\"45109327\",\n" +
				"      \"invoiceCode\":\"050003521270\",\n" +
				"      \"invoiceAmount\":\"1240\",\n" +
				"      \"invoiceValue\":\"bD4=\"\n" +
				"    }\n" +
				"]}";
		String b = returnAnalysisJson(a,"7");
		System.out.println(b);
	}

	/**
	 * 文件上传并返回下载地址
	 * @param fileStr 字符串文件流
	 * @param savePath 文件要保存的文件夹地址（/zzx-pac/）
	 * @return /getResource?path=/policy/1231231.jpg
	 */
	public static String uploadFile(String fileStr, String fileType, String savePath){
		String result = "";
		if (StringUtils.isEmpty(fileStr)) {
			return result;
		}
		try {
			if(StringUtils.isEmpty(fileType)){
				fileType = "pdf";
			}
			byte[] bytes = BASE64Util.decryptBASE64Byte(fileStr);
			String files = DateUtil.generatorRadomNumber() + ConstProp.DOT +fileType;
			result = savePath + files;
			String path = GlobalResources.COM_IMG_RE+savePath;
			FileHelp.byteFile(bytes, path, files);
			result = "/getResource?path="+result;
		} catch (Exception e) {
			e.printStackTrace();
			result = "";
		}
		return result;
	}

	private static String getDate(String doTime,int status){
		String result = "";
		if(StringUtils.isEmpty(doTime)){
			return result;
		}
		try {
			if(status == 0){//常规转换
				result = DateUtil.convertDateToString(DateUtil.parseDate(doTime),DateUtil.FORMAT2);
			}else if(status == 1){//+ 00:00:00
				result = DateUtil.convertDateToString(DateUtil.parseDate(doTime),DateUtil.FORMAT2);
				if(StringUtils.isNotEmpty(result)){
					result = result + ConstProp.DAY_00;
				}
			}else if(status == 2){//+ 23:59:59
				Date beT = DateUtil.parseDate(doTime);
				Calendar cDate = Calendar.getInstance();
				cDate.setTime(beT);
				cDate.set(Calendar.DATE, cDate.get(Calendar.DATE) - 1);
				result = DateUtil.convertDateToString(beT,DateUtil.FORMAT2);
				if(StringUtils.isNotEmpty(result)){
					result = result + ConstProp.DAY_23;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	private static String getCityCodeByPro(String pro,String city){
		if("110000".equals(pro)){
			return pro;
		}else if("120000".equals(pro)){
			return pro;
		}else if("500000".equals(pro)){
			return pro;
		}else if("310000".equals(pro)){
			return pro;
		}else if("710000".equals(pro)){
			return pro;
		}else if("810000".equals(pro)){
			return pro;
		}else if("820000".equals(pro)){
			return pro;
		}else{
			return city;
		}
	}

	private static void doResultCheDan() {
		//        String  resultMsg= "{\"header\":{\"transactionCode\":\"TCEGISNBUAPC001\",\"partnerId\":\"PCXM001\",\"requestId\":\"1493874890537\",\"code\":\"NBUERROR_0008\",\"message\":\"{\\\"ReturnFlag\\\":1,\\\"ResponseMsg\\\":\\\"系统生成保益保费之和510元与总单保费390元不符;\\\"}\"},\"body\":null}";
		String   resultMsg="{\"header\":{\"transactionCode\":\"TCEGISNBUWD001\",\"partnerId\":\"PCXM001\",\"requestId\":\"1493865755617\",\"code\":\"CRIGHT_0000\",\"message\":null},\"body\":\"\\\"{\\\\\\\"errorMessage\\\\\\\":\\\\\\\"fail\\\\\\\",\\\\\\\"rcptnoList\\\\\\\":[{\\\\\\\"message\\\\\\\":\\\\\\\"条形码9041K009837424的业务状态不允许进行撤件\\\\\\\",\\\\\\\"no\\\\\\\":\\\\\\\"30000070075776495\\\\\\\"}],\\\\\\\"resultFlag\\\\\\\":\\\\\\\"-1\\\\\\\"}\\\"\"}";
		Map<String, Object> map = null;
		try{
			map = JSON.parseObject(resultMsg,Map.class);
			Map<String, Object> header = JSON.parseObject( map.get("header").toString(),Map.class);
			if(!header.get("code").equals("CRIGHT_0000")){
				logger.info("300#撤单失败");
				return;
			}
			//返回成功
			String  bodyStr= map.get("body").toString();
			bodyStr=bodyStr.replaceFirst("\"","");//只替换第一个
			bodyStr=bodyStr.substring(ConstProp.INT_NUMBER_ZERO,bodyStr.lastIndexOf('"'));
			bodyStr = bodyStr.replace("\\", "");
			Map<String, Object> body = JSON.parseObject(bodyStr,Map.class);
			if(body.get("resultFlag").toString().equals(ConstProp.DIGIT_ZERO)){
				String errorMessage=body.get("errorMessage").toString();
				logger.info("200#"+errorMessage);
			}else{
			   JSONArray array= JSON.parseArray(body.get("rcptnoList").toString());
				String  result =ConstProp.BLANK_CHAR;
				for(int i=ConstProp.INT_NUMBER_ZERO;i<array.size();i++){
					com.alibaba.fastjson.JSONObject object = (com.alibaba.fastjson.JSONObject) array.get(i);
					result=result+ConstProp.POUND_SIGN+object.get("message")+ConstProp.POUND_SIGN+object.get("no");
				}
				String   errorMessage =body.get("resultFlag").toString();
				logger.info("300"+result);
			}
		}catch(Exception e){

			e.printStackTrace();
		}
 	}

	private static void doResultTouBao() {
		//        String  resultMsg= "{\"header\":{\"transactionCode\":\"TCEGISNBUAPC001\",\"partnerId\":\"PCXM001\",\"requestId\":\"1493874890537\",\"code\":\"NBUERROR_0008\",\"message\":\"{\\\"ReturnFlag\\\":1,\\\"ResponseMsg\\\":\\\"系统生成保益保费之和510元与总单保费390元不符;\\\"}\"},\"body\":null}";
		String   resultMsg="{\"header\":{\"transactionCode\":\"TCEGISNBUAPC001\",\"partnerId\":\"PCXM001\",\"requestId\":\"1493866040327\",\"code\":\"CRIGHT_0000\",\"message\":null},\"body\":\"{\\\"barCode\\\":\\\"9041K009837633\\\",\\\"receiptNo\\\":\\\"30000070075777063\\\",\\\"responseMsg\\\":\\\"AMESB接口InsuredAMESBService调用成功！\\\",\\\"returnFlag\\\":\\\"1\\\",\\\"totalPremium\\\":\\\"510\\\"}\"}";
		Map<String, Object> map = null;
		try{
            map = JSON.parseObject(resultMsg,Map.class);
            Map<String, Object> header = JSON.parseObject( map.get("header").toString(),Map.class);
            if(header.get("code").equals("CRIGHT_0000")){
                //返回成功
                Map<String, Object> body = JSON.parseObject( map.get("body").toString(),Map.class);
                String receiptNo=body.get("receiptNo").toString();
                String  totalPremium=body.get("totalPremium").toString();//保费
                logger.info("200#"+receiptNo+ConstProp.POUND_SIGN+totalPremium+ConstProp.POUND_SIGN+"http://www.baidu.com");
            }else{
                //返回失败
                Map<String, Object> message = JSON.parseObject(header.get("message").toString(),Map.class);
                String msg=message.get("ResponseMsg").toString();
                logger.info("300#"+msg);
            }
//            logger.info(header.toString());
        }catch(Exception e){

        }
	}
}
