using CoreCms.Net.Caching.AutoMate.RedisCache;
using CoreCms.Net.Configuration;
using CoreCms.Net.IServices;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.WeChat.Service.HttpClients;
using CoreCms.Net.WeChat.Service.Options;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoreCms.Net.Task
{
///
/// 定时重置用户余额,当用户刷新余额大于0的时候,每天会将用户余额数量设置为刷新余额数量。
///
public class RefreshUserBalanceJob
{
private readonly ISysTaskLogServices _taskLogServices;
private readonly ICoreCmsUserServices _userServices;
public RefreshUserBalanceJob(IRedisOperationRepository redisOperationRepository, ISysTaskLogServices taskLogServices, IOptions weChatOptions, IWeChatApiHttpClientFactory weChatApiHttpClientFactory, IWeChatAccessTokenServices weChatAccessTokenServices, ICoreCmsUserServices userServices)
{
_taskLogServices = taskLogServices;
_userServices = userServices;
}
public async System.Threading.Tasks.Task Execute()
{
try
{
// 查询所有需要刷新余额的用户(reBalance > 0)
var users = await _userServices.QueryListByClauseAsync(p => p.reBalance > 0);
if (users == null || users.Count == 0)
{
var emptyLog = new SysTaskLog
{
createTime = DateTime.Now,
isSuccess = true,
name = "刷新用户余额",
parameters = JsonConvert.SerializeObject(new { total = 0, updated = 0, skipped = 0 })
};
await _taskLogServices.InsertAsync(emptyLog);
return;
}
int total = users.Count;
int updated = 0;
int skipped = 0;
foreach (var u in users)
{
var delta = u.reBalance - u.balance;
if (delta == 0)
{
skipped++;
continue;
}
var res = await _userServices.UpdateBalance(u.id, delta);
if (res != null && res.code == 0)
{
updated++;
}
}
var log = new SysTaskLog
{
createTime = DateTime.Now,
isSuccess = true,
name = "刷新用户余额",
parameters = JsonConvert.SerializeObject(new { total, updated, skipped })
};
await _taskLogServices.InsertAsync(log);
}
catch (Exception ex)
{
//插入日志
var model = new SysTaskLog
{
createTime = DateTime.Now,
isSuccess = false,
name = "刷新用户余额",
parameters = JsonConvert.SerializeObject(ex)
};
await _taskLogServices.InsertAsync(model);
}
}
}
}