using System.Text; using Dlhis.Constants; using Dlhis.Entity.Basic.Entity; using Kurisu.AspNetCore.Authentication.Abstractions; using Kurisu.AspNetCore.DataAccess.SqlSugar.Services; using Kurisu.AspNetCore.Utils.Extensions; namespace Dlhis.Basic.Organization.Services.Implements; public class GainfoQrCodeService : IGainfoQrCodeService { private readonly IDbContext _dbContext; private readonly ICurrentUser _currentUser; private readonly IFactorySettingService _factorySettingService; public GainfoQrCodeService(IDbContext dbContext, ICurrentUser currentUser, IFactorySettingService factorySettingService) { _dbContext = dbContext; _currentUser = currentUser; _factorySettingService = factorySettingService; } public async Task GetMyQrCodeAsync(bool isNeedRefresh = false) { var jinkoCode = _currentUser.GetUserClaim(UserClaimConstants.JinkoCode); if (jinkoCode.IsEmpty()) { return null; } var factory = _currentUser.GetStringTenantId(); var now = DateTime.Now; var gainfoQrCode = await _dbContext.Queryable().SingleAsync(x => x.UserCode == jinkoCode); if (gainfoQrCode == null) { gainfoQrCode = new GainfoQrCodeEntity { UserCode = jinkoCode, QrCode = GenerateQrCode(jinkoCode) }; await _dbContext.InsertAsync(gainfoQrCode); return gainfoQrCode.QrCode; } var setting = await _factorySettingService.GetFactorySettingAsync(factory, false); if (gainfoQrCode.ModifiedTime.AddMinutes(setting.UserQrCodeExpiration!.Value) >= now && !isNeedRefresh) { return gainfoQrCode.QrCode; } gainfoQrCode.QrCode = GenerateQrCode(jinkoCode); await _dbContext.UpdateAsync(gainfoQrCode); return gainfoQrCode.QrCode; } //****************************************************************** help methods ********************************************************************************** private static string GenerateQrCode(string code) { var ts = DateTimeOffset.Now.ToUnixTimeMilliseconds(); var qrCode = string.Concat("consumer", ":", code, ":"); return QrCodeConstants.User + qrCode.ToArray().Select(x => { var b = Encoding.ASCII.GetBytes(x.ToString()); int i = b[0]; return Convert.ToString(i); }).Join(string.Empty) + ts; } }