package org.springblade.modules.app.aspect;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import org.springblade.common.auth.UserContext;
import org.springblade.common.auth.UserContextUtil;
import org.springblade.common.auth.support.AuthErrorConstants;
import com.wn.common.validator.Validator;
import org.springblade.common.auth.support.AuthUtil;
import org.springblade.modules.app.common.dto.UserDTO;
import org.springblade.modules.app.utils.ErrorMsg;
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.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

/**
 * 登录拦截
 *
 * @author zhangK
 * @date 2022/01/16 14:19
 */
@Slf4j
@Aspect
@Component
public class ClientLoginAspect {

    /**
     * 获取user
     */
    @Around("@annotation(clientLogin)")
    public Object getUserDTO(ProceedingJoinPoint joinPoint, ClientLogin clientLogin) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        JWT jwt = JWTUtil.parseToken(token);
        Integer exp = (Integer) jwt.getPayload("exp");
        Long now = new Date().getTime() / 1000;

        Validator.isTrue(exp > now, ErrorMsg.NEW(AuthErrorConstants.NOT_LOGIN.getCode(), AuthErrorConstants.NOT_LOGIN.getMessage()));

        Object object = jwt.getPayload("userDto");
        UserDTO userDTO = JSON.parseObject(object.toString(), UserDTO.class);



        Validator.notNull(userDTO, ErrorMsg.NEW(AuthErrorConstants.NOT_LOGIN.getCode(), AuthErrorConstants.NOT_LOGIN.getMessage()));
        Object[] args = joinPoint.getArgs();
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                Object arg = args[i];
                if (arg != null && arg.getClass() == UserDTO.class) {
                    args[i] = userDTO;
                    break;
                }
            }
        }


        return joinPoint.proceed(args);
    }


}
