package com.njcn.shiro.filter;


import com.njcn.enums.ProjectEnum;
import com.njcn.enums.SeparatorEnum;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.shiro.session.UserShiroSessionRepository;
import com.njcn.sso.pojo.user.User;
import com.njcn.utils.AppConfig;
import com.njcn.utils.PubUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;

/**
 *@author hongawen
 *@date 2018/3/21 19:48
 */
public class LoginFilter extends AccessControlFilter {

    private static UserShiroSessionRepository userShiroSessionRepository;

    public UserShiroSessionRepository getUserShiroSessionRepository() {
        return userShiroSessionRepository;
    }

    public static void setUserShiroSessionRepository(UserShiroSessionRepository userShiroSessionRepository) {
        LoginFilter.userShiroSessionRepository = userShiroSessionRepository;
    }

    @Autowired
    private UserLogDetailService userLogDetailService;

    @Autowired
    private AppConfig appConfig;

    /**
     * 表示是否允许访问
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request,
                                      ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        Subject subject = getSubject(request, response);
        Session session = userShiroSessionRepository.getSession(subject.getSession().getId());
        if (null == session) {
            return Boolean.FALSE;
        }
        User user = (User) subject.getPrincipal();
        String uri=httpServletRequest.getRequestURI();
        if(uri.contains("../")){
            return Boolean.FALSE;
        }
        String tokenValue;
        /*激活主会话start*/
        if (uri.startsWith(SeparatorEnum.URL.getSpearator()+ ProjectEnum.SSO.getItem())) {
            tokenValue = PubUtils.getSSOToken(httpServletRequest);
            if (StringUtils.isBlank(tokenValue)) {
                return Boolean.FALSE;
            }
        }else{
            Collection<Session> allSessions = userShiroSessionRepository.getAllSessions();
            for (Session session1:allSessions) {
                if(null!=session1&user!=null){
                    Object obj1 = session1.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
                    if(null != obj1){
                        SimplePrincipalCollection spc = (SimplePrincipalCollection)obj1;
                        obj1 = spc.getPrimaryPrincipal();
                        if(obj1 instanceof User){
                            User user1 = (User) obj1;
                            //当遍历的会话里的用户信息保存的项目名称是SSO，且遍历出的会话里的用户ID与当前会话里的用户ID是一致时则刷新生命周期
                            if(ProjectEnum.SSO.getItem().equalsIgnoreCase(user1.getItem())&user1.getUserIndex().equalsIgnoreCase(user.getUserIndex())){
                                userShiroSessionRepository.activeSession(session1);
                            }
                        }
                    }
                }
            }
        }
        /*激活主会话end*/
        if (subject.isAuthenticated()) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;

    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
            throws Exception {
        HttpServletResponse httpResponse = ((HttpServletResponse) response);
        HttpServletRequest httpRequest = (HttpServletRequest) request;
//        if(TokenManager.getToken()==null){
//            userLogDetailService.saveUserLog("未登录","未登录","用户非法访问","失败",appConfig.getSystemFlag(), PubUtils.getIpAddr(httpRequest), LogTypeEnum.SYSTEM.toString(),2);
//        }else{
//            userLogDetailService.saveUserLog(TokenManager.getToken().getUserIndex(), TokenManager.getToken().getLoginName(),"会话已过期","失败",appConfig.getSystemFlag(), PubUtils.getIpAddr(httpRequest), LogTypeEnum.SYSTEM.toString(),2);
//        }
        if (ShiroFilterUtils.isAjax(httpRequest)) {
            httpResponse.sendError(301);
            ShiroFilterUtils.out(response, "会话已过期");
        } else {
            //保存Request和Response 到登录后的链接
            boolean flag = appConfig.isOneContainer();
            String url;
            if (flag) {
                String baseUrl = httpRequest.getRequestURL().toString();
                if (baseUrl.contains(ProjectEnum.PQS9200.getItem())) {
                    url = baseUrl.substring(0, baseUrl.indexOf(ProjectEnum.PQS9200.getItem())) + ProjectEnum.PQS9200.getJudgeUrl();
                } else if (baseUrl.contains(ProjectEnum.PQS9000.getItem())) {
                    url = baseUrl.substring(0, baseUrl.indexOf(ProjectEnum.PQS9000.getItem())) + ProjectEnum.PQS9000.getJudgeUrl();
                } else if (baseUrl.contains(ProjectEnum.PQS9300.getItem())) {
                    url = baseUrl.substring(0, baseUrl.indexOf(ProjectEnum.PQS9300.getItem())) + ProjectEnum.PQS9300.getJudgeUrl();
                } else if (baseUrl.contains(ProjectEnum.PQS9900.getItem())) {
                    url = baseUrl.substring(0, baseUrl.indexOf(ProjectEnum.PQS9900.getItem())) + ProjectEnum.PQS9900.getJudgeUrl();
                } else {
                    url = ProjectEnum.SSO.getLoginUrl();
                }
            } else {
                url = appConfig.getSsoJudge();
            }
            WebUtils.issueRedirect(request, response, url);
        }
        return Boolean.FALSE;
    }


}
