package com.iamberry.wechat.handles.wx;

import java.io.IOException;

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

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.iamberry.app.tool.des.MD5;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.face.member.MemberService;

/**
 * 分享链接跳转
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/wechat/sharePage")
public class ShareInfoWechatHandler {
	@Autowired
	private WechatUtils wechatUtils;
	
	@Autowired
	private MemberService memberService;
	/**
	 * 跳转到上传分享页面
	 */
	@RequestMapping("/upShare")
	public void toUpImgPage(HttpServletRequest req,HttpServletResponse res){
		
		try {
			req.getRequestDispatcher("/WEB-INF/views/wechat/up.html").forward(req,res);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 跳转到分享页面
	 * @param req
	 * @param res
	 */
	@RequestMapping("/toSharePage")
	public void toSharePage(HttpServletRequest req,HttpServletResponse res){
		try {
			Member member =  wechatUtils.getUserBySession(req);
			String shareOpenid = req.getParameter("openid");
			//openid 加密
			MD5 md5=new MD5("fenxiang");
			try {
				shareOpenid = md5.decrypt(shareOpenid);
			} catch (Exception e) {
				System.out.println("openid解密异常");
				e.printStackTrace();
			}
			String userType = req.getParameter("userType");	//分享人的类型 	1：会员	2：代理商
			if(StringUtils.isNotEmpty(shareOpenid) && StringUtils.isNotEmpty(userType)){
				boolean flag = memberService.buildChildUser(shareOpenid, member,Integer.parseInt(userType));
				if(flag){
					memberService.updateUserFlagByOpenId(member.getUserOpenid());		
				}
			}
			req.getRequestDispatcher("/WEB-INF/views/wechat/fenxiao_2wm_share.html").forward(req,res);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
	
	/**
	 * 分享页点击我要购买
	 * @param req
	 * @param res
	 */
	@RequestMapping("/toBuy")
	public void toBuyShare(HttpServletRequest req,HttpServletResponse res){
		try {
			req.getRequestDispatcher("/WEB-INF/views/wechat/fenxiao_2wm_join.html").forward(req,res);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
