using Furion.Schedule;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WCS.Application;
/// <summary>
/// 日志清理任务
/// </summary>
[JobDetail("job_logClear", Description = "任务日志清理任务", GroupName = "default", Concurrent = false)]
[Daily(TriggerId = "trigger_logClear", Description = "任务日志清理任务")]
public class LogClearJob : IJob
{
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly ILogger _logger;

    public LogClearJob(IServiceScopeFactory scopeFactory, ILoggerFactory loggerFactory)
    {
        _scopeFactory = scopeFactory;
        _logger = loggerFactory.CreateLogger(CommonConst.SysLogCategoryName);
    }

    public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
    {
        using var serviceScope = _scopeFactory.CreateScope();
        
        var rep = serviceScope.ServiceProvider.GetRequiredService<SqlSugarRepository<WcsTask>>();
        DateTime threeMonthsAgo = DateTime.Now.AddMonths(-3);
        await rep.CopyNew().Context.Deleteable<WcsTask>().Where(s => s.CreateTime < threeMonthsAgo).ExecuteCommandAsync(stoppingToken);
        await rep.CopyNew().Context.Deleteable<WcsTaskMonitor>().Where(s => s.CreateTime < threeMonthsAgo).ExecuteCommandAsync(stoppingToken);
        threeMonthsAgo = DateTime.Now.AddMonths(-6);
        await rep.CopyNew().Context.Deleteable<WcsAlarmLog>().Where(s => s.CreateTime < threeMonthsAgo).ExecuteCommandAsync(stoppingToken);
    }
}