package com.iamberry.wechat.handles.order;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.activity.ActivityDate;
import com.iamberry.wechat.core.entity.cart.*;
import com.iamberry.wechat.core.entity.eo.Promotions;
import com.iamberry.wechat.core.entity.eo.SettlementGift;
import com.iamberry.wechat.core.entity.product.Product;
import com.iamberry.wechat.face.eo.SettlementGiftService;
import com.iamberry.wechat.face.order.AdminOrderService;
import com.iamberry.wechat.service.ActivityUtil;
import com.iamberry.wechat.tools.*;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.BeanUtils;
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.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.Member;
import com.iamberry.wechat.core.entity.mq.MQMessage;
import com.iamberry.wechat.core.entity.order.Order;
import com.iamberry.wechat.core.entity.order.OrderItem;
import com.iamberry.wechat.core.entity.pay.PayResult;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.cart.CartService;
import com.iamberry.wechat.face.cart.ProductInfoService;
import com.iamberry.wechat.face.coupon.CouponItemService;
import com.iamberry.wechat.face.coupon.CouponTypeService;
import com.iamberry.wechat.face.home.HomeService;
import com.iamberry.wechat.face.member.CashLogService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.pay.PayService;
import com.iamberry.wechat.face.reback.RebackServices;
import com.iamberry.wechat.handles.mq.MQServiceProxy;

/**
 * @author 何秀刚
 * Class Description: 订单hander
 * Create Date:2016年4月20日
 * Update Date:2016年4月20日
 */
@Controller
@RequestMapping("/wechat/order")
public class OrderHandler {
	
	@Autowired
	private CartService cartService;
	
	@Autowired
	private WechatUtils wechatUtils;
	
	@Autowired
	private HomeService homeService;
	
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private ValidatorUtil validatorUtil;
	
	@Autowired
	private OrderNOUtil orderNOUtil;
	
	@Autowired
	private PayService payService;
	
	@Autowired
	private MemberService memberService;
	@Autowired
	CouponItemService couponItemService;
	@Autowired
	CouponTypeService couponTypeService;
	@Autowired
	CashLogService cashLogService;
	@Autowired
	private RebackServices rebackServices;
	@Autowired
	private MQServiceProxy mQservice;
	@Autowired
	private ProductInfoService productInfoService;
	@Autowired
	private SettlementGiftService settlementGiftService;
	@Autowired
	private ActivityUtil activityUtil;
	@Autowired
	private AdminOrderService adminOrderService;
	@Autowired
	private RatFWLogger logger;

