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

import com.alibaba.fastjson.JSON;
import com.bcxin.ins.entity.common.LogBusinessrequest;
import com.bcxin.ins.entity.policy_core.InsOrderReconciliation;
import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.service.order.LogBusinessrequestService;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.third.gyx.taibao.util.MySecureProtocolSocketFactory;
import com.bcxin.ins.third.gzzrx.taibao.util.AESUtilsn;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.ins.vo.InsPreservationRecordVo;
import com.bcxin.ins.vo.OrderFormVo;
import com.bcxin.ins.vo.SpecialHirelingVo;
import com.bcxin.ins.vo.report_pac.InsCommonReportVo;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import com.google.common.collect.Lists;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.ssl.SSLContextBuilder;
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 javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 *
 * <b>太保-雇主责任险险http接口请求业务</b>
 *
 * @author zxf
 * @date 2017年10月11日 上午10:29:46
 * @注意事项 </b>
 * <b>
 */
@Service("gZZRX_TBRequestService")
@Transactional
public class GZZRX_TBRequestService {

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

	@Autowired
	private PolicyService policyService;
	@Autowired
	private LogBusinessrequestService logBusinessrequestService;
//	@Autowired
//	private InsCommonReportAPIService insCommonReportAPIService;

	// 版本标识，固定值 7
	private static String messageRouter = "7";
	// 合作伙伴编码，由太保指定，每个商户不一样
	private static String partnerCode = "ELME";
	// 业务协议，固定值 CPIC_ECOM
	private static String documentProtocol = "CPIC_ECOM";

	private String sentHttpPostRequest(String requestMsg) throws Exception {
//		ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
//		Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
		HttpClient httpclient = new DefaultHttpClient();
		// 设置超时时间
		int timeout = 60000;
		HttpConnectionParams.setSoTimeout(httpclient.getParams(), timeout);
		// 注意：必须以post方式发送请求
		HttpPost httppost = new HttpPost(GlobalResources.TB_GZ_API_URL);
		// 设置请求参数
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 版本标识
		params.add(new BasicNameValuePair("messageRouter", messageRouter));
		// 业务伙伴代码
		params.add(new BasicNameValuePair("tradingPartner", partnerCode));
		// 业务协议
		params.add(new BasicNameValuePair("documentProtocol", documentProtocol));
		// 请求报文
		params.add(new BasicNameValuePair("requestMessage", requestMsg));
		// 注意：编码必须是UTF-8
		HttpEntity request = new UrlEncodedFormEntity(params, "UTF-8");
		httppost.setEntity(request);
		// 返回报文
		HttpResponse httpResponse = httpclient.execute(httppost);
		HttpEntity entity = httpResponse.getEntity();
		String result = null;
		if (entity != null) {
			result = EntityUtils.toString(entity);
		}
		return result;
	}

