using Siger.DataSchedule.Infrastructure.Extend;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.QmsRepository;
using Siger.Middlelayer.QmsRepository.Entities;
using Siger.Middlelayer.Redis;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Siger.Schedule.QmsModule
{
    public class QmsDataMigrationJobSchedule : IScheduleJob
    {
        QmsDataMigrationJob migrationJob;
        public void PreInit(ScheduleContext context)
        {
            Logger.RegisterLogEngine(Module.Qms);
            migrationJob = new QmsDataMigrationJob();
        }

        public void Execute(ScheduleContext context)
        {
            migrationJob.Execute();
        }

        public void AfterExecute(ScheduleContext context)
        {

        }

        public void Undo()
        {

        }
    }

    public class QmsDataMigrationJob
    {
        private static ApiQmsDbContext _context;

        static QmsDataMigrationJob()
        {
            _context = new ApiQmsDbContext();
        }

        public void Execute()
        {
            _context = new ApiQmsDbContext();
            try
            {
                var state = _context.siger_system_config.FirstOrDefault(t => t.status == (int)RowState.Valid &&
                            t.key == SystemConfigKey.QmsDataMigrationStatus);
                if ((state != null && state.value.ToInt() != (int)RowState.Valid) || state == null)
                {
                    _context.Dispose();
                    return;
                }
                var dbConfigs = RedisCache.Instance.GetDbNameConfigs();
                foreach (var item in dbConfigs)
                {
                    try
                    {

                    }
                    catch (Exception e)
                    {
                        Logger.WriteLineError(e.Message);
                    }
                }
                _context.Dispose();
            }
            catch (Exception ex)
            {
                _context.Dispose();
                Logger.WriteLineError(ex.Message);
            }
        }

        public void SyncMiddleDataToBigDataBase()
        {
            return;
        }
    }
}
