using System;
using System.Text;
using Newtonsoft.Json;
using System.IO;
using Quartz;
using Quartz.Impl;
using System.Collections.Specialized;
using System.Threading.Tasks;
using Edu.Module.Course;
using Edu.Module.OKR;
using System.Linq;
using System.Collections.Generic;
using Edu.Module.Finance;

namespace Edu.Education.Helper
{

    /// <summary>
    /// 定时器
    /// </summary>
    public class QuarzHelper
    {
        /// <summary>
        /// 定时执行教师绩效生成
        /// </summary>
        /// <returns></returns>
        public async Task TeachingPerfTimer()
        {
            string cronExpression = "0 0 1 * * ?"; //每天凌晨1点
            NameValueCollection props = new NameValueCollection
            {
                { "quartz.serializer.type", "binary" }
            };
            StdSchedulerFactory factory = new StdSchedulerFactory(props);
            IScheduler scheduler = await factory.GetScheduler();
            await scheduler.Start();

            IJobDetail job = JobBuilder.Create<CreateTeachingPerf>()
                .WithIdentity("job1", "group1")
                .Build();
            //ITrigger trigger = TriggerBuilder.Create()
            //    .WithIdentity("trigger1", "group1")
            //    .StartNow()
            //    .WithSimpleSchedule(x => x
            //        .WithIntervalInHours(2)
            //        .RepeatForever())
            //    .Build();
            ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create()
                .WithIdentity("trigger1", "group1")
                .WithCronSchedule(cronExpression)
                .Build();

            await scheduler.ScheduleJob(job, trigger);
        }

        /// <summary>
        /// 定时执行OKR周期生成
        /// </summary>
        /// <returns></returns>
        public async Task OKRPeriodTimer()
        {
            string cronExpression = "0 0 1 * * ?"; //每天凌晨1点
            NameValueCollection props = new NameValueCollection
            {
                { "quartz.serializer.type", "binary" }
            };
            StdSchedulerFactory factory = new StdSchedulerFactory(props);
            IScheduler scheduler = await factory.GetScheduler();
            await scheduler.Start();

            IJobDetail job = JobBuilder.Create<CreateOKRPeriod>()
                .WithIdentity("job2", "group2")
                .Build();
            //ITrigger trigger = TriggerBuilder.Create()
            //    .WithIdentity("trigger2", "group2")
            //    .StartNow()
            //    .WithSimpleSchedule(x => x
            //        .WithIntervalInHours(2)
            //        .RepeatForever())
            //    .Build();
            ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create()
                .WithIdentity("trigger2", "group2")
                .WithCronSchedule(cronExpression)
                .Build();

            await scheduler.ScheduleJob(job, trigger);
        }

        /// <summary>
        /// 定时执行OKR规则
        /// </summary>
        /// <returns></returns>
        public async Task OKRPeriodRuleTimer()
        {
            NameValueCollection props = new NameValueCollection
            {
                { "quartz.serializer.type", "binary" }
            };
            StdSchedulerFactory factory = new StdSchedulerFactory(props);
            IScheduler scheduler = await factory.GetScheduler();
            await scheduler.Start();

            IJobDetail job = JobBuilder.Create<CreateOKRPeriodRule>()
                .WithIdentity("job3", "group3")
                .Build();
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("trigger3", "group3")
                .StartNow()
                .WithSimpleSchedule(x => x
                    .WithIntervalInHours(1)
                    .RepeatForever())
                .Build();

            await scheduler.ScheduleJob(job, trigger);
        }

        /// <summary>
        /// 定时执行营收报表
        /// </summary>
        /// <returns></returns>
        public async Task RevenueReportTimer()
        {
            string CronExpression2 = "0 10 8,12,18,22 * * ?";//每天8，12，19，22点触发
            NameValueCollection props = new NameValueCollection
            {
                { "quartz.serializer.type", "binary" }
            };
            StdSchedulerFactory factory = new StdSchedulerFactory(props);
            IScheduler scheduler = await factory.GetScheduler();
            await scheduler.Start();

            IJobDetail job = JobBuilder.Create<CreateRevenueReport>()
                .WithIdentity("job4", "group4")
                .Build();
            //ITrigger trigger = TriggerBuilder.Create()
            //    .WithIdentity("trigger4", "group4")
            //    .StartNow()
            //    .WithSimpleSchedule(x => x
            //        .WithIntervalInHours(1)
            //        .RepeatForever())
            //    .Build();
            ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create()
                .WithIdentity("trigger4", "group4")
                .WithCronSchedule(CronExpression2)
                .Build();

            await scheduler.ScheduleJob(job, trigger);
        }
    }

