package com.iamberry.wechat.handles.giftCard;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Date;
import java.util.Map;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.app.verify.ValidateUtil;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.giftCard.AgentMachine;
import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.giftCard.AgentInfo;
import com.iamberry.wechat.core.entity.giftCard.AgentPayLogs;
import com.iamberry.wechat.core.entity.giftCard.CardCashInfo;
import com.iamberry.wechat.core.entity.giftCard.GiftCardDto;
import com.iamberry.wechat.core.entity.giftCard.GiftCardInfo;
import com.iamberry.wechat.core.entity.giftCard.UserMachineInfo;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.product.ProductColor;
import com.iamberry.wechat.face.giftCard.AgentMachineService;
import com.iamberry.wechat.face.giftCard.AgentService;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.cart.ProductInfoService;
import com.iamberry.wechat.face.giftCard.GiftCardService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.mq.EfastOrderService;
import com.iamberry.wechat.face.order.CodeService;
import com.iamberry.wechat.face.porduct.ProductColorService;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.wechat.tools.ResponseJson;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.utils.SendMessageUtil;

/**
 * 提货卡handler
 * 
 * @company 深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author 献
 * @tel 18271840547
 * @date 2017年2月15日
 */
@RequestMapping(value = "/wechat/giftCard/card")
@Controller
public class CardHandler {

	@Autowired
	private CodeService codeService;
	@Autowired
	private GiftCardService cardService;
	@Autowired
	private AgentMachineService agentMachineService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private AgentService agentService;
	@Autowired
	private RatFWLogger logger;
	@Autowired
	private ProductColorService productColorService;
	@Autowired
	private ProductInfoService productInfoService;
	@Autowired
	private EfastOrderService efastOrderService;
	@Autowired
	private SendMessageUtil sendMessageUtil;

	/**
	 * 兑换入口 - 页面
	 * 
	 * @return
	 * @author 献
	 * @Time 2017年2月15日
	 */
	@RequestMapping(value = "/_exchangeUI")
	public ModelAndView exchangeUI() {
		ModelAndView mv = new ModelAndView();
		return mv;
	}

