using DotNet4.Utilities;
using HtmlAgilityPack;
using Microsoft.Win32;
using ryCommon;
using ryCommonDb;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using WeifenLuo.WinFormsUI.Docking;
using 开发辅助工具.Manager;
using 开发辅助工具.Tools;

namespace 开发辅助工具
{
    public partial class Form1 : Form
    {
        public Form1(string ProjectPath,string mode)
        {          
            InitializeComponent();
            if(ProjectPath!="")
            {
                if (mode == "get")
                {
                    FrmProject frm = new FrmProject(ProjectPath);
                    frm.Show(dockPanel1);
                }
                else if (mode == "open")
                {
                    FrmPathInfo frm = new FrmPathInfo(ProjectPath);
                    frm.Show(dockPanel1);
                }
            }
            Manager.Itrycn_Db.CreateDb();
            LoadBaseTools();

        }
        private void DockPanel1_ActiveContentChanged(object sender, EventArgs e)
        {
            if(dockPanel1.ActiveContent is FrmWebGet frm)
            {
                var clip_text = Clipboard.GetText();
                var ClipChanged = false;
                if (clip_text != Itrycn_Db.last_clip_text)
                {
                    ClipChanged = true;
                    Itrycn_Db.last_clip_text = clip_text;
                }
                if (ClipChanged)
                {
                    if(Itrycn_Db.last_clip_text.IndexOfEx("qurl://") >= 0)
                    {
                        switch (MessageBox.Show("是否确定要导入配置?\r\n\r\n" + Itrycn_Db.last_clip_text, "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2))
                        {
                            case DialogResult.Yes:
                                Focus();
                                frm.导入当前设置ToolStripMenuItem.PerformClick();
                                Focus();
                                break;
                            default:
                                frm.BringToFront();
                                Focus();
                                break;
                        }
                    }
                }
            }
        }

        public void HideDownList()
        {
            table1.Visible = false;
        }
        private void LoadBaseTools()
        {
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(Itrycn_Db.User_SQLConn) == 1)
            {
                DataSet ds = db.ReadData("select * from Starts order by ClickCount desc,editTime desc");
                if(mydb.HaveData(ds))
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        DataRow row = ds.Tables[0].Rows[i];
                        Type type = Type.GetType(row["Addr"].ToString());
                        if (type == null) { continue; }
                        ShowForm(type);                                             
                    }
                }
                else
                {
                    ShowForm(typeof(FrmWebGet));
                    ShowForm(typeof(FrmXpath));
                    ShowForm(typeof(FrmRegex));
                    ShowForm(typeof(FrmEncode));
                }
            }
            db.Free();
            //ShowForm(Type.GetType("开发辅助工具.Tools.FrmWebGet"));
            //ShowForm(typeof(FrmToolsBox));
            //FrmProject frm = new FrmProject(ProjectPath);
            //frm.Show(dockPanel1);
        }
        private void ShowForm(Type type)
        {
            DockContent frm = (DockContent)Activator.CreateInstance(type);
            frm.Click += Frm_Click;
            frm.Show(dockPanel1);
        }

