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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bcxin.ins.third.xyx.yb_enum.YB_City;
import com.bcxin.ins.third.zzx.yongan.vo.*;
import com.bcxin.ins.util.*;
import com.bcxin.ins.vo.*;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.mybatisplus.toolkit.StringUtils;
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 javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.util.*;

/**
 *
 * <b>都邦-投标保证保险各接口请求数据组装</b>
 *
 * @author zxf
 * @date 2017年10月11日 上午10:29:46
 * @注意事项 </b>
 * <b>
 */
public class ZZX_PackageMessageYongAn {
	protected Document requestDocument;
	protected Element rootElement;

	private final static String USER = "BCX";//用户名
//	private final static String PWD = "1234567890";//密码
	private final static String CCP = "TIT_BCX";//业务来源
//	private final static String OCODE = "330027";//出单员编码

	void Build_PackageMessageDuBang(){

	}

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

	public static AppRequestBean marshal(LOTEPolicyVo vo, OrderFormVo dto, String transType, int is_phone){
		String result;
		AppRequestBean arb = new AppRequestBean();
		try {
			if(ConstProp.DIGIT_ONE.equals(transType)){
				BaseInfo bi = new BaseInfo();
				List<AppInfo> ais = new ArrayList<AppInfo>();// 第三方投保信息集合
				AppInfo ai = new AppInfo();// 第三方投保信息
				AppBaseInfo abi = new AppBaseInfo();// 投保人基本信息
				List<InsuredInfo> iis = new ArrayList<InsuredInfo>();// 被保险人信息集合
				List<PropertyInfo> propertyInfo = new ArrayList<PropertyInfo>();// 标的信息集合
				InsuredInfo ii = new InsuredInfo();// 被保险人信息
				PropertyInfo pi = new PropertyInfo();// 标的信息

				marshalBaseInfo(vo, dto, bi, is_phone);//基本信息
				marshalAppBaseInfo(vo, dto, abi);//投保人信息
				marshalInsuredInfo(vo, dto, ii);//被保险人信息
				marshalPropertyInfo(vo, dto, pi);//标的信息
				ai.setAppBaseInfo(abi);
				iis.add(ii);
				ai.setInsuredInfos(iis);
				propertyInfo.add(pi);
				ai.setPropertyInfos(propertyInfo);

				ais.add(ai);
				arb.setAppInfos(ais);
				arb.setBaseInfo(bi);
			}else if(ConstProp.DIGIT_TWO.equals(transType)){
				BaseInfo bi = new BaseInfo();
				bi.setUser(USER);//用户名
				bi.setPassword(GlobalResources.YA_ZZ_PWD);//密码
				bi.setCcardbsnstyp(CCP);//业务来源
				bi.setSerialno(dto.getPolicy_serial_number());
				arb.setBaseInfo(bi);
			}
			result = arb.toString();
			logger.info("永安请求核保时数据组装报文--marshal："+result);
		}catch (Exception e){
			e.printStackTrace();
		}
		return arb;
	}

