using FluentScheduler;
using Siger.DataSchedule.Infrastructure.Extend;
using Siger.Middlelayer.AccRepository;
using Siger.Middlelayer.AccRepository.Entities;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.DashboardRepository.Response;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.QmsRepository;
using Siger.Middlelayer.QmsRepository.Entities;
using Siger.Middlelayer.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using siger_check_sn_trace_detail = Siger.Middlelayer.QmsRepository.Entities.siger_check_sn_trace_detail;
using siger_check_sn_trace_inspection = Siger.Middlelayer.QmsRepository.Entities.siger_check_sn_trace_inspection;

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


        public void AfterExecute(ScheduleContext context)
        {

        }


        public void Undo()
        {

        }
    }

    public class AutoQmsSnHelper : IJob
    {

        private static ApiQmsDbContext _context;

        static AutoQmsSnHelper()
        {
            _context = new ApiQmsDbContext();
        }

        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;
                        AutoQmsInspection(dbNameConfig.Pid);
                        AutoQmsReworkData(dbNameConfig.Pid);
                        AutoQmsTraceDetail(dbNameConfig.Pid);
                        AutoQmsTraceMaterial(dbNameConfig.Pid);
                        AutoQmsTraceMaterialDetail(dbNameConfig.Pid);
                    }
                }
                
            }
            catch(Exception e)
            {
                Logger.WriteLineError($"AutoTaskJob DbNameConfig setting error {e.StackTrace}");
            }
            
        }
        /// <summary>
        ///工件返工录入,工件报废录入
        /// </summary>
        /// <param name="projectId"></param>
        private void AutoQmsInspection( int projectId)
        {
            try
            {  
                var snList = _context.siger_qms_rework_data.Where(f => f.projectid==projectId && f.status != (int)RowState.Invalid).OrderByDescending(q => q.id).ToList();
                if (!snList.Any())
                {
                    return;
                }
                var lastTime = snList[0].DateTime.Date;
                var snLists = _context.siger_qms_rework_data.Where(f => f.projectid == projectId && f.status != (int)RowState.Invalid && f.DateTime
                                                                                                                                         >= lastTime && f.DateTime < lastTime.AddDays(1)).ToList();
                if (!snLists.Any())
                {
                    return;
                }
                var response = new List<siger_qms_rework_data>();
                foreach (var item in snLists)
                {
                    item.DateTime = item.DateTime.AddDays(1);
                }
                response.AddRange(Mapper<siger_qms_rework_data, siger_qms_rework_data>.MapList(snLists));
                _context.siger_qms_rework_data.AddRange(response);
                _context.SaveChanges();
                
                
            }
            catch (Exception ex)
            {
                Logger.WriteLineError(ex.Message);
            }
        }
        /// <summary>
        /// 人工检验数据,工件送检管理,检测检验管理
        /// </summary>
        /// <param name="projectId"></param>
        private void AutoQmsReworkData(int projectId)
        {
            try
            {
                var snList = _context.siger_check_sn_trace_inspection.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].send_time.Date;
                var snLists = _context.siger_check_sn_trace_inspection.Where(f => f.projectid
                                                                                  == projectId && f.status != (int)RowState.Invalid && f.send_time >= lastTime && f.send_time < lastTime.AddDays(1)).ToList();
                if (!snLists.Any())
                {
                    return;
                }
                var response = new List<siger_check_sn_trace_inspection>();
                foreach (var item in snLists)
                {
                    item.send_time = item.send_time.AddDays(1);
                    item.trace_id = item.trace_id + 1; ;
                    if (item.check_time != null)
                    {
                        item.check_time = ((DateTime)item.check_time).AddDays(1);
                    }
                    if (item.recieve_time != null)
                    {
                        item.recieve_time = ((DateTime)item.recieve_time).AddDays(1);
                    }
                    if (item.checking_time != null)
                    {
                        item.checking_time = ((DateTime)item.checking_time).AddDays(1);
                    }
                }
                response.AddRange(Mapper<siger_check_sn_trace_inspection, siger_check_sn_trace_inspection>.MapList(snLists));
                _context.siger_check_sn_trace_inspection.AddRange(response);
                _context.SaveChanges();


            }
            catch (Exception ex)
            {
                Logger.WriteLineError(ex.Message);
            }
        }
        /// <summary>
        /// 人工检验数据
        /// </summary>
        /// <param name="projectId"></param>
        private void AutoQmsTraceDetail(int projectId)
        {
            try
            {
                var snList = _context.siger_check_sn_trace_detail.Where(f => f.projectid == projectId && f.status != (int)RowState.Invalid).OrderByDescending(q => q.id).ToList();
                if (!snList.Any())
                {
                    return;
                }
                var lastTime = snList[0].CreateTime.Date;
                var snLists = _context.siger_check_sn_trace_detail.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_check_sn_trace_detail>();
                foreach (var item in snLists)
                {
                    item.CreateTime = item.CreateTime.AddDays(1);
                }
                response.AddRange(Mapper<siger_check_sn_trace_detail, siger_check_sn_trace_detail>.MapList(snLists));
                _context.siger_check_sn_trace_detail.AddRange(response);
                _context.SaveChanges();


            }
            catch (Exception ex)
            {
                Logger.WriteLineError(ex.Message);
            }
        }
        /// <summary>
        /// 进料检验收集,
        /// </summary>
        /// <param name="projectId"></param>
        private void AutoQmsTraceMaterial(int projectId)
        {
            try
            {
                var snList = _context.siger_check_sn_trace_material.Where(f => f.projectid == projectId && f.status != (int)RowState.Invalid).OrderByDescending(q => q.id).ToList();
                if (!snList.Any())
                {
                    return;
                }
                var lastTime = snList[0].CreateTime.Date;
                var snLists = _context.siger_check_sn_trace_material.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_check_sn_trace_material>();
                foreach (var item in snLists)
                {
                    item.CreateTime = item.CreateTime.AddDays(1);
                }
                response.AddRange(Mapper<siger_check_sn_trace_material, siger_check_sn_trace_material>.MapList(snLists));
                _context.siger_check_sn_trace_material.AddRange(response);
                _context.SaveChanges();


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

        private void AutoQmsTraceMaterialDetail(int projectId)
        {
            try
            {
                var snList = _context.siger_check_sn_trace_material_detail.Where(f => f.projectid == projectId && f.status != (int)RowState.Invalid).OrderByDescending(q => q.id).ToList();
                if (!snList.Any())
                {
                    return;
                }
                var lastTime = snList[0].CreateTime.Date;
                var snLists = _context.siger_check_sn_trace_material_detail.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_check_sn_trace_material_detail>();
                foreach (var item in snLists)
                {
                    item.CreateTime = item.CreateTime.AddDays(1);
                }
                response.AddRange(Mapper<siger_check_sn_trace_material_detail, siger_check_sn_trace_material_detail>.MapList(snLists));
                _context.siger_check_sn_trace_material_detail.AddRange(response);
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                Logger.WriteLineError(ex.Message);
            }
        }
    }
}
