package com.iamberry.wechat.handles.order;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iamberry.wechat.core.entity.product.SalesUserGift;
import com.iamberry.wechat.tools.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

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.cart.CartDto;
import com.iamberry.wechat.core.entity.cart.OrderPayDto;
import com.iamberry.wechat.core.entity.cart.SendPayDto;
import com.iamberry.wechat.core.entity.cart.TempOrderDto;
import com.iamberry.wechat.core.entity.coupon.CouponItem;
import com.iamberry.wechat.core.entity.coupon.CouponItemDto;
import com.iamberry.wechat.core.entity.coupon.CouponType;
import com.iamberry.wechat.core.entity.member.CashLog;
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.face.admin.SystemService;
import com.iamberry.wechat.face.cart.CartService;
import com.iamberry.wechat.face.cart.ProductInfoService;
import com.iamberry.wechat.face.coupon.CouponItemService;
import com.iamberry.wechat.face.coupon.CouponTypeService;
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.reback.RebackServices;
import com.iamberry.wechat.handles.mq.MQServiceProxy;

/**
 * @author 何秀刚
 * Class Description: 订单hander
 * Create Date:2016年4月20日
 * Update Date:2016年4月20日
 */
@Controller
@RequestMapping("/wechat/order")
public class OrderHandler {
	
	@Autowired
	private CartService cartService;
	
	@Autowired
	private WechatUtils wechatUtils;
	
	@Autowired
	private HomeService homeService;
	
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private ValidatorUtil validatorUtil;
	
	@Autowired
	private OrderNOUtil orderNOUtil;
	
	@Autowired
	private PayService payService;
	
	@Autowired
	private MemberService memberService;
	@Autowired
	CouponItemService couponItemService;
	@Autowired
	CouponTypeService couponTypeService;
	@Autowired
	CashLogService cashLogService;
	@Autowired
	private RebackServices rebackServices;
	@Autowired
	private MQServiceProxy mQservice;
	@Autowired
	private ProductInfoService productInfoService;
	
	/**
	 * 支付前，调用方法
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/payBefore", method = RequestMethod.POST)
	public ResultMsg payBefore(HttpServletRequest request) throws Exception {
		
		ResultMsg msg = new ResultMsg();
		msg.setResultCode(ResultInfo.ERRORCODE);
		
		OrderPayDto dto = new OrderPayDto();
		// 用户信息
		Member member = wechatUtils.getUserBySession(request);
		if (member == null || member.getUserOpenid() == null) {
			msg.setMessage(ResultInfo.loginOutError);
			return msg;
		}
		member=memberService.getMemberByUserId(member.getUserId());
		String cartIds = request.getParameter("cartIds");
		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.listCartByIds(cartIntList);
		if (cartDtos == null || cartDtos.size() <= 0) {
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}
		// 判断当前提交的购物车ID，有多少产品在售
		int total = 0; // 支付金额
		int sum = 0; // 产品数量
		
		List<CartDto> tempCarts = new ArrayList<CartDto>();
		for (CartDto cartDto : cartDtos) {
			switch (cartDto.getCartIsSource()) {
				case 1:
					cartDto = cartService.selectCartProductColor(cartDto);
					break;
				case 2:
					cartDto = cartService.getCartProductFitting(cartDto);
			}
			if (cartDto.getProductStatus() != null && cartDto.getProductStatus().intValue() == 1) {
				total += cartDto.getCartNum() * cartDto.getProductPrice();
				sum++;
				//查询产品赠品信息
				List<SalesUserGift> giftList = cartService.listGift(cartDto.getCartColorId());
				cartDto.setSalesUserGiftList(giftList);
				tempCarts.add(cartDto);
			}

		}
		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);
		
		dto.setCouponItems(list);
		
		request.getSession().setAttribute("cartIds", cartIds);
		dto.setCartId(cartIds);// 购物车ID
		dto.setPayTotal(total); // 支付金额,单位为分
		dto.setCartItems(tempCarts); // 订单项
		dto.setSuccess(true); // 请求成功
//		dto.setUserIntegral(homeService.selectUserIntegralByOpenid(member.getUserOpenid()));// 用户积分
//		dto.setMeonyProportion(systemService.selectOneShopRuleById(13).getRuleNum().intValue()); // 1积分=?分钱
		dto.setUserIntegral(0);
		dto.setMeonyProportion(0);
		dto.setBalance(member.getUserIncome());
		
		Order order=cartService.getOrderRecentAddress(member.getUserOpenid());
		
		if(order!=null){
			HashMap<String,String> map=new HashMap();
			//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(ResultInfo.SUCCESSINFO);
		msg.setData(dto);
		msg.setStatus(true);
		
		return msg;
	}
	
	/**
	 * 发起支付请求
	 * @param dto 支付参数, 根据情况调整方法是否进行synchronized<br>在生成订单时不会存在安全问题
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value = "/pay", method = RequestMethod.POST)
	public ResultMsg requestPay(
			TempOrderDto temp,
			HttpServletRequest request
			) throws Exception {
		
		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); // 当前用户
		/** 数据格式校验 */
		if (member == null || member.getUserOpenid() == null) {// 校验当前用户信息是否丢失
			msg.setMessage(ResultInfo.loginOutError);
			return msg;
		}
		