	//基础信息 baseInfo
	private static void marshalBaseInfo(LOTEPolicyVo vo, OrderFormVo dto, BaseInfo baseInfo, int is_phone){
		// 基本信息
		IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
		baseInfo.setUser(USER);//用户名
		baseInfo.setPassword(GlobalResources.YA_ZZ_PWD);//密码
		baseInfo.setSerialno(dto.getTrade_serial_number());
		baseInfo.setCcardbsnstyp(CCP);//业务来源
		baseInfo.setTapptm(setXGC(dto.getStart_time()));//投保日期
		baseInfo.setTissuetm(setXGC(dto.getStart_time()));//签单日期
		baseInfo.setTinsrncbgntm(setXGC(dto.getInception_date()+ConstProp.DAY_00));//保险起期
		baseInfo.setTinsrncendtm(setXGC(dto.getPlanned_end_date()+ConstProp.DAY_23));//保险止期
		baseInfo.setRationcode(getRationcode(vo, dto));//方案号
		baseInfo.setArguesolution(String.valueOf("0".equals(vo.getSpecialExhibitionVo().getDispute())?"A":"B"));//争议处理
		baseInfo.setOpercode(GlobalResources.YA_ZZ_OCODE);//出单员
		baseInfo.setIsgrp("0");//个单传值为0；团单传值1
		baseInfo.setAmt(Double.valueOf(dto.getGross_premium()));//总保费
		baseInfo.setPayflag(String.valueOf(is_phone));//见费出单支付渠道（0或空:电脑版，1：手机版）
		String returnUrl = GlobalResources.DONOW_PATH+"transaction/common-syntony/"+dto.getOid();
		if(ConstProp.BLB.equals(dto.getWeb_type())){
			returnUrl = GlobalResources.WEB_URL+"/insurance/zzx/transaction/syntony-service/"+dto.getOid();
		}
		if(is_phone == 1){
			returnUrl = GlobalResources.DONOW_PATH+"/weixin/product/pay/finish/"+dto.getOid();//支付完成的回调地址
		}
		baseInfo.setBackurl(returnUrl);//回调页面地址
	}
	
	private static String getRationcode(LOTEPolicyVo vo, OrderFormVo dto){
		RoleSubjectVo roleVo = vo.getRoleSubjectList().get(0);
		SpecialExhibitionVo seVo = vo.getSpecialExhibitionVo();
		Double ea = Double.valueOf(seVo.getEx_acreage());
		String result = "";
		if("1".equals(roleVo.getRole_type())){
			//参展商
			result = roleType1(dto, ea);
		}else if("2".equals(roleVo.getRole_type())){
			//搭建商
			result = roleType2(dto, ea);
		}
		return result;
	}

	/**
	 * <b> 搭建商类型产品配置编码 </b>
	 * @author ZXF
	 * @create 2020/09/29 0029 17:03
	 * @version
	 * @注意事项 </b>
	 */
	private static String roleType2(OrderFormVo dto, Double ea) {
		String result = "";
		if(ea<37){
            if("ZZX-YA-1".equals(dto.getProduct_code())){
                result = "0233000073";
            }else if("ZZX-YA-2".equals(dto.getProduct_code())){
                result = "0233000074";
            }else if("ZZX-YA-3".equals(dto.getProduct_code())){
                result = "0233000075";
            }
        }else if(ea>36 && ea<109){
            if("ZZX-YA-1".equals(dto.getProduct_code())){
                result = "0233000076";
            }else if("ZZX-YA-2".equals(dto.getProduct_code())){
                result = "0233000077";
            }else if("ZZX-YA-3".equals(dto.getProduct_code())){
                result = "0233000078";
            }
        }else if(ea>108){
            if("ZZX-YA-1".equals(dto.getProduct_code())){
                result = "0233000079";
            }else if("ZZX-YA-2".equals(dto.getProduct_code())){
                result = "0233000080";
            }else if("ZZX-YA-3".equals(dto.getProduct_code())){
                result = "0233000081";
            }
        }
		return result;
	}

	/**
	 * <b> 参展商类型产品配置编码 </b>
	 * @author ZXF
	 * @create 2020/09/29 0029 17:03
	 * @version
	 * @注意事项 </b>
	 */
	private static String roleType1(OrderFormVo dto, Double ea) {
		String result = "";
		if(ea<37){
            if("ZZX-YA-1".equals(dto.getProduct_code())){
                result = "0233000064";
            }else if("ZZX-YA-2".equals(dto.getProduct_code())){
                result = "0233000065";
            }else if("ZZX-YA-3".equals(dto.getProduct_code())){
                result = "0233000066";
            }
        }else if(ea>36 && ea<109){
            if("ZZX-YA-1".equals(dto.getProduct_code())){
                result = "0233000067";
            }else if("ZZX-YA-2".equals(dto.getProduct_code())){
                result = "0233000068";
            }else if("ZZX-YA-3".equals(dto.getProduct_code())){
                result = "0233000069";
            }
        }else if(ea>108){
            if("ZZX-YA-1".equals(dto.getProduct_code())){
                result = "0233000070";
            }else if("ZZX-YA-2".equals(dto.getProduct_code())){
                result = "0233000071";
            }else if("ZZX-YA-3".equals(dto.getProduct_code())){
                result = "0233000072";
            }
        }
		return result;
	}

