package cn.com.countrygarden.bi.main.interceptor;

import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.RoleService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


public class AccessTokenInterceptor extends HandlerInterceptorAdapter {

    protected final Logger logger = LoggerFactory.getLogger(AccessTokenInterceptor.class);

    @Autowired
    private TbSysUserService tbSysUserService;
    
    @Autowired
    private RoleService roleService;
    @Autowired
    protected AccessTokenService accessTokenService;
    /**
     * 前置检查
     *
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            String ip = request.getRemoteAddr();
            long startTime = System.currentTimeMillis();
            request.setAttribute("requestStartTime", startTime);
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取用户token
            Method method = handlerMethod.getMethod();
            logger.info("[" + ip + "] " + method.getDeclaringClass().getName() + "." + method.getName() + " request start");
        }
        String key=request.getParameter("key");
        if(key!=null){
            if("f275cbd642a946e8a509f38748d84771".equals(key)){
                return true;
            }
        }
        String accessToken = request.getParameter("AccessToken");
        //log.error("### AccessTokenInterceptor::preHandle validate accessToken: " + accessToken);
        //添加api授权检查
        String requestUrl =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+request.getServletPath();
        logger.info("当前访问链接============"+requestUrl);
        AccessToken userAccessToken = accessTokenService.findByToken(accessToken);
//        roleService.whiteUrlFiter(userAccessToken.getUserCode(), requestUrl);
//        return tbSysUserService.validateAccessToken(accessToken);
        return true;
    }

    /**
     * controller 处理完成
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        if (handler instanceof HandlerMethod) {
            String ip = request.getRemoteAddr();
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            long startTime = (Long) request.getAttribute("requestStartTime");
            long endTime = System.currentTimeMillis();
            long executeTime = endTime - startTime;

            logger.info("[" + ip + "] " + method.getDeclaringClass().getName() + "." + method.getName() + " " + executeTime + "ms");
        }
    }
}