	/**
	 * @return
	 */
	public String request_tb_gzzrx(Long order_id, String transType, InsPreservationRecordVo rvo) throws Exception {
		communicatorLog.info("request_tb_gzzrx：star-----------------------");
		communicatorLog.info("request_tb_gzzrx：接口编码-"+transType+",订单id-"+order_id+",RecordVo-"+(rvo != null ? JSON.toJSONString(rvo) : "null"));
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(order_id);
		SpecialHirelingVo vo = policyService.accordingToOrderIDToGetSpecialHirelingVo(Long.parseLong(dto.getOid()));
		String result = "300#（APP-TB-GZZRX-001）网络不稳定，请重新请求！";
		LogBusinessrequest lb = null;
		try {
			String jsonOrig = GZZRX_PackageMessageTaiBao.marshal(vo, dto, transType, rvo);
			communicatorLog.info("请求报文："+jsonOrig);
			String json = AESUtilsn.encrypt(jsonOrig, GlobalResources.TB_GZ_SECRET_KEY);
			communicatorLog.info("请求报文(加密)："+json);
			communicatorLog.info("请求地址："+GlobalResources.TB_GZ_API_URL);
			Date bTime = new Date();
			String ret = sentHttpPostRequest(json);
			communicatorLog.info("返回报文(加密)："+ret);
			lb = logBusinessrequestService.initLogBusinessrequest(String.valueOf(order_id),transType,GlobalResources.TB_GZ_API_URL,jsonOrig,ret,bTime,new Date(), TransTypeEnum.getAlias(transType));
			ret = AESUtilsn.decrypt(ret, GlobalResources.TB_GZ_SECRET_KEY);
			communicatorLog.info("返回报文："+ret);
			lb.setResponse_message(ret);
			GZZRX_PackageMessageTaiBao gpm = new GZZRX_PackageMessageTaiBao();
			result = gpm.returnAnalysisJson(ret,transType);
			communicatorLog.info("返回报文处理："+result);
			logBusinessrequestService.supplementDecAndSave(lb,result.startsWith(ConstProp.CODE_FAILURE)?1:0,ConstProp.BLANK_CHAR);
		}catch (Exception ex){
			ex.printStackTrace();
			if(lb != null){
				logBusinessrequestService.supplementDecAndSave(lb,2,ex.getMessage());
			}
		}
		communicatorLog.info("request_tb_gzzrx：end-----------------------");
		return result;
	}
	public String requestReport(Long order_id, InsCommonReportVo vo, String reportDetail, String transType) {
		communicatorLog.info("requestReportTB-GZZRX：star-----------------------");
		communicatorLog.info("requestReportTB-GZZRX：接口编码-"+transType+",订单id-"+order_id);
//		InsCommonReportVo vo = insCommonReportAPIService.getInsCommonReportVoInfoById(report_id,1);
		SpecialHirelingVo shVo = policyService.accordingToOrderIDToGetSpecialHirelingVo(order_id);
		OrderFormVo orderFormVo = policyService.accordingToOrderIDToGetPolicyDto(order_id);
		String result = "300#（APP-TB-GZZRX-REPORT-001）网络不稳定，请重新请求！";
		LogBusinessrequest lb = null;
		try {
			String jsonOrig = GZZRX_PackageMessageTaiBao.marshalReportJson(shVo, reportDetail, vo, transType, orderFormVo);
			communicatorLog.info("请求报文："+jsonOrig);
			String json = AESUtilsn.encrypt(jsonOrig, GlobalResources.TB_GZ_SECRET_KEY);
			communicatorLog.info("请求地址："+GlobalResources.TB_GZ_API_URL);
			Date bTime = new Date();
			String ret = sentHttpPostRequest(json);
			lb = logBusinessrequestService.initLogBusinessrequest(String.valueOf(order_id),transType,GlobalResources.TB_GZ_API_URL,jsonOrig,ret,bTime,new Date(), TransTypeEnum.getAlias(transType));
			communicatorLog.info("返回报文(加密)："+ret);
			ret = AESUtilsn.decrypt(ret, GlobalResources.TB_GZ_SECRET_KEY);
			communicatorLog.info("返回报文："+ret);
			GZZRX_PackageMessageTaiBao gpm = new GZZRX_PackageMessageTaiBao();
			result = gpm.returnAnalysisReportJson(ret,transType);
			communicatorLog.info("返回报文处理："+result);
			logBusinessrequestService.supplementDecAndSave(lb,result.startsWith(ConstProp.CODE_FAILURE)?1:0,ConstProp.BLANK_CHAR);
		}catch (Exception ex){
			ex.printStackTrace();
			logBusinessrequestService.supplementDecAndSave(lb,2,ex.getMessage());
		}
		communicatorLog.info("requestReportTB-GZZRX：end-----------------------");
		return result;
	}

