package com.bcxin.ins.third.zzx.zhongan;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.third.zzx.zhongan.dto.CashierConstant;
import com.bcxin.ins.util.DateUtil;
import com.bcxin.ins.util.IdWorker;
import com.bcxin.ins.util.RegionUtils;
import com.bcxin.ins.vo.*;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.util.*;

/**
 *
 * <b>团意险平安几块请求</b>
 *
 * @author liyognqiang
 * @date 2017年4月19日 上午10:29:46
 * @注意事项 </b>
 * <b>
 */
public class PackageMessageZhongAn {


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

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


	public static JSONObject marshal(LOTEPolicyVo vo, OrderFormVo dto, String transType, Map<String,String> map) throws Exception {
		JSONObject mapP = new JSONObject();
		//请求头部

		if("1".equals(transType)){//核保
			//投保接口
			//请求内容
			//投保基本信息
			mapP.put("productCode",matchProductCode(dto.getProduct_code()));//产品组合编号  TODO 数据为模拟
			mapP.put("channelOrderNo",dto.getTrade_serial_number());//商户订单号 TODO 数据为模拟
			setOrderInfo_1(mapP,vo, dto);
		}else if ("2".equals(transType)){//承保
			//承保数据组装
			mapP.put("productCode",matchProductCode(dto.getProduct_code()));//产品组合编号  TODO 数据为模拟
			mapP.put("channelOrderNo",dto.getTrade_serial_number());//商户订单号 TODO 数据为模拟
			setOrderInfo_2(mapP,vo, dto, map);
			setTranInfo(mapP,map);

		}else if("3".equals(transType)){//退保
			//支付跳转


		}
		return mapP;
	}

	private static String matchProductCode(String pCode){
		if("ZZX-ZA-1".equals(pCode)){
			return "ff633ad873686cf6b007a1e34f48aa1423d6b9eb19b9";
		}else if("ZZX-ZA-2".equals(pCode)){
			return "ff633ad873686cf6b007a1e34f48aa1423d6b9eb18b9";
		}else if("ZZX-ZA-3".equals(pCode)){
			return "ff633ad873686cf6b007a1e34f48aa1423d6b9ea11b9";
		}
		return "";
	}

	/**
	 * 交易信息组装
	 * @param map
	 * @param mapTran 外部支付完成后得到的支付信息
	 */
	private static void setTranInfo(JSONObject map,Map<String, String> mapTran){
		map.put("outTradeNo",mapTran.get(CashierConstant.RETURN_OUT_TRADE_NO));//交易订单号
		map.put("zaTradeNo",mapTran.get(CashierConstant.RETURN_TRADE_NO));//众安唯一订单号
		map.put("premiumPayAmount",mapTran.get(CashierConstant.AMT));//支付金额
		map.put("premiumPayTime",setDates(mapTran.get(CashierConstant.RETURN_PAY_TIME)));//支付时间
		map.put("premiumPayType",getPayType(mapTran.get(CashierConstant.RETURN_PAY_CHANNEL)));//保费支付方式，"1-支付宝2-银行转账3-其他4-微信支付5-财付通6-新浪支付 7-企业资金账户8-银联支付9-信保分期支付10-微信二支付11-翼支付12-德付通13-拉卡拉POS机99-众安支付"
	}

	private static String getPayType(String str){
		if("alipay".equals(str)){
			return ConstProp.DIGIT_ONE;
		}else if("wxpay".equals(str)){
			return ConstProp.DIGIT_FOUR;
		}else if("unionpay".equals(str)||"unionpayB2B".equals(str)){
			return "8";
		}
		return ConstProp.BLANK_CHAR;
	}

