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

import com.bcxin.ins.entity.common.LogBusinessrequest;
import com.bcxin.ins.entity.policy_core.InsTransaction;
import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.service.order.InsCommonReportAPIService;
import com.bcxin.ins.service.order.InsTransactionAPIService;
import com.bcxin.ins.service.order.LogBusinessrequestService;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.third.gzzrx.changan.GZZRX_PackageMessageChangAn;
import com.bcxin.ins.third.tyx.changan.http.CAHttpUtils;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.vo.*;
import com.bcxin.ins.vo.report_pac.InsCommonReportVo;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <b> 长安-团意险http接口请求业务 </b>
 * @author ZXF
 * @create 2021/04/02 0002 9:58
 * @version
 * @注意事项 </b>
 */
@Service("tYX_CARequestService")
@Transactional
public class TYX_CARequestService {

	private Logger communicatorLog =  LoggerFactory.getLogger(TYX_CARequestService.class);

	@Autowired
	private PolicyService policyService;
	@Autowired
	private InsTransactionAPIService insTransactionAPIService;
	@Autowired
	private LogBusinessrequestService logBusinessrequestService;
	@Autowired
	private InsCommonReportAPIService insCommonReportAPIService;

//"/data/upload/blb/cpic/cpic_jttp.keystore"

	/**
	 *
	 * 核保测试地址：https://test.channelplat.capli.com.cn:5443/17104/commlife
	 * 核保预发布地址：https://preprod.channelplat.capli.com.cn:5443/17104/commlife
	 * 核保生产地址：https://channelplatprod.capli.com.cn:5443/17104/commlife
	 *
	 * 支付测试地址：https://test.channelplat.capli.com.cn:5443/17116/commlife
	 * 支付测预发布地址：
	 * 支付生产地址：
	 *
	 * 批单测试地址：
	 * 批单生产地址：
	 *
	 *
	 * @return
	 */
	public String request_ca_tyx(Long order_id, String transType, InsPreservationRecordVo rvo) throws Exception {
		communicatorLog.info("request_rb_tyx：star-----------------------");
		communicatorLog.info("request_rb_tyx：接口编码-"+transType+",订单id-"+order_id+",RecordVo-"+(rvo != null ? rvo.toString() : "null"));
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(order_id);
		GMRPolicyVo vo = policyService.accordingToOrderIDToGetGMRPolicyVo(Long.parseLong(dto.getOid()));
		InsTransaction itran = null;
		if(TransTypeEnum.CBQR.getValue().equals(transType)){
			List<InsTransaction> itranList = insTransactionAPIService.selectInsTransactionByInsOrderForm(Long.parseLong(dto.getOid()));
			if(itranList.size()>0){
				itran = itranList.get(0);
			}
		}
		//如果是保全操作并且不是替换，标识为1
		String pdTo2 = "";
		if(rvo!=null&&!ConstProp.DIGIT_THREE.equals(rvo.getRevise_type())){
			pdTo2 = "1";
		}
		String result = "300#（APP-CA-TYX-001）网络不稳定，请重新请求！";
		LogBusinessrequest lb = null;
		try {
			String json = TYX_PackageMessageChangAn.marshal(vo, dto, transType, rvo, itran);
			communicatorLog.info("请求报文："+json);
			String url = getPath(transType,pdTo2);
			communicatorLog.info("请求地址："+url);
			Map<String, String> sslConfig = new HashMap<String, String>();
			//加载公钥私钥及密码
//			GlobalResources.CA_GZ_KEY_STORE_PATH = "F:/项目资料收藏夹/--历史项目记录--/百联保需求对接相关资料/2021_02-24(长安雇主责任险)/04_第三方对接文档/https/测试新证书/testjks/test_keystore.jks";
//			GlobalResources.CA_GZ_TRUST_STORE_PATH = "F:/项目资料收藏夹/--历史项目记录--/百联保需求对接相关资料/2021_02-24(长安雇主责任险)/04_第三方对接文档/https/测试新证书/testjks/test_truststore.jks";
			sslConfig.put("IgnoreVerifySSL", "false");
			sslConfig.put("keyStorePath", GlobalResources.CA_GZ_KEY_STORE_PATH);
			sslConfig.put("keyStorepass", GlobalResources.CA_GZ_KEY_STORE_PASS);
			sslConfig.put("trustStorePath", GlobalResources.CA_GZ_TRUST_STORE_PATH);
			sslConfig.put("trustStorepass", GlobalResources.CA_GZ_TRUST_STORE_PASS);
			Map<String, String> headers = new HashMap<String, String>();
			headers.put("Content-Type", "text/xml;charset=gbk");
			Date bTime = new Date();
			CloseableHttpResponse httpResponse = CAHttpUtils.doPost(url, null, null, headers, null, json, sslConfig);
			//获取结果实体
			String body = "";
			System.out.println("返回响应状态信息:" + httpResponse.getStatusLine());
			HttpEntity entity = httpResponse.getEntity();
			if (entity != null) {
				//按指定编码转换结果实体为String类型
				body = EntityUtils.toString(entity, "GBK");
			}
			EntityUtils.consume(entity);
			//释放链接
			httpResponse.close();
			String ret = StringUtils.replaceEach(body, new String[] {"\n","\t","\r"}, new String[] {"","",""});
			lb = logBusinessrequestService.initLogBusinessrequest(String.valueOf(order_id),transType,url,json,ret,bTime,new Date(), TransTypeEnum.getAlias(transType));
			communicatorLog.info("返回报文："+ret);
			TYX_PackageMessageChangAn gpm = new TYX_PackageMessageChangAn();
			result = gpm.returnAnalysisXML(ret,transType,pdTo2);
			communicatorLog.info("返回报文处理："+result);
			logBusinessrequestService.supplementDecAndSave(lb,result.startsWith(ConstProp.CODE_FAILURE)?1:0,ConstProp.BLANK_CHAR);
		}catch (Exception ex){
			logBusinessrequestService.supplementDecAndSave(lb,2,ex.getMessage());
			ex.printStackTrace();
		}
		communicatorLog.info("request_rb_tyx：end-----------------------");
		return result;
	}

