package com.ruoyi.commonapi.aop;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.commonapi.enums.ResultCode;
import com.ruoyi.commonapi.aop.annotation.Verification;
import com.ruoyi.commonapi.entity.enums.VerificationEnums;
import com.ruoyi.commonapi.service.VerificationService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * 验证码验证拦截
 *
 * @author Chopper
 */
@Aspect
@Configuration
@Slf4j
public class VerificationInterceptor {

    @Resource
    private VerificationService verificationService;

    @Before("@annotation(com.ruoyi.commonapi.aop.annotation.Verification)")
    public void interceptor(JoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        Verification verificationAnnotation = method.getAnnotation(Verification.class);
        VerificationEnums verificationEnums = verificationAnnotation.type();
        String uuid = verificationAnnotation.uuid();
        boolean result = verificationService.check(uuid, verificationEnums);
        if (result) {
            return;
        }
        throw new ServiceException(ResultCode.VERIFICATION_ERROR.message());
    }
}