package com.fjs.scenic.service.ticket.impl;

import java.io.StringReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fjs.scenic.cyt.request.ApplyOrderRefundByUserRequestBody;
import com.fjs.scenic.cyt.request.CancelOrderByOTARequestBody;
import com.fjs.scenic.cyt.request.CreateOrderRequestBody;
import com.fjs.scenic.cyt.request.CreatePaymentOrderRequestBody;
import com.fjs.scenic.cyt.request.GetOrderByOTARequestBody;
import com.fjs.scenic.cyt.request.GetProductByOTARequestBody;
import com.fjs.scenic.cyt.request.GetProductStockByOTARequestBody;
import com.fjs.scenic.cyt.request.NoticeOrderConsumedRequestBody;
import com.fjs.scenic.cyt.request.NoticeOrderRefundApproveResultRequestBody;
import com.fjs.scenic.cyt.request.PayOrderRequestBody;
import com.fjs.scenic.cyt.request.Request;
import com.fjs.scenic.cyt.request.RequestBody;
import com.fjs.scenic.cyt.request.RequestHeader;
import com.fjs.scenic.cyt.response.ApplyOrderRefundByUserResponseBody;
import com.fjs.scenic.cyt.response.CheckCreatePaymentOrderResponseBody;
import com.fjs.scenic.cyt.response.CreateOrderResponseBody;
import com.fjs.scenic.cyt.response.CreatePaymentOrderResponseBody;
import com.fjs.scenic.cyt.response.EditOrderStatusByOTAResponseBody;
import com.fjs.scenic.cyt.response.GetOrderByOTAResponseBody;
import com.fjs.scenic.cyt.response.GetProductByOTAResponseBody;
import com.fjs.scenic.cyt.response.GetProductStockByOTAResponseBody;
import com.fjs.scenic.cyt.response.NoticeOrderConsumedResponseBody;
import com.fjs.scenic.cyt.response.PayOrderResponseBody;
import com.fjs.scenic.cyt.response.Response;
import com.fjs.scenic.cyt.response.ResponseHeader;
import com.fjs.scenic.cyt.utils.AgentStandardExchangeJsonObject;
import com.fjs.scenic.cyt.utils.Base64Util;
import com.fjs.scenic.cyt.utils.EncryptUtil;
import com.fjs.scenic.cyt.utils.HttpUtil;
import com.fjs.scenic.cyt.utils.JsonUtils;
import com.fjs.scenic.cyt.utils.Md5Utils;
import com.fjs.scenic.entity.order.Orders;
import com.fjs.scenic.entity.order.PlayMan;
import com.fjs.scenic.service.ticket.OtaOrderService;
import com.fjs.scenic.ticket.config.CytConfiguration;
import com.fjs.scenic.utils.ReturnResult;

@Component
public class CytOrderServiceImpl implements OtaOrderService {

	private Logger log = LoggerFactory.getLogger(CytOrderServiceImpl.class);

	@Autowired
	protected CytConfiguration cytConfiguration;

	public String deleteOTAorder(String orderNo) throws Exception{
		
		Request request = new Request();
		// 请求体
		// --------------------获取产品信息--------------------
		CancelOrderByOTARequestBody body = new CancelOrderByOTARequestBody();
		body.setOrdercodes(orderNo);

		// 获取产品信息
		Response response = sendData(request, body, "cancelOrder");
		if (response == null) {
			System.out.println(":response-> response is null");
		}
		EditOrderStatusByOTAResponseBody getProductByOTAResponseBody = (EditOrderStatusByOTAResponseBody) response.getBody();
		System.out.println(":response-> " + JSON.toJSONString(getProductByOTAResponseBody));
		return JSON.toJSONString(getProductByOTAResponseBody);
	}
	
