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

import com.bcxin.ins.third.build.taibao.TransType;
import com.bcxin.ins.util.DateUtil;
import com.bcxin.ins.util.RegionUtils;
import com.bcxin.ins.vo.OrderFormVo;
import com.bcxin.ins.vo.RoleSubjectVo;
import com.bcxin.ins.vo.SpecialBidVo;
import com.bcxin.ins.vo.SpecialPublicDutyVo;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.text.DateFormat;
import java.util.Date;

/**
 *
 * <b>太保-公责险请求各类型接口数据组装及解析</b>
 *
 * @author zxf
 * @date 2017年9月25日 上午10:29:46
 * @注意事项 </b>
 * <b>
 */
public class PackageMessageTaiBao {

	private static final String APPLICANT = "Applicant";
	private static final String INSURED = "Insured";
	private static final String BLANK_CHAR = "";
	private static final String PARTNERCODE = "XMBCX";//合作方
	private static final String TBUSER = "XMBCX";
	private static final String TBPASS = "+kp0LXaWRRWq2bsb/EJR22O2aqjghfCrGe/OaJJheaJttbKcDxlXiDYfpcxLK1fKm75rGAjtNsTFuxt/v/F+Vw==";

	public static String marshal(String tsNumber, SpecialPublicDutyVo policy, OrderFormVo orderVo, String tb_code, String paymentType, TransType transType) throws Exception {
		if(policy == null) {
			return BLANK_CHAR;
		}

		Document requestDocument = DocumentHelper.createDocument();
		requestDocument.setXMLEncoding("UTF-8");
		Element rootElement = requestDocument.addElement("request");


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

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

				//投保基本信息
				Element plcBase = entityElement.addElement("plcBase");
				//支付信息节点
				//Element payinfo = entityElement.addElement("payinfo");
				//经办人节点循环
				//Element handlerList = rootElement.addElement("handlerList");
				//经办人节点循环>>经办人节点
				//Element handler = handlerList.addElement("handler");
				//投保人节点
				Element applicant = entityElement.addElement("applicant");
				//被保险人节点循环
				Element insuredList = entityElement.addElement("insuredList");
				//地址信息节点循环
				//Element addressList = entityElement.addElement("addressList");

				Element pconstruct = entityElement.addElement("pconstruct");

				Element elcPolicy = entityElement.addElement("elcPolicy");


				RoleSubjectVo applicants = policy.getRoleSubjectList().get(0);
				RoleSubjectVo insureds = policy.getRoleSubjectList().get(1);

				//保单信息
				marshalPolicy(policy,tb_code,paymentType, plcBase);

				//建筑信息
				marshalPconstruct(policy, pconstruct);

				//支付信息
				//marshalPayinfo(policy, payinfo);

				//投保人信息
				marshalApplicant( applicants, applicant);

				//被保人信息
				marshalInsured(policy, insureds, insuredList);

				//地址信息
				//marshalAddressMsg(policy, insureds, addressList);

				marshalElcPolicy(applicants, elcPolicy);
			} else if( TransType.EPIC_QUERY.equals(transType) ){
				entityElement.addElement("queryType").setText(String.valueOf("0"));
				entityElement.addElement("plcApplyNo").setText(String.valueOf(orderVo.getPolicy_serial_number()));
			} else if( TransType.EPIC_EPOLICY.equals(transType) ){
				RoleSubjectVo applicants = policy.getRoleSubjectList().get(0);
				entityElement.addElement("plcNo").setText(String.valueOf(orderVo.getExternal_reference()));
				entityElement.addElement("elcMsgFlag").setText(String.valueOf("0"));
				entityElement.addElement("elcMobile").setText(String.valueOf(applicants.getLink_tel()));
				entityElement.addElement("elcEmlFlag").setText(String.valueOf("0"));
				entityElement.addElement("elcEmail").setText(String.valueOf(""/*applicants.getEmail()*/));
				entityElement.addElement("returnPDF").setText(String.valueOf("1"));
			}
			String requestMsg = requestDocument.asXML();

			return requestMsg;

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

