using System.Text; using Dlhis.Constants; using Dlhis.Entity.Canteen.Entities.Voucher; using Kurisu.AspNetCore.Authentication.Abstractions; using Kurisu.AspNetCore.DataAccess.SqlSugar.Services; using Kurisu.AspNetCore.Utils.Extensions; namespace Dlhis.Canteen.Voucher.Services.Implements; public class VoucherQrCodeService : IVoucherQrCodeService { private readonly IDbContext _dbContext; private readonly ICurrentUser _currentUser; public VoucherQrCodeService(IDbContext dbContext, ICurrentUser currentUser) { _dbContext = dbContext; _currentUser = currentUser; } public async Task GetQrCodeAsync(string voucherNo, bool isNeedRefresh = false) { var userCode = _currentUser.GetUserClaim(UserClaimConstants.JinkoCode); if (!await _dbContext.Queryable().Where(x => x.VoucherNo == voucherNo && x.UserCode == userCode).AnyAsync()) { true.ThrowIfTrue("非法的消费券"); } var qrcodeInfo = await _dbContext.Queryable().SingleAsync(x => x.VoucherNo == voucherNo); if (qrcodeInfo == null) { qrcodeInfo = new VoucherQrCodeEntity { VoucherNo = voucherNo, QrCode = GenerateQrCode(voucherNo) }; await _dbContext.InsertAsync(qrcodeInfo); return qrcodeInfo.QrCode; } var now = DateTime.Now; if (qrcodeInfo.ModifiedTime.AddMinutes(1) >= now && !isNeedRefresh) { return qrcodeInfo.QrCode; } qrcodeInfo.QrCode = GenerateQrCode(voucherNo); await _dbContext.UpdateAsync(qrcodeInfo); return qrcodeInfo.QrCode; } /// /// qrCode生成 /// /// /// private static string GenerateQrCode(string voucherNo) { var ts = DateTimeOffset.Now.ToUnixTimeMilliseconds(); return QrCodeConstants.Birthday + voucherNo.ToArray().Select(x => { var b = Encoding.ASCII.GetBytes(x.ToString()); int i = b[0]; return Convert.ToString(i); }).Join(string.Empty) + ts; } }