package com.iamberry.wechat.handles.order;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.PageBean;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.activity.ActivityDate;
import com.iamberry.wechat.core.entity.cart.*;
import com.iamberry.wechat.core.entity.coupon.*;
import com.iamberry.wechat.core.entity.eo.Promotions;
import com.iamberry.wechat.core.entity.eo.SettlementGift;
import com.iamberry.wechat.core.entity.member.Member;
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.pay.PayResult;
import com.iamberry.wechat.core.entity.product.Product;
import com.iamberry.wechat.core.entity.product.ProductColor;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.cart.CartService;
import com.iamberry.wechat.face.cart.ProductInfoService;
import com.iamberry.wechat.face.eo.SettlementGiftService;
import com.iamberry.wechat.face.coupon.CouponItemService;
import com.iamberry.wechat.face.coupon.CouponTypeService;
import com.iamberry.wechat.face.coupon.ExchangeService;
import com.iamberry.wechat.face.home.HomeService;
import com.iamberry.wechat.face.member.CashLogService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.pay.PayService;
import com.iamberry.wechat.face.porduct.ProductColorService;
import com.iamberry.wechat.face.qrcode.TemporaryQrcodeService;
import com.iamberry.wechat.face.reback.RebackServices;
import com.iamberry.wechat.handles.mq.MQServiceProxy;
import com.iamberry.wechat.sendMsg.SendMessageUtil;
import com.iamberry.wechat.service.ActivityUtil;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.OrderNOUtil;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.ValidatorUtil;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * @author 何秀刚
 * Class Description: 订单hander
 * Create Date:2016年4月20日
 * Update Date:2016年4月20日
 */
@Controller
@RequestMapping("/wechat/order")
public class OrderHandler {
	@Autowired
	private RatFWLogger logger;
	@Autowired
	private CartService cartService;
	
	@Autowired
	private HomeService homeService;
	
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private ValidatorUtil validatorUtil;
	
	@Autowired
	private PayService payService;
	
	@Autowired
	private MemberService memberService;
	@Autowired
	CouponItemService couponItemService;
	@Autowired
	ExchangeService exchangeService;
	@Autowired
	CouponTypeService couponTypeService;
	@Autowired
	CashLogService cashLogService;
	@Autowired
	private RebackServices rebackServices;
	@Autowired
	private MQServiceProxy mQservice;
	@Autowired
	private ProductInfoService productInfoService;
	@Autowired
	private TemporaryQrcodeService temporaryQrcodeService;
	@Autowired
	private ProductColorService productColorService;
	@Autowired
	private ActivityUtil activityUtil;
	@Autowired
	private SettlementGiftService settlementGiftService;
	@Autowired
	private SendMessageUtil sendMessageUtil;

