package com.iamberry.wechat.handles.order;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.cart.CartDto;
import com.iamberry.wechat.core.entity.cart.OrderPayDto;
import com.iamberry.wechat.core.entity.cart.SendPayDto;
import com.iamberry.wechat.core.entity.cart.TempOrderDto;
import com.iamberry.wechat.core.entity.channel.ChannelPrice;
import com.iamberry.wechat.core.entity.channel.ChannelRebate;
import com.iamberry.wechat.core.entity.channel.ChildChannel;
import com.iamberry.wechat.core.entity.channel.MainChannel;
import com.iamberry.wechat.core.entity.coupon.*;
import com.iamberry.wechat.core.entity.customized.CustomizedTooth;
import com.iamberry.wechat.core.entity.integral.StayIntegral;
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.core.entity.product.ProductColor;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.cart.CartService;
import com.iamberry.wechat.face.cart.ProductInfoService;
import com.iamberry.wechat.face.channel.ChannelPriceService;
import com.iamberry.wechat.face.channel.ChannelRebateService;
import com.iamberry.wechat.face.channel.ChildChannelService;
import com.iamberry.wechat.face.channel.MainChannelService;
import com.iamberry.wechat.face.coupon.CouponItemService;
import com.iamberry.wechat.face.coupon.CouponTypeService;
import com.iamberry.wechat.face.coupon.SalesActivitiesService;
import com.iamberry.wechat.face.customized.CustomizedToothService;
import com.iamberry.wechat.face.home.HomeService;
import com.iamberry.wechat.face.integral.UseIntegralService;
import com.iamberry.wechat.face.member.CashLogService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.mq.EfastOrderService;
import com.iamberry.wechat.face.order.AdminOrderService;
import com.iamberry.wechat.face.pay.PayService;
import com.iamberry.wechat.face.porduct.ProductColorService;
import com.iamberry.wechat.face.qrcode.TemporaryQrcodeService;
import com.iamberry.wechat.face.reback.RebackServices;
import com.iamberry.wechat.handles.mq.MQServiceProxy;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.OrderNOUtil;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.ValidatorUtil;
import com.iamberry.wechat.utils.ActivityUtil;
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 javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 何秀刚
 * Class Description: 订单hander
 * Create Date:2016年4月20日
 * Update Date:2016年4月20日
 */
@Controller
@RequestMapping("/wechat/order")
public class OrderHandler {
	@Autowired
	private RatFWLogger ratFWLogger;

	@Autowired
	private CartService cartService;

	@Autowired
	private HomeService homeService;

	@Autowired
	private SystemService systemService;

	@Autowired
	private ValidatorUtil validatorUtil;

	@Autowired
	private PayService payService;
	@Autowired
	private MQServiceProxy mQservice;
	@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;
	@Autowired
	private UseIntegralService useIntegralService;
	@Autowired
	private EfastOrderService efastOrderService;
	@Autowired
	private CustomizedToothService customizedToothService;
	@Autowired
	private AdminOrderService adminOrderService;
	@Autowired
	private ChannelPriceService channelPriceService;
	@Autowired
	private ChannelRebateService channelRebateService;
	@Autowired
	private MainChannelService mainChannelService;
	@Autowired
	private ChildChannelService childChannelService;
	@Autowired
	private ActivityUtil activityUtil;
	@Autowired
	private SalesActivitiesService salesActivitiesService;

