package com.iamberry.wechat.handles.cart;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.iamberry.wechat.core.entity.product.Product;
import com.iamberry.wechat.core.entity.product.QrcodeGift;
import com.iamberry.wechat.face.order.CodeService;
import com.iamberry.wechat.service.ImberryConfig;
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.PaperBean;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.cart.CartDto;
import com.iamberry.wechat.core.entity.cart.SendPayDto;
import com.iamberry.wechat.core.entity.cart.ShopOrderAndItemDto;
import com.iamberry.wechat.core.entity.cart.ShopOrderItemDto;
import com.iamberry.wechat.core.entity.cart.ShopSalesOrderDto;
import com.iamberry.wechat.core.entity.cart.UserGiftDto;
import com.iamberry.wechat.core.entity.coupon.CouponItem;
import com.iamberry.wechat.core.entity.coupon.CouponType;
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.member.MemberService;
import com.iamberry.wechat.face.order.AdminOrderService;
import com.iamberry.wechat.face.pay.PayService;
import com.iamberry.wechat.handles.mq.MQServiceProxy;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.StaticInfo;

import static com.iamberry.wechat.service.ImberryConfig.INFORM_SHIPPING;

@Controller
@RequestMapping("/wechat/cart")
public class CartHandlers {

	@Autowired
	private CartService cartService;

	@Autowired
	private SystemService systemService;

	@Autowired
	private AdminOrderService adminOrderService;

	@Autowired
	private PayService payService;

	@Autowired
	private MQServiceProxy mQservice;

	@Autowired
	private MemberService memberService;

	@Autowired
	private CouponItemService couponItemService;

	@Autowired
	private ProductInfoService productInfoService;

	@Autowired
	private CodeService codeService;

