using Edu.CacheManager.Base;
using Edu.Common.Plugin;
using Edu.Module.Course;
using Edu.Module.Customer;
using Edu.Module.Duty;
using Edu.Module.EduTask;
using Edu.Module.Exam;
using System;
using System.IO;
using System.Threading;

namespace Edu.WebApi.Timers
{
    /// <summary>
    /// 定时任务
    /// </summary>
    public class TimerJobj
    {
        /// <summary>
        /// 值班处理对象
        /// </summary>
        private static readonly DutyPlanModule dutyPlanModule = AOP.AOPHelper.CreateAOPObject<DutyPlanModule>();

        /// <summary>
        /// 订单处理类对象
        /// </summary>
        private static readonly OrderModule orderModule = AOP.AOPHelper.CreateAOPObject<OrderModule>();

        /// <summary>
        /// 订单处理类对象
        /// </summary>
        private static readonly StopStudentClassModule stopStudentClassModule = AOP.AOPHelper.CreateAOPObject<StopStudentClassModule>();

        /// <summary>
        /// 转班订单处理类对象
        /// </summary>
        private static readonly OrderChangeModule orderChangeModule = new OrderChangeModule();

        /// <summary>
        /// 考试试卷处理类对象
        /// </summary>
        private static readonly PaperModule paperModule = new PaperModule();

        /// <summary>
        /// 使用redis第几号库
        /// </summary>
        static readonly int REDIS_DB3 = 3;

        static readonly RedisHelper redis = new RedisHelper(REDIS_DB3);

        /// <summary>
        /// 课程顾问部和市场部数据统计
        /// </summary>
        private static readonly MarketConsultantModule marketConsultantModule = new MarketConsultantModule();

        static System.Timers.Timer timer1;//计时器

        static System.Timers.Timer timer2;//定期处理未值班数据

        static System.Timers.Timer timer3;//定时处理订单生效日期

        static System.Timers.Timer timer4;//定时处理停课申请生效日期以及学员的上课状态

        static System.Timers.Timer changeOrder;//批量处理转班订单

        static System.Timers.Timer examTimer;//考卷定时处理

        static System.Timers.Timer finishGuest;//处理学生毕业状态

        static System.Timers.Timer marketTimer;//处理市场部和课程顾问部数据统计

        public static void RunTimer()
        {
            timer1 = new System.Timers.Timer
            {
                Interval = (1000 * 60) * (60 * 3) //3销售
            };
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(ClearFile);
            timer1.Enabled = true;

            timer2 = new System.Timers.Timer
            {
                Interval = (1000 * 60) * (60 * 1) //1小时执行一次
            };
            timer2.Elapsed += new System.Timers.ElapsedEventHandler(DealDuty);
            timer2.Enabled = true;

            timer3 = new System.Timers.Timer()
            {
                Interval = (1000 * 60) * (60 * 6) //6小时执行一次
            };
            timer3.Elapsed += new System.Timers.ElapsedEventHandler(DealOrderEffectStatus);
            timer3.Enabled = true;


            timer4 = new System.Timers.Timer()
            {
                Interval = (1000 * 60) * (1 * 10) //10分中执行一次
            };
            timer4.Elapsed += new System.Timers.ElapsedEventHandler(UpdateAuditThroughStudent);
            timer4.Enabled = true;

            changeOrder = new System.Timers.Timer()
            {
                Interval = (1000 * 60) * (1 * 20) //20分钟执行一次
            };
            changeOrder.Elapsed += new System.Timers.ElapsedEventHandler(BatchDealChangeOrder);
            changeOrder.Enabled = true;

            examTimer = new System.Timers.Timer()
            {
                Interval = (1000 * 60) * (1 * 30) //30分钟执行一次
            };
            examTimer.Elapsed += new System.Timers.ElapsedEventHandler(DealExamPublich);
            examTimer.Enabled = true;

            finishGuest = new System.Timers.Timer()
            {
                Interval = (1000 * 60) * (60 * 2) //2小时执行一次
            };
            finishGuest.Elapsed += new System.Timers.ElapsedEventHandler(DealGuestFinish);
            finishGuest.Enabled = true;

            marketTimer = new System.Timers.Timer()
            {
                Interval = (1000 * 60) * (1) //1小时检查一次
            };
            marketTimer.Elapsed += new System.Timers.ElapsedEventHandler(DealMarketConsultantData);
            marketTimer.Enabled = true;
        }

        public static void RunStop()
        {
            timer1.Enabled = false;
            timer2.Enabled = false;
            timer3.Enabled = false;
            timer4.Enabled = false;
            changeOrder.Enabled = false;
            examTimer.Enabled = false;
            finishGuest.Enabled = false;
            marketTimer.Enabled = false;
        }

