package com.iamberry.wechat.service.mq;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.iamberry.wechat.tools.*;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.coupon.CouponItem;
import com.iamberry.wechat.core.entity.coupon.CouponType;
import com.iamberry.wechat.core.entity.mq.MQMessage;
import com.iamberry.wechat.core.entity.order.Order;
import com.iamberry.wechat.core.entity.order.OrderItem;
import com.iamberry.wechat.face.cart.CartService;
import com.iamberry.wechat.face.mq.EfastOrderService;
import com.iamberry.wechat.face.order.AdminOrderService;

@Service
public class EfastOrderServiceImpl implements EfastOrderService {
	
	@Autowired
	private AdminOrderService adminOrderService;
	
	@Autowired
	private RatFWLogger logger;
	
	@Autowired
	private CartService cartService;

	@Autowired
	private SendMessageUtil sendMessageUtil;
	

	@Override
	public boolean selectEfastSendOrderInfo(MQMessage message) {
		// TODO Auto-generated method stub
		
		// 组装数据
		Map<String, String> requestData = new HashMap<String, String>();
		requestData.put("app_nick", NameUtils.getConfig("app_nick"));
		requestData.put("app_key", NameUtils.getConfig("app_key"));
		requestData.put("app_secret", NameUtils.getConfig("app_secret"));
		requestData.put("app_act", message.getServiceOtherMessage());
		requestData.put("timestamp",DateTimeUtil.format(new Date(),"yyyyMMddHHmmss"));
		requestData.put("oid", message.getServiceToMessage());
		requestData.put("feilds",  NameUtils.getConfig("order_field"));
		try {
			String resultJson = HttpClient431Util.doPost(requestData, NameUtils.getConfig("efast_base_url"));
			logger.info("订单号为:" + message.getServiceToMessage() + "的订单，百胜返回信息:" + resultJson);
			resultJson = StringEscapeUtils.unescapeJava(resultJson); // unicode
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(resultJson);
			if (m.find()) {
				resultJson = m.replaceAll("");
			}
			logger.info("get-订单号为:" + message.getServiceToMessage() + "的订单，百胜返回信息:" + resultJson);
			JSONObject jsonObject = JSONObject.fromObject(resultJson);
			
			// default HTTP SUCCESS
			JSONObject respData = JSONObject.fromObject(jsonObject.get("resp_data"));
			// 发货状态 : shipping_status
			String shippingStatus = respData.getString("shipping_status");

			Order orderByaddress = adminOrderService.getShopOrderByOrderId(message.getServiceToMessage());

			if ("1".equals(shippingStatus)) {
				// 更新数据:将订单从已支付、代发货状态修改为已发货状态
				Order order = new Order();
				order.setOldStatus(2); 								// 已支付、待发货 
				order.setSalesOrderid(message.getServiceToMessage());	// orderId
				order.setSalesStatus(5);								// 已发货
				order.setSalesPostFirm(respData.getString("shipping_name"));
				order.setSalesPostNum(respData.getString("invoice_no"));
				adminOrderService.updateOrderDeliver(order);

				if(orderByaddress.getSalesStatus() == 2){
					try {
						sendMessageUtil.orderSendSuccess(
								"尊敬的用户，您的订单已发货，物流信息:",
								order.getSalesOrderid(),
								SendMessageUtil.hashmap.get(respData.getString("shipping_name")),
								respData.getString("invoice_no"),
								orderByaddress.getSalesAddressInfo(),
								ResultInfo.sendRemark1,
								orderByaddress.getSalesOpenid(),
								ResultInfo.ORDER_DETAIL+order.getSalesOrderid()
						);
					} catch (Exception e) {
						logger.info("订单号："+ order.getSalesOrderid() +"的订单已发货，发送微信消息失败!");
					}
				}

				return true;
			}
			logger.error(this, "get-订单号为:" + message.getServiceToMessage() + "的订单，百胜返回信息:" + resultJson);
			return false;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error(this, "get-订单号为:" + message.getServiceToMessage() + "的订单，发生错误:" + e.getMessage());
		}
		return false;
	}
	
	