	public static List<InsOrderReconciliation> loadReconciliation(String data) throws Exception {
//		ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
//		Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
		List<InsOrderReconciliation> list = Lists.newArrayList();
		HttpClient httpclient = new DefaultHttpClient();
		// 设置超时时间
		int timeout = 60000;
		HttpConnectionParams.setSoTimeout(httpclient.getParams(), timeout);
		// 注意：必须以post方式发送请求
//		HttpPost httppost = new HttpPost(GlobalResources.TB_GZ_ZD_URL+"?CPIC_P_"+data+".txt");
		HttpPost httppost = new HttpPost("http://jttpitxsit.cpic.com.cn/jttpitx/externalpartner/un/BCX_loadpolicy"+"?CPIC_P_"+data+".txt");
		// 设置请求参数
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 版本标识
		params.add(new BasicNameValuePair("messageRouter", messageRouter));
		// 业务伙伴代码
		params.add(new BasicNameValuePair("tradingPartner", partnerCode));
		// 业务协议
		params.add(new BasicNameValuePair("documentProtocol", documentProtocol));
		// 请求报文
		params.add(new BasicNameValuePair("requestMessage", ""));
		// 注意：编码必须是UTF-8
		HttpEntity request = new UrlEncodedFormEntity(params, "UTF-8");
		httppost.setEntity(request);
		// 返回报文
		HttpResponse httpResponse = httpclient.execute(httppost);

		try (BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(httpResponse.getEntity().getContent(), StandardCharsets.UTF_8))) {
//			StringBuilder sb = new StringBuilder();
			String line;
			String[] arr;
			while ((line = bufferedReader.readLine()) != null) {
//				sb.append(line);
				if(StringUtils.isNotEmpty(line)){
//					1||ASHZ107E3420PA163NV5||ESHZ107E3420PA163NV5||365||20240405||张三||张三||1||100.00
//					2||ASHZ107E3420PA163NV6||||365||20240405||李四||李四||1||100.00
					arr = line.split("||");
					list.add(new InsOrderReconciliation("TB",arr[1], arr[2], Integer.parseInt(arr[3]), Integer.parseInt(arr[4]), arr[5], arr[6], Integer.parseInt(arr[7]), new BigDecimal(arr[8])));
				}
			}
//			String responseString = sb.toString();
//			System.out.println(responseString);
		}
		return list;
	}

	public static void main(String[] args) throws Exception {
		System.out.println(loadReconciliation("20240405"));
	}

	/**
	 * <b> 理赔报案接口 </b>
	 * @author ZXF
	 * @create 2019/11/15 0015 11:29
	 * @version
	 * @注意事项 </b>
	 */
	public String requestReportTB(Long order_id, InsCommonReportVo vo, String reportDetail, String transType) {
		communicatorLog.info("requestReportTB-GZZRX：star-----------------------");
		communicatorLog.info("requestReportTB-GZZRX：接口编码-"+transType+",订单id-"+vo.getIns_common_report_id());
//		InsCommonReportVo vo = insCommonReportAPIService.getInsCommonReportVoInfoById(report_id,1);
		SpecialHirelingVo shVo = policyService.accordingToOrderIDToGetSpecialHirelingVo(order_id);
		String result = "300#（APP-TB-GZZRX-REPORT-001）网络不稳定，请重新请求！";
		LogBusinessrequest lb = null;
		try {
			String xml = GZZRX_PackageMessageTaiBao.marshalReport(shVo, reportDetail, vo, transType);
			communicatorLog.info("请求报文："+xml);
			communicatorLog.info("请求地址："+GlobalResources.TB_GZ_API_URL);
			Date bTime = new Date();
			String ret = sentHttpPostRequest(xml);
			lb = logBusinessrequestService.initLogBusinessrequest(String.valueOf(vo.getIns_common_report_id()),transType,GlobalResources.TB_GZ_API_URL,xml,ret,bTime,new Date(), TransTypeEnum.getAlias(transType));
			communicatorLog.info("返回报文："+ret);
			GZZRX_PackageMessageTaiBao gpm = new GZZRX_PackageMessageTaiBao();
			result = gpm.returnAnalysisXml_LP(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("requestReportTB-GZZRX：end-----------------------");
		return result;
	}
}
