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.regex.Pattern;

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

import com.iamberry.wechat.core.entity.product.ProductColor;
import com.iamberry.wechat.core.entity.product.QrcodeGift;
import com.iamberry.wechat.face.order.AdminOrderService;
import com.iamberry.wechat.face.porduct.ProductColorService;
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.ShopSalesOrderDto;
import com.iamberry.wechat.core.entity.cart.TempOrderDto;
import com.iamberry.wechat.core.entity.cart.UserGiftDto;
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.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.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.qrcode.TemporaryQrcodeService;
import com.iamberry.wechat.face.reback.RebackServices;
import com.iamberry.wechat.handles.mq.MQServiceProxy;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.OrderNOUtil;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.ValidatorUtil;

/**
 * @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 HomeService homeService;

	@Autowired
	private SystemService systemService;

	@Autowired
	private ValidatorUtil validatorUtil;

	@Autowired
	private PayService payService;

	@Autowired
	private MemberService memberService;
	@Autowired
	CouponItemService couponItemService;
	@Autowired
	CouponTypeService couponTypeService;
	@Autowired
	CashLogService cashLogService;
	@Autowired
	private RebackServices rebackServices;
	@Autowired
	private ProductInfoService productInfoService;
	@Autowired
	private TemporaryQrcodeService temporaryQrcodeService;
	@Autowired
	private ProductColorService productColorService;
	/**
	 * 支付前，调用方法
	 * @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);
		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;
		}

        /*//如果是有二维码的商户，进入后显示优惠价
        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 && cartDtos != null && cartDtos.size() > 0) {
                for (CartDto cartDto : cartDtos) {
                    for (QrcodeGift qrcodeGift : giftList) {
                        if (cartDto.getCartColorId().intValue() == qrcodeGift.getQrcodeColorId()
                            && qrcodeGift.getQrcodePreDiscount() != null
                            && qrcodeGift.getQrcodePreDiscount() > 0) {
                            cartDto.setProductPrice(qrcodeGift.getQrcodePreDiscount());
                        }
                    }
                }
            }
        }*/

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

		//根据openid查询该用户是否购买过订单
		ShopSalesOrderDto shopSalesOrderDto = new ShopSalesOrderDto();
		shopSalesOrderDto.setSalesOpenid(member.getUserOpenid());
		shopSalesOrderDto.setSalesStatus("2");
		int orderNum = cartService.selectOrderCount(shopSalesOrderDto);
		//如果购买过订单，则滤芯的价格可按折扣价购买
		if (orderNum > 0) {
			if (cartDtos != null && cartDtos.size() >= 1) {
				for (CartDto cartDto : cartDtos) {
					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.setProductPrice(userGiftDto.getUserDiscount());
						}
					}
				}
			}
		}

		// 判断当前提交的购物车ID，有多少产品在售
		int total = 0; // 支付金额
		int sum = 0; // 产品数量
		int productNum = 0;	//计算商品为滤芯的数量
		int machineNum = 0;	//计算商品为水机的数量
		boolean disable = true;	//标识，是否可用优惠券，当购买商品只有滤芯时禁止使用优惠券

		List<CartDto> tempCarts = new ArrayList<CartDto>();

		//查询系统规则表滤芯id信息
		String element = systemService.selectOneShopRuleById(236).getRuleDesc();//赠送滤芯类型id
		String machine = systemService.selectOneShopRuleById(237).getRuleDesc();//水机类型id
		String[]  elements = null;
		String[]  machines = null;
		StringBuilder preGift = new StringBuilder();
		if (element != null) {
			String rolesStr = element.split(":")[1];
			elements = rolesStr.split(",");
		}
		if (machine != null) {
			String rolesStr = machine.split(":")[1];
			machines = rolesStr.split(",");
		}

		String userQrcodeType = request.getParameter("userQrcodeType");
		//存在水机时赠送4个滤芯
		if(userQrcodeType != null && !"".equals(userQrcodeType)){

			//如果是扫描优惠二维码进来，则显示优惠价并赠送滤芯
			QrcodeGift gift = new QrcodeGift();
			gift.setQrcodeStatus(1);
			List<QrcodeGift> giftList = productInfoService.listQrcodeGift(gift);
			if (giftList != null && giftList.size() > 0 && cartDtos != null && cartDtos.size() > 0) {
				for (CartDto cartDto : cartDtos) {
					for (QrcodeGift qrcodeGift : giftList) {
						if (cartDto.getCartColorId().intValue() == qrcodeGift.getQrcodeColorId()) {
							switch (userQrcodeType) {
								case "1":
									if (qrcodeGift.getQrcodePreDiscount() != null && qrcodeGift.getQrcodePreDiscount() > 0) {
										cartDto.setProductPrice(qrcodeGift.getQrcodePreDiscount());
									}
									if (qrcodeGift.getQrcodePreGiftColor() != null) {
										for (int i = 0;i < cartDto.getCartNum();i++) {
											preGift.append(qrcodeGift.getQrcodePreGiftColor());
											preGift.append(",");
										}
									}
									break;
								case "2":
									if (qrcodeGift.getQrcodeSalesDiscount() != null && qrcodeGift.getQrcodeSalesDiscount() > 0) {
										cartDto.setProductPrice(qrcodeGift.getQrcodeSalesDiscount());
									}
									if (qrcodeGift.getQrcodeSalesGiftColor() != null) {
										for (int i = 0;i < cartDto.getCartNum();i++) {
											preGift.append(qrcodeGift.getQrcodeSalesGiftColor());
											preGift.append(",");
										}
									}
									break;
							}
						}
					}
				}
			}
		}

		for (CartDto cartDto : cartDtos) {
			if (cartDto.getProductStatus() != null && cartDto.getProductStatus().intValue() == 1) {
				total += cartDto.getCartNum() * cartDto.getProductPrice();
				sum++;
				tempCarts.add(cartDto);
			}
			for(int i=0,len = elements.length;i < len;i++){
				//计算商品为滤芯的数量
				if (cartDto.getProductType().intValue() == Integer.valueOf(elements[i])) {
					productNum = productNum+cartDto.getCartNum();
				}
			}
			for(int i=0,len = machines.length;i < len;i++){
				//计算商品为滤芯的数量
				if (cartDto.getProductType().intValue() == Integer.valueOf(machines[i])) {
					machineNum = machineNum+cartDto.getCartNum();
				}
			}
		}

		if(preGift.toString() != null && !"".equals(preGift.toString())){
			String[] giftss = preGift.toString().split(",");
			ProductColor color = new ProductColor();
			color.setPage(null);
			List<ProductColor> colorList = productColorService.selectProductColorList(color);
			for (int i = 0;i < giftss.length;i++) {
				boolean cartFlag = false;
				for (CartDto cart : tempCarts) {
					//判断是否已经存在该赠品，如果存在则数量加1
					if (Integer.parseInt(giftss[i]) == cart.getCartColorId() && cart.getTotal() == 0) {
						cart.setCartNum(cart.getCartNum().intValue() + 1);
						cartFlag = true;
					}
				}
				//如果不存在，则新增赠品
				if (!cartFlag) {
					for (ProductColor productColor : colorList) {
						if (Integer.parseInt(giftss[i]) == productColor.getColorId()) {
							CartDto cartDto = new CartDto();
							cartDto.setCartOpenId(member.getUserOpenid());
							cartDto.setCartProductId(productColor.getColorProductId());
							cartDto.setCartColorId(productColor.getColorId());
							cartDto.setCartNum(1);
							cartDto.setCartCreateDate(new Date());
							cartDto.setProductName(productColor.getColorProductName());
							cartDto.setProductType(productColor.getColorProductType());
							cartDto.setProductPrice(0);
							cartDto.setProductIntroduceImg(productColor.getColorProductPic());
							cartDto.setTotal(0);
							cartDto.setProductDiscount(0);
							cartDto.setProductRemark("赠送滤芯");
							cartDto.setProductColor(productColor.getColorName());
							tempCarts.add(cartDto);
						}
					}
				}
			}
		}

		//当购买商品只有滤芯时禁止使用优惠券
		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);

		dto.setCouponItems(list);

		dto.setCartId(cartIds);// 购物车ID
		dto.setPayTotal(total); // 支付金额,单位为分
		dto.setCartItems(tempCarts); // 订单项
		dto.setSuccess(true); // 请求成功
		dto.setMeonyProportion(0);
		dto.setBalance(member.getUserIncome());

		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;
	}

	/**
	 * 发起支付请求
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/pay", method = RequestMethod.POST)
	public ResultMsg requestPay(
			TempOrderDto temp,
			HttpServletRequest request
	) throws Exception {

		ResultMsg msg = new ResultMsg();
		int machineNum = 0;//所有水机的数量
		StringBuilder preGift = new StringBuilder();
		msg.setResultCode(ResultInfo.ERRORCODE);
		//当前支付时间
		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;
		}
		List<CartDto> cartDtos = cartService.selectCartItemByListId(cartId);
		if (cartDtos == null || cartDtos.size() <= 0) {// 根据购物车ID，查询数据库中对应的产品信息（ID、产品状态）
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}

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

		int total = 0; // 需要支付的总额, 单位为分


		//查询金牌会员模板id
		int templateId = systemService.selectOneShopRuleById(114).getRuleNum().intValue();
		UserGiftDto userGift = null;
		int giftNum = 0;

		/** 提前准备订单项数据 */
		/** 准备数据 */
		Order order = new Order();
		order.setSalesOrderid(OrderNOUtil.createOrderCode(member.getUserId())); // 订单ID
		List<OrderItem> list = new ArrayList<OrderItem>();
		List<Integer> cartIds = new ArrayList<Integer>();
		String userQrcodeType = request.getParameter("userQrcodeType");
		int num = productInfoService.getQrCodeByPlaceOpenId(member.getUserOpenid());
		for (CartDto cartDto : cartDtos) {

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

			if (userQrcodeType != null && !"".equals(userQrcodeType)) {

				//如果是扫描优惠二维码进来，则显示优惠价并赠送滤芯
				QrcodeGift gift = new QrcodeGift();
				gift.setQrcodeStatus(1);
				List<QrcodeGift> giftList = productInfoService.listQrcodeGift(gift);
				if (giftList != null && giftList.size() > 0) {
					for (QrcodeGift qrcodeGift : giftList) {
						if (cartDto.getCartColorId().intValue() == qrcodeGift.getQrcodeColorId()) {
							switch (userQrcodeType) {
								case "1":
									if (qrcodeGift.getQrcodePreDiscount() != null && qrcodeGift.getQrcodePreDiscount() > 0) {
										cartDto.setProductDiscount(qrcodeGift.getQrcodePreDiscount());
										cartDto.setProductPrice(qrcodeGift.getQrcodePreDiscount());
									}
									if (qrcodeGift.getQrcodePreGiftColor() != null) {
										for (int i = 0;i < cartDto.getCartNum();i++) {
											preGift.append(qrcodeGift.getQrcodePreGiftColor());
											preGift.append(",");
										}
									}
									break;
								case "2":
									if (qrcodeGift.getQrcodeSalesDiscount() != null && qrcodeGift.getQrcodeSalesDiscount() > 0) {
										cartDto.setProductDiscount(qrcodeGift.getQrcodeSalesDiscount());
										cartDto.setProductPrice(qrcodeGift.getQrcodeSalesDiscount());
									}
									if (qrcodeGift.getQrcodeSalesGiftColor() != null) {
										for (int i = 0;i < cartDto.getCartNum();i++) {
											preGift.append(qrcodeGift.getQrcodeSalesGiftColor());
											preGift.append(",");
										}
									}
									break;
							}
						}
					}
				}
			}

			//如果购买过订单，则滤芯的价格可按折扣价购买
			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.setProductPrice(userGiftDto.getUserDiscount());
					}
				}
			}

			//如果模板id等于金牌会模板id，则该用户为金牌会员下线
			if (member.getUserDealers() != null && member.getTemplateId() != null
					&& templateId == member.getTemplateId().intValue() && member.getUserResType().intValue() == 3) {
				UserGiftDto userGiftDto = new UserGiftDto();
				userGiftDto.setUserLevel(2);
				userGiftDto.setUserProductId(cartDto.getCartProductId());
				userGiftDto.setUserColorId(cartDto.getCartColorId());
				//根据商品id和会员等级查询礼品信息
				userGiftDto = productInfoService.selectUserGift(userGiftDto);
				if (userGiftDto != null) {
					cartDto.setProductPrice(userGiftDto.getUserDiscount());
					giftNum += cartDto.getCartNum();
					if (userGift == null) {
						userGift = userGiftDto;
					}
				}
			}

			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.setItemProductType(cartDto.getProductType());
				item.setItemProductPrice(cartDto.getProductDiscount());
				item.setItemColorId(cartDto.getCartColorId());
				list.add(item);
			}
		}

		//扫描优惠二维码赠送赠品信息
		if (preGift != null && !"".equals(preGift.toString())) {
			String[] giftss = preGift.toString().split(",");
			ProductColor color = new ProductColor();
			color.setPage(null);
			List<ProductColor> colorList = productColorService.selectProductColorList(color);
			for (int i = 0;i < giftss.length;i++) {
				boolean cartFlag = false;
				for (OrderItem item : list) {
					//判断是否已经存在该赠品，如果存在则数量加1
					if (Integer.parseInt(giftss[i]) == item.getItemColorId() && item.getItemTotal() == 0) {
						item.setItemNum(item.getItemNum().intValue() + 1);
						cartFlag = true;
					}
				}
				//如果不存在，则新增订单项
				if (!cartFlag) {
					for (ProductColor productColor : colorList) {
						if (Integer.parseInt(giftss[i]) == productColor.getColorId()) {
							OrderItem orderItem = new OrderItem();
							orderItem.setItemNum(1);
							orderItem.setItemProductDiscount(0);
							orderItem.setItemProductId(productColor.getColorProductId());
							orderItem.setItemProductName(productColor.getColorProductName());
							orderItem.setItemProductPic(productColor.getColorProductPic());
							orderItem.setItemSalesOrderid(order.getSalesOrderid());
							orderItem.setItemTotal(0);
							orderItem.setItemProductType(productColor.getColorProductType());
							orderItem.setItemProductPrice(0);
							orderItem.setItemColorId(productColor.getColorId());
							list.add(orderItem);
						}
					}
				}
			}
		}

		//如果模板id等于金牌会模板id，来源是3，则该用户为金牌会员直接下线，直接下线送三年滤芯
		if (member.getUserDealers() != null && member.getTemplateId() != null &&
				templateId == member.getTemplateId().intValue() && member.getUserResType().intValue() == 3) {
			//当userGift不为空时，说明该用户购买的商品有奖励礼品，奖励礼品取第一个产品的，不适用于多个产品有不同奖励礼品的情况
			if (userGift != null && userGift.getUserGiftId() != null && !"".equals(userGift.getUserGiftId())) {
				Product product = productInfoService.getProductByProductId(userGift.getUserGiftId(),userGift.getUserGiftColor());
				OrderItem orderItem = new OrderItem();
				orderItem.setItemNum(userGift.getUserGiftCount() * giftNum);
				orderItem.setItemProductDiscount(0);
				orderItem.setItemProductId(userGift.getUserGiftId());
				orderItem.setItemProductName(product.getProductName());
				orderItem.setItemProductPic(product.getProductIntroduceImg());
				orderItem.setItemSalesOrderid(order.getSalesOrderid());
				orderItem.setItemTotal(0);
				orderItem.setItemProductType(product.getProductType().getTypeId());
				orderItem.setItemProductPrice(0);
				orderItem.setItemColorId(userGift.getUserColorId());
				list.add(orderItem);
			}
		}

		// 准备订单对象
		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(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;
		}

		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
			order.setSalesStatus(2);
			cartService.updateOrderStatus(order);
			//修改优惠券状态
			if(hasCoupon){
				couponItem.setCouponUseStatus(2);
				couponItem.setCouponUseDate(new Date());//添加使用时间
				int i=couponItemService.updateCouponItemById(couponItem);
			}

			//更新账户余额
			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());

		}
		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) {
			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;
	}
}
