package com.vctgo.common.mybatisplus.aop;

import com.vctgo.common.mybatisplus.domain.UserBaseInfo;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.system.api.model.LoginUser;
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.stereotype.Component;

import java.util.Date;

@Aspect
@Component
public class BaseInfoAop {

    @Pointcut("@annotation(com.vctgo.common.mybatisplus.aop.BaseInfoAnnotation))")
    public void setBaseInfo() {
    }

    @Around("setBaseInfo()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        BaseInfoAnnotation annotation = signature.getMethod().getAnnotation(BaseInfoAnnotation.class);
        OperateTypeEnum value = annotation.value();
        Object[] args = joinPoint.getArgs();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (args.length > 0) {
            UserBaseInfo arg = (UserBaseInfo) args[0];
            if (value == OperateTypeEnum.ADD) {
                arg.setCreateById(loginUser.getUserid());
                arg.setCreateBy(loginUser.getUsername());
                arg.setCreateTime(new Date());
            } else if (value == OperateTypeEnum.UPDATE) {
                arg.setUpdateById(loginUser.getUserid());
                arg.setUpdateBy(loginUser.getUsername());
                arg.setUpdateTime(new Date());
            } else if (value == OperateTypeEnum.DELETE) {
                arg.setUpdateById(loginUser.getUserid());
                arg.setUpdateBy(loginUser.getUsername());
                arg.setUpdateTime(new Date());
            }
        }
        return joinPoint.proceed(args);
    }

}