using ryCommon;
using ryCommonDb;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace TimeClock
{
    [DefaultEvent("OnTimeTip")]
    public partial class RyTimeClock : Component
    {
        public delegate void TimeHandler(object sender,TimeInfo e);
        /// <summary>
        /// 提醒事件发生时激发
        /// </summary>
        [Description("提醒事件发生时激发")]
        public event TimeHandler OnTimeTip;
        /// <summary>
        /// 提醒事件被编辑或新增、删除时激发
        /// </summary>
        [Description("提醒事件被编辑或新增、删除时激发")]
        public event EventHandler OnTimeTipChanged;
        /// <summary>
        /// 休息提醒数据改变时激发
        /// </summary>
        [Description("休息提醒数据改变时激发")]
        public event EventHandler OnRestDataChanged;
        /// <summary>
        /// 是否开启提醒功能
        /// </summary>
        [Description("是否开启提醒功能")]
        public bool Enabled
        {
            get {return timer.Enabled; }
            set
            {
                if (timer.Enabled != value && !GetIsDesignMode())
                {
                    UpdateTipTime();
                    UpdateTipTime_start(false);
                    if(value)
                    {
                       Itrycn_Info.InitRest();
                    }
                    if (Itrycn_Info.RestTip_On && Itrycn_Info.SaveSchedule && first_start)
                    {
                        if (Itrycn_Info.IdleOver_On && Last_CloseTime.AddMinutes(Itrycn_Info.IdleOverMinute) < DateTime.Now)
                        {

                        }
                        else
                        {
                            Int64 rest_second = Itrycn_Db.GetSetting("SaveSchedule", "0").ToInt64();
                            if (rest_second > 0)
                            {
                                Itrycn_Info.Timer_index = rest_second;
                            }
                        }
                    }
                    first_start = false;
                    timer.Enabled = value;
                }
            }
        }
        ~RyTimeClock()
        {
            if (Itrycn_Info.RestTip_On && Itrycn_Info.SaveSchedule)
            {
                Itrycn_Db.SetSetting("SaveSchedule", Itrycn_Info.Timer_index.ToString());
                Itrycn_Db.SetSetting("CloseTime", DateTime.Now.ToTimeStamp().ToString());
            }
        }
        /// <summary>
        /// 显示提醒管理窗口
        /// </summary>
        public void ShowMsgManage()
        {
            DbOp.FrmTimeView frm = new DbOp.FrmTimeView();
            frm.FormClosing+=new FormClosingEventHandler((object t, FormClosingEventArgs dg) => {
                if (frm.dr == DialogResult.OK)
                {
                    TipChanged();
                }
            });
            var form= RyForm.ShowOne(frm);
            form.WindowState = FormWindowState.Normal;
        }
        /// <summary>
        /// 添加快速提醒。
        /// </summary>
        public void ShowQuickAddTip()
        {
            DbOp.FrmQuickAdd frm = new DbOp.FrmQuickAdd();
            frm.mr = new ModalForm(null, frm);
            frm.mr.OnDialogResult += new ModalForm.DialogResultHandler((object t, DialogResult dg) => {
                if (dg == DialogResult.OK)
                {
                    TipChanged();
                }
            });
            frm.mr.ShowModal();
        }
        /// <summary>
        /// 显示提醒管理窗口中的日历页
        /// </summary>
        public void ShowCalendarManage()
        {
            DbOp.FrmTimeView frm = new DbOp.FrmTimeView();
            frm.FormClosing += new FormClosingEventHandler((object t, FormClosingEventArgs dg) => {
                if (frm.dr == DialogResult.OK)
                {
                    TipChanged();
                }
            });
            var form = (DbOp.FrmTimeView)RyForm.ShowOne(frm);
            form.chromeTabControl1.SelectedTab = form.TabCalendar;
            form.WindowState = FormWindowState.Normal;
        }
        /// <summary>
        /// 提醒发生变化
        /// </summary>
        private void TipChanged()
        {
            OnTimeTipChanged?.Invoke(this, new EventArgs());
            if(Itrycn_Info.TipViewHandle!=IntPtr.Zero)
            {
                ryControls.Win32.SendMessage(Itrycn_Info.TipViewHandle, 17189,100, API.Msgs.Msg_OnTimeTipChanged);
            }
        }
        /// <summary>
        /// 显示设置窗口
        /// </summary>
        public void ShowSetting()
        {
            DbOp.FrmSetting frm = new DbOp.FrmSetting();
            frm.FormClosing += new FormClosingEventHandler((object t, FormClosingEventArgs dg) => {
                if (frm.dr == DialogResult.OK)
                {
                    last_fullscreen = false;
                    last_idle = false;
                }
            });
            RyForm.ShowOne(frm);
        }
        public void LoadSticky()
        {
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(Itrycn_Db.SQLConnStr) == 1)
            {
                var ds = db.ReadData("select * from Sticky where DeskShow=1");
                if (mydb.HaveData(ds))
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        var row = ds.Tables[0].Rows[i];
                        TimeClock.DbOp.FrmSticky frm = new DbOp.FrmSticky
                        {
                            IsAdd = false,
                            Id = row["id"].ToInt(),
                            ProcUse = true
                        };
                        frm.LoadSticky();
                        RyForm.ShowNoActiveWindow(frm);
                        frm.ProcUse = false;
                    }
                }
            }
            db.Free();
        }
        /// <summary>
        /// 打开新的便笺
        /// </summary>
        public void OpenNewSticky()
        {
            TimeClock.DbOp.FrmSticky frm = new DbOp.FrmSticky();
            frm.ProcUse = true;
            frm.Id = -1;
            frm.IsAdd = true;
            frm.StickyBackColor = Color.FromArgb(255, 255, 192);
            frm.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width-frm.Width, 20);
            frm.Show();
            frm.ProcUse = false;
        }
        /// <summary>  
        /// 获取当前是否处于设计器模式  
        /// </summary>  
        /// <remarks>  
        /// 在程序初始化时获取一次比较准确，若需要时获取可能由于布局嵌套导致获取不正确，如GridControl-GridView组合。  
        /// </remarks>  
        /// <returns>是否为设计器模式</returns>  
        private bool GetIsDesignMode()  
        {
            //获取混音设备 
            return (this.GetService(typeof(System.ComponentModel.Design.IDesignerHost)) != null  
                || LicenseManager.UsageMode == LicenseUsageMode.Designtime);  
        }
        /// <summary>
        /// 更新下次提醒时间
        /// </summary>
        public void UpdateTipTime()
        {
            UpdateTipTime(false);
        }
        /// <summary>
        /// 更新下次提醒时间
        /// </summary>
        /// <param name="slient">是否静默更新,不静默的话会弹出过期提醒</param>
        public void UpdateTipTime(bool slient)
        {
            UpdateTipTime(slient,false);
        }
        /// <summary>
        /// 更新下次提醒时间
        /// </summary>
        /// <param name="slient">是否静默更新,不静默的话会弹出过期提醒</param>
        /// <param name="update_all">是否更新全部提醒,而不是已过期提醒,记住软件启动时提醒不会更新</param>
        public void UpdateTipTime(bool slient,bool update_all)
        {
            DataProvider mydb = new DataProvider();
            IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
            Itrycn_Db.CreateTable();
            if (db.ConnDb(TimeClock.Itrycn_Db.SQLConnStr) == 1)
            {
                RyQuickSQL mySQL = new RyQuickSQL("Dingshi");
                DateTime dt_now = DateTime.Now;
                mySQL.AddParameter("@dt_now", dt_now);
                mySQL.AddParameter("@dt_end", new DateTime(2100,1,1));
                string sql = "select * from Dingshi where (NextTipTime<@dt_now or NextTipTime=@dt_end) and modtype<>7 and Enabled=1 and TipClose=0";
                if(update_all)
                {
                    sql = "select * from Dingshi where modtype<>7 and Enabled=1 and TipClose=0";
                }
                DataSet ds = db.ReadData(sql, mySQL);
                if (mydb.HaveData(ds))
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        DataRow reader = ds.Tables[0].Rows[i];
                        if (!slient)
                        {
                            #region 例外免打扰
                            if (Itrycn_Db.CanTip(dt_now, 0, reader["ExceptXML"].ToString()))
                            {
                                #region 过期提醒
                                DbOp.FrmTip frm = new DbOp.FrmTip();
                                frm.LblTimeStr.Text = "过期时间:" + reader["NextTipTime"].ToDateTime().ToString("yyyy年MM月dd日 HH:mm");
                                frm.Id = reader["id"].ToInt();
                                frm.IsTemp = 0;
                                frm.RunTimeStr = reader["RunTimeStr"].ToString();
                                frm.Text = "【已过期】【" + reader["RunTimeStr"].ToString() + "】的提醒";
                                frm.LblState.Text = "过期提醒";
                                frm.LblState.ForeColor = System.Drawing.Color.Red;
                                frm.TxtTitle.Text = reader["MsgTitle"].ToString();
                                frm.labelTx1.Text = reader["RunTimeStr"].ToString();
                                frm.LblCloseTime.Visible = false;
                                frm.Show();
                                ryCommon.Storage tStor = new Storage(reader["SetXML"].ToString());
                                tStor.SelectNodeBySet();
                                string ActionId = tStor.GetAttrValue("ActionId");
                                string File = tStor.GetAttrValue("File");
                                string Pram = tStor.GetAttrValue("Pram");
                                switch (ActionId)
                                {
                                    case "OpenUrl":
                                        RyFiles.RunFile(File, "");
                                        break;
                                    case "OpenFile":
                                        RyFiles.RunFile(File, Pram);
                                        break;
                                }
                                #endregion                              
                            }
                            #endregion
                        }
                        RyQuickSQL mySQL2 = new RyQuickSQL("Dingshi");
                        DateTime dt = TimeClock.Itrycn_Db.GetNextTipTime2(reader, DateTime.Now);
                        mySQL2.AddField("NextTipTime", dt);
                        mySQL2.AddField("EarlierTipTime", dt.AddMinutes(-reader["EarlierMinute"].ToInt()));
                        mySQL2.AddField("Clac_Time", DateTime.Now);
                        if (reader["modtype"].ToInt() == TipType.tip_thetime)//指定时间
                        { mySQL2.AddField("TipClose", 1); }
                        db.ExecuteNonQuery(mySQL2.GetUpdateSQL() + " where id=" + reader["id"].ToString(), mySQL2);
                    }
                    TipChanged();
                    //MessageBox.Show("发现部分已过期的提醒,过期提醒将不会执行关机、重启等命令，但其它命令依旧会执行。","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                }
                db.ExecuteNonQuery("delete from Dingshi where NextTipTime<@dt_now and TempTip=1", mySQL);
            }
            db.Free();
        }
        /// <summary>
        /// 在启动软件时,更新下次提醒时间
        /// </summary>
        /// <param name="slient"></param>
        public void UpdateTipTime_start(bool slient)
        {
            DataProvider mydb = new DataProvider();
            IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
            Itrycn_Db.CreateTable();
            if (db.ConnDb(TimeClock.Itrycn_Db.SQLConnStr) == 1)
            {
                RyQuickSQL mySQL = new RyQuickSQL("Dingshi");
                DateTime dt_now = DateTime.Now;
                mySQL.AddParameter("@dt_now", dt_now);
                mySQL.AddParameter("@dt_end", new DateTime(2100, 1, 1));
                //modtype=7表示软件启动
                DataSet ds = db.ReadData("select * from Dingshi where modtype=7 and Enabled=1 and TipClose=0", mySQL);
                if (mydb.HaveData(ds))
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        DataRow reader = ds.Tables[0].Rows[i];
                        RyQuickSQL mySQL2 = new RyQuickSQL("Dingshi");
                        DateTime dt = TimeClock.Itrycn_Db.GetNextTipTime2(reader, DateTime.Now);
                        mySQL2.AddField("NextTipTime", dt);
                        mySQL2.AddField("EarlierTipTime", dt.AddMinutes(-reader["EarlierMinute"].ToInt()));
                        mySQL2.AddField("Clac_Time", DateTime.Now);
                        if (reader["modtype"].ToInt() == TipType.tip_thetime)//指定时间
                        { mySQL2.AddField("TipClose", 1); }
                        db.ExecuteNonQuery(mySQL2.GetUpdateSQL() + " where id=" + reader["id"].ToString(), mySQL2);
                    }
                    TipChanged();
                    //MessageBox.Show("发现部分已过期的提醒,过期提醒将不会执行关机、重启等命令，但其它命令依旧会执行。","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                }
                db.ExecuteNonQuery("delete from Dingshi where NextTipTime<@dt_now and TempTip=1", mySQL);
            }
            db.Free();
        }
        bool first_start = true;
        DateTime Last_CloseTime = DateTime.Now;
        private Form _parentForm;
        System.Timers.Timer timer = new System.Timers.Timer(1000);
        public RyTimeClock(Form parentForm)
        {
            InitializeComponent();
            _parentForm = parentForm;
            timer.SynchronizingObject = parentForm;
            timer.Elapsed += TimeElapsed;
            if (!GetIsDesignMode())
            {
                TimeClock.Itrycn_Db.CreateTable();
                Itrycn_Info.ReadSetting();
                Last_CloseTime = Itrycn_Db.GetSetting("CloseTime", "0").ToInt64().ToDateTime();
                if (Enabled)
                {
                    Itrycn_Info.InitRest();
                    UpdateTipTime(false,true);
                    UpdateTipTime_start(false);
                    if (Itrycn_Info.RestTip_On && Itrycn_Info.SaveSchedule && first_start)
                    {
                        if (Itrycn_Info.IdleOver_On && Last_CloseTime.AddMinutes(Itrycn_Info.IdleOverMinute) < DateTime.Now)
                        {

                        }
                        else
                        {
                            Int64 rest_second = Itrycn_Db.GetSetting("SaveSchedule", "0").ToInt64();
                            if (rest_second > 0)
                            {
                                Itrycn_Info.Timer_index= rest_second;
                            }
                        }
                    }
                    first_start = false;
                }                
            }
        }
        private void TimeElapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (!TimeComplete) { return; }
            TimeComplete = false;
            DateTime dt_now = DateTime.Now;
            if (last_IsRestNowing != Itrycn_Info.IsRestNowing)
            {
                last_IsRestNowing = Itrycn_Info.IsRestNowing;
                if (!last_IsRestNowing)
                {
                    AddRestRecord(new RestInfo() { UserSecondTime = (DateTime.Now - last_StartRestTime).TotalSeconds.ToInt(), Mode = 3 });
                }
                else { last_StartRestTime = DateTime.Now; }
            }
            if (Itrycn_Info.RestTip_On && !Itrycn_Info.IsRestNowing)//如果开启了休息提醒,并且现在不在休息
            {
                bool canTip = true;
                if (Itrycn_Info.StopRestByFullScreen) //全屏程序暂停计时
                {
                    try
                    {
                        #region 全屏程序暂停计时
                        var active_win = WinAPI.User32.GetForegroundWindow();
                        WinAPI.User32.GetWindowRect(active_win, out var appBounds);
                        //判断是否全屏 
                        var screenBounds = Screen.FromHandle(active_win).Bounds;
                        if ((appBounds.Bottom - appBounds.Top) == screenBounds.Height && (appBounds.Right - appBounds.Left) == screenBounds.Width)
                        {
                            //全屏
                            canTip = false;
                            if (!last_fullscreen)
                            {
                                last_fullscreen = true;
                                Itrycn_Info.IsStopCalcRestNowing = true;
                                Itrycn_Info.IsStopCalcRestReason = "全屏";
                            }
                        }
                        else
                        {
                            if (last_fullscreen)
                            {
                                last_fullscreen = false;
                                Itrycn_Info.IsStopCalcRestNowing = false;
                            }
                        }
                        #endregion
                    }
                    catch { }
                }
                if (Itrycn_Info.StopRestByIdle)
                {
                    var idle = ryCommon.RySystem.GetLastInputTime() / 1000;
                    if (idle >= Itrycn_Info.IdleMinute * 60)//闲置超过几分钟
                    {
                        if (!last_idle)
                        {
                            last_idle = true;//从非闲置状态切换到闲置状态
                            Itrycn_Info.IsStopCalcRestNowing = true;
                            Itrycn_Info.IsStopCalcRestReason = "空闲";
                            dt_start_idle = DateTime.Now;
                        }
                        canTip = false;
                    }
                    else
                    {
                        if (last_idle)
                        {
                            last_idle = false;//从闲置状态切换到忙碌状态
                            Itrycn_Info.IsStopCalcRestNowing = false;
                            AddRestRecord(new RestInfo() { UserSecondTime = (DateTime.Now - dt_start_idle.AddSeconds(-Itrycn_Info.IdleMinute * 60)).TotalSeconds.ToInt(), Mode = 1 });
                            if (canTip) //如果当前是全屏状态，则不去处理
                            {
                                if (Itrycn_Info.Timer_index > 0)
                                {
                                    if (Itrycn_Info.IdleOver_On)
                                    {
                                        if (dt_start_idle.AddMinutes(Itrycn_Info.IdleOverMinute) < dt_now)
                                        {
                                            Itrycn_Info.Timer_index = Itrycn_Info.RestInteval * 60;
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
                if (canTip)
                {
                    Itrycn_Info.Timer_index--;
                    var _time = Itrycn_Info.Timer_index;
                    if (_time == 60)//提前一分钟
                    {
                        #region 提前一分钟提醒
                        if (Itrycn_Info.TipBeforeRest)
                        {
                            //System.IO.File.AppendAllText(Application.StartupPath + "\\Logs.txt",
                            //    "\r\n" + DateTime.Now + "\t提前一分钟休息提醒");
                            bool is_form_show = false;
                            try
                            {
                                for (int i = 0; i < Itrycn_Info.StickyList.Count; i++)
                                {
                                    if (Itrycn_Info.StickyList[i] is DbOp.FrmBeforeRestTip)
                                    {
                                        is_form_show = true;
                                        break;
                                    }
                                }
                            }
                            catch
                            {

                            }
                            if (!is_form_show)
                            {
                                DbOp.FrmBeforeRestTip frm = new DbOp.FrmBeforeRestTip();
                                frm.FormClosing += delegate (object sender2, FormClosingEventArgs e2)
                                {
                                    if (frm.IsDelay > 0)
                                    {
                                        AddRestRecord(new RestInfo() { UserSecondTime = frm.IsDelay * 60, Mode = 4 });
                                    }
                                    else if (frm.IsDelay == -1)
                                    {
                                        AddRestRecord(new RestInfo() { UserSecondTime = 0, Mode = 2 });
                                    }
                                };
                                frm.Show();
                                frm.StartLoad(); 
                            }
                        }
                        if (Itrycn_Info.SoundBeforeRest)
                        {
                            Itrycn_Info.PlaySound(Itrycn_Info.SysDbFolder + @"\animation\sound_tip\before_rest.mp3");
                        }
                        #endregion
                    }
                    else if (_time <= 0)
                    {
                        #region 准时休息提醒
                        Itrycn_Info.IsRestNowing = true;
                        var screen_use = Screen.PrimaryScreen;
                        var dt_rest_end = DateTime.Now.AddMinutes(Itrycn_Info.Rest);
                        for (int i = 0; i < Screen.AllScreens.Length; i++)
                        {
                            var screen = Screen.AllScreens[i];
                            if (screen == Screen.PrimaryScreen) //主显示器
                            {
                                DbOp.FrmRest frm = new DbOp.FrmRest(dt_rest_end, false)
                                {
                                    Location = screen.Bounds.Location,
                                    Size = screen.Bounds.Size
                                };
                                frm.Show();
                            }
                            else //其它显示器
                            {
                                DbOp.FrmRest frm = new DbOp.FrmRest(dt_rest_end, true)
                                {
                                    Location = screen.Bounds.Location,
                                    Size = screen.Bounds.Size
                                };
                                frm.Show();
                            }
                        }
                        #endregion
                    }
                }
            }
            if (dt_now.Second < 20)
            {
                if (lastRunTime.AddSeconds(30) > dt_now)
                { TimeComplete = true; return; }
                if (GetIsDesignMode()) { TimeComplete = true; return; }
                lastRunTime = dt_now;
                if (dt_now.Minute == 0)//整点报时
                {
                    if (Itrycn_Info.HourlyChime_On)//如果开启了整点报时
                    {
                        Thread th = new Thread(delegate () { Itrycn_Info.PlayHours(true); });
                        th.Start();
                    }
                }
                #region 定时提醒
                DataProvider mydb = new DataProvider();
                IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
                if (db.ConnDb(TimeClock.Itrycn_Db.SQLConnStr) == 1)
                {
                    RyQuickSQL mySQL = new RyQuickSQL("Dingshi");
                    DateTime dt_now_2 = dt_now.Date.AddHours(dt_now.Hour).AddMinutes(dt_now.Minute);
                    mySQL.AddParameter("@NextTipTime", dt_now_2);
                    DataSet ds = db.ReadData("select * from Dingshi where (NextTipTime=@NextTipTime or (EarlierTipTime=@NextTipTime and EarlierMinute<>0)) and Enabled=1", mySQL);
                    if (mydb.HaveData(ds))
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            DataRow reader = ds.Tables[0].Rows[i];
                            #region 遍历需要提醒的项目
                            ryCommon.Storage tStor = new Storage(reader["SetXML"].ToString());
                            tStor.SelectNodeBySet();
                            var NextTipTime = reader["NextTipTime"].ToDateTime();
                            string ActionId = tStor.GetAttrValue("ActionId");
                            string File = RyFiles.GetRealPath(tStor.GetAttrValue("File"));
                            string Pram = tStor.GetAttrValue("Pram");
                            bool sound_on = tStor.GetAttrValue("sound_on", true);
                            string sound_path = tStor.GetAttrValue("sound", Itrycn_Info.SysDbFolder + @"\animation\sound\tip.wav");
                            if (sound_path.Length == 0) { sound_path = Itrycn_Info.SysDbFolder + @"\animation\sound\tip.wav"; }
                            sound_path = Itrycn_Info.GetRealPath(sound_path);
                            bool gif_on = tStor.GetAttrValue("showpic_on", false);
                            string gif_path = Itrycn_Info.GetRealPath(tStor.GetAttrValue("showpic", ""));
                            string _run_file = "";
                            string _run_param = "";
                            #region 执行动作
                            switch (ActionId)
                            {
                                case "Shutdown"://关机
                                case "Reboot"://重启电脑
                                case "Logoff"://注销
                                case "Mute_On"://静音
                                case "Mute_Off"://取消静音
                                case "TimeSync"://时间同步
                                    _run_file = Application.StartupPath + "\\RyLine.exe";
                                    if (!System.IO.File.Exists(_run_file))
                                    {
                                        _run_file = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\RyLine.exe";
                                    }
                                    _run_param = ActionId;
                                    break;
                                case "OpenUrl":
                                    _run_file = File;
                                    break;
                                case "OpenFile":
                                    _run_file = File;
                                    _run_param = Pram;
                                    break;
                                case "Speaker":
                                    _run_file = File;
                                    break;
                            }
                            #endregion
                            TimeInfo ti = new TimeInfo()
                            {
                                id = reader["id"].ToInt(),
                                isTemp = reader["TempTip"].ToInt(),
                                RunTime = reader["RunTime"].ToDateTime(),
                                RunTimeStr = reader["RunTimeStr"].ToString(),
                                StartTime = reader["StartTime"].ToDateTime(),
                                MsgTitle = reader["MsgTitle"].ToString(),
                                MsgText = reader["MsgText"].ToString(),
                                ActionId = ActionId,
                                isSysAction = _run_file != "",
                                File = File,
                                Pram = Pram
                            };
                            #region 更新下次提醒时间
                            RyQuickSQL mySQL2 = new RyQuickSQL("Dingshi");
                            mySQL2.AddField("Clac_Time", DateTime.Now);
                            DateTime dt = TimeClock.Itrycn_Db.GetNextTipTime2(reader, DateTime.Now);
                            mySQL2.AddField("EarlierTipTime", dt.AddMinutes(-reader["EarlierMinute"].ToInt()));
                            mySQL2.AddField("NextTipTime", dt);
                            int EarlierMinute = reader["EarlierMinute"].ToInt();
                            if (reader["modtype"].ToInt() == 3)//指定时间的提醒，提醒过一次就不再提醒。
                            {
                                if (EarlierMinute == 0 || reader["EarlierTipTime"].ToDateTime(DateTime.Now.AddYears(-10)) != dt_now_2)
                                {
                                    mySQL2.AddField("TipClose", 1);
                                }
                            }
                            db.ExecuteNonQuery(mySQL2.GetUpdateSQL() + " where id=" + reader["id"].ToString(), mySQL2);
                            #endregion
                            #region 例外免打扰
                            if (!Itrycn_Db.CanTip(dt_now, ti.isTemp, reader["ExceptXML"].ToString()))
                            { continue; }
                            #endregion
                            OnTimeTip?.Invoke(this, ti);
                            if (!ti.Cancel)
                            {
                                if (!tStor.GetAttrValue("NoShowTip", false))
                                {
                                    if (Itrycn_Info.FullScreenTip)
                                    {
                                        #region 全屏提醒
                                        DbOp.FrmFullScreenTip frm = new DbOp.FrmFullScreenTip
                                        {
                                            Id = ti.id,
                                            isTemp = ti.isTemp,
                                            RunTimeStr = ti.RunTimeStr
                                        };
                                        if (sound_on)
                                        {
                                            frm.PlaySound(sound_path);
                                        }
                                        if (gif_on)
                                        {
                                            frm.gif_path = gif_path;
                                        }
                                        frm.AddCustomShow(reader["CustomShow"].ToString(), NextTipTime);
                                        if (ti.isTemp == 1)
                                        {
                                            frm.Text = "【" + reader["RunTimeStr"].ToString() + "】推迟的提醒";
                                            frm.LblRunTimeStr.Text = "【" + reader["RunTimeStr"].ToString() + "】推迟的提醒";
                                            frm.LblState.Text = "推迟的提醒";
                                            frm.LblState.ForeColor = System.Drawing.Color.Cyan;
                                        }
                                        else
                                        {
                                            frm.Text = "【" + reader["RunTimeStr"].ToString() + "】的提醒";
                                            frm.LblRunTimeStr.Text = "【" + reader["RunTimeStr"].ToString() + "】的提醒";
                                            if (EarlierMinute != 0)
                                            {
                                                if (reader["EarlierTipTime"].ToDateTime(DateTime.Now.AddYears(-10)) == dt_now_2)
                                                {
                                                    string info = "";
                                                    if (EarlierMinute <= 60)
                                                    { info = EarlierMinute + "分钟"; }
                                                    else if (EarlierMinute < 60 * 24)
                                                    { info = EarlierMinute / 60 + "小时"; }
                                                    else
                                                    { info = EarlierMinute / 60 / 24 + "天"; }
                                                    frm.LblState.Text = "提前【" + info + "】的提醒";
                                                    frm.LblState.ForeColor = System.Drawing.Color.Cyan;
                                                }
                                            }

                                        }
                                        frm.TxtTitle.Text = ti.MsgTitle;
                                        frm.labelTx1.Text = ti.MsgText;
                                        frm.Show();
                                        #endregion
                                    }
                                    else
                                    {
                                        #region 普通小窗口
                                        DbOp.FrmTip frm = new DbOp.FrmTip
                                        {
                                            Id = ti.id,
                                            IsTemp = ti.isTemp,
                                            RunTimeStr = ti.RunTimeStr
                                        };
                                        if (sound_on)
                                        {
                                            frm.PlaySound(sound_path);
                                        }
                                        if (ti.isTemp == 1)
                                        {
                                            frm.Text = "【" + reader["RunTimeStr"].ToString() + "】推迟的提醒";
                                            frm.LblState.Text = "推迟提醒";
                                            frm.LblState.ForeColor = System.Drawing.Color.Blue;
                                        }
                                        else
                                        {
                                            frm.Text = "【" + reader["RunTimeStr"].ToString() + "】的提醒";
                                        }
                                        frm.TxtTitle.Text = ti.MsgTitle;
                                        frm.labelTx1.Text = ti.MsgText;
                                        frm.Show();
                                        #endregion
                                    }
                                }
                            }
                            if (ti.isTemp == 1)//如果是临时提醒,则删除
                            {
                                db.ExecuteNonQuery("delete from Dingshi where id=" + ti.id);
                            }
                            #region 执行动作
                            if (_run_file != "")
                            {
                                if (ActionId == "Speaker")
                                {
                                    #region 语音朗读
                                    Thread th = new Thread(delegate () { Speak(_run_file); });
                                    th.Start();
                                    void Speak(string text)
                                    {
                                        try
                                        {
                                            var spVoices = new COM.SpVoice()
                                            {
                                                Rate = Itrycn_Info.SpeakerRate,
                                                Volume = Itrycn_Info.SpeakerVolume
                                            };
                                            if (Itrycn_Info.Speaker != "")
                                            {
                                                spVoices.SetVoices(Itrycn_Info.Speaker);
                                            }
                                            spVoices.Speak(text, COM.SpVoice.Flags.SVSFlagsAsync);
                                        }
                                        catch
                                        {
                                        }
                                    }
                                    #endregion
                                }
                                else
                                {
                                    RyFiles.RunFile(_run_file, _run_param);
                                }
                            }
                            #endregion
                            #endregion
                        }
                        TipChanged();
                    }
                }
                db.Free();
                #endregion
                if (Itrycn_Info.CalcWorkInfo)
                {
                    CalcWorkInfo(dt_now);
                }
            }
            else if (dt_now.Second == 40)
            {
                if (dt_now.Minute == 0)
                {
                    UpdateTipTime(true);
                }
            }
            TimeComplete = true;
        }
        DateTime lastRunTime = DateTime.Now.AddDays(-1);
        bool last_fullscreen = false;
        bool last_idle = false;
        /// <summary>
        /// 计算工作信息
        /// </summary>
        /// <param name="dt_now"></param>
        private void CalcWorkInfo(DateTime dt_now)
        {
            var idle = ryCommon.RySystem.GetLastInputTime() / 1000;
            DateTime dt_now2 = dt_now.AddSeconds(-dt_now.Second).AddMilliseconds(-dt_now.Millisecond);
            int stype = 0;
            if (idle>=60)
            {
                stype = 0;
            }
            else { stype = 1; }
            DataProvider mydb = new DataProvider();
            IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
            if (db.ConnDb(TimeClock.Itrycn_Db.WorkInfo_ConnStr) == 1)
            {
                RyQuickSQL mySQL = new RyQuickSQL("WorkInfo");
                mySQL.AddField("StartTime", dt_now2.AddMinutes(-1));
                mySQL.AddField("EndTime", dt_now2);
                mySQL.AddField("stype", stype);
                mySQL.AddField("totalSecond", 60);
                db.ExecuteNonQuery(mySQL.GetInsertSQL());
            }
            db.Free();
        }
        /// <summary>
        /// 时间循环一轮是否结束,结束后才能开始下一轮
        /// </summary>
        bool TimeComplete = true;
        /// <summary>
        /// 开始休息时间
        /// </summary>
        DateTime dt_start_idle = DateTime.Now;
        /// <summary>
        /// 添加休息记录
        /// </summary>
        /// <param name="info"></param>
        private void AddRestRecord(RestInfo info)
        {
            if(Itrycn_Db.list_rest.Count>1000)
            {
                Itrycn_Db.list_rest.RemoveAt(0);
            }
            Itrycn_Db.list_rest.Add(info);
            OnRestDataChanged?.Invoke(this, new EventArgs());
        }
        /// <summary>
        ///最近一次是否是休息状态
        /// </summary>
        private bool last_IsRestNowing = Itrycn_Info.IsRestNowing;
        /// <summary>
        /// 最近一次开始休息的时间
        /// </summary>
        private DateTime last_StartRestTime = DateTime.Now;
        private void Timer1_Tick(object sender, EventArgs e)
        {

        }
    }
    public class TimeInfo
    {
        public int id = 0;
        public int isTemp = 0;
        public DateTime RunTime;
        public DateTime StartTime;
        public string MsgText;
        public string MsgTitle;
        public string RunTimeStr;
        public string ActionId = "";
        public string File = "";
        public string Pram = "";
        public bool isSysAction = false;
        public bool Cancel { get; set; } = false;
    }
    public class RestInfo
    {
        public DateTime Time = DateTime.Now;
        /// <summary>
        /// 经历多少秒
        /// </summary>
        public int UserSecondTime = 0;
        /// <summary>
        /// 0为进入空闲,1为退出空闲,2为进入休息,3为退出休息,4表示推迟休息
        /// </summary>
        public int Mode = 0;
        private string GetTime(int second)
        {
            if(second<60)
            {
                return second+"秒";
            }
            if (second < 3600)
            {
                int minute = second / 60;
                int _second = second % 60;
                if (_second == 0)
                { return minute + "分钟"; }
                else
                {
                    return minute + "分钟" + _second + "秒";
                }
            }
            if (second < 3600*24)
            {
                int hour = second / 3600;
                int _second = (second-hour*3600);
                return hour + "小时" + GetTime(_second);
            }
            return "超过一天";
        }
        public string Mode_Str
        {
            get
            {
                switch(Mode)
                {
                    case 0:
                        return "开始空闲";
                    case 1:
                        return "空闲,共空闲["+ GetTime(UserSecondTime)+ "]";
                    case 2:
                        return "提早进入休息";
                    case 3:
                        return "休息,共休息[" + GetTime(UserSecondTime) + "]";
                    case 4:
                        return "推迟休息[" + GetTime(UserSecondTime) + "]"; 
                    default:
                        return "未知";
                }
            }
        }
        public string Time_Str
        {
            get
            {
                //需要修改此处
                var start_time = Mode == 4 ? Time : Time.AddSeconds(-UserSecondTime);
                var end_time = Mode == 4 ? Time.AddSeconds(UserSecondTime) : Time;
                string time_str = "";
                if (start_time.Date == end_time.Date)
                {
                    if (start_time.IsInTime(end_time.Hour, end_time.Minute, end_time.Second))
                    {
                        time_str = start_time.ToString("yyyy年MM月dd日 HH:mm:ss");
                    }
                    else
                    {
                        time_str = start_time.ToString("yyyy年MM月dd日 HH:mm:ss") + " - " + end_time.ToString("HH:mm:ss");
                    }
                }
                else if (start_time.Date.AddDays(1) == Time.Date)
                {
                    time_str = start_time.ToString("yyyy年MM月dd日 HH:mm:ss") + " - 次日 " + end_time.ToString("HH:mm:ss");
                }
                else
                {
                    time_str = start_time.ToString("yyyy年MM月dd日 HH:mm:ss") + " - " + end_time.ToString("yyyy年MM月dd日 HH:mm:ss");
                }
                return time_str;
            }
        }
    }
}
