package com.dxhy.auth.client.interceptor;

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

import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.dxhy.auth.client.annotation.IgnoreUserToken;
import com.dxhy.auth.client.configuration.UserAuthConfig;
import com.dxhy.auth.client.feign.ServiceAuthFeign;
import com.dxhy.auth.client.jwt.UserAuthUtil;
import com.dxhy.common.jwt.IJWTInfo;
import com.dxhy.common.utils.BaseContextHandler;

/**
 * @author jiaohongyang
 * @date 2019年3月26日 下午5:51:59
 *
 */
public class UserAuthRestInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private UserAuthUtil userAuthUtil;

    @Resource
    private UserAuthConfig userAuthConfig;

    @Lazy
    @Resource
    private ServiceAuthFeign serviceAuthFeign;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response,
        @NotNull Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        // 配置该注解，说明不进行用户拦截
        IgnoreUserToken annotation = handlerMethod.getBeanType().getAnnotation(IgnoreUserToken.class);
        if (annotation == null) {
            annotation = handlerMethod.getMethodAnnotation(IgnoreUserToken.class);
        }
        if (annotation != null) {
            return super.preHandle(request, response, handler);
        }
        String token = request.getHeader(userAuthConfig.getTokenHeader());
        if (StringUtils.isEmpty(token)) {
            if (request.getCookies() != null) {
                for (Cookie cookie : request.getCookies()) {
                    if (cookie.getName().equals(userAuthConfig.getTokenHeader())) {
                        token = cookie.getValue();
                    }
                }
            }
        }
        IJWTInfo infoFromToken = userAuthUtil.getInfoFromToken(token);
        BaseContextHandler.setLoginname(infoFromToken.getLoginName());
        BaseContextHandler.setUsername(infoFromToken.getUserName());
        BaseContextHandler.setUserID(infoFromToken.getId());
        BaseContextHandler.setUserInfo(JSON.toJSONString(serviceAuthFeign.listUserInfo(infoFromToken.getLoginName())));
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response,
        @NotNull Object handler, Exception ex) throws Exception {
        BaseContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