	/**
	 * 支付前，调用方法
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/payBefore")
	public ResultMsg payBefore(HttpServletRequest request,
							   @RequestParam(value = "channelType",defaultValue = "0") Integer channelType,
							   @RequestParam(value = "channelId",defaultValue = "0") Integer channelId
	) throws Exception {

		ResultMsg msg = new ResultMsg();
		msg.setResultCode(ResultInfo.ERRORCODE);

		OrderPayDto dto = new OrderPayDto();
		// 用户信息
		String openId  = WechatUtils.getUserBySession(request).getUserOpenid();
		Member member = memberService.getMemberByUserOpenId(openId);
		String cartIds = request.getParameter("cartIds");	//普通牙刷就是购物车的id，  定制牙刷为定制表（tb_iamberry_customized_tooth）的id
		String isCustomize = request.getParameter("isCustomize");	// 1：普通牙刷购买  2：定制牙刷购买
		if(isCustomize == null || "".equals(isCustomize)){	//默认为普通牙刷
			isCustomize = "1";
		}

		if(channelType > 0 && channelId > 0){
			if(channelType == 1){
						MainChannel mainChannel = mainChannelService.getMainChannelById(channelId);
				dto.setChannelName(mainChannel.getMainChannelName());
			}else{
				ChildChannel childChannel = childChannelService.getChildChannelById(channelId);
				dto.setChannelName( childChannel.getChildChannelName());
			}
		}

		if (cartIds == null || isCustomize==null) {
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}
		cartIds = cartIds.trim();
		/*获取购物项--start*/
		List<CartDto> cartDtos = new ArrayList<>();
		if("1".equals(isCustomize)){
			// 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、产品状态）
			cartDtos = cartService.selectCartItemByListId(cartIntList);
			if (cartDtos == null || cartDtos.size() <= 0) {
				msg.setMessage(ResultInfo.cartEmptyError);
				return msg;
			}

			Integer toothAllbrush = 0;	//牙刷个数
			Integer toothAuthbrush = 0;	//成人牙刷个数
			Integer toothKidsbrush = 0;	//儿童牙刷个数

			Integer allAmount = 0;	//总金额

			/*上朵分销，查看是否为分销*/
			for (CartDto cd : cartDtos) {
				cd.setIsSelfLifting(2);	//不能自提

				if(channelType > 0 && channelId > 0){
					ChannelPrice channelPrice = channelPriceService.getChannelPriceByChannel(channelId,channelType,cd.getCartColorId());
					if(channelPrice != null){
						cd.setProductPrice( channelPrice.getChannelPriceOffer());	//因结算页面都是取price，所以都赋值优惠价
						cd.setProductDiscount( channelPrice.getChannelPriceOffer());
						cd.setIsSelfLifting(1);
					}
				}
				if(cd.getProductType() == 100){		//当订单中有电动牙刷时，+1
					toothAllbrush += cd.getCartNum();
				}
				if(cd.getColorToothType() == 2){	//牙刷分类 1：非牙刷，非刷头 2：成人牙刷 3：儿童牙刷 4：亲子款（成人+儿童） 5：刷头
					toothAuthbrush += cd.getCartNum();
				}else if(cd.getColorToothType() == 3){
					toothKidsbrush += cd.getCartNum();
				}

				allAmount += cd.getCartNum()*cd.getProductPrice();
			}

			ActivityDate activityDate = activityUtil.doubleTwelve();
			if(channelType > 0 && channelId > 0){
				activityDate.setStatus(false);
			}else{
				//非分销渠道，才能有促销
				if(activityDate.isStatus()){

					/*计算促销之后的支付金额*/
					Integer promotionAmout = allAmount;	//促销之后的金额

					SalesActivities sa = new SalesActivities();
					sa.setSalesActivitiesStatus(1);
					sa.setSalesActivitiesType(1);
					sa.setSalesActivitiesScenes(1);
					List<SalesActivities> salesActivitiesList = salesActivitiesService.getSalesActivitiesList(sa);
					activityDate.setSalesActivitiesList(salesActivitiesList);
					for (SalesActivities salesActivities : activityDate.getSalesActivitiesList()){
						if(promotionAmout >= salesActivities.getSalesActivitiesFull()){
							promotionAmout = allAmount - salesActivities.getSalesActivitiesReduction();
							break;
						}
					}
//					1、买任意成人款牙刷送进口艾科弗牙膏
//					2、买任意儿童款牙刷（普通、派火车款,亲子款）加送儿童护齿书籍（进口艾科弗牙膏+儿童护齿书籍）
//					3、满499送进口艾科弗牙膏+进口Ora2漱口水（按实际支付金额）
//					4、满699元送进口艾科弗牙膏+MAC口红（按实际支付金额）
					if(promotionAmout > 69900){
						addFullReduction(4,cartDtos);
					}
					if(promotionAmout > 49900){
						addFullReduction(3,cartDtos);
					}
					if(toothKidsbrush > 0){
						addFullReduction(2,cartDtos);
					}
					if(toothAuthbrush > 0){
						addFullReduction(1,cartDtos);
					}
				}
			}
			dto.setActivityDate(activityDate);
		}else if("2".equals(isCustomize)){
			Integer id = Integer.valueOf(cartIds);
			CustomizedTooth customizedTooth = customizedToothService.getCustomizedToothById(id);
			CartDto cartDto = new CartDto();
			cartDto.setCartOpenId(member.getUserOpenid());
			cartDto.setCartProductId(customizedTooth.getProductId());
			cartDto.setCartColorId(customizedTooth.getColorId());
			cartDto.setCartNum(1);
			ProductColor productColor = productColorService.selectProductColorById(customizedTooth.getColorId());
			if(productColor == null ){
				msg.setMessage("获取信息失败");
				return msg;
			}
			cartDto.setProductStatus(productColor.getColorStatus());
			cartDto.setProductType(productColor.getColorProductType());
			cartDto.setProductPrice(productColor.getColorPrice());
			cartDto.setProductDiscount(productColor.getColorDiscount());
			cartDtos.add(cartDto);
		}else{
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}
		/*获取购物项--end*/

