package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {
    private static final long BEGIN_TIMESTAMP = 1640995200L;
    private static final long COUNT_BITS = 32;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    // 拼接一个时间戳，再加一个根据输入的字符串自增长的32位id
    public long nextId(String prefix) {
        LocalDateTime now = LocalDateTime.now();
        long GapSecond = now.toEpochSecond(ZoneOffset.UTC)-BEGIN_TIMESTAMP;
        String date = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        long count = stringRedisTemplate.opsForValue().increment("icr:" + prefix+date);
        return GapSecond <<32 | count;
    }


//    public static void main(String[] args) {
//        LocalDateTime localDateTime = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
//        System.out.println(localDateTime.toEpochSecond(ZoneOffset.UTC)); //获取这个时间的秒数
//    }
}
