package com.jkcredit.invoice.annotation.annotationDes;

import cn.hutool.json.JSONUtil;
import com.jkcredit.invoice.annotation.LoginRequired;
import com.jkcredit.invoice.common.CommonConstants;
import com.jkcredit.invoice.model.entity.user.User;
import com.jkcredit.invoice.service.user.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * @description:
 * @author: sunzhaoning
 * @create: 2019-05-29 13:52
 * @version: V1.0
 **/
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 判断接口是否需要登录
        LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
        // 有 @LoginRequired 注解，需要认证
        if (methodAnnotation != null) {
            // 执行认证 从 http 请求头中取出 token
            String token = request.getHeader("token");
            if (token == null) {
                throw new RuntimeException("无token，请重新登录");
            }

            if (!redisTemplate.hasKey("user:token:" + token)) {
                throw new RuntimeException("token已过期，请重新登录");
            }
            User user = JSONUtil.toBean(redisTemplate.opsForValue().get(CommonConstants.TOKEN_KEY + token).toString(), User.class);
            if (user == null) {
                throw new RuntimeException("用户不存在，请重新登录");
            }
            request.setAttribute("currentUser", user);
            return true;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex) {
    }
}
