package com.sky.ioc.config;

import com.sky.ioc.constant.Constant;
import com.sky.ioc.tool.JwtUtil;
import com.sky.ioc.tool.RedisUtil;
import com.sky.ioc.tool.ReturnMsg;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Slf4j
@Component
@Aspect
public class LoginAspect {

    @Autowired
    private RedisUtil redisUtil;

    @Around("execution(* com.sky.ioc..*Controller.*(..))")
    public Object aroundLog(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        String clientId = request.getHeader("clientId");
        if (request.getServletPath().contains("login")||(StringUtils.hasText(clientId)&&clientId.equals("99"))) {
            return joinPoint.proceed(joinPoint.getArgs());
        }
        String token = request.getHeader("token");
        if (StringUtils.hasText(token)) {
            String username = JwtUtil.parseJWT(token) ;
            Object o = redisUtil.get("login:" + username);
            if (!Objects.isNull(o)) {
                return joinPoint.proceed(joinPoint.getArgs());
            }
        }
        return ReturnMsg.fail(Constant.MSG_CODE.LOGIN_TIMEOUT, "当前未登录");
    }
}
