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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bcxin.ins.util.DateUtil;
import com.bcxin.ins.util.MD5Util;
import com.bcxin.ins.vo.*;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class PackageMessageTK {

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

	private static final String FORMAT = "json";
	private static final String SIGNTYPE = "md5";
	private static final String CHARSET = "utf-8";
	private static final String VERSION = "1.0";
	private static final String BUSINESSCHANNEL = "05";
	private static final String FROMID = "62967";
	private static final String SALESMANCODE = "S131990026";
	private static final String GROUPIND = "2";
//	private static final String COMBOID = "1301A00301";
	private static final String SIGNKEY = "1234567890ABCDEF";
	private static final String CHANNELTIP = "01010106";
	private static final String SOLUTIONCODE = "0100000000006001120001";
	private static final String BLANK_CHAR = "";
	private static final String PRODUCTTYPE = "1301A003";//产品类型
	private static final String COOPID = "bai_chuan_xin";//合作方代码

	public static String marshal(GMRPolicyVo vo, OrderFormVo dto, String transType) throws Exception {
		if(dto == null) {
			return BLANK_CHAR;
		}
		Map<String, Object> mapP = Maps.newHashMap();
		//请求头
		doHead(mapP,dto,transType);
        String _md5 = "";
        if("01".equals(transType)){
			if(vo == null) {
				return BLANK_CHAR;
			}
			Map<String, Object> mapB = Maps.newHashMap();
			doContent(mapB,dto);
			//投保人
			List<Map<String, Object>> list_app = new ArrayList<Map<String, Object>>();
			doApplicant(list_app, vo.getRoleSubjectList());
			mapB.put("applicantList",list_app);
			//被保人
			List<Map<String, Object>> list_ins = new ArrayList<Map<String, Object>>();
			doInsured(list_ins, vo.getRoleSubjectList(),dto);
			mapB.put("insuredList",list_ins);
			if("1".equals(vo.getMailPolicyVo().getNeed_receipt())){
				//发票信息
				Map<String, Object> map_writ = Maps.newHashMap();
				doInvoice(map_writ,vo.getMailPolicyVo());
				mapB.put("parameterMap",map_writ);
			}

			mapP.put("apply_content",mapB);

            _md5 = MD5Util.string2MD5(SIGNKEY+ JSONArray.toJSONString(mapB));
		}else if("02".equals(transType)){
			Map<String, Object> map2 = Maps.newHashMap();
			//投保单号
			map2.put("proposalNo",dto.getPolicy_serial_number());
			mapP.put("apply_content",map2);
            _md5 = MD5Util.string2MD5(SIGNKEY+ JSONArray.toJSONString(map2));
		}
        //签名值
        mapP.put("sign",_md5);
        return JSONArray.toJSONString(mapP);
	}
	private static void doHead(Map<String, Object> map, OrderFormVo dto, String transType){
		//合作方代码
		map.put("coop_id",COOPID);
		//请求类型
		map.put("service_id",transType);
		//签名方式
		map.put("sign_type",SIGNTYPE);
		//报文格式
		map.put("format",FORMAT);
		//字符编码
		map.put("charset",CHARSET);
		//版本号
		map.put("version",VERSION);
		//交易时间戳
		map.put("timestamp", String.valueOf((new Date()).getTime()));
		//流水号
		map.put("serial_no",dto.getTrade_serial_number());
		//产品类型
		map.put("product_type",PRODUCTTYPE);
	}

	private static void doContent(Map<String, Object> map, OrderFormVo dto){
		//订单号
		map.put("requestId",dto.getTrade_serial_number());
		//投保时间
		map.put("issueDate",dto.getStart_time());
		//起保时间
		map.put("startDate",dto.getInception_date()+ConstProp.DAY_00/*"2017-04-25 00:00:00"*/);
		//终保时间
		map.put("endDate",dto.getPlanned_end_date()+ConstProp.DAY_23/*"2018-04-24 23:59:59"*/);
		//渠道编号
		map.put("businessChannel",BUSINESSCHANNEL);
		//定额方案代码
		map.put("comboId",getCOMBOID(dto.getProduct_code()));
		//客户ID(如果有会员机制就传入会员号)
		map.put("customerId",String.valueOf((new Date()).getTime()));
		//
		map.put("fromId",FROMID);
		//保额
		map.put("amount",dto.getInsured_amount());
		//保费
		map.put("premium",dto.getGross_premium());
		//销售员编号
		map.put("salesmanCode",SALESMANCODE);
		//渠道小类
		map.put("channelTip",CHANNELTIP);
		//子协议代码
		map.put("solutionCode",SOLUTIONCODE);
		//团险
		map.put("groupInd",GROUPIND);
	}

	private static void doApplicant(List<Map<String, Object>> list_app, List<RoleSubjectVo> roleList){
		Map<String, Object> map_app = null;
		for(RoleSubjectVo vo : roleList){
			if("1".equals(vo.getKind())){
				map_app = Maps.newHashMap();
				//投保单位
				map_app.put("name",vo.getName_cn());
				//证件类型，1-组织结构代码证,2-税务登记证,3-营业执照,99-其他
				map_app.put("identifyType",typeConversion_TK(vo.getId_type()));
				//证件号
				map_app.put("identifyNumber",vo.getOrganization_code());
				//省级代码）
				map_app.put("itemprovinceCode",vo.getReg_province());
				//市级代码
				map_app.put("itemcityCode",getCityCodeByPro(vo.getReg_province(),vo.getReg_city()));
				//县区代码
				map_app.put("itemdistrictCode",vo.getReg_district());
				//地址
				map_app.put("detailedAddress",vo.getReg_address());
				//联系人姓名
				map_app.put("contactName",vo.getLink_name());
				//联系人电话
				map_app.put("mobile",vo.getLink_tel());
				//联系人邮箱
				map_app.put("mail",vo.getLink_email());
				//邮政编码
				map_app.put("postCode",vo.getZip_code());
				//投保人类型
				map_app.put("insuredType","2");
				//投被保人标志
				map_app.put("insuredFlag","1");
				//单位电话
				map_app.put("officePhoneNumber",vo.getPhone());
				list_app.add(map_app);
			}
			map_app = null;
		}

	}

	private static void doInsured(List<Map<String, Object>> list_ins, List<RoleSubjectVo> roleList,OrderFormVo dto){
		Map<String, Object> map_ins = null;
		for(RoleSubjectVo vo : roleList){
			if("2".equals(vo.getKind())){
				map_ins = Maps.newHashMap();
				//姓名
				map_ins.put("name",vo.getName_cn());
				//性别
				map_ins.put("sex",vo.getSex());
				//证件类型，当证件类型为“01-居民身份证”时，校验长度为15位或18位，18位可带大写X或者小写x；
//				当证件类型为“02-护照”时，校验证件号2-20个字符；
//				当证件类型为“03-军人证”时，校验证件号为3-5个汉字+6-12个数字；
//				当证件类型为“05-港澳台同胞证”时，校验8-20个字符
				map_ins.put("identifyType", typeConversion_TK(vo.getId_type()));
				//证件号
				map_ins.put("identifyNumber",vo.getOrganization_code());
				//出生日期
				map_ins.put("birthday",vo.getBirth_date());
				//电话号码
				map_ins.put("mobile",vo.getMobile());
				/*//职业代码
				map_ins.put("occupationCode","1800010");
				//职业名称
				map_ins.put("occupationName","保安人员");*/
				//职业代码
				map_ins.put("occupationCode",getOccupation(vo.getMajor_group(),dto.getProduct_code()));
				//职业名称
				map_ins.put("occupationName","1".equals(vo.getMajor_group()) ? "内勤人员"
						: "2".equals(vo.getMajor_group()) ? "保安人员"
						: "武装押运人员");
				//请求类型
				map_ins.put("insuredFlag","2");
				//是否健康
				map_ins.put("healthStatus","0");
				//计划编码
				map_ins.put("projectCode",getCOMBOID(dto.getProduct_code()));
				//投保人类型
				map_ins.put("insuredType","1");
				//关系编码
				map_ins.put("relatedperson","99");
				//受益人标志
				map_ins.put("remark","01");
				list_ins.add(map_ins);
			}
			map_ins = null;
		}

	}

	private static String getOccupation(String major,String product_code){
		if("TYX-TK-3".equals(product_code)){
			if("1".equals(major)){
				return "18000101";
			}else if("2".equals(major)){
				return "18000101";
			}else{
				return "16020071";
			}
		}else if("TYX-TK-4".equals(product_code)){
			if("1".equals(major)){
				return "18000102";
			}else if("2".equals(major)){
				return "18000102";
			}else{
				return "16020072";
			}
		}else if("TYX-TK-5".equals(product_code)){
			if("1".equals(major)){
				return "18000103";
			}else if("2".equals(major)){
				return "18000103";
			}else{
				return "16020073";
			}
		}else if("TYX-TK-6".equals(product_code)){
			if("1".equals(major)){
				return "18000104";
			}else if("2".equals(major)){
				return "18000104";
			}else{
				return "16020074";
			}
		}else if("TYX-TK-1".equals(product_code)){
			if("1".equals(major)){
				return "18000105";
			}else if("2".equals(major)){
				return "18000105";
			}else{
				return "16020075";
			}
		}else if("TYX-TK-2".equals(product_code)){
			if("1".equals(major)){
				return "18000106";
			}else if("2".equals(major)){
				return "18000106";
			}else{
				return "16020076";
			}
		}
		return "";
	}

	private static String typeConversion_TK(String value){
		if("0".equals(value)){
			return "01";
		}else if("3".equals(value)){
			return "02";
		}else if("4".equals(value)){
			return "05";
		}else if("1".equals(value)){
			return "1";
		}else if("6".equals(value)){
			return "2";
		}else if("7".equals(value)){
			return "3";
		}else if("2".equals(value)){
			return "4";
		}else if("8".equals(value)){
			return "99";
		}
		return "99";
	}

	private static void doInvoice(Map<String, Object> map, MailPolicyVo mVo){
		//是否转保,1 是 2 否
		map.put("fieldAL","1");
		//发票抬头
		map.put("fieldAB",mVo.getReceipt_head());
		//增值税专票/增值税普票,01-增值税专票；02-增值税普票
		map.put("fieldAD", ConstProp.DIGIT_ONE.equals(mVo.getInvoice_type()) ? "01" : "02");
		//纳税人类型,1-小规模纳税人；2-一般纳税人
		map.put("fieldAA",ConstProp.DIGIT_ONE.equals(mVo.getInvoice_type()) ? "2" : "1");
		if(ConstProp.DIGIT_ONE.equals(mVo.getInvoice_type())){
			//税号
			map.put("fieldAC",mVo.getTaxpayer_number_invoice());
			//账户名称
			map.put("fieldAT",mVo.getBank_invoice());
			//银行账号
			map.put("fieldAU",mVo.getBank_account_invoice());
			//收款人开户银行省（省级代码）
			map.put("fieldAJ",mVo.getBank_province());
			//收款人开户银行市（市级代码）
			map.put("fieldAK",getCityCodeByPro(mVo.getBank_province(),mVo.getBank_city()));
			//开户银行
			map.put("fieldAI",mVo.getBank_invoice());
			//开票地址
			map.put("fieldAE",mVo.getRegister_address_invoice());
			//开票电话
			map.put("fieldAF",mVo.getReceipt_phone());
		}else{
			//税号
			map.put("fieldAC","123456789001");
			//账户名称
			map.put("fieldAT","123456789001");
			//银行账号
			map.put("fieldAU","123456789001");
			//收款人开户银行省（省级代码）
			map.put("fieldAJ","350000");
			//收款人开户银行市（市级代码）
			map.put("fieldAK","350600");
			//开户银行
			map.put("fieldAI","123456789001");
			//开票地址
			map.put("fieldAE","123456789001");
			//开票电话
			map.put("fieldAF","0592-6780000");
		}

	}

	/**
	 *	接口返回字符串解析
	 * @return
	 */
	public static String returnAnalysisJson(String json){
		String result = "";
		Map<String, Object> map = null;
		try{
			map = JSON.parseObject(json,Map.class);
		}catch(Exception e){
			return "300#（APP-TK-002）"+json;
		}
		if(map == null){
			return "300#（APP-TK-004）报文信息解析失败！";
		}
		String result_code = (String)map.get("result_code");
		if(!"0".equals(result_code)){
			return "300#（APP-TK-003）"+map.get("result_msg");
		}
		String service_id = (String)map.get("service_id");
		if(StringUtils.isEmpty(service_id)){
			return result;
		}
		Map<String, Object> contentMap = (Map<String, Object>) map.get("result_content");
		logger.info("报文解析：contentMap="+contentMap);
		if("01".equals(service_id)){//获取投保单号，起保日期，终保日期
			String proposalNo = "";
			String startDate = "";
			String endDate = "";
			if(contentMap.get("proposalNo") != null){
				proposalNo = (String)contentMap.get("proposalNo");
			}
			if(contentMap.get("startDate") != null){
				startDate = (String)contentMap.get("startDate");
			}
			if(contentMap.get("endDate") != null){
				endDate = (String)contentMap.get("endDate");
			}
			result = "200#"+proposalNo+ConstProp.POUND_SIGN+startDate+ConstProp.POUND_SIGN+endDate;
		}else if("02".equals(service_id)){//获取保单号跟电子保单下载地址
			String policyNo = "";
			String policyUrl = "";
			logger.info("报文解析：policyNo="+contentMap.get("policyNo"));
			if(contentMap.get("policyNo") != null){
				policyNo = (String)contentMap.get("policyNo");
			}
			if(contentMap.get("policyUrl") != null){
				policyUrl = (String)contentMap.get("policyUrl");
			}
			if(StringUtils.isNotEmpty(policyNo)){
				result = "200#"+policyNo+ConstProp.POUND_SIGN+policyUrl;
			}else{
				String result_msg = (String)map.get("result_msg");
				result = "300#（APP-TK-003）"+result_msg;
			}
		}
		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 String getCOMBOID(String product_code){//2017/11/13确认当前版本产品代码
		if(StringUtils.isEmpty(product_code) ? false : "TYX-TK-1".equals(product_code)){
			return "1301A00305";
		}else if(StringUtils.isEmpty(product_code) ? false : "TYX-TK-2".equals(product_code)){
			return "1301A00306";
		}else if(StringUtils.isEmpty(product_code) ? false : "TYX-TK-3".equals(product_code)){
			return "1301A00301";
		}else if(StringUtils.isEmpty(product_code) ? false : "TYX-TK-4".equals(product_code)){
			return "1301A00302";
		}else if(StringUtils.isEmpty(product_code) ? false : "TYX-TK-5".equals(product_code)){
			return "1301A00303";
		}else if(StringUtils.isEmpty(product_code) ? false : "TYX-TK-6".equals(product_code)){
			return "1301A00304";
		}else{
			return "";
		}
	}

	public static void main(String[] args){
		/*PolicyDto dto = exportsPolicyService.accordingToOrderIDToGetPolicyDto(Long.parseLong("847994294684696576"));
		GMRPolicyVo vo = policyCommonService.findGMRPolicyVoById(dto.getOid());
		marshal(vo, dto, "01");*/
	}
}