	private static XMLGregorianCalendar setXGC(String time){
		return dateToXmlDate(DateUtil.convertStringToDate(time));
	}

	// 转换日期格式
	private static XMLGregorianCalendar dateToXmlDate(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		DatatypeFactory dtf = null;
		try {
			dtf = DatatypeFactory.newInstance();
		} catch (DatatypeConfigurationException e) {
		}
		XMLGregorianCalendar dateType = dtf.newXMLGregorianCalendar();
		dateType.setYear(cal.get(Calendar.YEAR));
		// 由于Calendar.MONTH取值范围为0~11,需要加1
		System.out.println(cal.get(Calendar.MONTH) + 1);
		dateType.setMonth(cal.get(Calendar.MONTH) + 1);
		dateType.setDay(cal.get(Calendar.DAY_OF_MONTH));
		dateType.setHour(cal.get(Calendar.HOUR_OF_DAY));
		dateType.setMinute(cal.get(Calendar.MINUTE));
		dateType.setSecond(cal.get(Calendar.SECOND));
		return dateType;
	}

	private static String getIdType(String value){//证件类型
		if("1".equals(value)){//组织机构代码证
			return "110001";
		}else if("7".equals(value)){//营业执照代码
			return "110002";
		}else{//其它
			return "110009";
		}
	}

