package com.fjs.scenic.interceptor;

import java.util.concurrent.TimeUnit;

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

import com.fjs.scenic.entity.system.Manage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.fjs.scenic.cyt.utils.JsonUtils;
import com.fjs.scenic.utils.Cons;
import com.fjs.scenic.utils.ReturnResult;

@Component
public class LoginInterceper implements HandlerInterceptor{
	
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		/*String token = request.getHeader(Cons.TOKEN.WECHAT);
		if(StringUtils.isBlank(token)){
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.getWriter().write(JsonUtils.marshalToString(ReturnResult.build(401, "未授权")));
			return false;
		}
		Integer userId = (Integer)redisTemplate.opsForValue().get(token);
		if(userId!=null){
			redisTemplate.expire(token, 60 * 60 * 2, TimeUnit.SECONDS);
			setCookie(response, token);
			return true;
		}else{
			redisTemplate.delete(token);
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.getWriter().write(JsonUtils.marshalToString(ReturnResult.build(401, "登录信息已过期")));
			return false;
		}*/
		Manage loginer = (Manage)request.getSession().getAttribute("loginer");
		if(null == loginer){
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.getWriter().write(JsonUtils.marshalToString(ReturnResult.build(401, "请登陆!")));
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	
    /**
     * 写入客服端cookie
     * @param response
     * @param openId
     */
	private void setCookie(HttpServletResponse response, String token){
        // 生成cookie
        Cookie cookie = new Cookie("USER_TOKEN", token);
        cookie.setPath("/");
        //(24*60*60); 一天
        cookie.setMaxAge(60 * 60 * 2);
        response.addCookie(cookie);
    }

}
