using FluentScheduler;
using Microsoft.Extensions.Logging;
using Performance.Infrastructure;
using Performance.Repository;
using Performance.Services;
using System;
using System.Linq;

namespace Performance.Api
{
    public class AutoSyncConfigJob : IJob
    {
        private readonly ILogger logger;
        private readonly PerforPerallotRepository perallotRepository;
        private readonly ConfigService configService;

        public AutoSyncConfigJob(
            ILogger<AutoSyncConfigJob> logger,
            PerforPerallotRepository perallotRepository,
            ConfigService configService
            )
        {
            this.logger = logger;
            this.perallotRepository = perallotRepository;
            this.configService = configService;
        }

        public void Execute()
        {
            try
            {
                logger.LogInformation("开始同步配置");
                var list = perallotRepository.GetEntities();
                if (list == null || !list.Any()) return;

                var hospitalIds = list.Select(t => t.HospitalId).Distinct().OrderBy(t => t);

                foreach (var hospitalId in hospitalIds)
                {
                    var allots = list.Where(w => w.HospitalId == hospitalId)?.OrderByDescending(t => t.Year).ThenByDescending(t => t.Month).ToList();
                    if (allots == null || !allots.Any()) continue;

                    while (allots != null && allots.Any(w => w.IsModifyConfig == 0))
                    {
                        var prevAllot = allots.FirstOrDefault(t => t.IsModifyConfig == 1);
                        if (prevAllot == null) continue;

                        var date = ConvertHelper.To<DateTime>($"{prevAllot.Year}-{prevAllot.Month}");
                        var needSyncData = allots.Where(w => ConvertHelper.To<DateTime>($"{w.Year}-{w.Month}") > date);
                        if (needSyncData != null && needSyncData.Any())
                        {
                            foreach (var item in needSyncData)
                                configService.CopyCommand(item, prevAllot.ID, true);
                        }

                        var noModify = allots.FirstOrDefault(w => ConvertHelper.To<DateTime>($"{w.Year}-{w.Month}") < date && w.IsModifyConfig == 0);
                        if (noModify != null)
                            date = ConvertHelper.To<DateTime>($"{noModify.Year}-{noModify.Month}");

                        allots = allots.Where(w => ConvertHelper.To<DateTime>($"{w.Year}-{w.Month}") <= date)?.ToList();
                    }
                }
                logger.LogInformation("同步配置结束");
            }
            catch (Exception ex)
            {
                logger.LogError($"同步配置发生异常：" + ex);
            }

        }
    }
}
