using DotNet4.Utilities;
using ICSharpCode.TextEditor.Document;
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.Threading;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using 开发辅助工具.Manager;

namespace 开发辅助工具.Tools
{
    public partial class FrmWebGet : DockContent
    {
        public FrmWebGet()
        {
            InitializeComponent();
            LoadPram();
            tabControl2.SelectedTab = tabPage12;
            Te_Format.Document.FoldingManager.FoldingStrategy = new JackWangCUMT.WinForm.MingFolding();
        }
        private void LoadPram()
        {
            Te_Format.IsReadOnly = true;
            CbbContentType.SelectedIndex = 0;
            CbbUserAgent.SelectedIndex = 0;
            CbbEncoding.SelectedIndex = 0;
            CbbTimeout.SelectedIndex = CbbTimeout.Items.Count-2;
            CbbWriteTimeout.SelectedIndex = CbbWriteTimeout.Items.Count - 2;
            CbbUserAgent.Items.AddRange(new UserAgentInfo[]{
                new UserAgentInfo() { name = "QQ浏览器极速模式", useragent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6776.400 QQBrowser/10.3.2601.400" },
                new UserAgentInfo() { name = "360浏览器极速模式", useragent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36" },
                new UserAgentInfo() { name = "QQ浏览器手机版", useragent = "Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BLA-AL00 Build/HUAWEIBLA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/8.9 Mobile Safari/537.36" },
                new UserAgentInfo() { name = "微信", useragent = "Mozilla/5.0 (Linux; U; Android 4.1.2; zh-cn; GT-I9300 Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 MicroMessenger/5.2.380" },
                new UserAgentInfo() { name = "iPhone", useragent = "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1C28 Safari/419.3" },
                new UserAgentInfo() { name = "安卓", useragent = "Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03S) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19" },
            });
            TxtPost.AddSeparatorMenu();
            TxtPost.AddMenu("将选定项进行Url编码(UTF8)", "").Click += new EventHandler((object sender2, EventArgs e2) =>
            {
                RyWeb.QuickWeb web = new RyWeb.QuickWeb();
                TxtPost.SelectedText = web.UrlEncode(TxtPost.SelectedText, Encoding.UTF8);
            });
            TxtPost.AddMenu("将选定项进行Url编码(GB2312)", "").Click += new EventHandler((object sender2, EventArgs e2) =>
            {
                RyWeb.QuickWeb web = new RyWeb.QuickWeb();
                TxtPost.SelectedText = web.UrlEncode(TxtPost.SelectedText, Encoding.GetEncoding("GB2312"));
            });
            TxtPost.AddSeparatorMenu();
            TxtPost.AddMenu("将选定项进行Url解码(UTF8)", "").Click += new EventHandler((object sender2, EventArgs e2) =>
            {
                TxtPost.SelectedText = RyWeb.WebDecode.UrlDecode(TxtPost.SelectedText, Encoding.UTF8);
            });
            TxtPost.AddMenu("将选定项进行Url解码(GB2312)", "").Click += new EventHandler((object sender2, EventArgs e2) =>
            {
                TxtPost.SelectedText = RyWeb.WebDecode.UrlDecode(TxtPost.SelectedText, Encoding.GetEncoding("GB2312"));
            });
            TxtPost.AddSeparatorMenu();
            TxtPost.AddMenu("查询选定项对应的时间", "unixtime").Click += new EventHandler((object sender2, EventArgs e2) =>
            {
                MessageBox.Show("当前选中的时间是:" + RyDate.UnixTimeToDateTime(TxtPost.SelectedText).ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            });
            TxtPost.AddMenu("插入时间戳", "").Click += new EventHandler((object sender2, EventArgs e2) =>
            {
                SuperDesign.Controls.FrmInsertUnixTime frm = new SuperDesign.Controls.FrmInsertUnixTime();
                frm.Icon = Icon;
                var text = TxtPost.SelectedText;
                if(text.Length>4 && text.IsInt())
                {
                    frm.dateTimePickerEX1.Value = RyDate.UnixTimeToDateTime(text);
                }
                if (frm.ShowDialog()==DialogResult.OK)
                {
                    TxtPost.SelectedText = RyDate.DateTimeToUnixTime(frm.dateTimePickerEX1.Value).ToString();
                }
               // MessageBox.Show("当前选中的时间是:" + RyDate.UnixTimeToDateTime(TxtPost.SelectedText).ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            });
            TxtPost.OnMenuOpening += TxtPost_OnMenuOpening;
        }

        private void TxtPost_OnMenuOpening(object sender, CancelEventArgs e)
        {
            var item= TxtPost.GetMenuItem("unixtime");
            if(item!=null)
            {
                var text = TxtPost.SelectedText;
                item.Visible = text.IsInt() && text.Length>4;
            }
        }

        private bool IsExit = false;
        private bool IsRunning = false;
        Thread th;
        private void BtnRunHtml_Click(object sender, EventArgs e)
        {
            if (IsRunning) {
                IsExit = true;
                BtnRunHtml.Text = "停止中"; ;
                if (th!=null && th.IsAlive)
                {
                    th.Abort();
                }
                return;
            }
            IsExit = false;
            IsRunning = true;
            BtnRunHtml.Text = "停止执行"; ;
            #region 将当前设置赋值到查询
            this.RichHtml.Text = "正在获取数据...";
            Te_Format.Text = "正在获取数据...";
            this.RichCookie.Text = "";
            RichHeader.Text = "";
            RichStatus.Text = "";
            extendedWebBrowser1.LoadStrings("");
            if (TxtUrl.Text.IndexOfEx("//") == 0)
            {
                TxtUrl.Text = "http:" + TxtUrl.Text;
            }
            else if (TxtUrl.Text.IndexOfEx("://") == 0)
            {
                TxtUrl.Text = "http" + TxtUrl.Text;
            }
            else if (TxtUrl.Text.IndexOfEx("http") != 0)
            {
                TxtUrl.Text = "http://" + TxtUrl.Text.TrimStart('/');
            }

            string str = "get";
            if (RbGet.Checked)
            {
                str = "get";
            }
            if (RbPost.Checked)
            {
                str = "post";
            }
            HttpItem item = new HttpItem
            {
                URL = TxtUrl.Text.Trim(),
                Method = str,
                IsToLower = this.ChkUrlLower.Checked,
                Cookie = this.TxtCookie.Text.Trim(),
                Referer = this.CbbReferer.Text.Trim(),
                Postdata = this.TxtPost.Text.Trim(),
                Timeout = Convert.ToInt32(this.CbbTimeout.Text.Replace("秒", string.Empty).Trim()) * 0x3e8,
                ReadWriteTimeout = Convert.ToInt32(this.CbbWriteTimeout.Text.Replace("秒", string.Empty).Trim()) * 0x3e8,
                UserAgent = this.CbbUserAgent.Text,
                ContentType = this.CbbContentType.Text,
                Allowautoredirect = this.ChkJump.Checked,
                ProtocolVersion = System.Net.HttpVersion.Version11,
                ResultType = ChkGetPic.Checked ? ResultType.Byte : ResultType.String,
            };
            if (TxtInputHeader.Text.Length > 0)
            {
                try
                {
                    string[] item_header = TxtInputHeader.Text.Replace("\r", "").Split('\n');
                    for (int i = 0; i < item_header.Length; i++)
                    {
                        item.Header.Add(item_header[i]);
                        //int iPos = item_header[i].LastIndexOf(":");
                        //if (iPos > 0)
                        //{
                        //    var header_name = item_header[i].Substring(0, iPos);
                        //    var header_value = item_header[i].Substring(iPos + 1);
                        //    item.Header.Add(header_name, header_value);
                        //}
                    }
                }
                catch (Exception exception)
                {
                    this.RichHtml.Text = exception.Message;
                    Te_Format.Text = "";
                    tabControl2.SelectedIndex = 0;
                    BtnRunHtml.Text = "执行";
                    IsRunning = false;
                    return;
                }
            }
            if (CbbUserAgent.SelectedIndex != -1)
            {
                if (CbbUserAgent.SelectedItem is UserAgentInfo)
                {
                    item.UserAgent = ((UserAgentInfo)CbbUserAgent.SelectedItem).useragent;
                }
            }
            if (!string.IsNullOrEmpty(this.CbbIp.Text.Trim()))
            {
                item.ProxyIp = this.CbbIp.Text.Trim();
            }
            if (!this.CbbEncoding.Text.Contains("自动"))
            {
                item.Encoding = Encoding.GetEncoding(this.CbbEncoding.Text.Trim());
            }
            #endregion
            if (th != null && th.IsAlive)
            {
                th.Abort();
            }
            th = new Thread(Start);
            th.Start();
            void Start()
            {
                try
                {
                    var http = new HttpHelper();
                    DateTime dt = DateTime.Now;
                    var result = http.GetHtml(item);
                    DateTime dt_end = DateTime.Now;
                    _ = this.Invoke(new Action(() =>
                      {
                          #region 将获得的结果显示出来
                          if (result.Html.Length > 1024 * 1024 * 4)
                          {
                              this.RichHtml.Text = "获取失败,您要获取的网页超过4MB，暂时无法获取。";
                              Te_Format.Text = "获取失败,您要获取的网页超过4MB，暂时无法获取。";
                          }
                          else
                          {
                              if (result.StatusCode == System.Net.HttpStatusCode.Redirect)
                              {
                                  if (!ChkJump.Checked)
                                  {
                                      switch (MessageBox.Show("当前Url需要跳转,是否勾选跳转重试获取？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                                      {
                                          case DialogResult.Yes:
                                              ChkJump.Checked = true;
                                              IsRunning = false;
                                              BtnRunHtml_Click(sender, e);
                                              return;
                                      }
                                  }
                              }
                              RichHtml.Text = string.Empty;
                              if (this.ChkGetPic.Checked)
                              {
                                  pictureBox1.Image = this.ByteArrayToImage(result.ResultByte);
                                  RichHtml.Visible = false;
                                  pictureBox1.Visible = true;
                                  tabControl2.SelectedIndex = 0;
                                  AddUrl("", TxtUrl.Text);
                              }
                              else
                              {
                                  this.RichHtml.Text = result.Html;
                                  if (Manager.Json.IsJson(result.Html))
                                  {
                                      Te_Format.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy("JSON");
                                      Te_Format.Text = Manager.Json.ConvertJsonString(result.Html);
                                      AddUrl("", TxtUrl.Text);
                                  }
                                  else
                                  {
                                      string[] _format_html = result.Html.Replace("\r", "").Split('\n');
                                      string _html = "";
                                      for (int i = 0; i < _format_html.Length; i++)
                                      {
                                          if (_format_html[i].Trim().Length == 0)
                                          {
                                              continue;
                                          }
                                          if (_html.Length > 0) { _html += "\r\n"; }
                                          _html += _format_html[i];
                                      }
                                      Te_Format.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy("HTML");
                                      try
                                      {
                                          Te_Format.Text = JJCCX.Xml.HtmlFormater.ConvertToXml(_html, true);
                                      }
                                      catch
                                      {
                                          Te_Format.Text = _html;
                                      }
                                      if (result.StatusCode == System.Net.HttpStatusCode.Redirect || result.StatusCode == System.Net.HttpStatusCode.OK)
                                      {
                                          string title = "";
                                          try
                                          {
                                              HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
                                              htmlDoc.LoadHtml(result.Html);
                                              var anchors = htmlDoc.DocumentNode.SelectNodes("//title");
                                              if (anchors != null && anchors.Count > 0)
                                              {
                                                  title = RyWeb.WebDecode.ConvertHtmlInner(anchors[0].InnerText);
                                              }
                                          }
                                          catch { }
                                          AddUrl(title, TxtUrl.Text);
                                      }
                                  }
                                  this.RichHtml.Visible = true;
                                  this.pictureBox1.Visible = false;
                              }
                          }
                          this.RichCookie.Text = result.Cookie;
                          var timespan = (dt_end - dt).TotalMilliseconds.ToInt();
                          string timespan_str = "";
                          if (timespan < 1000) { timespan_str = timespan + "毫秒"; }
                          else { timespan_str = timespan / 1000 + "秒" + timespan % 1000 + "毫秒"; }
                          this.RichStatus.Text = "StatusCode:" + result.StatusCode.ToString() + "\r\nStatusDescription:" + result.StatusDescription + "\r\n耗时:" + timespan_str;
                          this.RichHeader.Text = "";
                          if (result.Header != null)
                          {
                              foreach (string str1 in result.Header.AllKeys)
                              {
                                  string text = this.RichHeader.Text;
                                  this.RichHeader.Text = text + str1 + ":" + result.Header[str1].ToString() + "\r\n";
                              }
                          }
                          if (!ChkNoPreview.Checked)
                          {
                              if (ChkHtmlPreview.Checked)
                              {
                                  if (!this.CbbEncoding.Text.Contains("自动"))
                                  {
                                      extendedWebBrowser1.LoadStrings(RichHtml.Text.Trim(), Encoding.GetEncoding(this.CbbEncoding.Text.Trim()));
                                  }
                                  else { extendedWebBrowser1.LoadStrings(RichHtml.Text.Trim(), Encoding.UTF8); }
                                  //MessageBox.Show(extendedWebBrowser1.Document.Encoding);
                                  //extendedWebBrowser1.Document.Encoding = Encoding.UTF8.BodyName;
                              }
                              else
                              {
                                  if (RbGet.Checked)
                                  {
                                      extendedWebBrowser1.Navigate(TxtUrl.Text, null, null, TxtInputHeader.Text);
                                  }
                                  else
                                  {
                                      string strData = TxtPost.Text;
                                      string strHeaders = "Content-Type: " + CbbContentType.Text + "\r\n" + TxtInputHeader.Text;
                                      ASCIIEncoding AE = new ASCIIEncoding();
                                      byte[] bytePost = AE.GetBytes(strData);
                                      //byte[] byteHeaders = AE.GetBytes(strHeaders);
                                      extendedWebBrowser1.Navigate(TxtUrl.Text, null, bytePost, strHeaders);
                                  }
                              }
                          }
                          #endregion
                      }));
                }
                catch (Exception exception)
                {
                    this.Invoke(new Action(() =>
                    {
                        if (IsExit)
                        { 
                            this.RichHtml.Text = "用户中断执行";
                            BtnRunHtml.Text = "执行";
                            IsRunning = false;
                        }
                        else
                        {
                            this.RichHtml.Text = exception.Message;
                        }
                        Te_Format.Text = "";
                    }));
                }
                this.Invoke(new Action(() =>
                {
                    BtnRunHtml.Text = "执行";
                    IsRunning = false;
                }));
            }

        }

        private Image ByteArrayToImage(byte[] Bytes)
        {
            MemoryStream stream = new MemoryStream(Bytes);
            return Image.FromStream(stream, true);
        }

        private void TxtUrl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                BtnRunHtml.PerformClick();
            }
            else 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 FrmWebGet_Load(object sender, EventArgs e)
        {
            contextMenuStripHighlightText1.AddSeparatorMenu();
            contextMenuStripHighlightText1.AddMenu("将选中的内容作为Json分析", "").Click += AnalyJson_Click;
            for (int i = 0; i < this.Controls.Count; i++)
            {
                switch (this.Controls[i])
                {
                    case GroupBox gb:
                        gb.Click += Gb_Click;
                        break;
                }
            }
        }

        private void Gb_Click(object sender, EventArgs e)
        {
            table1.Visible = false;
            //RbGet.Focus();
            switch ((this.DockPanel.FindForm()))
            {
                case Form1 frm:
                    frm.HideDownList();
                    break;
            }
        }

        private void AnalyJson_Click(object sender, EventArgs e)
        {
            ContextMenuStrip menu =(ContextMenuStrip) (((ToolStripMenuItem)sender).Owner);
            switch(menu.SourceControl)
            {
                case ICSharpCode.TextEditor.TextEditorControl rich_txt:
                    var SelectedText= rich_txt.ActiveTextAreaControl.SelectionManager.SelectedText;
                    if (SelectedText == "") { SelectedText = rich_txt.Text; }
                    //if (Manager.Json.IsJson(SelectedText))
                    {
                        FrmJson frm = new FrmJson();
                        frm.Show(this.DockPanel);
                        frm.LoadJson(SelectedText);
                    }
                    break;
                case RichTextBox rich_txt2:
                    var SelectedText2 = rich_txt2.SelectedText;
                    if (SelectedText2 == "") { SelectedText2 = rich_txt2.Text; }
                    //if (Manager.Json.IsJson(SelectedText2))
                    {
                        FrmJson frm = new FrmJson();
                        frm.Show(this.DockPanel);
                        frm.LoadJson(SelectedText2);
                    }
                    break;
            }
        }

        private void BtnCtreateCShape_Click(object sender, EventArgs e)
        {
            string str = "get";
            if (RbGet.Checked)
            {
                str = "get";
            }
            if (RbPost.Checked)
            {
                str = "post";
            }
            HttpItem item = new HttpItem
            {
                URL = TxtUrl.Text.Trim(),
                Method = str,
                IsToLower = this.ChkUrlLower.Checked,
                Cookie = this.TxtCookie.Text.Trim(),
                Referer = this.CbbReferer.Text.Trim(),
                Postdata = this.TxtPost.Text.Trim(),
                Timeout = Convert.ToInt32(this.CbbTimeout.Text.Replace("秒", string.Empty).Trim()) * 0x3e8,
                ReadWriteTimeout = Convert.ToInt32(this.CbbWriteTimeout.Text.Replace("秒", string.Empty).Trim()) * 0x3e8,
                UserAgent = this.CbbUserAgent.Text,
                ContentType = this.CbbContentType.Text,
                Allowautoredirect = this.ChkJump.Checked,
                ResultType = ChkGetPic.Checked ? ResultType.Byte : ResultType.String
            };
            if (CbbUserAgent.SelectedIndex != -1)
            {
                if (CbbUserAgent.SelectedItem is UserAgentInfo)
                {
                    item.UserAgent = ((UserAgentInfo)CbbUserAgent.SelectedItem).useragent;
                }
            }
            if (!string.IsNullOrEmpty(this.CbbIp.Text.Trim()))
            {
                item.ProxyIp = this.CbbIp.Text.Trim();
            }
            if (!this.CbbEncoding.Text.Contains("自动"))
            {
                item.Encoding = Encoding.GetEncoding(this.CbbEncoding.Text.Trim());
            }
            this.RichHtml.Visible = true;
            this.pictureBox1.Visible = false;
            //this.SetHttpItem();
            StringBuilder builder = new StringBuilder();
            builder.Append("            HttpHelper http = new HttpHelper();\r\n");
            builder.Append("            HttpItem item = new HttpItem()\r\n");
            builder.Append("            {\r\n");
            builder.Append("                URL = \"" + item.URL + "\",//URL     必需项    \r\n");
            if (!this.CbbEncoding.Text.Trim().Contains("自动"))
            {
                builder.Append("                Encoding = System.Text.Encoding.GetEncoding( \"" + this.CbbEncoding.Text.Trim() + "\"),//URL     可选项 默认为Get   \r\n");
            }
            builder.Append("                Method = \"" + item.Method + "\",//URL     可选项 默认为Get   \r\n");
            builder.Append("                IsToLower = " + item.IsToLower.ToString().ToLower() + ",//得到的HTML代码是否转成小写     可选项默认转小写   \r\n");
            builder.Append("                Cookie = \"" + item.Cookie + "\",//字符串Cookie     可选项   \r\n");
            builder.Append("                Referer =\"" + item.Referer + "\",//来源URL     可选项   \r\n");
            builder.Append("                Postdata = \"" + item.Postdata + "\",//Post数据     可选项GET时不需要写   \r\n");
            builder.Append("                Timeout = " + item.Timeout + ",//连接超时时间     可选项默认为100000    \r\n");
            builder.Append("                ReadWriteTimeout = " + item.ReadWriteTimeout + ",//写入Post数据超时时间     可选项默认为30000   \r\n");
            builder.Append("                UserAgent = \"" + item.UserAgent + "\",//用户的浏览器类型，版本，操作系统     可选项有默认值   \r\n");
            builder.Append("                ContentType = \"" + item.ContentType + "\",//返回类型    可选项有默认值   \r\n");
            builder.Append("                Allowautoredirect = " + item.Allowautoredirect.ToString().ToLower() + ",//是否根据301跳转     可选项   \r\n");
            builder.Append("                //CerPath = \"d:\\123.cer\",//证书绝对路径     可选项不需要证书时可以不写这个参数   \r\n");
            builder.Append("                //Connectionlimit = 1024,//最大连接数     可选项 默认为1024    \r\n");
            builder.Append("                ProxyIp = \"" + item.ProxyIp + "\",//代理服务器ID     可选项 不需要代理 时可以不设置这三个参数    \r\n");
            builder.Append("                //ProxyPwd = \"123456\",//代理服务器密码     可选项    \r\n");
            builder.Append("                //ProxyUserName = \"administrator\",//代理服务器账户名     可选项   \r\n");
            builder.Append("                ResultType = " + (ChkGetPic.Checked ? "ResultType.Byte" : "ResultType.String") + "\r\n");
            builder.Append("            };\r\n");
            builder.Append("");
            builder.Append("            HttpResult result = http.GetHtml(item);\r\n");
            builder.Append("            string html = result.Html;\r\n");
            builder.Append("            string cookie = result.Cookie;\r\n");
            builder.Append("        \r\n\r\n");
            builder.Append("        /// <summary>\r\n");
            builder.Append("        /// 字节数组生成图片\r\n");
            builder.Append("        /// </summary>\r\n");
            builder.Append("        /// <param name=\"Bytes\">字节数组</param>\r\n");
            builder.Append("        /// <returns>图片</returns>\r\n");
            builder.Append("        private Image byteArrayToImage(byte[] Bytes)\r\n");
            builder.Append("        {\r\n");
            builder.Append("            MemoryStream ms = new MemoryStream(Bytes);\r\n");
            builder.Append("            return Bitmap.FromStream(ms,true);\r\n");
            builder.Append("        }\r\n");
            RichHtml.Text = builder.ToString();
            Te_Format.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy("C#");
            Te_Format.Text= builder.ToString();

        }
        public void AddUrl(string title,string url)
        {
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(Itrycn_Db.User_SQLConn) == 1)
            {
                var _title = title;
                if(_title == "")
                {
                    var mode = url.Replace("?","&").GetStr("&a=","");
                    if (mode.IndexOf("&") > 0) { mode = mode.GetStr("", "&"); }
                    if(mode.Length==0)
                    {
                        mode = url.Replace("?", "&").GetStr("&Action=", "");
                        if (mode.IndexOf("&") > 0) { mode = mode.GetStr("", "&"); }
                    }
                    _title = mode;
                }
                RyQuickSQL mySQL = new RyQuickSQL("Urls");
                mySQL.AddField("Name", _title);
                mySQL.AddField("Url", url);
                mySQL.AddField("Cookie", TxtCookie.Text);
                mySQL.AddField("Postdata", TxtPost.Text);
                mySQL.AddField("Header", TxtInputHeader.Text);
                mySQL.AddField("Method", RbGet.Checked?"get":"post");
                mySQL.AddField("Referer", CbbReferer.Text);
                mySQL.AddField("ContentType", CbbContentType.Text);
                mySQL.AddField("Encoding", CbbEncoding.Text);
                DataSet ds = db.ReadData("select * from Urls where Url=@Url", mySQL);
                if (mydb.HaveData(ds))
                {
                    DataRow reader = ds.Tables[0].Rows[0];
                    #region 读取信息  
                    mySQL.AddFieldCalc("ClickCount", "ClickCount+1");//点击次数
                    mySQL.AddField("editTime", DateTime.Now);
                    db.ExecuteNonQuery(mySQL.GetUpdateSQL() + " where id=" + reader["id"].ToString(), mySQL);
                    #endregion
                }
                else
                {
                    mySQL.AddField("ClickCount",1);
                    mySQL.AddField("editTime", DateTime.Now);
                    mySQL.AddField("addTime", DateTime.Now);
                    db.ExecuteNonQuery(mySQL.GetInsertSQL(),mySQL);
                }
            }
            db.Free();
        }
        bool proc_use = false;
        private void ClickItem(bool run = false)
        {
            if (table1.SelectedItems.Length > 0)
            {
                table1.Visible = false;
                Application.DoEvents();
                proc_use = true;
                string url = table1.SelectedItems[0].Cells[ColUrl.Index].Text;
                DataProvider mydb = new DataProvider();
                IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
                if (db.ConnDb(Itrycn_Db.User_SQLConn) == 1)
                {
                    db.AddParameter("url", url);
                    DataSet ds = db.ReadData("select * from Urls where Url=@url", db.GetParameter());
                    if(mydb.HaveData(ds))
                    {
                        DataRow row = ds.Tables[0].Rows[0];
                        SetValueByRich(TxtCookie,"Cookie");
                        SetValueByRich(TxtPost, "Postdata");
                        SetValueByRich(TxtInputHeader, "Header");
                        SetValue2(CbbReferer, "Referer");
                        SetValue2(CbbContentType, "ContentType");
                        SetValue2(CbbEncoding, "Encoding");
                        if (row["Method"].ToString().Length>0)
                        {
                            if(row["Method"].ToString()=="post")
                            {
                                RbPost.Checked = true;
                            }
                            else { RbGet.Checked = true; }
                        }
                        void SetValueByRich(ryControls.Controls.RichTextBox2 txt, string Field)
                        {
                            if (row[Field].ToString().Length > 0) { txt.Text = row[Field].ToString(); }
                        }
                        void SetValue2(ryControls.RyComboBox cbb, string Field)
                        {
                            if (row[Field].ToString().Length>0) { cbb.Text = row[Field].ToString(); }
                        }
                    }
                    db.Free();
                }
                TxtUrl.Text = url;
                if (run)
                { BtnRunHtml.PerformClick(); }
                proc_use = false;
            }
            else { table1.Visible = false; }
        }
        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();
                    TxtUrl.Select();
                    //rySearch1.Select();
                }
            }
            else if (e.KeyCode == Keys.Enter)
            {
                ClickItem();
            }
        }

        private void TxtUrl_TextChanged2(object sender, EventArgs e)
        {
            if (proc_use) { return; }
            string sql_where = "";
            if (TxtUrl.Text != "") { sql_where = " where (Name like @SearchText or Url like @SearchText)"; }
            #region 重新载入数据
            tableModel1.Rows.Clear();
            tableModel1.Selections.Clear();
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(Itrycn_Db.User_SQLConn) == 1)
            {
                db.AddParameter("SearchText", "%" + TxtUrl.Text + "%");
                DataSet ds = db.ReadData("select * from Urls" + sql_where+ " order by ClickCount desc,editTime desc", db.GetParameter());
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow row = ds.Tables[0].Rows[i];
                    DateTime editTime = row["editTime"].ToDateTime();
                    XPTable.Models.Row itemList = new XPTable.Models.Row()
                    {
                        Tag = row["id"].ToString()
                    };
                    //需要修改此处
                    itemList.Cells.Add(new XPTable.Models.Cell(row["Url"].ToString()));//示例
                    itemList.Cells.Add(new XPTable.Models.Cell(row["Name"].ToString()));
                    if (editTime >= DateTime.Now.AddMinutes(-10))
                    {
                        tableModel1.Rows.Insert(0,itemList);
                    }
                    else
                    {
                        tableModel1.Rows.Add(itemList);
                    }
                }
                db.Free();
                table1.Visible = tableModel1.Rows.Count != 0;
                table1.BringToFront();
            }
            #endregion
        }

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