	/**
	 * 支付前，调用方法
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/payBefore", method = RequestMethod.POST)
	public ResultMsg payBefore(HttpServletRequest request) throws Exception {
		
		ResultMsg msg = new ResultMsg();
		msg.setResultCode(ResultInfo.ERRORCODE);
		
		OrderPayDto dto = new OrderPayDto();
		// 用户信息
		Member member = wechatUtils.getUserBySession(request);
		if (member == null || member.getUserOpenid() == null) {
			msg.setMessage(ResultInfo.loginOutError);
			return msg;
		}
		member=memberService.getMemberByUserOpenId(member.getUserOpenid());
		String cartIds = request.getParameter("cartIds");
		if (cartIds == null) {
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}
		cartIds.trim();
		// split 购物车ID
		String [] cartList = cartIds.split("-");
		if (cartList == null || cartList.length <= 0) {
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}
		// 转化 String 类型的购物车ID集合 --> Integer 类型的购物车集合
		Integer[] cartIntList = new Integer[cartList.length];
		for (int i = 0; i < cartList.length; i++) {
			String string = cartList[i];
			try {
				cartIntList[i] = Integer.parseInt(string);
			} catch (Exception e) {
				msg.setMessage(e.getMessage());
				return msg;
			}
		}
		if (cartIntList.length <= 0) {
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}
		// 根据购物车ID，查询数据库中对应的产品信息（ID、产品状态）
		List<CartDto> cartDtos = cartService.listCartByIds(cartIntList);
		if (cartDtos == null || cartDtos.size() <= 0) {
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}
		// 判断当前提交的购物车ID，有多少产品在售
		int total = 0; // 支付金额
		int sum = 0; // 产品数量
		int productIdW6 = 0; // W6水机数量
		// 水机数量
		int waterManchine = 0;

		//查询活动
		activityUtil.preferential(cartDtos);

		List<CartDto> tempCarts = new ArrayList<CartDto>();
		for (CartDto cartDto : cartDtos) {
			if (cartDto.getProductStatus() != null && cartDto.getProductStatus().intValue() == 1) {
				total += cartDto.getCartNum() * cartDto.getProductDiscount();
				sum++;
				tempCarts.add(cartDto);
			}
			if(cartDto.getCartProductId() == 39 || cartDto.getCartProductId() == 33){
				productIdW6 ++;
			}
			if (cartDto.getCartProductId() == 33 ||
					cartDto.getCartProductId() == 39 ||
					cartDto.getCartProductId() == 47 ||
					cartDto.getCartProductId() == 48 ||
					cartDto.getCartProductId() == 29 ||
					cartDto.getCartProductId() == 30 ||
					cartDto.getCartProductId() == 31 ||
					cartDto.getCartProductId() == 32) {
				waterManchine++;
			}
		}
		if (sum <= 0) {
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}

		//未使用的优惠券
		CouponItemDto cDto = new CouponItemDto();
		cDto.setUseropenid(member.getUserOpenid());
		cDto.setCouponUseStatus(1);
		cDto.setCouponIsGive(1);
		cDto.setBeginDate(new Date());
		cDto.setPage(new PageBean());
		cDto.getPage().setPageSize(12);
		//cDto.getPage().setPageNumber(pageNO);
		List<CouponItemDto> list = new ArrayList<CouponItemDto>();
		List<CouponItemDto> couponItemDtolist = couponItemService.getCouponItemDtoList(cDto);
		for (CouponItemDto cid : couponItemDtolist) {
			if(cid.getCouponId() == 20000||cid.getCouponId() == 20001){
				if(productIdW6 > 0){
					list.add(cid);
				}
			} else if (cid.getCouponId() == 30000 || cid.getCouponId() == 30001) {
				if (waterManchine >= 1) {
					list.add(cid);
				}
			} else if (cid.getCouponId() == 30002) {
				if (total >= 88800) {
					list.add(cid);
				}
			}else{
				list.add(cid);
			}
		}
		dto.setCouponItems(list);
		
		request.getSession().setAttribute("cartIds", cartIds);
		dto.setCartId(cartIds);// 购物车ID
		dto.setPayTotal(total); // 支付金额,单位为分
		dto.setCartItems(tempCarts); // 订单项
		dto.setSuccess(true); // 请求成功
		dto.setUserIntegral(member.getUserSurplusIntegral());
		dto.setMeonyProportion("0.1");
		dto.setBalance(member.getUserIncome());
		dto.setUserIsVip(member.getUserIsVip());

		Order order=cartService.getOrderRecentAddress(member.getUserOpenid());
		
		if(order!=null){
			HashMap<String,String> map=new HashMap();
			//map.put("orderId", order.getSalesOrderid());
			map.put("salesAddressName", order.getSalesAddressName());
			map.put("salesAddressInfo", order.getSalesAddressInfo());
			map.put("salesAddressTel", order.getSalesAddressTel());
			map.put("salesAddressPostnum", order.getSalesAddressPostnum());
			dto.setAddressInfo(map);
		}
		
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setMessage(ResultInfo.SUCCESSINFO);
		msg.setData(dto);
		msg.setStatus(true);
		
		return msg;
	}
	
	/**
	 * 发起支付请求
	 * @param dto 支付参数, 根据情况调整方法是否进行synchronized<br>在生成订单时不会存在安全问题
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value = "/pay", method = RequestMethod.POST)
	public ResultMsg requestPay(
			TempOrderDto temp,
			HttpServletRequest request
			) throws Exception {
		
		ResultMsg msg = new ResultMsg();
		msg.setResultCode(ResultInfo.ERRORCODE);
		//System.out.println(temp.toString());
		//当前支付时间
		Date nowDate=new Date();

		SendPayDto dto = new SendPayDto();
		dto.setSuccess(false);
		Member member = wechatUtils.getUserBySession(request); // 当前用户
		/** 数据格式校验 */
		if (member == null || member.getUserOpenid() == null) {// 校验当前用户信息是否丢失
			msg.setMessage(ResultInfo.loginOutError);
			return msg;
		}


