package cn.iocoder.foodnexus.module.system.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ThreadLocalRandom;


/**
 * @author : yanghao
 * create at:  2024/11/29  11:41
 * @description: code生成
 */
@Component
public class GenCodeUtils {

    // 表示最大位数（10的三次方表示最大四位数）
    private static final Long MAX = Double.valueOf(Math.pow(10, 3)).longValue();
    @Autowired
    private RedisTemplate redisTemplate;

    public String createAmBatch(String type) {
        String monthDay = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String key = String.format("CODE:%s:%s", monthDay, type);
        Boolean flag = redisTemplate.hasKey(key);
        Long increment = redisTemplate.opsForValue().increment(key, 1);
        if (Boolean.FALSE.equals(flag)) {
            redisTemplate.expire(key, Duration.ofHours(24));
        }
        return this.getCode(type, monthDay, increment);
    }

    private String getCode(String type, String monthDay, Long increment) {
        if (increment < MAX) {
            return String.format("%s%s%s0%s", type, monthDay, random(), String.valueOf(increment + MAX).substring(1));
        }
        return String.format("%s%s%s%s", type, monthDay, random(), increment);
    }

    private int random() {
        return ThreadLocalRandom.current().nextInt(100, 1000);
    }

}
