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 net.sf.json.JSONObject;

import org.apache.commons.lang3.StringEscapeUtils;
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.core.entity.order.ProbationOrder;
import com.iamberry.wechat.core.entity.product.ProductColor;
import com.iamberry.wechat.face.cart.CartService;
import com.iamberry.wechat.face.mq.EfastOrderService;
import com.iamberry.wechat.face.order.AdminOrderService;
import com.iamberry.wechat.face.order.AdminProbationOrderService;
import com.iamberry.wechat.face.porduct.ProductColorService;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.wechat.tools.HttpClient431Util;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.core.entity.admin.ShopSystemRule;

@Service
public class EfastOrderServiceImpl implements EfastOrderService {

	@Autowired
	private AdminOrderService adminOrderService;

	@Autowired
	private AdminProbationOrderService adminProbationOrderService;

	@Autowired
	private RatFWLogger logger;

	@Autowired
	private CartService cartService;

	@Autowired
	private ProductColorService productColorService;

	@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("timestamp", DateTimeUtil.format(new Date(), "yyyyMMddHHmmss"));
		requestData.put("app_act", message.getServiceOtherMessage());
		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");
			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);
				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("timestamp", DateTimeUtil.format(new Date(), "yyyyMMddHHmmss"));
		requestData.put("app_act", "efast.trade.list.get");
		requestData.put("shipping_status", "1");
		requestData.put("sd_id", NameUtils.getConfig("sd_id"));
		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) throws Exception {

		// orderInfo
		Order order = adminOrderService.getShopOrderByOrderId(message.getServiceToMessage());
		if (order == null || order.getSalesOrderid() == null) {
			return false;
		}

		List<OrderItem> items = adminOrderService.getShopOrderItemByOrderId(order.getSalesOrderid());

		//获取当前水机产品类型
		ShopSystemRule rule = adminOrderService.getReluByRid(237);

		// request url
		String url = NameUtils.getConfig("efast_base_url");

		// set Requeset Data
		Map<String, String> requestData = new HashMap<String, String>();

		int money = order.getSalesYetAmount();

		double couponMoney = 0;
		double avgPercentage = 0.0;  //均摊比例
		//将优惠券抵消金额加入实付金额中
		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:
						couponMoney = couponType.getCouponReduce();
						break;
					case 2:
						couponMoney = order.getSalesAmount() * couponType.getCouponReduce() / 100;
						break;
				}
			}
		}

		//只计算用户用微信支付的金额，不包含余额支付
		if (order.getBalancePayAmount() != null && !"".equals(order.getBalancePayAmount().toString())) {
			money = money - order.getBalancePayAmount().intValue();
			couponMoney += order.getBalancePayAmount().intValue();
		}
		//计算分摊金额比例
		if (items != null && items.size() > 0) {
			double avgMoney = 0;
			for (OrderItem item : items) {
				avgMoney += item.getItemNum().intValue() * item.getItemProductDiscount();
			}
			//计算均摊比例
			avgPercentage = 1 - couponMoney / avgMoney;
		}

		/**
		 * 系统级参数
		 */
		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 sd_id = NameUtils.getConfig("sd_id");

		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("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", order.getSalesOrderid());                                    // 订单号
		orderData.put("order_amount", (money / 100.0));                                    // 应付款,应付款金额要与已付款金额相同

		/**
		 * 产品信息
		 */
		String[] productType = null;
		if (rule != null && rule.getRuleDesc() != null) {
			String type = rule.getRuleDesc().split(":")[1];
			productType = type.split(",");
		}

		List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> filterMap = new ArrayList<Map<String, Object>>();
		boolean mapFlag = false;        //标识是否推送百胜
		boolean filterFlag = false;        //标识是否推送百胜
		int filterMoney = 0;                //除水机外的金额
		int orderItem = 0;
		int filterItem = 0;

		/**
		 * 产品信息
		 */
		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", (item.getItemProductDiscount() / 100.0 * avgPercentage * item.getItemNum()));                // 产品分摊价
			orders1.put("discount",(item.getItemProductDiscount() / 100.0));
			if (productType != null) {
				boolean productFlag = false; //用来判断当前产品是否为水机
				for (int i = 0; i < productType.length; i++) {
					if (item.getItemProductType() == Integer.parseInt(productType[i])) {
						mapFlag = true;
						productFlag = true;
					}
				}
				if (productFlag) {
					for (int i = 0; i < item.getItemNum(); i++) {
						orders1.put("goods_number", 1);
						maps.add(orders1);
					}
				} else {
					filterFlag = true;
					filterMap.add(orders1);
					filterItem += item.getItemNum();
					filterMoney += item.getItemProductDiscount() / 100 * item.getItemNum();
				}
			} else {
				maps.add(orders1);
				mapFlag = true;
			}
		}

		//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", sd_id);                                                    // 对应 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());                        // 邮编

		boolean returnFlag = true;
		//推送水机产品订单
		if (mapFlag) {
			for (int j = 0; j < maps.size(); j++) {
				Map<String, Object> map = maps.get(j);
				List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
				orderData.put("oid", order.getSalesOrderid() + j);
				orderData.put("user_name", order.getSalesOpenid() + j);
				orderData.put("goods_amount", map.get("goods_price"));
				orderData.put("money_paid", map.get("discount"));
				orderData.put("order_amount", map.get("discount"));
				orderData.put("total_amount", map.get("discount"));
				orderData.put("goods_count", map.get("goods_number"));
				mapList.add(map);
				orderData.put("orders", mapList);
				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() + j + "的订单，百胜返回信息:" + 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)) {
							returnFlag = false;
						}
					}
					logger.error(this, "add-推送订单号为:" + order.getSalesOrderid() + j + "的订单，百胜返回信息:" + result);
					//throw new Exception(respData.getString("msg"));
				} catch (Exception e) {
					//e.printStackTrace();
				}
			}
		}

		//推送除了水机以外的产品订单
		if (filterFlag) {
			orderData.put("oid", "ZP" + order.getSalesOrderid());
			orderData.put("user_name", "ZP" + order.getSalesOpenid());
			orderData.put("goods_amount", filterMoney);
			orderData.put("money_paid", filterMoney);
			orderData.put("order_amount", filterMoney);
			orderData.put("total_amount", filterMoney);
			orderData.put("goods_count", filterItem);
			orderData.put("orders", filterMap);                                                //非水机等订单产品
			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-推送订单号为:" + "ZP" +  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)) {
						returnFlag = false;
					}
				}
				logger.error(this, "add-推送订单号为:" + "ZP" +  order.getSalesOrderid() + "的订单，百胜返回信息:" + result);
				//throw new Exception(respData.getString("msg"));
			} catch (Exception e) {
				//e.printStackTrace();
			}
		}
		return returnFlag;
	}
	
	
	
	

	@Override
	public boolean addProbationOrderToEfast(MQMessage message) throws Exception {
		// TODO Auto-generated method stub
		// orderInfo
		ProbationOrder probationOrder = new ProbationOrder();
		probationOrder.setProbationOrderid(message.getServiceToMessage());
		probationOrder = adminProbationOrderService.getProbationOrderByOrderId(probationOrder);
		if (probationOrder == null || probationOrder.getProbationOrderid() == null) {
			return false;
		}
		// request url
		String url = NameUtils.getConfig("efast_base_url");
		// set Requeset Data
		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", message.getServiceOtherMessage()); // "efast.trade.new.add"
		
		/**
		 * 订单基本信息
		 */
		String [] addressDesc = probationOrder.getProbationAddressInfo().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(probationOrder.getProbationCreateTime()));		// 时间
		orderData.put("address", address);												// 收货地址
		orderData.put("city_name", addressDesc[1]); 									// 城市
		orderData.put("consignee", probationOrder.getProbationReceiveName());						// 收货人
		orderData.put("district_name", addressDesc[2]);									// 区域
		orderData.put("email", "");														// email
		orderData.put("goods_amount", (probationOrder.getProbationAmount()/100.0));					// 商品总价
		orderData.put("goods_count", 1);										// 产品数量
		orderData.put("mobile", probationOrder.getProbationReceiveTel());							// 手机号码
		orderData.put("money_paid", probationOrder.getProbationYetAmount()/100.0);										// 已付款
		orderData.put("oid", probationOrder.getProbationOrderid());									// 订单号
		orderData.put("order_amount", probationOrder.getProbationYetAmount()/100.0);									// 应付款,应付款金额要与已付款金额相同
		
		
		/**
		 * 产品信息
		 */
		List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
		Map<String, Object> orders1 = new HashMap<String, Object>();
		orders1.put("goods_name", probationOrder.getProductName());							// 产品名称
		orders1.put("goods_number", 1);									// 产品数量
		orders1.put("goods_price", (probationOrder.getProductDiscount()/100.0));					// 产品原价
		orders1.put("outer_sku", probationOrder.getProductRemark());								// 产品SKU
		orders1.put("payment_ft", probationOrder.getProbationYetAmount()/100.0);				// 产品分摊价
		maps.add(orders1);
		
		orderData.put("orders", maps);													// 订单产品
		orderData.put("pay_name", "weixinpay");											// 支付方式
		orderData.put("pay_time", DateTimeUtil.format(probationOrder.getProbationCreateTime()));// 支付时间  没有支付，传个创建时间
		orderData.put("postscript", "");						// 买家留言
		orderData.put("province_name", provinceName);									// 省份
		orderData.put("sd_id", NameUtils.getConfig("sd_id"));													// 对应 efast 店铺 id
		orderData.put("shipping_fee", 0);												// 快递费
		orderData.put("shipping_name", "02");											// 快递公司代码
		orderData.put("tel", "");											// 我司电话
		orderData.put("to_buyer", "试用订单");													// 商家备注
		orderData.put("total_amount", (probationOrder.getProbationAmount()/100.0));					// 订单总额
		orderData.put("user_name", probationOrder.getProbationOpenid());							// 买家账户   百胜根据user_name来判断是否有重复，传openId是为了防止重复
		orderData.put("zipcode", probationOrder.getProbationReceivePostnum());						// 邮编
		
		
		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-推送订单号为:" + probationOrder.getProbationOrderid() + "的订单，百胜返回信息:" + 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-推送订单号为:" + probationOrder.getProbationOrderid() + "的订单，百胜返回信息:" + result);
			throw new Exception(respData.getString("msg"));
		} catch (Exception e) {
			throw e;
		}
	}



	@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");
				
				// 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 sd_id = NameUtils.getConfig("sd_id");
				
				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", sd_id);													// 对应 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"));
		requestData.put("shipping_code", posts[0]);						// 快递代码
		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>();
		requestData.put("return_shipping_name", posts[0]);		// 退单物流代码
		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;
	}

	/**
	 * 兑换记录
	 */
	public boolean giftCard(String address, String id, Integer colorId, String addrName, String tel, String openId) throws Exception{
		Map<String, Object> orderData = new HashMap<String, Object>();
		Map<String, String> requestData = new HashMap<String, String>();
		// request url
		String url = NameUtils.getConfig("efast_base_url");
		
		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.new.add");
		
		//颜色表查询
		ProductColor productColor =	productColorService.selectProductColorById(colorId);
		
		//地址截取
		String [] addressDesc = address.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 = "重庆";
		}
		
		
		String	sd_id = NameUtils.getConfig("sd_id");
		
		orderData.put("add_time", DateTimeUtil.format(new Date()));				// 时间
		orderData.put("address", addressDesc[3]);								// 收货地址
		orderData.put("city_name", addressDesc[1]); 							// 城市
		orderData.put("consignee", addrName);									// 收货人
		orderData.put("district_name", addressDesc[2]);							// 区域
		orderData.put("email", "");												// email
		orderData.put("goods_amount", productColor.getColorDiscount() / 100);			// 商品总价
		orderData.put("goods_count", 1);										// 产品数量
		orderData.put("mobile", tel);											// 手机号码
		orderData.put("money_paid", productColor.getColorDiscount() / 100);				// 已付款
		// 兑换
		orderData.put("oid", id);		// 订单号
		orderData.put("order_amount", productColor.getColorDiscount() / 100);			// 应付款,应付款金额要与已付款金额相同
		
		
		/**
		 * 产品信息
		 */
		List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
		Map<String, Object> orders1 = new HashMap<String, Object>();
		orders1.put("goods_name", "【美国watero】净饮水一体机");	// 产品名称
		orders1.put("goods_number",1);									    	// 产品数量
		orders1.put("goods_price", productColor.getColorDiscount() / 100);				// 产品原价
		orders1.put("outer_sku", productColor.getColor69Code());				// 产品SKU
		orders1.put("payment_ft", productColor.getColorDiscount() / 100);		// 产品分摊价
		maps.add(orders1);
		
		
		orderData.put("orders", maps);													// 订单产品
		orderData.put("pay_name", "weixinpay");											// 支付方式
		orderData.put("pay_time", DateTimeUtil.format(new Date()));						// 支付时间
		orderData.put("postscript", "");												// 买家留言
		orderData.put("province_name", provinceName);									// 省份
		orderData.put("sd_id", sd_id);													// 对应 efast 店铺 id
		orderData.put("shipping_fee", 0);												// 快递费
		orderData.put("shipping_name", "yto");											// 快递公司代码
		orderData.put("tel", "");											// 我司电话
		orderData.put("to_buyer", "");													// 商家备注
		orderData.put("total_amount", productColor.getColorDiscount() / 100);					// 订单总额
		orderData.put("user_name", openId);												// 买家账户   百胜根据user_name来判断是否有重复，传openId是为了防止重复
		orderData.put("zipcode", "");													// 邮编
		
		
		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-推送订单号为:" + id + "的订单，百胜返回信息:" + 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-推送订单号为:" + id + "的订单，百胜返回信息:" + result);
			throw new Exception(respData.getString("msg"));
		} catch (Exception e) {
			throw e;
		}
	} 
}
