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

import com.alibaba.fastjson.JSONObject;
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.third.zzx.yongan.vo.*;
import com.bcxin.ins.util.FileHelp;
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.bcxin.mybatisplus.toolkit.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 javax.xml.namespace.QName;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 *
 * <b>永安-展责险http接口请求业务</b>
 *
 * @author zxf
 * @date 2018年7月17日 上午10:29:46
 * @注意事项 </b>
 * <b>
 */
@Service("zZX_YARequestService")
@Transactional
public class ZZX_YARequestService {

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

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

	private static final QName SERVICE_NAME = new QName(
			"http://service.webservice.yaic.com/", "AppServiceService");

	/**
	 * 永安接口请求方法
	 * 生产环境：
	 * @param is_phone 默认0 pc下单核保，1 移动端下单核保
	 * @return
	 */
	public String requestYA(Long order_id, String transType, Map<String,String> map, int is_phone) {
		communicatorLog.info("requestYA-ZZX：star-----------------------");
		communicatorLog.info("requestYA-ZZX：接口编码-"+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-YA-ZZX-001）网络不稳定，请重新请求！";
		LogBusinessrequest lb = null;
        try {
			String httpUrl = getUrlByTransType(transType);
			communicatorLog.info("requestYA-ZZX-transType："+transType+",请求地址："+httpUrl);
			URL url = new URL(httpUrl);
			AppRequestBean arb = ZZX_PackageMessageYongAn.marshal(vo,dto,transType,is_phone);//请求数据
			communicatorLog.info("requestYA-ZZX-transType："+transType+",请求报文："+ JSONObject.toJSONString(arb));
			Date bTime = new Date();
			AppServiceService ss = new AppServiceService(url, SERVICE_NAME);
			AppService port = ss.getAppServicePort();
			AppResponseBean rep = port.appRequest(arb);
			lb = logBusinessrequestService.initLogBusinessrequest(String.valueOf(order_id),transType,httpUrl,JSONObject.toJSONString(arb),rep.toString(),bTime,new Date(), TransTypeEnum.getAlias(transType));
			communicatorLog.info("requestYA-ZZX-transType："+transType+",返回报文："+rep.toString());
			if("1".equals(rep.getFlag())){
				result = "300#"+rep.getReason();
			}else{
				List<AppInfoRes> air = rep.getAppInfoRes();
				AppInfoRes ar = null;
				if(air.size()>0){
					ar = air.get(0);
					if(ar != null){
						if(ConstProp.DIGIT_ONE.equals(transType)){
							result = "200#"+ar.getSerialno()+ConstProp.POUND_SIGN+ar.getPayappno()+ConstProp.POUND_SIGN+ar.getPaymenturl();
						}else if(ConstProp.DIGIT_TWO.equals(transType)) {
							result = "200#"+ar.getPolicyno();
						}

					}
				}
			}
			logBusinessrequestService.supplementDecAndSave(lb,result.startsWith(ConstProp.CODE_FAILURE)?1:0,ConstProp.BLANK_CHAR);
		}catch (Exception ex){
			logBusinessrequestService.supplementDecAndSave(lb,2,ex.getMessage());
			communicatorLog.info("requestYA-ZZX：ERROR："+ex);
			ex.printStackTrace();
		}
        communicatorLog.info("requestYA-ZZX：end-----------------------");
		return result;
	}

	public String getUrlByTransType(String transType){
		if(ConstProp.DIGIT_ONE.equals(transType)){//出单
			return GlobalResources.YA_ZZ_INS_URL+"/yaicservice/api/appservice?wsdl";
		}else if(ConstProp.DIGIT_TWO.equals(transType)){//撤单
			return GlobalResources.YA_ZZ_INS_URL+"/yaicservice/api/cancelservice?wsdl";
		}else if(ConstProp.DIGIT_THREE.equals(transType)){//撤单（不定保费）
			return GlobalResources.YA_ZZ_INS_URL+"/yaicservice/api/cancelappservice?wsdl";
		}else if(ConstProp.DIGIT_FOUR.equals(transType)){//电子保单
			return GlobalResources.YA_ZZ_INS_URL+"/yaicservice/apppdfServlet";
		}
		return "";
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	/**
	 * <b>
	 *     根据保险公司电子保单下载地址转存成自己平台的下载地址
	 * </b>
	 * @param rb_url 电子保单下载地址
	 * @author ZXF
	 * @create 2018/10/25 0007 11:01
	 * @version
	 * @注意事项 </b>
	 */
	public static String unloading_ya(String rb_url){
		String result = rb_url;
		if (StringUtils.isNotEmpty(rb_url)) {

			InputStream inStream = null;
			try {
				String files = rb_url.split("policyno=")[1].split("&")[0]+".pdf";
				if(StringUtils.isEmpty(files)){
					files = "YAZZ"+System.currentTimeMillis();
				}
				URL url = new URL(rb_url);
				HttpURLConnection conn = (HttpURLConnection)url.openConnection();
				conn.setRequestMethod("GET");
				conn.setConnectTimeout(5 * 1000);
				inStream = conn.getInputStream();//通过输入流获取图片数据
				String savePath = "/policy/";
				result = savePath + files;
				String path = GlobalResources.COM_IMG_RE+savePath;
				FileHelp.isFile(inStream, path, files);
				result = GlobalResources.DONOW_PATH+"/getResource?path="+result;
			} catch (Exception e) {
				return result;
			} finally {
				if (inStream != null) {
					try {
						inStream.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}
		}
		return result;
	}
}