	@Override
	public JSONObject selectEfastSendOrderList() throws Exception {
		// TODO Auto-generated method stub
		java.util.Calendar rightNow = java.util.Calendar.getInstance();
        java.text.SimpleDateFormat sim = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //如果是后退几天，就写 -天数 例如：
        rightNow.add(java.util.Calendar.DAY_OF_MONTH, -60);
        //进行时间转换
        String date = sim.format(rightNow.getTime()); 
		// 组装数据
				Map<String, String> requestData = new HashMap<String, String>();
				requestData.put("app_nick", NameUtils.getConfig("app_nick"));
				requestData.put("app_key", NameUtils.getConfig("app_key"));
				requestData.put("app_secret", NameUtils.getConfig("app_secret"));
				requestData.put("app_act", "efast.trade.list.get");
				requestData.put("timestamp",DateTimeUtil.format(new Date(),"yyyyMMddHHmmss"));
				requestData.put("shipping_status", "1");
				requestData.put("sd_id", "001");
				requestData.put("start_time", date);
				requestData.put("time_type", "add");
				requestData.put("order_status", "1");
				requestData.put("page_no", "1");
				requestData.put("page_size", "100");
				try {
					String resultJson = HttpClient431Util.doPost(requestData, NameUtils.getConfig("efast_base_url"));
					resultJson = StringEscapeUtils.unescapeJava(resultJson); // unicode
					logger.info("get-百胜订单列表，百胜返回信息:" + resultJson);
					JSONObject jsonObject = JSONObject.fromObject(resultJson);
					
					// default HTTP SUCCESS
					JSONObject respData = JSONObject.fromObject(jsonObject.get("resp_data"));
					// 发货状态 : shipping_status
					logger.error(this, "get-百胜订单列表，百胜返回信息:" + resultJson);
					return respData;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					logger.error(this, "get-百胜订单列表，百胜返回信息，发生错误:" + e.getMessage());
					return null;
				}
	}



