using ryCommon;
using ryCommonDb;
using ryControls;
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using VSoft.Prams;

namespace VSoft
{
    public partial class FrmInCMD : Skins.SKinForm
    {
        public string SQLConnStr = Itrycn_Db.SQLConnStr_SysDb;
#if TEST
        private bool ReadOnly { get; set; } = false;
#else
        private bool ReadOnly { get; set; } = true;
#endif
        public FrmInCMD()
        {
            InitializeComponent();
            if(ReadOnly)
            {
                IconViewEx1.ContextMenuStrip = null;
                TabList_Column.ContextMenuStrip = null;
                TabList_Type.ContextMenuStrip = null;
                BtnAddColumn.Visible = false;
            }
        }
        private bool IsProcUse = false;
        /// <summary>
        /// 获取当前页面所属的分类或栏目ID
        /// </summary>
        /// <returns></returns>
        private int GetCurColumnId()
        {
            var ColumnId = 0;
            if (TabList_Type.SelectedItems.Count > 0)
            {
                var info = (ColumnInfo)TabList_Type.SelectedItems[0].Tag;
                ColumnId = info.Id;
            }
            if (ColumnId == 0)
            {
                if (TabList_Column.SelectedItems.Count > 0)
                {
                    var info = (ColumnInfo)TabList_Column.SelectedItems[0].Tag;
                    ColumnId = info.Id;
                }
            }
            return ColumnId;
        }
        private void LoadDb()
        {
            LoadDb(false);
        }
        private void LoadDb(bool isSearch)
        {
            IconViewEx1.Items.Clear();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(SQLConnStr) == 1)
            {
                var id = GetCurColumnId();
                RyQuickSQL mySQL = new RyQuickSQL("Softs");
                mySQL.AddField("SearchText", "%" + rySearch1.Text + "%");
                var sql = "select * from Softs where (Name like @SearchText or Path like @SearchText or Des like @SearchText or PinYin like @SearchText)";
                if (isSearch)
                {
                    IsProcUse = true;
                    TabList_Column.SelectedItems.Clear();
                    panel1.Visible = false;
                    TabList_Type.Items.Clear();
                    TabList_Type.Items.Add("默认分类").Tag =new ColumnInfo();
                    IsProcUse = false;
                }
                else
                {
                    if (id > 0)
                    {
                        sql += " and ColumnId=" + id;
                    }
                    else { sql += " and ColumnId<=0"; }
                }
                DataSet ds = db.ReadData(sql + " order by sortindex asc,AddTime desc", mySQL);
                IconViewEx1.BeginUpdate();
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow row = ds.Tables[0].Rows[i];
                    SoftInfo info = new SoftInfo();
                    info.Id = row["id"].ToInt();
                    info.ColumnId = row["ColumnId"].ToInt();
                    info.Name = row["Name"].ToString();
                    info.Path = row["Path"].ToString();
                    info.RunPram = row["RunPram"].ToString();
                    info.SetJson = row["SetJson"].ToString();
                    info.StartPath= row["StartPath"].ToString();
                    info.IconPath = row["IconPath"].ToString();
                    info.CmdId = row["CmdId"].ToString();
                    info.Des = row["Des"].ToString();
                    if (info.IconPath.Length == 0)
                    {
                        info.Image = API.GetImg(info.TruePath,128);
                    }
                    else
                    {
                        info.Image = API.GetImg(RyFiles.GetRealPath(row["IconPath"].ToString()),128);
                    }
                    IconViewEx1.Items.Add(info.Name).Tag = info ;
                }
                IconViewEx1.EndUpdate();
                db.Free();
            }
        }
        private void LoadColumn()
        {
            TabList_Column.Items.Clear();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(SQLConnStr) == 1)
            {
                TabList_Column.BeginUpdate();
                DataSet ds = db.ReadData("select * from Columns where parentId=0 order by sortindex asc");
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow row = ds.Tables[0].Rows[i];
                    ColumnInfo info = new ColumnInfo
                    {
                        Id = row["id"].ToInt(),
                        Name = row["Name"].ToString(),
                        Des = row["Des"].ToString()
                    };
                    TabList_Column.Items.Add(row["Name"].ToString()).Tag = info;
                }
                if(ds.Tables[0].Rows.Count==0)
                {
#region 如果没有栏目,则创建一个栏目
                    RyQuickSQL mySQL = new RyQuickSQL("Columns");
                    mySQL.AddField("Name", "默认栏目");
                    mySQL.AddField("editTime", DateTime.Now);
                    mySQL.AddField("sortindex", 1);
                    mySQL.AddField("parentId", 0);
                    mySQL.AddField("addTime", DateTime.Now);
                    db.ExecuteNonQuery(mySQL.GetInsertSQL(), mySQL);
                    DataSet ds2 = db.ReadData("select * from Columns where parentId=0 order by sortindex asc");
                    for (int i = 0; i < ds2.Tables[0].Rows.Count; i++)
                    {
                        DataRow row = ds2.Tables[0].Rows[i];
                        ColumnInfo info = new ColumnInfo
                        {
                            Id = row["id"].ToInt(),
                            Name = row["Name"].ToString(),
                            Des = row["Des"].ToString()
                        };
                        TabList_Column.Items.Add(row["Name"].ToString()).Tag = info;
                    }
                    ds2.Dispose(); 
#endregion
                }
                ds.Dispose();
                TabList_Column.EndUpdate();
                db.Free();
            }
            if(TabList_Column.Items.Count>0)
            {
                TabList_Column.Items[0].Selected = true;
            }
        }
        private void LoadTypeColumn(int id)
        {
            TabList_Type.Items.Clear();
            TabList_Type.Items.Add("默认分类").Tag =new ColumnInfo();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(SQLConnStr) == 1)
            {
                DataSet ds = db.ReadData("select * from Columns where parentId="+ id + " order by sortindex asc");
                TabList_Type.BeginUpdate();
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow row = ds.Tables[0].Rows[i];
                    ColumnInfo info = new ColumnInfo
                    {
                        Id = row["id"].ToInt(),
                        Name = row["Name"].ToString(),
                        Des = row["Des"].ToString()
                    };
                    TabList_Type.Items.Add(row["Name"].ToString()).Tag = info;
                }
                ds.Dispose();
                TabList_Type.EndUpdate();
                db.Free();
            }
            if (TabList_Type.Items.Count > 0)
            {
                TabList_Type.Items[0].Selected = true;
            }
        }
        private void FrmVSoft_Load(object sender, EventArgs e)
        {
            Config.Soft_Info.UserDataFolder = ryCommon.RyFiles.GetRealPath(Config.Soft_Info.UserDataFolder);
            VSoft.Prams.Itrycn_Db.CreateTable();
            VSoft.Config.Soft_Config.LoadSetting();
            LoadColumn();
            //rySearch1.PerformClick();
        }

        private void rySearch1_OnSearch(object sender, EventArgs e)
        {
            LoadDb(true);
        }