	public String request_ca_dzfp(Long order_id, String transType, String certino, String kpStar, String kpEnd) {
		communicatorLog.info("request_ca_dzfp：star-----------------------");
		communicatorLog.info("request_ca_dzfp：接口编码-"+transType+",订单id-"+order_id+",certino-"+certino+",kpStar-"+kpStar+",kpEnd-"+kpEnd);
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(order_id);
		GMRPolicyVo vo = policyService.accordingToOrderIDToGetGMRPolicyVo(Long.parseLong(dto.getOid()));
		String result = "300#（APP-CA-GZZRX-001）网络不稳定，请重新请求！";
		LogBusinessrequest lb = null;
		try {
			String json = TYX_PackageMessageChangAn.mail(vo, dto, transType, certino, kpStar, kpEnd);
			communicatorLog.info("请求报文："+json);
			String url = getPath(transType,"");
			communicatorLog.info("请求地址："+url);
			Map<String, String> sslConfig = new HashMap<String, String>();
			//加载公钥私钥及密码
//			GlobalResources.CA_GZ_KEY_STORE_PATH = "F:/项目资料收藏夹/--历史项目记录--/百联保需求对接相关资料/2021_02-24(长安雇主责任险)/04_第三方对接文档/https/测试新证书/testjks/test_keystore.jks";
//			GlobalResources.CA_GZ_TRUST_STORE_PATH = "F:/项目资料收藏夹/--历史项目记录--/百联保需求对接相关资料/2021_02-24(长安雇主责任险)/04_第三方对接文档/https/测试新证书/testjks/test_truststore.jks";
			sslConfig.put("IgnoreVerifySSL", "false");
			sslConfig.put("keyStorePath", GlobalResources.CA_GZ_KEY_STORE_PATH);
			sslConfig.put("keyStorepass", GlobalResources.CA_GZ_KEY_STORE_PASS);
			sslConfig.put("trustStorePath", GlobalResources.CA_GZ_TRUST_STORE_PATH);
			sslConfig.put("trustStorepass", GlobalResources.CA_GZ_TRUST_STORE_PASS);
			Map<String, String> headers = new HashMap<String, String>();
			headers.put("Content-Type", "text/xml;charset=gbk");
			Date bTime = new Date();
			CloseableHttpResponse httpResponse = com.bcxin.ins.third.gzzrx.changan.http.CAHttpUtils.doPost(url, null, null, headers, null, json, sslConfig);
			//获取结果实体
			String body = "";
			System.out.println("返回响应状态信息:" + httpResponse.getStatusLine());
			HttpEntity entity = httpResponse.getEntity();
			if (entity != null) {
				//按指定编码转换结果实体为String类型
				body = EntityUtils.toString(entity, "GBK");
			}
			EntityUtils.consume(entity);
			//释放链接
			httpResponse.close();
			String ret = StringUtils.replaceEach(body, new String[] {"\n","\t","\r"}, new String[] {"","",""});
			lb = logBusinessrequestService.initLogBusinessrequest(String.valueOf(order_id),transType,url,json,ret,bTime,new Date(), TransTypeEnum.getAlias(transType));
			communicatorLog.info("返回报文："+ret);
			GZZRX_PackageMessageChangAn gpm = new GZZRX_PackageMessageChangAn();
			result = gpm.returnAnalysisXML(ret,transType);
			communicatorLog.info("返回报文处理："+result);
			logBusinessrequestService.supplementDecAndSave(lb,result.startsWith(ConstProp.CODE_FAILURE)?1:0,ConstProp.BLANK_CHAR);
		}catch (Exception ex){
			logBusinessrequestService.supplementDecAndSave(lb,2,ex.getMessage());
			ex.printStackTrace();
		}
		communicatorLog.info("request_ca_dzfp：end-----------------------");
		return result;
	}