		if("收货人".equals(temp.getOrderAddressName())){
			msg.setMessage("收货人信息有误，请重新选择地址信息！");
			return msg;
		}
		if("收货人电话".equals(temp.getOrderAddressMoblie())){
			msg.setMessage("收货人电话信息有误，请重新选择地址信息！");
			return msg;
		}
		
		member=memberService.getMemberByUserOpenId(member.getUserOpenid());
		if (!validatorUtil.validatorObject(temp)) { // 校验订单信息是否输入有误
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
		if (temp.getOrderUserRemark() != null && !temp.getOrderUserRemark().isEmpty()) {
//			Pattern pattern = Pattern.compile("^[\u4e00-\u9fa5_a-zA-Z0-9]+$");
//			if (!pattern.matcher(temp.getOrderUserRemark()).find()) {
//				msg.setMessage(ResultInfo.paramFormatError);
//				return msg;
//			}
			if (!(temp.getOrderUserRemark().length() >= 1 && temp.getOrderUserRemark().length() <= 100)) {
				msg.setMessage(ResultInfo.paramFormatError);
				return msg;
			}
		}
		Integer [] cartId = null;
		try {
			cartId = checkCartIdListString(temp.getCartIdStr());
		} catch (Exception e) { // 一旦发生异常，表示错误
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
		/** 数据逻辑校验 */
		/*Integer inputIntegral = 0; 
		Integer userIntegral = homeService.selectUserIntegralByOpenid(member.getUserOpenid());
		if (inputIntegral > userIntegral) {// 输入积分不能大于用户可用积分
			msg.setMessage(ResultInfo.integralOutError);
			return msg;
		}*/
		List<CartDto> cartDtos = cartService.listCartByIds(cartId);
		if (cartDtos == null || cartDtos.size() <= 0) {// 根据购物车ID，查询数据库中对应的产品信息（ID、产品状态）
			msg.setMessage(ResultInfo.cartEmptyError);
			return msg;
		}
		int ruleNum = systemService.selectOneShopRuleById(13).getRuleNum().intValue(); // 积分和金额比例 : 1积分=?分钱
		int total = 0; // 需要支付的总额, 单位为分
		/** 提前准备订单项数据 */
		/** 准备数据 */
		Order order = new Order();
		order.setSalesOrderid(orderNOUtil.createOrderCode(member.getUserId())); // 订单ID
		List<OrderItem> list = new ArrayList<OrderItem>();
		List<Integer> cartIds = new ArrayList<Integer>();

		List<CartDto> cds = new ArrayList<>();
		for (int i=0;i<cartDtos.size();i++) {
			CartDto c = cartService.selectCartProductColor(cartDtos.get(i));
			cds.add(c);
		}
		cartDtos = cds;

		//添加赠品，秒杀
		activityUtil.preferential(cartDtos);

		Double kqjhj_amount_50000 = 0.00;

		OrderItem paizeItem = new OrderItem();
		boolean hasPrizeProduct = false;//含有买一赠一的颜色
		boolean satisfyPrizeProduct = false;//满足买一赠一的方式
		for (CartDto cartDto : cartDtos) {
			if (cartDto.getProductStatus() != null && cartDto.getProductStatus().intValue() == 1) {
				cartIds.add(cartDto.getCartId());
				Integer productDiscount = cartDto.getProductDiscount();
				if(cartDto.getColorType() == 1 && member.getUserIsVip() == 2 &&
						!"40001".equals(temp.getCouponTypeId()) && !"50000".equals(temp.getCouponTypeId()) && !"50001".equals(temp.getCouponTypeId())){
					Double doubleProductDiscount = productDiscount.doubleValue();
					doubleProductDiscount = doubleProductDiscount * 0.95;
					productDiscount = doubleProductDiscount.intValue();
				}else if((cartDto.getColorType() == 2 || cartDto.getColorType() == 3) && member.getUserIsVip() == 2 &&
						!"40001".equals(temp.getCouponTypeId()) && !"50000".equals(temp.getCouponTypeId()) && !"50001".equals(temp.getCouponTypeId())){
					Double doubleProductDiscount = productDiscount.doubleValue();
					doubleProductDiscount = doubleProductDiscount * 0.88;
					productDiscount = doubleProductDiscount.intValue();
				}
				Integer subTotal = cartDto.getCartNum() * productDiscount; // 小计
				total += subTotal;
				OrderItem item = new OrderItem();
				item.setItemNum(cartDto.getCartNum());
				item.setItemProductDiscount(cartDto.getProductDiscount());
				item.setItemProductId(cartDto.getCartProductId());
				item.setItemProductName(cartDto.getProductName());
				item.setItemProductPic(cartDto.getProductIntroduceImg());
				item.setItemSalesOrderid(order.getSalesOrderid());
				item.setItemTotal(subTotal);
				item.setItemProductPrice(cartDto.getProductPrice());
				item.setItemColorId(cartDto.getCartColorId());
				item.setItemProductColor(cartDto.getProductColor());
				item.setItemProductChildType(cartDto.getProductChildType());
				item.setItemIsSource(cartDto.getCartIsSource());
				item.setItemProductType(cartDto.getProductType());
				item.setItemProductChildType(cartDto.getProductChildType());
				item.setItemGiftList(cartDto.getItemGiftList());
				list.add(item);
				if(temp.getUseCouponPrizeColorId() != 0 && temp.getUseCouponPrizeColorId()==cartDto.getCartColorId()){
					BeanUtils.copyProperties(item,paizeItem);
					paizeItem.setItemProductDiscount(0);
					paizeItem.setItemProductName("【赠送】"+paizeItem.getItemProductName());
					hasPrizeProduct = true;
					if(cartDto.getColorType() == 3){	//该产品是抵扣产品
						satisfyPrizeProduct = true;
					}
				}
				if(item.getItemColorId() == 58){
					kqjhj_amount_50000 += cartDto.getCartNum() * productDiscount;
				}
			}
		}
		//含有该优惠抵扣产品并且该产品是可抵扣产品
		if(hasPrizeProduct && satisfyPrizeProduct){
			list.add(paizeItem);
		}

		// 准备订单对象
		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 && couponType.getCouponId() != 40001){
				msg.setMessage(ResultInfo.COUPON_CONSUME_NO_ENOUGH); //消费额度不足
				return msg;
			}

			if(couponType.getCouponId() == 40001 && !satisfyPrizeProduct && !hasPrizeProduct){
				msg.setMessage(ResultInfo.COUPON_CONSUME_NO_PRIZE); //消费额度不足
				return msg;
			}

			//优惠券的类型，是直接减免额度 还是折扣价 
			if(couponType.getCouponType()==1){
				total=total-couponType.getCouponReduce();
			}else if(couponType.getCouponType()==2){
				Double totalDouble = Double.valueOf(total);
				switch (couponItemDto.getCouponId()){
					case 50001:
					case 50000:
						Double reduce = Double.valueOf(couponType.getCouponReduce())/100;
						totalDouble = totalDouble-kqjhj_amount_50000*(1-reduce);
						total=totalDouble.intValue();
						break;
					default:
						total=total*couponType.getCouponReduce()/100;
						break;
				}
			}else if(couponType.getCouponType()==3){
				//赠送一个滤芯，上面直接添加到订单项
			}
		}