#region 对栏目标签进行操作
        /// <summary>
        /// 将栏目列表中的第几个栏目修改
        /// </summary>
        /// <param name="id"></param>
        /// <param name="index"></param>
        private void SetColumnRow(int id, int index)
        {
#region 重新载入数据
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(SQLConnStr) == 1)
            {
                DataSet ds = db.ReadData("select * from Columns where id=" + id);
                if (mydb.HaveData(ds))
                {
                    DataRow row = ds.Tables[0].Rows[0];
                    var item = TabList_Column.Items[index];
                    var info = (ColumnInfo)item.Tag;
                    info.Name= row["Name"].ToString();
                    info.Des = row["Des"].ToString();
                    item.Text = row["Name"].ToString();
                    if (info.Des.Length > 0)
                    {
                        LblDes.Text = info.Des;
                        panel1.Visible = true;
                    }
                    else
                    {
                        panel1.Visible = false;
                    }
                }
                db.Free();
            }
#endregion
        }
        private void BtnAddColumn_Click(object sender, EventArgs e)
        {
            FrmAddColumn frm = new FrmAddColumn();
            frm.TopMost = TopMost;
            frm.SQLConnStr = SQLConnStr;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
                if (db.ConnDb(SQLConnStr) == 1)
                {
                    DataSet ds = db.ReadData("select * from Columns where parentId=0 order by sortindex desc limit 1");
                    TabList_Column.BeginUpdate();
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        DataRow row = ds.Tables[0].Rows[0];
                        ColumnInfo info = new ColumnInfo
                        {
                            Id = row["id"].ToInt(),
                            Name = row["Name"].ToString(),
                            Des = row["Des"].ToString()
                        };
                        TabList_Column.Items.Add(row["Name"].ToString()).Tag = info;
                    }
                    TabList_Column.EndUpdate();
                    db.Free();
                }
            }
            frm.Dispose();
        }
        private void 修改栏目ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (TabList_Column.SelectedItems.Count == 0) { return; }
            var info = (ColumnInfo)TabList_Column.SelectedItems[0].Tag;
            FrmAddColumn frm = new FrmAddColumn();
            frm.TopMost = TopMost;
            frm.SQLConnStr = SQLConnStr;
            frm.IsAdd = 0;
            frm.GetInfo(info.Id);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                SetColumnRow(info.Id, TabList_Column.SelectedItems[0].Index);
            }
            frm.Dispose();
        }

        private void 删除栏目ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (TabList_Column.SelectedItems.Count == 0) { return; }
            if (Msg.ShowMsg("确定要删除选定项吗？一旦删除将不可恢复。", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
            {
                return;
            }
            if (TabList_Column.Items.Count ==1) {
                Msg.ShowMsg("请至少保留一个栏目。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(SQLConnStr) == 1)
            {
                var info2 = (ColumnInfo)TabList_Column.SelectedItems[0].Tag;
                var column_id = info2.Id;
                var ds = db.ReadData("select count(*) from Columns where parentId=" + column_id);
                if (mydb.HaveData(ds))
                {
                    if (mydb.GetValue(ds) > 0)
                    {
                        ds.Dispose();
                        Msg.ShowMsg("当前栏目下还有分类,请先移除再删除栏目。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        db.Free();
                        return;
                    }
                }
                ds.Dispose();
                db.DelById("Columns", column_id.ToString());
                db.ExecuteNonQuery("delete from Softs where ColumnId=" + column_id);
                TabList_Column.SelectedItems[0].Remove();
                db.BeginTransaction();
                for (int i = 1; i < TabList_Column.Items.Count; i++)
                {
                    var info = (ColumnInfo)TabList_Column.Items[i].Tag;
                    RyQuickSQL mySQL = new RyQuickSQL("Columns");
                    mySQL.AddField("sortindex", i);
                    db.ExecuteNonQuery(mySQL.GetUpdateSQL() + " where id=" + info.Id, mySQL);
                }
                db.Commit();
            }
            db.Free();
        }
#endregion
#region 对分类标签进行操作
        /// <summary>
        ///将分类列表中的第几个分类进行修改
        /// </summary>
        /// <param name="id"></param>
        /// <param name="index"></param>
        private void SetTypeRow(int id, int index)
        {
#region 重新载入数据
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(SQLConnStr) == 1)
            {
                DataSet ds = db.ReadData("select * from Columns where id=" + id);
                if (mydb.HaveData(ds))
                {
                    DataRow row = ds.Tables[0].Rows[0];
                    var item = TabList_Type.Items[index];
                    var info = (ColumnInfo)item.Tag;
                    info.Name = row["Name"].ToString();
                    info.Des = row["Des"].ToString();
                    item.Text = row["Name"].ToString();
                }
                db.Free();
            }
#endregion
        }
        private void 新增分类ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (TabList_Column.SelectedItems.Count == 0)
            {
                Msg.ShowMsg("请先选择一个栏目。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var id = ((ColumnInfo)TabList_Column.SelectedItems[0].Tag).Id;
            FrmAddType frm = new FrmAddType
            {
                ParentId = id,
                SQLConnStr = SQLConnStr,
                TopMost=TopMost
            };
            if (frm.ShowDialog() == DialogResult.OK)
            {
                IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
                if (db.ConnDb(SQLConnStr) == 1)
                {
                    DataSet ds = db.ReadData("select * from Columns where parentId=" + id + " order by sortindex desc limit 1");
                    TabList_Type.BeginUpdate();
                    if(ds.Tables[0].Rows.Count>0)
                    {
                        DataRow row = ds.Tables[0].Rows[0];
                        ColumnInfo info = new ColumnInfo
                        {
                            Id = row["id"].ToInt(),
                            Name = row["Name"].ToString(),
                            Des = row["Des"].ToString()
                        };
                        TabList_Type.Items.Add(row["Name"].ToString()).Tag = info;
                    }
                    TabList_Type.EndUpdate();
                    db.Free();
                }
            }
            frm.Dispose();
        }

        private void Menu修改分类_Click(object sender, EventArgs e)
        {
            if (TabList_Column.SelectedItems.Count == 0)
            {
                Msg.ShowMsg("请先选择一个栏目。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (TabList_Type.SelectedItems.Count == 0)
            {
                Msg.ShowMsg("请先选择一个分类。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var info = (ColumnInfo)TabList_Type.SelectedItems[0].Tag;
            if (info.Id == 0) {
                Msg.ShowMsg("默认分类不支持修改", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return; 
            }
            FrmAddType frm = new FrmAddType
            {
                IsAdd = 0,
                SQLConnStr = SQLConnStr,
                TopMost=TopMost
            };
            frm.GetInfo(info.Id);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                SetTypeRow(info.Id, TabList_Type.SelectedItems[0].Index);
            }
            frm.Dispose();
        }

        private void Menu删除分类_Click(object sender, EventArgs e)
        {
            if (TabList_Type.SelectedItems.Count == 0) { return; }
            if (Msg.ShowMsg("确定要删除选定项吗？一旦删除将不可恢复。", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
            {
                return;
            }
            if (TabList_Type.SelectedItems.Count == 0) { return; }
            var info2= (ColumnInfo)TabList_Type.SelectedItems[0].Tag;
            var column_id = info2.Id;
            if (column_id == 0) {
                Msg.ShowMsg("默认分类不支持删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return; 
            }
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(SQLConnStr) == 1)
            {
                var ds = db.ReadData("select count(*) from Softs where ColumnId=" + column_id);
                if (mydb.HaveData(ds))
                {
                    if (mydb.GetValue(ds) > 0)
                    {
                        ds.Dispose();
                        Msg.ShowMsg("当前分类下还有软件,请先移除再删除分类。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        db.Free();
                        return;
                    }
                }
                ds.Dispose();
                db.DelById("Columns", column_id.ToString());
                TabList_Type.SelectedItems[0].Remove();
                db.BeginTransaction();
                for (int i = 1; i < TabList_Type.Items.Count; i++)
                {
                    var info = (ColumnInfo)TabList_Type.Items[i].Tag;
                    RyQuickSQL mySQL = new RyQuickSQL("Columns");
                    mySQL.AddField("sortindex", i);
                    db.ExecuteNonQuery(mySQL.GetUpdateSQL() + " where id=" + info.Id, mySQL);
                }
                db.Commit();
            }
            db.Free();
        }
#endregion
#region 对软件列表进行操作
        private void SetSoftRow(int id, int index)
        {
#region 重新载入数据
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(SQLConnStr) == 1)
            {
                DataSet ds = db.ReadData("select * from Softs where id=" + id);
                if (mydb.HaveData(ds))
                {
                    DataRow row = ds.Tables[0].Rows[0];
                    var item = IconViewEx1.Items[index];
                    SoftInfo info = (SoftInfo)item.Tag;
                    info.Id = row["id"].ToInt();
                    info.Name = row["Name"].ToString();
                    info.Path = row["Path"].ToString();
                    info.RunPram = row["RunPram"].ToString();
                    info.SetJson = row["SetJson"].ToString();
                    info.StartPath = row["StartPath"].ToString();
                    info.IconPath = row["IconPath"].ToString();
                    info.CmdId = row["CmdId"].ToString();
                    info.Des = row["Des"].ToString();
                    if (info.IconPath.Length == 0)
                    {
                        info.Image = API.GetImg(info.TruePath, 128);
                    }
                    else
                    {
                        info.Image = API.GetImg(RyFiles.GetRealPath(row["IconPath"].ToString()), 128);
                    }
                    item.Text = row["Name"].ToString();
                }
                db.Free();
            }
#endregion
        }
        private void 新增软件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var ColumnId =GetCurColumnId();
            if (ColumnId == 0)
            {
                Msg.ShowMsg("当前模式下不支持添加软件。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            FrmAddSoft frm = new FrmAddSoft
            {
                SQLConnStr = SQLConnStr,
                ColumnId = ColumnId,
                TopMost=TopMost
            };
            if (frm.ShowDialog() == DialogResult.OK)
            {
                LoadDb();
            }
            frm.Dispose();
        }
        private void 修改软件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (IconViewEx1.SelectedItems.Count == 0) { return; }
            var info = (SoftInfo)IconViewEx1.SelectedItems[0].Tag;
            FrmAddSoft frm = new FrmAddSoft
            {
                SelectId = info.Id,
                SQLConnStr = SQLConnStr,
                IsAdd = 0,
                TopMost=TopMost
            };
            frm.GetInfo(info.Id);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                SetSoftRow(info.Id, IconViewEx1.SelectedItems[0].Index);
            }
            frm.Dispose();
        }
        private void 从列表删除该软件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (IconViewEx1.SelectedItems.Count == 0) { return; }
            if (Msg.ShowMsg("确定要删除选定项吗？一旦删除将不可恢复。", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
            {
                return;
            }
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(SQLConnStr) == 1)
            {
                for (int i = IconViewEx1.SelectedItems.Count - 1; i >= 0; i--)
                {
                    var info = (SoftInfo)IconViewEx1.SelectedItems[i].Tag;
                    if(info.IconPath.Length>0 && info.IconPath.StartsWith("<app>\\UserDb\\SoftLogos", StringComparison.OrdinalIgnoreCase))
                    {
                        RyFiles.DeleteFile(RyFiles.GetRealPath(info.IconPath));
                    }
                    db.DelById("Softs", info.Id.ToString());
                    IconViewEx1.SelectedItems[i].Remove();
                }
                ReSortSoftByList(db);
            }
            db.Free();
        }
        private void 以管理员方式启动ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (IconViewEx1.SelectedItems.Count == 0) { return; }
            var info = (SoftInfo)IconViewEx1.SelectedItems[0].Tag;
            VSoft.Prams.Run.Open(info, false);
        }
        private void 打开软件所在位置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (IconViewEx1.SelectedItems.Count == 0) { return; }
            var info = (SoftInfo)IconViewEx1.SelectedItems[0].Tag;
            if (System.IO.File.Exists(info.TruePath) || System.IO.Directory.Exists(info.TruePath))
            {
                RyFiles.OpenFolderGotoFile(info.TruePath);
            }
            else
            {
                Msg.ShowMsg("没有找到文件。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void IconViewEx1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (IconViewEx1.SelectedItems.Count == 0) { return; }
                var info = (SoftInfo)IconViewEx1.SelectedItems[0].Tag;
                VSoft.Prams.Run.Open(info, false);
            }
            else if (e.KeyCode == Keys.Up)
            {
                if (IconViewEx1.SelectedItems.Count == 0) { return; }
                var item = IconViewEx1.SelectedItems[0];
                if(item.Position.Y== IconViewEx1.Items[0].Position.Y)
                {
                    IconViewEx1.SelectedItems.Clear();
                    if (TabList_Column.SelectedItems.Count == 0)
                    {
                        TabList_Column.Items[0].Selected = true;
                    }
                    TabList_Column.Focus();
                    var color = TabList_Column.SelectedStartBackColor;
                    TabList_Column.SelectedStartBackColor = Color.LightYellow;
                    using (var bg = new BackgroundWorker())
                    {
                        bg.DoWork += delegate { System.Threading.Thread.Sleep(500); };//180秒后,3分钟
                        bg.RunWorkerCompleted += delegate {
                            this.Invoke(new Action(() =>
                            {
                                TabList_Column.SelectedStartBackColor = color; 
                            }));
                        }; // 线程执行完成后会执行 RunWorkerCompleted 事伯的代码块
                        bg.RunWorkerAsync();
                    }
                }
            }
            else if (e.KeyCode == Keys.Left)
            {
                if (IconViewEx1.SelectedItems.Count == 0) { return; }
                var item = IconViewEx1.SelectedItems[0];
                if (item.Index==0 || item.Position.X== IconViewEx1.Items[0].Position.X)
                {
                    IconViewEx1.SelectedItems.Clear();
                    if (TabList_Type.SelectedItems.Count == 0)
                    {
                        TabList_Type.Items[0].Selected = true;
                    }
                    TabList_Type.Focus();
                    var color = TabList_Type.SelectedStartBackColor;
                    TabList_Type.SelectedStartBackColor = Color.LightYellow;
                    using (var bg = new BackgroundWorker())
                    {
                        bg.DoWork += delegate { System.Threading.Thread.Sleep(500); };//180秒后,3分钟
                        bg.RunWorkerCompleted += delegate {
                            this.Invoke(new Action(() =>
                            {
                                TabList_Type.SelectedStartBackColor = color;
                            }));
                        }; // 线程执行完成后会执行 RunWorkerCompleted 事伯的代码块
                        bg.RunWorkerAsync();
                    }
                }
            }
        }
        public SoftInfo SelectedInfo { get; set; } = null;
        private void IconViewEx1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (IconViewEx1.SelectedItems.Count == 0) { return; }
                SelectedInfo = (SoftInfo)IconViewEx1.SelectedItems[0].Tag;
                DialogResult = DialogResult.OK;
            }
        }
#endregion
#region 软件列表拖放
        private void IconViewEx1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            if (ReadOnly){return;}
            this.DoDragDrop(e.Item, DragDropEffects.Move);
        }

        private void IconViewEx1_DragEnter(object sender, DragEventArgs e)
        {
            if (ReadOnly) {
                e.Effect = DragDropEffects.None;
                return;
            }
            LblDrag.Height = IconViewEx1.TileSize.Height;
            LblDrag.Parent = IconViewEx1;
            ListViewItem lvi = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
            if (lvi != null)
            {
                if (lvi.ListView != IconViewEx1)
                {
                    e.Effect = DragDropEffects.None;
                    return;
                }
            }
            e.Effect = DragDropEffects.Move;
        }
        private void IconViewEx1_DragDrop(object sender, DragEventArgs e)
        {
            LblDrag.Visible = false;
            var filedrop = e.Data.GetData(DataFormats.FileDrop);
            if (filedrop != null)
            {
#region 拖放文件到软件列表
                var ColumnId = GetCurColumnId();
                if(ColumnId==0)
                {
                    Msg.ShowMsg("当前模式下不支持添加软件。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                var path = ((string[])filedrop)[0];
                Thread th = new Thread(DragFiles);
                th.Start();
                void DragFiles()
                {
                    this.BeginInvoke(new Action(() =>
                    {
                        FrmAddSoft frm = new FrmAddSoft(path)
                        {
                            ColumnId = ColumnId,
                            SQLConnStr = SQLConnStr
                        };
                        if (frm.ShowDialog() == DialogResult.OK)
                        {
                            LoadDb();
                        }
                        frm.Dispose(); 
                    }));
                }
                return; 
#endregion
            }
            Point pt;
            pt = ((IconViewEx)(sender)).PointToClient(new Point(e.X, e.Y));
            var to_item = IconViewEx1.GetItemAt(pt.X, pt.Y);
            if (to_item == null) { return; }
            //获得拖放中的项
            ListViewItem lvi = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
            if (lvi == null) { return; }
            if (lvi.ListView!=IconViewEx1) { return; }
            if (lvi.Index == to_item.Index) { return; }
            IconViewEx1.BeginUpdate();
            IconViewEx1.View = View.List;
            IconViewEx1.Items.RemoveAt(lvi.Index);
            IconViewEx1.Items.Insert(to_item.Index, lvi);
            IconViewEx1.View = View.Tile;
            IconViewEx1.EndUpdate();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(SQLConnStr) == 1)
            {
                ReSortSoftByList(db);
            }
            db.Free();
        }
        private void IconViewEx1_DragOver(object sender, DragEventArgs e)
        {
            ListViewItem item = null;
            if (sender is IconViewEx)
            {
                var filedrop = e.Data.GetData(DataFormats.FileDrop);
                if (filedrop != null) {
                    if (LblDrag.Visible) { LblDrag.Visible = false; }
                    return; 
                }
                var lvi = e.Data.GetData(typeof(ListViewItem));
                if(lvi==null)
                {
                    if (LblDrag.Visible) { LblDrag.Visible = false; }
                    return;
                }
                else
                {
                    var lvi2 = (ListViewItem)lvi;
                    if(lvi2.ListView!=IconViewEx1)
                    {
                        if (LblDrag.Visible){LblDrag.Visible = false;}
                        return;
                    }
                }
                var list = ((IconViewEx)(sender));
                var pt = list.PointToClient(new Point(e.X, e.Y));
                item = list.GetItemAt(pt.X, pt.Y);
            }
            else if (sender is TabList)
            {
                var list = ((TabList)(sender));
                var pt = list.PointToClient(new Point(e.X, e.Y));
                item = list.GetItemAt(pt.X, pt.Y);
            }
            if (item == null)
            {
                if (LblDrag.Visible)
                {
                    LblDrag.Visible = false;
                }
            }
            else
            {
                if (!LblDrag.Visible)
                {
                    LblDrag.Visible = true;
                }
                LblDrag.Location = item.Position;
            }
        }
#endregion
#region 栏目拖放
        private void TabList_Column_DragEnter(object sender, DragEventArgs e)
        {
            if (ReadOnly)
            {
                e.Effect = DragDropEffects.None;
                return;
            }
            //判定是否现在拖动的数据是LISTVIEW项
            ListViewItem lvi = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
            if (lvi != null)
            {
                LblDrag.Height = TabList_Column.TileSize.Height;
                LblDrag.Parent = TabList_Column;
                e.Effect = DragDropEffects.Move;
            }
        }
        private void TabList_Column_DragDrop(object sender, DragEventArgs e)
        {
            LblDrag.Visible = false;
            Point pt;
            pt = ((TabList)(sender)).PointToClient(new Point(e.X, e.Y));
            var item = TabList_Column.GetItemAt(pt.X, pt.Y);
            if (item == null) { return; }
            var columnid = ((ColumnInfo)item.Tag).Id;
            //获得拖放中的项
            var drag_item = e.Data.GetData(typeof(ListViewItem));
            if (drag_item == null) { return; }
            ListViewItem lvi = (ListViewItem)drag_item;
            if (lvi.ListView == IconViewEx1)
            {
#region 从软件列表里拖放
                var info = (SoftInfo)lvi.Tag;
                RyQuickSQL mySQL = new RyQuickSQL("Softs");
                mySQL.AddField("ColumnId", columnid);
                mySQL.AddField("editTime", DateTime.Now);
                IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
                if (db.ConnDb(SQLConnStr) == 1)
                {
                    mySQL.AddField("sortindex", Itrycn_Db.GetSoftCount(db, columnid) + 1);
                    db.ExecuteNonQuery(mySQL.GetUpdateSQL() + " where id=" + info.Id, mySQL);
                    if (TabList_Column.SelectedItems.Count > 0)
                    {
                        var column_info = (ColumnInfo)TabList_Column.SelectedItems[0].Tag;
                        if (column_info.Id != columnid)
                        {
                            lvi.Remove();
                        }
                        else if (TabList_Type.SelectedItems.Count > 0 && ((ColumnInfo)TabList_Type.SelectedItems[0].Tag).Id > 0)
                        {
                            lvi.Remove();
                        }
                    }
                    else
                    {
                        lvi.Remove();
                    }
                    ReSortSoftByList(db);
                }
                db.Free(); 
#endregion
            }
            else if (lvi.ListView == TabList_Column)
            {
                if (lvi.Index == item.Index) { return; }
                TabList_Column.BeginUpdate();
                TabList_Column.View = View.List;
                TabList_Column.Items.RemoveAt(lvi.Index);
                TabList_Column.Items.Insert(item.Index, lvi);
                TabList_Column.View = View.Tile;
                TabList_Column.EndUpdate();
                IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
                if (db.ConnDb(SQLConnStr) == 1)
                {
                    db.BeginTransaction();
                    for (int i = 0; i < TabList_Column.Items.Count; i++)
                    {
                        var id = ((ColumnInfo)TabList_Column.Items[i].Tag).Id;
                        RyQuickSQL mySQL = new RyQuickSQL("Columns");
                        mySQL.AddField("sortindex", i + 1);
                        db.ExecuteNonQuery(mySQL.GetUpdateSQL() + " where id=" + id, mySQL);
                    }
                    db.Commit();
                }
                db.Free();
            }
        }
        private void TabList_Column_ItemDrag(object sender, ItemDragEventArgs e)
        {
            if (ReadOnly) { return; }
            this.DoDragDrop(e.Item, DragDropEffects.Move);
        }
#endregion
#region 分类拖放
        private void TabList_Type_DragEnter(object sender, DragEventArgs e)
        {
            if (ReadOnly)
            {
                e.Effect = DragDropEffects.None;
                return;
            }
            //判定是否现在拖动的数据是LISTVIEW项
            ListViewItem lvi = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
            if (lvi != null)
            {
                LblDrag.Height = TabList_Type.TileSize.Height;
                LblDrag.Parent = TabList_Type;
                e.Effect = DragDropEffects.Move;
            }
        }

        private void TabList_Type_DragDrop(object sender, DragEventArgs e)
        {
            LblDrag.Visible = false;
            Point pt;
            pt = ((TabList)(sender)).PointToClient(new Point(e.X, e.Y));
            var item = TabList_Type.GetItemAt(pt.X, pt.Y);
            if (item == null) { return; }
            var columnid = ((ColumnInfo)item.Tag).Id;
            if (columnid == 0)
            {
                if (TabList_Column.SelectedItems.Count > 0)
                {
                    columnid = ((ColumnInfo)TabList_Column.SelectedItems[0].Tag).Id;
                }
            }
            //获得拖放中的项
            var drag_item = e.Data.GetData(typeof(ListViewItem));
            if (drag_item == null) { return; }
            ListViewItem lvi = (ListViewItem)drag_item;
            if (lvi.ListView == IconViewEx1)
            {
#region 来源自软件列表
                var info = (SoftInfo)lvi.Tag;
                RyQuickSQL mySQL = new RyQuickSQL("Softs");
                mySQL.AddField("ColumnId", columnid);
                mySQL.AddField("editTime", DateTime.Now);
                IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
                if (db.ConnDb(SQLConnStr) == 1)
                {
                    mySQL.AddField("sortindex", Itrycn_Db.GetSoftCount(db, columnid) + 1);
                    db.ExecuteNonQuery(mySQL.GetUpdateSQL() + " where id=" + info.Id, mySQL);
                    if (TabList_Type.SelectedItems.Count > 0)
                    {
                        if (((ColumnInfo)TabList_Type.SelectedItems[0].Tag).Id != columnid)
                        {
                            lvi.Remove();
                        }
                    }
                    else { lvi.Remove(); }
                    ReSortSoftByList(db);
                }
                db.Free();
#endregion
            }
            else if (lvi.ListView == TabList_Type)
            {
                if (lvi.Index == item.Index || item.Index==0 || lvi.Index==0) { return; }
                TabList_Type.BeginUpdate();
                TabList_Type.View = View.List;
                TabList_Type.Items.RemoveAt(lvi.Index);
                TabList_Type.Items.Insert(item.Index, lvi);
                TabList_Type.View = View.Tile;
                TabList_Type.EndUpdate();
                IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
                if (db.ConnDb(SQLConnStr) == 1)
                {
                    db.BeginTransaction();
                    for (int i = 1; i < TabList_Type.Items.Count; i++)
                    {
                        var id = ((ColumnInfo)TabList_Type.Items[i].Tag).Id;
                        RyQuickSQL mySQL = new RyQuickSQL("Columns");
                        mySQL.AddField("sortindex", i);
                        db.ExecuteNonQuery(mySQL.GetUpdateSQL() + " where id=" +id, mySQL);
                    }
                    db.Commit();
                }
                db.Free();
            }
        }
        private void TabList_Type_ItemDrag(object sender, ItemDragEventArgs e)
        {
            if (ReadOnly) { return; }
            this.DoDragDrop(e.Item, DragDropEffects.Move);
        }
#endregion
        private void FrmVSoft_Shown(object sender, EventArgs e)
        {
        }
        private void TabList_Type_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (IsProcUse) { return; }
            LoadDb();
        }
        private void TabList_Column_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (IsProcUse) { return; }
            if (TabList_Column.SelectedItems.Count > 0)
            {
                var info = (ColumnInfo)TabList_Column.SelectedItems[0].Tag;
                if (info.Des.Length > 0)
                {
                    LblDes.Text = info.Des;
                    panel1.Visible = true;
                }
                else
                {
                    panel1.Visible = false;
                }
                LoadTypeColumn(info.Id);
            }
            else
            {
                panel1.Visible = false;
                LoadTypeColumn(-1);
            }
            //LoadDb();
        }
        /// <summary>
        /// 将当前列表中的软件在数据库中排序
        /// </summary>
        /// <param name="db"></param>
        private void ReSortSoftByList(IDbInterface db)
        {
            db.BeginTransaction();
            for (int i = 0; i < IconViewEx1.Items.Count; i++)
            {
                var info = (SoftInfo)IconViewEx1.Items[i].Tag;
                RyQuickSQL mySQL = new RyQuickSQL("Softs");
                mySQL.AddField("sortindex", i + 1);
                db.ExecuteNonQuery(mySQL.GetUpdateSQL() + " where id=" + info.Id, mySQL);
            }
            db.Commit();
        }

        private void FrmVSoft_FormClosing(object sender, FormClosingEventArgs e)
        {
        }

        private void TabList_Column_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode==Keys.Down)
            {
                if(IconViewEx1.Items.Count>0)
                {
                    if(IconViewEx1.SelectedItems.Count==0)
                    {
                        IconViewEx1.Items[0].Selected = true ;
                    }
                    IconViewEx1.Focus();
                }
            }
            else if (e.KeyCode == Keys.Up)
            {
                rySearch1.Focus();
            }
        }

        private void TabList_Type_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Right)
            {
                if (IconViewEx1.Items.Count > 0)
                {
                    if (IconViewEx1.SelectedItems.Count == 0)
                    {
                        IconViewEx1.Items[0].Selected = true;
                    }
                    IconViewEx1.Focus();
                }
            }
        }

        private void rySearch1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down)
            {
                if (TabList_Column.SelectedItems.Count == 0)
                {
                    if (IconViewEx1.Items.Count > 0)
                    {
                        if (IconViewEx1.SelectedItems.Count == 0)
                        {
                            IconViewEx1.Items[0].Selected = true;
                        }
                        IconViewEx1.Focus();
                        return;
                    }
                }
                TabList_Column.Focus();
                var color = TabList_Column.SelectedStartBackColor;
                TabList_Column.SelectedStartBackColor = Color.LightYellow;
                using (var bg = new BackgroundWorker())
                {
                    bg.DoWork += delegate { System.Threading.Thread.Sleep(500); };//180秒后,3分钟
                    bg.RunWorkerCompleted += delegate {
                        this.Invoke(new Action(() =>
                        {
                            TabList_Column.SelectedStartBackColor = color;
                        }));
                    }; // 线程执行完成后会执行 RunWorkerCompleted 事伯的代码块
                    bg.RunWorkerAsync();
                }
            }
        }


        private void 复制并新增软件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (IconViewEx1.SelectedItems.Count == 0) { return; }
            var info = (SoftInfo)IconViewEx1.SelectedItems[0].Tag;
            var ColumnId =GetCurColumnId();
            if (ColumnId == 0)
            {
                Msg.ShowMsg("当前模式下不支持添加软件。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            FrmAddSoft frm = new FrmAddSoft
            {
                SQLConnStr = SQLConnStr,
                ColumnId = ColumnId,
                TopMost=TopMost
            };
            frm.GetInfo(info.Id);
            frm.Text = "复制并新增软件";
            frm.SelectId = -1;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                LoadDb();
            }
            frm.Dispose();
        }
    }
}