	/**
	 * 进入购物车页面
	 * @param request
	 * @return	ResultMsg
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/selectCartByOpenId",method = RequestMethod.POST)
	public ResultMsg selectCartByOpenId(HttpServletRequest request) throws Exception {
		ResultMsg remsg = new ResultMsg();
		Member member =  WechatUtils.getUserBySession(request);
		//member.setUserId(11907);
		//member.setUserOpenid("o-icas-WiwbEXfwO1wLGDKQ1iWJU");
		List<CartDto> cartList = cartService.selectCartByOpenId(member.getUserOpenid());
		String userQrcodeType = request.getParameter("userQrcodeType");
		
		/*
		 * 金额统计
		 */
		Integer total = 0;
		if (null != cartList && cartList.size() > 0) {


            /*//如果是有二维码的商户，进入后显示优惠价
            int num = productInfoService.getQrCodeByPlaceOpenId(member.getUserOpenid());
            if (num > 0) {
                QrcodeGift gift = new QrcodeGift();
                List<QrcodeGift> giftList = productInfoService.listQrcodeGift(gift);
                if (giftList != null && giftList.size() > 0 && cartList != null && cartList.size() > 0) {
                    for (CartDto cartDto : cartList) {
                        for (QrcodeGift qrcodeGift : giftList) {
                            if (cartDto.getCartColorId().intValue() == qrcodeGift.getQrcodeColorId()
                                && qrcodeGift.getQrcodePreDiscount() != null
                                && qrcodeGift.getQrcodePreDiscount() > 0) {
                                cartDto.setProductDiscount(qrcodeGift.getQrcodePreDiscount());
                            }
                        }
                    }
                }
            }*/

			if (userQrcodeType != null) {
				QrcodeGift gift = new QrcodeGift();
				gift.setQrcodeStatus(1);
				List<QrcodeGift> giftList = productInfoService.listQrcodeGift(gift);
				if (giftList != null && giftList.size() > 0 && cartList != null && cartList.size() > 0) {
					for (CartDto cartDto : cartList) {
						for (QrcodeGift qrcodeGift : giftList) {
							if (cartDto.getCartColorId().intValue() == qrcodeGift.getQrcodeColorId()) {
								if ("1".equals(userQrcodeType) && qrcodeGift.getQrcodePreDiscount() != null
										&& qrcodeGift.getQrcodePreDiscount() > 0) {
									cartDto.setProductDiscount(qrcodeGift.getQrcodePreDiscount());
								} else if ("2".equals(userQrcodeType) && qrcodeGift.getQrcodeSalesDiscount() != null
										&& qrcodeGift.getQrcodeSalesDiscount() > 0) {
									cartDto.setProductDiscount(qrcodeGift.getQrcodeSalesDiscount());
								}
							}
						}
					}
				}
			}

			//判断是否为金牌会员下线，如果是，则以优惠价显示，如果不是则按原价显示
			//查询金牌会员模板id
			int templateId = systemService.selectOneShopRuleById(114).getRuleNum().intValue();
			//查询用户信息
			Member user= memberService.getMemberByUserOpenId(member.getUserOpenid());
			if (user == null) {
				remsg.setMessage(ResultInfo.loginOutError);
				remsg.setStatus(false);
				remsg.setMessage(ResultInfo.loginOutError);
				return remsg;
			}
			//如果模板id等于金牌会模板id，则该用户为金牌会员下线
			if (user.getUserDealers() != null && user.getTemplateId() != null
					&& templateId == user.getTemplateId().intValue()  && user.getUserResType().intValue() == 3) {
				//若果是金牌会员下线，产品的价格就以优惠价显示
				for (CartDto cartDto : cartList) {
					UserGiftDto userGiftDto = new UserGiftDto();
					userGiftDto.setUserLevel(2);
					userGiftDto.setUserProductId(cartDto.getCartProductId());
					userGiftDto.setUserColorId(cartDto.getCartColorId());
					//根据商品id和会员等级查询礼品信息
					userGiftDto = productInfoService.selectUserGift(userGiftDto);
					if (userGiftDto != null) {
						cartDto.setProductDiscount(userGiftDto.getUserDiscount());
					}
				}
			}

			//根据openid查询该用户是否购买过订单
			ShopSalesOrderDto shopSalesOrderDto = new ShopSalesOrderDto();
			shopSalesOrderDto.setSalesOpenid(member.getUserOpenid());
			shopSalesOrderDto.setSalesStatus("2");
			int orderNum = cartService.selectOrderCount(shopSalesOrderDto);

			for (CartDto cartDto : cartList) {

				//如果购买过订单，则滤芯的价格可按折扣价购买
				if (orderNum > 0) {
					if (cartDto.getProductType().intValue() == 2) {
						UserGiftDto userGiftDto = new UserGiftDto();
						userGiftDto.setUserLevel(3);
						userGiftDto.setUserProductId(cartDto.getCartProductId());
						userGiftDto.setUserColorId(cartDto.getCartColorId());
						//根据商品id和会员等级查询礼品信息
						userGiftDto = productInfoService.selectUserGift(userGiftDto);
						if (userGiftDto != null) {
							cartDto.setProductDiscount(userGiftDto.getUserDiscount());
						}
					}
				}

				if (cartDto.getProductStatus() != null && cartDto.getProductStatus() == 1) { 	// 产品状态:在售
					total += cartDto.getCartNum() * cartDto.getProductDiscount();
				}
			}
		}
		
		/*
		 * 组装数据
		 */
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cartList", cartList);
		map.put("total", total);
		map.put("isShow", ResultInfo.ISSHOW);
		map.put("cartDesc", ResultInfo.CARTDESC);
		map.put("cart_url", ResultInfo.CART_URL);
		map.put("userQrcodeType",userQrcodeType);

		remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setStatus(true);
		remsg.setData(map);
		return remsg;
	}

	/**
	 * 获取购物车数量
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/getCartNumByCartOpenId")
	public ResultMsg getCartNumByCartOpenId(HttpServletRequest request) throws Exception {
		ResultMsg remsg=new ResultMsg();
		Member member = WechatUtils.getUserBySession(request);
		String openId  = member.getUserOpenid();
		Integer cartNum = this.cartService.getCartNumByCartOpenId(openId);
		remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		remsg.setStatus(true);
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		if(cartNum == null){
			cartNum = 0;
		}
		remsg.setData(cartNum);
		return remsg;
	}

	/**
	 * 首页添加商品到购物车
	 * @param productId
	 * @param cartNum
	 * @param request
	 * @return ResultMsg
	 */
	@ResponseBody
	@RequestMapping("/addProductToCart")
	public ResultMsg addProductToCart(@RequestParam("productId") String productId,
									  @RequestParam("colorId") Integer colorId,
									  @RequestParam(value = "cartNum", required = false, defaultValue = "1") Integer cartNum,
									  HttpServletRequest request) throws Exception {
		String openId  = WechatUtils.getUserBySession(request).getUserOpenid();
		CartDto cartDto = new CartDto();
		ResultMsg remsg=new ResultMsg();

		Integer pid = 0;
		if (productId != null && !"".equals(productId) && !"null".equals(productId) && StaticInfo.pattern.matcher(productId).find()) {
			pid = Integer.parseInt(productId);
		} else {
			if (productId == null || "".equals(productId)) {
				remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setStatus(false);
				return remsg;
			}
			try {
				String productIdString = StaticInfo.md5.decrypt(productId);
				pid = Integer.parseInt(productIdString);
			} catch (Exception e) {
				remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setStatus(false);
				return remsg;
			}
			return remsg;
		}

		cartDto.setCartOpenId(openId);
		cartDto.setCartProductId(pid);
		cartDto.setCartColorId(colorId);
		//根据用户id和商品id查询购物车中是否存在
		CartDto cart = cartService.getCartByCartProductId(cartDto);
		if (null != cart) {
			//存在，则修改数量
			cartDto.setCartNum(cartNum + cart.getCartNum());
			Integer num = cartService.updateCartByOpenId(cartDto);
			if (num > 0) {
				remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
				remsg.setResultCode(ResultInfo.SUCCESSCODE);
				remsg.setData(cart.getCartId());
				remsg.setStatus(true);
			} else {
				remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setStatus(false);
			}
		} else {
			//不存在，则添加商品信息
			cartDto.setCartNum(cartNum);
			Integer num = cartService.addProductToCart(cartDto);
			if (num > 0) {
				remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
				remsg.setResultCode(ResultInfo.SUCCESSCODE);
				remsg.setData(num);
				remsg.setStatus(true);
			} else {
				remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setStatus(false);
			}
		}
		return remsg;
	}

	/**
	 * 	点击加号按钮添加商品到购物车
	 * @param request
	 * @param productId
	 * @param cartNum
	 * @return	ResultMsg
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/addCart",method = RequestMethod.GET)
	public ResultMsg  addCart(HttpServletRequest request,@RequestParam("productId") Integer productId,
							  @RequestParam("colorId") Integer colorId,
							  @RequestParam(value = "cartNum", required = false, defaultValue = "1") Integer cartNum) throws Exception {
		String openId  = WechatUtils.getUserBySession(request).getUserOpenid();
		ResultMsg remsg=new ResultMsg();
		CartDto cartDto = new CartDto();
		cartDto.setCartOpenId(openId);
		cartDto.setCartColorId(colorId);
		cartDto.setCartProductId(productId);
		Integer productNum = cartService.getCartNumByOpenId(cartDto);
		cartDto.setCartNum(productNum + cartNum);
		Integer num = cartService.updateCartByOpenId(cartDto);
		if (num > 0) {
			remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setStatus(true);
		} else {
			remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
		}
		return remsg;
	}

	/**
	 * 	点击减号按钮删除商品
	 * @param request
	 * @param productId
	 * @param cartNum
	 * @return	ResultMsg
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteCart",method = RequestMethod.GET)
	public ResultMsg  deleteCart(HttpServletRequest request,@RequestParam("productId") Integer productId,
								 @RequestParam("colorId") Integer colorId,
								 @RequestParam(value = "cartNum", required = false, defaultValue = "1") Integer cartNum) throws Exception {
		String openId  = WechatUtils.getUserBySession(request).getUserOpenid();
		ResultMsg remsg=new ResultMsg();
		CartDto cartDto = new CartDto();
		cartDto.setCartOpenId(openId);
		cartDto.setCartColorId(colorId);
		cartDto.setCartProductId(productId);
		Integer productNum = cartService.getCartNumByOpenId(cartDto);
		Integer num = 0;
		if (productNum != null && productNum > 1) {
			cartDto.setCartNum(productNum - cartNum);
			num = cartService.updateCartByOpenId(cartDto);
		}
		if (num > 0) {
			remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setStatus(true);
		} else {
			remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
		}
		return remsg;
	}

	/**
	 * 点击垃圾桶按钮删除购物车物品信息
	 * @param request
	 * @return ResultMsg
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteCartByProductId",method = RequestMethod.GET)
	public ResultMsg deleteCartByProductId(HttpServletRequest request,@RequestParam("productId") Integer productId,
										   @RequestParam("colorId") Integer colorId) throws Exception{
		String openId  = WechatUtils.getUserBySession(request).getUserOpenid();
		CartDto cartDto = new CartDto();
		ResultMsg remsg=new ResultMsg();
		cartDto.setCartOpenId(openId);
		cartDto.setCartColorId(colorId);
		cartDto.setCartProductId(productId);
		if (cartService.deleteCartByCartId(cartDto) >= 1) {
			remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setStatus(true);
		} else {
			remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
		}
		return remsg;
	}

	/**
	 *
	 * 查询订单列表页面
	 * @param request
	 * @param pageSize
	 * @param pageNO
	 * @param salesStatus
	 * @param text
	 * @return ResultMsg
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/selectShopOrder")
	public  ResultMsg selectShopOrder(HttpServletRequest request,
									  @RequestParam(value= "pageSize",defaultValue= "10" ,required=false) Integer pageSize,
									  @RequestParam(value = "pageNO", defaultValue = "1") Integer pageNO,
									  @RequestParam(value = "salesStatus",defaultValue = "")String salesStatus,
									  @RequestParam(value = "text",defaultValue = "")String text) throws Exception {
		String openId  = WechatUtils.getUserBySession(request).getUserOpenid();
		String beginDate = request.getParameter("beginDate");
		PaperBean bean = new PaperBean();
		ResultMsg remsg=new ResultMsg();
		if (null != salesStatus && !"".equals(salesStatus)) {
			bean.setStatus(salesStatus);
		}
		if (null != text && !"".equals(text)) {
			bean.setStr(text);
		}
		if (null != beginDate && !"".equals(beginDate)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			bean.setBeginDate(sdf.parse(beginDate));
		}
		bean.setText(openId);
		bean.setPaperData(pageNO, pageSize);
		List<ShopOrderAndItemDto> shopOrderList = cartService.selectShopOrder(bean);
		ShopSystemRule shopSystemRule = this.adminOrderService.getReluByRid(109);

		//查询订单列表时同步百胜信息
		if (null != shopOrderList && shopOrderList.size() > 0) {
			for (ShopOrderAndItemDto orderDto : shopOrderList) {
				//判断该订单能否进行支付
				if ("1".equals(orderDto.getSalesStatus()) && orderDto.getOrderItemList() != null && orderDto.getOrderItemList().size() > 0) {
					orderDto.setEfficacious(true);
					for (OrderItem orderItem : orderDto.getOrderItemList()) {
						if (orderItem.getProductStatus() != 1 && orderItem.getItemProductType() != shopSystemRule.getRuleNum().intValue()) {
							orderDto.setEfficacious(false);
						}
					}
				}
				MQMessage message = new MQMessage();
				if ("2".equals(orderDto.getSalesStatus())) {
					message.setServiceToMessage(orderDto.getSalesOrderid());
					message.setServiceOtherMessage("efast.trade.detail.get");
					message.setServiceIsSend(2);			// 没有推送的信息
					message.setServiceStatus(1); 			// 推送成功
					message.setServiceType(1); 				// 添加订单信息
					message.setServiceHandlerObjectName("efastOrderServiceImpl");
					message.setServiceHandlerMethodName("selectEfastSendOrderInfo");
					mQservice.insertMQMessage(message);
				} else if ("8".equals(orderDto.getSalesStatus())) {
					message.setServiceToMessage(orderDto.getSalesOrderid());
					message.setServiceOtherMessage("efast.order.return.info.fetch");
					message.setServiceIsSend(2);			// 没有推送的信息
					message.setServiceStatus(1); 			// 推送成功
					message.setServiceType(1); 				// 添加订单信息
					message.setServiceHandlerObjectName("efastOrderServiceImpl");
					message.setServiceHandlerMethodName("selectEfastReturnOrderInfo");
					mQservice.insertMQMessage(message);
				}
			}
		}

		Integer pageCount = cartService.getOrderNumByOpenId(bean);
		int count = pageCount % pageSize == 0? pageCount/pageSize:(pageCount/pageSize)+1;
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("pageCount", count);
		map.put("orderList", shopOrderList);
		map.put("productType", shopSystemRule.getRuleNum());
		remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setStatus(true);
		remsg.setData(map);
		return remsg;
	}


	/**
	 * 查询订单详情
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/getShopOrderByOrderId")
	public ResultMsg getShopOrderByOrderId(HttpServletRequest request) throws Exception{
		String orderId = request.getParameter("orderId");
		ShopSystemRule shopSystemRule = this.adminOrderService.getReluByRid(109);
		ResultMsg remsg=new ResultMsg();
		String openId  = WechatUtils.getUserBySession(request).getUserOpenid();
		ShopSalesOrderDto shopSalesOrderDto = null;
		List<ShopOrderItemDto> orderItemList = new ArrayList<ShopOrderItemDto>();
		CouponType couponType = null;
		CouponItem couponItem = new CouponItem();
		if (orderId != null && !"".equals(orderId)) {
			shopSalesOrderDto = cartService.getShopOrderByOrderId(orderId, openId);
			//查询优惠券信息
			if (null != shopSalesOrderDto.getSalesCouponReceiveId() && !"".equals(shopSalesOrderDto.getSalesCouponReceiveId())) {
				couponItem.setCouponItemId(shopSalesOrderDto.getSalesCouponReceiveId());
				couponItem.setCouponItemUseropenid(openId);
				couponType = cartService.getCouponReduceByItemId(couponItem);
			}
			if (null != couponType) {
				int money = 0;
				switch (couponType.getCouponType()) {
					case 1:
						money = couponType.getCouponReduce();
						break;
					case 2:
						money = shopSalesOrderDto.getSalesAmount() - shopSalesOrderDto.getSalesAmount() * couponType.getCouponReduce()/100;
						break;
				}
				shopSalesOrderDto.setCouponReduce(money);
			}
			orderItemList = cartService.selectShopOrderItem(orderId);

			//判断该订单是否可以支付
			if (orderItemList != null && orderItemList.size() > 0) {
				if ("1".equals(shopSalesOrderDto.getSalesStatus())) {
					shopSalesOrderDto.setEfficacious(true);
					for (ShopOrderItemDto shopOrderItemDto : orderItemList) {
						if (!"1".equals(shopOrderItemDto.getProductStatus()) &&
								shopOrderItemDto.getItemProductType().intValue() != shopSystemRule.getRuleNum().intValue()) {
							shopSalesOrderDto.setEfficacious(false);
						}
					}
				}
			}

			shopSalesOrderDto.setOrderItemList(orderItemList);
		}
		if (shopSalesOrderDto == null) {
			shopSalesOrderDto = new ShopSalesOrderDto();
		}
		if ("5".equals(shopSalesOrderDto.getSalesStatus())) {
			// 给百胜推送信息
			try {
				MQMessage message = new MQMessage();
				message.setServiceToMessage(orderId);
				message.setServiceOtherMessage("efast.trade.detail.get");
				message.setServiceIsSend(2);			// 没有推送的信息
				message.setServiceStatus(1); 			// 推送成功
				message.setServiceType(1); 				// 添加订单信息
				message.setServiceHandlerObjectName("efastOrderServiceImpl");
				message.setServiceHandlerMethodName("selectEfastSendOrderInfo");
				mQservice.insertMQMessage(message);
			} catch (Exception e) {
				// TODO: handle exception
			}
		} else if ("8".equals(shopSalesOrderDto.getSalesStatus())) {
			// 给百胜推送信息
			try {
				MQMessage message = new MQMessage();
				message.setServiceToMessage(orderId);
				message.setServiceOtherMessage("efast.trade.detail.get");
				message.setServiceIsSend(2);			// 没有推送的信息
				message.setServiceStatus(1); 			// 推送成功
				message.setServiceType(1); 				// 添加订单信息
				message.setServiceHandlerObjectName("efastOrderServiceImpl");
				message.setServiceHandlerMethodName("selectEfastReturnOrderInfo");
				mQservice.insertMQMessage(message);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		remsg.setData(shopSalesOrderDto);
		remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setStatus(true);
		return remsg;
	}


	/**
	 * 订单页面支付方法
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/orderPay")
	public ResultMsg orderPay(HttpServletRequest request) throws Exception {
		String openId  = WechatUtils.getUserBySession(request).getUserOpenid();
		String orderId = request.getParameter("orderId");
		ResultMsg msg=new ResultMsg();
		Order order = new Order();
		order.setSalesOrderid(orderId);
		order.setSalesOpenid(openId);
		ShopSalesOrderDto shopSalesOrderDto = null;
		SendPayDto dto = new SendPayDto();
		dto.setSuccess(false);
		List<ShopOrderItemDto> orderItemList = new ArrayList<ShopOrderItemDto>();
		if (orderId != null && !"".equals(orderId)) {
			shopSalesOrderDto = cartService.getShopOrderByOrderId(orderId, openId);
			orderItemList = cartService.selectShopOrderItem(orderId);
			Member member = memberService.getMemberByUserOpenId(openId);

			//获取账户余额，判断是否在可用范围内
			int balancePayAmount=shopSalesOrderDto.getBalancePayAmount();
			int total = shopSalesOrderDto.getSalesYetAmount();
			//判断余额支付金额是否大于用户余额
			if(balancePayAmount > 0 && member.getUserIncome() > balancePayAmount) {
				total = total - balancePayAmount > 0 ? total - balancePayAmount : 0;
			} else if(balancePayAmount > 0 && member.getUserIncome() < balancePayAmount) {
				msg.setMessage(ResultInfo.NO_ENOUGH_FOR_PAY);
				return msg;
			}
			// 发起支付
			PayResult result = payService.requestPay(openId, orderId, total, orderItemList.get(0).getItemProductName() + "...", NameUtils.getConfig("WECHAT_ORDER_BACK"));
			if (result.isPaySuccess()) {
				dto.setInfo(result.getPayData());
				dto.setSuccess(true);
				dto.setOrderId(orderId);
			} else {
				dto.setInfo(result.getPayData());
				dto.setOrderId(orderId);
			}
		} else {
			shopSalesOrderDto = new ShopSalesOrderDto();
		}
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		msg.setData(dto);
		msg.setStatus(true);

		return msg;
	}

	/**
	 * 	取消订单
	 * @param request
	 * @param orderId
	 * @return ResultMsg
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/cancelOrder")
	public ResultMsg cancelOrder(HttpServletRequest request,
								 @RequestParam(value = "orderId",defaultValue = "")String orderId,
								 @RequestParam(value = "status",defaultValue = "-1") Integer status)  throws Exception{
		String openId  = WechatUtils.getUserBySession(request).getUserOpenid();
		ResultMsg remsg=new ResultMsg();
		if (null != orderId && !"".equals(orderId)) {
			ShopSalesOrderDto orderDto = this.cartService.getOpenIdAndStatus(orderId);
			if (orderDto != null) {
				if (!openId.equals(orderDto.getSalesOpenid())) {
					remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
					remsg.setResultCode(ResultInfo.ERRORCODE);
					remsg.setStatus(false);
					return remsg;
				}
				if (Integer.parseInt(orderDto.getSalesStatus()) != 1) {
					remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
					remsg.setResultCode(ResultInfo.ERRORCODE);
					remsg.setStatus(false);
					return remsg;
				}
			} else {
				remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setStatus(false);
				return remsg;
			}
			if (null != orderDto.getSalesCouponReceiveId() && !"".equals(orderDto.getSalesCouponReceiveId())) {
				CouponItem couponItem = new CouponItem();
				couponItem.setCouponItemId(orderDto.getSalesCouponReceiveId());
				couponItem.setCouponItemUseropenid(openId);
				couponItem.setCouponUseStatus(1);
				couponItem.setOldCouponUseStatus(7);
				couponItemService.updateCouponItemById(couponItem);
			}
			Order order = new Order();
			order.setSalesStatus(0);
			order.setSalesOrderid(orderId);
			order.setOldStatus(status);
			adminOrderService.updateOrderStatusByOrderId(order);
			remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setStatus(true);
			return remsg;
		} else {
			remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
			return remsg;
		}
	}


	/**
	 * 	订单退货或退款
	 * @param request
	 * @param orderId
	 * @param remark
	 * @param status
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/returnOrder")
	public ResultMsg returnOrder(HttpServletRequest request,
								 @RequestParam(value = "orderId",defaultValue = "")String orderId,
								 @RequestParam(value = "remark",defaultValue = "")String remark,
								 @RequestParam(value = "returnOrderId",defaultValue = "")String returnOrderId,
								 @RequestParam(value = "status",defaultValue = "-1") Integer status) throws Exception {
		ResultMsg remsg=new ResultMsg();
		String openId  = WechatUtils.getUserBySession(request).getUserOpenid();
		Order order = new Order();
		order.setSalesOrderid(orderId);
		order.setOldStatus(status);
		ShopSystemRule shopSystemRule = this.adminOrderService.getReluByRid(102);
		ShopSystemRule rule = this.adminOrderService.getReluByRid(240);	//获取需要发短信的电话号码
		if (null != orderId && !"".equals(orderId)) {
			ShopSalesOrderDto orderDto = this.cartService.getOpenIdAndStatus(orderId);
			if (orderDto != null) {
				if (!openId.equals(orderDto.getSalesOpenid())) {
					remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
					remsg.setResultCode(ResultInfo.ERRORCODE);
					remsg.setStatus(false);
					return remsg;
				}
				//判断该订单是否被锁定，如果被锁定，则不能退款或是退换货
				if (orderDto.getSalesLockType() != null && "2".equals(orderDto.getSalesLockType().toString())) {
					remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
					remsg.setResultCode(ResultInfo.ERRORCODE);
					remsg.setStatus(false);
					return remsg;
				}
				//判断该订单是否可以退款
				if (status == 2) {
					if (Integer.parseInt(orderDto.getSalesStatus()) != status) {
						remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
						remsg.setResultCode(ResultInfo.ERRORCODE);
						remsg.setStatus(false);
						return remsg;
					} else {
						order.setSalesStatus(3);
						order.setSalesReturnDes(remark);
						cartService.updateOrderByOrderId(order);
						remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
						try {
							String text = MessageFormat.format(ImberryConfig.ORDER_UPDATE_STATUS_TEXT,  "退款 ");
							codeService.informShipping(rule.getRuleDesc(),text);
						} catch (Exception e) {
							System.out.println("订单退款发送消息失败!");
						}
						remsg.setResultCode(ResultInfo.SUCCESSCODE);
						remsg.setStatus(true);
						return remsg;
					}
				}
				//判断该订单是否可以退货
				if (status == 5) {
					if (Integer.parseInt(orderDto.getSalesStatus()) != status) {
						remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
						remsg.setResultCode(ResultInfo.ERRORCODE);
						remsg.setStatus(false);
						return remsg;
					} else {
						// 7天内用户可以退货
						if ((new Date().getTime() - orderDto.getSalesSendDate().getTime()) > shopSystemRule.getRuleNum() * (1000*3600*24)) {
							remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
							remsg.setResultCode(ResultInfo.ERRORCODE);
							remsg.setStatus(false);
							return remsg;
						} else {
							order.setSalesStatus(6);
							order.setSalesReturnDes(remark);
							order.setSalesChangeOrderid(returnOrderId);
							cartService.updateOrderByOrderId(order);
							try {
								String text = MessageFormat.format(ImberryConfig.ORDER_UPDATE_STATUS_TEXT, "退货");
								codeService.informShipping(rule.getRuleDesc(),text);
							} catch (Exception e) {
								System.out.println("订单退货发送消息失败!");
							}
							remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
							remsg.setResultCode(ResultInfo.SUCCESSCODE);
							remsg.setStatus(true);
							return remsg;
						}
					}
				}

			} else {
				remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setStatus(false);
				return remsg;
			}
		}
		return remsg;
	}

	/**
	 * 订单换货
	 * @param request
	 * @param orderId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/exchangeOrder")
	public ResultMsg exchangeOrder(HttpServletRequest request,
								   @RequestParam(value = "orderId",defaultValue = "")String orderId,
								   @RequestParam(value = "status",defaultValue = "-1") Integer status,
								   @RequestParam(value = "changeOrderId",defaultValue = "") String changeOrderId) throws Exception{
		ResultMsg remsg=new ResultMsg();
		String openId  = WechatUtils.getUserBySession(request).getUserOpenid();
		Order order = new Order();
		order.setSalesOrderid(orderId);
		order.setSalesChangeOrderid(changeOrderId);
		order.setOldStatus(status);
		ShopSystemRule shopSystemRule = this.adminOrderService.getReluByRid(103);
		ShopSystemRule rule = this.adminOrderService.getReluByRid(240);	//获取需要发短信的电话号码
		if (null != orderId && !"".equals(orderId)) {
			ShopSalesOrderDto orderDto = this.cartService.getOpenIdAndStatus(orderId);
			if (orderDto != null) {
				if (!openId.equals(orderDto.getSalesOpenid())) {
					remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
					remsg.setResultCode(ResultInfo.ERRORCODE);
					remsg.setStatus(false);
					return remsg;
				}
				if (Integer.parseInt(orderDto.getSalesStatus()) != 5 && Integer.parseInt(orderDto.getSalesStatus()) != 12) {
					remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
					remsg.setResultCode(ResultInfo.ERRORCODE);
					remsg.setStatus(false);
					return remsg;
				} else {
					// 1年内用户可以换货
					if ((new Date().getTime() - orderDto.getSalesSendDate().getTime()) >= shopSystemRule.getRuleNum() * (1000*3600*24)) {
						remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
						remsg.setResultCode(ResultInfo.ERRORCODE);
						remsg.setStatus(false);
						return remsg;
					} else {
						order.setSalesStatus(11);
						adminOrderService.updateOrderStatusByOrderId(order);
						try {
							String text = MessageFormat.format(ImberryConfig.ORDER_UPDATE_STATUS_TEXT, "换货");
							codeService.informShipping(rule.getRuleDesc(),text);
						} catch (Exception e) {
							System.out.println("订单换货发送消息失败!");
						}
						remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
						remsg.setResultCode(ResultInfo.SUCCESSCODE);
						remsg.setStatus(true);
						return remsg;
					}
				}
			} else {
				remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setStatus(false);
				return remsg;
			}
		}
		return remsg;
	}
}