        /// <summary>
        /// 防止重复提交
        /// </summary>
        private static int inTimer = 0;
        private static int inTimer2 = 0;
        private static int inTimer3 = 0;
        private static int inTimer4 = 0;
        private static int changeOrder_Timer = 0;
        private static int examPublish_Timer = 0;
        private static int guestfinish_Timer = 0;
        private static int marketconsultant_Timer = 0;


        private static string createMarkDataKey = "createMarkDataKey";
        /// <summary>
        /// 定时生成市场部和课程顾问部数据统计
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void DealMarketConsultantData(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Interlocked.Exchange(ref marketconsultant_Timer,1) == 0)
            {
                var currentDate = DateTime.Now;
                string cacheData = redis.Get(createMarkDataKey);
                if (string.IsNullOrEmpty(cacheData))
                {
                    redis.Set(createMarkDataKey, Common.ConvertHelper.FormatDate(currentDate));
                    cacheData = Common.ConvertHelper.FormatDate(currentDate);
                }
                if (!string.IsNullOrEmpty(cacheData) && cacheData != Common.ConvertHelper.FormatDate(currentDate))
                {
                    redis.Set(createMarkDataKey, Common.ConvertHelper.FormatDate(currentDate));
                    marketConsultantModule.CreateConsultantDataModule(currentDate);
                    marketConsultantModule.CreateMarketDataModule(currentDate);
                }
                Interlocked.Exchange(ref marketconsultant_Timer, 0);
            }
        }

        /// <summary>
        /// 处理学员毕业状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void DealGuestFinish(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Interlocked.Exchange(ref guestfinish_Timer, 1) == 0)
            {
                orderModule.DealGuestStateModule();
                Interlocked.Exchange(ref guestfinish_Timer, 0);
            }
        }

        /// <summary>
        /// 定时处理考卷过期数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void DealExamPublich(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Interlocked.Exchange(ref examPublish_Timer, 1) == 0)
            {
                paperModule.DealExamPublish();
                Interlocked.Exchange(ref examPublish_Timer, 0);
            }
        }


        /// <summary>
        /// 清理文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void ClearFile(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Interlocked.Exchange(ref inTimer, 1) == 0)
            {
                string rootBook = AppDomain.CurrentDomain.BaseDirectory;
                try
                {
                    DirectoryInfo dir = new DirectoryInfo(rootBook + "/upfile/temporary");
                    if (dir != null && dir.Exists)
                    {
                        DirectoryInfo[] dirArr = dir.GetDirectories();
                        foreach (DirectoryInfo item in dirArr)
                        {
                            if (item.CreationTime < DateTime.Now.AddDays(-1))
                                item.Delete(true);
                        }
                        foreach (FileInfo fi in dir.GetFiles())
                        {
                            if (fi.CreationTime < DateTime.Now.AddDays(-1))
                                fi.Delete();
                        }
                    }

                    #region 导出文件的
                    DirectoryInfo QRdir = new DirectoryInfo(rootBook + "/upfile/ExportFile");
                    if (QRdir != null && QRdir.Exists)
                    {
                        foreach (FileInfo fi in QRdir.GetFiles())
                        {
                            if (fi.CreationTime < DateTime.Now.AddDays(-1))
                                fi.Delete();
                        }
                    }
                    #endregion
                }
                catch
                {
                    LogHelper.Write("清理临时文件失败_ClearFile");
                }
                Interlocked.Exchange(ref inTimer, 0);
            }
        }

        /// <summary>
        /// 处理值班数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void DealDuty(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Interlocked.Exchange(ref inTimer2, 1) == 0)
            {
                dutyPlanModule.UpdateDutyModule();
                Interlocked.Exchange(ref inTimer2, 0);
            }
        }

        /// <summary>
        /// 定时处理订单生效日期
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void DealOrderEffectStatus(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Interlocked.Exchange(ref inTimer3, 1) == 0)
            {
                orderModule.DealOrderEffectStatusModule();
                Interlocked.Exchange(ref inTimer3, 0);
            }
        }


        /// <summary>
        /// 定时处理停课申请生效日期以及学员的上课状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void UpdateAuditThroughStudent(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Interlocked.Exchange(ref inTimer4, 1) == 0)
            {
                stopStudentClassModule.UpdateAuditThroughStudent();
                Interlocked.Exchange(ref inTimer4, 0);
            }
        }

        /// <summary>
        /// 批量处理转班订单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void BatchDealChangeOrder(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Interlocked.Exchange(ref changeOrder_Timer, 1) == 0)
            {
                orderChangeModule.GetChangeOrderListModule();
                Interlocked.Exchange(ref changeOrder_Timer, 0);
            }
        }
    }
}