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

import com.bcxin.ins.entity.common.LogBusinessrequest;
import com.bcxin.ins.service.order.LogBusinessrequestService;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.util.http.RequestUtil;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.ins.vo.GMRPolicyVo;
import com.bcxin.ins.vo.OrderFormVo;
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 liyognqiang
 * @date 2017年4月19日 上午10:29:46
 * @注意事项 </b>
 * <b>
 */
@Service("pARequestService")
@Transactional
public class PARequestService {

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

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


	/**
	 * 平安请求方法
	 * 测试地址：http://47.98.105.202:9003/api/transit
	 * 正式地址：http://47.98.105.202:9003/api/transitAdd
	 * 
	 * @return
	 */
	public String requestPA(Long order_id, String transType, Map<String,String> map) throws Exception {
		communicatorLog.info("requestPA：star-----------------------");
		communicatorLog.info("requestPA：接口编码-"+transType+",订单id-"+order_id+",MAP-"+(map != null ? map.toString() : "null"));
		OrderFormVo dto = policyService.accordingToOrderIDToGetPolicyDto(order_id);
		GMRPolicyVo vo = policyService.accordingToOrderIDToGetGMRPolicyVo(Long.parseLong(dto.getOid()));
		String result = "300#（APP-PA-001）网络不稳定，请重新请求！";
		LogBusinessrequest lb = null;
		try {
			String json =PackageMessagePingAn.marshal(vo, dto, transType, map);
			communicatorLog.info("请求报文："+json);
			String url = GlobalResources.PN_INS_URL + "/open/appsvr/annuity/openapi/receive/service?access_token="+policyService.pns_access_token();
			communicatorLog.info("请求地址："+url);
			Date bTime = new Date();
			String ret = RequestUtil.initHttp().doPost(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 = PackageMessagePingAn.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("requestPA：end-----------------------");
		return result;
	}


}
