package com.bootdo.system.config;



import com.bootdo.common.constant.Constants;
import com.bootdo.common.token.Token;
import com.bootdo.common.token.TokenUtil;
import com.bootdo.common.utils.IPUtils;
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 {
            String tokenStr = request.getHeader(Constants.LOGIN_TOKEN_KEY);
            if(ObjectUtils.isEmpty(tokenStr)){
                tokenStr = request.getParameter(Constants.LOGIN_TOKEN_KEY);
            }
            if(ObjectUtils.isEmpty(tokenStr)){
                tokenStr = tokenUtil.createCurrTokenString();
                if(ObjectUtils.isEmpty(tokenStr)){
                    logger.error("preHandle =====================tokenStr is null=======================");
                }
            }
            if(!ObjectUtils.isEmpty(tokenStr)){
                Token token = tokenUtil.getToken(tokenStr);
                if (token == null) {
                    logger.error("preHandle =====================token is null=======================");
                } else {
                    String ip = null;
                    try {
                        ip = IPUtils.getIpAddr(request);
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                    tokenUtil.saveLoginUser(token.getPayload().getUsername(), 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 {

    }
}
