package com.bcxin.ins.third.zzx.zhongan;

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.third.zzx.zhongan.dto.CashierConfig;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.ins.vo.LOTEPolicyVo;
import com.bcxin.ins.vo.OrderFormVo;
import com.zhongan.scorpoin.biz.common.CommonRequest;
import com.zhongan.scorpoin.biz.common.CommonResponse;
import com.zhongan.scorpoin.common.ZhongAnApiClient;
import com.zhongan.scorpoin.common.ZhongAnEnvEnum;
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.Map;


/**
 *
 * <b>展责险众安接口请求</b>
 *
 * @author zxf
 * @date 2017年9月13日 上午10:29:46
 * @注意事项 </b>
 * <b>
 */
@Service("zARequestService")
@Transactional
public class ZARequestService {

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

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


	/**
	 * 众安请求方法
	 * @param order_id
	 * @param transType 接口类型：1核保2出单3退保
	 * @param map 支付返回相关数据
	 * @return
	 */
	public String requestZA(Long order_id, String transType, Map<String,String> map) throws Exception {
		communicatorLog.info("requestZA：star-----------------------");
		communicatorLog.info("requestZA：接口编码-"+transType+",订单id-"+order_id+",MAP-"+(map != null ? map.toString() : "null"));
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(order_id);
		LOTEPolicyVo vo = policyService.accordingToOrderIDToGetLOTEPolicyVo(Long.parseLong(dto.getOid()));
		String result = "300#（APP-ZA-300.00）网络不稳定，请重新请求！";
		LogBusinessrequest lb = null;
		try {

			//以下参数为：环境参数、接口版本号、appKey、开发者rsa私钥、接口名
			String env = getEnvironmentSign();
			String version = CashierConfig.VERSION;
			String privateKey = CashierConfig.APP_KEY;
			String serviceName = getServiceName(transType);

			ZhongAnApiClient client = new ZhongAnApiClient(env, getAppKey(), privateKey, version);

			CommonRequest request = new CommonRequest(serviceName);
			JSONObject params = PackageMessageZhongAn.marshal(vo, dto, transType, map);
			communicatorLog.info("请求报文："+params);

			request.setParams(params);
			Date bTime = new Date();
			CommonResponse response = (CommonResponse) client.call(request);
			lb = logBusinessrequestService.initLogBusinessrequest(String.valueOf(order_id),transType, ZhongAnEnvEnum.get(env).getUrl(),params.toJSONString(),response.toString(),bTime,new Date(), TransTypeEnum.getAlias(transType));
			communicatorLog.info("返回报文："+response.toString());

			if(response == null){
				result = "300#（APP-ZA-300.01）请求过程出现异常，未获取到返回信息！";
			}else{
				if(response.getBizContent() == null){
					result = "300#（APP-ZA-300.02）"+response.getErrorMsg();
				}else{
					result = PackageMessageZhongAn.returnAnalysisJson(response.getBizContent(),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());
			communicatorLog.error("APP-ZA-ERROR: request error",ex);
		}
		communicatorLog.info("requestZA：end-----------------------");
		return result;
	}

	private static String getServiceName(String transType){
		if("1".equals(transType)){
			return "zhongan.normal.comm.new.galatea.insure.uw";
		}else if("2".equals(transType)){
			return "zhongan.normal.comm.new.galatea.insure.issue";
		}else if("3".equals(transType)){
			return "zhongan.normal.comm.cancel.policy";
		}
		return "";
	}

	/**
	 * 根据当前部署环境获取对应众安接口的环境标识
	 * @return
	 */
	private static String getEnvironmentSign(){
		if(!GlobalResources.IS_TEST_ENVI){//生成
			return "prd";
		}else{//测试
			return "dev";
		}
	}

	/**
	 * 根据当前部署环境获取对应众安接口的appKey
	 * @return
	 */
	private static String getAppKey(){
		if(!GlobalResources.IS_TEST_ENVI){//生成
			return CashierConfig.ZA_APP_KEY_ENV;
		}else{//测试
			return CashierConfig.ZA_APP_KEY_DEV;
		}
	}

}
