package com.lutao.cloud.collect.aspect;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lutao.cloud.collect.dto.DataAddDTO;
import com.lutao.cloud.collect.service.CollectLogService;
import com.lutao.cloud.collect.utils.JsonUtilConvert;
import com.lutao.cloud.collect.vo.DataAddVO;
import com.lutao.entity.AppInfo;
import com.lutao.entity.CollectLog;
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.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
/**
 * 日志数据库切面
 *
 * @author yx
 * @date 2023/08/21
 */
@Aspect
@Component
@Slf4j
public class CollectInfoAspect {

    private final CollectLogService collectLogService;

    private final RedisTemplate redisTemplate;

    @Autowired
    public CollectInfoAspect(CollectLogService collectLogService,RedisTemplate redisTemplate){
        this.collectLogService = collectLogService;
        this.redisTemplate = redisTemplate;
    }

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

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

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

        DataAddVO dataAddVO = (DataAddVO) args[1];

        DataAddDTO dataAddDTO = (DataAddDTO)args[2];

        JsonNode jsonNode = JsonUtilConvert.convertJsonToArray(dataAddDTO.getData());

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

        //得到命令
        String command = dataAddVO.getCommand();

        //日志入库操作
        //查询当前库中是否存在
        //collectLogService.saveCollectLog(dataAddVO.getRequestId(), dataAddVO.getAppId(), command,jsonNode.size(),resource);

        log.info("生产日志入库-{}-已完成",resource);

        return result;
    }

    //@Around("@annotation(com.lutao.cloud.collect.annotate.CollectInfoLog)")
    public Object collectLogToDateBase (ProceedingJoinPoint joinPoint) throws Throwable {

        Object[] args = joinPoint.getArgs();
        Object result = joinPoint.proceed();
        DataAddDTO addDTO = (DataAddDTO) args[0];
        //表名
        String resource = addDTO.getResource();
        //命令
        String command = addDTO.getCommand();
        //appId
        AppInfo appInfo = getAppInfo(addDTO.getAppKey());
        String appId = null;
        if (appInfo != null){
             appId = appInfo.getId();
        }
        //requestId
        String requestId = addDTO.getRequestId();
        JsonNode jsonNode = JsonUtilConvert.convertJsonToArray(addDTO.getData());
        CollectLog collectLog = collectLogService.getOne(
                Wrappers.lambdaQuery(CollectLog.class)
                        .eq(CollectLog::getRequestId, requestId)
                        .eq(CollectLog::getAppId, appId)
                        .eq(CollectLog::getCommand, command)
                        .eq(CollectLog::getTableName, resource)
        );
        if (collectLog == null) {
            //不存在
            //collectLogService.saveCollectLog(requestId, appId, command, jsonNode.size(), resource);
        } else {
            collectLog.setCollectNumber(collectLog.getCollectNumber() == null ? 0 : collectLog.getCollectNumber() + jsonNode.size());
            collectLogService.updateById(collectLog);
        }

        log.info("生产日志入库-{}-已完成",resource);

        return result;
    }


    private AppInfo getAppInfo(String appKey) {
        AppInfo appInfo = new AppInfo();
        BoundHashOperations appinfoCache = redisTemplate.boundHashOps("appinfo");
        Object appInfoStr = appinfoCache.get(appKey);
        if (appInfo != null) {
            appInfo = (AppInfo) appInfoStr;
        } else {
            return null;
        }
        return appInfo;
    }



    /**
     * 将消息转换为实体
     *
     * @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);
        }
    }
}