	/**
	 * <b> 理赔报案接口 </b>
	 * @author ZXF
	 * @create 2019/11/15 0015 11:29
	 * @version
	 * @注意事项 </b>
	 */
	public String requestReportCA(InsCommonReportVo vo, String transType) throws Exception {
		communicatorLog.info("requestReportCA-TYX：star-----------------------");
		String result = "300#（APP-CA-TYX-051）网络不稳定，请重新请求！";
		LogBusinessrequest lb = null;
		try {
			String json = TYX_PackageMessageChangAn.marshalReport(vo, transType);
			communicatorLog.info("请求报文："+json);
			String url = getPath(transType,"");
			communicatorLog.info("请求地址："+url);
			Map<String, String> sslConfig = new HashMap<String, String>();
//			GlobalResources.CA_GZ_KEY_STORE_PATH = "F:/项目资料收藏夹/--历史项目记录--/百联保需求对接相关资料/2021_02-24(长安雇主责任险)/04_第三方对接文档/https/测试新证书/testjks/test_keystore.jks";
//			GlobalResources.CA_GZ_TRUST_STORE_PATH = "F:/项目资料收藏夹/--历史项目记录--/百联保需求对接相关资料/2021_02-24(长安雇主责任险)/04_第三方对接文档/https/测试新证书/testjks/test_truststore.jks";
			sslConfig.put("IgnoreVerifySSL", "false");
			sslConfig.put("keyStorePath", GlobalResources.CA_GZ_KEY_STORE_PATH);
			sslConfig.put("keyStorepass", GlobalResources.CA_GZ_KEY_STORE_PASS);
			sslConfig.put("trustStorePath", GlobalResources.CA_GZ_TRUST_STORE_PATH);
			sslConfig.put("trustStorepass", GlobalResources.CA_GZ_TRUST_STORE_PASS);
			Map<String, String> headers = new HashMap<String, String>();
			headers.put("Content-Type", "text/xml;charset=gbk");
			Date bTime = new Date();
			CloseableHttpResponse httpResponse = CAHttpUtils.doPost(url, null, null, headers, null, json, sslConfig);
			//获取结果实体
			String body = "";
			System.out.println("返回响应状态信息:" + httpResponse.getStatusLine());
			HttpEntity entity = httpResponse.getEntity();
			if (entity != null) {
				//按指定编码转换结果实体为String类型
				body = EntityUtils.toString(entity, "GBK");
			}
			EntityUtils.consume(entity);
			//释放链接
			httpResponse.close();
			String ret = StringUtils.replaceEach(body, new String[] {"\n","\t","\r"}, new String[] {"","",""});
			lb = logBusinessrequestService.initLogBusinessrequest(String.valueOf(vo.getIns_common_report_id()),transType,url,json,ret,bTime,new Date(), TransTypeEnum.getAlias(transType));
			communicatorLog.info("返回报文："+ret);
			TYX_PackageMessageChangAn gpm = new TYX_PackageMessageChangAn();
			result = gpm.returnAnalysisXML(ret,transType,"");
			communicatorLog.info("返回报文处理："+result);
			logBusinessrequestService.supplementDecAndSave(lb,result.startsWith(ConstProp.CODE_FAILURE)?1:0,ConstProp.BLANK_CHAR);
		}catch (Exception ex){
			logBusinessrequestService.supplementDecAndSave(lb,2,ex.getMessage());
			ex.printStackTrace();
		}
		communicatorLog.info("requestReportCA-TYX：end-----------------------");
		return result;
	}

