package com.manage.interceptor;

import com.manage.encrypt.Base64;
import com.manage.encrypt.MD5;
import com.manage.service.cache.Cache;
import com.manage.service.cache.CacheManager;
import com.manage.service.Power_UserService;
import com.manage.util.Constant;
import com.manage.util.DateUtils;
import com.manage.vo.Power_UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Properties;

public class  LoginInterceptor implements HandlerInterceptor {
    @Value("${TOKEN_EXPIRE_TIME}")
    private long TOKEN_EXPIRE_TIME;
    @Autowired
    Power_UserService powerUserService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String ctx = request.getServletContext().getContextPath();
        String url = request.getRequestURI();
        if("/power/".equals(url)|| "/".equals(url)){
            request.getRequestDispatcher("/login").forward(request, response);
        }
        url = url.replace(ctx,"");
        String[] s = url.split("/");
        String parentUrl = "";
        if(!"/".equals(url)){
            parentUrl = "/"+s[1];
        }
        if (excludes(parentUrl, Constant.RELEASE_REQUEST)) {
            response.setHeader("Access-Control-Allow-Origin","*");
            return true;
        }else{
            String token = (String)request.getSession().getAttribute("token");
            if(StringUtils.isNoneBlank(token)){
                Cache cache = CacheManager.getCacheInfo(token);
                if (cache != null) {
                    if(!"/getSessionRemainingTime".equals(parentUrl)) {
                        //重新更新过期时间
                        Power_UserVo user = (Power_UserVo) cache.getValue();
                        CacheManager.putCache(token, new Cache(user,System.currentTimeMillis(),TOKEN_EXPIRE_TIME*1000));
                    }
                    return true;
                }
            }
            request.getRequestDispatcher("/login").forward(request, response);
            return false;
        }
    }

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

    }

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

    }

    private boolean excludes(String url,String key){
        Properties props = new Properties();
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try {
            props.load(loader.getResourceAsStream("config/config.properties"));
        }catch (Exception e){
            e.printStackTrace();
        }
        String value = props.getProperty(key);
        if(value != null && !"/".equals(value) && value.contains(",")){
            String[] values = value.split(",");
            PathMatcher matcher =  new AntPathMatcher();
            for(String v : values){
                if(matcher.match(v,url)) {
                    return true;
                }
            }
        }else {
            assert value != null;
            if(value.equals(url)){
                return true;
            }
        }
        return false;
    }
}
