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.common.utils.StringUtils;
import com.ruoyi.web.modules.goods.constant.GoodsConstants;
import com.ruoyi.web.modules.mall.facade.IMallConfigFacade;

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

    @Autowired
    private IMallConfigFacade mallConfigFacade;

    public String nextSn()
    {
        String prefix = mallConfigFacade.getGoodsSnPrefix();
        if (StringUtils.isEmpty(prefix))
        {
            prefix = "SN";
        }
        String date = DateUtils.dateTimeNow("yyyyMMdd");
        String key = GoodsConstants.REDIS_SN_PREFIX + 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 prefix + date + String.format("%06d", seq);
    }
}
