package com.jy.framework.aspect;

import com.jy.framework.model.annotation.JyLog;
import com.jy.framework.model.event.OperateEvent;
import jakarta.annotation.Resource;
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.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * 操作日志记录切面
 */
@Slf4j
@Aspect
@Component
public class JyLogAspect {

    @Resource
    private ApplicationContext applicationContext;

    @Around("@annotation(jyLog)")
    public Object around(ProceedingJoinPoint point, JyLog jyLog) throws Throwable {

        Object result = null;
        Exception exception = null;

        long startTime = System.currentTimeMillis();
        try {
            result = point.proceed();
            return result;
        } catch (Exception e) {
            exception = e;
            throw e;
        } finally {
            long endTime = System.currentTimeMillis();

            OperateEvent operateEvent = new OperateEvent();
            operateEvent.setTitle(jyLog.title());
            operateEvent.setBusinessType(jyLog.businessType());
            operateEvent.setExcludeFields(jyLog.excludeFields());
            operateEvent.setResult(result);
            operateEvent.setException(exception);
            operateEvent.setCostTime(endTime - startTime);

            applicationContext.publishEvent(operateEvent);
        }

    }

}
