package com.iamberry.wechat.handles.game;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.lang3.StringUtils;
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.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.game.GameLogsDto;
import com.iamberry.wechat.core.entity.game.GamePrizeDto;
import com.iamberry.wechat.core.entity.game.GameSystemDto;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.order.Order;
import com.iamberry.wechat.face.cart.CartService;
import com.iamberry.wechat.face.game.GameService;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
@Controller
@RequestMapping("/wechat/game")
public class GameHandler {

	@Autowired
	private GameService gameService;
	
	@Autowired
	private CartService orderService;
	
	/**
	 * 根据游戏id，查询游戏信息
	 * @param request
	 * @param gameType
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/get_game_id")
	public ResultMsg selectGameByGameType(HttpServletRequest request,
			@RequestParam(value = "id", required = false, defaultValue = "1") Integer id,
			HttpServletResponse response) throws Exception {
		ResultMsg resultMsg = new ResultMsg();
		Member member = WechatUtils.getUserBySession(request);	
		if (member == null || member.getUserOpenid() == null || "null".equals(member.getUserOpenid())) {
			resultMsg.setMessage(NameUtils.getConfig("ERRORINFO"));
			resultMsg.setStatus(false);
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
			resultMsg.setData(0);
			return resultMsg;
		}
		GameSystemDto gameSystemDto = new GameSystemDto();
		if (null != id) {
			gameSystemDto.setGameId(id);
		}
		//根据游戏类型查询游戏信息
		GameSystemDto gameSystem = gameService.selectGameByGameType(gameSystemDto);
		resultMsg.setData(gameSystem);
		resultMsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		resultMsg.setResultCode(ResultInfo.SUCCESSCODE);
		resultMsg.setStatus(true);
		return resultMsg;
	}
	
	/**
	 * 根据游戏id查询对应的游戏奖品信息
	 * @param request
	 * @param prizeGameId
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/get_prize_info")
	public ResultMsg selectGamePrizeByGameId(HttpServletRequest request,
			@RequestParam(value = "prizeGameId", required = false, defaultValue = "") Integer prizeGameId) throws Exception {
		ResultMsg resultMsg = new ResultMsg();
		WechatUtils.getUserBySession(request);
		GamePrizeDto gamePrizeDto = new GamePrizeDto();
		if (null != prizeGameId && !"".equals(prizeGameId)) {
			gamePrizeDto.setPrizeGameId(prizeGameId);
		}
		//根据游戏id查询对应的游戏奖品信息
		List<GamePrizeDto> gamePrizeList = gameService.selectGamePrizeByGameId(gamePrizeDto);
		resultMsg.setData(gamePrizeList);
		resultMsg.setStatus(true);
		resultMsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
		resultMsg.setResultCode(ResultInfo.SUCCESSCODE);
		return resultMsg;
	}
	
	/**
	 * 根据游戏id和orderId查询该游戏可玩次数
	 * @param gameId
	 * @param orderId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/selectGameCount")
	public ResultMsg selectGameCount(@RequestParam("gameId") Integer gameId,
			@RequestParam("orderId") String orderId, HttpServletRequest request) throws Exception {
		Member member = WechatUtils.getUserBySession(request);
		ResultMsg resultMsg = new ResultMsg();
		GameLogsDto gameLogsDto = new GameLogsDto();
		GameSystemDto gameSystemDto = new GameSystemDto();
		//游戏剩余可玩次数
		int gameCount = 0;
		if (null == gameId || "".equals(gameId.toString())) {
			resultMsg.setMessage("游戏id为空");
			resultMsg.setStatus(false);
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
			resultMsg.setData(0);
			return resultMsg;
		}
		if (StringUtils.isEmpty(orderId)) {
			resultMsg.setMessage("订单id为空");
			resultMsg.setStatus(false);
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
			resultMsg.setData(0);
			return resultMsg;
		}
		gameLogsDto.setLogsOpenId(member.getUserOpenid());
		gameLogsDto.setLogsGameId(gameId);
		gameLogsDto.setLogsOrderId(orderId);
		//通过订单号，游戏id和openid查询该用户玩游戏共玩了多少次
		int gameNum = gameService.selectGameLogsCount(gameLogsDto);
		
		gameSystemDto.setGameId(gameId);
		//根据游戏id查询该游戏一共可玩次数
		gameSystemDto = gameService.selectGameByGameType(gameSystemDto);
		
		if (null != gameSystemDto && null != gameSystemDto.getGameThresholdNum()) {
			//计算该游戏剩余可玩次数
			gameCount = gameSystemDto.getGameThresholdNum().intValue() - gameNum;
			resultMsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			resultMsg.setStatus(true);
			resultMsg.setResultCode(ResultInfo.SUCCESSCODE);
			resultMsg.setData(gameCount);
			return resultMsg;
		} else {
			resultMsg.setMessage("该游戏不存在");
			resultMsg.setStatus(false);
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
			resultMsg.setData(0);
			return resultMsg;
		}
	}
	
	/**
	 * 抽奖
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/luck_draw", method = RequestMethod.GET)
	@ResponseBody
	public ResultMsg LuckyDraw(@RequestParam("gameId") Integer gameId,
			@RequestParam("orderId") String orderId, HttpServletRequest request) throws Exception {
		Member member = WechatUtils.getUserBySession(request);
		ResultMsg resultMsg = new ResultMsg();
		
		// 判断
		if (null != orderId && !"".equals(orderId) && !StringUtils.isEmpty(orderId)) {
			Order order = new Order();
			order.setSalesOrderid(orderId);
			order.setSalesOpenid(member.getUserOpenid());
			order = orderService.selectOrderInfoById(order);
			if (order == null || StringUtils.isEmpty(order.getSalesOrderid())) {
				resultMsg.setMessage(NameUtils.getConfig("ERRORINFO"));
				resultMsg.setStatus(false);
				resultMsg.setResultCode(ResultInfo.ERRORCODE);
				resultMsg.setData(0);
				return resultMsg;
			}
		}
		// 抽奖
		return gameService.getPrize(gameId, orderId, member.getUserOpenid());
	}
	
	/**
	 * 获取当前用户游戏的中奖纪录
	 * 2016年9月28日
	 * 穆再兴
	 * @return
	 */
	@RequestMapping("/get_prize_log")
	@ResponseBody
	public ResultMsg getPrizeLog(HttpServletRequest req,
			@RequestParam(value="gameId",defaultValue = "") String gameId,
			@RequestParam(value= "pageSize",defaultValue= "6" ,required=false) Integer pageSize, 
			@RequestParam(value = "pageNO", defaultValue = "1") Integer pageNO){
		ResultMsg rm = new ResultMsg();
		Map<String,Object> map = new HashMap<String,Object>();
		Member member = WechatUtils.getUserBySession(req);
		List<GameLogsDto> winningList = new ArrayList<GameLogsDto>();
		if(StringUtils.isNotEmpty(member.getUserOpenid())){
			GameLogsDto logDto = new GameLogsDto();
			if (StringUtils.isNotEmpty(gameId)) {
				logDto.setLogsGameId(Integer.parseInt(gameId));
			}
			logDto.setLogsOpenId(member.getUserOpenid());
			logDto.getPage().setPageNumber(pageNO);
			logDto.getPage().setPageSize(pageSize);
			logDto.getPage().initRecordBegin();
			winningList = gameService.selectWinningLogsByGameId(logDto);
			map.put("pageCount", gameService.selectWinningCount(logDto));
		}
		if(winningList.size() > 0){
			rm.setResultCode("200");
			map.put("winningList", winningList);
			rm.setData(map);
			rm.setStatus(true);
		}else{
			rm.setResultCode("200");
			rm.setMessage("对不起,您没有中奖纪录！");
			rm.setData(0);
			rm.setStatus(true);
		}
		return rm;
	}
	
