package com.iamberry.wechat.core.entity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.iamberry.app.tool.des.MD5;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.tools.NameUtils;

/**
 * description ： 微信端用户工具类
 * @author 何秀刚
 * create date：2016年2月25日
 */
@Component
public class WechatUtils {

	@Autowired
	private AdminUtils adminUtils;
	public void setAdminUtils(AdminUtils adminUtils) {
		this.adminUtils = adminUtils;
	}

	@Autowired
	private MD5 md5;
	public void setMd5(MD5 md5) {
		this.md5 = md5;
	}

	/**
	 * 将用户信息保存到session中，并做安全设置
	 * @param object
	 * @param request
	 * @throws Exception
	 */
	public void saveUserToSession(Member object, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 一旦登陆成功，就改变sessionID的值，防止发生session fixation
		request.getSession().invalidate();
		HttpSession session = request.getSession(true);
		session.setAttribute("wechat_login_user", object);
		// 保存cookie,多项验证
		adminUtils.createCookie(response, "wechat_login_openid", md5.encrypt(object.getUserId()+""));
	}

	/**
	 * 获取当前用户
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public Member getUserBySession(HttpServletRequest request) throws Exception {
		Member info = (Member) request.getSession().getAttribute("wechat_login_user");
		if (info == null || info.getUserId() == null) {
			return null;
		}
		Cookie[] cookies = request.getCookies();//获取一个cookie数组
		if (cookies != null && cookies.length >= 1) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("wechat_login_openid")) {
					if ((info.getUserId().toString()).equals(md5.decrypt(cookie.getValue()))) {
						return info;
					}
				}
			}
		}
		return null;
	}

	/**
	 * 微信授权获取openid
	 * @param tokenId
	 * @return
	 */
	public String getOpenIdFunction(String tokenId, boolean flag) {
		String urlTemp;
		if (flag) {
			urlTemp = NameUtils.WECHAT_BACK_URL + "?tokenId=" + tokenId;
		} else {
			urlTemp = tokenId;
		}
		String url;
		try {
			url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
					+ NameUtils.appId
					+ "&redirect_uri="
					+ URLEncoder.encode(urlTemp, "UTF-8")
					+ "&response_type=code&scope=snsapi_base&state=iamberry#wechat_redirect";
			return url;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static String getOpenIdFunction() {
		String redirect_url = NameUtils.WECHAT_BACK_URL;
		String url = null;
		try {
			url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
					+ NameUtils.appId
					+ "&redirect_uri="
					+ URLEncoder.encode(redirect_url, "UTF-8")
					+ "&response_type=code&scope=snsapi_base&state=iamberry#wechat_redirect";
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return url;
	}
}
