package cn.meowrain.aioj.backend.framework.log.aspect;

import cn.hutool.core.util.StrUtil;
import cn.meowrain.aioj.backend.framework.core.utils.SpringContextHolder;
import cn.meowrain.aioj.backend.framework.log.annotation.SysLog;
import cn.meowrain.aioj.backend.framework.log.enums.LogTypeEnum;
import cn.meowrain.aioj.backend.framework.log.event.SysLogEvent;
import cn.meowrain.aioj.backend.framework.log.event.SysLogEventSource;
import cn.meowrain.aioj.backend.framework.log.utils.SysLogUtils;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.expression.EvaluationContext;

@Aspect
@Slf4j
@RequiredArgsConstructor
public class SysLogAspect {

	/**
	 * 环绕通知方法，用于处理系统日志记录
	 * @param point 连接点对象
	 * @param sysLog 系统日志注解
	 * @return 目标方法执行结果
	 * @throws Throwable 目标方法执行可能抛出的异常
	 */
	@Around("@annotation(sysLog)")
	@SneakyThrows
	public Object around(ProceedingJoinPoint point, SysLog sysLog) {
		String strClassName = point.getTarget().getClass().getName();
		String strMethodName = point.getSignature().getName();
		log.debug("[类名]:{},[方法]:{}", strClassName, strMethodName);

		String value = sysLog.value();
		String expression = sysLog.expression();
		// 当前表达式存在 SPEL，会覆盖 value 的值
		if (StrUtil.isNotBlank(expression)) {
			// 解析SPEL
			MethodSignature signature = (MethodSignature) point.getSignature();
			EvaluationContext context = SysLogUtils.getContext(point.getArgs(), signature.getMethod());
			try {
				value = SysLogUtils.getValue(context, expression, String.class);
			}
			catch (Exception e) {
				// SPEL 表达式异常，获取 value 的值
				log.error("@SysLog 解析SPEL {} 异常", expression);
			}
		}

		SysLogEventSource logVo = SysLogUtils.getSysLog();
		logVo.setTitle(value);
		// 获取请求body参数
		if (StrUtil.isBlank(logVo.getParams())) {
			logVo.setBody(point.getArgs());
		}
		// 发送异步日志事件
		Long startTime = System.currentTimeMillis();
		Object obj;

		try {
			obj = point.proceed();
		}
		catch (Exception e) {
			logVo.setLogType(LogTypeEnum.ERROR.getType());
			logVo.setException(e.getMessage());
			throw e;
		}
		finally {
			Long endTime = System.currentTimeMillis();
			logVo.setTime(endTime - startTime);
			SpringContextHolder.publishEvent(new SysLogEvent(logVo));
		}

		return obj;
	}

}
