package com.czg.log;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson2.JSON;
import com.czg.config.RedisCst;
import com.czg.service.RedisService;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * 从Redis队列中获取Log，保存到DB
 *
 * @author admin admin@cashier.com
 * @since 1.0.0
 */
@Slf4j
@Component
public class LogConsumer implements CommandLineRunner {
    @Resource
    private RedisService redisService;
    private final ScheduledExecutorService scheduledService = new ScheduledThreadPoolExecutor(1,
            new BasicThreadFactory.Builder().namingPattern("log-consumer-schedule-pool-%d").daemon(true).build());

    @Override
    public void run(String... args) {
        //上次任务结束后，等待10秒钟，再执行下次任务
        scheduledService.scheduleWithFixedDelay(() -> {
            try {
                receiveQueue();
            } catch (Exception e) {
                log.error("LogConsumer Error：" + ExceptionUtil.stacktraceToString(e));
            }
        }, 1, 10, TimeUnit.SECONDS);
    }

    private void receiveQueue() {
        String key = RedisCst.SYS_LOG_KEY;
        //每次插入100条
        int count = 100;
        for (int i = 0; i < count; i++) {
            String log = (String) redisService.rightPop(key);
            if (log == null) {
                return;
            }

            // 操作日志入库
            Row row = JSON.parseObject(log, Row.class);
            Db.insert("operation_log",row);
        }
    }

}