		// 判断当前提交的购物车ID，有多少产品在售
		int total = 0; // 支付金额
		int toothbrushTotal = 0; // 支付金额
		int sum = 0; // 产品数量
		boolean disable = false;	//标识，是否可以使用(新人券)优惠券，当购买商品需要有牙刷时才能使用优惠券 - 20180316 以前
		Integer brushFlag = 0;	//标识，是否可以使用(新人券)优惠券，只能购买刷头的时候才能使用 - 20180316 以后
		Integer combinationOffer = 0;	//标识，是否有组合优惠套装，购买组合优惠套装不可使用优惠券 - 20181024
		String element = systemService.selectOneShopRuleById(249).getRuleDesc();
		String brushelEment = systemService.selectOneShopRuleById(253).getRuleDesc();
		String combinationOfferColorIds = systemService.selectOneShopRuleById(259).getRuleDesc();

		List<CartDto> tempCarts = new ArrayList<CartDto>();
		for (CartDto cartDto : cartDtos) {
			if((cartDto.getColorAllNum() - cartDto.getColorSoldNum()) < 1){
				msg.setMessage(ResultInfo.cartNoNumError);
				return msg;
			}
			if (cartDto.getProductStatus() != null && cartDto.getProductStatus().intValue() == 1) {
				total += cartDto.getCartNum() * cartDto.getProductPrice();
				sum++;
				tempCarts.add(cartDto);
			}else if(cartDto.getProductStatus().intValue() != 1){
				msg.setMessage(ResultInfo.cartNoStatusError);
				return msg;
			}

			String[] els = element.split("-");
			for(String el : els){
				if(cartDto.getProductType().equals(Integer.valueOf(el))){		//订单中没有牙刷的时候，不能使用100元优惠券
					disable = true;
					toothbrushTotal += cartDto.getCartNum() * cartDto.getProductPrice();
				}
			}
			String[] brushelEls = brushelEment.split("-");
			for(String brushelEl : brushelEls){
				if(cartDto.getProductType().equals(Integer.valueOf(brushelEl))){		//判断订单中是否有刷头，有刷头 brushFlag 大于0；
					brushFlag += cartDto.getCartNum();
				}
			}
			String[] coColorId = combinationOfferColorIds.split("-");
			for(String colorId : coColorId){
				if(cartDto.getCartColorId().equals(Integer.valueOf(colorId))){		//判断订单中是否有优惠组合套装
					combinationOffer += cartDto.getCartNum();
				}
			}
		}
		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> couponItemDtoList = couponItemService.getCouponItemDtoList(cDto);
		List<CouponItemDto> list = new ArrayList<>();
		for(CouponItemDto couponItemDto : couponItemDtoList){
			boolean flag = true;

			/*达到优惠券所设置的金额 couponConsumeEnough*/
			if(total >= couponItemDto.getCouponConsumeEnough()){
				/*新人卷没有其他限制*/
				if(couponItemDto.getCouponIsNewPeople() == 1){  //当券为新人券
					if(member.getUserIdentity() != 1 || brushFlag<1){  //不为会员，或者没有牙刷刷头都无法使用
						flag = false;
					}
				}else if(couponItemDto.getCouponIsPurchase() == 1){  ///*控制是否需要购买的有牙刷*/
					if(!disable){     //订单中没有牙刷
						flag = false;
					}
				}
				/*需要购买牙刷到某种金额*/
				if(toothbrushTotal <  couponItemDto.getCouponToothbrushEnough()){
					flag = false;
				}
			}else{
				flag = false;
			}
			if(flag){
				list.add(couponItemDto);
			}
		}
		/*插入优惠券*/
		if(channelType <= 0 && channelId <= 0 && combinationOffer < 1){
			dto.setCouponItems(list);
		}else if(combinationOffer > 0 && brushFlag - combinationOffer > 0 ){
			dto.setCouponItems(list);
		}

		dto.setCartId(cartIds);// 购物车ID
		dto.setPayTotal(total); // 支付金额,单位为分
		dto.setIsCustomize(isCustomize);//判断是否为定制牙刷
		dto.setCartItems(tempCarts); // 订单项
		dto.setSuccess(true); // 请求成功
		dto.setMeonyProportion(0);

		//回显用户支付过的地址信息
		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;
	}


	/**
	 * 测试推送efast
	 * @return
	 * @throws Exception
	 */