	@Override
	public boolean addOrderInfoToEfast(MQMessage message) {
		logger.info("推送订单开始，订单号："+message.getServiceToMessage());
		
		// orderInfo
		Order order = adminOrderService.getShopOrderByOrderId(message.getServiceToMessage());
		if (order == null || order.getSalesOrderid() == null) {
			return false;
		}
		
		List<OrderItem> items = adminOrderService.getShopOrderItemByOrderId(order.getSalesOrderid());
		
		// request url
		String url = NameUtils.getConfig("rst_efast_base_url");
		
		// set Requeset Data
		Map<String, String> requestData = new HashMap<String, String>();

		//总优惠
		Double couponMoney =  Double.valueOf(order.getSalesAmount() - order.getSalesYetAmount());

		//计算分摊优惠
		//R(X1) =  X1 / X1+X2+…X(n)  * reduce   订单项分摊优惠
		Integer allcouponMoney = order.getSalesAmount() - order.getSalesYetAmount();
		Integer  salesYetAmount = order.getSalesYetAmount();
		double yetAmount = order.getSalesAmount();
		for (int k=0;k<items.size();k++) {
			Double itemTotal = Double.valueOf(items.get(k).getItemTotal());
			Double itemPayMonry = itemTotal / yetAmount * couponMoney;	//在第K项使用的优惠

			Integer newItemTotal = items.get(k).getItemTotal();
			if((k+1) == items.size()){
				newItemTotal -= allcouponMoney;
			}else{
				Integer newPayMonry = (itemPayMonry.intValue()/100)*100;
				allcouponMoney = allcouponMoney - newPayMonry;	//总优惠减去 第K项使用的优惠
				newItemTotal -= newPayMonry;
			}
			items.get(k).setItemTotal(newItemTotal);
		}
		
		requestData.put("app_act", "rst.trade.new.add");

		/**
		 * 订单基本信息
		 */
		String [] addressDesc = order.getSalesAddressInfo().split("-");
		
		String address = addressDesc[3];
        if (addressDesc[3]!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(addressDesc[3]);
            if (m.find()) {
            	address = m.replaceAll("");
			}
        }
		
		String provinceName = addressDesc[0];
		if (addressDesc[0].indexOf("北京") != -1) {
			provinceName = "北京";
		} else if (addressDesc[0].indexOf("上海") != -1) {
			provinceName = "上海";
		} else if (addressDesc[0].indexOf("天津") != -1) {
			provinceName = "天津";
		} else if (addressDesc[0].indexOf("重庆") != -1) {
			provinceName = "重庆";
		}
		Map<String, Object> orderData = new HashMap<String, Object>();
		orderData.put("add_time", DateTimeUtil.format(order.getSalesCreateDate()));		// 时间
		orderData.put("address", address);										// 收货地址
		orderData.put("city_name", addressDesc[1]); 									// 城市
		orderData.put("consignee", order.getSalesAddressName());						// 收货人
		orderData.put("district_name", addressDesc[2]);									// 区域
		orderData.put("postalcode", order.getSalesAddressPostnum());     // 邮政编码
		orderData.put("email", "");														// email
		orderData.put("goods_amount", order.getSalesAmount());					// 产品总价
		orderData.put("goods_count", items.size());										// 产品数量
		orderData.put("mobile", order.getSalesAddressTel());							// 手机号码
		orderData.put("oid", order.getSalesOrderid());									// 订单号

		/**
		 * 产品信息
		 */
		List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
		for (OrderItem item : items) {
			Map<String, Object> orders1 = new HashMap<String, Object>();
			orders1.put("goods_name", item.getItemProductName());                            // 产品名称
			orders1.put("goods_number", item.getItemNum());                                    // 产品数量
			orders1.put("goods_price", (item.getItemProductPrice()));                    // 产品原价
			orders1.put("goods_discount", (item.getItemProductDiscount()));                    // 产品售价
			orders1.put("goods_total", (item.getItemTotal()));                    // 产品售价
			orders1.put("outer_sku", item.getProduectRemark());                                // 产品SKU
//			orders1.put("payment_ft", item.getItemProductDiscount());												// 产品分摊价
			maps.add(orders1);
		}
		
		orderData.put("orders", maps);													// 订单产品
		orderData.put("pay_name", "weixinpay");											// 支付方式
		if(order.getSalesTransactionDate() != null){
			orderData.put("pay_time", DateTimeUtil.format(order.getSalesTransactionDate()));// 支付时间
		}else{
			orderData.put("pay_time", "");
		}
		orderData.put("postscript", order.getSalesUserRemark());						// 买家留言
		orderData.put("province_name", provinceName);									// 省份
		orderData.put("sd_id", "001");													// 对应 efast 店铺 id
		orderData.put("shipping_fee", 0);												// 快递费
		orderData.put("shipping_name", "yto");											// 快递公司代码
		orderData.put("tel", order.getSalesAddressTel());											// 我司电话
		orderData.put("to_buyer", "");													// 商家备注
		orderData.put("user_name", order.getSalesOpenid());							// 买家账户   百胜根据user_name来判断是否有重复，传openId是为了防止重复
		orderData.put("zipcode", order.getSalesAddressPostnum());                        // 邮编
		orderData.put("total_amount", (order.getSalesAmount()));                    // 订单总额
		orderData.put("money_paid", order.getSalesYetAmount());                     // 已付款
		orderData.put("order_amount", order.getSalesYetAmount());                   // 应付款,应付款金额要与已付款金额相同
		
		
		com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();
		String orderDataStr = null;;
		try {
			orderDataStr = mapper.writeValueAsString(orderData);
		} catch (JsonProcessingException e2) {
			e2.printStackTrace();
		}
		
		requestData.put("info", orderDataStr);

		logger.info("推送订单:" + requestData);
		
		try {
			String result = HttpClient431Util.doPost(requestData, url);
			result = StringEscapeUtils.unescapeJava(result); // unicode 编码
			logger.info("add-推送订单号为:" + order.getSalesOrderid() + "的订单，RST返回信息:" + result);
			// parse JSON String to Object
			JSONObject jsonObject = JSONObject.fromObject(result);
			//JSONObject respData = JSONObject.fromObject(jsonObject.get("resp_data"));
			String oderSn = jsonObject.getString("oder_sn");
			if (oderSn != null) {
				String msg = jsonObject.getString("msg");
				if ("success".equals(msg)) {
					return true;
				}
			}
			logger.error(this, "add-推送订单失败，订单号为:" + order.getSalesOrderid() + "的订单，RST返回信息:" + result);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	

	@Override
	public boolean exchangeOrderInfoToEfast(MQMessage message) throws Exception {
		// TODO Auto-generated method stub
		// orderInfo
				Order order = adminOrderService.getShopOrderByOrderId(message.getServiceToMessage());
				if (order == null || order.getSalesOrderid() == null) {
					return false;
				}
				
				String orderId = order.getSalesOrderid() + "HH";
				
				List<OrderItem> items = adminOrderService.getShopOrderItemByOrderId(order.getSalesOrderid());
				
				// request url
//				String url = NameUtils.getConfig("efast_base_url");
				String url = NameUtils.getConfig("efast_base_url");   //到配置文件查询


				// set Requeset Data
				Map<String, String> requestData = new HashMap<String, String>();
				
				int money = order.getSalesYetAmount();
				
				if (order.getCouponId() != null && !"".equals(order.getCouponId())) {
					CouponItem couponItem = new CouponItem();
					couponItem.setCouponItemId(order.getCouponId());
					couponItem.setCouponItemUseropenid(order.getSalesOpenid());
					CouponType couponType = cartService.getCouponReduceByItemId(couponItem);
					if (null != couponType) {
						switch (couponType.getCouponType()) {
						case 1:
							money += couponType.getCouponReduce();
							break;
						case 2:
							money += order.getSalesAmount() * couponType.getCouponReduce()/100;
							break;
						}
					}
				}
				
				/**
				 * 系统级参数
				 */
				requestData.put("app_nick", NameUtils.getConfig("app_nick"));
				requestData.put("app_key", NameUtils.getConfig("app_key"));
				requestData.put("app_secret", NameUtils.getConfig("app_secret"));
				requestData.put("timestamp",DateTimeUtil.format(new Date(),"yyyyMMddHHmmss"));
				requestData.put("app_act", message.getServiceOtherMessage()); // "efast.trade.new.add"
				
				/**
				 * 订单基本信息
				 */
				String [] addressDesc = order.getSalesAddressInfo().split("-");
				String provinceName = addressDesc[0];
				if (addressDesc[0].indexOf("北京") != -1) {
					provinceName = "北京";
				} else if (addressDesc[0].indexOf("上海") != -1) {
					provinceName = "上海";
				} else if (addressDesc[0].indexOf("天津") != -1) {
					provinceName = "天津";
				} else if (addressDesc[0].indexOf("重庆") != -1) {
					provinceName = "重庆";
				}
				Map<String, Object> orderData = new HashMap<String, Object>();
				orderData.put("add_time", DateTimeUtil.format(order.getSalesCreateDate()));		// 时间
				orderData.put("address", addressDesc[3]);										// 收货地址
				orderData.put("city_name", addressDesc[1]); 									// 城市
				orderData.put("consignee", order.getSalesAddressName());						// 收货人
				orderData.put("district_name", addressDesc[2]);									// 区域
				orderData.put("email", "");														// email
				orderData.put("goods_amount", (order.getSalesAmount()/100.0));					// 产品总价
				orderData.put("goods_count", items.size());										// 产品数量
				orderData.put("mobile", order.getSalesAddressTel());							// 手机号码
				orderData.put("money_paid", (money/100.0));					// 已付款
				orderData.put("oid", orderId);									// 订单号
				orderData.put("order_amount", (order.getSalesAmount()/100.0));					// 订单金额
				
				/**
				 * 产品信息
				 */
				List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
				for (OrderItem item : items) {
					Map<String, Object> orders1 = new HashMap<String, Object>();
					orders1.put("goods_name", item.getItemProductName());							// 产品名称
					orders1.put("goods_number", item.getItemNum());									// 产品数量
					orders1.put("goods_price", (item.getItemProductPrice()/100.0));					// 产品原价
					orders1.put("outer_sku", item.getProduectRemark());										// 产品SKU
					orders1.put("payment_ft", 0.00);												// 产品分摊价
					maps.add(orders1);
				}
				
				orderData.put("orders", maps);													// 订单产品
				orderData.put("pay_name", "weixinpay");											// 支付方式
				orderData.put("pay_time", DateTimeUtil.format(order.getSalesTransactionDate()));// 支付时间
				orderData.put("postscript", order.getSalesUserRemark());						// 买家留言
				orderData.put("province_name", provinceName);									// 省份
				orderData.put("sd_id", "001");													// 对应 efast 店铺 id
				orderData.put("shipping_fee", 0);												// 快递费
				orderData.put("shipping_name", "yto");											// 快递公司代码
				orderData.put("tel", "");											// 我司电话
				orderData.put("to_buyer", "");													// 商家备注
				orderData.put("total_amount", (order.getSalesAmount()/100.0));					// 商家备注
				orderData.put("user_name", order.getSalesOpenid());							// 买家账户   百胜根据user_name来判断是否有重复，传openId是为了防止重复
				orderData.put("zipcode", order.getSalesAddressPostnum());						// 邮编
				
				
				com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();
				String orderDataStr = null;;
				try {
					orderDataStr = mapper.writeValueAsString(orderData);
				} catch (JsonProcessingException e2) {
					e2.printStackTrace();
				}
				
				requestData.put("info", orderDataStr);
				
				try {
					String result = HttpClient431Util.doGet(requestData, url);
					result = StringEscapeUtils.unescapeJava(result); // unicode 编码
					logger.info("add-推送订单号为:" + order.getSalesOrderid() + "的订单，百胜返回信息:" + result);
					// parse JSON String to Object
					JSONObject jsonObject = JSONObject.fromObject(result);
					JSONObject respData = JSONObject.fromObject(jsonObject.get("resp_data"));
					String oderSn = respData.getString("oder_sn");
					if (oderSn != null) {
						String msg = respData.getString("msg");
						if ("success".equals(msg)) {
							return true;
						}
					}
					logger.error(this, "add-推送订单号为:" + order.getSalesOrderid() + "的订单，百胜返回信息:" + result);
					throw new Exception(respData.getString("msg"));
				} catch (Exception e) {
					throw e;
				}
	}

	@Override
	public boolean sendOrderInfoToEfast(MQMessage message) throws Exception {
		// TODO Auto-generated method stub
		String[] posts = message.getServiceOtherMessage().split("-");
		// 组装数据
		Map<String, String> requestData = new HashMap<String, String>();
		requestData.put("app_nick", NameUtils.getConfig("app_nick"));
		requestData.put("app_key", NameUtils.getConfig("app_key"));
		requestData.put("app_secret", NameUtils.getConfig("app_secret"));
		requestData.put("timestamp",DateTimeUtil.format(new Date(),"yyyyMMddHHmmss"));
		requestData.put("app_act", "efast.trade.send");					// efast.trade.send
		requestData.put("oid", message.getServiceToMessage());
		requestData.put("feilds", NameUtils.getConfig("order_field"));
		String code = this.getExpressCode(posts[0]);
		requestData.put("shipping_code", code);						// 快递代码
		requestData.put("invoice_no", posts[1]);						// 快递单号
		try {
			String resultJson = HttpClient431Util.doPost(requestData, NameUtils.getConfig("efast_base_url"));
			resultJson = StringEscapeUtils.unescapeJava(resultJson); // unicode
			logger.info("send-订单号为:" + message.getServiceToMessage() + "的订单，百胜返回信息:" + resultJson);
			JSONObject jsonObject = JSONObject.fromObject(resultJson);
			
			// default HTTP SUCCESS
			JSONObject respData = JSONObject.fromObject(jsonObject.get("resp_data"));
			
			String msg = respData.getString("msg");
			if ("success".equals(msg)) {
				return true;
			}
			//当订单推送发货失败时，修改订单表状态，将已发货改为待发货状态
			Order order = new Order();
			order.setSalesOrderid(message.getServiceToMessage());
			order.setSalesStatus(2);
			order.setOldStatus(5);
			adminOrderService.updateOrderStatusByOrderId(order);
			logger.error(this, "send-订单号为:" + message.getServiceToMessage() + "的订单，百胜返回信息:" + resultJson);
			return false;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(this, "send-订单号为:" + message.getServiceToMessage() + "的订单，发生错误:" + e.getMessage());
		}
		return false;
	}


	@Override
	public boolean selectEfastReturnOrderInfo(MQMessage message)throws Exception {
		// TODO Auto-generated method stub
		if (message == null) {
			return false;
		}
		Order orderEfast = this.adminOrderService.getShopOrderByOrderId(message.getServiceToMessage());
		if (orderEfast == null) {
			return false;
		}
		if (!"8".equals(orderEfast.getSalesStatus().toString())) {
			return false;
		}
		// 百胜接口所需参数
		Map<String, String> requestData = new HashMap<String, String>();
		requestData.put("app_nick", NameUtils.getConfig("app_nick"));
		requestData.put("app_key", NameUtils.getConfig("app_key"));
		requestData.put("app_secret", NameUtils.getConfig("app_secret"));
		requestData.put("timestamp",DateTimeUtil.format(new Date(),"yyyyMMddHHmmss"));
		requestData.put("app_act", "efast.order.return.info.fetch");
		requestData.put("return_sn", orderEfast.getSalesAdminRemark());
		
		try {
			String resultJson=HttpClient431Util.doPost(requestData, NameUtils.getConfig("efast_base_url"));
			resultJson=StringEscapeUtils.unescapeJava(resultJson);
			logger.info("get-订单号为:" + message.getServiceToMessage() + "的订单，百胜返回信息:" + resultJson);
			JSONObject jsonObject=JSONObject.fromObject(resultJson);
			JSONObject respData = JSONObject.fromObject(jsonObject.get("resp_data"));
			
			String returnOrderStatus=respData.getString("return_order_status");			//退单状态
			if("1".equals(returnOrderStatus)){//1表示已确认退单
				Order order = new Order();
				order.setSalesOpenid("7");
				order.setSalesOrderid(message.getServiceToMessage());		// orderId
				order.setSalesStatus(8);									// 订单退货，关闭
				adminOrderService.updateOrderStatusByOrderIdAndToStatus(order);
				return true;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error(this, "get-订单号为:" + message.getServiceToMessage() + "的订单，发生错误:" + e.getMessage());
		}
		
		return false;
	}

	@Override
	public boolean returnOrderInfoToEfast(MQMessage message) throws Exception {
		// TODO Auto-generated method stub
		//获取订单信息
		Order order = adminOrderService.getShopOrderByOrderId(message.getServiceToMessage());
		if (order == null || order.getSalesOrderid() == null) {
			return false;
		}
		
		JSONObject jsonObj = this.getEfastOrderInfo(message);
		if (null == jsonObj) {
			return false;
		}
		String dealCode = jsonObj.getString("deal_code");
		String orderSn = jsonObj.getString("order_sn");
		
		List<OrderItem> itemList = adminOrderService.getItemsNumByOrderId(message.getServiceToMessage());
		StringBuffer detail = new StringBuffer();
		String returnDetail = "";
		if (itemList != null && itemList.size() > 1) {
			for (OrderItem orderItem : itemList) {
				detail = detail.append(orderItem.getProduectRemark() + "@" + orderItem.getItemNum() + "@" + order.getSalesYetAmount() + "@" + dealCode + ",");
			}
			returnDetail = detail.toString().substring(0, detail.toString().length() - 1);
		} else {
			OrderItem orderItem = itemList.get(0);
			detail = detail.append(orderItem.getProduectRemark() + "@" + orderItem.getItemNum() + "@" + order.getSalesYetAmount() + "@" + dealCode);
			returnDetail = detail.toString();
		}
		String[] posts = message.getServiceOtherMessage().split("-");
		// 组装数据
		Map<String, String> requestData = new HashMap<String, String>();
		String code = this.getExpressCode(posts[0]);
		requestData.put("return_shipping_name", code);		// 退单物流代码
		requestData.put("kehu_return_invoice_no", posts[1]);	// 退单物流单号
		requestData.put("return_type", "2");
		requestData.put("app_nick", NameUtils.getConfig("app_nick"));
		requestData.put("app_key", NameUtils.getConfig("app_key"));
		requestData.put("app_secret", NameUtils.getConfig("app_secret"));
		requestData.put("timestamp",DateTimeUtil.format(new Date(),"yyyyMMddHHmmss"));
		requestData.put("app_act", "efast.trade.return");
		requestData.put("order_sn", orderSn);
		requestData.put("return_shipping", "");
		requestData.put("return_pfje_fee", "");
		requestData.put("return_other_discount", "");
		requestData.put("return_pay", "2");
		requestData.put("return_reason", "");
		requestData.put("return_desc", "");
		requestData.put("return_ck", "");
		requestData.put("return_detail", returnDetail);
		try {
		String resultJson = HttpClient431Util.doPost(requestData, NameUtils.getConfig("efast_base_url"));
		resultJson = StringEscapeUtils.unescapeJava(resultJson);
		logger.info("return-订单号为:" + message.getServiceToMessage() + "的订单，百胜返回信息:" + resultJson);
		JSONObject jsonObject = JSONObject.fromObject(resultJson);
		JSONObject respData = JSONObject.fromObject(jsonObject.get("resp_data"));
		if (respData != null) {
			String returnSn = respData.getString("return_sn");
			if (returnSn != null && !"".equals(returnSn)) {
				adminOrderService.updateOrderAdminRemarkByOrderId(returnSn, message.getServiceToMessage(), null);
				return true;
			}
		}
		//当订单推送发货失败时，修改订单表状态，将已发货改为待发货状态
		Order orders = new Order();
		orders.setSalesOrderid(message.getServiceToMessage());
		orders.setSalesStatus(7);
		orders.setOldStatus(8);
		adminOrderService.updateOrderStatusByOrderId(order);
		logger.error(this, "return-订单号为:" + message.getServiceToMessage() + "的订单，百胜返回信息:" + resultJson);
		return false;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(this, "return-订单号为:" + message.getServiceToMessage() + "的订单，发生错误:" + e.getMessage());
		}
		return false;
	}
	
	//获取百盛那边的订单详细信息
	public JSONObject getEfastOrderInfo(MQMessage message) {
		// 组装数据
				Map<String, String> requestData = new HashMap<String, String>();
				requestData.put("app_nick", NameUtils.getConfig("app_nick"));
				requestData.put("app_key", NameUtils.getConfig("app_key"));
				requestData.put("app_secret", NameUtils.getConfig("app_secret"));
				requestData.put("timestamp",DateTimeUtil.format(new Date(),"yyyyMMddHHmmss"));
				requestData.put("app_act", "efast.trade.detail.get");
				requestData.put("oid", message.getServiceToMessage());
				requestData.put("feilds", NameUtils.getConfig("order_field"));
				try {
					String resultJson = HttpClient431Util.doPost(requestData, NameUtils.getConfig("efast_base_url"));
					resultJson = StringEscapeUtils.unescapeJava(resultJson); // unicode
					logger.info("get-订单号为:" + message.getServiceToMessage() + "的订单，百胜返回信息:" + resultJson);
					JSONObject jsonObject = JSONObject.fromObject(resultJson);
					
					// default HTTP SUCCESS
					JSONObject respData = JSONObject.fromObject(jsonObject.get("resp_data"));
					if (null != respData.getJSONArray("orders")) {
						return respData;
					}
				} catch (Exception e) {
					e.printStackTrace();
					logger.error(this, "get-订单号为:" + message.getServiceToMessage() + "的订单，发生错误:" + e.getMessage());
				}
				return null;
	}

	@Override
	public JSONObject getOrderFormEfast(String orderid) throws Exception {
		if(StringUtils.isEmpty(orderid)) return null;
		Map<String, String> requestData = new HashMap<String, String>();
		requestData.put("app_nick", NameUtils.getConfig("app_nick"));
		requestData.put("app_key", NameUtils.getConfig("app_key"));
		requestData.put("app_secret", NameUtils.getConfig("app_secret"));
		requestData.put("timestamp", DateTimeUtil.format(new Date(),"yyyyMMddHHmmss"));
		requestData.put("app_act", "efast.trade.detail.get");

		requestData.put("oid", orderid);
		requestData.put("feilds",NameUtils.getConfig("order_field"));   //1.order_status 订单状态:0(未确认)1(确认)2(挂起)3(作废)     2.shipping_status发货状态: 0(未发货)1(已发货,即已扫描出库)3(备货中)

		try {
			String result = HttpClient431Util.doGet(requestData, NameUtils.getConfig("efast_base_url"));
			result = StringEscapeUtils.unescapeJava(result); // unicode 编码
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(result);
			if (m.find()) {
				result = m.replaceAll("");
			}
			logger.info("rst-推送百胜订单号-->>" + orderid + "，百胜返回信息-->" + result);
			// parse JSON String to Object
			JSONObject jsonObject = JSONObject.fromObject(result);
			JSONObject respData = JSONObject.fromObject(jsonObject.get("resp_data"));
			if (respData != null) {
				return respData;
			} else {
				logger.error(this,"rst-获取百胜出错，订单号-->>" + orderid + "，百胜返回信息-->" + result);
				throw new Exception(respData.getString("msg"));
			}
		} catch (Exception e) {
			logger.error(this,"rst-获取百胜出错，订单号-->>" + orderid + "，catch");
			throw e;
		}
	}
	
	//修改物流的快递代码,修改成百盛那边可以接收的快递代码
	public String getExpressCode(String code) {
		try {
			if (null == code || "".equals(code)) {
				return "";
			}
			if ("shentong".equals(code)) {
				return "sto";
			} else if ("yuantong".equals(code)) {
				return "yto";
			} else if ("shunfeng".equals(code)) {
				return "sf";
			} else if ("longbanwuliu".equals(code)) {
				return "lbwl";
			} else {
				return "";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
}