		member=memberService.getMemberByUserId(member.getUserId());
		if (!validatorUtil.validatorObject(temp)) { // 校验订单信息是否输入有误
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
		if (temp.getOrderUserRemark() != null && !temp.getOrderUserRemark().isEmpty()) {
			Pattern pattern = Pattern.compile("^[\u4e00-\u9fa5_a-zA-Z0-9]+$");
			if (!pattern.matcher(temp.getOrderUserRemark()).find()) {
				msg.setMessage(ResultInfo.paramFormatError);
				return msg;
			}
			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;
		}
		/** 数据逻辑校验 */
		/*Integer inputIntegral = 0; 
		Integer userIntegral = homeService.selectUserIntegralByOpenid(member.getUserOpenid());
		if (inputIntegral > userIntegral) {// 输入积分不能大于用户可用积分
			msg.setMessage(ResultInfo.integralOutError);
			return msg;
		}*/
		List<CartDto> cartDtos = cartService.listCartByIds(cartId);
		if (cartDtos == null || cartDtos.size() <= 0) {// 根据购物车ID，查询数据库中对应的产品信息（ID、产品状态）
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}
		int ruleNum = systemService.selectOneShopRuleById(13).getRuleNum().intValue(); // 积分和金额比例 : 1积分=?分钱
		int total = 0; // 需要支付的总额, 单位为分
		/** 提前准备订单项数据 */
		/** 准备数据 */
		Order order = new Order();
		order.setSalesOrderid(orderNOUtil.createOrderCode(member.getUserId())); // 订单ID
		List<OrderItem> list = new ArrayList<OrderItem>();
		List<Integer> cartIds = new ArrayList<Integer>();
		
		for (CartDto cartDto : cartDtos) {
			//判断购买产品是产品还是配件
			switch (cartDto.getCartIsSource()) {
				case 1:
					cartDto = cartService.selectCartProductColor(cartDto);
					break;
				case 2:
					cartDto = cartService.getCartProductFitting(cartDto);
			}
			if (cartDto.getProductStatus() != null && cartDto.getProductStatus().intValue() == 1) {
				cartIds.add(cartDto.getCartId());
				Integer subTotal = cartDto.getCartNum() * cartDto.getProductPrice(); // 小计
				total += subTotal;
				OrderItem item = new OrderItem();
				item.setItemNum(cartDto.getCartNum());
				item.setItemProductDiscount(cartDto.getProductPrice());
				item.setItemProductId(cartDto.getCartProductId());
				item.setItemProductName(cartDto.getProductName());
				item.setItemProductPic(cartDto.getProductIntroduceImg());
				item.setItemSalesOrderid(order.getSalesOrderid());
				item.setItemTotal(subTotal);
				item.setItemProductPrice(cartDto.getProductDiscount());
				item.setItemColorId(cartDto.getCartColorId());
				item.setItemProductColor(cartDto.getProductColor());
				item.setItemProductChildType(cartDto.getProductChildType());
				item.setItemIsSource(cartDto.getCartIsSource());
				list.add(item);
			}
			//查询产品赠品信息
			List<SalesUserGift> giftList = cartService.listGift(cartDto.getCartColorId());
			if (giftList != null && giftList.size() > 0) {
				for (SalesUserGift gift : giftList) {
					OrderItem item = new OrderItem();
					item.setItemNum(gift.getUserGiftCount());
					item.setItemProductDiscount(0);
					item.setItemProductId(gift.getUserProductId());
					item.setItemProductName(gift.getGiftName());
					item.setItemProductPic(gift.getGiftProductPic());
					item.setItemSalesOrderid(order.getSalesOrderid());
					item.setItemTotal(0);
					item.setItemProductPrice(0);
					item.setItemColorId(gift.getUserColorId());
					item.setItemProductColor(gift.getGiftColorName());
					item.setItemProductChildType(gift.getGiftChildType());
					item.setItemIsSource(1);
					item.setItemGiftSource(cartDto.getCartColorId());
					list.add(item);
				}
			}
		}
		
		// 准备订单对象
		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());
//System.out.println(couponType.getCouponConsumeEnough()+"================"+total);
			if(couponType.getCouponConsumeEnough()>total){
//System.out.println("==========未达到消费额！");
				msg.setMessage(ResultInfo.COUPON_CONSUME_NO_ENOUGH); //消费额度不足
				return msg;
			}
			//优惠券的类型，是直接减免额度 还是折扣价 
			if(couponType.getCouponType()==1){
				total=total-couponType.getCouponReduce();
			}else if(couponType.getCouponType()==2){
				total=total*couponType.getCouponReduce()/100;
			}
		
		}
		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;
		}
		
