package com.ruoyi.web.modules.goods.support;

import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.web.modules.goods.constant.GoodsConstants;

/**
 * 商品编号生成：G + yyyyMMdd + 6 位序号
 */
@Component
public class GoodsSnGenerator
{
    @Autowired
    private RedisCache redisCache;

    public String nextSn()
    {
        String date = DateUtils.dateTimeNow("yyyyMMdd");
        String key = GoodsConstants.REDIS_SN_PREFIX + date;
        Long seq = redisCache.redisTemplate.opsForValue().increment(key);
        if (seq != null && seq.longValue() == 1L)
        {
            redisCache.expire(key, 2, TimeUnit.DAYS);
        }
        if (seq == null)
        {
            seq = 1L;
        }
        return "G" + date + String.format("%06d", seq);
    }
}
