using System;
using System.Linq;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.KpiRespository.Entities;
using Siger.Middlelayer.KpiRespository;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Redis;
using Siger.Middlelayer.Share.ModuleEnum;
using Siger.Middlelayer.Utility.Helpers;
using Siger.DataSchedule.Infrastructure.Extend;

namespace Siger.Schedule.KpiModule
{
    public class KpiTasksJobSchedule : IScheduleJob
    {
        KpiTasksJob andonHelper;
        public void PreInit(ScheduleContext context)
        {
            Logger.RegisterLogEngine(Module.Kpi);
            andonHelper = new KpiTasksJob();
        }
        public void Execute(ScheduleContext context)
        {
            andonHelper.Execute();
        }


        public void AfterExecute(ScheduleContext context)
        {

        }


        public void Undo()
        {

        }
    }
    public class KpiTasksJob
    {
        private static readonly ApiKpiDbContext _context;

        static KpiTasksJob()
        {
            _context = new ApiKpiDbContext();
        }
        /// <summary>
        /// 
        /// </summary>
        public void Execute()
        {
            //var date = System.DateTime.Now;
            ////休息日 不推送
            //if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
            //    return;

            var dbConfigs = RedisCache.Instance.GetDbNameConfigs();
            foreach (var dbNameConfig in dbConfigs)
            {
                if (string.IsNullOrWhiteSpace(dbNameConfig.RedisDbName))
                {
                    Logger.WriteLineError($"KpiTasksJob DbNameConfig setting error, can not find redisdbname by cid:{dbNameConfig.Cid}, pid:{dbNameConfig.Pid}.");
                    continue;
                }
                TaskBuiding(dbNameConfig.Pid);
            }
        }
        /// <summary>
        /// 生产KPI 任务列表
        /// </summary>
        /// <param name="projectId"></param>
        private void TaskBuiding(int projectId)
        {
            try
            {
                var items = _context.siger_project_kpi_item.Where(f => f.projectId == projectId && f.status == (int)RowState.Valid);
                if (items.Any())
                {
                    foreach (var it in items)
                    {
                        CreateItemKpilist(it);
                    }

                }
            }catch(Exception ex)
            {
                Logger.WriteLineError(ex.ToString());
            }
        }

        void CreateItemKpilist(siger_project_kpi_item obj)
        {
            var strDate = DateTime.Now.ToString("yyyy-MM-dd");
            DateTime.TryParse(strDate, out DateTime cDate);
            var cycleText = string.Empty;
            switch (obj.KpiCycle)
            {
                case KpiCycleEnum.Year:
                    {
                        cycleText = cDate.Year.ToString();
                        if (_context.siger_project_kpi_tasklist.Where(f => f.projectId == obj.projectId && f.ItemId == obj.id && f.cycle==cycleText).Count() > 0)
                            return;
                        break;
                    }
                case KpiCycleEnum.Quarter:
                    {
                        var querter = DateTimeHelper.GetQuarterByMonth(cDate.Month);
                        cycleText = $"{cDate.Year.ToString()}Q{querter}";
                        if (_context.siger_project_kpi_tasklist.Where(f => f.projectId == obj.projectId && f.ItemId == obj.id && f.cycle == cycleText).Count() > 0)
                            return;
                        break;
                    }
                case KpiCycleEnum.Month:
                    {
                        cycleText = $"{cDate.Year.ToString()}-{cDate.Month.ToString()}";
                        if (_context.siger_project_kpi_tasklist.Where(f => f.projectId == obj.projectId && f.ItemId == obj.id && f.cycle == cycleText).Count() > 0)
                            return;
                        break;
                    }
                case KpiCycleEnum.Week:
                    {
                        var weekofYear = DateTimeHelper.GetWeekOfYear(cDate);
                        cycleText = $"{cDate.Year.ToString()}W{weekofYear}";
                        if (_context.siger_project_kpi_tasklist.Where(f => f.projectId == obj.projectId && f.ItemId == obj.id && f.cycle == cycleText).Count() > 0)
                            return;
                        break;
                    }
                case KpiCycleEnum.Day:
                    {
                        cycleText = strDate;
                        if (_context.siger_project_kpi_tasklist.Where(f => f.projectId == obj.projectId && f.ItemId == obj.id && f.cycle == cycleText).Count() > 0)
                            return;
                        break;
                    }
                default:
                    {
                        return;
                    }
            }
            Create(obj, cDate, cycleText);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="item"></param>
        /// <param name="cDate"></param>
        /// <param name="cycleText"></param>
        void Create(siger_project_kpi_item item,DateTime cDate,string cycleText)
        {
            try
            {
                _context.siger_project_kpi_tasklist.Add(new SigerProjectKpiTasklist
                {
                    projectId = item.projectId,
                    Busidate = cDate,
                    cycle=cycleText,
                    Type=0,
                    ItemId = item.id,
                    ActVal = 0d,
                    Excption = KpiExecption.Default,
                    Result = KpiTaskResult.NoConfg,
                    Section = item.Section,
                    status = (int)RowState.Valid
                });
                _context.SaveChanges();
            }catch (Exception e)
            {
                Logger.WriteLineError("KpiTasksJobs Error" + e.StackTrace);
            }
        }

    }
}
