package com.chushang.system.component;

import com.chushang.common.core.constant.ServiceConstant;
import com.chushang.common.log.entity.SysLogEntity;
import com.chushang.system.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RQueue;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @auther: zhao
 * @date: 2024/4/12 17:09
 */
@Slf4j
@Component
public class LogRedisComponent {

    private final SysLogService logService;
    private final RedissonClient redissonClient;
    public LogRedisComponent(SysLogService logService, RedissonClient redissonClient){
        log.info("构造器执行");
        this.logService = logService;
        this.redissonClient = redissonClient;
    }
    private final ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
    @PostConstruct
    public void redisStart() {
        log.info("线程执行");
        Thread startLogQueueThread = startLogQueueThread();
        scheduledThreadPoolExecutor.scheduleWithFixedDelay(()->{
            Thread runLog = startLogQueueThread;
            try {
                boolean runLogThreadAlive = runLog.isAlive();
                if (!runLogThreadAlive) {
                    throw new NullPointerException("runLogThread alive false");
                }
            } catch (Exception ex) {
                System.out.println("logQueueThread 重启线程");
                runLog = startLogQueueThread();
            }
        }, 10 ,30, TimeUnit.SECONDS);
        log.info("RedisLogQueueCollect is starting!");
    }

    private Thread startLogQueueThread() {
        Thread logQueueThread = new Thread(this::logQueueThread);
        logQueueThread.start();
        return logQueueThread;
    }

    private void logQueueThread()
    {
        while (true) {
            if (log.isDebugEnabled()){
                log.debug("读取redis 数据");
            }
            try {
                try {
                    // 每1000 毫秒从 redis 获取一遍 入队数据
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    log.error("", e);
                    Thread.currentThread().interrupt();
                }
                if (!redissonClient.isShutdown()){
                    RQueue<SysLogEntity> list = redissonClient.getQueue(ServiceConstant.QUEUE_NAME);
                    List<SysLogEntity> reqList = list.poll(5000);
                    logService.saveBatch(reqList);
                }else {
                    if (log.isDebugEnabled()) log.debug(" Redisson is shutdown");
                }
            } catch (RuntimeException e) {
                log.error("logQueueThread error, 并重启线程！", e);
            }
        }
    }
}