	/**
	 * 支付前，调用方法
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/payBefore", method = RequestMethod.POST)
	public ResultMsg payBefore(HttpServletRequest request) {
		
		ResultMsg msg = new ResultMsg();
		msg.setResultCode(ResultInfo.ERRORCODE);

		String orderId = request.getParameter("orderId");
		if(orderId != null && !orderId.equals("")){
			Order order = new Order();
			order.setSalesOrderid(orderId);
			order = cartService.selectOrderInfoById(order);
			if(order!= null && order.getSalesSpellOrderId() != null){
				msg.setMessage(ResultInfo.spellErrorMsg);
				return msg;
			}
		}
		OrderPayDto dto = new OrderPayDto();
		// 用户信息
		Member member = WechatUtils.getUserBySession(request);
		member = memberService.getMemberByUserId(member.getUserId());
		String cartIds = request.getParameter("cartId");
		if (cartIds == null) {
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}
		cartIds.trim();
		// split 购物车ID
		String [] cartList = cartIds.split("-");
		if (cartList == null || cartList.length <= 0) {
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}
		// 转化 String 类型的购物车ID集合 --> Integer 类型的购物车集合
		Integer[] cartIntList = new Integer[cartList.length];
		for (int i = 0; i < cartList.length; i++) {
			String string = cartList[i];
			try {
				cartIntList[i] = Integer.parseInt(string);
			} catch (Exception e) {
				msg.setMessage(e.getMessage());
				return msg;
			}
		}
		if (cartIntList.length <= 0) {
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}
		// 根据购物车ID，查询数据库中对应的产品信息（ID、产品状态）
		List<CartDto> cartDtos = cartService.selectCartItemByListId(cartIntList);
		if (cartDtos == null || cartDtos.size() <= 0) {
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}

		//添加赠品
		activityUtil.preferential(cartDtos);

		// 判断当前提交的购物车ID，有多少产品在售
		int total = 0; // 支付金额
		int sum = 0; // 产品数量
		int productNum = 0;	//计算商品为滤芯的数量
		boolean disable = true;	//标识，是否可用优惠券，当购买商品只有滤芯时禁止使用优惠券
		//获取是否是拼团订单字段 1是 2否
		String isSpell = request.getParameter("isSpell");
		for (CartDto cartDto : cartDtos) {
			int subTotal = cartDto.getProductDiscount();
			if (cartDto.getProductStatus() != null && cartDto.getProductStatus().intValue() == 1) {
				if (isSpell != null && isSpell.equals("1")) {
					//是否可拼团
					if(cartDto.getProductIsSpell() != null && cartDto.getProductIsSpell().intValue() == 2){
						subTotal = cartDto.getColorSpellAmount(); // 小计 拼团价
					}else{
						subTotal = cartDto.getProductDiscount(); // 小计 正常价
					}
				}
			}
			total += cartDto.getCartNum() * subTotal;
			sum++;

			//计算商品为滤芯的数量
			if (cartDto.getProductType().intValue() == 2) {
				productNum++;
			}
		}
		
		//当购买商品只有滤芯时禁止使用优惠券
		if(productNum == cartDtos.size()) {
			disable = false;
		}
		
		if (sum <= 0) {
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}

		//未使用的优惠券
		CouponItemDto cDto = new CouponItemDto();	
		cDto.setUseropenid(member.getUserOpenid());
		cDto.setCouponUseStatus(1);
		cDto.setBeginDate(new Date());
		cDto.setPage(new PageBean());
		cDto.getPage().setPageSize(12);
		//cDto.getPage().setPageNumber(pageNO);
		List<CouponItemDto> list = couponItemService.getCouponItemDtoList(cDto);

		//整理优惠券，在下面循环中有可能会删除无法使用的优惠券
		List<CouponItemDto> couponItemDtoList = new ArrayList<>();
		for (CouponItemDto cid : list){

			if(total < cid.getCouponConsumeEnough()){
				cid.setIsCanUsed(2);
			}else{
				cid.setIsCanUsed(1);
			}

			if(3 == cid.getCouponType()){
				//判断抵扣券的是否能够使用
				Exchange exchange = new Exchange();
				exchange.setCouponId(cid.getCouponId());
				List<Exchange>  exchangeList = exchangeService.getExchangeList(exchange);
				for (Exchange ex : exchangeList){
					boolean fl = false;	//用于表示是否有兑换的产品
					for (CartDto cartDto : cartDtos) {
						Integer noColor = 0;
						for (ExchangeItem exchangeItem : ex.getExchangeItemList()){
							if(cartDto.getCartColorId().equals(exchangeItem.getColorId())){
								fl = true;
							}
						}
					}
					if(!fl){
						cid.setIsCanUsed(2);
					}
				}
			}
			couponItemDtoList.add(cid);
		}

		dto.setCouponItems(couponItemDtoList);

		dto.setUserIsVip(member.getUserIsVip());
		dto.setCartId(cartIds);// 购物车ID
		dto.setPayTotal(total); // 支付金额,单位为分
		dto.setCartItems(cartDtos); // 订单项
		dto.setSuccess(true); // 请求成功
		dto.setMeonyProportion(0);
		dto.setBalance(member.getUserIncome());
		dto.setUser38Interests(2);	//活动过期

		dto.setDisable(disable);
		
		//回显用户支付过的地址信息
		Order order=cartService.getOrderRecentAddress(member.getUserOpenid());
		if(order!=null){
			HashMap<String,String> map = new HashMap<String,String>();
			//map.put("orderId", order.getSalesOrderid());
			map.put("salesAddressName", order.getSalesAddressName());
			map.put("salesAddressInfo", order.getSalesAddressInfo());
			map.put("salesAddressTel", order.getSalesAddressTel());
			map.put("salesAddressPostnum", order.getSalesAddressPostnum());
			dto.setAddressInfo(map);
		}
		
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		msg.setData(dto);
		msg.setStatus(true);
		
		return msg;
	}
	
	/**
	 * 发起支付请求
	 * @param request 支付参数, 根据情况调整方法是否进行synchronized<br>在生成订单时不会存在安全问题
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value = "/pay", method = RequestMethod.POST)
	public ResultMsg requestPay(
			TempOrderDto temp,
			HttpServletRequest request
			)  {
		
		ResultMsg msg = new ResultMsg();
		msg.setResultCode(ResultInfo.ERRORCODE);
		//System.out.println(temp.toString());
		//当前支付时间
		Date nowDate=new Date();

		SendPayDto dto = new SendPayDto();
		dto.setSuccess(false);
		Member member = WechatUtils.getUserBySession(request); // 当前用户
		member = memberService.getMemberByUserId(member.getUserId());
		/** 数据格式校验 */
		if (member == null || member.getUserOpenid() == null) {// 校验当前用户信息是否丢失
			msg.setMessage(ResultInfo.loginOutError);
			return msg;
		}

