using Khd.Core.EntityFramework;
using Khd.Core.Library;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Timers;
namespace Khd.Core.Wcs.Wcs
{
    public class BackUpData
    {
        private readonly IHost _host;
        public BackUpData(IHost host)
        {
            this._host = host;
        }
        /// <summary>
        /// 启动线程
        /// </summary>
        public void StartPoint()
        {
            Thread OrderBakThread = new Thread(MonitorInLocatorPoint);
            OrderBakThread.Start();
        }
        public void MonitorInLocatorPoint()
        {
            // 创建一个定时器对象，设置时间间隔为24小时  
            System.Timers.Timer timer = new System.Timers.Timer(24 * 60 * 60 * 1000); // 1000毫秒 = 1秒  
            //timer = new System.Timers.Timer(10*1000); // 1000毫秒 = 1秒  

            // 添加一个事件处理程序，当定时器间隔结束时调用方法  
            timer.Elapsed += OnTimerElapsed;

            // 启动定时器  
            timer.Enabled = true;
        }

        /// <summary>
        /// 定时方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnTimerElapsed(object? sender, ElapsedEventArgs e)
        {
            LoggerUtils _logger = new LoggerUtils();
            try
            {
                using var scope = _host.Services.CreateScope();
                using var dbContext = scope.ServiceProvider.GetRequiredService<DefaultDbContext>();
                string sqlQuery = @$"INSERT INTO 
                                base_production_order_split_bak 
                                (id,site_code, line_code, line_name, order_code,prod_code,prod_desc,IsOver,est,Quantity,production_sequence)
                                SELECT 
                                id,site_code, line_code, line_name, order_code,prod_code,prod_desc,IsOver,est,Quantity,production_sequence
                                FROM base_production_order_split 
                                where  
                                IsOver = 1 
                                and 
                                est < date_add(NOW(), interval -1 DAY);
                                delete
                                FROM
                                base_production_order_split
                                WHERE
                                IsOver = 1
                                and
                                est < date_add(NOW(), interval -1 DAY);";
                var ret = dbContext.Database.ExecuteSqlRaw(sqlQuery);
                string saveLog = ret == 0 ? "备份任务SQL语句存在问题!" : "备份任务SQL语句执行成功!";
                _logger.Info($"定时备份任务日志记录 >>> {saveLog}");
            }
            catch (Exception ex)
            {
                _logger.Info($"定时备份任务方法报错 >>> {ex.Message}");
            }

        }
    }
}
