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

namespace Siger.Schedule.DashboardModule
{
    public class AuteKpiActionSchedule : IScheduleJob
    {
        AuteKpiAction andonHelper;
        public void PreInit(ScheduleContext context)
        {
            Logger.RegisterLogEngine(Module.Dashboard);
            andonHelper = new AuteKpiAction();
        }
        public void Execute(ScheduleContext context)
        {
            andonHelper.Execute();
        }


        public void AfterExecute(ScheduleContext context)
        {

        }


        public void Undo()
        {

        }
    }
    public class AuteKpiAction 
    {
        private ApiKpiDbContext _context;
        public AuteKpiAction()
        {
            _context = new ApiKpiDbContext();
        }

        public void Execute()
        {
            try
            {
                var state = _context.siger_system_config.FirstOrDefault(t => t.status == (int)RowState.Valid &&
                               t.key == SystemConfigKey.gkydata);
                if (state != null )
                {
                    var dbConfigs = RedisCache.Instance.GetDbNameConfigs();
                    foreach (var dbNameConfig in dbConfigs)
                    {
                        if (string.IsNullOrWhiteSpace(dbNameConfig.RedisDbName))
                        {
                            Logger.WriteLineError($"AutoTaskJob DbNameConfig setting error, can not find redisdbname by cid:{dbNameConfig.Cid}, pid:{dbNameConfig.Pid}.");
                            continue;
                        }
                        if (dbNameConfig.Pid != state.value.ToInt())
                            continue;
                        AutoKpiProjectAction(dbNameConfig.Pid);
                        AutoKpiProjectTasklist(dbNameConfig.Pid);
                    }
                }
                
            }
            catch (Exception e)
            {
                Logger.WriteLineError($"AutoTaskJob DbNameConfig setting error {e.StackTrace}");
            }

        }
        /// <summary>
        /// 行动计划制定
        /// </summary>
        /// <param name="projectId"></param>
        private void AutoKpiProjectAction(int projectId)
        {
            try
            {
                var snList = _context.siger_project_kpi_action.Where(f => f.projectId==projectId && f.status != (int)RowState.Invalid).OrderByDescending(q => q.id).Take(1).ToList();
                if (!snList.Any())
                {
                    return;
                }
                var lastTime = snList[0].Plantime.Date;
                var snLists = _context.siger_project_kpi_action.Where(f => f.projectId==projectId && f.status != (int)RowState.Invalid && f.Plantime >= lastTime && f.Plantime< lastTime.AddDays(1)).ToList();
                if (!snLists.Any())
                {
                    return;
                }
                var response = new List<SigerProjectKpiAction>();
                foreach (var item in snLists)
                {
                    item.Plantime = item.Plantime.AddDays(1);
                    item.Excutetime = item.Excutetime > 0 ? item.Excutetime + 86400 : 0;
                    item.Checktime = item.Checktime > 0 ? item.Checktime + 86400 : 0;
                }
                response.AddRange(Mapper<SigerProjectKpiAction, SigerProjectKpiAction>.MapList(snLists));
                _context.siger_project_kpi_action.AddRange(response);
                _context.SaveChanges();
                
                
            }
            catch (Exception ex)
            {
                Logger.WriteLineError(ex.Message);
            }
            
        }

        private void AutoKpiProjectTasklist(int projectId)
        {
            try
            {
                var snListss = _context.siger_project_kpi_item.Where(f => f.projectId==projectId && f.status != (int)RowState.Invalid).OrderByDescending(q => q.id).Take(1).ToList();
                if (!snListss.Any())
                {
                    return;
                }
                var lastTime = snListss[0].CreateTime.Date;
                var snLists = _context.siger_project_kpi_item.Where(f => f.projectId==projectId && f.status != (int)RowState.Invalid && f.CreateTime >= lastTime && f.CreateTime< lastTime.AddDays(1)).ToList();
                if (!snLists.Any())
                {
                    return;
                }
                var response = new List<siger_project_kpi_item>();
                foreach (var item in snLists)
                {
                    item.CreateTime = item.CreateTime.AddDays(1);
                }
                response.AddRange(Mapper<siger_project_kpi_item, siger_project_kpi_item>.MapList(snLists));
                _context.siger_project_kpi_item.AddRange(response);
                if (_context.SaveChanges() > 0)
                {
                    var snList = _context.siger_project_kpi_tasklist.Where(f => f.projectId==projectId && f.status != (int)RowState.Invalid && f.Type == (int)KpiTaskType.Exception).OrderByDescending(q => q.id).ToList();
                    if (!snList.Any())
                    {
                        return;
                    }
                    var lastTimes = snList[0].Busidate.Date;
                        var kpiitemList = _context.siger_project_kpi_tasklist.Where(f => f.projectId == projectId && f.status != (int)RowState.Invalid && f.Busidate >= lastTimes && f.Busidate < lastTimes.AddDays(1)).ToList();
                    if (!kpiitemList.Any())
                    {
                        return;
                    }
                    var responses = new List<SigerProjectKpiTasklist>();
                    foreach (var item in kpiitemList)
                    {
                        item.Busidate = item.Busidate.AddDays(1);
                    }
                    responses.AddRange(Mapper<SigerProjectKpiTasklist, SigerProjectKpiTasklist>.MapList(kpiitemList));
                    _context.siger_project_kpi_tasklist.AddRange(responses);
                    _context.SaveChanges(); 
                }
                
                
            }
            catch (Exception ex)
            {
                Logger.WriteLineError(ex.Message);
            }
        }
    }
}
