using System;
using System.Threading.Tasks;
using Wicture.DbRESTFul.Cache;
using Wicture.DbRESTFul.Infrastructure.Repository;

namespace JiaZhiQuan.Common {
    public static partial class RepositoryExtension {
        //仓库标志位数
        const int StorageBits = 2;
        //序列号识位数
        const int SequenceBits = 6;

        public static async Task<long> GoodsNoNextId(this DbRESTFulRepository repository, RedisCacheProvider redis) {
            var now = DateTime.Now;            
            var today = long.Parse($"{now:yyyyMMdd}");
            var _sequence = await redis.Increase(CacheKeys.GoodsNoSequence(now), now.AddDays(1));
            
            var maxSequence = (ulong)Math.Pow(10, SequenceBits);
            if (_sequence >= maxSequence) {
                //抛异常
                throw new Exception($"一天最多生成{maxSequence}个货号");
            }

            return long.Parse($"{today}{0:D2}{_sequence:D6}"); // 入仓顺序号，不足6位前;
        }
    }
}