		if("收货人".equals(temp.getOrderAddressName())){
			msg.setMessage("收货人信息有误，请重新选择地址信息！");
			return msg;
		}
		if("收货人电话".equals(temp.getOrderAddressMoblie())){
			msg.setMessage("收货人电话信息有误，请重新选择地址信息！");
			return msg;
		}
		
		member=memberService.getMemberByUserId(member.getUserId());
		if (!validatorUtil.validatorObject(temp)) { // 校验订单信息是否输入有误
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
		if (temp.getOrderUserRemark() != null && !temp.getOrderUserRemark().isEmpty()) {
			if (!(temp.getOrderUserRemark().length() >= 1 && temp.getOrderUserRemark().length() <= 100)) {
				msg.setMessage(ResultInfo.paramFormatError);
				return msg;
			}
		}
		Integer [] cartId = null;
		try {
			cartId = checkCartIdListString(temp.getCartIdStr());
		} catch (Exception e) { // 一旦发生异常，表示错误
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
		List<CartDto> cartDtos = cartService.selectCartItemByListId(cartId);
		if (cartDtos == null || cartDtos.size() <= 0) {// 根据购物车ID，查询数据库中对应的产品信息（ID、产品状态）
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}

		boolean isUse99Voucher = false;	//true:可以使用    false：不允许使用
		if(temp.getExchangeColorId() != null && !"".equals(temp.getExchangeColorId())){
			boolean flag = false;
			Integer exchangeColorId = Integer.valueOf(temp.getExchangeColorId());
			if(exchangeColorId != 0){
				for (CartDto cd : cartDtos) {
					if(cd.getCartColorId().equals(exchangeColorId)){
						cd.setCartNum(cd.getCartNum()+1);
						flag = true;
					}
				}

				if(!flag){
					ProductColor productColor = productColorService.selectProductColorById(exchangeColorId);
					CartDto cartDto = new CartDto();
					cartDto.setCartProductId(productColor.getColorProductId());
					cartDto.setCartColorId(productColor.getColorId());
					cartDto.setCartNum(1);
					cartDto.setProductName(productColor.getColorProductName());
					cartDto.setProductType(productColor.getColorProductType());	//colorProductType
					cartDto.setProductPrice(productColor.getColorDiscount());
					cartDto.setProductDiscount(productColor.getColorPrice());
					cartDto.setProductStatus(1);
					cartDto.setTotal(productColor.getColorDiscount());
					cartDto.setProductColor(productColor.getColorName());
					cartDto.setColorImg(productColor.getColorImg());
					cartDtos.add(cartDto);
					isUse99Voucher = true;
				}
			}
		}

		//根据openid查询该用户是否购买过订单
//		ShopSalesOrderDto shopSalesOrderDto = new ShopSalesOrderDto();
//		shopSalesOrderDto.setSalesOpenid(member.getUserOpenid());
//		shopSalesOrderDto.setSalesStatus("2");
//		int orderNum = cartService.selectOrderCount(shopSalesOrderDto);
		
		int total = 0; // 需要支付的总额, 单位为分

		//vip会员买年套滤芯减价，此表示为减价金额
		int priceReduction = 0;

		boolean isCludeT1ORT2 = false;	//是否包含T1/T2
		
		/** 提前准备订单项数据 */
		/** 准备数据 */
		Order order = new Order();
		order.setSalesOrderid(OrderNOUtil.createOrderCode(member.getUserId())); // 订单ID
		List<OrderItem> list = new ArrayList<OrderItem>();
		List<Integer> cartIds = new ArrayList<Integer>();

		//添加赠品
		activityUtil.preferential(cartDtos);

		for (CartDto cartDto : cartDtos) {
			//VIP用户滤芯年套减一百
			if(cartDto.getCartColorId() == 5 && member.getUserIsVip() == 2){
				priceReduction += 10000*cartDto.getCartNum();
			}

			if(7 == cartDto.getCartColorId() || 8 == cartDto.getCartColorId()){
				isCludeT1ORT2 = true;
			}
			if (cartDto.getProductStatus() != null && cartDto.getProductStatus().intValue() == 1) {
				cartIds.add(cartDto.getCartId());
				Integer subTotal = 0;
				//是否是团购订单
				if(temp.getIsSpell() != null && temp.getIsSpell() == 1){
					//是否可拼团
					if(cartDto.getProductIsSpell().intValue() == 2){
						subTotal = cartDto.getCartNum() * cartDto.getColorSpellAmount(); // 小计 拼团价
					}else{
						subTotal = cartDto.getCartNum() * cartDto.getProductDiscount(); // 小计 正常价
					}
				}else{
					subTotal = cartDto.getCartNum() * cartDto.getProductDiscount(); // 小计 正常价
				}
				total += subTotal;
				OrderItem item = new OrderItem();
				item.setItemNum(cartDto.getCartNum());
				item.setItemProductDiscount(cartDto.getProductDiscount());
				item.setItemProductId(cartDto.getCartProductId());
				item.setItemProductName(cartDto.getProductName());
				item.setItemProductPic(cartDto.getColorImg());
				item.setItemSalesOrderid(order.getSalesOrderid());
				item.setItemTotal(subTotal);
				item.setItemProductType(cartDto.getProductType());
				item.setItemProductPrice(cartDto.getProductPrice());
				item.setItemColorId(cartDto.getCartColorId());
				item.setItemGiftList(cartDto.getItemGiftList());
				list.add(item);
			}
		}

		//是否是团购订单
		if(temp.getIsSpell() != null && temp.getIsSpell() == 1){
			order.setSalesIsSpellOrder(1);//团购订单
		}else{
			order.setSalesIsSpellOrder(2);
		}
		//是否是被邀请人支付（完成拼单）
		if(temp.getSpellOrderId() != null && !temp.getSpellOrderId().equals("")){
			order.setSalesSpellOrderId(temp.getSpellOrderId());
		}
		// 准备订单对象
		order.setSalesOpenid(member.getUserOpenid()); // openid 
		order.setSalesAmount(total); // 订单金额

		int mustPay=0;
		
		String couponId=temp.getCouponId();
		CouponItemDto couponItemDto=new CouponItemDto();
		CouponItem couponItem=new CouponItem();
		boolean hasCoupon=false;
		//获取优惠券不为空
		if(couponId!=null && !couponId.equals("")){
			hasCoupon=true;
			//查询优惠券，获取对应的金额
			couponItemDto = couponItemService.getCouponItemById(couponId);
			couponItem.setCouponId(couponItemDto.getCouponId());
			couponItem.setCouponItemId(couponItemDto.getCouponItemId());
			couponItem.setCouponItemRemark(couponItemDto.getCouponItemRemark());
			couponItem.setCouponItemUseropenid(couponItemDto.getUseropenid());
			couponItem.setCouponUseEndDate(couponItemDto.getCouponUseEndDate());
			couponItem.setCouponUseDate(couponItemDto.getCouponUseDate());
			
			if(null==couponItemDto || !couponItemDto.getUseropenid().equals(member.getUserOpenid()) || couponItemDto.getCouponUseStatus()!=1){
				msg.setMessage(ResultInfo.COUPON_INVALID); //优惠券无效
				return msg;
			}
			if(couponItem.getCouponUseEndDate().getTime()<nowDate.getTime()){
				msg.setMessage(ResultInfo.COUPON_OUTOFDATE); //优惠券过期
				return msg;
			}
			
			//消费达到指定额度
			CouponType couponType = couponTypeService.getCouponTypeById(couponItemDto.getCouponId());
			if(couponType.getCouponConsumeEnough()>total){
				msg.setMessage(ResultInfo.COUPON_CONSUME_NO_ENOUGH); //消费额度不足
				return msg;
			}

			if(3 == couponType.getCouponType()){
				if(couponType.getCouponId() == 10001){
					if(!isCludeT1ORT2){
						msg.setMessage(ResultInfo.COUPON_T1_T2_NO_MSG); //未购买指定商品
						return msg;
					}
				}else if(couponType.getCouponId() == 10000){
					//判断抵扣券的是否能够使用
					Exchange exchange = new Exchange();
					exchange.setCouponId(couponType.getCouponId());
					List<Exchange>  exchangeList = exchangeService.getExchangeList(exchange);
					boolean fl = false;
					for (Exchange ex : exchangeList){
						for (ExchangeItem exchangeItem : ex.getExchangeItemList()){
							for (CartDto cartDto : cartDtos) {
								if(cartDto.getCartColorId().equals(exchangeItem.getColorId())){
									fl = true;
								}
							}
						}
						if(fl){
							break;
						}
					}
					if(!fl){
						msg.setMessage(ResultInfo.COUPON_NO_MEET_DEMAND); //消费没有达到需求
						return msg;
					}
				}
			}

			//优惠券的类型，是直接减免额度 还是折扣价
			if(couponType.getCouponType()==1){
				total=total-couponType.getCouponReduce();
			}else if(couponType.getCouponType()==2){
				total=total*couponType.getCouponReduce()/100;
			}else if(couponType.getCouponType()==3){
				total=total-couponType.getCouponReduce();
			}
		}

		// 套装减去100元
		total -= priceReduction;

		if(total==0 || total<0){
			total=0;
			mustPay=0;
		}else{
			mustPay=total;
		}
		
		//获取账户余额，判断是否在可用范围内
		int balancePayAmount=temp.getBalancePayAmount();
		if(balancePayAmount>0 && member.getUserIncome()>balancePayAmount){
			mustPay=total-temp.getBalancePayAmount()>0?total-temp.getBalancePayAmount():0;
		}else if(balancePayAmount>0 && member.getUserIncome()<balancePayAmount){
			msg.setMessage(ResultInfo.NO_ENOUGH_FOR_PAY);
			return msg;
		}
		
		order.setSalesYetAmount(total);
		order.setSalesRateAmount(0);
		order.setSalesIntegralNum(temp.getOrderIntegralNum()); // 订单使用积分
		order.setSalesCreateDate(new Date()); // 创建时间
		order.setBalancePayAmount(temp.getBalancePayAmount()); //账户余额支付金额
		order.setCouponId(couponId);   //优惠券id

		order.setSalesStatus(1); // 待支付订单
		order.setSalesTransactionDate(nowDate);  //事务时间
		order.setSalesTransactionId("8990"+nowDate.getTime());
		order.setSalesAddressInfo(temp.getOrderAddressInfo()); // 收货地址
		order.setSalesAddressName(temp.getOrderAddressName()); // 收货人
		order.setSalesAddressTel(temp.getOrderAddressMoblie()); // 收入联系方式
		order.setSalesAddressPostnum(temp.getOrderAddressPostNum()); // 物流编号
		order.setSalesUserRemark(temp.getOrderUserRemark()); // 用户备注
		// 保存
		boolean flag = false;
		try {
			flag = cartService.addOrderAndSaveOrderItem(order, list, cartIds);
//System.out.println("====插入订单列表信息===="+flag);
			//修改优惠券状态为临时状态
			if(hasCoupon){
				couponItem.setCouponUseStatus(7);
				couponItemService.updateCouponItemById(couponItem);
			}
		} catch (Exception e) {
			flag = false;
			System.out.println("====插入订单列表信息失败====");
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
		
		boolean updateFlase=false;
		if (flag && mustPay>0) {
			// 发起支付
			PayResult result = payService.requestPay(order.getSalesOpenid(), order.getSalesOrderid(), mustPay, list.get(0).getItemProductName() + "...", NameUtils.getConfig("WECHAT_ORDER_BACK"));
			if (result.isPaySuccess()) {
				dto.setInfo(result.getPayData());
				dto.setSuccess(true);
				dto.setOrderId(order.getSalesOrderid());
				updateFlase=false;
			} else {
				dto.setInfo(result.getPayData());
				dto.setOrderId(order.getSalesOrderid());
				msg.setResultCode(ResultInfo.ERRORCODE);
				msg.setMessage(NameUtils.getConfig("ERRORINFO"));
				msg.setData(dto);
				msg.setStatus(false);
				return msg;
			}
		} else if(flag && mustPay==0){
			dto.setInfo("isOK");
			dto.setSuccess(true);
			dto.setOrderId(order.getSalesOrderid());
			updateFlase=true;
		}else{
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
	
		if(updateFlase){
			//设置订单状态，还有优惠券id

			if(temp.getIsSpell() == 1){//如果是团购订单则状态改为正在团购
				order.setSalesStatus(15);
			}else{
				order.setSalesStatus(2);
			}
			cartService.updateOrderStatus(order);
			//修改优惠券状态
			if(hasCoupon){
				couponItem.setCouponUseStatus(2);
//				int i=couponItemService.updateCouponItemById(couponItem);
			}

			if(temp.getIsSpell() == null || temp.getIsSpell() == 2){//如果是团购订单则暂时不推送订单，在完成拼单后再推送
				/*if(o.getSalesIsSpellOrder() != null && o.getSalesIsSpellOrder() == 1 && o.getSalesSpellOrderId() != null){*/
				// 给rst推送订单
				try {
					MQMessage message = new MQMessage();
					message.setServiceToMessage(order.getSalesOrderid());
					message.setServiceOtherMessage("efast.trade.new.add");
					message.setServiceIsSend(2);			// 没有推送的信息
					message.setServiceStatus(1); 			// 推送成功
					message.setServiceType(1); 				// 添加订单信息
					message.setServiceHandlerObjectName("efastOrderServiceImpl");
					message.setServiceHandlerMethodName("addOrderInfoToEfast");
					mQservice.insertMQMessage(message);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}


			//更新账户余额
//			if(balancePayAmount>0){
//				member.setUserIncome(-balancePayAmount);
//				memberService.updateUserIncomeByOpenId(member);
//
//				//修改用户购买记录为已购买
//				memberService.updateIsBaughtByOpenid(member.getUserOpenid(), 2);
//				//更新用户绑定状态
//				if (member.getUserIsFlag()!= null && member.getUserIsFlag() == 1) {
//					member.setUserIsFlag(2);//终身绑定
//					homeService.updateMemberIsFlagByOpenid(member);
//				}
//				try {
//					temporaryQrcodeService.applyTempQrcode(member.getUserOpenid());//为用户生成二维码
//				} catch (Exception e) {
//					System.out.println("为用户生成二维码失败!");
//				}
//
//				//现金使用记录
//				CashLog log=new CashLog();
//				log.setCashLogsIntroduction("订单支出");
//				log.setCashLogsNum(balancePayAmount);
//				log.setCashLogsOpenid(member.getUserOpenid());
//				log.setCashLogsType(2);
//				log.setCashLogsResType(3);
//				log.setCashLogsOrderid(order.getSalesOrderid());
//				log.setCashLogsCreateDate(nowDate);
//				cashLogService.addCashLog(log);
//
//			}
//			rebackServices.loadSingleOrderReward(order);
			productInfoService.updateProductNumList(order.getSalesOrderid());

			/**
			 * 修改拼单信息并推送
			 */
			if(temp.getSpellOrderId() != null && !temp.getSpellOrderId().equals("")){
				//邀请人订单修改
				Order or1 = new Order();
				or1.setSalesOrderid(temp.getSpellOrderId());
				or1.setSalesStatus(2);
				or1.setSalesSpellOrderId(order.getSalesOrderid());
				cartService.updateOrderSpellOrderId(or1);//修改状态为已支付，待发货，关联拼单订单id
				//邀请人信息state
				Order orderOne = new Order();
				orderOne.setSalesOrderid(temp.getSpellOrderId());
				orderOne = cartService.selectOrderInfoById(orderOne);
				List<ShopOrderItemDto> orderItems1 = cartService.selectShopOrderItem(temp.getSpellOrderId());
				//邀请人信息end
				//被邀请人信息state
				Order orderTwo = new Order();
				orderTwo.setSalesOrderid(order.getSalesOrderid());
				orderTwo = cartService.selectOrderInfoById(orderTwo);
				List<ShopOrderItemDto> orderItems2 = cartService.selectShopOrderItem(order.getSalesOrderid());
				//被邀请人信息end
				if(orderOne.getSalesOpenid() != null){
				Member	memberOne = memberService.getMemberByUserOpenId(orderTwo.getSalesOpenid());
				String name = "我";
				if(memberOne != null && !memberOne.getUserNickname().equals("")){
					try {
						name = URLDecoder.decode(memberOne.getUserNickname(),"UTF-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
					String names = name +",微信好友";

					try {
						names  = name +","+(member.getUserNickname() == null? "微信好友": URLDecoder.decode(member.getUserNickname(),"UTF-8"));
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				//推送微信模板消息
					logger.info("微信账户支付推送拼单成功消息-------------------------------------------------1");
					try {
						sendMessageUtil.spellPush(
								"恭喜您与"+name+"拼单成功，点击逛逛更多好货吧。",
								orderItems1.get(0).getItemProductName(),
								names,
								"点击查看拼单详情>>",
								orderOne.getSalesOpenid(),
								ResultInfo.ORDER_GUOQI+"?salesStatus=2");
					}catch (Exception e){
						logger.info("推送拼单成功消息失败，失败openId："+orderOne.getSalesOpenid());
						e.printStackTrace();
					}
				}
				//推送邀请人订单到rst
				try {
					MQMessage message = new MQMessage();
					message.setServiceToMessage(temp.getSpellOrderId());
					message.setServiceOtherMessage("efast.trade.new.add");
					message.setServiceIsSend(2);			// 没有推送的信息
					message.setServiceStatus(1); 			// 推送成功
					message.setServiceType(1); 				// 添加订单信息
					message.setServiceHandlerObjectName("efastOrderServiceImpl");
					message.setServiceHandlerMethodName("addOrderInfoToEfast");
					mQservice.insertMQMessage(message);
				} catch (Exception e) {
					e.printStackTrace();
				}





				//被邀请人（当前）订单修改
				Order or2 = new Order();
				or2.setSalesOrderid(order.getSalesOrderid());
				or2.setSalesStatus(2);
				or2.setSalesSpellOrderId(temp.getSpellOrderId());
				cartService.updateOrderSpellOrderId(or2);

				if(orderTwo.getSalesOpenid() != null){
					Member	memberOne = memberService.getMemberByUserOpenId(orderOne.getSalesOpenid());
					String name = "微信好友";
					if(memberOne != null && !memberOne.getUserNickname().equals("")){
						try {
							name = URLDecoder.decode(memberOne.getUserNickname(),"UTF-8");
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
					}
					String names  = member.getUserNickname() == null? "我": member.getUserNickname() +","+name;
					try {
						names  = member.getUserNickname() == null? "我": URLDecoder.decode(member.getUserNickname(),"UTF-8") +","+name;
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					//推送微信模板消息
					logger.info("微信账户支付推送拼单成功消息-------------------------------------------------2");
					try {
						sendMessageUtil.spellPush(
								"恭喜您与"+name+"拼单成功，点击逛逛更多好货吧。",
								orderItems2.get(0).getItemProductName(),
								names,
								"点击查看拼单详情>>",
								orderTwo.getSalesOpenid(),
								ResultInfo.ORDER_GUOQI+"?salesStatus=2");
					}catch (Exception e){
						logger.info("推送拼单成功消息失败，失败openId："+orderTwo.getSalesOpenid());
						e.printStackTrace();
					}
				}
				//推送被邀请人订单到rst
				try {
					MQMessage message = new MQMessage();
					message.setServiceToMessage(order.getSalesOrderid());
					message.setServiceOtherMessage("efast.trade.new.add");
					message.setServiceIsSend(2);			// 没有推送的信息
					message.setServiceStatus(1); 			// 推送成功
					message.setServiceType(1); 				// 添加订单信息
					message.setServiceHandlerObjectName("efastOrderServiceImpl");
					message.setServiceHandlerMethodName("addOrderInfoToEfast");
					mQservice.insertMQMessage(message);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}

		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		dto.setOrderId(order.getSalesOrderid());
		msg.setData(dto);
		msg.setStatus(true);
		
		return msg;
	}
	
	/**
	 * 校验订单状态，判断是否支付成功
	 * @param orderId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/checkOrderPaySuccess")
	public ResultMsg checkOrderPaySuccess(
			@RequestParam(value = "orderId") String orderId) {
		ResultMsg msg = new ResultMsg();
		msg.setResultCode(ResultInfo.ERRORCODE);
		Integer orderStatus = cartService.selectOrderStatusByOrderId(orderId);
		if (orderStatus != null && (orderStatus.intValue() == 2 || orderStatus.intValue() == 15) ) {
			msg.setResultCode(ResultInfo.SUCCESSCODE);
			msg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			msg.setStatus(true);
			return msg;
		}
		msg.setResultCode(ResultInfo.ERRORCODE);
		msg.setMessage(NameUtils.getConfig("ERRORINFO"));
		msg.setStatus(false);
		
		return msg;
	}

	@RequestMapping("/paySuccess")
	public void paySuccess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher(NameUtils.getConfig("WECHAT_SHOP_ORDER_PAY_SUCCESS")).forward(request, response);
	}
	
	@RequestMapping(value = "/getOrderInfo", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg getOrderInfoByOrderId(
			HttpServletRequest request,
			@RequestParam(value = "orderId") String orderId) throws Exception {
		ResultMsg msg = new ResultMsg();
		msg.setResultCode(ResultInfo.ERRORCODE);

		Member member = WechatUtils.getUserBySession(request); // 当前用户
		Order order = new Order();
		order.setSalesOrderid(orderId);
		order.setSalesOpenid(member.getUserOpenid());
		order = cartService.selectOrderInfoById(order);
		
		if (order == null || order.getSalesStatus() != 2) {
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
		
		msg.setData(order);
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		msg.setStatus(true);
		return msg;
	}
	
	/**
	 * 校验一个购物车字符串
	 * @param cartIds 购物车ID字符串
	 * @return
	 * @throws Exception 
	 */
	public Integer[] checkCartIdListString(String cartIds) throws Exception {
		if (cartIds == null) {
			throw new Exception(ResultInfo.paramFormatError);
		}
		cartIds.trim();
		// split 购物车ID
		String [] cartList = cartIds.split("-");
		if (cartList == null || cartList.length <= 0) {
			throw new Exception(ResultInfo.paramFormatError);
		}
		// 转化 String 类型的购物车ID集合 --> Integer 类型的购物车集合
		Integer[] cartIntList = new Integer[cartList.length];
		for (int i = 0; i < cartList.length; i++) {
			String string = cartList[i];
			try {
				cartIntList[i] = Integer.parseInt(string);
			} catch (Exception e) {
				throw new Exception(ResultInfo.paramFormatError);
			}
		}
		if (cartIntList.length <= 0) {
			throw new Exception(ResultInfo.paramFormatError);
		}
		return cartIntList;
	}



}