	public String requestXXReportCA(String policyNo, String reportNo, int pageNo, String transType) throws Exception {
		communicatorLog.info("requestXXReportCA：star-----------------------");
		communicatorLog.info("requestXXReportCA：接口编码-"+transType+",保单号-"+policyNo+",报案号-"+reportNo);
		String result = "300#（APP-CA-TYX-001）网络不稳定，请重新请求！";
		LogBusinessrequest lb = null;
		try {
			String json = TYX_PackageMessageChangAn.marshalFindReport(policyNo, reportNo, pageNo);
			communicatorLog.info("请求报文："+json);
			String url = getPath(transType,"");
			communicatorLog.info("请求地址："+url);
			Map<String, String> sslConfig = new HashMap<String, String>();
//			GlobalResources.CA_GZ_KEY_STORE_PATH = "F:/项目资料收藏夹/--历史项目记录--/百联保需求对接相关资料/2021_02-24(长安雇主责任险)/04_第三方对接文档/https/测试新证书/testjks/test_keystore.jks";
//			GlobalResources.CA_GZ_TRUST_STORE_PATH = "F:/项目资料收藏夹/--历史项目记录--/百联保需求对接相关资料/2021_02-24(长安雇主责任险)/04_第三方对接文档/https/测试新证书/testjks/test_truststore.jks";
			sslConfig.put("IgnoreVerifySSL", "false");
			sslConfig.put("keyStorePath", GlobalResources.CA_GZ_KEY_STORE_PATH);
			sslConfig.put("keyStorepass", GlobalResources.CA_GZ_KEY_STORE_PASS);
			sslConfig.put("trustStorePath", GlobalResources.CA_GZ_TRUST_STORE_PATH);
			sslConfig.put("trustStorepass", GlobalResources.CA_GZ_TRUST_STORE_PASS);
			Map<String, String> headers = new HashMap<String, String>();
			headers.put("Content-Type", "text/xml;charset=gbk");
			Date bTime = new Date();
			CloseableHttpResponse httpResponse = CAHttpUtils.doPost(url, null, null, headers, null, json, sslConfig);
			//获取结果实体
			String body = "";
			System.out.println("返回响应状态信息:" + httpResponse.getStatusLine());
			HttpEntity entity = httpResponse.getEntity();
			if (entity != null) {
				//按指定编码转换结果实体为String类型
				body = EntityUtils.toString(entity, "GBK");
			}
			EntityUtils.consume(entity);
			//释放链接
			httpResponse.close();
			String ret = StringUtils.replaceEach(body, new String[] {"\n","\t","\r"}, new String[] {"","",""});
			String orderSign = "";
//			String orderSign = StringUtils.isNotEmpty(policyNo)?policyNo:reportNo;
			lb = logBusinessrequestService.initLogBusinessrequest(orderSign,transType,url,json,ret,bTime,new Date(), TransTypeEnum.getAlias(transType));
			communicatorLog.info("返回报文："+ret);
			TYX_PackageMessageChangAn gpm = new TYX_PackageMessageChangAn();
			result = gpm.returnAnalysisXML(ret,transType,"");
			communicatorLog.info("返回报文处理："+result);
			logBusinessrequestService.supplementDecAndSave(lb,result.startsWith(ConstProp.CODE_FAILURE)?1:0,ConstProp.BLANK_CHAR);
		}catch (Exception ex){
			logBusinessrequestService.supplementDecAndSave(lb,2,ex.getMessage());
			ex.printStackTrace();
		}
		communicatorLog.info("request_rb_tyx：end-----------------------");
		return result;
	}

	private String getPath(String tt,String pdTo2){
		if(TransTypeEnum.HB.getValue().equals(tt)){
			return GlobalResources.CA_TY_API_URL;
		}else if(TransTypeEnum.PD.getValue().equals(tt)){
			return StringUtils.isEmpty(pdTo2)?GlobalResources.CA_TY_PD_API_URL:GlobalResources.CA_TY_PD_2_API_URL;
		}else if(TransTypeEnum.PDJG.getValue().equals(tt)){
			return GlobalResources.CA_TY_PD_2_API_URL;
		}else if(TransTypeEnum.ZFDZ.getValue().equals(tt)){
			return GlobalResources.CA_TY_PAY_API_URL;
		}else if(TransTypeEnum.CBQR.getValue().equals(tt)){
			return GlobalResources.CA_TY_API_URL;
		}else if(TransTypeEnum.BASL.getValue().equals(tt)){
			return GlobalResources.CA_TY_BASL_API_URL;
		}else if(TransTypeEnum.CLSC.getValue().equals(tt)){
			return GlobalResources.CA_TY_BASL_API_URL;
		}else if(TransTypeEnum.AJCX.getValue().equals(tt)){
			return GlobalResources.CA_TY_BASL_API_URL;
		}else if(TransTypeEnum.DZFP.getValue().equals(tt)){
			return GlobalResources.CA_FP_API_URL;
		}else if(TransTypeEnum.PDDZFP.getValue().equals(tt)){
			return GlobalResources.CA_FP_API_URL;
		}
		return "";
	}
}