	/**
	 * 查询万圣节大转盘游戏可玩次数
	 * @param request
	 * @param gameId
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/selectHallowmasGameCount")
	public ResultMsg selectHallowmasGameCount(HttpServletRequest request,
			@RequestParam(value="gameId",defaultValue = "") String gameId) throws Exception {
		Member member = WechatUtils.getUserBySession(request);
		ResultMsg resultMsg = new ResultMsg();
		GameLogsDto gameLogsDto = new GameLogsDto();
		GameSystemDto gameSystemDto = new GameSystemDto();
		//游戏剩余可玩次数
		int gameCount = 0;
		if (null == gameId || "".equals(gameId)) {
			resultMsg.setMessage("游戏id为空");
			resultMsg.setStatus(false);
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
			resultMsg.setData(0);
			return resultMsg;
		}
		gameLogsDto.setLogsOpenId(member.getUserOpenid());
		gameLogsDto.setLogsGameId(Integer.parseInt(gameId));
		//通过订单号，游戏id查询该用户玩游戏共玩了多少次
		int gameNum = gameService.selectGameLogsCount(gameLogsDto);
		
		gameSystemDto.setGameId(Integer.parseInt(gameId));
		//根据游戏id查询该游戏一共可玩次数
		gameSystemDto = gameService.selectGameByGameType(gameSystemDto);
		
		if (null != gameSystemDto && null != gameSystemDto.getGameThresholdNum()) {
			//计算该游戏剩余可玩次数
			gameCount = gameSystemDto.getGameThresholdNum().intValue() - gameNum;
			resultMsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			resultMsg.setStatus(true);
			resultMsg.setResultCode(ResultInfo.SUCCESSCODE);
			resultMsg.setData(gameCount);
			return resultMsg;
		} else {
			resultMsg.setMessage("该游戏不存在");
			resultMsg.setStatus(false);
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
			resultMsg.setData(0);
			return resultMsg;
		}
	}
	
	/**
	 * 万圣节大转盘，判断是否需要购买订单
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/buyOrder")
	public ResultMsg buyOrder(HttpServletRequest request, 
			@RequestParam(value="gameId",defaultValue = "") String gameId) throws Exception {
		Member member = WechatUtils.getUserBySession(request);
		ResultMsg resultMsg = new ResultMsg();
		Order order = new Order();
		if (null == gameId || "".equals(gameId)) {
			resultMsg.setMessage("游戏id为空");
			resultMsg.setStatus(false);
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
			resultMsg.setData(false);
			return resultMsg;
		}
		GameSystemDto gameSystemDto = new GameSystemDto();
		gameSystemDto.setGameId(Integer.parseInt(gameId));
		//根据游戏id查询游戏信息
		GameSystemDto gameSystem = gameService.selectGameByGameType(gameSystemDto);
		if (gameSystem == null || gameSystem.getGameStartDate() == null || gameSystem.getGameEndDate() == null) {
			resultMsg.setMessage("该游戏或是开始结束时间为空");
			resultMsg.setStatus(false);
			resultMsg.setResultCode(ResultInfo.ERRORCODE);
			resultMsg.setData(false);
			return resultMsg;
		}
		order.setBeginDate(gameSystem.getGameStartDate());
		order.setEndDate(gameSystem.getGameEndDate());
		order.setSalesOpenid(member.getUserOpenid());
		//根据游戏开始时间，结束时间，openid查询时候存在有效订单(订单状态为2，5，12为有效订单)
		int num = gameService.selectOrderByCreateDate(order);
		if (num > 0) {
			resultMsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			resultMsg.setStatus(true);
			resultMsg.setResultCode(ResultInfo.SUCCESSCODE);
			resultMsg.setData(true);
			return resultMsg;
		} else {
			resultMsg.setMessage(NameUtils.getConfig("SUCCESSINFO"));
			resultMsg.setStatus(true);
			resultMsg.setResultCode(ResultInfo.SUCCESSCODE);
			resultMsg.setData(false);
			return resultMsg;
		}
	}
}
