package com.chuanxia.mcp.aop;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chuanxia.mcp.bean.model.SystemUser;
import com.chuanxia.mcp.exception.ResultException;
import com.chuanxia.mcp.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.HttpStatus;
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.lang.reflect.Method;
import java.util.Date;

/**
 * @author Administrator
 * @Aspect 声明是个切面的类（必要）
 * @Component 将该类交给spring容器管理（必要）
 * @Slf4j 日志输出
 */
@Aspect
@Component
@Slf4j
@RequiredArgsConstructor
public class CheckTokenAspect {

    private final UserService userService;

    /**
     * @Pointct 表示该方法可用于 com.tdkj.DataApi.annotation.CheckToken 这个注解
     * 还可以使用*号表示通配符
     */
    @Pointcut("@annotation(com.chuanxia.mcp.aop.Login)")
    public void pointcut() {

    }

    @Around("pointcut()")
    public Object checkTokenAroundAspect(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取请求头
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            //返回的错误信息将会直接返回给用户。 可看本文最后一张图
            throw new ResultException(600, "token不能为空");
        }
        LambdaQueryWrapper<SystemUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SystemUser::getToken, token);
        SystemUser one = userService.getOne(wrapper);
        if (one == null) {
            throw new ResultException(601, "token不存在");
        }
        Date tokenValidityTime = one.getTokenValidityTime();
        if (System.currentTimeMillis() > tokenValidityTime.getTime()) {
            throw new ResultException(602, "token已过期,需要重新登录");
        }
        // 打印出参 就只是输出
        return joinPoint.proceed();
    }

}
