package com.lutao.cloud.consume.aspect;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lutao.cloud.collect.vo.DataAddVO;
import com.lutao.cloud.consume.service.ConsumerLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 日志数据库切面
 *
 * @author yx
 * @date 2023/08/21
 */
@Aspect
@Component
@Slf4j
public class LogToDatabaseAspect {

    private final ConsumerLogService collectLogService;

    @Autowired
    public LogToDatabaseAspect(ConsumerLogService collectLogService) {
        this.collectLogService = collectLogService;
    }

    //@Around("@annotation(com.lutao.cloud.consume.annotate.LogToDatabase)")
    public Object beforeLogToDatabase(ProceedingJoinPoint joinPoint) throws Throwable {

        //获取方法参数
        Object[] args = joinPoint.getArgs();

        // 执行原始方法
        Object result = joinPoint.proceed();

        String message = (String) args[0];

        DataAddVO dataAddVO = convertMessageToEntity(message);

        //需要操作的数据表
        String resource = dataAddVO.getResource();

        //得到命令
        String command = dataAddVO.getCommand();
        //日志入库操作
        collectLogService.saveConsumeLog(dataAddVO.getRequestId(), dataAddVO.getAppId(), command, 1, resource);
        log.info("消费日志入库-{}-已完成", resource);

        return result;
    }


    /**
     * 将消息转换为实体
     *
     * @param message 消息
     */
    public DataAddVO convertMessageToEntity(String message) {
        try {
            //创建ObjectMapper对象
            ObjectMapper objectMapper = new ObjectMapper();
            //将字符串转换为JSON对象
            JsonNode jsonNode = objectMapper.readTree(message);
            //将JSON对象转换为Java对象
            return objectMapper.treeToValue(jsonNode, DataAddVO.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
