using Siger.CommonUtil;
using Siger.DataSchedule.Infrastructure.Extend;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.QmsRepository;
using Siger.Middlelayer.Redis;
using Siger.Middlelayer.Redis.RedisEntities;
using Siger.Middlelayer.Repository;
using System;
using System.Collections.Generic;
using System.Linq;

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

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

        public void AfterExecute(ScheduleContext context)
        {

        }

        public void Undo()
        {

        }
    }

    public class QmsCreateTraceTableJob
    {
        private static ApiQmsDbContext _context;
        private static ApiConfigDbContext _configContext;

        static QmsCreateTraceTableJob()
        {
            _context = new ApiQmsDbContext();
            _configContext = new ApiConfigDbContext();
        }

        private IEnumerable<DbNameConfig> GetDbNameConfigs()
        {
            var dbConfigs = new List<DbNameConfig>();
            RedisOpHelper opHelper = new RedisOpHelper();
            var configs = opHelper.HGetAll(RedisCache.DbNameConfigHash);
            foreach (var config in configs)
            {
                dbConfigs.Add(Middlelayer.Common.Helpers.JsonHelper.DeserializerJsonResult<DbNameConfig>(config.Value));
            }

            return dbConfigs.OrderBy(q => q.Cid);
        }

        public void Execute()
        {
            _context = new ApiQmsDbContext();
            _configContext = new ApiConfigDbContext();
            try
            {
                var dbConfigs = GetDbNameConfigs();
                foreach (var item in dbConfigs)
                {
                    try
                    {
                        if (item.Cid > 0 && item.Pid > 0)
                        {
                            //CreateTraceTable(item.Pid, item.Cid);
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.WriteLineError(e.Message);
                    }
                }
                _context.Dispose();
                _configContext.Dispose();
            }
            catch (Exception ex)
            {
                _context.Dispose();
                _configContext.Dispose();
                Logger.WriteLineError(ex.Message);
            }
        }
    }
}