//System.out.println("====mustPay===="+mustPay+"totalMoney======"+total);
		
		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) {
		//if (flag) {
			// 发起支付
			//PayResult result = payService.requestPay(order.getSalesOpenid(), order.getSalesOrderid(), order.getSalesYetAmount(), list.get(0).getItemProductName() + "...", NameUtils.WECHAT_ORDER_BACK);
			PayResult result = payService.requestPay(order.getSalesOpenid(), order.getSalesOrderid(), mustPay, list.get(0).getItemProductName() + "...", NameUtils.WECHAT_ORDER_BACK);
//System.out.println("====================支付"+result.isPaySuccess()+"。====================");
			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(ResultInfo.ERRORINFO);
				msg.setData(dto);
				msg.setStatus(false);
//System.out.println("====================支付失败了。====================");
				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
			order.setSalesStatus(2);
			//cartService.updateOrderByOrderId(order);
			cartService.updateOrderStatus(order);
			//修改优惠券状态
			if(hasCoupon){
				couponItem.setCouponUseStatus(2);
				int i=couponItemService.updateCouponItemById(couponItem);
//System.out.println("================================更新优惠券状态"+i);
			}
				
			//更新账户余额
			if(balancePayAmount>0){
				member.setUserIncome(-balancePayAmount);
				memberService.updateUserIncomeByOpenId(member);
				
				//现金使用记录
				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());
			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) {
				// TODO: handle exception
			}
			
		}
		
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setMessage(ResultInfo.SUCCESSINFO);
		dto.setOrderId(order.getSalesOrderid());
		msg.setData(dto);
		msg.setStatus(true);
//System.out.println("====================支付完成了。====================");
		
		return msg;
	}
	
	/**
	 * 结算 ：微信共享地址V1.0, V1.1以后版本不需要调用此方法
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/wechatAddrShare", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg wechatAddrShare(HttpServletRequest request) {
		
		ResultMsg msg = new ResultMsg();
		msg.setResultCode(ResultInfo.ERRORCODE);
		
		Map<String, String> map = new HashMap<String, String>();
		// 获取session中的 数据
		String wechatAccessToken = (String) request.getSession().getAttribute("wechatAccessToken");
		String code = (String) request.getSession().getAttribute("wechatAddrCode");
		String cartIds = (String) request.getSession().getAttribute("cartIds");
		if (wechatAccessToken == null || code == null || cartIds == null) {
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
		// 清空数据
		request.getSession().removeAttribute("wechatAccessToken");
		request.getSession().removeAttribute("wechatAddrCode");
		// 组装数据
		StringBuffer sb = new StringBuffer(NameUtils.TOCHECKOUT_ADDR_URL + cartIds);
		sb.append("?code=").append(code).append("&state=iamberry");// 微信共享地址兼容，Android系统url需要加上#，ios则不用
		String currentUrl = sb.toString();
		String nonceStr = Sha1Util.getNonceStr();
		String timestamp = Sha1Util.getTimeStamp();
		TreeMap<String, String> signatureParams = new TreeMap<String, String>();
		signatureParams.put("noncestr", nonceStr);
		signatureParams.put("appid", NameUtils.appId);
		signatureParams.put("timestamp", timestamp);
		signatureParams.put("url", currentUrl);
		signatureParams.put("accesstoken", wechatAccessToken);
		String s1 = TenpayUtil.getKeyValue(signatureParams);
		String addrSign = Sha1Util.getSha2(s1);
		// 组装数据
		map.put("appId", NameUtils.appId);
		map.put("scope", "jsapi_address");
		map.put("signType", "SHA1");
		map.put("addrSign", addrSign);
		map.put("timestamp", timestamp);
		map.put("nonceStr", nonceStr);
		map.put("status", "true");
		
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setMessage(ResultInfo.SUCCESSINFO);
		msg.setData(map);
		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);
//System.out.println("============orderId===="+orderId);
		Integer orderStatus = cartService.selectOrderStatusByOrderId(orderId);
		if (orderStatus != null && orderStatus.intValue() == 2) {
			msg.setResultCode(ResultInfo.SUCCESSCODE);
			msg.setMessage(ResultInfo.SUCCESSINFO);
			msg.setStatus(true);
			return msg;
		}
		msg.setResultCode(ResultInfo.ERRORCODE);
		msg.setMessage(ResultInfo.ERRORINFO);
		msg.setStatus(false);
		
		return msg;
	}

	@RequestMapping("/paySuccess")
	public void paySuccess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher(NameUtils.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); // 当前用户
		/** 数据格式校验 */
		if (member == null || member.getUserOpenid() == null) {// 校验当前用户信息是否丢失
			msg.setMessage(ResultInfo.loginOutError);
			return msg;
		}
		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(ResultInfo.SUCCESSINFO);
		msg.setStatus(true);
		return msg;
	}
	
	/**
	 * 校验一个购物车字符串
	 * @param cartIds 购物车ID字符串
	 * @param cartId 接受数据数组
	 * @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;
	}
}