	/**
	 * 订单信息组装数据
	 * @param map
	 * @param vo
	 * @param dto
	 */
	private static void setOrderInfo_1(JSONObject map,LOTEPolicyVo vo, OrderFormVo dto){
		setAppAndInsInfo(map,vo, dto);
		String email = "zhongxuefeng@bcxin.com.cn";
		for(RoleSubjectVo roleSubjectVo : vo.getRoleSubjectList()) {
			if ("1".equals(roleSubjectVo.getKind())) {
				email = roleSubjectVo.getLink_email();
				break;
			}
		}
		map.put("premiumAmount",dto.getGross_premium());//保费金额
		boolean nr = ConstProp.DIGIT_ONE.equals(vo.getMailPolicyVo().getNeed_receipt());//是否需要发票
		boolean it = false;
		if(nr){
			it = ConstProp.DIGIT_ZERO.equals(vo.getMailPolicyVo().getInvoice_type());//是否是增值税普通发票（电子发票）
		}
		map.put("requireInvoice",it ? "Y" : "N");//是否需要电子发票"Y-需要N-不需要"
		map.put("contactMail", email);//保单联系邮箱 TODO 直接取自投保人信息中的邮箱
		JSONObject mapEx = new JSONObject();
		mapEx.put("address", RegionUtils.getRegionNameByALLCode(vo.getSpecialExhibitionVo().getEx_province(),vo.getSpecialExhibitionVo().getEx_city(),vo.getSpecialExhibitionVo().getEx_county()));
		mapEx.put("numberOfEmployees",vo.getSpecialExhibitionVo().getEx_emp_num());
		mapEx.put("space",vo.getSpecialExhibitionVo().getEx_acreage());
		DateFormat dateFormatAny = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
		mapEx.put("policyEffectiveDate",String.valueOf(dateFormatAny.format(DateUtil.convertStringToDate(vo.getSpecialExhibitionVo().getStar_time()+ConstProp.DAY_00).getTime())));
		mapEx.put("policyExpiryDate",String.valueOf(dateFormatAny.format(DateUtil.convertStringToDate(vo.getSpecialExhibitionVo().getEnd_time()+ConstProp.DAY_23).getTime())));
		map.put("extraInfo",mapEx.toString());//policystartdate/policyexpiredate TODO 该字段可能为存放生效失效日期
	}

	/**
	 * 订单信息组装数据
	 * @param map
	 * @param vo
	 * @param dto
	 * @param maps
	 */
	private static void setOrderInfo_2(JSONObject map,LOTEPolicyVo vo, OrderFormVo dto, Map<String,String> maps){
		setAppAndInsInfo(map,vo, dto);
		String email = "zhongxuefeng@bcxin.com.cn";
		for(RoleSubjectVo roleSubjectVo : vo.getRoleSubjectList()) {
			if ("1".equals(roleSubjectVo.getKind())) {
				email = roleSubjectVo.getLink_email();
				break;
			}
		}
		map.put("premiumAmount",dto.getGross_premium());//保费金额
		boolean nr = ConstProp.DIGIT_ONE.equals(vo.getMailPolicyVo().getNeed_receipt());//是否需要发票
		boolean it = false;
		if(nr){
			it = ConstProp.DIGIT_ZERO.equals(vo.getMailPolicyVo().getInvoice_type());//是否是增值税普通发票（电子发票）
		}
		map.put("requireInvoice",it ? "Y" : "N");//是否需要电子发票"Y-需要N-不需要"
		map.put("contactMail", email);//保单联系邮箱 TODO 直接取自投保人信息中的邮箱
		JSONObject mapEx = new JSONObject();
		mapEx.put("address", RegionUtils.getRegionNameByALLCode(vo.getSpecialExhibitionVo().getEx_province(),vo.getSpecialExhibitionVo().getEx_city(),vo.getSpecialExhibitionVo().getEx_county()));
		mapEx.put("numberOfEmployees",vo.getSpecialExhibitionVo().getEx_emp_num());
		mapEx.put("space",vo.getSpecialExhibitionVo().getEx_acreage());
		mapEx.put("payTradeNo",maps.get(CashierConstant.RETURN_PAY_TRADE_NO));
		DateFormat dateFormatAny = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
		mapEx.put("policyEffectiveDate",String.valueOf(dateFormatAny.format(DateUtil.convertStringToDate(vo.getSpecialExhibitionVo().getStar_time()+ConstProp.DAY_00).getTime())));
		mapEx.put("policyExpiryDate",String.valueOf(dateFormatAny.format(DateUtil.convertStringToDate(vo.getSpecialExhibitionVo().getEnd_time()+ConstProp.DAY_23).getTime())));
		map.put("extraInfo",mapEx.toString());//policystartdate/policyexpiredate TODO 该字段可能为存放生效失效日期
	}

