package com.iamberry.wechat.handles.cart;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.iamberry.wechat.core.entity.eo.GiftPool;
import com.iamberry.wechat.core.entity.eo.ItemGift;
import com.iamberry.wechat.core.entity.order.OrderItem;
import com.iamberry.wechat.core.entity.product.ProductColor;
import com.iamberry.wechat.core.entity.product.SalesUserGift;
import com.iamberry.wechat.face.cart.ProductInfoService;
import com.iamberry.wechat.face.eo.GiftPoolService;
import com.iamberry.wechat.face.eo.ItemGiftService;
import com.iamberry.wechat.face.ism.IntegralLogService;
import com.iamberry.wechat.service.ActivityUtil;
import com.iamberry.wechat.tools.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.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.pay.PayResult;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.cart.CartService;
import com.iamberry.wechat.face.coupon.CouponItemService;
import com.iamberry.wechat.face.home.HomeService;
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;

/**
 * @company	深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author 	献
 * @tel		18271840547
 * @date	2016年11月3日
 * @explain	购物车Handler
 */
@Controller
@RequestMapping("/wechat/cart")
public class CartHandlers {
	Logger logger = LoggerFactory.getLogger(CartHandlers.class);

	@Autowired
	private CartService cartService;
	@Autowired
	private WechatUtils wechatUtils;
	@Autowired
	private HomeService homeService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ValidatorUtil validatorUtil;
	@Autowired
	private AdminOrderService adminOrderService;
	@Autowired
	private PayService payService;
	@Autowired
	private MQServiceProxy mQservice;
	@Autowired
	private MemberService memberService;
	@Autowired
	private CouponItemService couponItemService;
	@Autowired
	private ItemGiftService itemGiftService;
	@Autowired
	private ProductInfoService produtInfoService;
	@Autowired
	private GiftPoolService giftPoolService;
	@Autowired
	private ActivityUtil activityUtil;
	@Autowired
	private IntegralLogService integralLogService;

	/**
	 * 进入购物车页面
	 * @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);
		List<CartDto> cartList = cartService.selectCartByOpenId(member.getUserOpenid());
		activityUtil.getColorSpike(cartList);
		/*
		 * 金额统计
		 */
		Integer total = 0;
		if (null != cartList && cartList.size() > 0) {
			for (CartDto cartDto : cartList) {
				if (cartDto.getProductStatus() != null && cartDto.getProductStatus() == 1) { 	// 产品状态:在售
					total += cartDto.getCartNum() * cartDto.getProductPrice();
				}
			}
		}