//	@ResponseBody
//	@RequestMapping(value = "/toEfast")
//	public ResultMsg toEfast(HttpServletRequest request) throws Exception {
//		ResultMsg msg = new ResultMsg();
//
//		Order order = new Order();
//		order.setSalesOrderid("0119173614I15563Z");
//		efastOrderService.addOrderInfoToEfastTest(order);
//
//		msg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
//		msg.setData("");
//		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.getOrderAddressMoblie() == null || "".equals(temp.getOrderAddressMoblie())){
			msg.setMessage("电话号码为空，请重新添加收货地址信息！");
			return msg;
		}
		if(temp.getOrderAddressMoblie().length() != 11){
			msg.setMessage("电话号码错误，请重新添加收货地址信息！");
			return msg;
		}
		if(temp.getOrderAddressName() == null || "".equals(temp.getOrderAddressName())){
			msg.setMessage("收货人姓名为空，请重新添加收货地址信息！");
			return msg;
		}
		if(temp.getCartIdStr() == null || "".equals(temp.getCartIdStr())){
			msg.setMessage("未选择商品，请重新选择商品并结算！");
			return msg;
		}
		if(temp.getOrderUserRemark() != null){
			if (temp.getOrderUserRemark().length() > 100) {
				msg.setMessage("备注只能输入100个字符");
				return msg;
			}
		}
		//salesTransportationType
		if(temp.getSalesTransportationType() == 1){
			if(temp.getOrderAddressInfo() == null || "".equals(temp.getOrderAddressInfo())){
				msg.setMessage("收货人地址为空，请重新添加收货地址信息！");
				return msg;
			}
		}

		if(temp.getIsCustomize() == null || "".equals(temp.getIsCustomize())){		//默认为1
			temp.setIsCustomize("1");
		}

		List<CartDto> cartDtos = new ArrayList<>();
		ActivityDate activityDate = activityUtil.doubleTwelve();	//活动内容
		if("1".equals(temp.getIsCustomize())){	//  1：普通牙刷购买  2：定制牙刷购买
			Integer [] cartId = null;
			try {
				cartId = checkCartIdListString(temp.getCartIdStr());
			} catch (Exception e) { // 一旦发生异常，表示错误
				msg.setMessage(ResultInfo.paramFormatError);
				return msg;
			}
			cartDtos = cartService.selectCartItemByListId(cartId);


			Integer toothAllbrush = 0;	//牙刷个数
			Integer toothAuthbrush = 0;	//成人牙刷个数
			Integer toothKidsbrush = 0;	//儿童牙刷个数
			Integer allAmount = 0;	//总金额


			for (CartDto cd : cartDtos) {
				if(cd.getProductType() == 100){		//当订单中有电动牙刷时，+1
					toothAllbrush += cd.getCartNum();
				}
				if(cd.getColorToothType() == 2){	//牙刷分类 1：非牙刷，非刷头 2：成人牙刷 3：儿童牙刷 4：亲子款（成人+儿童） 5：刷头
					toothAuthbrush += cd.getCartNum();
				}else if(cd.getColorToothType() == 3){
					toothKidsbrush += cd.getCartNum();
				}
				allAmount += cd.getCartNum()*cd.getProductPrice();
			}

			if(temp.getChannelType() > 0 && temp.getChannelId() > 0){
				activityDate.setStatus(false);
			}else {
				/*计算促销之后的支付金额*/
				Integer promotionAmout = allAmount;	//促销之后的金额

				SalesActivities sa = new SalesActivities();
				sa.setSalesActivitiesStatus(1);
				sa.setSalesActivitiesType(1);
				sa.setSalesActivitiesScenes(1);
				List<SalesActivities> salesActivitiesList = salesActivitiesService.getSalesActivitiesList(sa);
				activityDate.setSalesActivitiesList(salesActivitiesList);
				for (SalesActivities salesActivities : activityDate.getSalesActivitiesList()){
					if(promotionAmout >= salesActivities.getSalesActivitiesFull()){
						promotionAmout = allAmount - salesActivities.getSalesActivitiesReduction();
						break;
					}
				}

				//非分销渠道，才能有促销
				if (activityDate.isStatus()) {
//					1、买任意成人款牙刷送进口艾科弗牙膏
//					2、买任意儿童款牙刷（普通、派火车款,亲子款）加送儿童护齿书籍（进口艾科弗牙膏+儿童护齿书籍）
//					3、满499送进口艾科弗牙膏+进口Ora2漱口水（按实际支付金额）
//					4、满699元送进口艾科弗牙膏+MAC口红（按实际支付金额）
					if(promotionAmout > 69900){
						addFullReduction(4,cartDtos);
					}
					if(promotionAmout > 49900){
						addFullReduction(3,cartDtos);
					}
					if(toothKidsbrush > 0){
						addFullReduction(2,cartDtos);
					}
					if(toothAuthbrush > 0){
						addFullReduction(1,cartDtos);
					}
				}
			}
		}else if("2".equals(temp.getIsCustomize())){
			Integer id = Integer.valueOf(temp.getCartIdStr());
			CustomizedTooth customizedTooth = customizedToothService.getCustomizedToothById(id);
			CartDto cartDto = new CartDto();
			cartDto.setCartId(Integer.valueOf(temp.getCartIdStr()));
			cartDto.setCartOpenId(member.getUserOpenid());
			cartDto.setCartProductId(customizedTooth.getProductId());
			cartDto.setCartColorId(customizedTooth.getColorId());
			cartDto.setCartNum(1);
			ProductColor productColor = productColorService.selectProductColorById(customizedTooth.getColorId());
			if(productColor == null ){
				msg.setMessage("获取信息失败");
				return msg;
			}
			cartDto.setProductStatus(productColor.getColorStatus());
			cartDto.setProductType(productColor.getColorProductType());
			cartDto.setProductPrice(productColor.getColorPrice());
			cartDto.setProductDiscount(productColor.getColorDiscount());
			cartDto.setProductName(productColor.getColorProductName());
			cartDto.setProductIntroduceImg(productColor.getColorImg());
			cartDtos.add(cartDto);
		}else{
			msg.setMessage("error");
			return msg;
		}

		if (cartDtos == null || cartDtos.size() <= 0) {// 根据购物车ID，查询数据库中对应的产品信息（ID、产品状态）
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}

		/*是否含有电动牙刷*/
		boolean isContainProduct = false;
		boolean brush1Flag = false;	//60元优惠券
		boolean brush2Flag = false;	//刷头兑换券
		Integer brusHeadNumber = 0;	//刷头个数
		Integer combinationOffer = 0;// 组合优惠个数
