package com.qmth.teachcloud.common.util;

import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.StringJoiner;

/**
 * redis计数器工具类
 */
@Component
public class RedisCounterUtil {


    @Resource
    private RedissonClient redissonClient;

    /**
     * 计数器
     *
     * @param schoolId 学校ID
     * @param keys     keys
     * @param fillZero 补0个数
     */
    public String getCounter(Long schoolId, int fillZero, String... keys) {
        try {
            StringJoiner stringJoiner = new StringJoiner(":");
            stringJoiner.add("counter").add(String.valueOf(schoolId));
            for (String key : keys) {
                stringJoiner.add(key);
            }
            long count = redissonClient.getAtomicLong(stringJoiner.toString()).incrementAndGet();
            return String.format("%0" + fillZero + "d", count);
        } catch (NumberFormatException e) {
            throw new RuntimeException("生成考试编码失败");
        }
    }
}
