package com.iamberry.wechat.handles.pay;

import java.util.List;

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

import com.iamberry.wechat.tools.WeixinUtil;
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.servlet.ModelAndView;

import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.cart.CartDto;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.cart.CartService;
import com.iamberry.wechat.face.home.HomeService;
import com.iamberry.wechat.face.pay.PayService;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ValidatorUtil;

/**
 * @author 何秀刚<br>
 * Class Description: 发起微信支付Handler,凡是发起微信支付的URL，必须在本类发起，否则支付异常;<br>
 * 	不允许使用/pay/xx/yy ，理应使用/pay/xx?zz=yy 替换<br>
 * Create Date:2016年4月19日<br>
 * Update Date:2016年4月19日<br>
 */
@Controller
@RequestMapping("/pay")
public class RequestWechatPayHandler {

	@Autowired
	private CartService cartService;
	
	@Autowired
	private WechatUtils wechatUtils;
	
	@Autowired
	private HomeService homeService;
	
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private ValidatorUtil validatorUtil;
	
	@Autowired
	private PayService payService;
	

	/**
	 * 购物车针对购物项，结算
	 * @param cartIds 需要结算的购物车ID，参数示例:1-2-3-4、1-
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/settlement", method = RequestMethod.GET)
	public ModelAndView settlement(
			@RequestParam("cartId") String cartIds, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:" + NameUtils.WECHAT_SHOP_INDEX); // 回到购物车页面
		// 用户信息
		Member member = wechatUtils.getUserBySession(request);
		
		if (member == null || member.getUserOpenid() == null) {
			return null;
		}
		// 清空数据
		request.getSession().removeAttribute("cartIds");
		
		if ((cartIds == null || cartIds.isEmpty()))
			return mv;
		/** 使用wechat-JSSDK1.1版本，不需要服务器重新交互数据
		// 是否经过微信收货地址授权
		String code = request.getParameter("code");
		if (code == null || code.isEmpty()) {
			String url = wechatUtils.getOpenIdFunction(WXPublicNo.TOCHECKOUT_ADDR_URL + cartIds, false);
			mv.setViewName("redirect:" + url);
			return mv;
		}
		try {
			String accessToken = weixinUtil.getParamByOauth2(code).getString("access_token");
			request.getSession().setAttribute("wechatAccessToken", accessToken);
			request.getSession().setAttribute("wechatAddrCode", code);
			request.getSession().setAttribute("cartIds", cartIds);
			mv.setViewName(""); // 地址
		} catch (Exception e) {
			String url = wechatUtils.getOpenIdFunction(WXPublicNo.TOCHECKOUT_ADDR_URL + cartIds, false);
			mv.setViewName("redirect:" + url);
		}*/
		// split 购物车ID
		String [] cartList = cartIds.split("-");
		if (cartList == null || cartList.length <= 0) {
			return mv;
		}
		// 转化 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) {
				return mv;
			}
		}
		if (cartIntList.length <= 0) {
			return mv;
		}
		// 根据购物车ID，查询数据库中对应的产品信息（ID、产品状态）
		List<CartDto> cartDtos = cartService.selectCartItemByListId(cartIntList);
		if (cartDtos == null || cartDtos.size() <= 0) {
			return mv;
		}
		// 判断当前提交的购物车ID，有多少产品在售
		int sum = 0;
		for (CartDto cartDto : cartDtos) {
			if (cartDto.getProductStatus() != null && cartDto.getProductStatus().intValue() == 1)
				sum++;
		}
		if (sum <= 0) {
			return mv;
		}
		request.getSession().setAttribute("cartIds", cartIds);
		mv.setViewName("forward:" + NameUtils.WECHAT_SHOP_ORDER_PAY); // 支付页面
		return mv;
	
	}
	
	/**
	 * 去订单详情页面
	 * @param request
	 * @param response
	 */
	@RequestMapping("/goOrderInfo")
	public void goOrderInfo(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.getRequestDispatcher(NameUtils.WECHAT_SHOP_ORDER_GOORDERINFO).forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	
	/**
	 * 进入订单列表页面
	 * @param request
	 * @param response
	 */
	@RequestMapping("/goOrderList")
	public void goOrderList(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.getRequestDispatcher(NameUtils.WECHAT_SHOP_ORDER_GOORDERLIST).forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 跳转到订货支付页面
	 * @param request
	 * @param response
	 */
	@RequestMapping("/drpPlayOrderPage")
	public void drpPlayOrderPage(HttpServletRequest request, HttpServletResponse response) {
		/*boolean flag=true;
		if(!checkDrpUserService.checkDrpAuthorizontion(request)){
			try {
				request.getRequestDispatcher(NameUtils.WECHAT_SHOP_INDEX).forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			} 
			flag=false;
		}
		
		if(flag){
			if(!checkDrpUserService.checkDrpBookAuthorizontion(request)){
				try {
					request.getRequestDispatcher(NameUtils.WECHAT_SHOP_FENXIAO_INDEX).forward(request, response);
				} catch (Exception e) {
					e.printStackTrace();
				} 
				flag=false;
			}
		}
		try {
			if(flag){
				request.getRequestDispatcher(NameUtils.WECHAT_SHOP_FENXIAO_PAYORDERPAGE).forward(request, response);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} */
	}
	/**
	 * 去分销订货页面 ---可以支付页面
	 * @param request
	 * @param response
	 */
	@RequestMapping("/drpOrdersList")
	public void ordersList(HttpServletRequest request, HttpServletResponse response) {
		/*boolean flag=true;
		if(!checkDrpUserService.checkDrpAuthorizontion(request)){
			try {
				request.getRequestDispatcher(NameUtils.WECHAT_SHOP_INDEX).forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			} 
			flag=false;
		}
		try {
			if(flag){
			request.getRequestDispatcher(NameUtils.WECHAT_SHOP_FENXIAO_ORDERLIST).forward(request, response);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} */
	}
}
