
package com.ruoyi.common.redis.service;
import io.lettuce.core.api.sync.RedisCommands;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdGenerator {

    @Autowired
    private RedisCommands<String, String> redisCommands;
    private final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");

/**
     * 生成带日期前缀的唯一ID
     * @param businessType 业务类型
     * @return 格式为 YYYYMMDD_业务类型_序号 的唯一ID
     */

    public String generateUniqueId(String businessType) {
        String dateStr = LocalDate.now().format(dateFormatter);
        String key = "id_counter:" + businessType + ":" + dateStr;
        // 使用INCR命令原子性递增
        long sequence = redisCommands.incr(key);
        // 设置过期时间(24小时)
        if (sequence == 1) {
            redisCommands.expire(key, 86400);
        }
        return  businessType + dateStr + String.format("%06d", sequence);
    }


/**
     * 生成简单递增ID
     * @param key 计数器键名
     * @return 递增后的ID值
     */

    public long generateSimpleId(String key) {
        return redisCommands.incr(key);
    }
}