    /// <summary>
    /// 教师绩效生成
    /// </summary>
    public class CreateTeachingPerf : IJob
    {
        /// <summary>
        /// 这里是作业调度每次定时执行方法
        /// </summary>
        /// <param name="context"></param>
        public Task Execute(IJobExecutionContext context)
        {
            try
            {
                LogHelper.Write("教师绩效生成");
                TeachingRewardsModule teachingRewardsModule = new TeachingRewardsModule();
                var glist = teachingRewardsModule.GetGroupList();
                foreach (var item in glist)
                {
                    //查询该集团下 所有的班级
                    var clist = teachingRewardsModule.GetTeachingPerfClassList(item.GId);
                    foreach (var qitem in clist)
                    {
                        try
                        {
                            LogHelper.Write("ClassId：" + qitem.ClassId);
                            string msg = teachingRewardsModule.SetTeachingPerfCreate(0, qitem);
                            if (msg != "")
                            {
                                LogHelper.Write("CreateTeachingPerf【" + qitem.ClassId + "】：" + msg);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Write(ex, "CreateTeachingPerf【" + qitem.ClassId + "】");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "CreateTeachingPerf");
            }
            return null;
        }
    }

    /// <summary>
    /// 周期生成
    /// </summary>
    public class CreateOKRPeriod : IJob
    {
        /// <summary>
        /// 这里是作业调度每次定时执行方法
        /// </summary>
        /// <param name="context"></param>
        public Task Execute(IJobExecutionContext context)
        {
            try
            {
                LogHelper.Write("周期生成....");
                OKRPeriodModule oKRPeriodModule = new OKRPeriodModule();
                var clist = oKRPeriodModule.GetOKRPeriodConfigList();
                foreach (var dmodel in clist)
                {
                    //查询改配置下当前周期
                    var list = oKRPeriodModule.GetCurrentPeriodList(dmodel.Group_Id);
                    if (list.Any()) {
                        var model = list.FirstOrDefault();
                        //看是否已到可生成下周期时间
                        if (dmodel.BeforeType == 1)
                        {
                            //天
                            var ds = model.EndDate - DateTime.Now;
                            if (ds.TotalDays < dmodel.BeforeNum)
                            {
                                dmodel.EndDate = model.EndDate;
                                //生成下一个周期
                                oKRPeriodModule.CreatePeriodNext(dmodel, true);
                            }
                        }
                        else
                        {
                            //月
                            var ds = DateTime.Now.AddMonths(dmodel.BeforeNum);
                            if (ds > model.EndDate)
                            {
                                dmodel.EndDate = model.EndDate;
                                //生成下一个周期
                                oKRPeriodModule.CreatePeriodNext(dmodel, true);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "CreateOKRPeriod");
            }

            try
            {
                LogHelper.Write("开始提醒....");
                //OKRPeriodModule oKRPeriodModule = new OKRPeriodModule();
                //oKRPeriodModule.SendOKRRemid();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SendOKRRemid");
            }
            return null;
        }
    }

    /// <summary>
    /// 规则更新进度
    /// </summary>
    public class CreateOKRPeriodRule : IJob
    {
        /// <summary>
        /// 这里是作业调度每次定时执行方法
        /// </summary>
        /// <param name="context"></param>
        public Task Execute(IJobExecutionContext context)
        {
            try
            {
                LogHelper.Write("开始执行规则适配....");
                OKRPeriodModule oKRPeriodModule = new OKRPeriodModule();
                var clist = oKRPeriodModule.GetOKRKeyResultList(new Model.ViewModel.OKR.RB_OKR_KeyResult_ViewModel() { IsUseRule = 1 });
                foreach (var item in clist) {
                    oKRPeriodModule.UpdateOKRKeyresultRuleProgress(item);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "CreateOKRPeriodRule");
            }
            return null;
        }
    }

    /// <summary>
    /// 更新营收报表
    /// </summary>
    public class CreateRevenueReport : IJob
    {
        /// <summary>
        /// 这里是作业调度每次定时执行方法
        /// </summary>
        /// <param name="context"></param>
        public Task Execute(IJobExecutionContext context)
        {
            try
            {
                Console.WriteLine("开始执行营收报表....");
                FinanceModule financeModule = new FinanceModule();
                financeModule.SetEduRevenueReport(100000, "2020-01-01", false);
                Console.WriteLine("结束执行营收报表....");
                Console.WriteLine("开始执行简易报表....");
                financeModule.InsertBatchSimple(100000, 2020);
                financeModule.InsertBatchSimple(100000, 2021);
                Console.WriteLine("结束执行简易报表....");
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "CreateRevenueReport");
            }
            return null;
        }
    }
}
