using FluentScheduler;
using Siger.DataSchedule.Infrastructure.Extend;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.DashboardRepository.Response;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Redis;
using Siger.Middlelayer.TpmRepository;
using Siger.Middlelayer.TpmRepository.Entities;
using System;
using System.Collections.Generic;
using System.Linq;

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


        public void AfterExecute(ScheduleContext context)
        {

        }


        public void Undo()
        {

        }
    }
    public class AutoTpmRepair : IJob
    {
        private static ApiTpmDbContext _context;
        public AutoTpmRepair()
        {
            _context = new ApiTpmDbContext();
        }

        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;
                        AutoTpmProjectRepair(dbNameConfig.Pid);
                        AutoTpmProjectPlan(dbNameConfig.Pid);
                        AutoTpmProjectPlanItem(dbNameConfig.Pid);
                        AutoAndon(dbNameConfig.Pid);
                    }
                }

            }
            catch (Exception e)
            {
                Logger.WriteLineError($"AutoTaskJob DbNameConfig setting error {e.StackTrace}");
            }

        }
        /// <summary>
        /// 安灯状态一览
        /// </summary>
        /// <param name="projectId"></param>
        private void AutoAndon(int projectId)
        {
            try
            {
                var yesterday = UnixTimeHelper.ConvertDataTimeLong(DateTime.Now.Date.AddDays(-1));
                var snList = _context.siger_andon_info.Where(f => f.projectid == projectId && f.status != (int)RowState.Invalid).OrderByDescending(q => q.id).ToList();
                if (!snList.Any())
                {
                    return;
                }
                var snLists = _context.siger_andon_info.Where(f => f.projectid == projectId && f.status != (int)RowState.Invalid && f.create_time >= yesterday && f.create_time < yesterday + 86400).ToList();
                if (!snLists.Any())
                {
                    return;
                }
                var response = new List<siger_andon_info>();
                foreach (var item in snLists)
                {
                    item.create_time = item.create_time + 86400;
                    item.complete_time = item.complete_time > 0 ? item.complete_time + 86400 : 0;
                    item.handle_time = item.handle_time > 0 ? item.handle_time + 86400 : UnixTimeHelper.ConvertDataTimeLong(DateTime.Now.ToString());
                    item.approve_time = item.approve_time > 0 ? item.approve_time + 86400 : 0;
                    item.approve_time = item.abnormal_time > 0 ? item.abnormal_time + 86400 : 0;
                    item.handler = item.handler == 0 ? item.handler = 2103 : item.handler;//默认用户
                }
                response.AddRange(Mapper<siger_andon_info, siger_andon_info>.MapList(snLists));
                _context.siger_andon_info.AddRange(response);
                _context.SaveChanges();

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

        }
        /// <summary>
        /// 设备维修列表
        /// </summary>
        /// <param name="projectId"></param>
        private void AutoTpmProjectRepair(int projectId)
        {
            try
            {
                var snList = _context.siger_project_repair.Where(f => f.projectid == projectId && f.status != (int)RowState.Invalid).OrderByDescending(q => q.id).ToList();
                if (!snList.Any())
                {
                    return;
                }
                var lastTime = UnixTimeHelper.ConvertDataTimeLong(UnixTimeHelper.ConvertIntDateTime(snList[0].createtime).ToDateTime().Date);
                var nextTime = lastTime + 86400;
                var snLists = _context.siger_project_repair.Where(f => f.projectid == projectId && f.status != (int)RowState.Invalid && f.createtime >= lastTime && f.createtime < nextTime).ToList();
                if (!snList.Any())
                {
                    return;
                }
                var response = new List<siger_project_repair>();
                foreach (var item in snLists)
                {
                    item.createtime = item.createtime + 86400;
                    item.taketime = item.taketime > 0 ? item.taketime + 86400 : 0;
                    item.signtime = item.signtime > 0 ? item.signtime + 86400 : 0;
                    item.repairtime = item.repairtime > 0 ? item.repairtime + 86400 : 0;
                    item.checktime = item.checktime > 0 ? item.checktime + 86400 : 0;
                    item.completetime = item.completetime > 0 ? item.completetime + 86400 : 0;
                }
                response.AddRange(Mapper<siger_project_repair, siger_project_repair>.MapList(snLists));
                _context.siger_project_repair.AddRange(response);
                _context.SaveChanges();

            }
            catch (Exception ex)
            {
                Logger.WriteLineError(ex.Message);
            }
        }
        /// <summary>
        /// 计划维护列表
        /// </summary>
        /// <param name="projectId"></param>
        private void AutoTpmProjectPlan(int projectId)
        {
            try
            {
                var snList = _context.siger_project_plan.Where(f => f.projectid == projectId && f.status != (int)RowState.Invalid).OrderByDescending(q => q.id).ToList();
                if (!snList.Any())
                {
                    return;
                }

                var lastTime = UnixTimeHelper.ConvertDataTimeLong(UnixTimeHelper.ConvertIntDateTime(snList[0].first_instruction_time.ToInt()).ToDateTime().Date);
                var nextTime = lastTime + 86400;
                var snLists = _context.siger_project_plan.Where(f => f.projectid == projectId && f.status != (int)RowState.Invalid && f.first_instruction_time.ToInt() >= lastTime && f.first_instruction_time.ToInt() < nextTime).ToList();
                if (!snLists.Any())
                {
                    return;
                }
                var response = new List<siger_project_plan>();
                foreach (var item in snLists)
                {
                    item.first_instruction_time = (item.first_instruction_time.ToInt() + 86400).ToStr();
                    item.endtime = item.endtime > 0 ? item.endtime + 86400 : 0;
                    item.starttime = item.starttime > 0 ? item.starttime + 86400 : 0;
                }
                response.AddRange(Mapper<siger_project_plan, siger_project_plan>.MapList(snLists));
                _context.siger_project_plan.AddRange(response);
                _context.SaveChanges();

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

        }
        private void AutoTpmProjectPlanItem(int projectId)
        {
            try
            {
                var snList = _context.siger_project_plan_item.Where(f => f.projectid == projectId && f.status != (int)RowState.Invalid).OrderByDescending(q => q.id).ToList();
                if (!snList.Any())
                {
                    return;
                }

                var lastTime = UnixTimeHelper.ConvertDataTimeLong(UnixTimeHelper.ConvertIntDateTime(snList[0].create_time).ToDateTime().Date);
                var nextTime = lastTime + 86400;
                var snLists = _context.siger_project_plan_item.Where(f => f.projectid == projectId && f.status != (int)RowState.Invalid && f.create_time >= lastTime && f.create_time < nextTime).ToList();
                if (!snLists.Any())
                {
                    return;
                }
                var response = new List<siger_project_plan_item>();
                foreach (var item in snLists)
                {
                    item.create_time = item.create_time + 86400;
                }
                response.AddRange(Mapper<siger_project_plan_item, siger_project_plan_item>.MapList(snLists));
                _context.siger_project_plan_item.AddRange(response);
                _context.SaveChanges();

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