package com.ruoyi.system.task;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.collection.CollectionUtils;
import com.ruoyi.ss.commandLog.domain.CommandLog;
import com.ruoyi.ss.commandLog.service.ICommandLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;

/**
 * @author wjh
 * 2025/1/4
 */
@Component
@Slf4j
public class CommandLogTask {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ICommandLogService commandLogService;

    // 从缓存中获取数据，并插入到数据库中
    public void recordRedis() {
        List<CommandLog> list = redisCache.getAndClearCacheList(CacheConstants.INSERT_COMMAND_LOG);
        if (CollectionUtils.isEmptyElement(list)) {
            log.info("暂无需要保存的数据");
            return;
        }

        // 插入数据库
        int insert = commandLogService.batchInsert(list);
        log.info("插入命令日志成功，共插入{}条数据", insert);
    }


    public void clearBeforeDays(Integer days) {
        commandLogService.clearBeforeDateLater(LocalDate.now().plusDays(-days));
    }
}
