package com.xinyilu.common.utils.codes;

import com.xinyilu.common.utils.DateUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @Description 编号工具类
 * @Author 纪寒
 * @Date 2022-08-02 18:13:55
 * @Version 1.0
 */
@Component
public class GenerateSystemCodeUtil {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 使用Redis生成唯一不重复的编码
     *
     * @param prefixCode 编号前缀
     * @return 编号信息
     */
    public String generateSystemCode(String prefixCode) {
        DecimalFormat df = new DecimalFormat("0000");
        String dateFmt = DateUtils.formatDateToString(LocalDate.now(), "yyyyMMdd");
        Long maxVal = redisTemplate.opsForValue().increment(prefixCode, 1);
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime end = DateUtils.end(LocalDate.now());
        redisTemplate.expire(prefixCode, DateUtils.differenceMinutes(now, end), TimeUnit.MINUTES);
        return dateFmt + df.format(maxVal);
    }
}