	private static String getIDType(String str){
		if("1".equals(str)){//组织机构代码
			return "Z";
		}else if("2".equals(str)){//统一社会信用代码
			return "TY";
		}else if("6".equals(str)){//税务登记证件号
			return "T";
		}else if("7".equals(str)){//工商登记号
			return "L";
		}
		return "";
	}

	/**
	 * 投保人被保险人组装信息
	 * @param map
	 * @param vo
	 * @param dto
	 */
	private static void setAppAndInsInfo(JSONObject map,LOTEPolicyVo vo, OrderFormVo dto){
		for(RoleSubjectVo roleSubjectVo : vo.getRoleSubjectList()) {
			if (ConstProp.DIGIT_ONE.equals(roleSubjectVo.getKind())) {
				map.put("policyHolderUserName",roleSubjectVo.getName_cn());//投保人姓名
				map.put("policyHolderCertiType",getIDType(roleSubjectVo.getId_type()));//投保人证件类型，企业：T-税务登记证 L-执照 O-组织机构证 Z-组织机构代码 TY-统一社会信用代码
				map.put("policyHolderCertiNo",roleSubjectVo.getOrganization_code());//投保人证件号码
				map.put("policyHolderPhone",roleSubjectVo.getLink_tel());//投保人手机号
			}
			if (ConstProp.DIGIT_TWO.equals(roleSubjectVo.getKind())) {
				map.put("insuredUserName",roleSubjectVo.getName_cn());//被保险人姓名
				map.put("insuredCertiType",getIDType(roleSubjectVo.getId_type()));//被保险人证件类型，企业：T-税务登记证 L-执照 O-组织机构证 Z-组织机构代码 TY-统一社会信用代码
				map.put("insuredCertiNo",roleSubjectVo.getOrganization_code());//被保险人证件号码
				map.put("insuredPhone",roleSubjectVo.getLink_tel());//被保险人手机号

				map.put("policyHolderBirthDate",ConstProp.BLANK_CHAR);//-----------------------------
				map.put("insuredBirthDay",ConstProp.BLANK_CHAR);//-----------------------------
				map.put("policyHolderType",ConstProp.DIGIT_TWO);//-----------------------------
				DateFormat dateFormatAny = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
				map.put("insureDate",String.valueOf(dateFormatAny.format(DateUtil.convertStringToDate(dto.getStart_time()).getTime())));//被保险人投保时间
			}
		}
	}

	/**
	 *	接口返回字符串解析
	 * @return
	 */
	public static String returnAnalysisJson(String json, String  transType){
		String result = ConstProp.BLANK_CHAR;
		try{
			Map<String, Object> map = JSON.parseObject(json,Map.class);
			if( map != null ){
				if("N".equals(map.get("issueResultType"))){
					return "300#（APP-ZA-300.02）"+map.get("issueErrorDetail");
				}else{
					if(transType.equals(ConstProp.DIGIT_ONE)) {
						//核保
						return "200#BCX-"+ IdWorker.getId();
					}else if(transType.equals(ConstProp.DIGIT_TWO)) {
						//承保
						return "200#"+map.get("policyNo")+ConstProp.POUND_SIGN+map.get("contractURL");
					}else if(transType.equals(ConstProp.DIGIT_THREE)) {
						//退保
						return "200#";
					}
				}

			}else{
				return "300#（APP-ZA-300.09）接口调用失败！";
			}
		}catch(Exception e){
			e.printStackTrace();
			return "300#（APP-ZA-300.10）异常错误";
		}
		return "";
	}

	/* **************************以上为新加*********************************/

	//转换日期格式
	private static String setDates(String doTime){
		String result = ConstProp.BLANK_CHAR;
		if(StringUtils.isNotEmpty(doTime)){
			result = DateUtil.convertDateToString(DateUtil.convertString2Date(doTime), DateUtil.FORMAT1_2);
		}
		return result;
	}


	private static String getDate(String doTime,int status){
		String result = ConstProp.BLANK_CHAR;
		if(StringUtils.isNotEmpty(doTime)){
			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;
		}
	}

	public static void main(String[] args){
//		Map<String, String> addOrderMap = buildRequest();
//		System.out.println(CashierSubmitUtil.buildRequest("http://cashier.daily.zhongan.com/za-cashier-web/gateway.do", addOrderMap, CashierConfig.APP_KEY));
	}

}