	public void creatOTAOrder() {
		// 请求体
		// --------------------获取产品信息--------------------
		GetProductByOTARequestBody body = new GetProductByOTARequestBody();
		body.setMethod("SINGLE"); // 仅支持SINGLE方法
		body.setCurrentPage("");
		body.setPageSize("");
		body.setResourceId("44");

		Request request = new Request();

		// 获取产品信息
		Response response = sendData(request, body, "getProductByOTA");

		if (response == null) {
			System.out.println(":response-> response is null");
			return;
		}

		GetProductByOTAResponseBody getProductByOTAResponseBody = (GetProductByOTAResponseBody) response.getBody();

		System.out.println(":response-> " + JSON.toJSONString(getProductByOTAResponseBody));
	}

	private Response sendData(Request request, RequestBody body, String method) {
		request.setBody(body);
		request.setHeader(new RequestHeader());
		request.getHeader().setApplication("tour.ectrip.com");
		request.getHeader().setBodyType(request.getBody().getClass().getSimpleName());
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		request.getHeader().setCreateTime(format.format(new Date()));
		request.getHeader().setCreateUser(cytConfiguration.getCreateUser());
		request.getHeader().setVersion("v1.0.0");
		request.getHeader().setProcessor("DataExchangeProcessor");
		request.getHeader().setSupplierIdentity("");

		JAXBContext requestJc;
		try {
			requestJc = JAXBContext.newInstance("com.fjs.scenic.cyt.request");
			Marshaller requestMarshaller = requestJc.createMarshaller();

			StringWriter sw = new StringWriter();
			requestMarshaller.marshal(request, sw);
			String requestString = sw.toString();

			System.out.println("request xml:-> " + requestString);

			requestString = Base64Util.getBASE64(requestString);

			AgentStandardExchangeJsonObject requsetJson = new AgentStandardExchangeJsonObject();
			requsetJson.setData(requestString);
			requsetJson.setSecurityType("MD5");
			requsetJson.setSigned(EncryptUtil.MD5Hex(cytConfiguration.getKey() + requestString).toUpperCase());

			String responseString = HttpUtil.httpPost(cytConfiguration.getApiUrl(), method,
					JsonUtils.marshalToString(requsetJson));

			if (null == responseString) {
				// 畅游通交互失败
				throw new Exception("response is empty");
			} else {
				System.out.println(":->response - " + responseString);
			}

			AgentStandardExchangeJsonObject responseJson = new AgentStandardExchangeJsonObject();
			try {
				responseJson = JsonUtils.unmarshalFromString(responseString, AgentStandardExchangeJsonObject.class);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				responseJson.setPlanString(responseString);
			}

			String responseData = responseJson.getData();

			if (!StringUtils.equals(EncryptUtil.MD5Hex(cytConfiguration.getKey() + responseData).toUpperCase(),
					responseJson.getSigned().toUpperCase())) {
				System.out.print("安全密文校验失败");
			}
			responseData = Base64Util.getFromBASE64(responseData);
			System.out.println("response xml:-> " + responseData);

			StringReader reader = new StringReader(responseData);
			JAXBContext responseJc = JAXBContext.newInstance("com.fjs.scenic.cyt.response");
			Unmarshaller responseUnmarshaller = responseJc.createUnmarshaller();
			Response response = (Response) responseUnmarshaller.unmarshal(reader);

			return response;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	public String getProduct() {
		Request request = new Request();
		// 请求体
		// --------------------获取产品信息--------------------
		GetProductByOTARequestBody body = new GetProductByOTARequestBody();
		body.setMethod("ALL"); // 仅支持SINGLE方法
		body.setCurrentPage("1");
		body.setPageSize("10");
		body.setResourceId("44");

		// 获取产品信息
		Response response = sendData(request, body, "getProductByOTA");
		if (response == null) {
			System.out.println(":response-> response is null");
			return ":response-> response is null";
		}
		GetProductByOTAResponseBody getProductByOTAResponseBody = (GetProductByOTAResponseBody) response.getBody();
		System.out.println(":response-> " + JSON.toJSONString(getProductByOTAResponseBody));
		return JSON.toJSONString(getProductByOTAResponseBody);
	}

	public String getOrder(String cytOrderNo) {
		Request request = new Request();
		GetOrderByOTARequestBody body = new GetOrderByOTARequestBody();
		// 畅游通生成的订单ID：
		body.setPartnerOrderId(cytOrderNo);
		Response response = sendData(request, body, "getOrderByOTA");
		if (response == null) {
			System.out.println(":response-> response is null");
			return ":response-> response is null";
		}
		GetOrderByOTAResponseBody GetOrderResponse = (GetOrderByOTAResponseBody) response.getBody();
		System.out.println(":response-> " + JSON.toJSONString(GetOrderResponse));
		return JSON.toJSONString(GetOrderResponse);
	}

	public String getProductStock() {
		Request request = new Request();
		GetProductStockByOTARequestBody body = new GetProductStockByOTARequestBody();
		body.setMethod("getProductStock");
		body.setProductId("222");
		body.setServiceProvider("222");
		body.setStime("111");
		Response response = sendData(request, body, "getProductStock");
		if (response == null) {
			System.out.println(":response-> response is null");
			return ":response-> response is null";
		}
		GetProductStockByOTAResponseBody applyOrderRefundResponse = (GetProductStockByOTAResponseBody) response
				.getBody();

		System.out.println("------------用户申请退款------------");
		System.out.println(":response-> " + JSON.toJSONString(applyOrderRefundResponse));
		return JSON.toJSONString(applyOrderRefundResponse);
	}

	@Override
	public ReturnResult checkorderInfo(Orders order, List<PlayMan> playMans, String goodsId, Integer price, int num) {
		Request request = new Request();
		// ---------------------创建订单-----------------------
		CreatePaymentOrderRequestBody body = new CreatePaymentOrderRequestBody();
		CreatePaymentOrderRequestBody.OrderInfo orderInfo = new CreatePaymentOrderRequestBody.OrderInfo();
		CreatePaymentOrderRequestBody.OrderInfo.Product product = new CreatePaymentOrderRequestBody.OrderInfo.Product();
		// 产品信息
		/*
		 * product.setResourceId("25579");// 产品ID
		 * product.setProductName("梵净山门票（成人票）");// 票名 SimpleDateFormat format =
		 * new SimpleDateFormat("yyyy-MM-dd");
		 */

		/*
		 * Calendar c = Calendar.getInstance(); c.setTime(new Date());
		 * c.add(Calendar.DAY_OF_MONTH, 1);
		 * product.setVisitDate(format.format(c.getTime()));//游览日期
		 */
		/*
		 * product.setVisitDate(format.format(new Date()));// 游览日期
		 * product.setSellPrice("2000");// 人价 单位：分
		 */
		product.setResourceId(goodsId);// 产品ID
		product.setProductName(order.getOrderName());// 票名
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		product.setVisitDate(format.format(order.getPlayTime()));// 游览日期
		product.setSellPrice(price + "");// 人价 单位：分
		// 取票人信息
		CreatePaymentOrderRequestBody.OrderInfo.ContactPerson contactPerson = new CreatePaymentOrderRequestBody.OrderInfo.ContactPerson();

		contactPerson.setName(order.getBuyUserName());
		contactPerson.setMobile(order.getBuyPhone());
		contactPerson.setCredentialsType("ID_CARD");
		contactPerson.setCredentials(order.getBuyIdCard());

		// 游客信息，根据产品的实际情况处理
		// 产品bookPersonType为CONTACT_PERSON时，person节点赋空值即可
		orderInfo.setVisitPerson(new CreatePaymentOrderRequestBody.OrderInfo.VisitPerson());

		// OTA订单ID
		orderInfo.setOrderId(UUID.randomUUID().toString());
		// 产品信息
		orderInfo.setProduct(product);
		// 取票人信息
		orderInfo.setContactPerson(contactPerson);
		// 订单数量
		orderInfo.setOrderQuantity(num + "");
		// 订单金额
		orderInfo.setOrderPrice(order.getTotelPrice() + "");
		// 订单状态
		orderInfo.setOrderStatus("PREPAY_ORDER_PRINTING");
		// o.setOrderStatus("CASHPAY_ORDER_INIT");
		body.setOrderInfo(orderInfo);

		Response response = sendData(request, body, "checkorderInfo");

		if (response == null) {
			System.out.println(":response-> response is null");
			return ReturnResult.build(500, "网络异常");
		}

		CheckCreatePaymentOrderResponseBody responseStr = (CheckCreatePaymentOrderResponseBody) response.getBody();
		if (!responseStr.getStatus().equals("200")) {
			return ReturnResult.build(500, responseStr.getMsg());
		}
		System.out.println(":response-> " + JSON.toJSONString(responseStr));
		return ReturnResult.ok();
	}

	@Override
	public String ticketNotice(String param, String method) {
		log.info(param);
		Request request = checkParam(param);
		if (request == null) {
			return null;
		}
		if ("noticeOrderConsumed".equals(method)) {// 消费通知
			return noticeOrderConsumed(request);
		} else if ("noticeOrderRefundApproveResult".equals(method)) {// ",
																		// "消息回调-退款申请结果通知"
			return noticeRefundApproveResul(request);
		} else {
			return null;
		}
	}

	private String noticeOrderConsumed(Request request) {
		// 转换参数
		NoticeOrderConsumedRequestBody consumedBody = (NoticeOrderConsumedRequestBody) request.getBody();
		log.info("消费成功通知返回consumedBody={}", JSONObject.toJSON(consumedBody));
		// 畅游通生成的订单ID
		String partnerorderId = consumedBody.getOrderInfo().getPartnerorderId();
		// 电子票消费信息
		String consumeInfo = consumedBody.getOrderInfo().getConsumeInfo();
		// 原始订票总数
		String orderQuantity = consumedBody.getOrderInfo().getOrderQuantity();
		// 累计消费票的总数
		String useQuantity = consumedBody.getOrderInfo().getUseQuantity();
		// 改变订单的业务状态

		// 封装接口的返回信息
		Response response = getInstance("noticeOrderConsumed");
		log.info("response:{}", JSONObject.toJSON(response));
		return encry(response);
	}

	/**
	 * 处理退款申请结果的业务
	 *
	 * @param request
	 * @return
	 */
	private String noticeRefundApproveResul(Request request) {
		// 转换参数
		NoticeOrderRefundApproveResultRequestBody refundResultBody = (NoticeOrderRefundApproveResultRequestBody) request
				.getBody();
		log.info("退票通知返回refundResultBody={}", JSON.toJSON(refundResultBody));
		// 畅游通生成的订单ID
		String partnerorderId = refundResultBody.getOrderInfo().getPartnerorderId();
		// 退款流水号，用于标记每一笔退款，由OTA定义
		String refundSeq = refundResultBody.getOrderInfo().getRefundSeq();
		// 原始订单票数
		String orderQuantity = refundResultBody.getOrderInfo().getOrderQuantity();
		// 退款票数
		String refundQuantity = refundResultBody.getOrderInfo().getRefundQuantity();
		// 退款结果【APPROVE：同意退款，REJECT：拒绝退款】
		String refundResult = refundResultBody.getOrderInfo().getRefundResult();
		// 退款金额
		String orderRefundPrice = refundResultBody.getOrderInfo().getOrderRefundPrice();
		// 退款手续费
		String orderRefundCharge = refundResultBody.getOrderInfo().getOrderRefundCharge();
		// 封装接口的返回信息
		Response response = getInstance("noticeOrderRefundApproveResult");
		log.info("response:{}", JSONObject.toJSON(response));
		return encry(response);
	}

	/**
	 * 封装接口返回的实体对象
	 *
	 * @param method
	 *            方法名
	 * @return
	 */
	private Response getInstance(String method) {
		// 封装接口的返回信息
		Response response = new Response();
		ResponseHeader responseHeader = new ResponseHeader();
		responseHeader.setApplication("tour.ectrip.com");
		responseHeader.setProcessor("DataExchangeProcessor");
		responseHeader.setVersion("v2.0.0");
		responseHeader.setCreateUser("[OTA]CQDY-TEST");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		responseHeader.setCreateTime(format.format(new Date()));
		responseHeader.setCode("1000");
		responseHeader.setDescribe("响应成功");
		NoticeOrderConsumedResponseBody responseMessage = new NoticeOrderConsumedResponseBody();
		if ("noticeOrderConsumed".equals(method)) {
			responseHeader.setBodyType("NoticeOrderConsumedResponseBody");
			responseMessage.setMessage("处理消费的业务成功.");
		} else if ("noticeOrderRefundApproveResult".equals(method)) {
			responseHeader.setBodyType("NoticeOrderRefundApproveResultResponseBody");
			responseMessage.setMessage("处理退订的业务成功.");
		}
		response.setHeader(responseHeader);
		response.setBody(responseMessage);
		return response;
	}

	/**
	 * 加密接口请求的参数
	 *
	 * @param request
	 * @return
	 */
	private String encry(Request request) {
		try {
			JAXBContext responseJc = JAXBContext.newInstance("com.fjs.scenic.cyt.request");
			Marshaller requestMarshaller = responseJc.createMarshaller();
			StringWriter sw = new StringWriter();
			requestMarshaller.marshal(request, sw);
			String responseString = sw.toString();
			responseString = Base64Util.getBASE64(responseString);
			AgentStandardExchangeJsonObject responseJson = new AgentStandardExchangeJsonObject();
			responseJson.setData(responseString);
			responseJson.setSecurityType("MD5");
			responseJson.setSigned(Md5Utils.MD5(cytConfiguration.getKey() + responseString).toUpperCase());
			String data = JSON.toJSONString(responseJson);
			log.info("加密的request:{}", data);
			return data;
		} catch (Exception e) {
			log.error(e.toString());
			return null;
		}
	}

	/**
	 * 加密接口返回的信息
	 *
	 * @param response
	 * @return
	 */
	private String encry(Response response) {
		try {
			JAXBContext responseJc = JAXBContext.newInstance("com.fjs.scenic.cyt.response");
			Marshaller requestMarshaller = responseJc.createMarshaller();
			StringWriter sw = new StringWriter();
			requestMarshaller.marshal(response, sw);
			String responseString = sw.toString();
			responseString = Base64Util.getBASE64(responseString);
			AgentStandardExchangeJsonObject responseJson = new AgentStandardExchangeJsonObject();
			responseJson.setData(responseString);
			responseJson.setSecurityType("MD5");
			responseJson.setSigned(Md5Utils.MD5(cytConfiguration.getKey() + responseString).toUpperCase());
			String data = JSON.toJSONString(responseJson);
			log.info("加密的response:{}", data);
			return data;
		} catch (Exception e) {
			log.error(e.toString());
			return null;
		}
	}

	/**
	 * 检查参数的合法性
	 *
	 * @param param
	 * @return 返回解析后的XML实体数据
	 */
	private Request checkParam(String param) {
		// 检验参数
		AgentStandardExchangeJsonObject paramJson = new AgentStandardExchangeJsonObject();
		try {
			paramJson = JsonUtils.unmarshalFromString(param, AgentStandardExchangeJsonObject.class);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			paramJson.setPlanString(param);
		}
		String data = paramJson.getData();
		if (!StringUtils.equals(Md5Utils.MD5(cytConfiguration.getKey() + data).toUpperCase(),
				paramJson.getSigned().toUpperCase())) {
			log.info("安全密文校验失败");
			return null;
		}
		data = Base64Util.getFromBASE64(data);
		log.info("xml:->{}", data);
		StringReader reader = new StringReader(data);
		try {
			JAXBContext requestJc = JAXBContext.newInstance("com.fjs.scenic.cyt.request");
			Unmarshaller requestUnmarshaller = requestJc.createUnmarshaller();
			Request request = (Request) requestUnmarshaller.unmarshal(reader);
			return request;
		} catch (JAXBException e) {
			log.error(e.toString());
		}
		return null;
	}

	@Override
	public ReturnResult createOrder() {
		try {
			String resourceId = "25598";
			String ProductName = "22222222222";
			String visitDate = "2019-12-25";
			Integer sellPrice = 10000;
			Integer num = 1;
			Integer totalPrice = sellPrice*num;
			Request request = new Request();
			// ---------------------创建订单-----------------------
			CreateOrderRequestBody body = new CreateOrderRequestBody();
			CreateOrderRequestBody.OrderInfo orderInfo = new CreateOrderRequestBody.OrderInfo();
			CreateOrderRequestBody.OrderInfo.Product product = new CreateOrderRequestBody.OrderInfo.Product();
			// 产品信息
			product.setResourceId(resourceId);// 产品ID
			product.setProductName(ProductName);// 票名
//			product.setVisitDate("");// 分时
			/*
			 * SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			 * product.setVisitDate(format.format(new Date()));// 游览日期
			 */
			//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			product.setVisitDate(visitDate);
			product.setSellPrice(sellPrice+"");// 人价 单位：分

			// 取票人信息
			CreateOrderRequestBody.OrderInfo.ContactPerson contactPerson = new CreateOrderRequestBody.OrderInfo.ContactPerson();
			contactPerson.setName("LWQ-cyttest");
			contactPerson.setMobile("13823122406");
			contactPerson.setCredentialsType("ID_CARD");
			contactPerson.setCredentials("360122199011201234");

			// 游客信息，根据产品的实际情况处理
			// 产品bookPersonType为CONTACT_PERSON时，person节点赋空值即可
			// orderInfo.setVisitPerson(new
			// CreateOrderRequestBody.OrderInfo.VisitPerson());

			CreateOrderRequestBody.OrderInfo.VisitPerson visitPerson = new CreateOrderRequestBody.OrderInfo.VisitPerson();
			List<CreateOrderRequestBody.OrderInfo.VisitPerson.Person> visiList = visitPerson.getPerson();
			CreateOrderRequestBody.OrderInfo.VisitPerson.Person person = new CreateOrderRequestBody.OrderInfo.VisitPerson.Person();
			person.setName("yangya");
			person.setCredentialsType("ID_CARD");
			person.setCredentials("429006199008240654");
			visiList.add(person);
			orderInfo.setVisitPerson(visitPerson);
			// OTA订单ID
			orderInfo.setOrderId(UUID.randomUUID().toString());
			// 产品信息
			orderInfo.setProduct(product);
			// 取票人信息
			orderInfo.setContactPerson(contactPerson);
			// 订单数量
			orderInfo.setOrderQuantity(num+"");
			// 订单金额
			orderInfo.setOrderPrice( totalPrice+"");
			// 订单状态
			orderInfo.setOrderStatus("PREPAY_ORDER_INIT");
			orderInfo.setSubstockId("2");
			// o.setOrderStatus("CASHPAY_ORDER_INIT");
			body.setOrderInfo(orderInfo);
			Response response = sendData(request, body, "createOrder");
			if (response == null) {
				System.out.println(":response-> response is null");
				return ReturnResult.build(500, "网络异常");
			}
			JSONObject json = (JSONObject)JSONObject.toJSON(response);
			String code = json.getJSONObject("header").getString("code");
			if(StringUtils.isBlank(code) || !code.equals("1000")){
				return ReturnResult.build(500,json.getJSONObject("header").getString("describe"));
			}
			CreateOrderResponseBody createOrderResponse = (CreateOrderResponseBody) response.getBody();
			System.out.println(":response-> " + JSON.toJSONString(createOrderResponse));
			return ReturnResult.ok(createOrderResponse.getOrderInfo());
		} catch (Exception e) {
			e.printStackTrace();
			return ReturnResult.build(500, "网络异常");
		}
	}
	
	@Override
	public ReturnResult updateOrderToPayment(String totelPrice,String pwOrderNo) {
		try {
			Request request = new Request();
			PayOrderRequestBody body = new PayOrderRequestBody();
			PayOrderRequestBody.OrderInfo orderInfo = new PayOrderRequestBody.OrderInfo();
			orderInfo.setOrderPrice(totelPrice);
			orderInfo.setOrderStatus("ORDER_RESERVE_SUCCESSFUL");
			orderInfo.setPartnerOrderId(pwOrderNo);
			//orderInfo.setSubstocktimes(order.getParkingTime());
			body.setOrderInfo(orderInfo);
			Response response = sendData(request, body, "payOrder");
			log.info("调用票务系统修改订单状态为已支付返回response={}", JSONObject.toJSONString(response));
			if (response == null) {
				return ReturnResult.error("222");
			}
			if(!response.getHeader().getCode().equals("1000")){
				log.error("调用票务系统修改订单状态为已支付失败返回errorinfo={}",response.getHeader().getDescribe());
				return ReturnResult.error(response.getHeader().getDescribe());
			}
			/*
			 * JSONObject json = (JSONObject)JSONObject.toJSON(response);
			 * if(StringUtils.isNotBlank(json.getJSONObject("header").getString(
			 * "describe"))){ return
			 * ReturnResult.build(500,json.getJSONObject("header").getString(
			 * "describe")); }
			 */
			PayOrderResponseBody applyOrderRefundResponse = (PayOrderResponseBody) response.getBody();
			if (applyOrderRefundResponse.getOrderInfo().getOrderStatus().equals("PREPAY_ORDER_PRINT_SUCCESS")) {
				return ReturnResult.ok();
			}
			// TODO 修改分销系统订单状态为已支付失败，记录异常日志
			log.error("畅游通修改订单状态为已支付异常{}", JSON.toJSONString(applyOrderRefundResponse));
			return ReturnResult.build(500, "畅游通返回订单状态不正确");
		} catch (Exception e) {
			e.printStackTrace();
			return ReturnResult.build(500, "网络异常");
		}

	}
	
	public String createPaymentOrder(String idCard,String platTime) {
		
		String resourceId = "25598";
		String productName = "22222222222";
		String visitDate = platTime;
		Integer sellPrice = 10000;
		Integer num = 1;
		Integer totalPrice = sellPrice*num;
		
		
		Request request = new Request();
		// ---------------------创建订单-----------------------
		CreatePaymentOrderRequestBody body = new CreatePaymentOrderRequestBody();
		CreatePaymentOrderRequestBody.OrderInfo orderInfo = new CreatePaymentOrderRequestBody.OrderInfo();
		CreatePaymentOrderRequestBody.OrderInfo.Product product = new CreatePaymentOrderRequestBody.OrderInfo.Product();
		// 产品信息
		product.setResourceId(resourceId);// 产品ID
		product.setProductName(productName);// 票名
		/*SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		c.add(Calendar.DAY_OF_MONTH, 1);
		product.setVisitDate(format.format(c.getTime()));*/// 游览日期
		// product.setVisitDate(format.format(new Date()));//游览日期
		product.setVisitDate(visitDate);
		product.setSellPrice(sellPrice+"");// 人价 单位：分

		// 取票人信息
		CreatePaymentOrderRequestBody.OrderInfo.ContactPerson contactPerson = new CreatePaymentOrderRequestBody.OrderInfo.ContactPerson();

		contactPerson.setName("LWQ-cyttest");
		contactPerson.setMobile("18290461556");
		contactPerson.setCredentialsType("ID_CARD");
		contactPerson.setCredentials(idCard);

		// 游客信息，根据产品的实际情况处理
		// 产品bookPersonType为CONTACT_PERSON时，person节点赋空值即可
		Map<String, String> pm = new HashMap<>();
		List<Map<String, String>> playMans = new ArrayList<>();// =
		pm.put("name", "杨亚");
		pm.put("phone", "18290461556");
		pm.put("card_no", idCard); // playManMapper.selectByPrimaryKeys(playId);
		playMans.add(pm);
		if (playMans.isEmpty() || playMans.size() < 1) {
			orderInfo.setVisitPerson(new CreatePaymentOrderRequestBody.OrderInfo.VisitPerson());
		} else {
			CreatePaymentOrderRequestBody.OrderInfo.VisitPerson visitPerson = new CreatePaymentOrderRequestBody.OrderInfo.VisitPerson();
			List<CreatePaymentOrderRequestBody.OrderInfo.VisitPerson.Person> visiList = visitPerson.getPerson();

			playMans.forEach(pms -> {
				CreatePaymentOrderRequestBody.OrderInfo.VisitPerson.Person person = new CreatePaymentOrderRequestBody.OrderInfo.VisitPerson.Person();
				person.setName(pms.get("name"));
				person.setCredentialsType("ID_CARD");
				person.setCredentials(pms.get("card_no"));
				visiList.add(person);
			});
			orderInfo.setVisitPerson(visitPerson);
		}

		// OTA订单ID
		orderInfo.setOrderId(UUID.randomUUID().toString());
		// 产品信息
		orderInfo.setProduct(product);
		// 取票人信息
		orderInfo.setContactPerson(contactPerson);
		// 订单数量
		orderInfo.setOrderQuantity(num+"");
		// 订单金额
		orderInfo.setOrderPrice(totalPrice+"");
		// 订单状态
		orderInfo.setOrderStatus("PREPAY_ORDER_PRINTING");
		// o.setOrderStatus("CASHPAY_ORDER_INIT");
		body.setOrderInfo(orderInfo);

		Response response = sendData(request, body, "createPaymentOrder");

		if (response == null) {
			System.out.println(":response-> response is null");
			return ":response-> response is null";
		}

		CreatePaymentOrderResponseBody createOrderResponse = (CreatePaymentOrderResponseBody) response.getBody();

		System.out.println(":response-> " + JSON.toJSONString(createOrderResponse));
		return JSON.toJSONString(createOrderResponse);
	}
	
	public String refundTicket(String cytOrderNo,String myOrderNo,String price) {
		Request request = new Request();
		ApplyOrderRefundByUserRequestBody body = new ApplyOrderRefundByUserRequestBody();

		ApplyOrderRefundByUserRequestBody.OrderInfo refund = new ApplyOrderRefundByUserRequestBody.OrderInfo();

		// 畅游通订单ID
		refund.setPartnerorderId(cytOrderNo);
		// 分销商退款流水号ID
		refund.setRefundSeq(myOrderNo);
		// 订单金额
		refund.setOrderPrice(price);
		// 订单票张数
		refund.setOrderQuantity("1");
		// 退订张数
		refund.setRefundQuantity("1");
		// 退订金额
		refund.setOrderRefundPrice(price);
		// 退订手续费
		refund.setOrderRefundCharge("0");
		// 退订说明
		refund.setRefundExplain("行程取消");
	/*	ApplyOrderRefundByUserRequestBody.OrderInfo.VisitPerson visitPerson = new ApplyOrderRefundByUserRequestBody.OrderInfo.VisitPerson();
		List<Person> person = visitPerson.getPerson();
		person.add(e);
		refund.setVisitPerson(value);*/

		body.setOrderInfo(refund);

		Response response = sendData(request, body, "applyOrderRefundByUser");

		if (response == null) {
			System.out.println(":response-> response is null");
			return ":response-> response is null";
		}
		ApplyOrderRefundByUserResponseBody applyOrderRefundResponse = (ApplyOrderRefundByUserResponseBody) response
				.getBody();

		System.out.println("------------用户申请退款------------");
		System.out.println(":response-> " + JSON.toJSONString(applyOrderRefundResponse));
		return JSON.toJSONString(applyOrderRefundResponse);
	}

}
