package com.friday.distributor.aspect;

import com.alibaba.fastjson.JSON;
import com.friday.distributor.annotation.AuditInfo;
import com.friday.distributor.mapper.AuditMapper;
import com.friday.distributor.po.AuditPo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
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;


@Aspect
@Component
@Slf4j
public class AuditInfoAspect {
    @Autowired
    private AuditMapper auditMapper;

    @Pointcut("@annotation(com.friday.distributor.annotation.AuditInfo)")
    public void auditInfo() {}

    @Around("auditInfo()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        long time = System.currentTimeMillis() - startTime;
        AuditInfo methodInfo = this.getAuditAspect(proceedingJoinPoint);
        try {
            auditMapper.insertAudit(AuditPo.builder()
                    .method(proceedingJoinPoint.getSignature().getName())
                    .desc(methodInfo.desc())
                    .args(JSON.toJSONString(proceedingJoinPoint.getArgs()))
                    .response(JSON.toJSONString(result))
                    .during(String.valueOf(time))
                    .build());
        } catch (Exception e){
            log.error("审计信息落库失败", e);
        }
        return result;
    }

    @Before("auditInfo()")
    public void doBefore(JoinPoint joinPoint) {
        AuditInfo methodInfo = this.getAuditAspect(joinPoint);
        log.info("Method Description = {}", methodInfo.desc());
        log.info("Start Class Method {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        log.info("Request Args = {}", JSON.toJSONString(joinPoint.getArgs()));
    }

    private AuditInfo getAuditAspect(JoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        return methodSignature.getMethod().getAnnotation(AuditInfo.class);
    }

}