package com.bootdo.system.config;

import com.bootdo.common.token.Token;
import com.bootdo.common.token.TokenUtil;
import com.bootdo.common.utils.IPUtils;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.system.domain.UserDO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 描述:
 *
 * @author y
 * @create 2018-10-18 15:11
 */
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    private static final Logger logger = LogManager.getLogger(AuthorizationInterceptor.class);
    @Resource
    private TokenUtil tokenUtil;
    /**
     * 解析请求
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            UserDO userDO = ShiroUtils.getUser();
            if(!ObjectUtils.isEmpty(userDO)){
                String username = ShiroUtils.getUser().getUsername();
                if(ObjectUtils.isEmpty(username)){
                    return true;
                }
                String cacheToken =  tokenUtil.getLoginUser(username);
                if(ObjectUtils.isEmpty(cacheToken)) {
                    //logger.error("preHandle =====================cacheToken is null=======================A");
                    return true;
                }
                String tokenStr = cacheToken.split("_")[0];

                Token token = tokenUtil.getToken(tokenStr);
                if (ObjectUtils.isEmpty(token)) {
                    //logger.error("preHandle =====================token is null=======================B");
                    return true;
                }

                String ip = null;
                try {
                    ip = IPUtils.getIpAddr(request);
                } catch (Exception e){
                    e.printStackTrace();
                }
                tokenUtil.saveLoginUser(username, tokenStr, ip, System.currentTimeMillis(),"1");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