        private void Frm_Click(object sender, EventArgs e)
        {
            HideDownList();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Text = "开发辅助工具 V"+ryCommon.RySoft.VersionStr;
            bool test_mode = false;
            if (System.IO.File.Exists(Application.StartupPath + "\\测试.txt")){test_mode = true;}
            BtnTools.Visible = test_mode;
            BtnCreateProject.Visible = test_mode;
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(Itrycn_Db.User_SQLConn) == 1)
            {
                RyQuickSQL mySQL = new RyQuickSQL("Urls");
                mySQL.AddField("editTime",DateTime.Now.AddDays(-10));
                db.ExecuteNonQuery("DELETE FROM Urls WHERE id IN (SELECT id FROM Urls ORDER BY ClickCount desc,editTime desc LIMIT 1000,50) and editTime<=@editTime and IsFav<>1", mySQL);
            }
            db.Free();
        }
       
        private void BtnTools_Click(object sender, EventArgs e)
        {
            FrmToolsSearch frm = new FrmToolsSearch();
            frm.ShowDialog();
        }
        private void Search()
        {
            string sql_where = "";
            if (rySearch1.Text != "") { sql_where = " where (Name like @SearchText or Des like @SearchText or Keys like @SearchText or PY like @SearchText)"; }
            #region 重新载入数据
            tableModel1.Rows.Clear();
            tableModel1.Selections.Clear();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(Itrycn_Db.Sys_SQLConn) == 1)
            {
                db.AddParameter("SearchText", "%" + rySearch1.Text + "%");
                DataSet ds = db.ReadData("select * from Tools" + sql_where + " order by sort desc, addTime desc", db.GetParameter());
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow row = ds.Tables[0].Rows[i];
                    XPTable.Models.Row itemList = new XPTable.Models.Row()
                    {
                        Tag = row["Addr"].ToString()
                    };
                    //需要修改此处
                    itemList.Cells.Add(new XPTable.Models.Cell(row["Name"].ToString()));//示例
                    var cell = new XPTable.Models.Cell(row["Des"].ToString())
                    {
                        ForeColor = Color.Gray
                    };
                    itemList.Cells.Add(cell);
                    tableModel1.Rows.Add(itemList);
                }
                db.Free();
                textColumn4.Text = "工具名称(" + tableModel1.Rows.Count + ")";
                table1.Visible = tableModel1.Rows.Count != 0;
            }
            #endregion
        }
        private void RySearch1_OnTextChanged(object sender, EventArgs e)
        {
            Search();
        }

        private void RySearch1_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode==Keys.Down)
            {
                if (table1.Visible)
                {
                    table1.TableModel.Selections.Clear();
                    table1.TableModel.Selections.AddCells(0, 0, 0, columnModel1.Columns.Count - 1);
                    table1.Focus();
                }
            }
        }

        private void Table1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Up)
            {
                if (table1.SelectedItems.Length>0 && table1.SelectedItems[0].Index==0)
                {
                    table1.TableModel.Selections.Clear();
                    rySearch1.Select();
                }
            }
            else if(e.KeyCode==Keys.Enter)
            {
                ClickItem();
            }
        }

        private void DockPanel1_Enter(object sender, EventArgs e)
        {
            table1.Visible = false;
        }

        private void Panel1_Click(object sender, EventArgs e)
        {
            table1.Visible = false;
        }
        private void ClickItem()
        {
            if (table1.SelectedItems.Length > 0)
            {
                table1.Visible = false;
                Application.DoEvents();
                string addr = table1.SelectedItems[0].Tag.ToString();
                Type type = Type.GetType("开发辅助工具." + addr);
                if (type == null)
                {
                    MessageBox.Show("无法找到工具", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    ShowForm(type);
                }
            }
        }
        private void Table1_Click(object sender, EventArgs e)
        {
            ClickItem();
        }
        protected override void WndProc(ref Message m)
        {
            //Console.WriteLine(m.Msg);
            const int WM_SYSCOMMAND = 0x0112;
            const int SC_CLOSE = 0xF060;
            #region 关闭软件时
            if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE)
            {
                //捕捉关闭窗体消息      
                //用户点击关闭窗体控制按钮   注释为最小化窗体   
                //this.WindowState = FormWindowState.Minimized;
                if (Itrycn_Db.IsCloseConfirm)
                {
                    switch (MessageBox.Show("是否确定要关闭所有窗口?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                    {
                        case DialogResult.Cancel:
                            RyForm.SetActiveWindow(Handle);
                            return;
                        case DialogResult.OK:
                            Itrycn_Db.IsCloseConfirm = false;
                            break;
                    }
                }
            }
            #endregion
            base.WndProc(ref m);
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Itrycn_Db.IsCloseConfirm = false;
        }

        private void RySearch1_Leave(object sender, EventArgs e)
        {
            if (!table1.Focused)
            {
                table1.Visible = false;
            }
        }

        private void Table1_Leave(object sender, EventArgs e)
        {
            if (!rySearch1.Focused)
            {
                table1.Visible = false;
            }
        }

        private void BtnSetting_Click(object sender, EventArgs e)
        {
            FrmSetting frm = new FrmSetting
            {
                Icon = Icon
            };
            frm.ShowDialog();
            frm.Dispose();
        }

        private void BtnCreateProject_Click(object sender, EventArgs e)
        {
            FrmCreateProject frm = new FrmCreateProject
            {
                Icon = Icon,
                StartPosition = FormStartPosition.CenterParent
            };
            frm.ShowDialog();
            frm.Dispose();
        }

        private void BtnEditor_Click(object sender, EventArgs e)
        {
            RyFiles.OpenFile(Application.StartupPath+"\\RySmartEditor.exe");
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            dockPanel1.ActiveContentChanged += DockPanel1_ActiveContentChanged;
        }

        private void rySearch1_Click(object sender, EventArgs e)
        {

        }

        private void rySearch1_MouseClick(object sender, MouseEventArgs e)
        {
            if (rySearch1.Text.Length == 0)
                Search();
        }
    }

}