		Integer integralNum = temp.getOrderIntegralNum();
		//使用积分
		if(integralNum != null && integralNum != 0){
			if(member.getUserIsVip() == 2 && member.getUserSurplusIntegral() >= integralNum){// vip用户 && 用户积分大于等于使用的积分
				//积分的使用需要除以10，但是支付金额的单位为分，所以需要乘以100  == 》 integralNum/10*100 ==》 integralNum*10
				total -= integralNum*10;
			}else{
				msg.setMessage(ResultInfo.ORDER_NO_INTEGRAL); //积分不足
				return msg;
			}
		}

		if(total==0 || total<0){
			total=0;
			mustPay=0;
		}else{
			mustPay=total;
		}
		order.setSalesYetAmount(total);
		order.setSalesRateAmount(0);
		order.setSalesIntegralNum(temp.getOrderIntegralNum()); // 订单使用积分
		order.setSalesCreateDate(new Date()); // 创建时间
		order.setBalancePayAmount(temp.getBalancePayAmount()); //账户余额支付金额
		order.setCouponId(couponId);   //优惠券id

		order.setSalesStatus(1); // 待支付订单
		order.setSalesTransactionDate(nowDate);  //事务时间
		order.setSalesTransactionId("8990"+nowDate.getTime());
		order.setSalesAddressInfo(temp.getOrderAddressInfo()); // 收货地址
		order.setSalesAddressName(temp.getOrderAddressName()); // 收货人
		order.setSalesAddressTel(temp.getOrderAddressMoblie()); // 收入联系方式
		order.setSalesAddressPostnum(temp.getOrderAddressPostNum()); // 物流编号
		order.setSalesUserRemark(temp.getOrderUserRemark()); // 用户备注
		// 保存
		boolean flag = false;
		try {
			flag = cartService.addOrderAndSaveOrderItem(order, list, cartIds);
			//修改优惠券状态为临时状态
			if(hasCoupon){
				couponItem.setCouponUseStatus(7);
				couponItemService.updateCouponItemById(couponItem);
			}
		} catch (Exception e) {
			flag = false;
			System.out.println("====插入订单列表信息失败====");
			e.printStackTrace();
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
		
		boolean updateFlase=false;
		if (flag && mustPay>0) {
		//if (flag) {
			// 发起支付
			//PayResult result = payService.requestPay(order.getSalesOpenid(), order.getSalesOrderid(), order.getSalesYetAmount(), list.get(0).getItemProductName() + "...", NameUtils.WECHAT_ORDER_BACK);
			PayResult result = payService.requestPay(order.getSalesOpenid(), order.getSalesOrderid(), mustPay, list.get(0).getItemProductName() + "...", NameUtils.WECHAT_ORDER_BACK);
			if (result.isPaySuccess()) {
				dto.setInfo(result.getPayData());
				dto.setSuccess(true);
				dto.setOrderId(order.getSalesOrderid());
				updateFlase=false;
			} else {
				dto.setInfo(result.getPayData());
				dto.setOrderId(order.getSalesOrderid());
				msg.setResultCode(ResultInfo.ERRORCODE);
				msg.setMessage(ResultInfo.ERRORINFO);
				msg.setData(dto);
				msg.setStatus(false);
				return msg;
			}
		} else if(flag && mustPay==0){
			dto.setInfo("isOK");
			dto.setSuccess(true);
			dto.setOrderId(order.getSalesOrderid());
			updateFlase=true;
		}else{
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
	
		if(updateFlase){
			//设置订单状态，还有优惠券id
			order.setSalesStatus(2);
			//cartService.updateOrderByOrderId(order);
			cartService.updateOrderStatus(order);
			//修改优惠券状态
			if(hasCoupon){
				couponItem.setCouponUseStatus(2);
				int i=couponItemService.updateCouponItemById(couponItem);
			}
				
			rebackServices.loadSingleOrderReward(order);
			productInfoService.updateProductNumList(order.getSalesOrderid());
			try {
				MQMessage message = new MQMessage();
				message.setServiceToMessage(order.getSalesOrderid());
				message.setServiceOtherMessage("efast.trade.new.add");
				message.setServiceIsSend(2);			// 没有推送的信息
				message.setServiceStatus(1); 			// 推送成功
				message.setServiceType(1); 				// 添加订单信息
				message.setServiceHandlerObjectName("efastOrderServiceImpl");
				message.setServiceHandlerMethodName("addOrderInfoToEfast");
				mQservice.insertMQMessage(message);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setMessage(ResultInfo.SUCCESSINFO);
		dto.setOrderId(order.getSalesOrderid());
		msg.setData(dto);
		msg.setStatus(true);
		return msg;
	}
	
	/**
	 * 结算 ：微信共享地址V1.0, V1.1以后版本不需要调用此方法
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/wechatAddrShare", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg wechatAddrShare(HttpServletRequest request) {
		
		ResultMsg msg = new ResultMsg();
		msg.setResultCode(ResultInfo.ERRORCODE);
		
		Map<String, String> map = new HashMap<String, String>();
		// 获取session中的 数据
		String wechatAccessToken = (String) request.getSession().getAttribute("wechatAccessToken");
		String code = (String) request.getSession().getAttribute("wechatAddrCode");
		String cartIds = (String) request.getSession().getAttribute("cartIds");
		if (wechatAccessToken == null || code == null || cartIds == null) {
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
		// 清空数据
		request.getSession().removeAttribute("wechatAccessToken");
		request.getSession().removeAttribute("wechatAddrCode");
		// 组装数据
		StringBuffer sb = new StringBuffer(NameUtils.TOCHECKOUT_ADDR_URL + cartIds);
		sb.append("?code=").append(code).append("&state=iamberry");// 微信共享地址兼容，Android系统url需要加上#，ios则不用
		String currentUrl = sb.toString();
		String nonceStr = Sha1Util.getNonceStr();
		String timestamp = Sha1Util.getTimeStamp();
		TreeMap<String, String> signatureParams = new TreeMap<String, String>();
		signatureParams.put("noncestr", nonceStr);
		signatureParams.put("appid", NameUtils.appId);
		signatureParams.put("timestamp", timestamp);
		signatureParams.put("url", currentUrl);
		signatureParams.put("accesstoken", wechatAccessToken);
		String s1 = TenpayUtil.getKeyValue(signatureParams);
		String addrSign = Sha1Util.getSha2(s1);
		// 组装数据
		map.put("appId", NameUtils.appId);
		map.put("scope", "jsapi_address");
		map.put("signType", "SHA1");
		map.put("addrSign", addrSign);
		map.put("timestamp", timestamp);
		map.put("nonceStr", nonceStr);
		map.put("status", "true");
		
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setMessage(ResultInfo.SUCCESSINFO);
		msg.setData(map);
		msg.setStatus(true);
		
		return msg;
	}
	
	/**
	 * 校验订单状态，判断是否支付成功
	 * @param orderId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/checkOrderPaySuccess")
	public ResultMsg checkOrderPaySuccess(
			@RequestParam(value = "orderId") String orderId) {
		ResultMsg msg = new ResultMsg();
		msg.setResultCode(ResultInfo.ERRORCODE);
//System.out.println("============orderId===="+orderId);
		Integer orderStatus = cartService.selectOrderStatusByOrderId(orderId);
		if (orderStatus != null && orderStatus.intValue() == 2) {
			msg.setResultCode(ResultInfo.SUCCESSCODE);
			msg.setMessage(ResultInfo.SUCCESSINFO);
			msg.setStatus(true);
			return msg;
		}
		msg.setResultCode(ResultInfo.ERRORCODE);
		msg.setMessage(ResultInfo.ERRORINFO);
		msg.setStatus(false);
		
		return msg;
	}

	@RequestMapping("/paySuccess")
	public void paySuccess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher(NameUtils.WECHAT_SHOP_ORDER_PAY_SUCCESS).forward(request, response);
	}
	
	@RequestMapping(value = "/getOrderInfo", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg getOrderInfoByOrderId(
			HttpServletRequest request,
			@RequestParam(value = "orderId") String orderId) throws Exception {
		ResultMsg msg = new ResultMsg();
		msg.setResultCode(ResultInfo.ERRORCODE);
		Member member = wechatUtils.getUserBySession(request); // 当前用户
		/** 数据格式校验 */
		if (member == null || member.getUserOpenid() == null) {// 校验当前用户信息是否丢失
			msg.setMessage(ResultInfo.loginOutError);
			return msg;
		}
		Order order = new Order();
		order.setSalesOrderid(orderId);
		order.setSalesOpenid(member.getUserOpenid());
		order = cartService.selectOrderInfoById(order);
		
		if (order == null || order.getSalesStatus() != 2) {
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
		
		msg.setData(order);
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setMessage(ResultInfo.SUCCESSINFO);
		msg.setStatus(true);
		return msg;
	}
	
	/**
	 * 校验一个购物车字符串
	 * @param cartIds 购物车ID字符串
	 * @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;
	}




	/**
	 * 支付前，调用方法
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/syncOrder", method = RequestMethod.POST)
	public ResultMsg syncOrder(HttpServletRequest request,String orderId) throws Exception {
		// orderInfo
		Order order = adminOrderService.getShopOrderByOrderId(orderId);
		if (order == null || order.getSalesOrderid() == null) {
			return new ResultMsg();
		}

		List<OrderItem> items = adminOrderService.getShopOrderItemByOrderId(order.getSalesOrderid());

		// request url
		String url = NameUtils.getConfig("rst_efast_base_url");

		// set Requeset Data
		Map<String, String> requestData = new HashMap<String, String>();

		int money = order.getSalesYetAmount();

		if (order.getCouponId() != null && !"".equals(order.getCouponId())) {
			CouponItem couponItem = new CouponItem();
			couponItem.setCouponItemId(order.getCouponId());
			couponItem.setCouponItemUseropenid(order.getSalesOpenid());
			CouponType couponType = cartService.getCouponReduceByItemId(couponItem);
			if (null != couponType) {
				switch (couponType.getCouponType()) {
					case 1:
						money += couponType.getCouponReduce();
						break;
					case 2:
						money += order.getSalesAmount() * couponType.getCouponReduce()/100;
						break;
				}
			}
		}

		requestData.put("app_act", "rst.trade.new.add");

		/**
		 * 订单基本信息
		 */
		String [] addressDesc = order.getSalesAddressInfo().split("-");

		String address = addressDesc[3];
		if (addressDesc[3]!=null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(addressDesc[3]);
			if (m.find()) {
				address = m.replaceAll("");
			}
		}

		String provinceName = addressDesc[0];
		if (addressDesc[0].indexOf("北京") != -1) {
			provinceName = "北京";
		} else if (addressDesc[0].indexOf("上海") != -1) {
			provinceName = "上海";
		} else if (addressDesc[0].indexOf("天津") != -1) {
			provinceName = "天津";
		} else if (addressDesc[0].indexOf("重庆") != -1) {
			provinceName = "重庆";
		}
		Map<String, Object> orderData = new HashMap<String, Object>();
		orderData.put("add_time", DateTimeUtil.format(order.getSalesCreateDate()));		// 时间
		orderData.put("address", address);										// 收货地址
		orderData.put("city_name", addressDesc[1]); 									// 城市
		orderData.put("consignee", order.getSalesAddressName());						// 收货人
		orderData.put("district_name", addressDesc[2]);									// 区域
		orderData.put("postalcode", order.getSalesAddressPostnum());     // 邮政编码
		orderData.put("email", "");														// email
		orderData.put("goods_amount", order.getSalesAmount());					// 产品总价
		orderData.put("goods_count", items.size());										// 产品数量
		orderData.put("mobile", order.getSalesAddressTel());							// 手机号码
		orderData.put("money_paid", money);					// 已付款
		orderData.put("oid", order.getSalesOrderid());									// 订单号
		orderData.put("order_amount", order.getSalesAmount());					// 订单金额

		/**
		 * 产品信息
		 */
		List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
		for (OrderItem item : items) {
			Map<String, Object> orders1 = new HashMap<String, Object>();
			orders1.put("goods_name", item.getItemProductName());							// 产品名称
			orders1.put("goods_number", item.getItemNum());									// 产品数量
			orders1.put("goods_price", item.getItemProductPrice());					// 产品原价
			orders1.put("outer_sku", item.getProduectRemark());										// 产品SKU
			orders1.put("payment_ft", item.getItemProductDiscount());												// 产品分摊价
			maps.add(orders1);
		}

		orderData.put("orders", maps);													// 订单产品
		orderData.put("pay_name", "weixinpay");											// 支付方式
		if(order.getSalesTransactionDate() != null){
			orderData.put("pay_time", DateTimeUtil.format(order.getSalesTransactionDate()));// 支付时间
		}else{
			orderData.put("pay_time", "");
		}
		orderData.put("postscript", order.getSalesUserRemark());						// 买家留言
		orderData.put("province_name", provinceName);									// 省份
		orderData.put("sd_id", "001");													// 对应 efast 店铺 id
		orderData.put("shipping_fee", 0);												// 快递费
		orderData.put("shipping_name", "yto");											// 快递公司代码
		orderData.put("tel", order.getSalesAddressTel());											// 我司电话
		orderData.put("to_buyer", "");													// 商家备注
		orderData.put("total_amount", order.getSalesAmount());					// 商家备注
		orderData.put("user_name", order.getSalesOpenid());							// 买家账户   百胜根据user_name来判断是否有重复，传openId是为了防止重复
		orderData.put("zipcode", order.getSalesAddressPostnum());						// 邮编


		com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();
		String orderDataStr = null;;
		try {
			orderDataStr = mapper.writeValueAsString(orderData);
		} catch (JsonProcessingException e2) {
			e2.printStackTrace();
		}

		requestData.put("info", orderDataStr);

		logger.info("推送订单:" + requestData);

		try {
			String result = HttpClient431Util.doPost(requestData, url);
			result = StringEscapeUtils.unescapeJava(result); // unicode 编码
			logger.info("add-推送订单号为:" + order.getSalesOrderid() + "的订单，RST返回信息:" + result);
			// parse JSON String to Object
			JSONObject jsonObject = JSONObject.fromObject(result);
			//JSONObject respData = JSONObject.fromObject(jsonObject.get("resp_data"));
			String oderSn = jsonObject.getString("oder_sn");
			if (oderSn != null) {
				String msg = jsonObject.getString("msg");
				if ("success".equals(msg)) {
					return new ResultMsg();
				}
			}
			logger.error(this, "add-推送订单失败，订单号为:" + order.getSalesOrderid() + "的订单，RST返回信息:" + result);
			throw new Exception(jsonObject.getString("msg"));
		} catch (Exception e) {
			throw e;
		}
	}
}