        private void Table1_CellLostFocus(object sender, XPTable.Events.CellFocusEventArgs e)
        {
            if (e.Row == -1) { table1.Visible = false; }
        }

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

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

        private void timer1_Tick(object sender, EventArgs e)
        {
        }

        private void table1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ClickItem();
            }
        }

        private void TxtPost_DoubleClick(object sender, EventArgs e)
        {
            ryControls.Controls.RichTextBox2 txt = (ryControls.Controls.RichTextBox2)sender;
            开发辅助工具.Controls.FrmText frm = new Controls.FrmText
            {
                Icon = Icon
            };
            frm.richTextBox1.Text = txt.Text;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                txt.Text = frm.richTextBox1.Text;
            }
        }

        private void TxtPost_TextChanged(object sender, EventArgs e)
        {
            if (TxtPost.Text != "") { tabPage1.Text = "Post数据(有数据)"; }
            else { tabPage1.Text = "Post数据"; }
        }

        private void TxtCookie_TextChanged(object sender, EventArgs e)
        {
            if (TxtCookie.Text != "") { tabPage2.Text = "Cookie(有数据)"; }
            else { tabPage2.Text = "Cookie"; }
        }

        private void TxtInputHeader_TextChanged(object sender, EventArgs e)
        {
            if (TxtInputHeader.Text != "") { tabPage7.Text = "Header(有数据)"; }
            else { tabPage7.Text = "Header"; }
        }

        private void ChkNoPreview_CheckedChanged(object sender, EventArgs e)
        {
            ChkHtmlPreview.Enabled = !ChkNoPreview.Checked;
        }

        private void Te_Format_TextChanged(object sender, EventArgs e)
        {
            Te_Format.Document.FoldingManager.UpdateFoldings(null, null);
        }
    }
    public class UserAgentInfo
    {
        public string name = "";
        public string useragent = "";
        public override string ToString()
        {
            return name;
        }
    }
}
