package cn.pluss.platform.aop;

import cn.pluss.platform.annotation.Cert;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.userApp.UserAppService;
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.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 因为登录注册，以及忘记密码的时候，没有token，所以这三个操作的操作日志不通过注解实现
 * 保存APP操作日志，取请求头中的用户信息
 */
@Slf4j
@Aspect
@Component
public class CertAspect {

    @Autowired
    private UserAppService userAppService;

    // 定义切点
    // 记录后台接口的操作记录
    // 拦截Controller所在的包
    @Pointcut("(@within(cn.pluss.platform.annotation.Cert) && execution(* cn.pluss.platform.controller..*(..)))" +
            "|| (execution(* cn.pluss.platform.controller..*(..)) && @annotation(cn.pluss.platform.annotation.Cert))")
    public void executionService2() {
    }


    @Before(value = "executionService2()")
    public void after(JoinPoint point) {

        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Class<?> declaringType = signature.getDeclaringType();
        Cert classCertAnno = declaringType.getAnnotation(Cert.class);
        Cert methodCertAnno = method.getAnnotation(Cert.class);

        boolean classFlag = classCertAnno == null || classCertAnno.check();
        boolean annoExistFlag = classCertAnno != null || methodCertAnno != null;
        boolean methodFlag = methodCertAnno == null || methodCertAnno.check();

        if (classFlag && methodFlag && annoExistFlag) {
            final UserApp userApp = userAppService.queryUserAppByToken();

            if (!Objects.equals(3, userApp.getBankStatus())) {
                throw new MsgException("请先在APP中完成实名认证");
            }
        }

    }
}
