package com.multictrl.common.aspect;

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.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * Q20 service 调用日志切面
 * 在每个 Q20 service 方法执行前后打印开始/结束及耗时，异常时打印错误信息
 *
 * @author 938693313@qq.com
 * @since 1.0.0 2026/5/20
 */
@Slf4j
@Aspect
@Component
public class Q20ServiceLogAspect {

    @Pointcut("execution(public * com.multictrl.modules.business.q20.service.impl.*.*(..))")
    public void q20ServicePointcut() {
    }

    @Around("q20ServicePointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature sig = (MethodSignature) point.getSignature();
        String className = sig.getDeclaringType().getSimpleName();
        String methodName = sig.getName();
        String tag = className + "." + methodName;

        // 第一个参数通常是 deviceSn
        Object[] args = point.getArgs();
        String deviceSn = (args != null && args.length > 0 && args[0] instanceof String)
                ? (String) args[0] : "-";

        log.info("Q20 [{}] 开始 deviceSn={}", tag, deviceSn);
        long start = System.currentTimeMillis();
        try {
            Object result = point.proceed();
            log.info("Q20 [{}] 结束 deviceSn={} 耗时={}ms", tag, deviceSn, System.currentTimeMillis() - start);
            return result;
        } catch (Exception e) {
            log.error("Q20 [{}] 异常 deviceSn={} 耗时={}ms error={}",
                    tag, deviceSn, System.currentTimeMillis() - start, e.getMessage());
            throw e;
        }
    }
}
