package com.iamberry.answer.web.utils;



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.AdminUtils;
import com.iamberry.wechat.core.entity.questionnaire.QuestionnaireAnswer;

/**
 * description ： 微信端用户工具类 
 * @author 何秀刚
 * create date：2016年2月25日
 */
@Component
public class AnswerUtils {
	
	@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(QuestionnaireAnswer object, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 一旦登陆成功，就改变sessionID的值，防止发生session fixation
		request.getSession().invalidate();
		HttpSession session = request.getSession(true);
		session.setAttribute("answer_login_user", object);
		System.out.println("存入session"+object);
		// 保存cookie,多项验证
		adminUtils.createCookie(response, "answer_login_openid", md5.encrypt(object.getAnswerId()+""));
	}
	
	/**
	 * 获取当前用户
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public QuestionnaireAnswer getUserBySession(HttpServletRequest request) throws Exception {
		QuestionnaireAnswer info = (QuestionnaireAnswer) request.getSession().getAttribute("answer_login_user");
		System.out.println("获取session"+info);
		if (info == null || info.getAnswerId() == null) {
			return null;
		}
		Cookie[] cookies = request.getCookies();//获取一个cookie数组
		if (cookies != null && cookies.length >= 1) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("answer_login_openid")) {
					if ((info.getAnswerId().toString()).equals(md5.decrypt(cookie.getValue()))) {
						return info;
					}
				}
			}
		}
		return null;
	}
	
}
