using Backend.Models;
using Microsoft.Extensions.Logging;
using Quartz;
using Repository.BackendRepository.Interface;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace BackendWorkerService.Quartz.Jobs
{
    [DisallowConcurrentExecution]
    public class ExecutionBackgroundServicePlanJob : IJob
    {
        private readonly ILogger<ExecutionBackgroundServicePlanJob> logger;
        private readonly IBackgroundServiceRepository backgroundServiceRepository;

        public ExecutionBackgroundServicePlanJob(
            ILogger<ExecutionBackgroundServicePlanJob> logger,
            IBackgroundServiceRepository backgroundServiceRepository)
        {
            this.logger = logger;
            this.backgroundServiceRepository = backgroundServiceRepository;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                logger.LogInformation("【ExecutionBackgroundServicePlanJob】【任務開始】");

                // 找出當前在起始與結束時間所有計畫
                var DateTimeNow = DateTime.Now;
                var sPlanWhere = @"deleted = 0 
                                    AND 
                                        (
                                            @DateTimeNow Between start_time AND end_time
                                        OR  (end_time IS NULL AND @DateTimeNow > start_time)
                                        )
                                ";
                var backgroundServicePlans = await backgroundServiceRepository.GetAllAsync<BackgroundServicePlan>("background_service_plan", sPlanWhere, new { DateTimeNow = DateTimeNow.ToString("yyyy-MM-dd HH:mm:ss") });

                foreach (var plan in backgroundServicePlans)
                {
                    //logger.LogInformation("【ExecutionBackgroundServicePlanJob】【計畫編號:{0},計畫名稱:{1}】 - 開始生成下次任務項目", plan.Id, plan.Plane_name);
                    #region 紀錄最後生成任務的時間
                    try
                    {
                        var lastCreateTime = Convert.ToDateTime(plan.Last_create_time);
                        if (lastCreateTime == default(DateTime))
                        {
                            lastCreateTime = Convert.ToDateTime(plan.Start_time);
                        }

                        DateTime nextCreateTime; //下次待生成的時間
                        nextCreateTime = plan.Execution_type switch
                        {
                            (byte)ExecutionTypeEnum.Min => Convert.ToDateTime(lastCreateTime).AddMinutes(plan.Execution_time),
                            (byte)ExecutionTypeEnum.Hour => Convert.ToDateTime(lastCreateTime).AddHours(plan.Execution_time),
                            (byte)ExecutionTypeEnum.Day => Convert.ToDateTime(lastCreateTime).AddDays(plan.Execution_time),
                            (byte)ExecutionTypeEnum.Week => Convert.ToDateTime(lastCreateTime).AddDays(plan.Execution_time * 7),
                            (byte)ExecutionTypeEnum.Month => Convert.ToDateTime(lastCreateTime).AddMonths(plan.Execution_time),
                            _ => default(DateTime)
                        };

                        if (nextCreateTime != default(DateTime) && nextCreateTime < DateTimeNow)
                        {
                            Dictionary<string, object> servicePlanDic = new Dictionary<string, object>()
                            {
                                { "@last_create_time", nextCreateTime},
                                { "@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
                            };

                            await backgroundServiceRepository.UpdateOneByCustomTable(servicePlanDic, "background_service_plan", "id=" + plan.Id + "");

                            #region 建立任務
                            try
                            {
                                BackgroundServiceTask backgroundServiceTask = new BackgroundServiceTask()
                                {

                                };
                            }
                            catch(Exception exception)
                            {

                            }
                            #endregion 建立任務
                        }

                    }
                    catch (Exception exception)
                    {
                        //logger.LogError("【ExecutionBackgroundServicePlanJob】【計畫編號:{0},計畫名稱:{1}】 - 產生下次任務時間失敗", plan.Id, plan.Plane_name);
                        //logger.LogError("【ExecutionBackgroundServicePlanJob】【計畫編號:{0},計畫名稱:{1}】 - 產生下次任務時間失敗[Exception]- {2}", plan.Id, plan.Plane_name, exception.Message); ;
                    }
                    #endregion 紀錄最後該生成任務的時間

                }



                logger.LogInformation("【ExecutionBackgroundServicePlanJob】【任務完成】");
            }
            catch (Exception exception)
            {
                logger.LogError("【ExecutionBackgroundServicePlanJob】【任務失敗】");
                logger.LogError("【ExecutionBackgroundServicePlanJob】【任務失敗】[Exception]:{0}", exception.Message); ;
            }

        }
    }
}