package com.iamberry.wechat.handles.agent;

import java.text.MessageFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.iamberry.app.config.ImberryConfig;
import com.iamberry.util.RandomUtil;
import com.iamberry.wechat.core.entity.coupon.CouponItemDto;
import com.iamberry.wechat.face.coupon.CouponItemService;
import com.iamberry.wechat.face.sendmsg.CodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.apache.commons.lang.StringUtils;

import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.agent.AgentMemberDto;
import com.iamberry.wechat.core.entity.agent.AgentOrderDto;
import com.iamberry.wechat.core.entity.agent.OrderStatusDto;
import com.iamberry.wechat.core.entity.cart.ShopSalesOrderDto;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.mq.MQMessage;
import com.iamberry.wechat.face.agent.AgentMemberService;
import com.iamberry.wechat.face.agent.AgentOrderService;
import com.iamberry.wechat.face.cart.CartService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.mq.MQSerivce;
import com.iamberry.wechat.face.qrcode.QrcodeService;
import com.iamberry.wechat.handles.mq.MQServiceProxy;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.StrUtils;

/**
 * 微代理 handler 类
 * @author 穆再兴
 *	2016年4月19日
 */
@Controller
@RequestMapping("/wechat/agent")
public class AgentHandler {
	private Logger logger = LoggerFactory.getLogger(AgentHandler.class);
	@Autowired
	private AgentOrderService agentOrderService;	//微代理订单service
	@Autowired
	private MemberService memberService;			//会员service
	@Autowired
	private AgentMemberService agentMemberService;	//微代理会员service
	@Autowired
	private CouponItemService couponItemService;
	@Autowired
	private CodeService codeService;
	@Autowired
	private QrcodeService qrcodeService;
	@Autowired
	private CartService cartService;
	@Autowired
	private MQServiceProxy mQservice;
	/**
	 * 获取当前用户<微代理> 的订单记录
	 * 2016年4月19日
	 * @author 穆再兴
	 * @return json格式
	 */
	@RequestMapping("/agentOrder")
	@ResponseBody
	public ResultMsg getAgentOrderJson(HttpServletRequest req,
			@RequestParam(value="rebackStatus",defaultValue= "4", required=false)Integer rebackStatus,
			@RequestParam(value="pageSize",defaultValue= "6", required=false)String pageSize,
			@RequestParam(value="pageNO",defaultValue= "1", required=false)String pageNO){
		ResultMsg rm = new ResultMsg();
		Member member = new Member();
		try {
			member = WechatUtils.getUserBySession(req);
			if(member == null){
				rm.setMessage(ResultInfo.loginOutError);
				return rm;
			}
			member = memberService.getMemberByUserOpenId(member.getUserOpenid());
			if(member == null){ member = new Member();}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//查当前用户<微代理>userid 所有订单
		AgentOrderDto orderDto = new AgentOrderDto();
		orderDto.setOrderOpenid(member.getUserOpenid());
		orderDto.getPage().setPageSize(Integer.parseInt(pageSize));
		orderDto.getPage().setPageNumber(Integer.parseInt(pageNO));
		orderDto.setRebackStatus(rebackStatus);
		
		// 我加的
		orderDto.getPage().initRecordBegin();
		
		Map<String, Object> map = agentOrderService.getOrderListAndCountByOpenid(orderDto);
		map.put("userIncome", member.getUserIncome() == null ? 0 : member.getUserIncome().intValue());
		rm.setResultCode(ResultInfo.SUCCESSCODE);
		rm.setMessage(ResultInfo.SUCCESSINFO);
		rm.setStatus(true);
		rm.setData(map);
		return rm;
	}
	
	/**
	 * 会员中心页面
	 * 2016年4月21日
	 * @author 穆再兴
	 * @return
	 */
	@RequestMapping("/member")
	@ResponseBody
	public ResultMsg getMemberInfo(HttpServletRequest req){
		ResultMsg rm = new ResultMsg();
		Member member = WechatUtils.getUserBySession(req);
		member = memberService.getMemberByUserOpenId(member.getUserOpenid());
		AgentMemberDto agentMember = agentMemberService.getMemberInfo(member);

//		ShopSalesOrderDto shopSalesOrderDto = new ShopSalesOrderDto();
//		shopSalesOrderDto.setSalesOpenid(member.getUserOpenid());
//		List<ShopSalesOrderDto> orderList = cartService.getOrderList(shopSalesOrderDto);

		CouponItemDto couponItemDto = new CouponItemDto();
		couponItemDto.setUseropenid(member.getUserOpenid());
		couponItemDto.setBeginDate(new Date());
		couponItemDto.setCouponUseStatus(1);
		Integer couponCount = couponItemService.getCouponItemCount(couponItemDto);
		agentMember.setCouponCount(couponCount);

		rm.setMessage(ResultInfo.SUCCESSINFO);
		rm.setStatus(true);
		rm.setData(agentMember);
		return rm;
	}

	/**
	 * 完善用户信息
	 * @return
	 */
	@RequestMapping("/updateMemberInfo")
	@ResponseBody
	public ResultMsg updateMemberInfo(HttpServletRequest request,Member member,String code){
		ResultMsg rm = new ResultMsg();
		Member m = WechatUtils.getUserBySession(request);

		m = memberService.getMemberByUserOpenId(m.getUserOpenid());
		if(m.getUserIsVip() == 2){
			return new ResultMsg(false, ResultMsg.ERROR, "您已经是会员了!",null);
		}

		if(m.getUserOpenid()== null || "".equals(m.getUserOpenid())){
			return new ResultMsg(false,  ResultMsg.ERROR, "完善信息失败-用户OpenId为空",null);
		}
		if(member == null){
			return new ResultMsg(false, ResultMsg.ERROR, "完善信息失败，用户信息为空，请联系公众号客服!",null);
		}

		//姓名
		if(member.getUserName() == null){
			return new ResultMsg(false, ResultMsg.ERROR, "完善信息失败，姓名不能为空!",null);
		}
		//性别
		if(member.getUserSex() == null){
			return new ResultMsg(false, ResultMsg.ERROR, "完善信息失败，性别不能为空!",null);
		}
		//生日	userBirthDate
		if(member.getUserBirthDate() == null){
			return new ResultMsg(false, ResultMsg.ERROR, "完善信息失败，生日不能为空!",null);
		}
		//手机号码
		if(member.getUserTel() == null){
			return new ResultMsg(false, ResultMsg.ERROR, "完善信息失败，手机号码为空!",null);
		}
		//验证码
		if(code == null || "".equals(code)){
			return new ResultMsg(false, ResultMsg.ERROR, "完善信息失败，验证码为空!",null);
		}

		//使用request对象的getSession()获取session，如果session不存在则创建一个
		HttpSession session = request.getSession();
		Map verificMemberPhoneMap = (Map) session.getAttribute("verification_tel_"+m.getUserOpenid());
		String verificationTel = (String) verificMemberPhoneMap.get("verification_tel");
		String verificationCode = (String) verificMemberPhoneMap.get("verification_code");
		Date verificationDate = (Date)  verificMemberPhoneMap.get("verification_date");
		if(verificationTel == null || verificationCode == null || verificationDate == null){
			logger.info("openid="+member.getUserOpenid()+"phone："+member.getUserTel()+"=完善信息失败，请重新获取验证码");
			return new ResultMsg(false, ResultMsg.ERROR, "完善信息失败，请重新获取验证码!",null);
		}
		if(member.getUserTel().length() != 11 && member.getUserTel().equals(verificationTel)){
			rm.setMessage(ResultMsg.ERROR);
			rm.setMessage("电话号码错误!");
			return rm;
		}
		if(code == null || "".equals(code)){
			return new ResultMsg(false, ResultMsg.ERROR, "验证码为空!",null);
		}
		Calendar nowTime = Calendar.getInstance();
		nowTime.setTime(verificationDate);
		nowTime.add(Calendar.MINUTE, 5);
		Date verData = nowTime.getTime();
		if(!verificationCode.equals(code)){
			logger.info("openid="+member.getUserOpenid()+"phone："+member.getUserTel()+"=验证码不正确，请重新输入");
			return new ResultMsg(false,  ResultMsg.ERROR, "验证码不正确，请重新输入!",null);
		}
		if((verData.getTime() < System.currentTimeMillis())){
			request.getSession().removeAttribute("verification_tel_"+m.getUserOpenid()); //遍历删除session中的值
			return new ResultMsg(false,  ResultMsg.ERROR, "验证码已失效，请重新获取!",null);
		}

		ResultMsg msg = new ResultMsg();
		member.setUserOpenid(m.getUserOpenid());
		member.setUserIsVip(2);	//是否为vip ：1:非vip  2：vip
		member.setUserVipDate(new Date());
		Integer  flag = memberService.becomeVipByOpenId(member);
		if (flag > 0 ) {
			request.getSession().removeAttribute("verification_tel_"+m.getUserOpenid()); //遍历删除session中的值
			msg.setResultCode(ResultInfo.SUCCESSCODE);
			msg.setStatus(true);
			return msg;
		} else {
			msg.setResultCode(ResultInfo.ERRORCODE);
			msg.setStatus(false);
			msg.setMessage("成为会员失败");
			return msg;
		}
	}


	/**
	 * 修改手机号码
	 * @return
	 */
	@RequestMapping("/updateMemberPhone")
	@ResponseBody
	public ResultMsg updateMemberPhone(HttpServletRequest request,Member member,String code){
		ResultMsg rm = new ResultMsg();
		Member m = WechatUtils.getUserBySession(request);

		//手机号码
		if(member.getUserTel() == null){
			return new ResultMsg(false, ResultMsg.ERROR, "修改手机号码失败，手机号码为空!",null);
		}
		//验证码
		if(code == null || "".equals(code)){
			return new ResultMsg(false, ResultMsg.ERROR, "修改手机号码失败，验证码为空!",null);
		}

		//使用request对象的getSession()获取session，如果session不存在则创建一个
		HttpSession session = request.getSession();
		Map verificMemberPhoneMap = (Map) session.getAttribute("verification_tel_"+m.getUserOpenid());
		String verificationTel = (String) verificMemberPhoneMap.get("verification_tel");
		String verificationCode = (String) verificMemberPhoneMap.get("verification_code");
		Date verificationDate = (Date)  verificMemberPhoneMap.get("verification_date");
		if(verificationTel == null || verificationCode == null || verificationDate == null){
			logger.info("openid="+member.getUserOpenid()+"phone："+member.getUserTel()+"=修改手机号码失败，请重新获取验证码");
			return new ResultMsg(false, ResultMsg.ERROR, "修改手机号码失败，请重新获取验证码!",null);
		}
		if(member.getUserTel().length() != 11 && member.getUserTel().equals(verificationTel)){
			rm.setMessage(ResultMsg.ERROR);
			rm.setMessage("修改手机号码失败-手机号码错误!");
			return rm;
		}
		if(code == null || "".equals(code)){
			return new ResultMsg(false, ResultMsg.ERROR, "验证码不能为空!",null);
		}
		Calendar nowTime = Calendar.getInstance();
		nowTime.setTime(verificationDate);
		nowTime.add(Calendar.MINUTE, 5);
		Date verData = nowTime.getTime();
		if(!verificationCode.equals(code)){
			logger.info("openid="+member.getUserOpenid()+"phone："+member.getUserTel()+"=验证码不正确，请重新输入");
			return new ResultMsg(false,  ResultMsg.ERROR, "验证码不正确，请重新输入!",null);
		}
		if((verData.getTime() < System.currentTimeMillis())){
			request.getSession().removeAttribute("verification_tel_"+m.getUserOpenid()); //遍历删除session中的值
			return new ResultMsg(false,  ResultMsg.ERROR, "验证码已失效，请重新获取!",null);
		}

		ResultMsg msg = new ResultMsg();
		member.setUserOpenid(m.getUserOpenid());
		Integer  flag = memberService.nowUpdateUserByOpenId(member);
		if (flag > 0 ) {
			request.getSession().removeAttribute("verification_tel_"+m.getUserOpenid()); //遍历删除session中的值
			msg.setResultCode(ResultInfo.SUCCESSCODE);
			msg.setStatus(true);
			return msg;
		} else {
			msg.setResultCode(ResultInfo.ERRORCODE);
			msg.setStatus(false);
			msg.setMessage("修改电话号码失败");
			return msg;
		}
	}

	/**
	 * 发送短信
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/send_phone")
	public ResultMsg sendPhone(HttpServletRequest request,String phone) throws Exception {
		ResultMsg msg = new ResultMsg();

		Member m = WechatUtils.getUserBySession(request);

		if(phone.trim().length() != 11){
			msg.setMessage("电话号码错误!");
			return msg;
		}

		//获取验证码
		String num = RandomUtil.getRandom();
		//使用request对象的getSession()获取session，如果session不存在则创建一个
		HttpSession session = request.getSession();
		String text = MessageFormat.format(ImberryConfig.PROBATION_VERIFICATION_CODE, num);
		String result = codeService.informShipping(phone, text);

		Map verificMemberPhoneMap = new HashMap();
		verificMemberPhoneMap.put("verification_code",num);
		verificMemberPhoneMap.put("verification_tel",phone);
		verificMemberPhoneMap.put("verification_date",new Date());
		session.setAttribute("verification_tel_"+m.getUserOpenid(),verificMemberPhoneMap);

		if ("SUCCESS".equals(result)) {
			logger.info("短信发送成功，验证码为：" + num);
			msg.setResultCode(ResultInfo.SUCCESSCODE);
			msg.setStatus(true);
			return msg;
		} else {
			logger.info("短信发送失败：" + result);
			msg.setResultCode(ResultInfo.ERRORCODE);
			msg.setStatus(false);
			msg.setMessage("短信发送失败");
			return msg;
		}
	}
	
	/**
	 * 前台根据openid获取用户信息
	 * create date 2016年6月2日
	 * @param openid
	 * @return
	 */
	@RequestMapping("/memberInfo")
	@ResponseBody
	public ResultMsg getMemberInfo(HttpServletRequest req,
			@RequestParam(value="openid",defaultValue= "", required=false)String openid){
		ResultMsg rm = new ResultMsg();
		Member member = null;
		if(StringUtils.isEmpty(openid)){
			try {
				member = WechatUtils.getUserBySession(req);
				if(member == null){
					rm.setMessage(ResultInfo.loginOutError);
					rm.setStatus(false);
					return rm;
				}
				member = memberService.getMemberByUserOpenId(member.getUserOpenid());
				if(member == null){ member = new Member();}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			member = memberService.getMemberByUserOpenId(openid);
		}
		
		rm.setStatus(true);
		rm.setResultCode(ResultInfo.SUCCESSCODE);
		rm.setMessage(ResultInfo.SUCCESSINFO);
		rm.setData(member);
		return rm;
	}
	
}