//		String element = systemService.selectOneShopRuleById(249).getRuleDesc();
		String brushelEment = systemService.selectOneShopRuleById(253).getRuleDesc();
		/*优惠套装的颜色id*/
		String combinationOfferColorIds = systemService.selectOneShopRuleById(259).getRuleDesc();

		int brushelTotal = 0; // 牙刷总金额
		int brushHeadTotal = 0; // 刷头总金额
		int brushelCouponTotal = 0;  //优惠总价
		int combinationOfferTotal = 0;  //组合优惠总价

		boolean isChannelProduct = false;	//没有上朵分销商品

		int total = 0; // 需要支付的总额, 单位为分
		int channelTotal = 0; // 如果有分销，此值为分销总额，没有就与total值等同
		/** 提前准备订单项数据 */
		/** 准备数据 */
		Order order = new Order();
		order.setSalesOrderid(OrderNOUtil.createOrderCode(member.getUserId())); // 订单ID
		List<OrderItem> list = new ArrayList<OrderItem>();
		List<Integer> cartIds = new ArrayList<Integer>();
		int num = productInfoService.getQrCodeByPlaceOpenId(member.getUserOpenid());
		for (CartDto cartDto : cartDtos) {
			if (cartDto.getProductStatus() != null && cartDto.getProductStatus().intValue() == 1) {
				cartIds.add(cartDto.getCartId());
				Integer subTotal = cartDto.getCartNum() * cartDto.getProductPrice(); // 小计
				Integer discount = 0,price=0;
				total += subTotal;

				/*上朵分销，*/
				if(temp.getChannelType() > 0 && temp.getChannelId() > 0){
					ChannelPrice channelPrice = channelPriceService.getChannelPriceByChannel(temp.getChannelId(),temp.getChannelType(),cartDto.getCartColorId());
					if(channelPrice != null){
						subTotal = cartDto.getCartNum() * channelPrice.getChannelPriceOffer();
						discount = channelPrice.getChannelPriceOffer();
						price =channelPrice.getChannelOriginalPrice();
						isChannelProduct = true;	//上朵分销减价
					}
				}
				channelTotal += subTotal;
				/*上朵分销，*/

				OrderItem item = new OrderItem();
				item.setItemNum(cartDto.getCartNum());

				if(discount > 0 ){
					item.setItemProductDiscount(discount);
				}else{
					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());
				if(price > 0 ){
					item.setItemProductPrice(price);
				}else{
					item.setItemProductPrice(cartDto.getProductDiscount());
				}

				item.setItemColorId(cartDto.getCartColorId());
				list.add(item);

				if(cartDto.getProductType() == 100){		//当订单中有电动牙刷时，isContainProduct为true
					brushelTotal += subTotal;
					isContainProduct = true;
				}

				String[] brushelEls = brushelEment.split("-");
				for(String brushelEl : brushelEls){
					if(cartDto.getProductType().equals(Integer.valueOf(brushelEl)) && cartDto.getCartProductId() != 310){		//判断订单中是否有刷头，有刷头 brushFlag 为true；
						brush1Flag = true;
						brush2Flag = true;
						//刷头个数
						brusHeadNumber += cartDto.getCartNum();
						brushHeadTotal += subTotal;
						if(brushelCouponTotal == 0 || brushelCouponTotal < cartDto.getProductPrice()){
							brushelCouponTotal = cartDto.getProductPrice();
						}
					}
					if(cartDto.getCartProductId() == 310){
						//刷头个数
						brusHeadNumber += cartDto.getCartNum();
						combinationOfferTotal += subTotal;
					}
				}

				/*获取优惠套装个数*/
				String[] coColorId = combinationOfferColorIds.split("-");
				for(String colorId : coColorId){
					if(cartDto.getCartColorId().equals(Integer.valueOf(colorId))){		//判断订单中是否有优惠组合套装
						combinationOffer += cartDto.getCartNum();
					}
				}
			}else if(cartDto.getProductStatus().intValue() != 1){
				msg.setMessage(ResultInfo.cartNoStatusError);
				return msg;
			}
		}

		// 准备订单对象
		order.setSalesOpenid(member.getUserOpenid()); // openid 
		order.setSalesAmount(total); // 订单金额

		if(total > channelTotal && temp.getChannelType() > 0 && temp.getChannelId() > 0){		//如果有分销优惠，将直接使用分销优惠价
			total = channelTotal;
		}

		int mustPay=0;

		String couponId=temp.getCouponId();
		CouponItemDto couponItemDto=new CouponItemDto();
		CouponItem couponItem=new CouponItem();
		boolean hasCoupon=false;
		//获取优惠券不为空		//////////////////////上朵分销不能使用优惠券
		if(couponId!=null && !couponId.equals("") && isChannelProduct==false){
			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());
			couponItem.setCouponIsNewPeople(couponItemDto.getCouponIsNewPeople());

			if(null==couponItemDto || !couponItemDto.getUseropenid().equals(member.getUserOpenid()) || couponItemDto.getCouponUseStatus()!=1){
				msg.setMessage(ResultInfo.COUPON_INVALID); //优惠券无效
				return msg;
			}

			Date couponUseEndDate = couponItem.getCouponUseEndDate();
			Calendar nowTime = Calendar.getInstance();
			nowTime.setTime(couponUseEndDate);
			nowTime.set(Calendar.HOUR_OF_DAY, 23);
			nowTime.set(Calendar.MINUTE, 59);
			nowTime.set(Calendar.SECOND, 59);
			couponUseEndDate = nowTime.getTime();
			if(couponUseEndDate.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(couponItemDto.getCouponIsNewPeople() == 1){  //当券为新人券
				if(member.getUserIdentity() != 1 || !brush1Flag || !brush2Flag){  //不为会员，或者没有牙刷刷头都无法使用
					msg.setMessage(ResultInfo.COUPON_NO_MEMBER); //非会员需要购买电动牙刷才能使用该优惠券
					return msg;
				}
				if(combinationOffer > 0 && brusHeadNumber - combinationOffer < 1){
					msg.setMessage(ResultInfo.COUPON_YOUHUI); //非会员需要购买电动牙刷才能使用该优惠券
					return msg;
				}
			}else if(couponType.getCouponIsPurchase() == 1){/*判断优惠券是否购买牙刷必须优惠券，与新人卷 分开*/
				if(!isContainProduct){
					msg.setMessage(ResultInfo.COUPON_NO_TOOTH);  //100元现金券
					return msg;
				}
			}

			/*需要购买牙刷到某种金额*/
			if(brushelTotal <  couponItemDto.getCouponToothbrushEnough()){
				msg.setMessage(ResultInfo.COUPON_NO_TOOTH_AMOUNT);  //100元现金券
				return msg;
			}

			//优惠券的类型，是直接减免额度 还是折扣价
			if(couponType.getCouponType()==1){
				if(couponItemDto.getCouponIsNewPeople() == 1 && couponItemDto.getCouponId() == 20000){  //当券 新人卷    刷头抵扣卷
					total = total - brushelCouponTotal;
				}else if(couponItemDto.getCouponIsNewPeople() == 1 && couponItemDto.getCouponId() ==40000){			////当券 新人卷    60元优惠券
					int br = 0;
					br = brushHeadTotal - couponType.getCouponReduce();	//刷头总价减去优惠券金额  小于零（只需要减去刷头总价） 大于零（需要减去优惠券总价）
					if(br <= 0){
						total = total - brushHeadTotal;
					}else{
						total = total - couponType.getCouponReduce();
					}
				}else{
					total=total-couponType.getCouponReduce();
				}
			}else if(couponType.getCouponType()==2){
				Integer all =  new Integer(total);
				total=total*couponType.getCouponReduce()/100;
			}
		}
		if(total==0 || total<0){
			total=0;
			mustPay=0;
		}else{
			mustPay=total;
		}

		//双十二期间，全场满328元减50元，全场满499元减100元，全场满满699元减150元
		if (activityDate.isStatus()) {
			for (SalesActivities salesActivities : activityDate.getSalesActivitiesList()){
				if(mustPay >= salesActivities.getSalesActivitiesFull()){
					mustPay = mustPay - salesActivities.getSalesActivitiesReduction();
					break;
				}
			}
		}

		Integer salesPostage = 0;
		//当总金额小于30 的时候，不包邮，需要10块钱邮费
		if(mustPay < 3000){
			salesPostage = 1000;
			mustPay = mustPay+1000;
		}

		order.setSalesYetAmount(mustPay);
		order.setSalesRateAmount(0);
		order.setSalesIntegralNum(0); // 订单使用积分
		order.setSalesCreateDate(new Date()); // 创建时间
		order.setBalancePayAmount(0); //账户余额支付金额
		order.setCouponId(couponId);   //优惠券id
		order.setSalesPostage(salesPostage);	//邮费金额

		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()); // 用户备注

		order.setSalesChannelId(temp.getChannelId());
		order.setSalesChannelType(temp.getChannelType());
		order.setSalesTransportationType(temp.getSalesTransportationType());	//salesTransportationType	订单运输类型  1:邮寄  2:自提

		if(temp.getSalesTransportationType() == 2){
			if(temp.getChannelType() == 1){
				MainChannel mainChannel = mainChannelService.getMainChannelById(temp.getChannelId());
				order.setSalesChannelAddress(mainChannel.getMainChannelName());	//salesChannelAddress
			}else if(temp.getChannelType() == 2){
				ChildChannel childChannel = childChannelService.getChildChannelById(temp.getChannelId());
				order.setSalesChannelAddress(childChannel.getChildChannelName());
			}
		}

		// 保存
		boolean flag = false;
		try {
			flag = cartService.addOrderAndSaveOrderItem(order, list, cartIds, temp.getIsCustomize());
			//System.out.println("====插入订单列表信息===="+flag);
			//修改优惠券状态为临时状态
			if(hasCoupon){
				couponItem.setCouponUseStatus(7);
				couponItemService.updateCouponItemById(couponItem);
			}

			/*分销添加返利 -- start */
			List<OrderItem> orderItemList = adminOrderService.getShopOrderItemByOrderId(order.getSalesOrderid());
			try{
				for (OrderItem oi:orderItemList) {
					if(temp.getChannelType() > 0 && temp.getChannelId() > 0){
						ChannelPrice channelPrice = channelPriceService.getChannelPriceByChannel(temp.getChannelId(),temp.getChannelType(),oi.getItemColorId());
						if(channelPrice != null){
							Integer rebateAmount = channelPrice.getChannelRebateAmount();	//channelRebateAmount  返利金额
							rebateAmount = rebateAmount * oi.getItemNum();

							ChannelRebate channelRebate = new ChannelRebate();
							channelRebate.setRebateSalesOrderId(order.getSalesOrderid());
							channelRebate.setRebackFromOpenId(member.getUserOpenid());
							channelRebate.setRebateItemId(oi.getItemId());
							channelRebate.setRebackChannelType(temp.getChannelType());
							channelRebate.setRebackChannelId(temp.getChannelId());
							channelRebate.setRebackAmount(rebateAmount);
							channelRebate.setRebackStatus(1); 	//1:待返利
							Integer fl = channelRebateService.save(channelRebate);
							if(fl < 1){
								ratFWLogger.info("返利生成失败！失败订单号："+order.getSalesOrderid());
							}
						}
					}
				}
			}catch (Exception e){
				ratFWLogger.info("返利生成错误！失败订单号："+order.getSalesOrderid());
				e.printStackTrace();
			}
			/*分销添加返利 -- end */
		} catch (Exception e) {
			flag = false;
			System.out.println("====插入订单列表信息失败====");
			e.printStackTrace();
			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"));
			System.out.println("支付返回result="+result.getPayData());
			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){
			List<OrderItem> orderItemList = adminOrderService.getShopOrderItemByOrderId(order.getSalesOrderid());
			/*调整库存*/
			for (int i = 0; i < orderItemList.size(); i++) {
				Integer fl = productColorService.updateAddSoldNum(orderItemList.get(i).getItemColorId(),orderItemList.get(i).getItemNum());
 				if (fl < 1) {
					ratFWLogger.info("售出修改数量失败，订单号为:" +orderItemList.get(i).getItemSalesOrderid() );
				}else{
					ratFWLogger.info("售出修改数量成功，订单号为:" +orderItemList.get(i).getItemSalesOrderid()
							+";颜色id为："+orderItemList.get(i).getItemColorId()+"的数量减去"+orderItemList.get(i).getItemNum());
				}
			}
			/*调整库存*/

			//设置订单状态，还有优惠券id
			order.setSalesStatus(2);
			cartService.updateOrderStatus(order);
			//修改优惠券状态
			if(hasCoupon){
				couponItem.setCouponUseStatus(2);
				couponItem.setCouponUseDate(new Date());//添加使用时间
				int i=couponItemService.updateCouponItemById(couponItem);
			}
			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(HttpServletRequest request,
			@RequestParam(value = "orderId") String orderId) {
		Member member = WechatUtils.getUserBySession(request); // 当前用户
		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.setData(orderId);
			msg.setStatus(true);
			return msg;
		}
		msg.setResultCode(ResultInfo.ERRORCODE);
		msg.setMessage(NameUtils.getConfig("ERRORINFO"));
		msg.setData(orderId);
		msg.setStatus(false);
		return msg;
	}

	/**
	 * 获取订单支付的积分
	 * @param orderId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getOrderIntegral")
	public ResultMsg getOrderIntegral(HttpServletRequest request,@RequestParam(value = "orderId") String orderId) {
		Member member = WechatUtils.getUserBySession(request); // 当前用户
		ResultMsg msg = new ResultMsg();
		msg.setResultCode(ResultInfo.ERRORCODE);
		//Integer orderStatus = cartService.selectOrderStatusByOrderId(orderId);
		if(orderId == null || "".equals(orderId)){
			msg.setResultCode(ResultInfo.ERRORCODE);
			msg.setMessage(NameUtils.getConfig("未查询到订单信息！"));
			msg.setStatus(false);
			return msg;
		}
		StayIntegral stayIntegral = new StayIntegral();
		stayIntegral.setOrderId(orderId);
		List<StayIntegral>  listStayIntegral = useIntegralService.listStayIntegral(stayIntegral);
		if (listStayIntegral != null && listStayIntegral.size() > 0) {
			msg.setResultCode(ResultInfo.SUCCESSCODE);
			msg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			msg.setData(listStayIntegral.get(0).getStayNumber());
			msg.setStatus(true);
			return msg;
		}else{
			msg.setResultCode(ResultInfo.SUCCESSCODE);
			msg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			msg.setData(0);
			msg.setStatus(true);
			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;
	}

	/**
	 * 满赠
		 1、买任意成人款牙刷送进口艾科弗牙膏
		 2、买任意儿童款牙刷（普通、派火车款,亲子款）加送儿童护齿书籍（进口艾科弗牙膏+儿童护齿书籍）
		 3、满499送进口艾科弗牙膏+进口Ora2漱口水（按实际支付金额）
		 4、满699元送进口艾科弗牙膏+MAC口红（按实际支付金额）
	 * @param type
	 * @param cartDtos
	 * @return
	 */
	private void addFullReduction(Integer type, List<CartDto> cartDtos){
		switch (type){
			case 4 :
				addCartDtos(cartDtos,314);//牙膏
				addCartDtos(cartDtos,321);//MAC口红
				break;
			case 3 :
				addCartDtos(cartDtos,314);//牙膏
				addCartDtos(cartDtos,315);//漱口水
				break;
			case 2 :
				addCartDtos(cartDtos,314);//牙膏
				addCartDtos(cartDtos,322);//儿童护齿书籍
				break;
			case 1 :
				addCartDtos(cartDtos,314);//牙膏
				break;
			default:
				break;
		}
	}

	/**
	 * 添加赠品
	 * @param
	 * @return
	 */
	private void addCartDtos(List<CartDto> cartDtos,Integer id){
		boolean flag = false;
		for (CartDto cartDto : cartDtos) {
			if(id.equals(cartDto.getCartColorId())){
				flag = true;
			}
		}
		if(!flag){
			CartDto cd = getGiftCartDtos(id);
			cartDtos.add(cd);
		}
	}

	/**
	 * 获取赠品信息
	 * @param colorId
	 * @return
	 */
	private CartDto getGiftCartDtos(Integer colorId){
		CartDto cartDto = new CartDto();
		Product product = productInfoService.selectProductByColorId(colorId);
		if((product.getColorSoldNum()+1) > product.getColorAllNum()){
			return null;
		}
		cartDto.setCartId(1);
		cartDto.setCartProductId(product.getProductId());
		cartDto.setCartColorId(colorId);
		cartDto.setCartNum(1);
		cartDto.setProductName(product.getProductName());
		cartDto.setProductType(product.getProductTypeId());
		cartDto.setProductPrice(product.getColorDiscount());
		cartDto.setProductStatus(1);
		cartDto.setProductIntroduceImg(product.getColorImg());
		cartDto.setTotal(0);
		cartDto.setProductDiscount(product.getColorDiscount());
		cartDto.setProductRemark(product.getColorPresent());
		cartDto.setProductColor(product.getColorName());
		cartDto.setColorAllNum(product.getColorAllNum());
		cartDto.setColorSoldNum(product.getColorSoldNum());
		cartDto.setIsSelfLifting(2);
		return cartDto;
	}

//
//	public static void main(String[] args) {
//		String tel = "13265476840";
//		String regExp = "^((13[0-9])|(15[0-9])|(18[0-9])|(17[0-9])|(147))\\d{8}$";
//		Pattern p = Pattern.compile(regExp);
//		Matcher m = p.matcher(tel);
//		if(m.matches()){
//			System.out.println("电话号码错误，请重新添加收货地址信息！");
//		}
//	}

}
