using Common;
using JobService.Entity;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace JobService
{
    public class JobMange
    {
        private IScheduler _sched = null;
        /// <summary>
        /// 开始所有作业调度
        /// </summary>
        public void JobStart()
        {
            string configFile = AppDomain.CurrentDomain.BaseDirectory + "/config/SyncJobConfig.xml";
             List<JobConfig> configs = CommonHelper.ConvertXMLToObject<JobConfig>(configFile, "SCCSettings");
            //List<JobConfig> configs = new List<JobConfig>();
            var properties = new NameValueCollection
            {
                ["author"] = "kjh_rec缓存任务调度"
            };
            ISchedulerFactory sf = new StdSchedulerFactory(properties);
            _sched = sf.GetScheduler();

            List<Type> allInheirtFromIJob = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IJob))).ToList();
            foreach (JobConfig config in configs)
            {
                Type jobType = allInheirtFromIJob.FirstOrDefault(s => s.Name == config.JobName);
                if (jobType == null) continue;

                IJobDetail job = JobBuilder.Create(jobType)
                                    .WithIdentity(config.JobIdentityName, config.JobGroup)
                                    .Build();
                ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create()
                                    .WithIdentity(config.TriggerIdentityName, config.JobGroup)
                                    .WithCronSchedule(config.CronExpression)
                                    .Build();

                foreach (PropertyInfo property in typeof(JobConfig).GetProperties())
                {
                    job.JobDataMap.Put(property.Name, property.GetValue(config, null));
                }

                DateTimeOffset ft = _sched.ScheduleJob(job, trigger);
                Trace.WriteLine(ft.DateTime);
            }
            _sched.Start();
        }

        /// <summary>
        /// 停止所有作业调度
        /// </summary>
        public void JobStop()
        {
            if (_sched != null && _sched.IsStarted)
                _sched.Shutdown(true);
        }
    }
}