package com.agri.quartz.task;

import com.agri.common.utils.spring.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Component("agriTask")
public class AgriTask {

    private static final Logger log = LoggerFactory.getLogger(AgriTask.class);

    public void clearInvalidCache() {
        log.info("=============【定时任务】开始执行Redis sub: 键清理任务=============");
        int deletedCount = 0;

        try {
            // 重点*****
            RedisTemplate<String, Object> redisTemplate = SpringUtils.getBean("redisTemplate");
            if (redisTemplate == null) {
                log.error("RedisTemplate 获取失败，清理任务终止");
                return;
            }

            ScanOptions scanOptions = ScanOptions.scanOptions()
                    .match("sub:*")
                    .count(1000)
                    .build();

            Cursor<byte[]> cursor = redisTemplate.executeWithStickyConnection(connection ->
                    connection.scan(scanOptions)
            );

            List<String> batchKeys = new ArrayList<>(1000);

            while (cursor != null && cursor.hasNext()) {
                byte[] keyBytes = cursor.next();
                String key = new String(keyBytes, StandardCharsets.UTF_8);
                batchKeys.add(key);

                if (batchKeys.size() >= 1000) {
                    deletedCount += batchKeys.size();
                    redisTemplate.delete(batchKeys);
                    log.info("批量删除 {} 个sub: 键", batchKeys.size());
                    batchKeys.clear();
                }
            }

            if (!batchKeys.isEmpty()) {
                deletedCount += batchKeys.size();
                redisTemplate.delete(batchKeys);
                log.info("批量删除剩余 {} 个sub: 键", batchKeys.size());
            }

            if (cursor != null) {
                try {
                    cursor.close();
                } catch (Exception e) {
                    log.error("关闭 Redis 游标失败", e);
                }
            }

            log.info("=============【定时任务】Redis sub: 键清理完成，总计删除 {} 个键=============", deletedCount);

        } catch (Exception e) {
            log.error("=============【定时任务】Redis sub: 键清理失败=============", e);
        }
    }
}