using NAudio.Wave;
using ryCommon;
using ryCommonDb;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace TimeClock.DbOp
{
    public partial class FrmTimeAdd : Form
    {
        public string tableName = "Dingshi";
        public ModalForm mr = null;
        private string ImgPath = "";
        public FrmTimeAdd(ImageList imglist)
        {
            InitializeComponent();
            RbTheTime.Checked = true;
            DtDay.Value = DateTime.Now.AddMinutes(10);
            DtTime.Value = DateTime.Now.AddMinutes(10);
            Dt_StartDate.Value = DateTime.Now;
            Dt_StartTime.Value = DateTime.Now;
            CbbShowPic.Enabled = false;
            BtnSelectPic.Enabled = false;
            CbbWeekIndexByMonth.SelectedIndex = 0;
            CbbWeekByMonth.SelectedIndex = 0;
            CbbAction.Items.AddRange(new ActionInfo[] {
                new ActionInfo { Title = "不执行任何动作",Id="NoAction" },
                new ActionInfo { Title = "重启电脑", Id = "Reboot" },
                new ActionInfo { Title = "关闭电脑",Id = "Shutdown" },
                new ActionInfo { Title = "注销电脑", Id = "Logoff" },
                new ActionInfo { Title = "打开网页",Id="OpenUrl", ShowFileUI=true, File_Title="打开网址:" },
                new ActionInfo { Title = "打开文件",Id="OpenFile",File_Filter="所有文件|*.*", ShowFileUI=true,ShowPramUI=true },
                new ActionInfo { Title = "电脑静音",Id="Mute_On" },
                new ActionInfo { Title = "取消静音",Id="Mute_Off" },
                new ActionInfo { Title = "语音朗读",Id="Speaker", ShowFileUI=true, File_Title="朗读文本:" },
                new ActionInfo { Title = "时间同步",Id="TimeSync" },
            });
            for (int i = 0; i < Custom.ActionList.Count; i++)
            {
                CbbAction.Items.Add(Custom.ActionList[i]);
            }
            CbbAction.SelectedIndex = 0;
            #region 是否提前提醒
            CbbEarlierTime.Items.Clear();
            CbbEarlierTime.Items.AddRange(new EarlierTimeInfo[] {
                new EarlierTimeInfo { Title = "1分钟",Minute=1 },
                new EarlierTimeInfo { Title = "2分钟",Minute=2 },
                new EarlierTimeInfo { Title = "3分钟",Minute=3 },
                new EarlierTimeInfo { Title = "5分钟",Minute=5 },
                new EarlierTimeInfo { Title = "10分钟",Minute=10},
                new EarlierTimeInfo { Title = "15分钟",Minute=15 },
                new EarlierTimeInfo { Title = "30分钟",Minute=30 },
                new EarlierTimeInfo { Title = "1小时",Minute=60 },
                new EarlierTimeInfo { Title = "2小时",Minute=120 },
                new EarlierTimeInfo { Title = "3小时",Minute=180 },
                new EarlierTimeInfo { Title = "1天",Minute=60*24 },
                new EarlierTimeInfo { Title = "2天",Minute=60*24*2 },
                new EarlierTimeInfo { Title = "3天",Minute=60*24*3 },
                new EarlierTimeInfo { Title = "5天",Minute=60*24*5 },
                new EarlierTimeInfo { Title = "7天",Minute=60*24*7 },
                new EarlierTimeInfo { Title = "15天",Minute=60*24*15 },
                new EarlierTimeInfo { Title = "30天",Minute=60*24*30 },
            });
            CbbEarlierTime.Enabled = false;
            CbbEarlierTime.SelectedIndex = 0;
            CbbEarlierTime.ForeColor = CbbEarlierTime.Enabled ? Color.Black : Color.Gray;
            #endregion
            LblTimeStr.Text = "软件将在以下时刻进行提醒:" + GetRunTimeStr(out string week2, out int modtype);
            CbbDisturbed.SelectedIndex = 0;
            CbbLunar.SelectedIndex = 0;
            proc_AfterSelect = true;
            ctlTreeView1.ImageList = imglist;
            pictureBox1.Image = Itrycn_Db.GetGroupImg("1");
            TxtKeys.Text = "所有提醒";
            ctlTreeView1.LoadFromXMLText(Itrycn_Db.GetSetting("TipGroup", ""));
            proc_AfterSelect = false;
            TxtKeys.MouseDown += TxtKeys_MouseDown;
            pictureBox1.MouseDown += TxtKeys_MouseDown;
            PnlKeys.MouseDown += TxtKeys_MouseDown;
            this.MouseDown += KeysLeave_MouseDown;
            txtName.MouseDown += KeysLeave_MouseDown;
            TxtContent.MouseDown += KeysLeave_MouseDown;
            tabControl1.MouseDown += KeysLeave_MouseDown;
            if (System.IO.Directory.Exists(Itrycn_Info.UserDbFolder + @"\sound\"))
            {
                string[] files = System.IO.Directory.GetFiles(Itrycn_Info.UserDbFolder + @"\sound\");
                for (int i = 0; i < files.Length; i++)
                {
                    CbbSound.Items.Add(new SoundInfo() { Name = System.IO.Path.GetFileName(files[i]), Path = files[i] });
                }
            }
            if (System.IO.Directory.Exists(Itrycn_Info.SysDbFolder + @"\animation\sound\"))
            {
                string[] files = System.IO.Directory.GetFiles(Itrycn_Info.SysDbFolder + @"\animation\sound\");
                for (int i = 0; i < files.Length; i++)
                {
                    CbbSound.Items.Add(new SoundInfo() { Name = System.IO.Path.GetFileName(files[i]), Path = files[i] });
                }
                if(CbbSound.Items.Contains("默认提醒.wav"))
                {
                    CbbSound.Text = "默认提醒.wav";
                }
            }
            OlvCustomType.AspectGetter = (object x) =>
            {
                return ((CustomShowInfo)x).TypeStr;
            };
            OlvCustomTitle.AspectGetter = (object x) =>
            {
                return ((CustomShowInfo)x).Name;
            };
            OlvCustomContent.AspectGetter = (object x) =>
            {
                return ((CustomShowInfo)x).DateStr;
            };
            OlvNotDisturbTime.AspectGetter = (object x) =>
            {
                return ((DateInfo)x).TimeStr;
            };
            OlvNotDisturbDesc.AspectGetter = (object x) =>
            {
                return ((DateInfo)x).des;
            };
        }
        class SoundInfo
        {
            public string Name { get; set; }
            public string Path { get; set; }
            public override string ToString()
            {
                return Name;
            }
        }
        private void KeysLeave_MouseDown(object sender, MouseEventArgs e)
        {
            panelEx2.Visible = false;
        }

        private void TxtKeys_MouseDown(object sender, MouseEventArgs e)
        {
            panelEx2.Top = PnlKeys.Top + PnlKeys.Height;
            panelEx2.BringToFront();
            panelEx2.Visible = true;
        }

        public int isAdd = 1;
        public int selectId = -1;
        public void SetGroup(string groupkey)
        {
            proc_AfterSelect = true;
            ctlTreeView1.SelectedTreeByKey(groupkey);
            if (ctlTreeView1.SelectedNode != null)
            {
                if (ctlTreeView1.SelectedNode.ImageIndex != -1)
                {
                    pictureBox1.Image = Itrycn_Db.GetGroupImg(ctlTreeView1.ImageList.Images.Keys[ctlTreeView1.SelectedNode.ImageIndex]);
                    TxtKeys.Text = ctlTreeView1.SelectedNode.Text;
                }
            }
            proc_AfterSelect = false;
        }
        #region 需要修改
        public void GetInfo(int id)
        {
            selectId = id;
            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(tableName, id.ToString());
                if (mydb.HaveData(ds))
                {
                    DataRow reader = ds.Tables[0].Rows[0];
                    proc_AfterSelect = true;
                    ctlTreeView1.SelectedTreeByKey(reader["GroupKey"].ToString());
                    if(ctlTreeView1.SelectedNode!=null)
                    {
                        if (ctlTreeView1.SelectedNode.ImageIndex != -1)
                        {
                            pictureBox1.Image =Itrycn_Db.GetGroupImg(ctlTreeView1.ImageList.Images.Keys[ctlTreeView1.SelectedNode.ImageIndex]);
                            TxtKeys.Text = ctlTreeView1.SelectedNode.Text;
                        }
                    }
                    proc_AfterSelect = false;
                    #region 读取信息     
                    switch (reader["modtype"].ToInt())
                    {
                       case TipType.tip_minute:
                            RbMinute.Checked = true;
                         break;
                        case TipType.tip_hour:
                            RbHour.Checked = true;
                            break;
                        case TipType.tip_day:
                            RbDay.Checked = true;
                            break;
                        case TipType.tip_thetime:
                            RbTheTime.Checked = true;
                            break;
                        case TipType.tip_week:
                            RbWeek.Checked = true;
                            break;
                        case TipType.tip_month:
                            RbMonth.Checked = true;
                            break;
                        case TipType.tip_year:
                            RbYear.Checked = true;
                            break;
                        case TipType.tip_winstart:
                            RbWinStart.Checked = true;
                            break;
                    }

                    txtName.Text = reader["MsgTitle"].ToString();
                    TxtContent.Text = reader["MsgText"].ToString();
                    NumInterval.Value = reader["Interval"].ToDecimal();
                    DtDay.Value = reader["RunTime"].ToDateTime();
                    DtTime.Value = reader["RunTime"].ToDateTime();
                    Dt_StartDate.Value = reader["StartTime"].ToDateTime();
                    Dt_StartTime.Value = reader["StartTime"].ToDateTime();
                    ChkEnabled.Checked = reader["Enabled"].ToBool();
                    ChkAllowShow.Checked = !reader["NoShow"].ToBool();
                    #region 例外免打扰
                    ryCommon.Storage myExcept_XML = new Storage(reader["ExceptXML"].ToString());
                    myExcept_XML.SelectNodeBySet();
                    int ExceptionType = myExcept_XML.GetAttrValue("ExceptionType",0);
                    int iCount = myExcept_XML.GetAttrValue("ExceptionCount",0);
                    if (ExceptionType == 1) { CbbDisturbed.SelectedIndex = 1; } else { CbbDisturbed.SelectedIndex = 0; }
                    List<DateInfo> list_Except = new List<DateInfo>();
                    for (int m = 0; m < iCount; m++)
                    {
                        list_Except.Add(new DateInfo() { iType = myExcept_XML.GetAttrValue("ExType" + (m + 1).ToString(), 1),
                            start = myExcept_XML.GetAttrValue("ExStart" + (m + 1).ToString(),DateTime.Now),
                            end = myExcept_XML.GetAttrValue("ExEnd" + (m + 1).ToString(), DateTime.Now),
                            start_week = myExcept_XML.GetAttrValue("ExStartWeek" + (m + 1).ToString(),1),
                            end_week = myExcept_XML.GetAttrValue("ExEndWeek" + (m + 1).ToString(), 1),
                            des = myExcept_XML.GetAttrValue("Des" + (m + 1).ToString(), "")
                        });                   
                    }
                    LvNotDisturb.AddObjects(list_Except);
                    tabPage3.Text = "免打扰(" + list_Except.Count + ")";
                    #endregion
                    #region 自定义显示
                    ryCommon.Storage myCustomShow_XML = new Storage(reader["CustomShow"].ToString());
                    myCustomShow_XML.SelectNodeBySet();
                    iCount = myCustomShow_XML.GetAttrValue("Count", 0);
                    List<CustomShowInfo> list = new List<CustomShowInfo>();
                    for (int m = 0; m < iCount; m++)
                    {
                        list.Add(new CustomShowInfo()
                        {
                            Type = myCustomShow_XML.GetAttrValue("CsType" + (m + 1).ToString(), 1),
                            Name = myCustomShow_XML.GetAttrValue("CsName" + (m + 1).ToString(),""),
                            IsLunar = myCustomShow_XML.GetAttrValue("CsIsLunar" + (m + 1).ToString(),false),
                            Year = myCustomShow_XML.GetAttrValue("CsYear" + (m + 1).ToString(), 1),
                            Month = myCustomShow_XML.GetAttrValue("CsMonth" + (m + 1).ToString(), 1),
                            Day = myCustomShow_XML.GetAttrValue("CsDay" + (m + 1).ToString(), 1)
                        });
                    }
                    LvCustom.AddObjects(list);
                    tabPage4.Text = "自定义显示(" + list.Count + ")";
                    #endregion
                    #endregion
                    ryCommon.Storage tStor = new Storage(reader["SetXML"].ToString());
                    tStor.SelectNodeBySet();
                    ChkSound.Checked=tStor.GetAttrValue("sound_on", true);
                    string sound = tStor.GetAttrValue("sound", @"tip.wav");
                    for (int i = 0; i < CbbSound.Items.Count; i++)
                    {
                        var item = (SoundInfo)CbbSound.Items[i];
                        if(item.Path== sound) { CbbSound.SelectedItem = item;  break; }
                    }
                    if (CbbSound.SelectedIndex==-1)
                    {
                        CbbSound.Items.Add(new SoundInfo() {Name= sound,Path= sound });
                        CbbSound.SelectedIndex = CbbSound.Items.Count - 1 ;
                    }
                    ChkShowPic.Checked = tStor.GetAttrValue("showpic_on", false);
                    ImgPath= tStor.GetAttrValue("showpic", "");
                    CbbShowPic.Text = ImgPath;
                    ChkNoShowTip.Checked = tStor.GetAttrValue("NoShowTip", false);
                    string ActionId = tStor.GetAttrValue("ActionId");
                    string File = tStor.GetAttrValue("File");
                    string Pram = tStor.GetAttrValue("Pram");
                    if (RbWeek.Checked)
                    {
                        string week = tStor.GetAttrValue("week");
                        if (week.Length == 7)
                        {
                            ChkW1.Checked = week.IndexOf("1", 0) == 0;
                            ChkW2.Checked = week.IndexOf("1", 1) == 1;
                            ChkW3.Checked = week.IndexOf("1", 2) == 2;
                            ChkW4.Checked = week.IndexOf("1", 3) == 3;
                            ChkW5.Checked = week.IndexOf("1", 4) == 4;
                            ChkW6.Checked = week.IndexOf("1", 5) == 5;
                            ChkW7.Checked = week.IndexOf("1", 6) == 6;
                        }
                    }
                    if (RbMonth.Checked)
                    {
                        var month_mode = tStor.GetAttrValue("month_mode", 0);
                        if (month_mode == 0)
                        {
                            RbDayByMonth.Checked = true;
                            ChkRevDay.Checked = tStor.GetAttrValue("revday", false);
                            int day = tStor.GetAttrValue("day", -1);
                            if (day.IsInRange(0, 29))
                            {
                                CbbDay.SelectedIndex = day;
                            }
                        }
                        else
                        {
                            RbWeekByMonth.Checked = true;
                            var week_m= tStor.GetAttrValue("week_m", 1);
                            if (!week_m.IsInRange(1, 7)) { week_m = 1; }
                            CbbWeekByMonth.SelectedIndex = week_m - 1;
                            var weekindex_m= tStor.GetAttrValue("weekindex_m", 1);
                            if(!weekindex_m.IsInRange(1,4) && weekindex_m != -1) { weekindex_m = 1; }
                            if (weekindex_m > 0) { CbbWeekIndexByMonth.SelectedIndex = weekindex_m - 1; }
                            else { CbbWeekIndexByMonth.SelectedIndex = CbbWeekIndexByMonth.Items.Count - 1; }
                            ChkWeekTypeByMonth.Checked= tStor.GetAttrValue("weektype_m",false);
                        }
                    }
                    if (RbYear.Checked)
                    {
                        ChkRevDay_y.Checked = tStor.GetAttrValue("revday", false);
                        int IsLunar = tStor.GetAttrValue("IsLunar", 0);
                        if (IsLunar.IsInRange(0, 1))
                        {
                            CbbLunar.SelectedIndex = IsLunar;
                        }
                        int day = tStor.GetAttrValue("day", -1);
                        if (day.IsInRange(0, CbbDay_y.Items.Count-1))
                        {
                            CbbDay_y.SelectedIndex = day;
                        }
                        int Month = tStor.GetAttrValue("Month", 0);
                        if (Month.IsInRange(0, CbbMonth_y.Items.Count - 1))
                        {
                            CbbMonth_y.SelectedIndex = Month;
                        }
                    }
                    CbbFile.Text = File;
                    CbbPram.Text = Pram;
                    for(int i=0;i<CbbAction.Items.Count;i++)
                    {
                        ActionInfo item = (ActionInfo)CbbAction.Items[i];
                        if(item.Id==ActionId)
                        {
                            CbbAction.SelectedIndex = i;
                            break;
                        }
                    }
                    #region 提前提醒
                    int EarlierMinute = reader["EarlierMinute"].ToInt();
                    if (EarlierMinute == 0)
                    { ChkEarlierTime.Checked = false; }
                    else
                    {
                        ChkEarlierTime.Checked = true;
                        for (int i = 0; i < CbbEarlierTime.Items.Count; i++)
                        {
                            EarlierTimeInfo item = (EarlierTimeInfo)CbbEarlierTime.Items[i];
                            if (item.Minute == EarlierMinute)
                            {
                                CbbEarlierTime.SelectedIndex = i;
                                break;
                            }
                        }
                    } 
                    #endregion
                    LblTimeStr.Text = "软件将在以下时刻进行提醒:" + GetRunTimeStr(out string week2, out int modtype);
                }
            }
            db.Free();
        }
        private string GetRunTimeStr(out string week,out int modtype)
        {
            week = GetValue(ChkW1) + GetValue(ChkW2) + GetValue(ChkW3) + GetValue(ChkW4) + GetValue(ChkW5) + GetValue(ChkW6) + GetValue(ChkW7);
            string week_title = "";
            modtype = 0;
            if (RbWeek.Checked)
            {
                if (week == "0000000")
                {
                    MessageBox.Show("请选择要提醒的星期。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return "";
                }
                string week_chs = "一二三四五六日";
                //int pos0= week.IndexOf("0");
                int notip_count = 0;
                
                for (int i = 0; i < 7; i++)
                {
                    int pos = week.IndexOf("1", i);
                    if (pos == i)
                    {
                        week_title += "周" + week_chs.Substring(pos, 1) + ",";
                    }
                    else { notip_count++; }
                }
                if (week=="1111100")
                {
                    week_title = "周一到周五";
                }
                else if (week == "1111101")
                {
                    week_title = "周日到周五";
                }
                else if (week == "1111110")
                {
                    week_title = "周一到周六";
                }
                else
                {
                    week_title = week_title.Trim(',');
                }
            }
            int interval = NumInterval.Value.ToInt();
            string runtime_str = "";
            if (RbMinute.Checked) { modtype = TipType.tip_minute; runtime_str =(interval == 1 ? "每" : "每过" + interval) + "分钟"; }
            else if (RbHour.Checked)
            {
                modtype = TipType.tip_hour;
                runtime_str = (interval == 1 ? "每" : "每过" + interval) + "小时";
                if (Dt_StartTime.Value.Minute == 0)
                {
                    runtime_str += " 整点";
                }
                else { runtime_str +="的"+ Dt_StartTime.Value.ToString("mm") + "分"; }
            }
            else if (RbDay.Checked) { modtype = TipType.tip_day; runtime_str = (interval == 1 ? "每" : "每过" + interval) + "天 " + Dt_StartTime.Value.ToString("HH:mm"); }
            else if (RbTheTime.Checked) { modtype = TipType.tip_thetime; runtime_str = DtDay.Value.ToString("yyyy年MM月dd日") + " " + DtTime.Value.ToString("HH:mm"); }
            else if (RbWeek.Checked) { modtype = TipType.tip_week; runtime_str = (interval == 1 ? "每" : "每过" + interval) + "周 " + week_title + " " + Dt_StartTime.Value.ToString("HH:mm"); }
            else if (RbMonth.Checked)
            {
                modtype = TipType.tip_month;
                if (RbDayByMonth.Checked)
                {
                    runtime_str = (interval == 1 ? "每" : "每过" + interval + "个") + "月 " + (ChkRevDay.Checked ? "倒数" : "") + CbbDay.Text + " " + Dt_StartTime.Value.ToString("HH:mm");
                }
                else if (RbWeekByMonth.Checked)
                {
                    runtime_str = (interval == 1 ? "每" : "每过" + interval+"个") + "月 " + CbbWeekIndexByMonth.Text +(ChkWeekTypeByMonth.Checked?"的 ":"")+ CbbWeekByMonth.Text + " " + Dt_StartTime.Value.ToString("HH:mm");
                }
            }
            else if (RbYear.Checked)
            {
                modtype = TipType.tip_year;
                runtime_str = CbbLunar.Text + " " + (interval == 1 ? "每" : "每过" + interval) + "年";
                if (ChkRevDay_y.Checked && CbbLunar.SelectedIndex == 1 && CbbMonth_y.SelectedIndex == 11 && CbbDay_y.SelectedIndex == 0)
                { runtime_str += "除夕"; }
                else
                { runtime_str += CbbMonth_y.Text+(ChkRevDay_y.Checked ? "倒数" : "") + CbbDay_y.Text; }
                runtime_str += " " + Dt_StartTime.Value.ToString("HH:mm");
            }
            else if (RbWinStart.Checked)
            {
                modtype = TipType.tip_winstart;
                runtime_str =(interval ==0? "开机启动后" : "开机启动"+ interval+"分钟后");
            }
            return runtime_str;
            string GetValue(CheckBox chk)
            {
                return chk.Checked.ToInt().ToString();
            }
        }
        private void BtnOK_Click(object sender, EventArgs e)
        {
            if (txtName.Text.Length==0)
            {
                MessageBox.Show("提醒标题不能为空。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if(PnlFile.Visible)
            {
                if(CbbFile.Text.Length==0)
                {
                    MessageBox.Show("必须选择文件或输入网址。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            if (RbTheTime.Checked)
            {
                if(DtDay.Value.Date.AddHours(DtTime.Value.Hour).AddMinutes(DtTime.Value.Minute)<DateTime.Now)
                {
                    MessageBox.Show("当前提醒时间已经过期。","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                    return;
                }
                if(LvNotDisturb.GetItemCount()>0)
                {
                    switch (MessageBox.Show("具体时间提醒，免打扰功能将无效,确定要删除免打扰吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                    {
                        case DialogResult.No:
                            return;
                        case DialogResult.Yes:
                            LvNotDisturb.ClearObjects();
                            tabPage3.Text = "免打扰(" + LvNotDisturb.GetItemCount() + ")";
                            break;
                    }
                }
            }
            int interval = NumInterval.Value.ToInt();
            string runtime_str = GetRunTimeStr(out string week, out int modtype);
            if (runtime_str.Length==0) { return; }
            var pic_path = CbbShowPic.Text;
            if(pic_path.Length>0 && pic_path.IndexOfEx("<")!=0)
            {
                if(System.IO.File.Exists(pic_path))
                {
                    var toPath= RyFiles.AddFileToFolder(pic_path, Itrycn_Info.UserDbFolder+"\\Images",false,out bool OK);
                    if(OK)
                    {
                        pic_path = toPath.Replace(Itrycn_Info.UserDbFolder + "\\Images","<imgfolder>").Replace(Application.StartupPath, "<app>");
                    }
                }
            }
            if (ImgPath.Length > 0 && ImgPath.IndexOfEx("<imgfolder>") == 0 && ImgPath != pic_path)
            {
                RyFiles.DeleteFile(ImgPath.Replace("<imgfolder>", Itrycn_Info.UserDbFolder + "\\Images").Replace("<app>", Application.StartupPath));
            }
            RyQuickSQL mySQL = new RyQuickSQL(tableName);
            mySQL.AddField("MsgTitle", txtName.Text);
            mySQL.AddField("MsgText", TxtContent.Text);
            mySQL.AddField("modtype", modtype);
            mySQL.AddField("Interval", interval);
            mySQL.AddField("RunTime",DtDay.Value.Date.AddHours(DtTime.Value.Hour).AddMinutes(DtTime.Value.Minute));
            mySQL.AddField("StartTime",Dt_StartDate.Value.Date.AddHours(Dt_StartTime.Value.Hour).AddMinutes(Dt_StartTime.Value.Minute));
            mySQL.AddField("RunTimeStr", runtime_str);
            mySQL.AddField("Clac_TipTime",0);
            mySQL.AddField("NextTipAddMinute", 0);
            if(ChkEarlierTime.Checked)
            { mySQL.AddField("EarlierMinute", ((EarlierTimeInfo)CbbEarlierTime.SelectedItem).Minute); }
            else
            { mySQL.AddField("EarlierMinute", 0); }
            mySQL.AddField("TipClose", 0);
            mySQL.AddField("NextTipTime", DtDay.Value.Date.AddHours(DtTime.Value.Hour).AddMinutes(DtTime.Value.Minute));
            #region 例外免打扰
            if (LvNotDisturb.GetItemCount() == 0) { mySQL.AddField("ExceptXML", ""); }
            else
            {
                ryCommon.Storage myExcept_XML = new Storage();
                myExcept_XML.SelectNodeBySet();
                myExcept_XML.SetAttrValue("ExceptionType", CbbDisturbed.SelectedIndex);
                myExcept_XML.SetAttrValue("ExceptionCount", LvNotDisturb.GetItemCount());
                var list_except = LvNotDisturb.ObjectsList;
                for (int m = 0; m < list_except.Count; m++)
                {
                    DateInfo info = (DateInfo)list_except[m];
                    myExcept_XML.SetAttrValue("ExType" + (m + 1).ToString(), info.iType);
                    myExcept_XML.SetAttrValue("ExStart" + (m + 1).ToString(), info.start);
                    myExcept_XML.SetAttrValue("ExEnd" + (m + 1).ToString(), info.end);
                    myExcept_XML.SetAttrValue("ExStartWeek" + (m + 1).ToString(), info.start_week);
                    myExcept_XML.SetAttrValue("ExEndWeek" + (m + 1).ToString(), info.end_week);
                    myExcept_XML.SetAttrValue("Des" + (m + 1).ToString(), info.des);
                }
                mySQL.AddField("ExceptXML", myExcept_XML.XMLText);
            }
            #endregion
            #region 自定义显示
            if (LvCustom.GetItemCount() == 0) { mySQL.AddField("CustomShow", ""); }
            else
            {
                ryCommon.Storage myCustomShow_XML = new Storage();
                myCustomShow_XML.SelectNodeBySet();
                myCustomShow_XML.SetAttrValue("Count", LvCustom.GetItemCount());
                var list_custom = LvCustom.ObjectsList ;
                for (int m = 0; m < list_custom.Count; m++)
                {
                    CustomShowInfo info = (CustomShowInfo)list_custom[m];
                    myCustomShow_XML.SetAttrValue("CsType" + (m + 1).ToString(), info.Type);
                    myCustomShow_XML.SetAttrValue("CsName" + (m + 1).ToString(), info.Name);
                    myCustomShow_XML.SetAttrValue("CsIsLunar" + (m + 1).ToString(), info.IsLunar);
                    myCustomShow_XML.SetAttrValue("CsYear" + (m + 1).ToString(), info.Year);
                    myCustomShow_XML.SetAttrValue("CsMonth" + (m + 1).ToString(), info.Month);
                    myCustomShow_XML.SetAttrValue("CsDay" + (m + 1).ToString(), info.Day);
                }
                mySQL.AddField("CustomShow", myCustomShow_XML.XMLText);
            }
            #endregion
            #region 动作XML
            ActionInfo item = (ActionInfo)CbbAction.SelectedItem;
            ryCommon.Storage tStor = new Storage();
            tStor.SelectNodeBySet();
            tStor.SetAttrValue("ActionId", item.Id);
            tStor.SetAttrValue("File", CbbFile.Text);
            tStor.SetAttrValue("Pram", CbbPram.Text);
            tStor.SetAttrValue("week", week);      
            tStor.SetAttrValue("sound_on", ChkSound.Checked);
            switch(CbbSound.SelectedItem)
            {
                case SoundInfo sound_item:
                    tStor.SetAttrValue("sound", sound_item.Path);
                    break;
                case string sound_item:
                    tStor.SetAttrValue("sound", sound_item);
                    break;
                default:
                    tStor.SetAttrValue("sound", "");
                    break;
            }
            tStor.SetAttrValue("showpic_on", ChkShowPic.Checked);
            tStor.SetAttrValue("showpic", pic_path);
            tStor.SetAttrValue("NoShowTip", ChkNoShowTip.Checked);
            if (RbYear.Checked)
            {
                tStor.SetAttrValue("IsLunar", CbbLunar.SelectedIndex);
                tStor.SetAttrValue("Month", CbbMonth_y.SelectedIndex);
                tStor.SetAttrValue("day", CbbDay_y.SelectedIndex);
                tStor.SetAttrValue("revday", ChkRevDay_y.Checked);
            }
            else
            {
                if (RbDayByMonth.Checked)
                {
                    tStor.SetAttrValue("month_mode", 0);
                    tStor.SetAttrValue("revday", ChkRevDay.Checked);
                    tStor.SetAttrValue("day", CbbDay.SelectedIndex);
                }
                else if (RbWeekByMonth.Checked)
                {
                    tStor.SetAttrValue("month_mode", 1);
                    if (CbbWeekIndexByMonth.SelectedIndex <= 3)
                    {
                        tStor.SetAttrValue("weekindex_m", CbbWeekIndexByMonth.SelectedIndex+1);
                    }
                    else
                    {
                        tStor.SetAttrValue("weekindex_m", -1);
                    }
                    tStor.SetAttrValue("week_m", CbbWeekByMonth.SelectedIndex+1);
                    tStor.SetAttrValue("weektype_m",ChkWeekTypeByMonth.Checked);
                }
            }
            #endregion
            mySQL.AddField("SetXML", tStor.XMLText);
            mySQL.AddField("Enabled",ChkEnabled.Checked);
            mySQL.AddField("NoShow", !ChkAllowShow.Checked);
            string keys = ctlTreeView1.FormatKeysInfo(ctlTreeView1.GetNodeItem(ctlTreeView1.SelectedNode).Keys);
            if (keys == ";;") { keys = ""; }
            mySQL.AddField("GroupKey", keys);
            DataProvider mydb = new DataProvider();
            IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
            if (db.ConnDb(TimeClock.Itrycn_Db.SQLConnStr) == 1)
            {
                if (isAdd >= 1)
                {
                    db.ExecuteNonQuery(mySQL.GetInsertSQL(), mySQL);
                }
                else
                {
                    db.ExecuteNonQuery(mySQL.GetUpdateSQL() + " where id=" + selectId, mySQL);
                }
                #region 更新下次提醒时间
                DataSet ds = db.ReadData("select * from Dingshi where Clac_TipTime=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];
                        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);
                        mySQL2.AddField("Clac_TipTime", 1);
                        db.ExecuteNonQuery(mySQL2.GetUpdateSQL() + " where id=" + reader["id"].ToString(), mySQL2);
                    }
                } 
                #endregion
            }
            if (mr != null) mr.Form_Result = DialogResult.OK;
        } 
        #endregion

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            if (mr != null) mr.Form_Result = DialogResult.Cancel;
        }

        private void RbTheTime_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = (RadioButton)sender;
            if (rb.Checked)
            {
                PnlInterval.Visible = false;
                PnlMonth.Visible = false;
                PnlTime.Visible = true;
                PnlWeek.Visible = false;
                PnlStartTime.Visible = false;
                PnlYear.Visible = false;
                DtTime.Value = Dt_StartTime.Value;
                if (DtDay.Value.Date < DateTime.Now.Date) { DtDay.Value = DateTime.Now; }
            }
        }

        private void RbDay_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = (RadioButton)sender;
            if (rb.Checked)
            {
                PnlInterval.Visible = true;
                PnlYear.Visible = false;
                PnlMonth.Visible = false;
                PnlTime.Visible = false;
                PnlWeek.Visible = false;
                label3.Text = "每过";
                LblInterval.Text = "天";
                PnlStartTime.Visible = true;
                Dt_StartTime.Value = DtTime.Value;
            }
        }

        private void RbHour_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = (RadioButton)sender;
            if (rb.Checked)
            {
                PnlInterval.Visible = true;
                PnlYear.Visible = false;
                PnlMonth.Visible = false;
                PnlTime.Visible = false;
                PnlWeek.Visible = false;
                label3.Text = "每过";
                LblInterval.Text = "小时";
                PnlStartTime.Visible = true;
                Dt_StartTime.Value = DtTime.Value;
            }
        }

        private void RbMinute_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = (RadioButton)sender;
            if (rb.Checked)
            {
                PnlInterval.Visible = true;
                PnlYear.Visible = false;
                PnlMonth.Visible = false;
                PnlTime.Visible = false;
                PnlWeek.Visible = false;
                label3.Text = "每过";
                LblInterval.Text = "分钟";
                PnlStartTime.Visible = true;
                Dt_StartTime.Value = DtTime.Value;
            }
        }
        private void CbbAction_SelectedIndexChanged(object sender, EventArgs e)
        {
            ActionInfo item = (ActionInfo)CbbAction.SelectedItem;
            toolTip1.SetToolTip(CbbFile,item.File_ToolTip);
            toolTip1.SetToolTip(BtnFile, item.File_ToolTip);
            if (item.ShowFileUI || item.ShowPramUI)
            {
                PnlFile.Visible = true;
                LblFile.Text = item.File_Title;
                CbbPram.Visible = item.ShowPramUI;
                LblPram.Visible = item.ShowPramUI;
                if (item.Id == "OpenUrl") { BtnFile.Visible = false; } else {  BtnFile.Visible = true; }
                if (item.Id == "Speaker") { BtnFile.Visible = true; BtnFile.Text = "朗读"; } else { BtnFile.Text = "选择"; }
            }
            else
            {
                PnlFile.Visible = false;
            }
        }

        private void BtnFile_Click(object sender, EventArgs e)
        {
            ActionInfo item = (ActionInfo)CbbAction.SelectedItem;
            if(item.Id=="Speaker")
            {
                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(CbbFile.Text, COM.SpVoice.Flags.SVSFlagsAsync);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                return;
            }
            if (item.File_Filter != "")
            {
                openFileDialog1.Filter = item.File_Filter;
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    CbbFile.Text =RyFiles.GetRelativePath(openFileDialog1.FileName);
                }
            }
            else
            {
                item.Cancel = false;
                item.Selected();
                if (!item.Cancel)
                {
                    CbbFile.Text = item.File;
                    CbbPram.Text = item.Pram;
                }
            }
        }

        private void RbWeek_CheckedChanged(object sender, EventArgs e)
        {
            PnlInterval.Visible = true;
            PnlMonth.Visible = false;
            PnlYear.Visible = false;
            PnlTime.Visible = false;
            PnlWeek.Visible = true;
            label3.Text = "每过";
            LblInterval.Text = "周";
            PnlStartTime.Visible = true;
            Dt_StartTime.Value = DtTime.Value;
        }

        private void RbMonth_CheckedChanged(object sender, EventArgs e)
        {
            PnlInterval.Visible = true;
            PnlYear.Visible = false;
            PnlMonth.Visible = true;
            PnlTime.Visible = false;
            PnlWeek.Visible = false;
            label3.Text = "每过";
            LblInterval.Text = "月";
            PnlStartTime.Visible = true;
            Dt_StartTime.Value = DtTime.Value;
            if (CbbDay.Items.Count==0)
            {
                for(int i=0;i<28;i++)
                {
                    CbbDay.Items.Add((i+1).ToString()+"日");
                }
                if (DateTime.Now.Day <= 28)
                {
                    CbbDay.SelectedIndex = DateTime.Now.Day - 1;
                }
                else { CbbDay.SelectedIndex =0; }
            }
        }

        private void TabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            LblTimeStr.Text ="软件将在以下时刻进行提醒:"+ GetRunTimeStr(out string week, out int modtype);
        }

        private void 添加时间段ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmDisturbedAdd frm = new FrmDisturbedAdd() { Icon = this.Icon };
            frm.mr = new ModalForm(this, frm);
            frm.mr.OnDialogResult += new ModalForm.DialogResultHandler((object t, DialogResult dg) => {
                if (dg == DialogResult.OK)
                {
                    DateInfo dt_info = new DateInfo()
                    {
                        iType = frm.CbbType.SelectedIndex,
                        start = getdate_minute(frm.Dt_start.Value),
                        end = getdate_minute(frm.Dt_End.Value),
                        start_week = frm.CbbStartWeek.SelectedIndex + 1,
                        end_week = frm.CbbEndWeek.SelectedIndex + 1,
                        des = frm.TxtDes.Text
                    };
                    LvNotDisturb.AddObject(dt_info);
                    tabPage3.Text = "免打扰(" + LvNotDisturb.GetItemCount() + ")";
                    DateTime getdate_minute(DateTime dt)
                    {
                        return dt.Date.AddHours(dt.Hour).AddMinutes(dt.Minute);
                    }
                }
            });
            frm.mr.ShowModal();
        }

        private void 删除时间段ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (LvNotDisturb.SelectedObject==null) { return; }
            LvNotDisturb.RemoveObject(LvNotDisturb.SelectedObject);
            tabPage3.Text = "免打扰(" + LvNotDisturb.GetItemCount() + ")";
        }

        private void 清空时间段ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要清空所有免打扰数据吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
            {
                return;
            }
            LvNotDisturb.ClearObjects();
            tabPage3.Text = "免打扰(" + LvNotDisturb.GetItemCount() + ")";
        }

        private void BtnSelectSound_Click(object sender, EventArgs e)
        {
            openFileDialog2.Filter = "音频文件(*.mp3;*.wav)|*.mp3;*.wav";
            if (CbbSound.Text.Length > 0)
            {
                openFileDialog2.InitialDirectory = System.IO.Path.GetDirectoryName(Itrycn_Info.GetRealPath(CbbSound.Text));
            }
            if (openFileDialog2.ShowDialog() == DialogResult.OK)
            {
                CbbSound.Text = Itrycn_Info.GetRelativePath(openFileDialog2.FileName);
            }
        }

        private void BtnSelectPic_Click(object sender, EventArgs e)
        {
            openFileDialog2.Filter = "图片文件(*.gif;*.jpg;*.png;*.bmp)|*.gif;*.jpg;*.png;*.bmp";
            var pic_path =Itrycn_Info.GetRealPath(CbbShowPic.Text);
            if (pic_path.Length > 0)
            {
                openFileDialog2.FileName = System.IO.Path.GetDirectoryName(pic_path);
            }
            if (openFileDialog2.ShowDialog() == DialogResult.OK)
            {
                CbbShowPic.Text = Itrycn_Info.GetRelativePath(openFileDialog2.FileName);
            }
        }

        private void ChkSound_CheckedChanged(object sender, EventArgs e)
        {
            CbbSound.Enabled = ChkSound.Checked;
            BtnSelectSound.Enabled = ChkSound.Checked;
        }

        private void ChkShowPic_CheckedChanged(object sender, EventArgs e)
        {
            CbbShowPic.Enabled = ChkShowPic.Checked;
            BtnSelectPic.Enabled = ChkShowPic.Checked;
        }

        private void ChkEarlierTime_CheckedChanged(object sender, EventArgs e)
        {
            CbbEarlierTime.Enabled = ChkEarlierTime.Checked;
            CbbEarlierTime.ForeColor = CbbEarlierTime.Enabled?Color.Black:Color.Gray;
        }

        private void RbYear_CheckedChanged(object sender, EventArgs e)
        {
            PnlInterval.Visible = true;
            PnlYear.Visible = true;
            PnlMonth.Visible = false;
            PnlTime.Visible = false;
            PnlWeek.Visible = false;
            label3.Text = "每过";
            LblInterval.Text = "年";
            PnlStartTime.Visible = true;
            Dt_StartTime.Value = DtTime.Value;

            //if (CbbDay.Items.Count == 0)
            //{
            //    for (int i = 0; i < 28; i++)
            //    {
            //        CbbDay.Items.Add("第" + (i + 1).ToString() + "天");
            //    }
            //    CbbDay.SelectedIndex = 0;
            //}
        }

        private void CheckBox1_CheckedChanged(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 上一次选择的是阳历还是农历，0表示阳历,1表示农历
        /// </summary>
        int last_lunar_y_value = -1;
        private void CbbLunar_SelectedIndexChanged(object sender, EventArgs e)
        {
            #region 获取当前选择的时间
            var getdate = DateTime.Now;
            try
            {
                if (last_lunar_y_value == 0)
                {
                    if (!ChkRevDay_y.Checked)
                        getdate = new DateTime(Dt_StartDate.Value.Year, CbbMonth_y.SelectedIndex + 1, CbbDay_y.SelectedIndex + 1);
                }
                else if (last_lunar_y_value == 1)
                {
                    if (!ChkRevDay_y.Checked)
                    {
                        if (ChinaDate.GetDayFromLunar(Dt_StartDate.Value.Year, CbbMonth_y.SelectedIndex + 1, CbbDay_y.SelectedIndex + 1, false, out int AYear, out int AMonth, out int ADay))
                        {
                            getdate = new DateTime(AYear, AMonth, ADay);
                        }
                    }
                }
            }
            catch
            {
            } 
            #endregion
            last_lunar_y_value = CbbLunar.SelectedIndex;
            if (CbbLunar.SelectedIndex==0) //阳历
            {
                CbbMonth_y.Items.Clear();
                for (int i = 0; i < 12; i++)
                {
                    CbbMonth_y.Items.Add((i + 1).ToString() + "月");
                }
                CbbMonth_y.SelectedIndex = getdate.Month - 1;
            }
            else
            {
                CbbMonth_y.Items.Clear();
                string stext = "正二三四五六七八九十";
                for (int i = 0; i < 10; i++)
                {
                    CbbMonth_y.Items.Add(stext[i].ToString() + "月");
                }
                CbbMonth_y.Items.Add("十一月"); CbbMonth_y.Items.Add("十二月");
                ChinaDate.GetLunarFromDay(getdate.Year, getdate.Month, getdate.Day, out int LunarYear, out int LunarMonth, out int LunarDay, out bool IsLeapMonth);
                CbbMonth_y.SelectedIndex = LunarMonth-1;
            }
            if (ChkRevDay_y.Checked)
            {
                CbbDay_y.Items.Clear();
                for (int i = 0; i < 31; i++)
                {
                    if (i == 30 && CbbLunar.SelectedIndex == 1) { continue; }
                    CbbDay_y.Items.Add("第" + (i + 1).ToString() + "天");
                }
                CbbDay_y.SelectedIndex = 0;
            }
            else
            {
                CbbDay_y.Items.Clear();
                if (CbbLunar.SelectedIndex == 0)
                {
                    for (int i = 0; i < 31; i++)
                    {
                        CbbDay_y.Items.Add((i + 1).ToString()+"日");
                    }
                    CbbDay_y.SelectedIndex= getdate.Day-1;
                }
                else
                {
                    for (int i = 0; i < 30; i++)
                    {
                        CbbDay_y.Items.Add(ChinaDate.GetDay(i + 1));
                    }
                    ChinaDate.GetLunarFromDay(getdate.Year, getdate.Month, getdate.Day, out int LunarYear, out int LunarMonth, out int LunarDay, out bool IsLeapMonth);
                    CbbDay_y.SelectedIndex = LunarDay-1;
                }
            }
        }

        private void ChkRevDay_y_CheckedChanged(object sender, EventArgs e)
        {
            if (ChkRevDay_y.Checked)
            {
                CbbDay_y.Items.Clear();
                for (int i = 0; i < 31; i++)
                {
                    if (i == 30 && CbbLunar.SelectedIndex == 1) { continue; }
                    CbbDay_y.Items.Add("第" + (i + 1).ToString() + "天");
                }
                CbbDay_y.SelectedIndex = 0;
            }
            else
            {
                CbbDay_y.Items.Clear();
                if (CbbLunar.SelectedIndex == 0)
                {
                    for (int i = 0; i < 31; i++)
                    {
                        CbbDay_y.Items.Add((i + 1).ToString() + "日");
                    }
                }
                else
                {
                    for (int i = 0; i < 30; i++)
                    {
                        CbbDay_y.Items.Add(ChinaDate.GetDay(i + 1));
                    }
                }
                CbbDay_y.SelectedIndex = 0;
            }
        }

        private void ChkRevDay_CheckedChanged(object sender, EventArgs e)
        {
            CbbDay.Items.Clear();
            if (ChkRevDay.Checked)
            {
                for (int i = 0; i < 28; i++)
                {
                    CbbDay.Items.Add("第" + (i + 1).ToString() + "天");
                }
            }
            else
            {
                for (int i = 0; i < 28; i++)
                {
                    CbbDay.Items.Add((i + 1).ToString() + "日");
                }
            }
            CbbDay.SelectedIndex = 0;
        }

        private void BtnPlay_Click(object sender, EventArgs e)
        {
            var item = (SoundInfo)CbbSound.SelectedItem;
            if (item == null)
            {
                string path = CbbSound.Text;
                Itrycn_Info.PlaySound(path);
            }
            else
            {
                Itrycn_Info.PlaySound(item.Path);
            }
        }

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

        private void 分钟后ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int minute = ((ToolStripMenuItem)sender).Tag.ToInt();
            DateTime dt =DateTime.Now;
            dt = dt.AddMinutes(minute);
            DtDay.Value = dt;
            DtTime.Value = dt;
        }

        private void 天后ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int day = ((ToolStripMenuItem)sender).Tag.ToInt();
            DateTime dt = DateTime.Now;
            dt = dt.AddDays(day);
            DtDay.Value = dt;
            DtTime.Value = dt;
        }

        private void 个月后ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int month = ((ToolStripMenuItem)sender).Tag.ToInt();
            DateTime dt = DateTime.Now;
            dt = dt.AddMonths(month);
            DtDay.Value = dt;
            DtTime.Value = dt;
        }
        bool proc_AfterSelect = false;
        private void CtlTreeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (proc_AfterSelect) { return; }
            if (ctlTreeView1.SelectedNode != null)
            {
                int img_index = ctlTreeView1.SelectedNode.ImageIndex;
                if (img_index < 0) { img_index = 0; }
                pictureBox1.Image =Itrycn_Db.GetGroupImg(ctlTreeView1.ImageList.Images.Keys[img_index]);
                TxtKeys.Text = ctlTreeView1.SelectedNode.Text;
            }
            panelEx2.Visible = false;
        }

        private void RbWinStart_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = (RadioButton)sender;
            if (rb.Checked)
            {
                PnlInterval.Visible = true;
                PnlYear.Visible = false;
                PnlMonth.Visible = false;
                PnlTime.Visible = false;
                PnlWeek.Visible = false;
                label3.Text = "开机";
                LblInterval.Text = "分钟后";
                PnlStartTime.Visible = false;
                NumInterval.Minimum = 0;
                Dt_StartTime.Value = DtTime.Value;
            }
            else { NumInterval.Minimum = 1; }
        }

        private void 自定义时间ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmCountdownTip frm = new FrmCountdownTip
            {
                Icon = Icon
            };
            if (frm.ShowDialog()==DialogResult.OK)
            {
                DateTime dt = DateTime.Now;
                dt = dt.AddMinutes(frm.Minute);
                DtDay.Value = dt;
                DtTime.Value = dt;
            }
        }
        private void AddCustomShow(int type)
        {
            if(LvCustom.GetItemCount()>=5)
            {
                MessageBox.Show("无法再添加，已经到达最大值。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            CustomShow.FrmAddBirthDay frm = new CustomShow.FrmAddBirthDay();
            frm.Icon = Icon;
            if (type == 0) { frm.Text = "添加出生日期"; }
            else if (type == 1) { frm.Text = "添加纪念日"; }
            else if (type == 2) { frm.Text = "添加倒计时"; }
            frm.CbbType.SelectedIndex = type;
            frm.mr = new ModalForm(this, frm);
            frm.mr.OnDialogResult += new ModalForm.DialogResultHandler((object t, DialogResult dg) => {
                if (dg == DialogResult.OK)
                {
                    CustomShowInfo dt_info = new CustomShowInfo()
                    {
                        Type = type,
                        Name = frm.txtName.Text,
                        IsLunar = frm.CbbLunar.SelectedIndex == 1,
                        Year = frm.Dt_Year.Value.Year,
                        Month = frm.CbbMonth_y.SelectedIndex + 1,
                        Day = frm.CbbDay_y.SelectedIndex + 1
                    };
                    LvCustom.AddObject(dt_info);
                    tabPage4.Text = "自定义显示(" + LvCustom.GetItemCount() + ")";
                }
            });
            frm.mr.ShowModal();
        }
        private void 添加出生日期ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddCustomShow(0);
        }

        private void 添加纪念日ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddCustomShow(1);
        }

        private void 添加倒计时ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddCustomShow(2);
        }

        private void 删除自定义显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (LvCustom.SelectedObject==null) { return; }
            LvCustom.RemoveObject(LvCustom.SelectedObject);
        }

        private void RbDayByMonth_CheckedChanged(object sender, EventArgs e)
        {
            ChkRevDay.Enabled = RbDayByMonth.Checked;
            CbbDay.Enabled = RbDayByMonth.Checked;
            CbbWeekByMonth.Enabled = !RbDayByMonth.Checked;
            CbbWeekIndexByMonth.Enabled = !RbDayByMonth.Checked;
            ChkWeekTypeByMonth.Enabled = !RbDayByMonth.Checked;
        }

        private void ChkWeekTypeByMonth_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < CbbWeekIndexByMonth.Items.Count; i++)
            {
                if (ChkWeekTypeByMonth.Checked)
                {
                    CbbWeekIndexByMonth.Items[i] = CbbWeekIndexByMonth.Items[i].ToString().Replace("星期", "") + "星期";
                }
                else { CbbWeekIndexByMonth.Items[i] = CbbWeekIndexByMonth.Items[i].ToString().Replace("星期", ""); }
            }
        }
    }
    public class ActionInfo
    {
        public delegate void FileEventHandler(object sender);
        public event FileEventHandler OnSelected;       
        public string Id = "";
        public string Title = "";
        public string File = "";
        public string Pram = "";
        public string File_Title = "文件:";
        /// <summary>
        /// 文件过滤。
        /// </summary>
        public string File_Filter = "";
        /// <summary>
        /// 文件文本框提示
        /// </summary>
        public string File_ToolTip = "";
        public bool ShowFileUI = false;
        public bool ShowPramUI = false;
        public bool Cancel = false;
        public override string ToString()
        {
            return Title;
        }
        public void Selected()
        {
            OnSelected?.Invoke(this);
        }
    }
    public class DateInfo
    {
        public DateTime start;
        public DateTime end;
        public int start_week = 1;
        public int end_week = 1;
        /// <summary>
        /// 1表示具体时间，0表示每天
        /// </summary>
        public int iType = 0;
        public string TimeStr
        {
            get
            {
                var date_str = "";
                if (iType == 1)
                {
                    date_str = start.ToString("yyyy-MM-dd HH:mm") + " 到 " + end.ToString("yyyy-MM-dd HH:mm");
                }
                else if (iType == 2)//星期
                {
                    if (start_week == end_week)
                    { date_str = "每周" + RyDate.GetWeekName(start_week); }
                    else
                    {
                        date_str = "周" + RyDate.GetWeekName(start_week) + " 到 周" + RyDate.GetWeekName(end_week);
                    }
                }
                else
                {
                    date_str = "每天 " + start.ToString("HH:mm") + " 到 " + end.ToString("HH:mm");
                }
                return date_str;
            }
        }
        public string des = "";
    }
    public class EarlierTimeInfo
    {
        public string Title = "";
        /// <summary>
        /// 提前多少分钟提醒
        /// </summary>
        public int Minute = 0;
        public override string ToString()
        {
            return Title;
        }
    }
    public class CustomShowInfo
    {
        /// <summary>
        /// 类型
        /// </summary>
        public int Type;
        /// <summary>
        /// 类型
        /// </summary>
        public string TypeStr
        {
            get
            {
                var str = "";
                switch(Type)
                {
                    case 0:
                        str = "出生日期";
                        break;
                    case 1:
                        str = "纪念日";
                        break;
                    case 2:
                        str = "倒计时";
                        break;
                    default:
                        str = "未知";
                        break;
                }
                return str;
            }
        }
        /// <summary>
        /// 名称
        /// </summary>
        public string Name = "";
        /// <summary>
        /// 是否是农历
        /// </summary>
        public bool IsLunar =false;
        /// <summary>
        /// 年份
        /// </summary>
        public int Year = 2019;
        /// <summary>
        /// 月份
        /// </summary>
        public int Month = 1;
        /// <summary>
        /// 日
        /// </summary>
        public int Day = 1;
        /// <summary>
        /// 日期描述
        /// </summary>
        public string DateStr
        {
            get
            {
                var date_str = "";
                if (IsLunar)
                {
                    date_str = "农历" + Year + "年" + ChinaDate.GetMonth(Month) + ChinaDate.GetDay(Day);
                }
                else
                {
                    date_str = "阳历" + Year + "年" + Month + "月" + Day + "日";
                }
                return date_str;
            }
        }
    }
}