	//投保人信息  marshalAppBaseInfo
	private static void marshalAppBaseInfo(LOTEPolicyVo vo, OrderFormVo dto, AppBaseInfo appBaseInfo){
		for(RoleSubjectVo roleSubjectVo : vo.getRoleSubjectList()){
			if(!ConstProp.DIGIT_ONE.equals(roleSubjectVo.getKind())){
				continue;
			}
			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];
				}
			}
			appBaseInfo.setAppname(roleSubjectVo.getName_cn());//公司名称 否
			appBaseInfo.setApptype(getIdType(roleSubjectVo.getId_type()));//证件类型，
			appBaseInfo.setAppid(organizationCode);//证件号码
			appBaseInfo.setAppmrk("0");//投保人性质 TODO 默认法人 0法人；1个人
			appBaseInfo.setBusinessid(1);//批次序列号
			appBaseInfo.setApppost(getZipCode(roleSubjectVo.getReg_city()));
			appBaseInfo.setApprel("601001");//与被保人关系
			String address = RegionUtils.getRegionNameByALLCode(roleSubjectVo.getReg_province(),roleSubjectVo.getReg_city(),roleSubjectVo.getReg_district())+roleSubjectVo.getReg_address();
			appBaseInfo.setAppaddress(address);//通讯地址
			appBaseInfo.setAppphone(roleSubjectVo.getLink_tel());//移动电话
		}
	}

	//被保险人信息  marshalInsuredInfo
	private static void marshalInsuredInfo(LOTEPolicyVo vo, OrderFormVo dto, InsuredInfo insuredInfo){

		for(RoleSubjectVo roleSubjectVo : vo.getRoleSubjectList()){
			if(!ConstProp.DIGIT_TWO.equals(roleSubjectVo.getKind())){
				continue;
			}
			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];
				}
			}
			insuredInfo.setPname(roleSubjectVo.getName_cn());//公司名称 否
			insuredInfo.setPtype(getIdType(roleSubjectVo.getId_type()));//证件类型，
			insuredInfo.setPid(organizationCode);//证件号码
			insuredInfo.setPmrk(ConstProp.DIGIT_ZERO);//被保险人人性质 TODO 默认法人 0法人；1个人
			insuredInfo.setAllinesflag("NV75101");//受益人类型
			insuredInfo.setCzipcde(getZipCode(roleSubjectVo.getReg_city()));//邮编
			insuredInfo.setApprel("601001");//与被保人关系
			String address = RegionUtils.getRegionNameByALLCode(roleSubjectVo.getReg_province(),roleSubjectVo.getReg_city(),roleSubjectVo.getReg_district())+roleSubjectVo.getReg_address();
			insuredInfo.setClntaddr(address);//通讯地址
			insuredInfo.setPtel(roleSubjectVo.getLink_tel());//移动电话
		}
	}

	//标的信息 marshalPropertyInfo
	private static void marshalPropertyInfo(LOTEPolicyVo vo, OrderFormVo dto, PropertyInfo propertyInfo){
		propertyInfo.setSeqno(1);//序号
		propertyInfo.setYafcProText1("589001");//保险价值确定方式
		propertyInfo.setYafcProText2("00");//标的项目类别 00	道路，01	地铁，02	电厂，03	商业楼宇，99	其他
		propertyInfo.setYafcProText3(RegionUtils.getRegionNameByALLCode(vo.getSpecialExhibitionVo().getEx_province(),vo.getSpecialExhibitionVo().getEx_city(),vo.getSpecialExhibitionVo().getEx_county()));//所属省市区
		propertyInfo.setYafcProText4(getZipCode(vo.getSpecialExhibitionVo().getEx_city()));//邮编
		propertyInfo.setYafcProText5(vo.getSpecialExhibitionVo().getEx_address());//展览会地址
		propertyInfo.setYafcProNum1(Double.valueOf(vo.getSpecialExhibitionVo().getEx_acreage()));//实际平米数
	}

	//根据城市代码获取邮编
	public static String getZipCode(String cityCode){
		YB_City yc = YB_City.fromYBCity(cityCode);
		String result = "";
		if(yc != null){
			result = String.valueOf(yc).split("_")[1];
		}
		return result;
	}

	/**
	 * 获得都邦支付相关接口报文解析
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getDBPayResult(String originalXML) {
		String repCode = ConstProp.BLANK_CHAR;
		String prm = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);
			rootElement = requestDocument.getRootElement();
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){
				Element node = (Element) i.next();
				if(!"BODY".equals(node.getName())){
					continue;
				}
				for(Iterator n = node.elementIterator(); n.hasNext();){
					Element node_n = (Element) n.next();
					if(!"ORDERINFO".equals(node_n.getName())){
						continue;
					}
					for(Iterator r = node_n.elementIterator(); r.hasNext();){
						Element node_r = (Element) r.next();
						if("ORDERNO".equals(node_r.getName())){
							repCode = node_r.getText();
						}
						if("SUMPAYFEE".equals(node_r.getName())){
							prm = node_r.getText();
						}
					}
				}
			}
		}catch (Exception e){
			logger.info("isDBPayResult:"+e.getMessage());
		}
		return repCode+ConstProp.POUND_SIGN+prm;
	}

	/**
	 *	接口返回字符串解析
	 * @return
	 */
	public String returnAnalysisXML(String xml, String  transType){
		String msgCode = getDBMsgCode(xml);
		if( !ConstProp.DIGIT_ZERO.equals(msgCode)){
			if(StringUtils.isNotEmpty(xml)){
				return "300#（APP-DB-"+msgCode+"）"+getDBFailMsg(xml);
			}else{
				return "300#（APP-DB-001）未获取到返回数据！";
			}
		}
		if(transType.equals(ConstProp.DIGIT_ONE)) {
			//核保，承保统一一个接口
			//200#投保单号#保单号
			return getDBResult(xml);
		}else if(transType.equals(ConstProp.DIGIT_THREE)) {
			//获取电子保单文件流   返回值
			String filePath = uploadFile("文件字符流","/build-db/");
			if(StringUtils.isNotEmpty(filePath)){
				return "200#"+filePath;
			}else{
				return "300#（APP-DB-002）电子保单打印文件流解析失败！";
			}
		}
		return "300#（APP-PAC-001.1）数据处理失败！";
	}

	/**
	 * 获得都邦返回报文是否成功
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getDBMsgCode(String originalXML) {
		String repCode = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);
			rootElement = requestDocument.getRootElement();
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){
				Element node = (Element) i.next();
				if(!"body".equals(node.getName())){
					continue;
				}
				for(Iterator n = node.elementIterator(); n.hasNext();){
					Element node_n = (Element) n.next();
					if("resultcode".equals(node_n.getName())){
						repCode = node_n.getText();
						System.out.println(repCode);
						break;
					}
				}
			}
		}catch (Exception e){
			logger.info("isDBSuccess:"+e.getMessage());
		}
		return repCode;
	}

	/**
	 * 获得都邦返回核保成功的报文信息，200#投保单号#保单号
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getDBResult(String originalXML) {
		String repCode = "200#";
		String policyno = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);
			rootElement = requestDocument.getRootElement();
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){
				Element node = (Element) i.next();
				if(!"body".equals(node.getName())){
					continue;
				}
				for(Iterator n = node.elementIterator(); n.hasNext();){
					Element node_n = (Element) n.next();
					if("policyInfo".equals(node_n.getName())){
						for(Iterator r = node_n.elementIterator(); r.hasNext();) {
							Element node_r = (Element) r.next();
							if ("serialNumber".equals(node_r.getName())) {
								repCode = repCode + node_r.getText() + ConstProp.POUND_SIGN;
								break;
							}
						}
					}
					if ("policyno".equals(node_n.getName())) {
						policyno = node_n.getText();
					}
				}
			}
		}catch (Exception e){
			logger.info("isDBSuccess:"+e.getMessage());
		}
		return repCode+policyno;
	}

	/**
	 * 获得都邦返回失败的消息
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getDBFailMsg(String originalXML) {
		String repCode = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);
			rootElement = requestDocument.getRootElement();
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){
				Element node = (Element) i.next();
				if(!"body".equals(node.getName())){
					continue;
				}
				for(Iterator n = node.elementIterator(); n.hasNext();){
					Element node_n = (Element) n.next();
					if("errordesc".equals(node_n.getName())){
						repCode = node_n.getText();
						System.out.println(repCode);
						break;
					}
				}
			}
		}catch (Exception e){
			logger.info("getDBFailMsg:"+e.getMessage());
		}
		return repCode;
	}




	/**
	 * 文件上传并返回下载地址
	 * @param fileStr 字符串文件流
	 * @param savePath 文件要保存的文件夹地址（/zzx-pac/）
	 * @return /getResource?path=/policy/1231231.jpg
	 */
	public static String uploadFile(String fileStr, String savePath){
		String result = "";
		if (StringUtils.isNotEmpty(fileStr)) {
			try {
				byte[] bytes = BASE64Util.decryptBASE64Byte(fileStr);
				String files = DateUtil.generatorRadomNumber() + ".pdf";
				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;
	}









	public static void main(String[] args){

//		doResultCheDan();
		System.out.println(getZipCode("120100"));
	}

	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")){
				//返回成功
				String  bodyStr= map.get("body").toString();
				bodyStr=bodyStr.replaceFirst("\"","");
				bodyStr=bodyStr.substring(ConstProp.INT_NUMBER_ZERO,bodyStr.lastIndexOf('"'));
				bodyStr = bodyStr.replace("\\", ConstProp.BLANK_CHAR);
				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);

				}
			}else{

				logger.info("300#撤单失败");
			}
//            logger.info(header.toString());
		}catch(Exception e){

			e.printStackTrace();
		}
 	}

}
