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

import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.third.gzzrx.changan.ca_enum.CraftType;
import com.bcxin.ins.third.gzzrx.qianhai.util.Encrypt;
import com.bcxin.ins.util.*;
import com.bcxin.ins.vo.*;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.xiaoleilu.hutool.http.HttpUtil;
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.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

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

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

	/**
	 * 核保数据组装
	 * @param vo 投保详细信息
	 * @param dto 订单基本信息
	 * @param transType 接口类型
	 * @param iprVo 保全申请单
	 * @return
	 */
	public static String marshal(SpecialHirelingVo vo, OrderFormVo dto, String transType, InsPreservationRecordVo iprVo){
		String result = ConstProp.BLANK_CHAR;
		Document requestDocument = DocumentHelper.createDocument();
		requestDocument.setXMLEncoding("UTF-8");//设置该XML文件的Encoding = "GBK"
		Element Packet = requestDocument.addElement("Packet");
		try {
			//前海投保人名称括号大写转小写
//			dto.setApplicant_name(dto.getApplicant_name().replace("（","(").replace("）",")"));
			if(TransTypeEnum.HB.getValue().equals(transType)){//核保
				RoleSubjectVo roleSubjectVo = vo.getRoleSubjectList().get(0);
//				roleSubjectVo.setName_cn(roleSubjectVo.getName_cn().replace("（","(").replace("）",")"));
				//头
				Element Head = Packet.addElement("Head");
				head(Head, dto,"900101", roleSubjectVo);
				Element Body = Packet.addElement("Body");
				//内容列
				Element Base = Body.addElement("Base");
				policyInfo(Base, vo, dto);
				//投保人
				Element Applicant = Body.addElement("Applicant");
				applicant(Applicant, roleSubjectVo, vo);
				//雇员
				Element TgtObjList = Body.addElement("TgtObjList");
				employees(TgtObjList, vo.getHirelingVoList(), dto,roleSubjectVo.getReg_province());
				//标的信息
				Element Tgt = Body.addElement("Tgt");
				Tgt.addElement("CTgtTxtFld1").setText("002");//行业性质
				Tgt.addElement("CTgtTxtFld6").setText(vo.getHirelingVoList().size()+"");//雇员总人数
				Tgt.addElement("CTgtTxtFld5").setText("637001");//记名投保
				Tgt.addElement("CTgtTxtFld8").setText("中国境内（不含港澳台）");//承保区域范围:详见特别约定
				Tgt.addElement("CTgtTxtFld14").setText("0");//是否涉及高风险作业
				result = requestDocument.asXML();
			}else if(TransTypeEnum.PD.getValue().equals(transType)){//批单
				//头
				Element Head = Packet.addElement("Head");
				head_pd(Head, dto,"900103");
				Element Body = Packet.addElement("Body");
				//内容列
				Element Base = Body.addElement("Base");
				policyInfo_pd(Base, vo, dto, iprVo);
				//雇员信息批改
				Element TgtObjList_element = Body.addElement("TgtObjList");
				emps_pd(TgtObjList_element, iprVo);
				Element acctinfo_element = Body.addElement("acctinfo");
				acctinfo_pd(acctinfo_element, vo.getRoleSubjectList().get(0));
				result = requestDocument.asXML();
			}else if(TransTypeEnum.DZFP.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];
					}
				}
				//头
				Element Head = Packet.addElement("Head");
				head_pd(Head, dto,"160003");
				Element Body = Packet.addElement("Body");
				//保单号
				Body.addElement("PlyNo").setText(dto.getExternal_reference());
				//纳税人名称
				Body.addElement("TaxpayerName").setText(dto.getApplicant_name());
				//纳税人识别号
				Body.addElement("TaxId").setText(organizationCode);
				String taxpayerType = "0";
				if(vo.getMailPolicyVo() != null&&ConstProp.DIGIT_ONE.equals(vo.getMailPolicyVo().getNeed_receipt())){
					taxpayerType = ConstProp.DIGIT_ZERO.equals(vo.getMailPolicyVo().getInvoice_type()) ? "0" : "1";
				}
				//客户纳税资质0-一般纳税人 1-非一般纳税人
				Body.addElement("TaxpayerType").setText(taxpayerType);
				result = requestDocument.asXML();
			}else if(TransTypeEnum.ZXPG.getValue().equals(transType)){//最新批单查询
				//头
				Element Head = Packet.addElement("Head");
				head_pd(Head, dto,"900104");
				Element Body = Packet.addElement("Body");
				//内容列
				Element Base = Body.addElement("Base");
				if(StringUtils.isEmpty(iprVo.getRevise_serial_num_ins())){
					Base.addElement("CPlyType").setText("1");//单号类型 1:保单号2:批单号
					Base.addElement("CPlyNo").setText(dto.getExternal_reference());//请求单号
				}else{
					Base.addElement("CPlyType").setText("2");//单号类型 1:保单号2:批单号
					Base.addElement("CPlyNo").setText(iprVo.getRevise_serial_num_ins());//请求单号
				}
				result = requestDocument.asXML();
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}

	//头信息
	private static void head(Element underwrite, OrderFormVo dto,String type, RoleSubjectVo roleSubjectVo) {
		//签名KEY(测试),UUID,CRequestType,CBusiChnl,TAcctTm,CProdNo,TInsrncBgnTm,TInsrncEndTm,CCertfCde(投保人)
		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 uuid = UUID.randomUUID().toString();
		String time = DateUtil.getCurrentDateTime();
		String str = GlobalResources.map.get("QH_GZ_INS_KEY")+uuid+type+"BLB"+time+"040002"+dto.getInception_date()+ConstProp.DAY_00+dto.getPlanned_end_date()+ConstProp.DAY_23+organizationCode;
		System.out.println("明文："+str);
		String priStr = Encrypt.md5(str);
		System.out.println("密文："+priStr);
		//校验码(md5)
		underwrite.addElement("CheckCode").setText(priStr);
		//唯一码
		underwrite.addElement("UUID").setText(uuid);
		//请求类型
		underwrite.addElement("CRequestType").setText(type);
		//业务渠道
		underwrite.addElement("CBusiChnl").setText("BLB");
		//交易时间
		underwrite.addElement("TAcctTm").setText(time);

	}

	/*
	 * 产品方案 基础版
	 */
	private static String getQuoteMark1(String product_code){
		if(StringUtils.isEmpty(product_code) ? false : "GZZRX-QH-1".equals(product_code)){
			return "A04000201";
		}else if(StringUtils.isEmpty(product_code) ? false : "GZZRX-QH-2".equals(product_code)){
			return "A04000202";
		}else if(StringUtils.isEmpty(product_code) ? false : "GZZRX-QH-3".equals(product_code)){
			return "A04000203";
		}else if(StringUtils.isEmpty(product_code) ? false : "GZZRX-QH-4".equals(product_code)){
			return "A04000204";
		}else if(StringUtils.isEmpty(product_code) ? false : "GZZRX-QH-5".equals(product_code)){
			return "A04000205";
		}else if(StringUtils.isEmpty(product_code) ? false : "GZZRX-QH-6".equals(product_code)){
			return "A04000206";
		}else if(StringUtils.isEmpty(product_code) ? false : "GZZRX-QH-7".equals(product_code)){
			return "A04000207";
		}else if(StringUtils.isEmpty(product_code) ? false : "GZZRX-QH-8".equals(product_code)){
			return "A04000208";
		}else{
			return "";
		}
	}

	/*
	 * 产品方案 升级版
	 */
	private static String getQuoteMark2(String product_code){
		if(StringUtils.isEmpty(product_code) ? false : "GZZRX-QH-1".equals(product_code)){
			return "B04000201";
		}else if(StringUtils.isEmpty(product_code) ? false : "GZZRX-QH-2".equals(product_code)){
			return "B04000202";
		}else if(StringUtils.isEmpty(product_code) ? false : "GZZRX-QH-3".equals(product_code)){
			return "B04000203";
		}else if(StringUtils.isEmpty(product_code) ? false : "GZZRX-QH-4".equals(product_code)){
			return "B04000204";
		}else if(StringUtils.isEmpty(product_code) ? false : "GZZRX-QH-5".equals(product_code)){
			return "B04000205";
		}else if(StringUtils.isEmpty(product_code) ? false : "GZZRX-QH-6".equals(product_code)){
			return "B04000206";
		}else if(StringUtils.isEmpty(product_code) ? false : "GZZRX-QH-7".equals(product_code)){
			return "B04000207";
		}else if(StringUtils.isEmpty(product_code) ? false : "GZZRX-QH-8".equals(product_code)){
			return "B04000208";
		}else{
			return "";
		}
	}

	//保单主信息 policyInfo
	private static void policyInfo(Element policyInfo, SpecialHirelingVo vo, OrderFormVo dto){
		policyInfo.addElement("CProdNo").setText("040002");//产品号
		policyInfo.addElement("CProdPlan").setText("1".equals(vo.getIs_contain_repo())?
				getQuoteMark2(dto.getProduct_code()):getQuoteMark1(dto.getProduct_code()));//产品方案号
		policyInfo.addElement("CPlcyType").setText("2".equals(vo.getInception_type())?"1":"2");//投保方式：1：月缴 2：年缴 todo 需要设计 年缴 月缴
		policyInfo.addElement("TAppTm").setText(dto.getStart_time());//投保日期
		policyInfo.addElement("TInsrncBgnTm").setText(dto.getInception_date()+ConstProp.DAY_00);//起保日期
		policyInfo.addElement("TInsrncEndTm").setText(dto.getPlanned_end_date()+ConstProp.DAY_23);//终保日期
		int syDay = DateUtil.getDistDates(DateUtil.convertStringToDate(dto.getInception_date()),DateUtil.convertStringToDate(dto.getPlanned_end_date()))+1;
		policyInfo.addElement("CTmSysCde").setText(syDay+"");//保险期限(天)
		policyInfo.addElement("NAmt").setText(dto.getInsured_amount());//总保额
		policyInfo.addElement("NPrm").setText(dto.getGross_premium());//总保费
		policyInfo.addElement("OrderNo").setText(dto.getTrade_serial_number());//订单号
	}


	//投保人信息  applicant
	private static void applicant(Element holder, RoleSubjectVo roleSubjectVo, SpecialHirelingVo vo){
		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];
			}
		}
		holder.addElement("CAppNme").setText(roleSubjectVo.getName_cn());//客户名称
		holder.addElement("CClntMrk").setText("0");//客户性质 1为自然人，0为非自然人
		holder.addElement("CCertfCls").setText(changeCTypeCom(roleSubjectVo.getId_type()));//证件类型，
		holder.addElement("CCertfCde").setText(organizationCode);//证件号码
		holder.addElement("CCreditCde").setText(organizationCode);//纳税人识别号
		holder.addElement("CEmail").setText(roleSubjectVo.getLink_email());//邮箱
		holder.addElement("CMobile").setText(roleSubjectVo.getLink_tel());//手机
		String address = RegionUtils.getRegionNameByALLCode(roleSubjectVo.getReg_province(),roleSubjectVo.getReg_city(),roleSubjectVo.getReg_district())+roleSubjectVo.getReg_address();
		holder.addElement("CClntAddr").setText(address);//地址
		String InvoiceType = "";
		if(!ConstProp.DIGIT_ZERO.equals(vo.getMailPolicyVo().getNeed_receipt())||!ConstProp.DIGIT_ZERO.equals(vo.getMailPolicyVo().getIs_send_einvoice())){
			holder.addElement("CImediumTyp").setText(ConstProp.DIGIT_ZERO.equals(vo.getMailPolicyVo().getIs_send_einvoice())?"1":"2");//发票介质 1:纸质发票，2:电子发票
			holder.addElement("CTaxpayerTyp").setText("0");//纳税人资质 0:一般纳税人，1:小规模纳税人，2:非纳税人
			InvoiceType = "A";
			//不要电子票
//			if(!ConstProp.DIGIT_ONE.equals(vo.getMailPolicyVo().getIs_send_einvoice())){
//				InvoiceType = ConstProp.DIGIT_ZERO.equals(vo.getMailPolicyVo().getInvoice_type()) ? InvoiceType : "B";
//			}
			InvoiceType = ConstProp.DIGIT_ZERO.equals(vo.getMailPolicyVo().getInvoice_type()) ? InvoiceType : "B";
			if("B".equals(InvoiceType)){
				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();
				holder.addElement("CVatBanknme").setText(Bank);//开户行
				holder.addElement("CVatAccount").setText(Account);//银行账号
			}
//			holder.addElement("CImediumTyp").setText(ConstProp.DIGIT_ZERO.equals(vo.getMailPolicyVo().getIs_send_einvoice())?"1":"2");//发票介质 1:纸质发票，2:电子发票
//			holder.addElement("CImediumTyp").setText("B".equals(InvoiceType)?"081":"082");//发票介质 081- 数字化电子专票 082-数字化电子普票
//			holder.addElement("CTaxpayerTyp").setText("0");//纳税人资质 0:一般纳税人，1:小规模纳税人，2:非纳税人
			holder.addElement("CInvoiceTyp").setText(InvoiceType);//发票类型 A:增值税普通发票，B:增值税专用发票
			holder.addElement("CBillTel").setText(vo.getMailPolicyVo().getTaker_mobile());//开票电话
			String TaxRegistAddress = StringUtils.isEmpty(vo.getMailPolicyVo().getRegister_address_invoice())?"":vo.getMailPolicyVo().getRegister_address_invoice();
			holder.addElement("CBillAddr").setText(TaxRegistAddress);//税务登记地址
		}
	}

	public static String getByCareer(String career){
		if("1".equals(career)){
			return "行政人员";
		}else if("2".equals(career)){
			return "保安";
		}else if("4".equals(career)){
			return "清洁工";
		}
		return "";
	}

	//雇员信息列信息  employees
	private static void employees(Element employees, List<HirelingVo> hvoList, OrderFormVo dto,String province){
		int count = 1;
		for(HirelingVo vo : hvoList){
			Element employee = employees.addElement("TgtObj");
			employee.addElement("NSeqNo").setText(String.valueOf(count));//序号
			employee.addElement("CTgtObjTxtFld3").setText("NV040214New");//工种类型
			employee.addElement("CTgtObjTxtFld7").setText(getByCareer(vo.getCareer()));//工种名称
			employee.addElement("CTgtObjTxtFld1").setText(vo.getName());//雇员姓名
			employee.addElement("CTgtObjTxtFld8").setText(changeCTypePer(vo.getId_type()));//证件类型，
			employee.addElement("CTgtObjTxtFld2").setText(vo.getId_card());//证件号码
			String proName = RegionUtils.getRegionNameByCode(province);
			String CTgtObjTxtFld5 = proName.substring(0,proName.length()-1);
			if(proName.startsWith("广西")){
				CTgtObjTxtFld5 = "广西";
			}else if(proName.startsWith("宁夏")){
				CTgtObjTxtFld5 = "宁夏";
			}
			employee.addElement("CTgtObjTxtFld5").setText(CTgtObjTxtFld5);//证件号码
			employee.addElement("sex").setText(vo.getSex());//性别
			int age;
			try {
				age = DateUtil.getAge(vo.getBirth_date());
			} catch (Exception e) {
				age = 0;
			}
			employee.addElement("NTgtObjNumFld1").setText(String.valueOf(age));//年龄
			employee.addElement("NTgtObjNumFld2").setText(dto.getPremium());//每人保费
			count++;
		}
	}

	//企业证件类型编码转换
	private static String changeCTypeCom(String c_t){
		if("1".equals(c_t)){//组织机构代码
			return "1";
		}else if("2".equals(c_t)){//统一社会代码
			return "3";
		}else if("6".equals(c_t)){//税务登记证件号
			return "2";
		}else if("7".equals(c_t)){//工商登记号
			return "4";
		}else{//其它
			return "9";
		}
	}

	//个人证件类型编码转换
	private static String changeCTypePer(String c_t){
		if("0".equals(c_t)){//身份证
			return "111";
		}else if("3".equals(c_t)){//护照
			return "114";
		}else if("4".equals(c_t)){//台胞证
			return "119";
		}else{//其它
			return "999";
		}
	}


	//头信息
	private static void head_pd(Element underwrite, OrderFormVo dto,String type) {
		//签名KEY(测试),UUID,CRequestType,CBusiChnl,TAcctTm,CPlyNo
		String uuid = UUID.randomUUID().toString();
		String time = DateUtil.getCurrentDateTime();
		String str = GlobalResources.map.get("QH_GZ_INS_KEY")+uuid+type+"BLB"+time+dto.getExternal_reference();
		System.out.println("明文："+str);
		String priStr = Encrypt.md5(str);
		System.out.println("密文："+priStr);
		//校验码(md5)
		underwrite.addElement("CheckCode").setText(priStr);
		//唯一码
		underwrite.addElement("UUID").setText(uuid);
		//请求类型
		underwrite.addElement("CRequestType").setText(type);
		//业务渠道
		underwrite.addElement("CBusiChnl").setText("BLB");
		//交易时间
		underwrite.addElement("TAcctTm").setText(time);

	}

	//基本信息Base
	private static void policyInfo_pd(Element policyInfo, SpecialHirelingVo vo, OrderFormVo dto, InsPreservationRecordVo iprVo){
		String type = ConstProp.DIGIT_THREE.equals(iprVo.getRevise_type())?"2":ConstProp.DIGIT_TWO.equals(iprVo.getRevise_type())?"3":"1";
		policyInfo.addElement("CProdPlan").setText("1".equals(vo.getIs_contain_repo())?
				getQuoteMark2(dto.getProduct_code()):getQuoteMark1(dto.getProduct_code()));//产品方案号
		policyInfo.addElement("EdrType").setText(type);//操作类型 1-纯新增 2-修改 3-纯删除
		policyInfo.addElement("TEdrAppTm").setText(iprVo.getStart_time());//批改申请日期
		policyInfo.addElement("TEdrBgnTm").setText(iprVo.getInception_date());//批改生效日期
		policyInfo.addElement("CPlyNo").setText(dto.getExternal_reference());//保单号
		policyInfo.addElement("CAppNme").setText(dto.getApplicant_name());//投保人姓名
		policyInfo.addElement("CProdNo").setText("040002");//产品编码
	}

	private static void emps_pd(Element underwrite, InsPreservationRecordVo iprVo){
		//批改类型
		String type = ConstProp.DIGIT_THREE.equals(iprVo.getRevise_type())?"2":ConstProp.DIGIT_TWO.equals(iprVo.getRevise_type())?"3":"1";
		String pn = String.valueOf(iprVo.getInsPreservationDetailVoList().size());
		//每人保费
		String pp = BigDecimal.valueOf(Double.parseDouble(iprVo.getTotal_premium())).divide(BigDecimal.valueOf(iprVo.getInsPreservationDetailVoList().size()),2,BigDecimal.ROUND_HALF_EVEN).toString().replace("-","");
		//编号
		int count = 1;
		for(InsPreservationDetailVo ipdVo : iprVo.getInsPreservationDetailVoList()){
			if(ConstProp.DIGIT_THREE.equals(iprVo.getRevise_type())){
				setEmp_pd( underwrite, ipdVo, "1", String.valueOf(count),pp);
				count ++;
				setEmp_pd( underwrite, ipdVo.getBusiness_vo(), "3", String.valueOf(count),pp);
			}else{
				setEmp_pd( underwrite, ipdVo, type, String.valueOf(count),pp);
			}
			count ++;
		}
	}

	private static void setEmp_pd(Element underwrite, InsPreservationDetailVo ipdVo, String tp, String sn, String pp){
		Element TgtObj_element = underwrite.addElement("TgtObj");
		//序号
		TgtObj_element.addElement("NSeqNo").setText(sn);
		//雇员姓名
		TgtObj_element.addElement("CTgtObjTxtFld1").setText(ipdVo.getName());
		//证件类型
		TgtObj_element.addElement("CTgtObjTxtFld8").setText(changeCTypePer(ipdVo.getId_type()));
		//证件号码
		TgtObj_element.addElement("CTgtObjTxtFld2").setText(ipdVo.getId_card());
		int age = 0;
		try {
			age = DateUtil.getAge(ipdVo.getBirthday());
		} catch (Exception e) {
			e.printStackTrace();
		}
		TgtObj_element.addElement("NTgtObjNumFld1").setText(String.valueOf(age));//年龄
		//性别
		TgtObj_element.addElement("sex").setText(ipdVo.getSex());
		//工种类型
		TgtObj_element.addElement("CTgtObjTxtFld3").setText("NV040214New");
		//工种名称
		TgtObj_element.addElement("CTgtObjTxtFld7").setText(getByCareer(ipdVo.getCareer()));
		//每人保费
		TgtObj_element.addElement("NTgtObjNumFld2").setText(pp);
		//操作类型 1-纯新增 2-修改 3-纯删除
		TgtObj_element.addElement("CStatusType").setText(tp);
	}

	private static void acctinfo_pd(Element underwrite, RoleSubjectVo roleSubjectVo){
		//开户行省
		String pro = RegionUtils.getRegionNameByCode(roleSubjectVo.getBank_province());
		underwrite.addElement("bankPro").setText(roleSubjectVo.getBank_province());
		underwrite.addElement("bankProName").setText(covertPro(pro));
		//对公对私
		underwrite.addElement("pubPri").setText(roleSubjectVo.getBank_pub_pri());
		//开户行市
		underwrite.addElement("bankArea").setText(roleSubjectVo.getBank_city());
		underwrite.addElement("bankAreaName").setText(covertArea(pro,RegionUtils.getRegionNameByCode(roleSubjectVo.getBank_city())));
		//收款人账户名
		underwrite.addElement("acctNme").setText(roleSubjectVo.getAccount_name());
		//开户行地址
		underwrite.addElement("bankAddr").setText(roleSubjectVo.getBank_name());
		//收款人账号
		underwrite.addElement("acctNo").setText(roleSubjectVo.getBank_account());
		//收款银行大类
		underwrite.addElement("bankRelTyp").setText(roleSubjectVo.getBank_type());
		//银行网点
		underwrite.addElement("bankName").setText(roleSubjectVo.getBank_addr());
	}

	private static String covertPro(String area){
		if(area.endsWith("市")||area.endsWith("省")){
			return area.substring(0,area.length()-1);
		}if(area.endsWith("自治区")){
			return area.replace("壮族自治区","").replace("回族自治区","").replace("维吾尔自治区","").replace("自治区","");
		}else{
			return area;
		}
	}
	private static String covertArea(String pro,String area){
		if(area.contains("市辖区")){
			return pro;
		}if(area.contains("自治州")){
			if(area.contains("克孜勒苏柯尔克孜")){
				return area.replace("自治州","");
			}
			if(area.contains("昌吉回族自治州")){
				return area;
			}
			return area.replace("朝鲜族自治州","")
					.replace("土家族苗族自治州","")
					.replace("藏族羌族自治州","")
					.replace("藏族自治州","")
					.replace("彝族自治州","")
					.replace("布依族苗族自治州","")
					.replace("苗族侗族自治州","")
					.replace("哈尼族彝族自治州","")
					.replace("壮族苗族自治州","")
					.replace("傣族自治州","")
					.replace("白族自治州","")
					.replace("傣族景颇族自治州","")
					.replace("傈僳族自治州","")
					.replace("藏族自治州","")
					.replace("回族自治州","")
					.replace("蒙古族藏族自治州","");
		}else{
			return area;
		}
	}

	/**
	 * 获得核保接口返回报文解析
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getQHHBResult(String originalXML) {
		String code = ConstProp.BLANK_CHAR;
		String msg = ConstProp.BLANK_CHAR;
		String pno = ConstProp.BLANK_CHAR;
		String payUrl = ConstProp.BLANK_CHAR;
		try {
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){//遍历Packet 直到没有节点时结束
				Element node = (Element) i.next();
				if("Head".equals(node.getName())){
					for(Iterator r = node.elementIterator(); r.hasNext();){
						Element node_r = (Element) r.next();
						if("ResultCode".equals(node_r.getName())){
							code = node_r.getText();
						}
						if("ResultMessage".equals(node_r.getName())){
							msg = node_r.getText();
						}
					}
					if(!"0000".equals(code)){
						return "300#"+msg;
					}
				}
				if("Body".equals(node.getName())){
					for(Iterator r = node.elementIterator(); r.hasNext();){
						Element node_r = (Element) r.next();
						if("Base".equals(node_r.getName())){
							for(Iterator t = node_r.elementIterator(); t.hasNext();){
								Element node_t = (Element) t.next();
								if("AppNo".equals(node_t.getName())){
									pno = node_t.getText();
								}
								if("PayUrl".equals(node_t.getName())){
									payUrl = node_t.getText();
								}
							}
							if(StringUtils.isEmpty(pno)||StringUtils.isEmpty(payUrl)){
								return "300#解析数据丢失";
							}else{
								return "200#"+pno+ConstProp.POUND_SIGN+payUrl;
							}
						}
					}
				}
			}
		}catch (Exception e){
			logger.info("getRBHBResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * 获得批改接口返回报文解析
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getQHPDResult(String originalXML) {
		String code = ConstProp.BLANK_CHAR;
		String msg = ConstProp.BLANK_CHAR;
		String pno = ConstProp.BLANK_CHAR;
		String endorseNo = ConstProp.BLANK_CHAR;
		String pdUrl = ConstProp.BLANK_CHAR;
		try {
			if(StringUtils.isEmpty(originalXML)){
				return "300#系统响应超时，请重试";
			}
			originalXML = originalXML.replace("&","&amp;");
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){//遍历Packet 直到没有节点时结束
				Element node = (Element) i.next();
				if("Head".equals(node.getName())){
					for(Iterator r = node.elementIterator(); r.hasNext();){
						Element node_r = (Element) r.next();
						if("ResultCode".equals(node_r.getName())){
							code = node_r.getText();
						}
						if("ResultMessage".equals(node_r.getName())){
							msg = node_r.getText();
						}
					}
					if(!"0000".equals(code)){
						return "300#"+msg;
					}
				}
				if("Body".equals(node.getName())){
					for(Iterator t = node.elementIterator(); t.hasNext();){
						Element node_t = (Element) t.next();
						if("CPlyNo".equals(node_t.getName())){
							pno = node_t.getText();
						}
						if("CEdrNo".equals(node_t.getName())){
							endorseNo = node_t.getText();
						}
						if("CEdrNoUrl".equals(node_t.getName())){
							pdUrl = node_t.getText();
						}
					}
					if(StringUtils.isEmpty(endorseNo)||StringUtils.isEmpty(pdUrl)){
						return "300#解析数据丢失";
					}else{
						pdUrl = pdUrl.replace("&amp;","&");
//						pdUrl = unloading_bd(pdUrl);
						return "200#"+pno+ConstProp.POUND_SIGN+endorseNo+ConstProp.POUND_SIGN+pdUrl;
					}
				}
			}
		}catch (Exception e){
			logger.info("getQHPDResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * 获得最新批改接口返回报文解析
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getZXPGResult(String originalXML) {
		String code = ConstProp.BLANK_CHAR;
		String msg = ConstProp.BLANK_CHAR;
		String endorseNo = ConstProp.BLANK_CHAR;
		String pdUrl = ConstProp.BLANK_CHAR;
		String amo = ConstProp.BLANK_CHAR;
		String idcards = ConstProp.BLANK_CHAR;
		try {
			if(StringUtils.isEmpty(originalXML)){
				return "300#系统响应超时，请重试";
			}
			originalXML = originalXML.replace("&","&amp;");
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){//遍历Packet 直到没有节点时结束
				Element node = (Element) i.next();
				if("Head".equals(node.getName())){
					for(Iterator r = node.elementIterator(); r.hasNext();){
						Element node_r = (Element) r.next();
						if("ResultCode".equals(node_r.getName())){
							code = node_r.getText();
						}
						if("ResultMessage".equals(node_r.getName())){
							msg = node_r.getText();
						}
					}
					if(!"0000".equals(code)){
						return "300#"+msg;
					}
				}
				if("Body".equals(node.getName())){
					for(Iterator t = node.elementIterator(); t.hasNext();){
						Element node_t = (Element) t.next();
						if("CEdrMations".equals(node_t.getName())){
							for(Iterator q = node_t.elementIterator(); q.hasNext();){
								Element node_r = (Element) q.next();
								if("CEdrMation".equals(node_r.getName())){//CLatestMrk
									for(Iterator p = node_r.elementIterator(); p.hasNext();){
										Element node_p = (Element) p.next();
										if("CEdrNo".equals(node_p.getName())){
											endorseNo = node_p.getText();
										}
										if("CPrmVar".equals(node_p.getName())){
											amo = node_p.getText();
										}
										if("CEdrUrl".equals(node_p.getName())){
											pdUrl = node_p.getText();
										}
										if("InForMations".equals(node_p.getName())){
											List<String> list = Lists.newArrayList();
											for(Iterator k = node_p.elementIterator(); k.hasNext();){
												Element node_k = (Element) k.next();
												if("InForMation".equals(node_k.getName())){
													for(Iterator w = node_k.elementIterator(); w.hasNext();){
														Element node_o = (Element) w.next();
														if("CCertfCde".equals(node_o.getName())){
															list.add(node_o.getText());
														}
													}
												}
											}
											idcards = list.toString();
										}
									}
								}
							}
						}
					}
					if(StringUtils.isEmpty(endorseNo)||StringUtils.isEmpty(pdUrl)||StringUtils.isEmpty(idcards)||idcards.length()<3){
						return "300#解析数据丢失";
					}else{
						pdUrl = pdUrl.replace("&amp;","&");
//						pdUrl = unloading_bd(pdUrl);
						//批单号#保费#电子批单#投保人员身份证数组
						return "200#"+endorseNo+ConstProp.POUND_SIGN+amo+ConstProp.POUND_SIGN+pdUrl+ConstProp.POUND_SIGN+idcards;
					}
				}
			}
		}catch (Exception e){
			logger.info("getZXPGResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * 获得电子发票接口返回报文解析
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getQHDZFPResult(String originalXML) {
		String code = ConstProp.BLANK_CHAR;
		String msg = ConstProp.BLANK_CHAR;
		String pno = ConstProp.BLANK_CHAR;
		String fpCode = ConstProp.BLANK_CHAR;
		String fpNum = ConstProp.BLANK_CHAR;
		String fpUrl = ConstProp.BLANK_CHAR;
		try {
			originalXML = originalXML.replace("&","&amp;");
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){//遍历Packet 直到没有节点时结束
				Element node = (Element) i.next();
				if("Head".equals(node.getName())){
					for(Iterator r = node.elementIterator(); r.hasNext();){
						Element node_r = (Element) r.next();
						if("ResultCode".equals(node_r.getName())){
							code = node_r.getText();
						}
						if("ResultMessage".equals(node_r.getName())){
							msg = node_r.getText();
						}
					}
					if(!"0000".equals(code)){
						return "300#"+msg;
					}
				}
				if("Body".equals(node.getName())){
					for(Iterator t = node.elementIterator(); t.hasNext();){
						Element node_t = (Element) t.next();
						if("PlyNo".equals(node_t.getName())){
							pno = node_t.getText();
						}
						if("InvCode".equals(node_t.getName())){
							fpCode = node_t.getText();
						}
						if("InvNum".equals(node_t.getName())){
							fpNum = node_t.getText();
						}
						if("InvUrl".equals(node_t.getName())){
							fpUrl = node_t.getText();
						}
					}
					if(StringUtils.isEmpty(fpCode)||StringUtils.isEmpty(fpUrl)){
						return "300#解析数据丢失";
					}else{
						fpUrl = fpUrl.replace("&amp;","&");
//						fpUrl = unloading_bd(fpUrl);
						return "200#"+pno+ConstProp.POUND_SIGN+fpUrl;
					}
				}
			}
		}catch (Exception e){
			logger.info("getQHDZFPResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 * <b> 获取批单号 </b>
	 * @param pdsqh 批单申请号
	 * @author ZXF
	 * @create 2019/12/20 0020 15:05
	 * @version
	 * @注意事项 </b>
	 */
	public static String getPdh(String pdsqh){
		return HttpUtil.get(GlobalResources.map.get("RB_GZ_PDH_URL")+"?applyno="+pdsqh);
	}

	/**
	 * 获得人保支付信息回调报文解析
	 * @param originalXML
	 * @return
	 * @throws DocumentException
	 */
	private String getQHHDCBResult(String originalXML) {
		String code = ConstProp.BLANK_CHAR;
		String msg = ConstProp.BLANK_CHAR;
		String proposalNo = ConstProp.BLANK_CHAR;
		String policyNo = ConstProp.BLANK_CHAR;
		String policyDownUrl = ConstProp.BLANK_CHAR;
		try {
			originalXML = originalXML.replace("&","&amp;");
			requestDocument = DocumentHelper.parseText(originalXML);//解析XML文件
			rootElement = requestDocument.getRootElement();//获取节点
			for(Iterator i = rootElement.elementIterator(); i.hasNext();){//遍历Packet 直到没有节点时结束
				Element node = (Element) i.next();
				if("Body".equals(node.getName())){
					for(Iterator r = node.elementIterator(); r.hasNext();){
						Element node_r = (Element) r.next();
						if("Base".equals(node_r.getName())){
							for(Iterator t = node_r.elementIterator(); t.hasNext();){
								Element node_t = (Element) t.next();
								if("ResultCode".equals(node_t.getName())){
									code = node_t.getText();
								}
								if("ResultMsg".equals(node_t.getName())){
									msg = node_t.getText();
								}
								if("AppNo".equals(node_t.getName())){
									proposalNo = node_t.getText();
								}
								if("PlyNo".equals(node_t.getName())){
									policyNo = node_t.getText();
								}
								if("PlyDocUrl".equals(node_t.getName())){
									policyDownUrl = node_t.getText();
								}
							}
							if(!"1".equals(code)){
								return "300#"+msg;
							}
							policyDownUrl = policyDownUrl.replace("&amp;","&");
//							policyDownUrl = unloading_bd(policyDownUrl);
//							System.err.println("====>getQHHDCBResult.policyDownUrl:"+policyDownUrl);
							//重新保存并生成下载地址（保存原文件到我们平台，生成我们平台的访问地址）
//							policyDownUrl = unloading_bd(policyNo, policyDownUrl);
							//200#投保单号#保单号#电子保单地址
							return "200#"+proposalNo+ConstProp.POUND_SIGN+policyNo+ConstProp.POUND_SIGN+policyDownUrl;
						}
					}
				}
			}
		}catch (Exception e){
			logger.info("getQHHDCBResult:"+e.getMessage());
		}
		return "300#数据解析失败";
	}

	/**
	 *	核保接口返回字符串解析
	 * @return
	 */
	public String returnAnalysisXML(String xml, String transType){
		if(TransTypeEnum.HB.getValue().equals(transType)) {
			//核保
			return getQHHBResult(xml);
		}else if(TransTypeEnum.HDCB.getValue().equals(transType)) {
			//承保回调
			return getQHHDCBResult(xml);
		}else if(TransTypeEnum.PD.getValue().equals(transType)) {
			//批改
			return getQHPDResult(xml);
		}else if(TransTypeEnum.DZFP.getValue().equals(transType)) {
			//申请发票
			return getQHDZFPResult(xml);
		}else if(TransTypeEnum.ZXPG.getValue().equals(transType)) {
			//最新批改查询
			return getZXPGResult(xml);
		}
		return ConstProp.BLANK_CHAR;
	}

	/**
	 * <b>
	 *     根据保险公司电子保单下载地址转存成自己平台的下载地址（该方法暂未用）
	 * </b>
	 * @param rb_url 电子保单下载地址
	 * @author ZXF
	 * @create 2018/06/07 0007 11:01
	 * @version
	 * @注意事项 </b>
	 */
	private static String unloading_bd(String rb_url){
		String result = rb_url;
		if (StringUtils.isEmpty(rb_url)) {
			return result;
		}
		rb_url = rb_url.replace("amp;","");
		String pno = "QHGZZRX"+System.currentTimeMillis();
		HttpURLConnection conn = null;
		InputStream inStream = null;
		ByteArrayOutputStream output = null;
		try {
			URL url = new URL(rb_url);
			conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(10 * 1000);
			// 流处理
			inStream = conn.getInputStream();

//			result = OSSFileUtil.huaweiOBSFileUpload(inStream,"policy/","pdf");

			output = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int length;
			while ((length = inStream.read(buffer)) != -1) {
				output.write(buffer, 0, length);
			}
			// 获取字节数组并进行Base64编码
			String base64Str = Base64.getEncoder().encodeToString(output.toByteArray());
			result = OSSFileUtil.huaweiOBSFileUpload_base64(base64Str, "policy", pno+".pdf");
		} catch (Exception e) {
			logger.error("投保业务文件转存异常："+e.getMessage(),e);
			return rb_url;
		} finally {
			if (output != null) {
				try {
					output.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (inStream != null) {
				try {
					inStream.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return result;
	}

	public static void main(String[] args) {
		String url = "https://www.qhins.com/webins/epoliy?pNo=1BLB2023122937058906&sign=62fefe13a0950cb557bfc6d9a579ed43";
		System.out.println(unloading_bd(url));
	}
}
