using FluentScheduler;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Performance.DtoModels;
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 IConfiguration _configuration;
        private readonly PerforPerallotRepository perallotRepository;
        private readonly ConfigService configService;

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

        public void Execute()
        {
            try
            {
                var @switch = _configuration.GetValue("Application:OpenAutoSyncConfig", false);
                logger.LogInformation($"同步配置开关：{@switch}");
                if (@switch)
                {
                    logger.LogInformation("开始同步配置");

                    //先查询perallot所有数据
                    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)
                    {
                        //按年月进行倒序查询allots
                        var allots = list.Where(w => w.HospitalId == hospitalId && string.IsNullOrEmpty(w.Path) && w.IsModifyConfig != 1)?.OrderByDescending(t => t.Year).ThenByDescending(t => t.Month).ToList();
                        if (allots == null || !allots.Any()) continue;

                        foreach (var item in allots)
                        {
                            configService.NewCopy(new CopyRequest() { AllotId = item.ID, Type = new[] { "personnels", "workItems", "drugTypeDisburses", "drugTypeFactors", "deptTypes", "agains", "accountings", "department" } });
                        }
                    }
                    logger.LogInformation("同步配置结束");
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"同步配置发生异常：" + ex);
            }

        }
    }
}