		return null;
	}
	private static void marshalPconstruct(SpecialPublicDutyVo policy, Element underwrite){
		/*//工程项目名称(必须输入)
		underwrite.addElement("projectname").setText(policy.getProject_name());
		//建设工程招标文件编号(可选输入)
		underwrite.addElement("biddingdocno").setText(policy.getInvitation_code());
		//工程项目建设地点(必须输入)
		underwrite.addElement("businessaddress").setText(String.valueOf(policy.getProject_address()));
		//计划工期(可选输入)
		underwrite.addElement("projectduration").setText(policy.getProject_time());
		//投标日期(必须输入yyyy-MM-dd)
		underwrite.addElement("bidtime").setText(String.valueOf(dateFormat.format(DateUtil.convertStringToDate(policy.getBid_time()))));
*/
	}
	private static void marshalHead(String tsNumber,Element underwrite,TransType transType) {
		// 合作方编码，必传
		underwrite.addElement("partnerCode").setText(PARTNERCODE);
		// 业务交易码，必传
		underwrite.addElement("transactionCode").setText(transType.getValue());
		// 交易流水号，必传
		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 void marshalPolicy(SpecialPublicDutyVo policy, String tb_code, String paymentType, Element underwrite) {
		//TODO  业务归属地编码？打印方式的值？
		// 业务归属地编码，必传
		underwrite.addElement("plcTerminalNo").setText(tb_code);
		// 业务号(订单号)，必传
		underwrite.addElement("plcBusinessNo").setText(policy.getTrade_serial_number());
		// 承保方案代码，必传
		underwrite.addElement("plcPlanCode").setText("PN130932001600000006"/*policy.getPlanSpec().getExternalReference()*/);
		// 保单生效时间，必传 yyyyMMdd
		DateFormat dateFormatH = new java.text.SimpleDateFormat("yyyyMMddHH");
		underwrite.addElement("plcStartDate").setText(dateFormatH.format(DateUtil.convertStringToDate(policy.getInception_date())));
		// 保单失效时间，必传 yyyyMMdd
		String dateEnd = dateFormatH.format(DateUtil.convertStringToDate(policy.getPlanned_end_date()));
		dateEnd = dateEnd.substring(0, dateEnd.length()-2)+"24";
		underwrite.addElement("plcEndDate").setText(dateEnd);
		// 总保证金额度，必传（根据额度的多少匹配相对应的保费，太保那边做）
		underwrite.addElement("plcAmount").setText(String.valueOf(policy.getInsured_amount()));
		// 份数，必传
		underwrite.addElement("plcCopies").setText(String.valueOf(1));
		// 打印方式，必传
		underwrite.addElement("plcElcFlag").setText("0");
		//支付方式(必须输入 支付渠道 1-CHINAPAY-对公,2-CHINAPAY-对私,3-目前未使用,4-微信)
		underwrite.addElement("paymentWay").setText(paymentType);
		//微信支付地址(必须输入)
		underwrite.addElement("wxUrl").setText("0");

	}

	private static void marshalPayinfo(SpecialBidVo policy, Element underwrite) {
		// 支付方式，必传
		underwrite.addElement("payType").setText("4");
		// 支付号，必传
		underwrite.addElement("payNo").setText("Test201521");
		// 商户号，必传
		underwrite.addElement("payMerchantNo").setText("Test20150129");
		// 支付确认时间，必传 yyyy-MM-dd
		DateFormat dateFormatAny = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
		underwrite.addElement("payConfirmDate").setText(dateFormatAny.format(new Date()));

	}


	private static void marshalApplicant(RoleSubjectVo applicant, Element underwrite) {
		//投保人证件号码 ，必传
		underwrite.addElement("apltCretCode").setText(String.valueOf(applicant.getOrganization_code()));
		//投保人证件类型 ，必传
		underwrite.addElement("apltCretType").setText("4");
		//投保人名称，必传
		underwrite.addElement("apltName").setText(String.valueOf(applicant.getName_cn()));
		//电子邮箱，可选 【用于接收邮件】
		//underwrite.addElement("apltEmail").setText(String.valueOf(applicant.getLinkEmail()));
		underwrite.addElement("apltEmail").setText(String.valueOf(applicant.getLink_email()));
		//投保人固定电话，可选
		underwrite.addElement("apltTelephone").setText(String.valueOf(applicant.getPhone()));
		//移动电话，可选
		underwrite.addElement("apltMobile").setText(String.valueOf(applicant.getLink_tel()));
		//投保人地址信息，可选
		String address = RegionUtils.getRegionNameByALLCode(applicant.getReg_province(),applicant.getReg_city(),applicant.getReg_district())+applicant.getReg_address();
		underwrite.addElement("apltAddress").setText(address);
		//投保人邮编，可选
		underwrite.addElement("apltPost").setText(String.valueOf(applicant.getZip_code()));
		//投保人联系人，可选
		underwrite.addElement("apltCntactName").setText(String.valueOf(applicant.getLink_name()));

	}


	private static void marshalInsured(SpecialPublicDutyVo policy, RoleSubjectVo insured, Element underwrite) {
		Element insuredElement = underwrite.addElement("insured");
		//被保人证件号码 ，必传
		insuredElement.addElement("isrdCretCode").setText(String.valueOf(insured.getOrganization_code()));
		//被保人证件类型 ，必传
		insuredElement.addElement("isrdCretType").setText("4");
		//被保人名称，必传
		insuredElement.addElement("isrdName").setText(String.valueOf(insured.getName_cn()));
		//被保人固定电话，可选
		insuredElement.addElement("isrdTelephone").setText(String.valueOf(insured.getPhone()));
		//移动电话，可选
		insuredElement.addElement("isrdMobile").setText(String.valueOf(insured.getLink_tel()));
		String address = RegionUtils.getRegionNameByALLCode(insured.getReg_province(),insured.getReg_city(),insured.getReg_district())+insured.getReg_address();
		//被保人地址信息，可选
		insuredElement.addElement("isrdAddress").setText(address);
		//被保人邮编，可选
		insuredElement.addElement("isrPost").setText(String.valueOf(insured.getZip_code()));
		//被保人联系人，可选
		insuredElement.addElement("isrCntactName").setText(String.valueOf(insured.getLink_name()));

	}


	private static void marshalElcPolicy(RoleSubjectVo applicants, Element underwrite) {
		//短信发送标志(必须输入)
		underwrite.addElement("elcMsgFlag").setText("1");
		//短信接收手机号(可选输入)
		underwrite.addElement("elcMobile").setText(String.valueOf(applicants.getTel()));
		//邮件发送标志(必须输入)
		underwrite.addElement("elcEmlFlag").setText("1");
		//电子保单接收邮箱(可选输入)
		underwrite.addElement("elcEmail").setText(String.valueOf(applicants.getLink_email()));
	}

	private static void marshalAddressMsg(SpecialBidVo policy, RoleSubjectVo insureds, Element underwrite) {
		Element address = underwrite.addElement("address");
		//邮编
		address.addElement("adsPostCode").setText(String.valueOf("363900"));
//		<!--被保险人-->
		address.addElement("insurcode").setText(String.valueOf(insureds.getName_cn()));
//		<!--地址-->
		address.addElement("adsAddress").setText(String.valueOf("漳州"));
//		<!--市代码-->
		address.addElement("adsCity").setText(String.valueOf("150300"));
	}

}
