package com.iamberry.wechat.handles.member;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
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.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.Page;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.member.ApplyDto;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.member.Withdraw;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.member.WithdrawService;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.ValidatorUtil;
/**
 * @author 何秀刚
 * Class Description: 
 * Create Date:2016年4月21日
 * Update Date:2016年4月21日
 */
@Controller
@RequestMapping("/wechat/withdraw")
public class WithdrawHandler {
	
	@Autowired
	private WithdrawService withdrawService;
	
	@Autowired
	private WechatUtils wechatUtils;

	@Autowired
	private ValidatorUtil validatorUtil;
	
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private MemberService memberService;
	
	/**
	 * 请求提现接口
	 * @param applyDto
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/applyCash", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg applyCash(ApplyDto applyDto, HttpServletRequest request) throws Exception {
		ResultMsg msg = new ResultMsg();
		
		Member dataMember = wechatUtils.getUserBySession(request);
		if (dataMember == null) {
			msg.setMessage(ResultInfo.loginOutError);
			return msg;
		}
		dataMember = memberService.getMemberByUserOpenId(dataMember.getUserOpenid());
		if (!validatorUtil.validatorObject(applyDto)) {
			msg.setMessage(ResultInfo.paramFormatError);
			return msg;
		}
		
		// 获取用户可用金额
		int minCash = systemService.selectOneShopRuleById(101).getRuleNum().intValue(); // 提现下限
		int userCash = dataMember.getUserIncome(); // 可用金额
		if (applyDto.getIntegralNum() <= 0) {
			msg.setMessage("提现金额不能为负数!");
			return msg;	
		}
		if (!(applyDto.getIntegralNum() >= minCash / 100 && applyDto.getIntegralNum() <= userCash)) {
			msg.setMessage("提现金额需大于最小金额,小于您的可提现金额!");
			return msg;
		}
		int moneyCount = systemService.selectOneShopRuleById(100).getRuleNum().intValue(); // 提现次数
		Date date = new Date();
		date = new Date(date.getTime() - 2592000000L);	//时间减去一个月
		Withdraw withdraw = new Withdraw();
		withdraw.setWithdrawalsOpenid(dataMember.getUserOpenid());
		withdraw.setWithdrawalsLogsDate(date);
		int count = withdrawService.selectUseLogsCount(withdraw);	//提现时间大于date的记录数
		if (moneyCount <= count) { // 是否本月提现次数已经使用完了
			msg.setMessage(ResultInfo.withdrawCountOutError);
			return msg;
		}
		
		// 添加申请 修改用户可用金额 添加现金记录
		try {
			if (withdrawService.addApplyCashWithdraw(applyDto, dataMember)) {
				msg.setMessage(ResultInfo.SUCCESSINFO);
				msg.setStatus(true);
				return msg;
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg.setMessage(e.getMessage());
			return msg;
		}
		return msg;
	}
	
	/**
	 * 申请提现前调用数据	<现金>
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value = "/applyCashBefore", method = RequestMethod.POST)
	public ResultMsg applyCashBefore(
			HttpServletRequest request) throws Exception {
		ResultMsg msg = new ResultMsg();
		
		/** 校验 */
		Member member = wechatUtils.getUserBySession(request);
		if (member == null) {
			msg.setMessage(ResultInfo.loginOutError);
			return msg;
		}
//		Member member = memberService.getMemberByUserId(2029);
		Member dataMember = memberService.getMemberByUserOpenId(member.getUserOpenid());
		/** 拼装数据 */
		Map<String, Object> maps = new HashMap<String, Object>();
		List<ShopSystemRule> systemRule = systemService.selectAllShopRule();
		//获取当前用户上一次的提款记录
		Page page = new Page();
		page.setPageNo(0);
		page.setPageSize(1);
		page.getParams().put("openid", member.getUserOpenid());
		List<Withdraw> list = withdrawService.selectLogsByOpenid(page); //这里有且最多一条数据，或者没有数据
		if(list!=null && list.size()>0 ){
			maps.put("Withdraw", list.get(0));		//最大可取金额
		}
		
		//当前用户可用金额
		int userMoney = dataMember.getUserIncome() == null ? 0 : dataMember.getUserIncome();
		maps.put("userMoney", userMoney);		//最大可取金额
		for (ShopSystemRule rule : systemRule) {
			if(rule.getRuleId().intValue() == 100){		// 提现次数
				maps.put("withdrawMoneyCount", rule.getRuleNum().intValue());
			}
			if(rule.getRuleId().intValue() == 101){		// 最低提现金额
				maps.put("minWithdrawMoneyAmount", rule.getRuleNum().intValue());
				if(userMoney < rule.getRuleNum()){
					msg.setMessage(ResultInfo.userMoneyOutError);
					return msg;
				}
			}
		}
		
		// 封装返回数据
		msg.setData(maps);
		msg.setMessage(ResultInfo.SUCCESSINFO);
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setStatus(true);
		return msg;
	}

	/**
	 * 分页获取用户的提现信息
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value = "/selectUserLogs", method = RequestMethod.POST)
	public ResultMsg selectUserLogs(
			@RequestParam(value = "pageNO", defaultValue = "1", required = false) int pageNO,
			@RequestParam(value = "pageSize", defaultValue = "5", required = false) int pageSize, 
			HttpServletRequest request) throws Exception {
		ResultMsg msg = new ResultMsg();
		
		Member member = wechatUtils.getUserBySession(request);
		Page page = new Page();
		page.setPageNo((pageNO - 1) * pageSize);
		page.setPageSize(pageSize);
		page.getParams().put("openid", member.getUserOpenid());
		List<Withdraw> list = withdrawService.selectLogsByOpenid(page);
		
		msg.setData(list);
		msg.setMessage(ResultInfo.SUCCESSINFO);
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setStatus(true);
		return msg;
	}
	
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public void productDesc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher(NameUtils.WECHAT_SHOP_WITHDRAW_APPLY).forward(request, response);return;
	}
	
	/**
	 * 现金提现页面跳转
	 * 2016年5月4日
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "/cash", method = RequestMethod.GET)
	public void toApplyCash(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		
		request.getRequestDispatcher(NameUtils.WECHAT_SHOP_WITHDRAW_APPLY_CASH).forward(request, response);return;
	}
	
	/**
	 * 现金提现页面跳转
	 * 2016年5月4日
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "/success", method = RequestMethod.GET)
	public void toApplyCashSuccess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher(NameUtils.WECHAT_SHOP_WITHDRAW_APPLY_CASH_SUCCESS).forward(request, response);return;
	}
}