	/**
	 * 转发地址跳转
	 * 
	 * @param response
	 * @param requestion
	 * @param url
	 */
	public void dispatcherLink(HttpServletResponse response,
			HttpServletRequest requestion, String url) {
		try {
			requestion.getRequestDispatcher(url).forward(requestion, response);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 代理中心入口 - 页面
	 * 
	 * @return
	 * @author LJK
	 * @Time 2017年2月22日10:15:48
	 */
	@RequestMapping(value = "/agencyUI")
	public void agencyUI(HttpServletRequest request,
			HttpServletResponse response) {
		// 获取当前用户
		Member member = WechatUtils.getUserBySession(request);
		String url = null;
		List<AgentPayLogs> agentPayLogsList = agentService
				.selectPayLogHasByOpenid(member.getUserOpenid());
		if (agentPayLogsList == null || agentPayLogsList.size() == 0) {
			url = "/view/gift_card_go_agent.html";
			dispatcherLink(response, request, url);
			return;
		}
		if (agentPayLogsList.size() > 0) {
			url = "/WEB-INF/views/wechat/gift_card_agent_center.html";
			dispatcherLink(response, request, url);
			return;
		}
		/*
		 * for(AgentPayLogs agentPayLogs : agentPayLogsList){
		 * if(agentPayLogs.getPayStatus() == null ||
		 * agentPayLogs.getPayStatus().equals("")|| agentPayLogs.getPayStatus()
		 * == 1){ url="/view/gift_card_to_agent.html";//这里应该跳转到续费页面
		 * dispatcherLink(response,request,url); return; } } else
		 * if(agentPayLogs.getPayStatus() == 2){}
		 * url="/WEB-INF/views/wechat/gift_card_agent_center.html";
		 * dispatcherLink(response,request,url); return; }
		 */
	}

	/**
	 * 兑换列表入口 - 页面
	 * 
	 * @return
	 * @author LJK
	 * @Time 2017年2月22日10:15:48
	 */
	@RequestMapping(value = "/exchangeUI")
	public void exchangeUI(HttpServletRequest request,
			HttpServletResponse response) {
		// 获取当前用户
		Member member = WechatUtils.getUserBySession(request);
		String url = null;
		List<UserMachineInfo> UserMachineInfoList = cardService.list(member
				.getUserOpenid());
		if (UserMachineInfoList.size() > 0) {
			url = "/WEB-INF/views/wechat/gift_card_exchange_list.html";
			dispatcherLink(response, request, url);
			return;
		} else {
			url = "/view/gift_card_user_exchange.html";
			dispatcherLink(response, request, url);
			return;
		}

	}

	/**
	 * 兑换申请
	 * 
	 * @param machineInfo
	 * @return
	 * @author 献
	 * @Time 2017年2月15日
	 */
	@ResponseBody
	@RequestMapping(value = "/exchange")
	public ResponseJson exchange(UserMachineInfo machineInfo,
			@RequestParam("cardPwd") String cardPwd, HttpServletRequest request) {
		ResponseJson json = new ResponseJson();
		json.setResultCode(200);
		// 获取当前用户
		Member member = WechatUtils.getUserBySession(request);
		// 根据openid查询付费代理商信息
		AgentInfo agent = agentService.selectAgentByOpenId(member.getUserOpenid());
		if (agent == null) {
			json.setReturnCode(500);
			json.addResponseKeyValue("没有查到该付费代理商信息!");
			return json;
		}

		// 收货信息校验
		if (!ValidateUtil.checkMobile(machineInfo.getUserMachineAddressTel())
				|| !ValidateUtil.checkLength(
						machineInfo.getUserMachineAddressName(), 10)
				|| !ValidateUtil.checkLength(
						machineInfo.getUserMachineAddressInfo(), 100)) {
			json.setReturnCode(500);
			json.addResponseKeyValue("收货地址信息有误!");
			return json;
		}

		// 兑换密码
		cardPwd = cardPwd.toUpperCase();
		GiftCardInfo cardInfo = cardService.get(cardPwd);
		if (cardInfo == null) {
			json.setReturnCode(501);
			json.addResponseKeyValue("提货卡不存在!");
			return json;
		}
		if (cardInfo.getCardStatus() != 1) {
			json.setReturnCode(501);
			json.addResponseKeyValue("提货卡已经被使用!");
			return json;
		}
		return useCard(cardInfo, machineInfo, agent);
	}
	
	/**
	 * 开始提货
	 * 2017年3月31日
	 * @author muzx
	 * @param cardInfo
	 * @param machineInfo
	 * @param agent
	 * @return
	 */
	private ResponseJson useCard(GiftCardInfo cardInfo, UserMachineInfo machineInfo, AgentInfo agent){
	    ResponseJson json = new ResponseJson();
	    json.setResultCode(200);
	    try {
            Map<String, Object> map = cardService.salesCard(cardInfo, machineInfo, agent);
            if (!"1".equals(map.get("status"))) {
                json.setReturnCode(503);
                json.addResponseKeyValue("您的流程有误，请重试!");
                return json;
            }
            // 判断是否已经达到目标并赠送一台水机，如果赠送了，则推送消息
				if ("1".equals(map.get("target"))) {
					Member member = memberService.getMemberByUserOpenId(agent.getAgentOpenId());
					sendMessageUtil.prizeReceivePush(
							"您好，您已经达到销售目标，详情为:",
                        URLDecoder.decode(member.getUserNickname(), "UTF-8"),
                        "Watero水时代",
                        "0元",
                        DateTimeUtil.format(new Date()),
                        "美国watero净饮水一体机一台",
                        "请点击完善收货地址并领取奖励。",
                        member.getUserOpenid(),
                        ResultInfo.AGENT_REFERRER_MACHINE_PAGE
                                + "?agentMachineId="
                                + map.get("agentMachineId"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            json.setReturnCode(503);
            json.addResponseKeyValue("您的提货卡密码已被使用，请联系代理商!");
            return json;
        }

        json.setReturnCode(200);
        return json;
	}

	/**
	 * 发送短信验证码
	 * 
	 * @return
	 * @author 献
	 * @Time 2017年2月15日
	 */
	@ResponseBody
	@RequestMapping(value = "/send/sms/{phone}")
	public ResponseJson sms(@PathVariable(name = "phone") String phone) {
		ResponseJson json = new ResponseJson();

		// 校验手机号码
		if (!ValidateUtil.checkMobile(phone)) {
			json.setReturnCode(500);
			json.addResponseKeyValue("手机号码有误!");
			json.setResultCode(200);
			return json;
		}

		// 发送短信验证码
		return codeService.sms(phone);
	}

	/**
	 * 获取产品详细信息,通过颜色名称辨别对应的图片
	 * 
	 * @return
	 * @author 献
	 * @Time 2017年2月16日
	 */
	@ResponseBody
	@RequestMapping("/product/details")
	public ResponseJson productDetails(HttpServletRequest request) {
		ResponseJson json = new ResponseJson();
		String agentMachineId = request.getParameter("agentMachineId");
		if (agentMachineId != null && !agentMachineId.equals("")) {
			AgentMachine agentMachine = agentMachineService
					.selectAgentMachine(Integer.valueOf(agentMachineId));
			if (agentMachine != null) {
				if (agentMachine.getAgentMachineStatus() == 2 || agentMachine.getAgentMachineStatus() == 3) {
					json.addResponseKeyValue("msg", 2);
				} else if (agentMachine.getAgentMachineStatus() == 1) { 
					json.addResponseKeyValue("msg", 1);
				}
			}

		}
		// 获取当前用户
		Member member = WechatUtils.getUserBySession(request);
		// 查询用户信息
		AgentInfo agentInfo = agentService.selectAgentByOpenId(member
				.getUserOpenid());
		json.setResultCode(200);
		json.setReturnCode(200);
		// 获取水机颜色，写死产品ID
		json.addResponseKeyValue("colors", cardService.getColor(34));
		// 用户信息
		json.addResponseKeyValue("agentInfo", agentInfo);
		return json;
	}

	/**
	 * 申请兑现
	 * 
	 * @param request
	 * @param cardId
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/applyCash")
	public ResultMsg applyCash(HttpServletRequest request,
			@RequestParam("cardId") Integer cardId) throws Exception {

		ResultMsg msg = new ResultMsg();
		GiftCardDto card = new GiftCardDto();
		// 获取当前用户
		Member member = WechatUtils.getUserBySession(request);
		// 从规则表中获取提货卡兑现期限
		ShopSystemRule shopSystemRule = systemService
				.selectOneShopRuleById(223);
		// 查询用户信息
		Member user = memberService.getMemberByUserOpenId(member
				.getUserOpenid());

		card.setCardId(cardId);
		card.setCardOpenId(member.getUserOpenid());

		// 通过cardId和openId查询提货卡详情
		card = cardService.selectCardInfo(card);

		// 校验订单是否存在
		if (card == null) {
			msg.setMessage("该提货卡信息不存在");
			msg.setResultCode(ResultInfo.ERRORCODE);
			msg.setStatus(false);
			return msg;
		}
		// 判断提货卡是否已经达到可以兑现的期限了，如果没有，则不能兑现
		if ((new Date().getTime() - card.getCardCreateDate().getTime()) < shopSystemRule
				.getRuleNum() * (1000 * 3600 * 24)) {
			msg.setMessage("您好，兑现时间未到（获取一年后方可兑现）");
			msg.setResultCode(ResultInfo.ERRORCODE);
			msg.setStatus(false);
			return msg;
		}

		if (card.getCardStatus().intValue() != 1) {
			msg.setMessage("该提货卡已使用，不能兑现");
			msg.setResultCode(ResultInfo.ERRORCODE);
			msg.setStatus(false);
			return msg;
		}

		// 封装需要提货卡修改的信息
		GiftCardDto giftCardDto = new GiftCardDto();
		giftCardDto.setCardId(cardId);
		giftCardDto.setCardOpenId(member.getUserOpenid());
		giftCardDto.setCardOldStatus(1);
		giftCardDto.setCardStatus(3);

		// 封装提货卡兑换信息
		CardCashInfo cardCashInfo = new CardCashInfo();
		cardCashInfo.setCardCashOpenId(member.getUserOpenid());
		cardCashInfo.setCardCashCardId(cardId.toString());
		cardCashInfo.setCardCashSalesNickname(user.getUserNickname());
		cardCashInfo.setCardCashStatus(1);

		// 申请兑现，修改提货卡状态，在提货卡兑现表添加记录
		boolean flag = cardService.applyCash(giftCardDto, cardCashInfo);

		if (flag) {
			msg.setMessage("申请兑现成功");
			msg.setResultCode(ResultInfo.SUCCESSCODE);
			msg.setStatus(true);
		} else {
			msg.setMessage("申请兑现失败");
			msg.setResultCode(ResultInfo.ERRORCODE);
			msg.setStatus(false);
		}
		return msg;
	}

	/**
	 * 修改未出售的提货卡为已出售状态
	 * 
	 * @param request
	 * @param cardId
	 * @return
	 * @throws Exception
	 */
	/*
	 * @ResponseBody
	 * 
	 * @RequestMapping("/updateSalesStatus") public ResultMsg
	 * updateSalesStatus(HttpServletRequest request,
	 * 
	 * @RequestParam("cardId") Integer cardId) throws Exception {
	 * 
	 * ResultMsg msg = new ResultMsg(); GiftCardDto card = new GiftCardDto(); //
	 * 获取当前用户 Member member = WechatUtils.getUserBySession(request);
	 * 
	 * GiftCardDto giftCardDto = new GiftCardDto();
	 * giftCardDto.setCardId(cardId);
	 * giftCardDto.setCardOpenId(member.getUserOpenid()); //查询该提货卡详细信息
	 * giftCardDto = cardService.selectCardInfo(giftCardDto);
	 * //如果该提货卡状态必须是未售和未用，否则不能出售 if (giftCardDto.getCardSalesStatus().intValue()
	 * != 2 || giftCardDto.getCardStatus().intValue() != 1) {
	 * msg.setMessage("该提货卡已使用或已出售，不能再次出售!");
	 * msg.setResultCode(ResultInfo.ERRORCODE); msg.setStatus(false); }
	 * 
	 * //参数必须为未出售，未使用，如果条件不满足，则不会修改状态 card.setCardId(cardId);
	 * card.setCardOldSalesStatus(2); card.setCardOldStatus(1);
	 * card.setCardOpenId(member.getUserOpenid()); card.setCardSalesStatus(1);
	 * card.setCardSalesDate(new Date());
	 * 
	 * //修改提货卡出售状态 int num = cardService.updateCardStatus(card);
	 * 
	 * if (num > 0) { msg.setMessage("该提货卡已成功出售!");
	 * msg.setResultCode(ResultInfo.SUCCESSCODE); msg.setStatus(true); } else {
	 * msg.setMessage("该提货卡出售失败!"); msg.setResultCode(ResultInfo.ERRORCODE);
	 * msg.setStatus(false); } return msg; }
	 */

	/**
	 * 按openid分页查询个人提货卡信息
	 * 
	 * @param request
	 * @param pageSize
	 * @param pageNO
	 * @param status
	 *            1：未用，2：已兑换，3：待兑现，4：全部
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/selectCardList")
	public ResultMsg selectCardList(
			HttpServletRequest request,
			@RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
			@RequestParam(value = "pageNO", defaultValue = "1") Integer pageNO,
			@RequestParam(value = "status", defaultValue = "4") Integer status)
			throws Exception {

		ResultMsg msg = new ResultMsg();
		GiftCardDto card = new GiftCardDto();
		int salesNum = 0;	//待售礼品卡数量
		int waitExchangeNum = 0;	//待兑换数量
		int exchangeNum = 0;	//已兑换数量
		// 待售状态
		if (status.intValue() == 1) {
			card.setCardStatus(1);
		}
		// 待兑换状态
		if (status.intValue() == 2) {
			card.setCardStatus(2);
		}
		// 已兑换状态
		if (status.intValue() == 3) {
			card.setCardStatus(3);
		}
		// 获取当前用户
		Member member = WechatUtils.getUserBySession(request);

		card.setCardOpenId(member.getUserOpenid());
		card.getPage().setPageNumber(pageNO);
		card.getPage().setPageSize(pageSize);
		card.getPage().initRecordBegin();

		GiftCardDto cardDto = new GiftCardDto();
		cardDto.setCardOpenId(member.getUserOpenid());
		cardDto.setPage(null);
		// 查询个人所有提货卡信息
		List<GiftCardDto> cardAllList = cardService.selectCardList(cardDto);


		// 分页查询个人提货卡信息
		List<GiftCardDto> cardList = cardService.selectCardList(card);
		Map<String, Object> map = new HashMap<String, Object>();
		if (cardAllList != null && cardAllList.size() > 0) {
			for (GiftCardDto giftCardDto : cardAllList) {
				switch (giftCardDto.getCardStatus().intValue()) {
					case 1:salesNum++;break;
					case 2:waitExchangeNum++;break;
					case 3:exchangeNum++;break;
				}
			}
		}
		map.put("count", cardAllList.size());
		map.put("salesNum",salesNum);
		map.put("waitExchangeNum",waitExchangeNum);
		map.put("exchangeNum",exchangeNum);
		map.put("list", cardList);
		msg.setData(map);
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setStatus(true);
		return msg;
	}

	/**
	 * 兑换记录
	 * 
	 * @return
	 * @author 献
	 * @Time 2017年2月16日
	 */
	@ResponseBody
	@RequestMapping("/exchange/logs")
	public ResponseJson exChangeLogs(HttpServletRequest httpServletRequest) {
		Member member = WechatUtils.getUserBySession(httpServletRequest);
		ResponseJson json = new ResponseJson();
		json.setResultCode(200);
		json.setReturnCode(200);
		json.addResponseKeyValue("logs",
				cardService.list(member.getUserOpenid()));
		return json;
	}

	/**
	 * 代理商确认物流信息
	 * 
	 * @return
	 * @author LJK
	 * @Time 2017年2月16日
	 */
	@ResponseBody
	@RequestMapping("/selectAgentMachine")
	public ResponseJson selectAgentMachine(
			HttpServletRequest httpServletRequest,
			@RequestParam(value = "agentMachineId", required = false, defaultValue = "0") Integer agentMachineId) {
		ResponseJson json = new ResponseJson();
		if (agentMachineId == 0) {
			json.setReturnCode(503);
			json.setResultCode(200);
			json.addResponseKeyValue("查询失败！");
			return json;
		}
		json.setResultCode(200);
		json.setReturnCode(200);
		json.addResponseKeyValue("logs",
				agentMachineService.selectAgentMachine(agentMachineId));
		return json;
	}

	/**
	 * 代理商修改物流信息
	 *
	 * @return
	 * @author LJK
	 * @Time 2017年2月16日
	 */
	@ResponseBody
	@RequestMapping("/updateAgentMachine")
	public ResponseJson updateAgentMachine(
			HttpServletRequest httpServletRequest, AgentMachine agentMachine) {
		ResponseJson json = new ResponseJson();
		// 获取当前用户
		Member member = WechatUtils.getUserBySession(httpServletRequest);
		if (agentMachine == null) {
			json.setReturnCode(503);
			json.setResultCode(200);
			json.addResponseKeyValue("操作失败！");
			return json;
		}
		if (agentMachine.getAgentMachineId() == null) {
			json.setReturnCode(503);
			json.setResultCode(200);
			json.addResponseKeyValue("操作失败！");
			return json;
		}
		if (agentMachine.getAgentMachineColorId() == null) {
			json.setReturnCode(503);
			json.setResultCode(200);
			json.addResponseKeyValue("操作失败！");
			return json;
		}
		agentMachine.setAgentMachineOpenId(member.getUserOpenid());
		Integer msg = agentMachineService.selectAgentMachineByOpenId(agentMachine);
		if(msg == 0){
			json.setReturnCode(503);
			json.setResultCode(200);
			json.addResponseKeyValue("操作失败！");
			return json;
		}
		ProductColor productColor = productColorService.selectProductColorById(agentMachine.getAgentMachineColorId());
		agentMachine.setAgentMachineColorName(productColor.getColorName());
		agentMachine.setAgentMachineProductName(productColor.getColorProductName());
		agentMachine.setAgentMachine69code(productColor.getColor69Code());
		agentMachine.setAgentMachineProductId(productColor.getColorProductId());
		agentMachine.setAgentMachineStatus(2);
		msg = agentMachineService.updateAgentMachine(agentMachine);
		if (msg > 0) {
			json.setResultCode(200);
			json.setReturnCode(200);
			json.addResponseKeyValue("操作成功！");
			try {
				// 推送百胜
				efastOrderService.giftCard(
						agentMachine.getAgentMachineAddressInfo(), "ZS22222222"
								+ agentMachine.getAgentMachineId(),
						agentMachine.getAgentMachineColorId(),
						agentMachine.getAgentMachineAddressName(),
						agentMachine.getAgentMachineAddressTel(),
						member.getUserOpenid());
			} catch (Exception e) {
				System.out.println("推送百胜失败!");
			}
		} else {
			json.setReturnCode(503);
			json.setResultCode(200);
			json.addResponseKeyValue("操作失败！");
			return json;
		}
		return json;
	}

	/**
	 * 根据兑换密码，查看兑换详情
	 * 
	 * @param card
	 * @return
	 * @author 献
	 * @Time 2017年2月16日
	 */
	@ResponseBody
	@RequestMapping("/exchangDetails")
	public ResponseJson exchangeDetails(@RequestParam("cardPwd") String card) {
		ResponseJson json = new ResponseJson();
		json.setResultCode(200);
		json.setReturnCode(200);
		json.addResponseKeyValue("card", cardService.get(card));
		return json;
	}

	/**
	 * 我推荐的人列表
	 * 
	 * @param request
	 * @param pageSize
	 * @param pageNO
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/beRefereesList")
	public ResultMsg beRefereesList(
			HttpServletRequest request,
			@RequestParam(value = "pageSize", defaultValue = "6", required = false) Integer pageSize,
			@RequestParam(value = "pageNO", defaultValue = "1") Integer pageNO)
			throws Exception {

		ResultMsg msg = new ResultMsg();
		AgentInfo agentInfo = new AgentInfo();
		// 获取当前用户
		Member member = WechatUtils.getUserBySession(request);

		agentInfo.setAgentReferrerOpenid(member.getUserOpenid());
		agentInfo.getPage().setPageNumber(pageNO);
		agentInfo.getPage().setPageSize(pageSize);
		agentInfo.getPage().initRecordBegin();

		// 分页查询个人提货卡信息
		List<AgentInfo> cardList = agentService.beRefereesList(agentInfo);

		msg.setData(cardList);
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setStatus(true);
		return msg;
	}

	/**
	 * 赠品列表
	 * 
	 * @param request
	 * @param pageSize
	 * @param pageNO
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/giftList")
	public ResultMsg giftList(
			HttpServletRequest request,
			@RequestParam(value = "pageSize", defaultValue = "6", required = false) Integer pageSize,
			@RequestParam(value = "pageNO", defaultValue = "1") Integer pageNO)
			throws Exception {

		ResultMsg msg = new ResultMsg();
		AgentMachine agentMachine = new AgentMachine();
		// 获取当前用户
		Member member = WechatUtils.getUserBySession(request);

		agentMachine.setAgentMachineOpenId(member.getUserOpenid());
		// agentMachine.getPage().setPageNo(pageNO);
		agentMachine.getPage().setPageSize(pageSize);
		agentMachine.getPage().setPageNo(recordBegin(pageNO, pageSize));

		// 分页查询个人赠品信息信息
		List<AgentMachine> cardList = agentMachineService
				.selectAllAgentMachineById(agentMachine);

		msg.setData(cardList);
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setStatus(true);
		return msg;
	}

	public Integer recordBegin(Integer pageNumber, Integer getPageSize) {
		if (pageNumber == 1)
			pageNumber = 0;
		if (pageNumber > 1) {
			pageNumber = getPageSize * (pageNumber - 1);
		}
		return pageNumber;
	}

	/**
	 * 续费页面入口 - 页面
	 * 
	 * @return
	 * @author LJK
	 * @Time 2017年2月22日10:15:48
	 */
	@RequestMapping(value = "/renewalUI")
	public void renewalUI(HttpServletRequest request,
			HttpServletResponse response) {
		// 获取当前用户
		Member member = WechatUtils.getUserBySession(request);
		String url = null;
		List<UserMachineInfo> UserMachineInfoList = cardService.list(member
				.getUserOpenid());
		if (UserMachineInfoList.size() > 0) {
			url = "/WEB-INF/views/wechat/gift_card_exchange_list.html";
			dispatcherLink(response, request, url);
			return;
		} else {
			url = "/view/gift_card_user_exchange.html";
			dispatcherLink(response, request, url);
			return;
		}

	}
}
