package com.iamberry.wechat.handles.member;

import java.io.IOException;
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 org.springframework.web.servlet.ModelAndView;

import org.apache.commons.lang.StringUtils;
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.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.qrcode.QrcodeResult;
import com.iamberry.wechat.face.drp.PlaceInfoService;
import com.iamberry.wechat.face.home.HomeService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.qrcode.QrcodeService;
import com.iamberry.wechat.face.qrcode.TemporaryQrcodeService;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.StaticInfo;
/**
 * 
 *		description: 
 * 	   		@author: 张应真
 *	    @createDate: 2016年4月21日
 */
@Controller
@RequestMapping("/wechat/member")
public class MemberHandler {
	
	@Autowired
	private MemberService memberService;
	// 将后台数据传输到前端
	//private Map<String, Object> maps = new HashMap<String, Object>();
	
	@Autowired
	private WechatUtils wechatUtils;
	@Autowired
	private PlaceInfoService placeInfoService;
	@Autowired
	private QrcodeService qrcodeService;
	@Autowired
	private HomeService homeService;
	@Autowired
	private TemporaryQrcodeService temporaryQrcodeService;
	/**
	 * 微代理查看下线
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value = "/porxyCheckUser", method = RequestMethod.POST)
	public ResultMsg porxyCheckUser(
			@RequestParam(defaultValue = "10", value = "pageSize", required = false) Integer pageSize,
			HttpServletRequest request) throws Exception {
		ResultMsg msg = new ResultMsg();
		
		Member member = wechatUtils.getUserBySession(request);
		if (member == null) {
			msg.setMessage(ResultInfo.loginOutError);
			return msg;
		}
		Page page = new Page();
		page.setPageSize(pageSize);
		page.setTotalRecord(member.getUserId());
		
		String beginNo=request.getParameter("beginNo");
		if(beginNo!=null){
			page.getParams().put("beginNo",beginNo);
		}
		String endNo=request.getParameter("endNo");
		if(endNo!=null){
			page.getParams().put("endNo",endNo);
		}
		
		Map<String, Object> map = memberService.getDownInfoAndBuyedCount(page);
		msg.setData(map);
		msg.setMessage(ResultInfo.SUCCESSINFO);
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setStatus(true);
		
		return msg;
	}
	
	/**
	 * 前台获取会员二维码接口
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value = "/shareProxyMemberUrl", method = RequestMethod.POST)
	public ResultMsg shareMemberUrl(
			@RequestParam(value = "share", required = false) String share,
			@RequestParam(value = "isDefault", required = false) String isDefault,
			HttpServletResponse response, 
			HttpServletRequest request) throws Exception {
		ResultMsg msg = new ResultMsg();
		
		if(share != null) {// 是否为分享,不为空表示分享
			Map<String, Object> map = new HashMap<String, Object>();
			
			if ("true".equals(isDefault)) { // 是否分享了默认的二维码,true表示分享默认的二维码
				map.put("shareUrl", NameUtils.WECHAT_MEMBER_SHARE_QRCODE + "?isDefault=true");
				map.put("qrcodeUrl", NameUtils.WECHAT_DEFAULT_QRCODE);
			} else {
				try {
					Member tempMember = memberService.getMemberByUserId(Integer.parseInt(StaticInfo.md5.decrypt(share)));
					if (tempMember != null && tempMember.getUserIdentity() == 2) {
						StringBuffer shareUrl = new StringBuffer(NameUtils.WECHAT_MEMBER_SHARE_QRCODE);
						shareUrl.append("?share=" + StaticInfo.md5.encrypt(tempMember.getUserId().toString()));
						//当前用户
						Member member = wechatUtils.getUserBySession(request);
						// 绑定用户关系
						boolean flag = memberService.buildChildUser(tempMember.getUserOpenid(), member,1);
						if(flag){
							memberService.updateUserFlagByOpenId(member.getUserOpenid());		
						}
						
						map.put("shareUrl", shareUrl.toString());
						QrcodeResult qr = temporaryQrcodeService.getTempQrcodeUrlByOpenid(tempMember.getUserOpenid());
						if(qr.isSuccess()){
							map.put("qrcodeUrl", qr.getQroceUrl());
						}else{
							map.put("qrcodeUrl", NameUtils.WECHAT_DEFAULT_QRCODE);
						}
						map.put("data", tempMember);
					} else {
						map.put("shareUrl", NameUtils.WECHAT_MEMBER_SHARE_QRCODE + "?isDefault=true");
						map.put("qrcodeUrl", NameUtils.WECHAT_DEFAULT_QRCODE);
					}
					
				} catch (Exception e) {
					e.printStackTrace();
					map.put("shareUrl", NameUtils.WECHAT_MEMBER_SHARE_QRCODE + "?isDefault=true");
					map.put("qrcodeUrl", NameUtils.WECHAT_DEFAULT_QRCODE);
				}
			}
			msg.setData(map);
			msg.setResultCode(ResultInfo.SUCCESSCODE);
			msg.setStatus(true);
			return msg;
		}
		
		Member member = wechatUtils.getUserBySession(request);
		if (member == null || member.getUserOpenid() == null) {
			msg.setMessage(ResultInfo.loginOutError);
			msg.setResultCode(ResultInfo.ERRORCODE);
			return msg;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		if (member.getUserIdentity() != null && member.getUserIdentity() == 2) { // 1:会员 ； 2:微代理
			if (member.getUserNickname() == null) {
				Member tempMember = memberService.getMemberByUserId(member.getUserId());
				member.setUserNickname(tempMember.getUserNickname());
				member.setUserHead(tempMember.getUserHead());
				map.put("data", tempMember);
				wechatUtils.saveUserToSession(member, request, response);
			} else {
				map.put("data", member);
			}
		} else {
			Member tempMember = memberService.getMemberByUserId(member.getUserId());
			//if (tempMember == null || tempMember.getUserIdentity() != 2) {
		  if (tempMember == null){
				msg.setStatus(false);
				msg.setResultCode(ResultInfo.ERRORCODE);
				msg.setMessage(ResultInfo.ERRORINFO);
				return msg;
			}
			map.put("data", tempMember);
			member.setUserNickname(tempMember.getUserNickname());
			member.setUserHead(tempMember.getUserHead());
			member.setUserIdentity(2); // 代理
			wechatUtils.saveUserToSession(member, request, response);
		}
		StringBuffer shareUrl = new StringBuffer(NameUtils.WECHAT_MEMBER_SHARE_QRCODE);
		shareUrl.append("?share=" + StaticInfo.md5.encrypt(member.getUserId().toString()));
		map.put("shareUrl", shareUrl.toString());
		
		QrcodeResult qr = temporaryQrcodeService.getTempQrcodeUrlByOpenid(member.getUserOpenid());
		if(qr.isSuccess()){
			map.put("qrcodeUrl", qr.getQroceUrl());
		}else{
			map.put("qrcodeUrl", NameUtils.WECHAT_DEFAULT_QRCODE);
		}
		
		msg.setData(map);
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setStatus(true);
		return msg;
	}
	

	/**
	 * 获取分销商二维码
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value = "/shareDrpUrl", method = RequestMethod.POST)
	public ResultMsg shareDrpUrl(
			@RequestParam(value = "share", required = false) String share, // 如果此参数存在，表示别人查看的二维码，否则表示自己查看二维码
			@RequestParam(value = "isDefault", required = false) String isDefault,
			HttpServletRequest request) throws Exception {
		ResultMsg msg = new ResultMsg();
		
		// 就算失败，也返回默认二维码
		Map<String, String> map = new HashMap<String, String>();
		map.put("shareUrl", NameUtils.WECHAT_MEMBER_PROXY_QRCODE + "?isDefault=true");
		map.put("qrcodeUrl", NameUtils.WECHAT_DEFAULT_QRCODE);
		msg.setData(map);
		
		Member member = wechatUtils.getUserBySession(request);
		if (member == null || member.getUserOpenid() == null) {
			msg.setMessage(ResultInfo.loginOutError);
			msg.setResultCode(ResultInfo.ERRORCODE);
			return msg;
		}
		
		// 是否默认
		if ("true".equals(isDefault)) {
			msg.setData(map);
			msg.setResultCode(ResultInfo.SUCCESSCODE);
			msg.setStatus(true);
			return msg;
		}
		
		// 判断是否查看分享连接
		if (share != null) {
			try {
				// 解析加密值
				Integer placeId = Integer.parseInt(StaticInfo.md5.decrypt(share));
				String qrcodeUrl = qrcodeService.selectQrcodeUrlByReplaceUser(placeId);
				if (qrcodeUrl == null) {
					msg.setMessage(ResultInfo.userNoDrpError);
					msg.setResultCode(ResultInfo.ERRORCODE);
					return msg;
				}
				// 拼装数据
				StringBuffer shareUrl = new StringBuffer(NameUtils.WECHAT_MEMBER_PROXY_QRCODE);
				shareUrl.append("?share=" + StaticInfo.md5.encrypt(placeId.toString()));
				map.put("shareUrl", shareUrl.toString());
				map.put("qrcodeUrl", qrcodeUrl);
				
				// 代理商管理元的信息
				Member tempMember = homeService.selectUserInfoByPlaceId(placeId);
				//绑定关系
				boolean flag = memberService.buildChildUser(tempMember.getUserOpenid(), member,2);
				if(flag){
					memberService.updateUserFlagByOpenId(member.getUserOpenid());		
				}
				if (tempMember == null) {
					msg.setMessage(ResultInfo.userNoDrpError);
					msg.setResultCode(ResultInfo.ERRORCODE);
					return msg;
				}
				map.put("userHeadImage", tempMember.getUserHead());
				map.put("userNickName", tempMember.getUserNickname());
				
				msg.setData(map);
				
				return msg;
			} catch (Exception e) {
				e.printStackTrace();
				msg.setMessage(ResultInfo.userNoDrpError);
				msg.setResultCode(ResultInfo.ERRORCODE);
				return msg;
			}
		}
		
		// 判断用户是否为分销商
		PlaceInfo placeInfo=placeInfoService.getPlaceInfoByOpenId(member.getUserOpenid());
		if(null == placeInfo){
			msg.setMessage(ResultInfo.userNoDrpError);
			msg.setResultCode(ResultInfo.ERRORCODE);
			return msg;
		}
		
		// 查询当前分销商的二维码
		String qrcodeUrl = qrcodeService.selectQrcodeUrlByReplaceUser(placeInfo.getId());
		if (qrcodeUrl == null) {
			msg.setMessage(ResultInfo.userNoDrpError);
			msg.setResultCode(ResultInfo.ERRORCODE);
			return msg;
		}
		

		// 代理商管理的信息
		Member tempMember = memberService.getMemberByUserId(member.getUserId());
		if (tempMember == null) {
			msg.setMessage(ResultInfo.userNoDrpError);
			msg.setResultCode(ResultInfo.ERRORCODE);
			return msg;
		}
		map.put("userHeadImage", tempMember.getUserHead());
		map.put("userNickName", tempMember.getUserNickname());

		StringBuffer shareUrl = new StringBuffer(NameUtils.WECHAT_MEMBER_PROXY_QRCODE);
		shareUrl.append("?share=" + StaticInfo.md5.encrypt(placeInfo.getId()+""));
		map.put("shareUrl", shareUrl.toString());
		map.put("qrcodeUrl", qrcodeUrl);
		msg.setData(map);
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setStatus(true);
		return msg;
	}
	
	/**
	 * 通过openid获取用户二维码
	 */
	@ResponseBody
	@RequestMapping("/getQrcode")
	public ResultMsg getQrcode(@RequestParam(value="openid",defaultValue= "", required=false)String openid){
		ResultMsg rm = new ResultMsg();
		if(StringUtils.isEmpty(openid)){
			rm.setStatus(false);
			rm.setResultCode(ResultInfo.ERRORCODE);
			rm.setMessage(ResultInfo.ERRORINFO);
		}
		PlaceInfo placeInfo = placeInfoService.getPlaceInfoByOpenId(openid);
		String qrcode = "";
		if(placeInfo == null){
			qrcode = qrcodeService.selectQrcodeUrlByReplaceUser(openid);
		}else{
			qrcode = qrcodeService.selectQrcodeUrlByReplaceUser(placeInfo.getId());
		}
		if(StringUtils.isNotEmpty(qrcode)){
			rm.setStatus(true);
			rm.setResultCode(ResultInfo.SUCCESSCODE);
			rm.setMessage(ResultInfo.SUCCESSINFO);
			rm.setData(qrcode);
		}else{
			rm.setStatus(false);
			rm.setResultCode(ResultInfo.ERRORCODE);
			rm.setMessage(ResultInfo.ERRORINFO);
		}
		return rm;
	}
	/**
	 * 查看二维码
	 * @param request
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping(value = "/showQrcode", method = RequestMethod.GET)
	public void showQrcode(
			HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher(NameUtils.WECHAT_SHOP_MEMGER_INDEX).forward(request, response);
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}
}
