package com.ssm.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.dgtis.sso.model.UserModel;
import com.dgtis.sso.utils.SSOHelper;
import com.ssm.model.system.SysRole;
import com.ssm.model.system.SysUser;
import com.ssm.service.system.SysRoleService;
import com.ssm.service.system.SysUserService;
import com.ssm.web.Const;

public class Util {
	/**
	 * 获取UserSession
	 * 先从session中取，若不存在，则从redis里取
	 * @return
	 */
	public static SysUser getUserSession(HttpServletRequest request){
		HttpSession httpSession = request.getSession();
		SysUser sysuser = (SysUser) httpSession.getAttribute(Const.USER_SESSION_KEY);
		if(sysuser != null){
			return sysuser;
		} else {
			//从redis里取
			UserModel model = SSOHelper.getUser(request);
			if(model != null){
				String loginId = model.getLoginName();
				ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(httpSession.getServletContext());
				SysUserService service = ac.getBean(SysUserService.class);
				sysuser = service.findByEmployeeno(loginId);
				if(sysuser != null){
					httpSession.setAttribute(Const.USER_SESSION_KEY, sysuser);
					SysRoleService sysRoleService = ac.getBean(SysRoleService.class);
					List<SysRole> roleList = sysRoleService.findUserRoleByUserId(sysuser.getUserid());
					httpSession.setAttribute(sysuser.getUserid().toString(), roleList);
					return sysuser;
				} else {
					return null;
				}
			} else {
				return null;
			}
		}
	}
	
	/**
	 * 返回json信息，调用此方法的方法需要设置成void
	 * 
	 * @param response
	 * @param jsonString
	 */
	public static void json(HttpServletResponse response, String jsonString) {
		escapeCache(response);
		/**
		 * 废弃的请求头信息
		 * response.setContentType("text/json; charset=utf-8");
		 * 部分情况下返回的内容中加入了<pre></pre>标签
		 * 所以直接使用text/html
		 */
		response.setContentType("text/html; charset=utf-8");
		try {
			PrintWriter writer = response.getWriter();
			writer.write(jsonString);
			writer.flush();
		} catch (IOException e) {e.printStackTrace();}
	}
	/**
	 * 设置返回信息无缓存
	 * 
	 * @param response
	 */
	public static void escapeCache(HttpServletResponse response) {
		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Prama", "no-cache");
	}
}
