package com.tuoheng.system.filter;


import com.alibaba.fastjson.JSONObject;
import com.tuoheng.system.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.*;

@Slf4j
public class KickoutSessionFilter extends AccessControlFilter {

    // 用户被踢出后重定向的地址
    private String kickoutUrl = "/api/";
    // 使用RedisCacheManager 存储的cache前缀名
    public static String ONLINE_USER = "online_user";
    // 踢出当前登录用户还是之前用户
    private boolean kickoutAfter = true;
    // 同一个账号最大同时在线人数
    private int maxSession = 1;
    // SessionManager session管理器
    private SessionManager sessionManager;
    // 缓存
    private Cache<String, LinkedList<Serializable>> cache;

    public void setCacheManager(CacheManager cacheManager) {
        this.cache = cacheManager.getCache(ONLINE_USER);
    }

    public void setSessionManager(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    public void setMaxSession(int maxSession) {
        this.maxSession = maxSession;
    }

    public void setKickoutUrl(String kickoutUrl) {
        this.kickoutUrl = kickoutUrl;
    }

    public void setKickoutBefore(boolean kickoutAfter) {
        this.kickoutAfter = kickoutAfter;
    }

    /**
     * 是否允许访问，true表示允许访问
     * @param servletRequest
     * @param servletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        return false;
    }

    /**
     * 访问拒绝时是否自己处理，return false表示已经自己处理，true 表示自己不处理，继续由下一个拦截器执行
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        //如果用户未登录，跳过此过程
        if(!subject.isAuthenticated() && !subject.isRemembered()) {
            return true;
        }
        // -1表示无人数限制
        if (maxSession == -1){
            return true;
        }

        // 获取当前登录的sessionId
        Session session = subject.getSession();
        Serializable sessionId = session.getId();

        // 获取当前登录用户信息
        User user = (User) subject.getPrincipal();
        String username = user.getUsername();

        // 读取当前用户的Redis缓存，没有就创建一个空队列
        LinkedList<Serializable> deque = cache.get(username);
        if(deque==null){
            deque = new LinkedList<>();
        }

        //如果队列里没有此sessionId，且用户没有被踢出；放入队列
        if(!deque.contains(sessionId) && session.getAttribute("kickout") == null) {
            //将sessionId存入队列
            deque.add(sessionId);
            //将用户的sessionId队列缓存
            cache.put(username, deque);
        }

        //如果队列里的sessionId数超出最大会话数，开始踢人
        while(deque.size() > maxSession) {
            // 保存待踢出用户的sessionId
            Serializable kickoutSessionId = null;
            //如果踢出后登录者，更新队列
            if(kickoutAfter) {
                kickoutSessionId = deque.removeFirst();
                cache.put(username, deque);
            } else {
                //否则踢出前者，更新队列
                kickoutSessionId = deque.removeLast();
                cache.put(username, deque);
            }
            // 对即将踢出的用户标记
            try {
                Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
                if(kickoutSession != null) {
                    //设置会话的kickout属性表示踢出
                    kickoutSession.setAttribute("kickout", true);
                }
            } catch (Exception e) {
                log.error("踢出用户异常！");
            }
        }

        //如果被踢出了，直接退出，重定向到踢出后的地址
        if (session.getAttribute("kickout")!=null && (Boolean)session.getAttribute("kickout")) {
            try {
                //退出登录
                subject.logout();
            } catch (Exception e) { //ignore
                log.error("用户退出异常！");
            }
            // 保存请求
            saveRequest(request);
            //若为Ajax请求
            //if ("XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))) {
                // 自定义ajax返回结果
                try {
                    response.setContentType("application/json; charset=utf-8");
                    response.setCharacterEncoding("UTF-8");
                    PrintWriter out = response.getWriter();
                    JSONObject result = new JSONObject();
                    result.put("msg", "登录过期!");
                    result.put("code", 401);
                    out.println(result);
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    log.error("未知异常，请联系管理员，或刷新重试！");
                }
            /*}else{
                //重定向到踢出地址
                WebUtils.issueRedirect(request, response,"/api"+kickoutUrl);
            }*/
            return false;
        }
        return true;
    }

}