		/*
		 * 组装数据
		 */
		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);

		remsg.setMessage(ResultInfo.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);
		if (member == null || member.getUserOpenid() == null || "null".equals(member.getUserOpenid())) {
			remsg.setMessage(ResultInfo.SUCCESSINFO);
			remsg.setStatus(true);
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setData(0);
			return remsg;
		}
		String openId  = member.getUserOpenid();
		Integer cartNum = this.cartService.getCartNumByCartOpenId(openId);
		remsg.setMessage(ResultInfo.SUCCESSINFO);
		remsg.setStatus(true);
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setData(cartNum);
		return remsg;
	}

	/**
	 * 首页添加商品到购物车
	 * @param cartNum
	 * @param request
	 * @return ResultMsg
	 */
	@ResponseBody
	@RequestMapping("/addProductToCart")
	public ResultMsg addProductToCart(@RequestParam("productColorId") String productColorId,
									  @RequestParam(value = "cartIsSource", required = false, defaultValue = "1") Integer cartIsSource,
									  @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 cid = 0;
		if (productColorId != null && !"".equals(productColorId) && !"null".equals(productColorId) && StaticInfo.pattern.matcher(productColorId).find()) {
			cid = Integer.parseInt(productColorId);
		} else {
			remsg.setMessage(ResultInfo.ERRORINFO);
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
			return remsg;
		}
		cartDto.setCartOpenId(openId);
		cartDto.setCartIsSource(cartIsSource);  	//商品来源   1：产品颜色表   2：配件表
		cartDto.setCartColorId(cid);
		//根据颜色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(ResultInfo.SUCCESSINFO);
				remsg.setResultCode(ResultInfo.SUCCESSCODE);
				remsg.setData(cart.getCartId());
				remsg.setStatus(true);
			} else {
				remsg.setMessage(ResultInfo.ERRORINFO);
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setStatus(false);
			}
		} else {
			cartDto.setCartNum(cartNum);
			//不存在，则添加商品信息
			Integer num = cartService.addProductToCart(cartDto);
			if (num > 0) {
				remsg.setMessage(ResultInfo.SUCCESSINFO);
				remsg.setResultCode(ResultInfo.SUCCESSCODE);
				remsg.setData(num);
				remsg.setStatus(true);
			} else {
				remsg.setMessage(ResultInfo.ERRORINFO);
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setStatus(false);
			}
		}
		return remsg;
	}

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

	/**
	 * 	点击减号按钮删除商品
	 * @param request
	 * @param productColorId
	 * @param cartNum
	 * @return	ResultMsg
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteCart",method = RequestMethod.GET)
	public ResultMsg  deleteCart(HttpServletRequest request,
								 @RequestParam("productColorId") Integer productColorId,
								 @RequestParam(value = "cartIsSource", required = false, defaultValue = "1") Integer cartIsSource,
			@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(productColorId);
		cartDto.setCartIsSource(cartIsSource);
		Integer productNum = cartService.getCartNumByOpenId(cartDto);
		Integer num = 0;
		if (productNum > 1) {
			cartDto.setCartNum(productNum - cartNum);
			num = cartService.updateCartByOpenId(cartDto);
		} else {
			this.deleteCartByProductId(request,productColorId,cartIsSource);
			num = 1;
		}
		if (num > 0) {
			remsg.setMessage(ResultInfo.SUCCESSINFO);
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setStatus(true);
			remsg.setData("");
		} else {
			remsg.setMessage(ResultInfo.ERRORINFO);
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
			remsg.setData("");
		}
		return remsg;
	}

	/**
	 * 点击垃圾桶按钮删除购物车物品信息
	 * @param request
	 * @return ResultMsg
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteCartByProductId",method = RequestMethod.GET)
	public ResultMsg deleteCartByProductId(HttpServletRequest request,
										   @RequestParam("productColorId") Integer productColorId,
										   @RequestParam(value = "cartIsSource", required = false, defaultValue = "1") Integer cartIsSource
								) throws Exception{
		String openId  = wechatUtils.getUserBySession(request).getUserOpenid();
		CartDto cartDto = new CartDto();
		ResultMsg remsg=new ResultMsg();
		cartDto.setCartOpenId(openId);
		cartDto.setCartIsSource(cartIsSource);
		cartDto.setCartColorId(productColorId);
		if (cartService.deleteCartByCartId(cartDto) >= 1) {
			remsg.setMessage(ResultInfo.SUCCESSINFO);
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setStatus(true);
		} else {
			remsg.setMessage(ResultInfo.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);

		//查询订单列表时同步百胜信息
		if (null != shopOrderList && shopOrderList.size() > 0) {

			for (ShopOrderAndItemDto orderDto : shopOrderList) {
				List<SalesUserGift> giftList = new ArrayList<SalesUserGift>();
				//将赠品和订单项区分开
				List<OrderItem> orderItemList = orderDto.getOrderItemList();
				if (orderItemList == null || orderItemList.size() == 0) {
					remsg.setResultCode(ResultInfo.ERRORCODE);
					remsg.setStatus(false);
					return remsg;
				}

				Iterator it = orderItemList.iterator();
				//将所有赠品筛选出来
				while (it.hasNext()) {
					OrderItem item = (OrderItem)it.next();
					if (item.getItemGiftSource() != null && !"".equals(item.getItemGiftSource())) {
						SalesUserGift gift = new SalesUserGift();
						gift.setGiftName(item.getItemProductName());
						gift.setGiftColorName(item.getItemProductColor());
						gift.setUserGiftCount(item.getItemNum());
						gift.setUserColorId(item.getItemGiftSource());
						gift.setUserGiftColor(item.getItemColorId());
						giftList.add(gift);
						it.remove();
					}
				}

				//将赠品添加到对应的机器上
				for (OrderItem item : orderItemList) {
					List<SalesUserGift> gifts = new ArrayList<SalesUserGift>();
					for (int i = 0;i < giftList.size();i++) {
						SalesUserGift gift = giftList.get(i);
						if (item.getItemColorId() == gift.getUserColorId()) {
							gifts.add(gift);
						}
					}
					item.setSalesUserGiftList(gifts);
				}
			}
		}
		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);
		remsg.setMessage(ResultInfo.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");
		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);
			}

			List<SalesUserGift> giftList = new ArrayList<SalesUserGift>();
			//将赠品和订单项区分开
			orderItemList = cartService.selectShopOrderItem(orderId);
			if (orderItemList == null || orderItemList.size() == 0) {
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setStatus(false);
				return remsg;
			}

			Iterator it = orderItemList.iterator();
			//将所有赠品筛选出来
			while (it.hasNext()) {
				ShopOrderItemDto item = (ShopOrderItemDto)it.next();
				if (item.getItemGiftSource() != null && !"".equals(item.getItemGiftSource())) {
					SalesUserGift gift = new SalesUserGift();
					gift.setGiftName(item.getItemProductName());
					gift.setGiftColorName(item.getItemProductColor());
					gift.setUserGiftCount(item.getItemNum());
					gift.setUserColorId(item.getItemGiftSource());
					gift.setUserGiftColor(item.getItemColorId());
					giftList.add(gift);
					it.remove();
				}
			}

			//将赠品添加到对应的机器上
			for (ShopOrderItemDto item : orderItemList) {
				List<SalesUserGift> gifts = new ArrayList<SalesUserGift>();
				for (int i = 0;i < giftList.size();i++) {
					SalesUserGift gift = giftList.get(i);
					if (item.getItemColorId() == gift.getUserColorId()) {
						gifts.add(gift);
					}
				}
				item.setSalesUserGiftList(gifts);
			}

			shopSalesOrderDto.setOrderItemList(orderItemList);
		}
		if (shopSalesOrderDto == null) {
			shopSalesOrderDto = new ShopSalesOrderDto();
		}
		remsg.setData(shopSalesOrderDto);
		remsg.setMessage(ResultInfo.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.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(ResultInfo.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(ResultInfo.ERRORINFO);
					remsg.setResultCode(ResultInfo.ERRORCODE);
					remsg.setStatus(false);
					return remsg;
				}
				if (Integer.parseInt(orderDto.getSalesStatus()) != 1) {
					remsg.setMessage(ResultInfo.ERRORINFO);
					remsg.setResultCode(ResultInfo.ERRORCODE);
					remsg.setStatus(false);
					return remsg;
				}
			} else {
				remsg.setMessage(ResultInfo.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(ResultInfo.SUCCESSINFO);
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setStatus(true);
			return remsg;
		} else {
			remsg.setMessage(ResultInfo.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);
		if (null != orderId && !"".equals(orderId)) {
			ShopSalesOrderDto orderDto = this.cartService.getOpenIdAndStatus(orderId);
			if (orderDto != null) {
				if (!openId.equals(orderDto.getSalesOpenid())) {
					remsg.setMessage(ResultInfo.ERRORINFO);
					remsg.setResultCode(ResultInfo.ERRORCODE);
					remsg.setStatus(false);
					return remsg;
				}
				//判断该订单是否被锁定，如果被锁定，则不能退款或是退换货
				if (orderDto.getSalesLockType() != null && "2".equals(orderDto.getSalesLockType().toString())) {
					remsg.setMessage(ResultInfo.ERRORINFO);
					remsg.setResultCode(ResultInfo.ERRORCODE);
					remsg.setStatus(false);
					return remsg;
				}
				//判断该订单是否可以退款
				if (status == 2) {
					if (Integer.parseInt(orderDto.getSalesStatus()) != status) {
						remsg.setMessage(ResultInfo.ERRORINFO);
						remsg.setResultCode(ResultInfo.ERRORCODE);
						remsg.setStatus(false);
						return remsg;
					} else {
						order.setSalesStatus(3);
						order.setSalesReturnDes(remark);
						cartService.updateOrderByOrderId(order);
						remsg.setMessage(ResultInfo.SUCCESSINFO);
						remsg.setResultCode(ResultInfo.SUCCESSCODE);
						remsg.setStatus(true);
						return remsg;
					}
				}
				//判断该订单是否可以退货
				if (status == 5) {
					if (Integer.parseInt(orderDto.getSalesStatus()) != status) {
						remsg.setMessage(ResultInfo.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(ResultInfo.ERRORINFO);
							remsg.setResultCode(ResultInfo.ERRORCODE);
							remsg.setStatus(false);
							return remsg;
						} else {
							order.setSalesStatus(6);
							order.setSalesReturnDes(remark);
							order.setSalesChangeOrderid(returnOrderId);
							cartService.updateOrderByOrderId(order);
							remsg.setMessage(ResultInfo.SUCCESSINFO);
							remsg.setResultCode(ResultInfo.SUCCESSCODE);
							remsg.setStatus(true);
							return remsg;
						}
					}
				}

			} else {
				remsg.setMessage(ResultInfo.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);
		if (null != orderId && !"".equals(orderId)) {
			ShopSalesOrderDto orderDto = this.cartService.getOpenIdAndStatus(orderId);
			if (orderDto != null) {
				if (!openId.equals(orderDto.getSalesOpenid())) {
					remsg.setMessage(ResultInfo.ERRORINFO);
					remsg.setResultCode(ResultInfo.ERRORCODE);
					remsg.setStatus(false);
					return remsg;
				}
				if (Integer.parseInt(orderDto.getSalesStatus()) != 5 && Integer.parseInt(orderDto.getSalesStatus()) != 12) {
					remsg.setMessage(ResultInfo.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(ResultInfo.ERRORINFO);
						remsg.setResultCode(ResultInfo.ERRORCODE);
						remsg.setStatus(false);
						return remsg;
					} else {
						order.setSalesStatus(11);
						adminOrderService.updateOrderStatusByOrderId(order);
						remsg.setMessage(ResultInfo.SUCCESSINFO);
						remsg.setResultCode(ResultInfo.SUCCESSCODE);
						remsg.setStatus(true);
						return remsg;
					}
				}
			} else {
				remsg.setMessage(ResultInfo.ERRORINFO);
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setStatus(false);
				return remsg;
			}
		}
		return remsg;
	}

	/**
	 * 	修改订单状态
	 * @param request
	 * @param orderId
	 * @return ResultMsg
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/updateOrderStatus")
	public ResultMsg updateOrderStatus(HttpServletRequest request,
									   @RequestParam(value = "orderId",defaultValue = "")String orderId,
									   @RequestParam(value = "remark",defaultValue = "")String remark,
									   @RequestParam(value = "status",defaultValue = "-1") Integer status)  throws Exception {
		String openId = WechatUtils.getUserBySession(request).getUserOpenid();
		ResultMsg remsg = new ResultMsg();
		Map<String, Object> map = new HashMap<String, Object>();
		if(status == -1){
			remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
			return remsg;
		}

		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;
				}
			} else {
				remsg.setMessage(NameUtils.getConfig("ERRORINFO"));
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setStatus(false);
				return remsg;
			}
			map = cartService.updateOrderStatus(orderId, Integer.valueOf(orderDto.getSalesStatus()), remark, status);

			if (((boolean) map.get("flag")) && Integer.valueOf(orderDto.getSalesStatus()) == 1) { //待支付，取消订单
				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);
				}

				//恢复赠品的库存
				List<OrderItem> orderItemList = adminOrderService.getShopOrderItemByOrderId(orderId);
				for (OrderItem orderItem:orderItemList) {
					ItemGift itemGift = new ItemGift();
					itemGift.setItemId(orderItem.getItemId());
					List<ItemGift> itemGiftList = itemGiftService.getItemGiftList(itemGift);
					for (ItemGift ig:itemGiftList) {
						GiftPool gp = new GiftPool();
						gp.setGiftPoolId(ig.getGiftPoolId());
						gp.setGiftPoolStock(ig.getItemGiftNum());
						giftPoolService.updateAddStock(gp);
					}
				}

				//恢复积分
				try {
					Integer flag = integralLogService.cancelSurplusIntegral(orderId);
				}catch (Exception e){
					e.printStackTrace();
					logger.info("取消订单，积分退回失败，订单id："+ orderId);
				}
			}
		}

		if((Boolean) map.get("flag")){
			remsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setStatus(true);
		}else{
			remsg.setMessage(String.valueOf(map.get("msg")));
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
		}
		return remsg;
	}

	/**
	 * 确认收货
	 * @param request
	 * @param orderId
	 * @param status
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/confirm_receipt")
	public ResultMsg confirmReceipt(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("您没有权限,无法操作该订单!");
					remsg.setResultCode(ResultInfo.ERRORCODE);
					remsg.setStatus(false);
					return remsg;
				}
				if (Integer.parseInt(orderDto.getSalesStatus()) != 5) {
					remsg.setMessage("该订单不支持确认收货!");
					remsg.setResultCode(ResultInfo.ERRORCODE);
					remsg.setStatus(false);
					return remsg;
				}
			} else {
				remsg.setMessage("该订单无效,请重新确认!");
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setStatus(false);
				return remsg;
			}
			Order order = new Order();
			order.setSalesStatus(12);
			order.setSalesOrderid(orderId);
			order.setOldStatus(status);
			//修改订单状态
			boolean flag = adminOrderService.updateOrderStatusByOrderId(order);
			if (flag) {
				remsg.setMessage("确认成功!");
				remsg.setResultCode(ResultInfo.SUCCESSCODE);
				remsg.setStatus(true);
			} else {
				remsg.setMessage("确认失败，请重新操作!");
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setStatus(false);
			}
			return remsg;
		} else {
			remsg.setMessage("订单号为空，请重新输入！");
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
			return remsg;
		}
	}

	/**
	 * 提醒发货
	 * @param request
	 * @param orderId
	 * @param status
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/warn_send")
	public ResultMsg warnSend(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 (orderId == null || "".equals(orderId)) {
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
			return remsg;
		}
		ShopSalesOrderDto orderDto = this.cartService.getOpenIdAndStatus(orderId);
		if (orderDto != null) {
			if (!openId.equals(orderDto.getSalesOpenid())) {
				remsg.setMessage(ResultInfo.ERRORINFO);
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setStatus(false);
				return remsg;
			}
			if (Integer.parseInt(orderDto.getSalesStatus()) != 2) {
				remsg.setMessage(ResultInfo.ERRORINFO);
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setStatus(false);
				return remsg;
			}
		} else {
			remsg.setMessage(ResultInfo.ERRORINFO);
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
			return remsg;
		}
		Order order = new Order();
		order.setSalesOrderid(orderId);
		order.setOldStatus(status);
		int num = cartService.updateSendWarnNum(order);
		if (num > 0) {
			remsg.setMessage("提醒发货成功!");
			remsg.setResultCode(ResultInfo.SUCCESSCODE);
			remsg.setStatus(true);
		} else {
			remsg.setMessage("提醒发货失败!");
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setStatus(false);
		}
		return remsg;
	}
}
