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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.entity.common.LogBusinessrequest;
import com.bcxin.ins.service.order.LogBusinessrequestService;
import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.service.order.InsCommonReportAPIService;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.util.http.RequestUtil;
import com.bcxin.ins.vo.*;
import com.bcxin.ins.vo.report_pac.InsCommonReportVo;
import com.google.common.collect.Maps;
import com.pingan.iobs.sdk.common.Config;
import com.pingan.iobs.sdk.model.Response;
import com.pingan.iobs.sdk.service.IobsService;
import org.apache.commons.lang.StringUtils;
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.io.*;
import java.util.Date;
import java.util.Map;


/**
 * <b> 平安财-雇主责任险接口 </b>
 * @author ZXF
 * @create 2019/11/14 0014 14:54
 * @version
 * @注意事项 </b>
 */
@Service("gZZRX_PACRequestService")
@Transactional
public class GZZRX_PACRequestService {

	private static Logger communicatorLog =  LoggerFactory.getLogger(GZZRX_PACRequestService.class);

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

	private static final String PARTNERCODE = "P_BCXZR_GP";

	/**
	 * 平安请求方法
	 * 
	 * @return
	 */
	public String requestPAC(Long order_id, String transType, InsPreservationRecordVo iprVo) throws Exception {
		communicatorLog.info("requestPAC-GZZRX：star-----------------------");
		communicatorLog.info("requestPAC-GZZRX：接口编码-"+transType+",订单id-"+order_id+",iprVo-"+(iprVo != null ? iprVo.toString() : "null"));
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(order_id);
		SpecialHirelingVo vo = policyService.accordingToOrderIDToGetSpecialHirelingVo(Long.parseLong(dto.getOid()));
		String result = "300#（APP-PAC-GZZRX-001）网络不稳定，请重新请求！";
		LogBusinessrequest lb = null;
		try {
			String json = GZZRX_PackageMessagePAC.marshal(vo, dto, transType, iprVo);
			communicatorLog.info("请求报文："+json);
			String url = GlobalResources.PN_INS_URL
					+ "/open/appsvr/property/openapi/"
					+PARTNERCODE+ ConstProp.SLASH+getUrlByTransType(dto.getIs_policy_before_pay_fee(),transType)
					+"?access_token="+policyService.pnc_access_token();
			communicatorLog.info("请求地址："+url);
			Date bTime = new Date();
			String ret = RequestUtil.initHttp().doPostByAccept(url, json, "application/json", "UTF-8");
			lb = logBusinessrequestService.initLogBusinessrequest(String.valueOf(order_id),transType,url,json,ret,bTime,new Date(), TransTypeEnum.getAlias(transType));
			communicatorLog.info("返回报文："+ret);
			result = GZZRX_PackageMessagePAC.returnAnalysisJson(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("requestPAC-GZZRX：end-----------------------");
		return result;
	}

	private static String getUrlByTransType(String isPayFee,String type){
		if(TransTypeEnum.HB.getValue().equals(type)){//核保
			return DictConst.PAY_FEE_JF.equals(isPayFee)?"applyForFee":"applyForNoFee";
		}else if(TransTypeEnum.CBXX.getValue().equals(type)){//承保
			return "acceptForFee";
		}else if(TransTypeEnum.DZBD.getValue().equals(type)){//电子保单打印
			return "printGP";
		}else if(TransTypeEnum.DZPD.getValue().equals(type)){//电子批单打印
			return "printGP";
		}else if(TransTypeEnum.ZFDZ.getValue().equals(type)){//获取支付地址
			return "prePayFinance";
		}else if(TransTypeEnum.DZFP.getValue().equals(type)){//电子发票
			return "printInvoice";
		}else if(TransTypeEnum.PD.getValue().equals(type)){//批单
			return "endorse";
		}else if(TransTypeEnum.BASL.getValue().equals(type)){//报案受理
			return "interface/commonOpenApi/saveReportInfo";
		}else if(TransTypeEnum.AJCX.getValue().equals(type)){//案件查询
			return "interface/commonOpenApi/queryCaseInfoList";
		}else if(TransTypeEnum.CLSC.getValue().equals(type)){//材料上传
			return "interface/uploadFileOpenApi/fileUpload";
		}else if(TransTypeEnum.XXAJCX.getValue().equals(type)){//同步线下案件信息
			return "interface/commonEsg/queryBCXCaseList";
		}
		return "";
	}

	/**
	 * <b> 批单确认接口，增减员保费出现变动时调用 </b>
	 * @author ZXF
	 * @create 2019/11/01 0001 16:13
	 * @version
	 * @注意事项 </b>
	 */
	public String pdqr(String transType, String pdResult){
		communicatorLog.info("pdqr-GZZRX：star-----------------------");
		communicatorLog.info("pdqr-GZZRX：接口编码-"+transType+",pdResult-"+pdResult);
		if(StringUtils.isNotEmpty(pdResult)) {
			//200#保单号#批单号#保费#批单申请号#批改申请时的流水号
			String[] arr = pdResult.split(ConstProp.POUND_SIGN);
			String result = "300#（APP-PAC-GZZRX-001）网络不稳定，请重新请求！";
			LogBusinessrequest lb = null;
			try {
				String json = GZZRX_PackageMessagePAC.pdqr_marshal(arr[1], transType, arr[4],arr[3],arr[5]);
				communicatorLog.info("请求报文："+json);
				String url = GlobalResources.PN_INS_URL + "/open/appsvr/property/openapi/"+PARTNERCODE+ ConstProp.SLASH+getUrlByTransType("",transType)+"?access_token="+policyService.pnc_access_token();
				communicatorLog.info("请求地址："+url);
				Date bTime = new Date();
				String ret = RequestUtil.initHttp().doPostByAccept(url, json, "application/json", "UTF-8");
				lb = logBusinessrequestService.initLogBusinessrequest(ConstProp.BLANK_CHAR,transType,url,json,ret,bTime,new Date(), TransTypeEnum.getAlias(transType));
				communicatorLog.info("返回报文："+ret);
				result = GZZRX_PackageMessagePAC.returnAnalysisJson(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("pdqr-GZZRX：end-----------------------");
			return result;
		}else{
			return "300#无批改信息！";
		}
	}

	/**
	 * <b> 理赔报案接口 </b>
	 * @author ZXF
	 * @create 2019/11/15 0015 11:29
	 * @version
	 * @注意事项 </b>
	 */
	public String requestReportPAC(Long report_id, String transType) throws Exception {
		communicatorLog.info("requestReportPAC-GZZRX：star-----------------------");
		communicatorLog.info("requestReportPAC-GZZRX：接口编码-"+transType+",订单id-"+report_id);
		InsCommonReportVo vo = insCommonReportAPIService.getInsCommonReportVoInfoById(report_id,1);
		String result = "300#（APP-PAC-GZZRX-REPORT-001）网络不稳定，请重新请求！";
		LogBusinessrequest lb = null;
		try {
			String json = GZZRX_PackageMessagePAC.marshalReport(vo, transType);
			communicatorLog.info("请求报文："+json);
			String url = GlobalResources.PN_INS_URL + "/open/appsvr/property/"+getUrlByTransType("",transType)+"?access_token="+policyService.pnc_access_token();
			if(TransTypeEnum.CLSC.equals(transType)){
				url = url + "&request_id=fileUpload" + System.currentTimeMillis();;
			}
			communicatorLog.info("请求地址："+url);
			Date bTime = new Date();
			String ret = OpenApiPost.post(url, json);
			lb = logBusinessrequestService.initLogBusinessrequest(String.valueOf(report_id),transType,url,json,ret,bTime,new Date(), TransTypeEnum.getAlias(transType));
			communicatorLog.info("返回报文："+ret);
			result = GZZRX_PackageMessagePAC.returnAnalysisJson_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("requestReportPAC-GZZRX：end-----------------------");
		return result;
	}

	/**
	 * <b> 根据保单号查询线下做理赔的保安信息列 </b>
	 * @param policyNos 保单号列，一次最多传50个保单号
	 * @param pageSize 每页记录数【最大200,建议100】
	 * @param pageNum 当前页数
	 * @author ZXF
	 * @create 2020/04/27 0027 11:14
	 * @version
	 * @注意事项 由于请求频繁注释掉接口请求日志记录，有需要再开启</b>
	 */
	public String requestXXReportPAC(String policyNos, Integer pageSize, Integer pageNum, String transType) throws Exception {
		communicatorLog.info("requestXXReportPAC-GZZRX：star-----------------------");
		communicatorLog.info("requestXXReportPAC-GZZRX：接口编码-"+transType+",保单号列-"+policyNos);
		String result = "300#（APP-PAC-GZZRX-XXREPORT-001）网络不稳定，请重新请求！";
		try {
			JSONObject body = new JSONObject();
			body.put("policyNos",policyNos);
			body.put("pageNum",pageNum);
			body.put("pageSize",pageSize);
			String json = body.toString();
			communicatorLog.info("请求报文："+json);
			String url = GlobalResources.PN_INS_URL + "/open/appsvr/property/"+getUrlByTransType("",transType)+"?access_token="+policyService.pnc_access_token();
			communicatorLog.info("请求地址："+url);
			String ret = OpenApiPost.post(url, json);
			communicatorLog.info("返回报文："+ret);
			result = GZZRX_PackageMessagePAC.returnAnalysisJson_LP(ret,transType);
			communicatorLog.info("返回报文处理："+result);
		}catch (Exception ex){
			ex.printStackTrace();
		}
		communicatorLog.info("requestXXReportPAC-GZZRX：end-----------------------");
		return result;
	}

	/**
	 * <b> 提交报案 </b>
	 * @author ZXF
	 * @create 2019/12/12 0012 9:52
	 * @version
	 * @注意事项 </b>
	 */
	public String submitReportPAC(InsCommonReportVo vo, String transType) throws Exception {
		communicatorLog.info("submitReportPAC-GZZRX：star-----------------------");
		String result = "300#（APP-PAC-GZZRX-REPORT-001）网络不稳定，请重新请求！";
		LogBusinessrequest lb = null;
		try {
			String json = GZZRX_PackageMessagePAC.marshalReport(vo, transType);
			communicatorLog.info("请求报文："+json);
			String url = GlobalResources.PN_INS_URL + "/open/appsvr/property/"+getUrlByTransType("",transType)+"?access_token="+policyService.pnc_access_token();
			if(TransTypeEnum.CLSC.equals(transType)){
				url = url + "&request_id=fileUpload" + System.currentTimeMillis();;
			}
			communicatorLog.info("请求地址："+url);
			Date bTime = new Date();
			String ret = OpenApiPost.post(url, json);
			lb = logBusinessrequestService.initLogBusinessrequest(vo.getIns_common_report_id(),transType,url,json,ret,bTime,new Date(), TransTypeEnum.getAlias(transType));
			communicatorLog.info("返回报文："+ret);
			result = GZZRX_PackageMessagePAC.returnAnalysisJson_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("submitReportPAC-GZZRX：end-----------------------");
		return result;
	}

	/**
	 * <b> 平安财报案附件上传接口的token获取 </b>
	 * @author ZXF
	 * @create 2019/11/15 0015 14:49
	 * @version
	 * @注意事项 </b>
	 */
	private Map<String, String> getIobsParam(){
		String url=  GlobalResources.PN_INS_URL
				+ "/open/appsvr/property/interface/uploadFileOpenApi/fileUploadToken?access_token="
				+policyService.pnc_access_token()
				+ "&request_id=fileUploadToken" + System.currentTimeMillis();
		communicatorLog.info("===========================PNC_GET_UPLOAD_ACCESS_TOKEN_URL-START======================");
		try {
			communicatorLog.info("平安财报案附件上传接口的token获取,地址："+url);
			String result = OpenApiPost.post(url, "");
			communicatorLog.info("平安财报案附件上传接口的token获取,返回报文："+result);
			if(StringUtils.isNotEmpty(result)){
				return jxToken(result);
			}
		}catch (Exception ex){
			communicatorLog.error("PNC_GET_UPLOAD_ACCESS_TOKEN_URL-ERROR",ex);
		}
		return null;
	}

	private static Map<String,String> jxToken(String apiResult){
		Map<String,String> iobsMap = null;
		JSONObject apiJson = JSON.parseObject(apiResult);
		if (ConstProp.DIGIT_ZERO.equals(apiJson.getString("ret"))) {
			iobsMap = Maps.newHashMap();
			// 上传附件到iobs的token
			iobsMap.put("token", apiJson.getJSONObject("data").getJSONObject("data").getString("fileUploadToken"));
			// 上传附件到iobs的bucket
			iobsMap.put("bucket", apiJson.getJSONObject("data").getJSONObject("data").getString("bucket"));
			communicatorLog.info("平安财报案附件上传接口的token获取,token值："+iobsMap.get("token")+",bucket值："+iobsMap.get("bucket"));
			communicatorLog.info("===========================PNC_GET_UPLOAD_ACCESS_TOKEN_URL-END======================");
		}
		return iobsMap;
	}

	/**
	 * <b> 文件流推送平安业务方法 </b>
	 * @author ZXF
	 * @create 2019/11/18 0018 16:15
	 * @version
	 * @注意事项 </b>
	 */
	public boolean isUploadPA(InputStream inputStream
			, String fileId
			, String originalName) throws IOException {
		Map<String, String> iobsParamMap = getIobsParam();
		if(iobsParamMap != null){
			// 上传文件流的大小
			long length = inputStream.available();
			// 上传的关键方法
			// 访问域名、bucket(测试环境)
			Config.HOST = GlobalResources.PN_IOBS_URL;
			communicatorLog.info("报案附件上传Iobs接口,请求参数：fileId值："+fileId
					+",host值："+Config.HOST
					+",bucket值："+iobsParamMap.get("bucket")
					+",fileName值："+originalName
					+",token值："+iobsParamMap.get("token")
					+",length值："+length);
			Response response = new IobsService().uploadStream(iobsParamMap.get("bucket"), fileId, inputStream, originalName, iobsParamMap.get("token"), length);
			communicatorLog.info("平安财报案附件上传接口用于激活fileId,返回值："+JSON.toJSONString(response));
			if (response.isOK()) {
				communicatorLog.info("平安财报案附件上传接口fileId已激活,fileId："+fileId);
				return true;
			} else {
				communicatorLog.error("平安财报案附件上传接口fileId激活失败,ERROR:",response.error());
			}
		}
		return false;
	}
}
