using ryCommon;
using ryCommonDb;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace TimeClock.DbOp
{
    public partial class FrmTimeView : Form
    {
        string orderSQL = "order by addTime desc";
        string tableName = "Dingshi";
        public FrmTimeView()
        {
            InitializeComponent();
            for (int i = 1; i <= 12; i++)
            {
                imageList1.Images.Add(i.ToString(), Itrycn_Db.GetGroupImg(i.ToString()));
            }
            _RestTip_On = Itrycn_Info.RestTip_On;
            if (Itrycn_Info.RestTip_On)
            {
                LblNextRestTime.Text = DateTime.Now.AddSeconds(Itrycn_Info.Timer_index).ToString("HH:mm:ss");
                LblNextRestTime.ForeColor = Color.Blue;
            }
            else
            {
                _RestTip_On = Itrycn_Info.RestTip_On;
                LblNextRestTime.Text = "未开启休息提醒"; LblNextRestTime.ForeColor = Color.Red;
            }
            OlvRestTime.AspectGetter = delegate (object x) { return ((RestInfo)x).Time_Str; };
            OlvRestText.AspectGetter = delegate (object x) { return ((RestInfo)x).Mode_Str; };
            OlvHolidayTime.AspectGetter = delegate (object x) { return ((HolidayInfo)x).Title; };
            OlvHolidayContent.AspectGetter = delegate (object x) { return ((HolidayInfo)x).Content; };
            LvHoliday.FormatRow+=delegate(object sender2, BrightIdeasSoftware.FormatRowEventArgs e2)
            {
                var row = (HolidayInfo)e2.Model;
                if (row.ForeColor != Color.Black)
                {
                    e2.Item.ForeColor = row.ForeColor;
                }
            };
            OlvTipsDingshi.AspectGetter = delegate (object x) { return ((TipInfo)x).RunTimeStr; };
            OlvTipsTitle.AspectGetter = delegate (object x) { return ((TipInfo)x).MsgTitle; };
            OlvTipsNextTipTime.AspectGetter = delegate (object x) { return ((TipInfo)x).NextTipTimeStr; };
            OlvTipsAttr.AspectGetter = delegate (object x) { return ((TipInfo)x).Attr; };
            LvTips.FormatRow += delegate (object sender3, BrightIdeasSoftware.FormatRowEventArgs e3)
            {
                var row = (TipInfo)e3.Model;
                if (!row.Enabled)
                {
                    e3.Item.ForeColor = Color.Gray ;
                }
                else
                {
                    if(row.NextTipTime.Value<=DateTime.Now)
                    {
                        e3.Item.ForeColor = Color.Red;
                    }
                }
            };
            LvTips.FormatCell += delegate (object sender4, BrightIdeasSoftware.FormatCellEventArgs e4)
            {
                if (e4.Column == OlvTipsAttr)
                {
                    e4.SubItem.ForeColor = Color.Gray;
                }
            };
            OlvTodoTitle.AspectGetter = delegate (object x) { return ((TipInfo)x).MsgTitle; };
            OlvTodoStartTime.AspectGetter = delegate (object x) {
                var dt = ((TipInfo)x).StartTime;
                if (dt == null) { return "现在"; }
                return dt.Value.ToDateTimeStr();
            };
            OlvTodoEndTime.AspectGetter = delegate (object x) {
                var dt = ((TipInfo)x).EndTime;
                if (dt == null) { return "无限期"; }
                return dt.Value.ToDateTimeStr();
            };
            OlvTodoState.AspectGetter = delegate (object x) { return ((TipInfo)x).State_Str; };
            LvTodo.FormatRow += delegate (object sender5, BrightIdeasSoftware.FormatRowEventArgs e5)
            {
                var row = (TipInfo)e5.Model;
                var state = row.State_Str;
                Color color = Color.Black;
                switch (state)
                {
                    case "任务已过期":
                        color = Color.Red;
                        break;
                    case "任务未开始":
                        color = Color.Gray;break;
                    case "已完成":
                        color = Color.Gray;
                        e5.Item.Font = new Font(LvTodo.Font, FontStyle.Strikeout);
                        break;
                    case "任务作废":
                         color = Color.Gray;
                        break;
                }
                e5.Item.ForeColor = color;
            };
            OlvStickyTitle.AspectGetter = delegate (object x) { return ((TipInfo)x).MsgTitle; };
            OlvStickyIsShow.AspectGetter = delegate (object x) { return ((TipInfo)x).Enabled?"是":""; };
            OlvStickyAddTime.AspectGetter = delegate (object x) { return ((TipInfo)x).StartTime.Value; };
            OlvDateName.AspectGetter = delegate (object x) { return ((HolidayInfo)x).Title; };
            OlvDateContent.AspectGetter = delegate (object x) { return ((HolidayInfo)x).Content; };
            LvDate.FormatCell += delegate (object sender6, BrightIdeasSoftware.FormatCellEventArgs e6)
            {
                if (e6.Column == OlvDateName)
                {
                    e6.SubItem.Font = new Font(LvDate.Font, FontStyle.Bold);
                }
                else if (e6.Column == OlvDateContent)
                {
                    var row = (HolidayInfo)e6.Model;
                    if(row.Title.StartsWith("节日"))
                    {
                        e6.SubItem.ForeColor = Color.Blue;
                    }
                   // e6.SubItem.ForeColor = 
                }
            };
        }
        #region 需要修改的内容
        private void RySearch1_OnSearch(object sender, EventArgs e)
        {
            //需要修改此处
            NoUpdateList = true;
            LoadDb("(MsgText like @SearchText or MsgTitle like @SearchText)");
            NoUpdateList = false;
        }

        private void CtlMyPage1_OnPageChange(object sender, EventArgs e)
        {
            #region 重新载入数据
            LvTips.ClearObjects();
            List<TipInfo> list_tips = new List<TipInfo>();
            DataProvider mydb = new DataProvider();
            IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
            if (db.ConnDb(TimeClock.Itrycn_Db.SQLConnStr) == 1)
            {
                DataSet ds = db.ReadData(ctlMyPage1.GetSQLText, ctlMyPage1.T_Parameters);
                Font font_base = LvTips.Font;
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow row = ds.Tables[0].Rows[i];
                    list_tips.Add(new TipInfo() { 
                        Id = row["id"].ToInt(),
                        MsgTitle= row["MsgTitle"].ToString(),
                        RunTimeStr = row["RunTimeStr"].ToString(),
                        EarlierMinute= row["EarlierMinute"].ToInt(),
                        Enabled = row["Enabled"].ToBool(),
                        NextTipTime = row["NextTipTime"].ToDateTime(),
                        Modtype = row["modtype"].ToInt()
                    });
                }
                db.Free();
                LvTips.AddObjects(list_tips);
            }
            #endregion
        }
        /// <summary>
        /// 获得最近的几个提醒
        /// </summary>
        private void GetLastTipList()
        {
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(Itrycn_Db.SQLConnStr) == 1)
            {
                RyQuickSQL mySQL = new RyQuickSQL("Dingshi");
                mySQL.AddParameter("@date", DateTime.Now);
                mySQL.AddParameter("@enddate", DateTime.Now.AddDays(7));
                DataSet ds = db.ReadData("select * from Dingshi where NextTipTime>=@date and NextTipTime<@enddate and Enabled=1 and NoShow<>1 and TipClose=0 order by NextTipTime asc limit 5", mySQL);
                if (!mydb.HaveData(ds))
                {
                    //BtnNoTip.Visible = true;
                }
                else
                {
                    // BtnNoTip.Visible = false;
                }
                int icount = 0;
                List<Label> lbl_list = new List<Label>() { LblTipLine1, LblTipLine2, LblTipLine3, LblTipLine4, LblTipLine5 };
                List<Panel> pnl_list = new List<Panel>() { PnlTipLine1, PnlTipLine2, PnlTipLine3, PnlTipLine4, PnlTipLine5 };
                List<Label> time_list = new List<Label>() { LblTipTime1, LblTipTime2, LblTipTime3, LblTipTime4, LblTipTime5 };
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    icount++;
                    DataRow row = ds.Tables[0].Rows[i];
                    lbl_list[i].Text = row["MsgTitle"].ToString();
                    DateTime dt = row["NextTipTime"].ToDateTime();
                    if (dt.Date == DateTime.Now.Date)
                    {
                        time_list[i].Text = dt.ToString("HH:mm");
                        time_list[i].ForeColor = Color.DodgerBlue;
                        lbl_list[i].ForeColor = Color.Blue;
                    }
                    else if (dt.AddDays(-1).Date == DateTime.Now.Date)
                    {
                        time_list[i].Text = "明 天"; time_list[i].ForeColor = Color.DimGray; lbl_list[i].ForeColor = Color.DimGray;
                    }
                    else if (dt.AddDays(-2).Date == DateTime.Now.Date)
                    {
                        time_list[i].Text = "后 天"; time_list[i].ForeColor = Color.DimGray; lbl_list[i].ForeColor = Color.DimGray;
                    }
                    else
                    { time_list[i].Text = dt.ToString("MM-dd"); time_list[i].ForeColor = Color.DimGray; lbl_list[i].ForeColor = Color.DimGray; }
                    pnl_list[i].Visible = true;
                }
                for (int i = icount; i < 5; i++)
                {
                    pnl_list[i].Visible = false;
                }
                db.Free();
            }
        }
        private void GetRow(TipInfo row_tip)
        {
            #region 重新载入数据
            DataProvider mydb = new DataProvider();
            IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
            if (db.ConnDb(TimeClock.Itrycn_Db.SQLConnStr) == 1)
            {
                DataSet ds = db.ReadData("select * from " + tableName + " where id=" + row_tip.Id);
                if (mydb.HaveData(ds))
                {
                    DataRow row = ds.Tables[0].Rows[0];
                    row_tip.NextTipTime= row["NextTipTime"].ToDateTime(); 
                    row_tip.Modtype = row["modtype"].ToInt();
                    row_tip.RunTimeStr= row["RunTimeStr"].ToString();
                    row_tip.MsgTitle = row["MsgTitle"].ToString();
                    row_tip.EarlierMinute = row["EarlierMinute"].ToInt();
                    row_tip.Enabled= row["Enabled"].ToInt()==1;
                    row_tip.UpdateNextTipTimeStr();
                    LvTips.RefreshObject(row_tip);
                }
                db.Free();
            }
            #endregion
        }
        private void GetRow_Todo(TipInfo row_todo)
        {
            #region 重新载入数据
            DataProvider mydb = new DataProvider();
            IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
            if (db.ConnDb(TimeClock.Itrycn_Db.SQLConnStr) == 1)
            {
                DataSet ds = db.ReadData("select * from ToDo where id=" + row_todo.Id);
                var dt_base = new DateTime(1970, 1, 1);
                if (mydb.HaveData(ds))
                {
                    DataRow row = ds.Tables[0].Rows[0];
                    var startTime = row["startTime"].ToInt64();
                    var endTime = row["endTime"].ToInt64();
                    var startTime_dt = dt_base.AddSeconds(startTime);
                    var endTime_dt = dt_base.AddSeconds(endTime);
                    row_todo.StartTime = startTime == 0 ? (DateTime?)null : startTime_dt;
                    row_todo.EndTime = endTime == 0 ? (DateTime?)null : endTime_dt;
                    row_todo.state = row["state"].ToInt();
                    LvTodo.RefreshObject(row_todo);
                }
                db.Free();
            }
            #endregion
        }
        #endregion
        public void LoadDb(string whereSQL)
        {
            NoUpdateList = true;
            string _whereSQL = whereSQL;
            _whereSQL += " and TempTip<>1";
            var item = ctlTreeView1.GetNodeItem(ctlTreeView1.SelectedNode);
            string m_KeyWord = ctlTreeView1.FormatKeysInfo(item.Keys);
            if (m_KeyWord != "")
            {
                _whereSQL += " and GroupKey like @KeyName";
            }
            else
            {
                if (ctlTreeView1.SelectedNode != null)
                {
                    if (ctlTreeView1.SelectedNode.Name == "nokeys")
                    {
                        _whereSQL += " and (GroupKey='' or GroupKey is null)";
                    }
                }
            }
            if (ChkNoShow.Checked)
            {
                _whereSQL += " and (Enabled=1 and NextTipTime>@NextTipTime)";
            }
            DataProvider mydb = new DataProvider();
            IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
            if (db.ConnDb(TimeClock.Itrycn_Db.SQLConnStr) == 1)
            {
                #region 重新载入数据
                db.AddParameter("SearchText", "%" + rySearch1.Text + "%");
                db.AddParameter("KeyName", "%" + m_KeyWord + "%");
                db.AddParameter("NextTipTime", DateTime.Now);
                ctlMyPage1.RecordCount = db.GetCount(tableName, _whereSQL);
                ctlMyPage1.T_Parameters = db.GetParameter();
                ctlMyPage1.SQLText = db.GetPageSQL(tableName, _whereSQL, orderSQL);
                ctlMyPage1.SQLText2 = db.GetPageSQL2(tableName, _whereSQL, orderSQL);
                ctlMyPage1.GotoPageIndex(1);
                #endregion
            }
            db.Free();
            NoUpdateList = false;
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            FrmTimeAdd frm = new FrmTimeAdd(imageList1)
            {
                Text = "添加定时",
                Icon = Icon,
                isAdd = 1
            };
            frm.SetGroup(ctlTreeView1.FormatKeysInfo(ctlTreeView1.GetNodeItem(ctlTreeView1.SelectedNode).Keys));
            frm.mr = new ModalForm(this, frm);
            frm.mr.OnDialogResult += new ModalForm.DialogResultHandler((object t, DialogResult dg) => {
                if (dg == DialogResult.OK)
                {
                    rySearch1.PerformClick();
                    GetLastTipList();
                    dr = DialogResult.OK;
                }
            });
            frm.mr.ShowModal();
        }

        private void BtnEdit_Click(object sender, EventArgs e)
        {
            var row = (TipInfo)LvTips.SelectedObject;
            if (row==null) { return; }
            int selectId = row.Id;
            int index = LvTips.IndexOf(row);
            FrmTimeAdd frm = new FrmTimeAdd(imageList1)
            {
                Text = "修改定时",
                Icon = Icon,
                isAdd = 0
            };
            frm.GetInfo(selectId);
            frm.mr = new ModalForm(this, frm);
            frm.mr.OnDialogResult += new ModalForm.DialogResultHandler((object t, DialogResult dg) => {
                if (dg == DialogResult.OK)
                {
                    GetRow(row);
                    GetLastTipList();
                    dr = DialogResult.OK;
                }
            });
            frm.mr.ShowModal();
        }
        public DialogResult dr = DialogResult.None;
        private void BtnDel_Click(object sender, EventArgs e)
        {
            var list = LvTips.SelectedObjects;
            if (list.Count==0) { MessageBox.Show("请先选择要删除的项。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; }
            if (MessageBox.Show("确定要删除选定项吗？一旦删除将不可恢复。", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
            {
                return;
            }
            NoUpdateList = true;
            DataProvider mydb = new DataProvider();
            IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
            if (db.ConnDb(TimeClock.Itrycn_Db.SQLConnStr) == 1)
            {
                for (int i = list.Count - 1; i >= 0; i--)
                {
                    string selectId = ((TipInfo)list[i]).Id.ToString();
                    var ds = db.ReadData("select * from " + tableName + " where id=" + selectId);
                    if(mydb.HaveData(ds))
                    {
                        var row = mydb.GetData(ds);
                        ryCommon.Storage tStor = new Storage(row["SetXML"].ToString());
                        tStor.SelectNodeBySet();
                        var ImgPath = tStor.GetAttrValue("showpic", "");
                        if (ImgPath.Length > 0 && ImgPath.IndexOfEx("<imgfolder>") == 0)
                        {
                            RyFiles.DeleteFile(ImgPath.Replace(Itrycn_Info.UserDbFolder + "\\Images", "<imgfolder>").Replace(Application.StartupPath, "<app>"));
                        }
                    }
                    db.DelById(tableName, selectId);
                }
                LvTips.RemoveObjects(list);
                GetLastTipList();
                dr = DialogResult.OK;
            }
            db.Free();
            NoUpdateList = false;
        }
        bool ProcUse = false;
        private void FrmView_Load(object sender, EventArgs e)
        {
            if (Custom.DonateVisabled)
            {
                LblAbout.Text = "捐助";
            }
            chinaCalendar1.HolidayFolder = Itrycn_Info.SysDbFolder + "\\Holidays";
            Itrycn_Info.TipViewHandle = Handle;
            TimeClock.Itrycn_Db.CreateTable();
            Text = Custom.AppTitle;
            var aaa= Itrycn_Db.GetSetting("TipGroup", "");
            ctlTreeView1.LoadFromXMLText(Itrycn_Db.GetSetting("TipGroup", ""));
            ctlTreeView1.Nodes.Add("nokeys", "未分组的提醒", 0);
            ryCommon.Storage myStor = new Storage(Itrycn_Db.GetSetting("Setting2", ""));
            myStor.SelectNodeBySet();
            ProcUse = true;
            按下次提醒时间排序ToolStripMenuItem.Checked = myStor.GetAttrValue("NextTipTimeSort", false);
            ChkNoShow.Checked = myStor.GetAttrValue("NoShow", false);
            if (按下次提醒时间排序ToolStripMenuItem.Checked)
            {
                orderSQL = "order by Enabled desc,NextTipTime asc";
            }
            else
            { orderSQL = "order by addTime desc"; }
            ProcUse = false;
            rySearch1.PerformClick();
            InitDate(DateTime.Now);
            timer1.Enabled = true;
            GetLastTipList();
            GetLatelyHoliday();
            chinaCalendar1.DateTime = DateTime.Now;
            ChinaCalendar1_OnClickItem(chinaCalendar1, DateTime.Now);
            LoadRestRecord();
        }
        public void LoadRestRecord()
        {
            LvRest.ClearObjects();
            List<RestInfo> list = new List<RestInfo>();
            for (int i = Itrycn_Db.list_rest.Count - 1; i >= 0; i--)
            {
                var row = Itrycn_Db.list_rest[i];
                list.Add(row);
            }
            LvRest.AddObjects(list);
        }
        private void GetLatelyHoliday()
        {
            LvHoliday.ClearObjects();
            DataProvider mydb = new DataProvider();
            IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
            if (db.ConnDb(TimeClock.Itrycn_Db.Holidays_ConnStr) == 1)
            {
                AddDate(DateTime.Now, "今天");
                AddDate(DateTime.Now.AddDays(1), "明天");
                AddDate(DateTime.Now.AddDays(2), "后天");
                AddDate(DateTime.Now.AddDays(3), "3天后(" + DateTime.Now.AddDays(3).ToString("MM-dd") + ")");
                AddDate(DateTime.Now.AddDays(4), "4天后(" + DateTime.Now.AddDays(4).ToString("MM-dd") + ")");
                AddDate(DateTime.Now.AddDays(5), "5天后(" + DateTime.Now.AddDays(5).ToString("MM-dd") + ")");
                AddDate(DateTime.Now.AddDays(6), "6天后(" + DateTime.Now.AddDays(6).ToString("MM-dd") + ")");
                void AddDate(DateTime dt, string date_str)
                {
                    DataSet ds = db.ReadData(Itrycn_Info.GetHolidaySQL(dt));
                    string jq = ChinaDate.GetSolarTerm(dt);
                    if (jq != "")
                    {
                        AddList(date_str, "节气:" + jq, "", Color.Blue);
                    }
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        DataRow row = ds.Tables[0].Rows[i];
                        AddList(date_str, row["name"].ToString(), row["des"].ToString(), Color.Blue);
                    }
                }
                void AddList(string name, string des, string tooltip, Color color)
                {
                    if (des == "") { return; }
                    LvHoliday.AddObject(new HolidayInfo() { Title=name,Content=des, ToolTip=tooltip, ForeColor=color});
                }
            }
            db.Free();
        }
        private void 添加数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnAdd.PerformClick();
        }

        private void 修改数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnEdit.PerformClick();
        }

        private void 删除数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnDel.PerformClick();
        }

        private void 快速提醒ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BtnQuickAdd.PerformClick();
        }

        private void BtnQuickAdd_Click(object sender, EventArgs e)
        {
            FrmQuickAdd frm = new FrmQuickAdd();
            frm.mr = new ModalForm(this, frm);
            frm.mr.OnDialogResult += new ModalForm.DialogResultHandler((object t, DialogResult dg) => {
                if (dg == DialogResult.OK)
                {
                    rySearch1.PerformClick();
                    GetLastTipList();
                    dr = DialogResult.OK;
                }
            });
            frm.mr.ShowModal();
        }

        private void ListView1_DoubleClick(object sender, EventArgs e)
        {
            btnEdit.PerformClick();
        }

        private void LnkSetting_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            DbOp.FrmSetting frm = new DbOp.FrmSetting();
            frm.FormClosing += new FormClosingEventHandler((object t, FormClosingEventArgs dg) => {
                if (frm.dr == DialogResult.OK)
                {
                    Itrycn_Info.ReadSetting();
                    InitDate(DateTime.Now);
                }
            });
            RyForm.ShowOne(frm);
        }
        private void SetTipState(int enabled)
        {
            var list = LvTips.SelectedObjects;
            if (list.Count == 0) { return; }
            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");
                mySQL.AddField("Enabled", enabled);
                for (int i = 0; i < list.Count; i++)
                {
                    var tipinfo = (TipInfo)list[i];
                    tipinfo.Enabled = enabled != 0;
                    db.ExecuteNonQuery(mySQL.GetUpdateSQL() + " where id=" + tipinfo.Id, mySQL);
                }
                LvTips.RefreshObjects(list);
            }
            db.Free();
        }
        private void 启用提醒ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetTipState(1);
            GetLastTipList();
            dr = DialogResult.OK;
        }

        private void 禁用提醒ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetTipState(0);
            GetLastTipList();
            dr = DialogResult.OK;
        }

        private void 复制提醒ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var row = (TipInfo)LvTips.SelectedObject;
            if (row == null) { return; }
            int selectId = row.Id;
            int index =LvTips.IndexOf(row);
            FrmTimeAdd frm = new FrmTimeAdd(imageList1)
            {
                Text = "复制并添加定时",
                Icon = Icon,
                isAdd = 1
            };
            frm.GetInfo(selectId);
            frm.mr = new ModalForm(this, frm);
            frm.mr.OnDialogResult += new ModalForm.DialogResultHandler((object t, DialogResult dg) => {
                if (dg == DialogResult.OK)
                {
                    rySearch1.PerformClick();
                    GetLastTipList();
                    dr = DialogResult.OK;
                }
            });
            frm.mr.ShowModal();
        }

        private void CtlTreeView1_OnDataChange(object sender, EventArgs e)
        {
            Itrycn_Db.SetSetting("TipGroup", ctlTreeView1.SaveToXmlText());
        }

        private void CtlTreeView1_OnBeforeDelGroup(object sender, ref bool Cancel)
        {
            string select_keys = ctlTreeView1.GetKey();//获取所有选择的关键词
        }

        private void CtlTreeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            rySearch1.PerformClick();

        }

        private void CtlTreeView1_OnBeforeAddGroup(object sender, ref bool Cancel)
        {
            if (ctlTreeView1.SelectedNode == null) { return; }
            if (ctlTreeView1.SelectedNode.Parent == null && ctlTreeView1.SelectedNode.PrevNode != null)
            { Cancel = true; }
        }

        private void LblAbout_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (!Custom.DonateVisabled)
            {
                MessageBox.Show(Custom.AboutText.Replace("#softname#", Custom.AppTitle).Replace("#ver#", "V" + RySoft.VersionStr), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            FrmAbout frm = new FrmAbout();
            frm.ShowDialog();
        }

        private void BtnMore_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            Point p = new Point(0, btn.Height);
            MenuMore.Show(btn, p);
        }

        private void 按下次提醒时间排序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ProcUse) { return; }
            按下次提醒时间排序ToolStripMenuItem.Checked = !按下次提醒时间排序ToolStripMenuItem.Checked;
            if (按下次提醒时间排序ToolStripMenuItem.Checked)
            {
                orderSQL = "order by Enabled desc,NextTipTime asc";
            }
            else
            { orderSQL = "order by addTime desc"; }
            ryCommon.Storage myStor = new Storage(Itrycn_Db.GetSetting("Setting2", ""));
            myStor.SelectNodeBySet();
            myStor.SetAttrValue("NextTipTimeSort", 按下次提醒时间排序ToolStripMenuItem.Checked);
            Itrycn_Db.SetSetting("Setting2", myStor.XMLText);
            rySearch1.PerformClick();
        }

        private void ChkNoShow_CheckedChanged(object sender, EventArgs e)
        {
            if (ProcUse) { return; }
            ryCommon.Storage myStor = new Storage(Itrycn_Db.GetSetting("Setting2", ""));
            myStor.SelectNodeBySet();
            myStor.SetAttrValue("NoShow", ChkNoShow.Checked);
            Itrycn_Db.SetSetting("Setting2", myStor.XMLText);
            rySearch1.PerformClick();
        }

        private void ContextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            var list = LvTips.SelectedObjects;
            toolStripMenuItem2.Visible = list.Count > 0;
            if (list.Count == 1)
            {
                var tipinfo = (TipInfo)list[0];
                启用提醒ToolStripMenuItem.Visible = !tipinfo.Enabled;
                禁用提醒ToolStripMenuItem.Visible = tipinfo.Enabled;
                启用提醒ToolStripMenuItem.Text = "启用该提醒";
                禁用提醒ToolStripMenuItem.Text = "禁用该提醒";
                复制提醒ToolStripMenuItem.Visible = true;
                修改数据ToolStripMenuItem.Visible = true;
                删除数据ToolStripMenuItem.Text = "删除该提醒";
            }
            else
            {
                启用提醒ToolStripMenuItem.Text = "启用选定的提醒";
                禁用提醒ToolStripMenuItem.Text = "禁用选定的提醒";
                删除数据ToolStripMenuItem.Text = "删除选定的提醒";
                复制提醒ToolStripMenuItem.Visible = false;
                修改数据ToolStripMenuItem.Visible = false;
                if (list.Count > 1 && list.Count <= 20)
                {
                    int enabled_count = 0;
                    for (int i = 0; i < list.Count; i++)
                    {
                        var tipinfo = (TipInfo)list[i];
                        if (tipinfo.Enabled) { enabled_count++; }
                    }
                    if (list.Count == enabled_count)
                    { 启用提醒ToolStripMenuItem.Visible = false; 禁用提醒ToolStripMenuItem.Visible = true; }
                    else if (enabled_count == 0)
                    { 启用提醒ToolStripMenuItem.Visible = true; 禁用提醒ToolStripMenuItem.Visible = false; }
                    else
                    {
                        启用提醒ToolStripMenuItem.Visible = true;
                        禁用提醒ToolStripMenuItem.Visible = true;
                    }
                }
                else if (list.Count > 20)
                {
                    启用提醒ToolStripMenuItem.Visible = true;
                    禁用提醒ToolStripMenuItem.Visible = true;
                }
                else
                {
                    启用提醒ToolStripMenuItem.Visible = false;
                    禁用提醒ToolStripMenuItem.Visible = false;

                }
            }
        }
        private void InitDate(DateTime dt_now)
        {
            var week_count = RyDate.GetWeekCount(Itrycn_Info.CurrWeekDate, DateTime.Now) + 1;
            LblTime.Text = dt_now.ToString("HH:mm:ss");
            LblDate.Text = dt_now.ToString("yyyy-MM-dd dddd") + "(第" + week_count + "周)";
            LblLunarDate.Text = ChinaDate.GetChinaDate(dt_now);
        }
        bool second_0 = false;//是否到0秒整
        bool _RestTip_On = false;
        string next_rest_str = "";
        private void Timer1_Tick(object sender, EventArgs e)
        {
            var dt_now = DateTime.Now;
            LblTime.Text = dt_now.ToString("HH:mm:ss");
            if (Itrycn_Info.RestTip_On)
            {
                var _next_rest_str = DateTime.Now.AddSeconds(Itrycn_Info.Timer_index).ToString("HH:mm:ss");
                if (next_rest_str != _next_rest_str)
                {
                    LblNextRestTime.Text = _next_rest_str;
                    next_rest_str = _next_rest_str;
                    LblNextRestTime.ForeColor = Color.Blue;
                }
            }
            else
            {
                if (_RestTip_On != Itrycn_Info.RestTip_On)
                {
                    _RestTip_On = Itrycn_Info.RestTip_On;
                    LblNextRestTime.Text = "未开启休息提醒"; LblNextRestTime.ForeColor = Color.Red;
                }
            }
            if (!second_0)
            {
                if (dt_now.Second >= 0 && dt_now.Second <= 5) //每分钟整
                {
                    second_0 = true;
                    InitDate(dt_now);
                    if (chromeTabControl1.SelectedTab == tabPage1 && LvTodo.GetItemCount() > 0)
                    {
                        LvRest.Refresh();
                    }
                    UpdateList2();
                    #region 0秒整
                    if (dt_now.Hour == 0 && dt_now.Minute == 0)
                    {
                        GetLastTipList();
                        GetLatelyHoliday();
                        chinaCalendar1.DateTime = DateTime.Now;
                    }
                    #endregion
                }
            }
            else
            {
                if (dt_now.Second > 30)
                {
                    second_0 = false;
                }
            }
        }
        bool NoUpdateList = false;
        /// <summary>
        /// 更新列表
        /// </summary>
        private void UpdateList()
        {
            if (NoUpdateList) { return; }
            var list = LvTips.ObjectsList;
            for (int i = 0; i < list.Count; i++)
            {
                if (NoUpdateList) { break; }
                TipInfo info = (TipInfo)list[i];
                if (info.NextTipTime <= DateTime.Now)
                {
                    if (info.Modtype != TipType.tip_thetime)
                    {
                        GetRow(info);
                    }
                }
            }
        }
        /// <summary>
        /// 更新列表
        /// </summary>
        private void UpdateList2()
        {
            if (NoUpdateList) { return; }
            var list = LvTips.ObjectsList;
            for (int i = 0; i < list.Count; i++)
            {
                if (NoUpdateList) { break; }
                TipInfo info = (TipInfo)list[i];
                if (info.NextTipTime == null) { continue; }
                if (!info.Enabled) { continue; }
                if (info.Modtype == TipType.tip_winstart && info.NextTipTime < DateTime.Now)
                {

                }
                else
                {
                    info.UpdateNextTipTimeStr() ;
                }
            }
            LvTips.RefreshObjects(list);
        }
        protected override void WndProc(ref System.Windows.Forms.Message msg)
        {
            switch (msg.Msg)
            {
                case 17189: //处理消息
                    {
                        #region  是我们的消息
                        switch (msg.WParam.ToInt32())
                        {
                            case 100://
                                #region 是我们的消息
                                switch (msg.LParam.ToInt32())
                                {
                                    case API.Msgs.Msg_OnTimeTipChanged:
                                        GetLastTipList();
                                        UpdateList();
                                        break;
                                }
                                #endregion
                                break;
                        }
                        #endregion
                    }
                    break;
                default:
                    base.WndProc(ref msg);//调用基类函数处理非自定义消息。
                    break;
            }
        }
        private void FrmTimeView_FormClosing(object sender, FormClosingEventArgs e)
        {
            Itrycn_Info.TipViewHandle = IntPtr.Zero;
        }


        private void ChinaCalendar1_OnClickItem(object sender, DateTime dt)
        {
            richTextBox1.Text = "";
            #region 九九算法
            int year = dt.Year;
            if (dt.Month < 6)
            {
                year = year - 1;
            }
            ChinaDate.GetJieQiInAYear(year, 23, out int AMonth, out int ADay, out int AHour, out int AMinitue); //获取上一个冬至
            var dt_dongzhi = new DateTime(year, AMonth, ADay);
            string jiujiu = "";
            if (dt >= dt_dongzhi)
            {
                int jiu_day = (dt.Date - dt_dongzhi).TotalDays.ToInt() / 9;
                if (jiu_day < 9)
                {
                    jiujiu = "一二三四五六七八九".Substring(jiu_day, 1) + "九";
                    int jiu_day2 = (dt.Date - dt_dongzhi).TotalDays.ToInt() % 9;
                    jiujiu += " 第" + (jiu_day2 + 1) + "天";
                    jiujiu = "(" + jiujiu + ")";
                }
            }
            #endregion
            string sanfu_str = "";//三伏信息
            if (dt.Month == 7 || dt.Month == 8)
            {
                DateTime dt_1fu = ChinaDate.Get3Fu(dt.Year, 0);
                DateTime dt_2fu = dt_1fu.AddDays(10);
                DateTime dt_3fu = ChinaDate.Get3Fu(dt.Year, 2);
                if (dt >= dt_1fu && dt < dt_2fu)
                {
                    int sf_daycount = ((dt - dt_1fu).TotalDays.ToInt() + 1);
                    int sf_daycount2 = 10 - sf_daycount;
                    if (sf_daycount2 == 0)
                    {
                        sanfu_str = "初伏第" + sf_daycount + "天,初伏最后一天";
                    }
                    else { sanfu_str = "初伏第" + sf_daycount + "天,还剩" + sf_daycount2 + "天"; }
                }
                else if (dt >= dt_2fu && dt < dt_3fu)
                {
                    int sf_daycount = ((dt - dt_2fu).TotalDays.ToInt() + 1);
                    int sf_daycount2 = (dt_3fu - dt).TotalDays.ToInt() - 1;
                    if (sf_daycount2 == 0)
                    {
                        sanfu_str = "中伏第" + sf_daycount + "天,中伏最后一天";
                    }
                    else
                    {
                        sanfu_str = "中伏第" + sf_daycount + "天,还剩" + sf_daycount2 + "天";
                    }
                }
                else if (dt >= dt_3fu && dt < dt_3fu.AddDays(10))
                {
                    int sf_daycount = ((dt - dt_3fu).TotalDays.ToInt() + 1);
                    int sf_daycount2 = 10 - sf_daycount;
                    if (sf_daycount2 == 0)
                    {
                        sanfu_str = "末伏第" + sf_daycount + "天,末伏最后一天";
                    }
                    else
                    {
                        sanfu_str = "末伏第" + sf_daycount + "天,还剩" + sf_daycount2 + "天";
                    }
                }
            }
            int day = (dt.Date - DateTime.Now.Date).TotalDays.ToInt();
            string day_str = "";
            if (day == 0) { day_str = "今天"; }
            else if (day == 1) { day_str = "明天"; }
            else if (day == 2) { day_str = "后天"; }
            else if (day == -1) { day_str = "昨天"; }
            else if (day == -2) { day_str = "前天"; }
            else if (day > 0) { day_str = day + "天后"; }
            else if (day < 0) { day_str = (-day) + "天前"; }
            LvDate.ClearObjects();
            AddList("日期", dt.ToString("yyyy年MM月dd日 dddd") + jiujiu, "", Color.Black);
            if (sanfu_str != "")
            {
                AddList("三伏", sanfu_str, "", Color.Black);
            }
            AddList("农历", ChinaDate.GetChinaDate(dt), "", Color.Black);
            AddList("天数", "第" + dt.DayOfYear.ToString() + "天 第" + (RyDate.GetWeekCount(new DateTime(dt.Year, 1, 1), dt) + 1).ToString() + "周 (" + day_str + ")", "", Color.Black);
            AddList("星座", ChinaDate.GetXingzuo(dt), "", Color.Black);
            AddList("节气", ChinaDate.GetSolarTerm(dt), "", Color.Black);
            //AddList("农历节日", ChinaDate.GetChinaHoliday(dt), "");
            //AddList("公历节日", ChinaDate.GetHoliday(dt), "");
            //AddList("其它节日", ChinaDate.GetWeekHoliday(dt), "");
            DataProvider mydb = new DataProvider();
            IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
            if (db.ConnDb(TimeClock.Itrycn_Db.Holidays_ConnStr) == 1)
            {
                DataSet ds = db.ReadData(Itrycn_Info.GetHolidaySQL(dt));
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow row = ds.Tables[0].Rows[i];
                    AddList("节日" + (i + 1).ToString(), row["name"].ToString(), row["des"].ToString(), Color.Blue);
                    if (i == 0) { richTextBox1.Text = row["des"].ToString(); }
                }
            }
            db.Free();
            void AddList(string name, string des, string tooltip, Color color)
            {
                if (des == "") { return; }
                LvDate.AddObject(new HolidayInfo() {Title=name,Content=des,ToolTip=tooltip });
            }
        }


        private void LblGetRestRecord_Click(object sender, EventArgs e)
        {
            LoadRestRecord();
        }

        private void RySearch2_OnSearch(object sender, EventArgs e)
        {
            NoUpdateList = true;
            #region 重新载入数据
            LvTodo.ClearObjects();
            List<TipInfo> list = new List<TipInfo>();
            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("ToDo");
                mySQL.AddParameter("searchtext", "%" + rySearch2.Text + "%");
                DataSet ds = db.ReadData("select * from ToDo where name like @searchtext or des like @searchtext order by Sorts desc", mySQL);
                Font font_base = LvTips.Font;
                var dt_base = new DateTime(1970, 1, 1);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow row = ds.Tables[0].Rows[i];
                    var startTime = row["startTime"].ToInt64();
                    var endTime = row["endTime"].ToInt64();
                    var startTime_dt = dt_base.AddSeconds(startTime);
                    var endTime_dt = dt_base.AddSeconds(endTime);
                    list.Add(new TipInfo() { Id = row["id"].ToInt(), MsgTitle= row["Name"].ToString(), state = row["state"].ToInt(), StartTime = (startTime == 0 ? (DateTime?)null : startTime_dt), EndTime = (endTime == 0 ? (DateTime?)null : endTime_dt) });
                }
                db.Free();
            }
            #endregion
            LvTodo.AddObjects(list);
            NoUpdateList = false;
        }

        private void chromeTabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (chromeTabControl1.SelectedTab == tabPage1 &&LvTodo.GetItemCount() == 0)
            {
                rySearch2.PerformClick();
            }
            else if (chromeTabControl1.SelectedTab == TabSticky && LvSticky.GetItemCount() == 0)
            {
                rySearch_sticky.PerformClick();
            }
        }

        private void 添加待办ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmAddTodo frm = new FrmAddTodo()
            {
                Text = "添加待办",
                Icon = Icon,
                isAdd = 1
            };
            frm.mr = new ModalForm(this, frm);
            frm.mr.OnDialogResult += new ModalForm.DialogResultHandler((object t, DialogResult dg) => {
                if (dg == DialogResult.OK)
                {
                    rySearch2.PerformClick();
                }
            });
            frm.mr.ShowModal();
        }

        private void 修改待办ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var row = (TipInfo)LvTodo.SelectedObject;
            if (row==null) { return; }
            int selectId = row.Id;
            FrmAddTodo frm = new FrmAddTodo()
            {
                Text = "修改待办",
                Icon = Icon,
                isAdd = 0
            };
            frm.GetInfo(selectId.ToString());
            frm.mr = new ModalForm(this, frm);
            frm.mr.OnDialogResult += new ModalForm.DialogResultHandler((object t, DialogResult dg) => {
                if (dg == DialogResult.OK)
                {
                    GetRow_Todo(row);
                }
            });
            frm.mr.ShowModal();
        }

        private void 删除待办ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var list = LvTodo.SelectedObjects;
            if (list.Count == 0) { MessageBox.Show("请先选择要删除的项。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; }
            if (MessageBox.Show("确定要删除选定项吗？一旦删除将不可恢复。", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
            {
                return;
            }
            DataProvider mydb = new DataProvider();
            IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
            if (db.ConnDb(TimeClock.Itrycn_Db.SQLConnStr) == 1)
            {
                for (int i = list.Count - 1; i >= 0; i--)
                {
                    string selectId = ((TipInfo)list[i]).Id.ToString();
                    db.DelById("ToDo", selectId);
                    db.ExecuteNonQuery("delete from ToDo_logs where todo_id=" + selectId);
                }
                LvTodo.RemoveObjects(list);
            }
            db.Free();
        }
        private void ChangeState(int state)
        {
            var list = LvTodo.SelectedObjects;
            if (list.Count == 0) { MessageBox.Show("请先选择要操作的项。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; }
            DataProvider mydb = new DataProvider();
            IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
            if (db.ConnDb(TimeClock.Itrycn_Db.SQLConnStr) == 1)
            {
                int state_0_count = 0;
                for (int i = list.Count - 1; i >= 0; i--)
                {
                    var tipinfo = (TipInfo)list[i];
                    if (tipinfo.state == 0) { state_0_count++; }
                    int selectId = tipinfo.Id;
                    RyQuickSQL mySQL = new RyQuickSQL("ToDo");
                    mySQL.AddField("state", state);
                    db.ExecuteNonQuery(mySQL.GetUpdateSQL() + " where id=" + selectId + " and state=0", mySQL);
                    if (tipinfo.state == 0)
                    {
                        tipinfo.state = state;
                        Itrycn_Db.AddTodo_Log(selectId, "改变状态", "将任务状态设置为["+tipinfo.State_Str+"]");
                    }
                    GetRow_Todo(tipinfo);
                }
                if (state_0_count == 0)
                {
                    MessageBox.Show("只能操作未完成的项目。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            db.Free();
        }
        private void 任务完成ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChangeState(100);
        }

        private void 任务作废ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChangeState(-1);
        }

        private void 查看该待办操作记录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var row = (TipInfo)LvTodo.SelectedObject;
            if ((row == null)) { MessageBox.Show("请先选择要操作的项。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; }
            var selectId = row.Id.ToInt();
            FrmToDo_Log frm = new FrmToDo_Log();
            frm.Icon = Icon;
            frm.LoadDb(selectId);
            frm.ShowDialog();
        }

        private void RySearch_sticky_OnSearch(object sender, EventArgs e)
        {
            #region 重新载入数据
            LvSticky.ClearObjects();
            List<TipInfo>   list = new List<TipInfo>();
            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("Sticky");
                mySQL.AddParameter("searchtext", "%" + rySearch_sticky.Text + "%");
                DataSet ds = db.ReadData("select * from Sticky where name like @searchtext or Content like @searchtext order by addTime desc", mySQL);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow row = ds.Tables[0].Rows[i];
                    list.Add(new TipInfo()
                    {
                        Id = row["id"].ToInt(),
                        MsgTitle = row["Content"].ToString().Replace("\r", "").Replace("\n", ""),
                        Enabled = row["DeskShow"].ToString() == "1",
                        StartTime = row["addTime"].ToDateTime(),
                    });
                }
                LvSticky.AddObjects(list);
                db.Free();
            }
            #endregion
        }

        private void 添加便笺ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TimeClock.DbOp.FrmSticky frm = new FrmSticky();
            frm.ProcUse = true;
            frm.Id = -1;
            frm.IsAdd = true;
            frm.StickyBackColor = Color.FromArgb(255, 255, 192);
            frm.Location =new Point(this.Left,this.Top+20);
            frm.Show();
            frm.ProcUse = false;
        }

        private void 删除便笺ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var list =LvSticky.SelectedObjects;
            if (list.Count== 0) { return; }
            if (MessageBox.Show("确定要删除选定项吗？一旦删除将不可恢复。", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
            {
                return;
            }
            DataProvider mydb = new DataProvider();
            IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
            if (db.ConnDb(TimeClock.Itrycn_Db.SQLConnStr) == 1)
            {
                for (int i = list.Count - 1; i >= 0; i--)
                {
                    var row= (TipInfo)list[i];
                    db.DelById("Sticky", row.Id);
                    #region 找到相应窗体并关闭
                    bool find = false;
                    for (int m = 0; m < Itrycn_Info.StickyList.Count; m++)
                    {
                        switch (Itrycn_Info.StickyList[m])
                        {
                            case TimeClock.DbOp.FrmSticky frm:
                                if (frm.Id == row.Id)
                                {
                                    frm.Close();
                                    find = true;
                                }
                                break;
                        }
                        if (find) { break; }
                    } 
                    #endregion
                }
                LvSticky.RemoveObjects(list);
            }
            db.Free();
        }

        private void 在桌面显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var list = LvSticky.SelectedObjects;
            if (list.Count == 0) { return; }
            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("Sticky");
                mySQL.AddField("DeskShow",1);
                for (int i = list.Count - 1; i >= 0; i--)
                {
                    var row = (TipInfo)list[i];
                    row.Enabled = true;
                    db.ExecuteNonQuery(mySQL.GetUpdateSQL()+" where id="+ row.Id, mySQL);
                    #region 查找是否已存在相应窗体
                    bool find = false;
                    for (int m = 0; m < Itrycn_Info.StickyList.Count; m++)
                    {
                        switch (Itrycn_Info.StickyList[m])
                        {
                            case TimeClock.DbOp.FrmSticky frm:
                                if (frm.Id == row.Id)
                                {
                                    find = true;
                                }
                                break;
                        }
                        if (find) { break; }
                    }
                    #endregion
                    if(!find)
                    {
                        TimeClock.DbOp.FrmSticky frm = new FrmSticky();
                        frm.ProcUse = true;
                        frm.LoadSticky(false, row.Id);
                        RyForm.ShowNoActiveWindow(frm);
                        frm.ProcUse = false;
                    }
                }
                LvSticky.RefreshObjects(list);
            }
            db.Free();
        }

        private void 关闭桌面显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var list = LvSticky.SelectedObjects;
            if (list.Count == 0) { return; }
            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("Sticky");
                mySQL.AddField("DeskShow", 0);
                for (int i = list.Count - 1; i >= 0; i--)
                {
                    var row = (TipInfo)list[i];
                    row.Enabled = false;
                    db.ExecuteNonQuery(mySQL.GetUpdateSQL() + " where id=" + row.Id, mySQL);
                    #region 查找是否已存在相应窗体
                    bool find = false;
                    for (int m = 0; m < Itrycn_Info.StickyList.Count; m++)
                    {
                        switch (Itrycn_Info.StickyList[m])
                        {
                            case TimeClock.DbOp.FrmSticky frm:
                                if (frm.Id == row.Id)
                                {
                                    frm.Close();
                                    find = true;
                                }
                                break;
                        }
                        if (find) { break; }
                    }
                    #endregion
                }
                LvSticky.RefreshObjects(list);
            }
            db.Free();
        }

        private void ctlTreeView1_OnBeforeEditGroup(object sender, ref bool Cancel)
        {
            if (ctlTreeView1.SelectedNode!=null && ctlTreeView1.SelectedNode.Name== "nokeys")
            {
                Cancel = true;
            }
        }

        private void LvTips_DoubleClick(object sender, EventArgs e)
        {
            btnEdit.PerformClick();
        }

        private void LvTips_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F1)
            {
                BtnQuickAdd.PerformClick();
            }
            else if (e.KeyCode == Keys.F2)
            {
                btnAdd.PerformClick();
            }
            else if (e.KeyCode == Keys.F3)
            {
                btnEdit.PerformClick();
            }
            else if (e.KeyCode == Keys.F4)
            {
                btnDel.PerformClick();
            }
            else if (e.KeyCode == Keys.F5)
            {
                复制提醒ToolStripMenuItem.PerformClick();
            }
        }

        private void LvDate_SelectedIndexChanged(object sender, EventArgs e)
        {
            var row= (HolidayInfo)LvDate.SelectedObject;
            if (row == null) { richTextBox1.Text = ""; return; }
            string HolidayName = row.Title;
            if (HolidayName == "节气")
            {
                DataProvider mydb = new DataProvider();
                IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
                if (db.ConnDb(TimeClock.Itrycn_Db.Holidays_ConnStr) == 1)
                {
                    RyQuickSQL mySQL = new RyQuickSQL("Holidays");
                    mySQL.AddField("Name", row.Content);
                    DataSet ds = db.ReadData("select * from Holidays where Name=@Name and sType=3", mySQL);
                    if (mydb.HaveData(ds))
                    {
                        richTextBox1.Text = ds.Tables[0].Rows[0]["des"].ToString();
                    }
                    else { richTextBox1.Text = ""; }
                }
                db.Free();
                return;
            }
            richTextBox1.Text = row.ToolTip;
        }
    }
    public class HolidayInfo
    {
        public int Id { get; set; } = 0;
        public string Title { get; set; } = "";
        public int Type { get; set; } = 0;
        public string TypeStr { get; set; } ="";
        public string Content { get; set; } = "";
        public string ToolTip { get; set; } = "";
        public Color ForeColor { get; set; } =Color.Black;
        public string Holiday_Time { get; set; } = "";
        public int StartYear { get; set; } = 0;
        public int EndYear { get; set; } = 0;
        private string _Holiday_Time_str = "";
        public string Holiday_Time_str
        {
            get
            {
                return _Holiday_Time_str;
            }
        }
        public void Update()
        {
            _Holiday_Time_str = "";
            switch (Type)
            {
                case 0:
                    if (Holiday_Time.Length == 4)
                    {
                        int day = Holiday_Time.Substring(2, 2).ToInt();
                        if (day == 0)
                        {
                            _Holiday_Time_str = Holiday_Time.Substring(0, 2).ToInt() + "月最后一天";
                        }
                        else
                        {
                            _Holiday_Time_str = Holiday_Time.Substring(0, 2).ToInt() + "月" + day + "日";
                        }
                    }
                    TypeStr = "公历节日";
                    break;
                case 1:
                    if (Holiday_Time.Length == 4)
                    {
                        _Holiday_Time_str = ChinaDate.GetMonth(Holiday_Time.Substring(0, 2).ToInt()) + ChinaDate.GetDay(Holiday_Time.Substring(2, 2).ToInt());
                    }
                    TypeStr = "农历节日";
                    break;
                case 2:
                    if (Holiday_Time.Length == 4)
                    {
                        _Holiday_Time_str = Holiday_Time.Substring(0, 2).ToInt() + "月";
                        var week = Holiday_Time.Substring(2, 1).ToInt();
                        if (week == 0) { _Holiday_Time_str += "最后一个"; }
                        else { _Holiday_Time_str += "第" + week + "个"; }
                        _Holiday_Time_str += "周" + RyDate.GetWeekName(Holiday_Time.Substring(3, 1).ToInt());
                    }
                    TypeStr = "星期节日";
                    break;
                case 3:
                    _Holiday_Time_str = "";
                    TypeStr = "节气";
                     break;
                default:
                    TypeStr = "未知节日";
                     break;
            }
        }
    }
    public class TipInfo
    {
        public int Id = 0;
        public string MsgTitle { get; set; } = "";
        public string RunTimeStr { get; set; } = "";
        public int EarlierMinute { get; set; } = 0;
        public void UpdateNextTipTimeStr()
        {
            if (!Enabled)
            {
                _NextTipTimeStr = "提醒已禁用";
            }
            else
            {
                if (NextTipTime == null) { _NextTipTimeStr= "";return; }
                bool out_run = false;
                if (Modtype == TipType.tip_winstart)
                {
                    if (NextTipTime.Value < DateTime.Now)
                    {
                        _NextTipTimeStr = "本次已执行完毕";
                        out_run = true;
                    }
                }
                if (!out_run)
                {
                    DateTime dt = NextTipTime.Value;
                    _NextTipTimeStr = Itrycn_Db.GetNextTipTimeStr(dt, false);
                }
            }
        }
        private bool _Enabled = true;
        public bool Enabled
        {
            get
            {
                return _Enabled;
            }
            set
            {
                if (_Enabled == value) { return; }
                _Enabled = value;
                UpdateNextTipTimeStr();
            }
        }
        private DateTime? _NextTipTime = null;
        public DateTime? NextTipTime
        {
            get { return _NextTipTime; }
            set
            {
                if (_NextTipTime == value) { return; }
                _NextTipTime = value;
                UpdateNextTipTimeStr();
            }
        }
        private string _NextTipTimeStr = "";
        public string NextTipTimeStr
        {
            get
            {
               return _NextTipTimeStr;
            }
        }
        public int Modtype = 0;
        /// <summary>
        /// 待办状态
        /// </summary>
        public int state = 0;
        /// <summary>
        /// 待办状态,显示具体内容
        /// </summary>
        public string State_Str
        {
            get
            {
                string state_str = "";
                switch (state)
                {
                    case 0:
                        if (EndTime!=null && EndTime.Value < DateTime.Now)
                        {
                            state_str = "任务已过期";
                        }
                        else if (StartTime!=null && StartTime.Value > DateTime.Now)
                        {
                            state_str = "任务未开始";
                        }
                        else
                        {
                            state_str = "进行中";
                        }
                        break;
                    case 100:
                        state_str = "已完成"; 
                        break;
                    case -1:
                        state_str = "任务作废"; 
                        break;
                }
                return state_str;
            }
        }
        public DateTime? StartTime = null;
        public DateTime? EndTime = null;
        public string Attr
        {
            get
            {
                string attr = "";
                #region 提前提醒
                if (EarlierMinute != 0)
                {
                    if (EarlierMinute < 60)
                    {
                        attr += "提前" + EarlierMinute + "分钟";
                    }
                    else if (EarlierMinute < 60 * 24)
                    {
                        attr += "提前" + EarlierMinute / 60 + "小时";
                    }
                    else
                    {
                        attr += "提前" + EarlierMinute / 60 / 24 + "天";
                    }
                }
                #endregion
                return attr;
            }
        }
    }
}
