using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FRControl
{
    public partial class WebView : Form
    {
        private Timer timer1 = null;
        public WebView()
        {
            SetWebBrowserFeatures(11);
            InitializeComponent();
            Size WindowsScreenSize = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            int width = Screen.PrimaryScreen.Bounds.Width;
            //Console.WriteLine("WindowsScreenSize:" + WindowsScreenSize+ "，width："+ width);

            if (width == 1080)
            {
                this.Size = new Size(1080, 1920);
                this.BodyPanel.Size = new Size(1080, 1920);
                this.ReturnBtn.Size = new Size(35,35);
                this.TitleLab.Font = new System.Drawing.Font("微软雅黑", 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            }
            else
            {
                this.Size = new Size(608, 1080);
                this.BodyPanel.Size = new Size(608, 1080);
                this.ReturnBtn.Size = new Size(25, 25);
            }
        }
        private void WebView_Load(object sender, EventArgs e)
        {
            //webBrowser1.Document.Body.Style = "zoom:0.5";
            this.TitlePanel.BackColor = Color.FromArgb(37, 122, 187);
            this.webBrowser1.Url = new Uri(Home.url);
            //Console.WriteLine(Home.url);
            this.TitleLab.Text = Home.title;
            this.webBrowser1.ScriptErrorsSuppressed = true;
            //this.webBrowser1.ScrollBarsEnabled = false;
           
        }

        private void webBrowser1_DocumentCompleted_1(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //System.IO.StreamReader sr = new System.IO.StreamReader(webBrowser1.DocumentStream, Encoding.GetEncoding("gb2312"));
            //string html = sr.ReadToEnd();//获取源文件
            //sr.Close();
            ///*截取table 的html源文件*/
            //int start = html.IndexOf("<div class='indexnews clearfix'>");
            //int end = html.IndexOf("</div>", start) + 8;
            //string tbhtm = html.Substring(start, end - start);

            if (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
                return;
            //if (e.Url.ToString() != webBrowser1.Url.ToString())
            //    return;

            //webBrowser1.DocumentText = tbhtm;//设置为table的html代码
            //将所有的链接的目标，指向本窗体
            foreach (HtmlElement htmlElement in webBrowser1.Document.Links)
            {
                htmlElement.SetAttribute("target", "_self");
            }
            HtmlElementCollection elementCollection = this.webBrowser1.Document.GetElementsByTagName("b");

            if (null != elementCollection)
            {
                foreach (HtmlElement elem in elementCollection)
                {

                    if (elem.GetAttribute("className").ToString().Equals("lanmu"))
                    {
                        elem.SetAttribute("className", "lanmuc");
                        elem.Click += new HtmlElementEventHandler(elem_Click);
                    }

                    //Console.WriteLine(elem.InnerHtml+",class="+ elem.GetAttribute("className").ToString());
                    //Console.WriteLine(elem.GetAttribute("class").ToString());

                }
            }
            this.webBrowser1.Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);
            //获取网页的最大size
            Size szba = new Size(webBrowser1.Document.Body.ScrollRectangle.Width, webBrowser1.Document.Body.ScrollRectangle.Height);
            Size sz = webBrowser1.Size;
            //Console.WriteLine("szba:" + szba + "，sz：" + sz);
            int xbili = (int)((float)sz.Width / (float)szba.Width * 100);//水平方向缩小比例
            int ybili = (int)((float)sz.Height / (float)szba.Height * 100);//垂直方向缩小比例
            //Console.WriteLine("xbili:" + xbili + "，ybili：" + ybili);
            //webBrowser1.Document.Body.Style = "width:1080px;";

            //Zoom(axIWebBrowser2, 150);

           // webBrowser1.Document.Body.Style = "zoom:" + xbili.ToString() + "%";
            //if (xbili < ybili)
            //    webBrowser1.Document.Body.Style = "zoom:" + xbili.ToString() + "%";
            //else
            //    webBrowser1.Document.Body.Style = "zoom:" + ybili.ToString() + "%";
            //webBrowser1.Invalidate();

            FRControl.ZoomBrowser.IWebBrowser2 axIWebBrowser2 = (FRControl.ZoomBrowser.IWebBrowser2)this.webBrowser1.ActiveXInstance;　//关键代码
            axIWebBrowser2.ExecWB(FRControl.ZoomBrowser.OLECMDID.OLECMDID_OPTICAL_ZOOM,
                   FRControl.ZoomBrowser.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER,
                   xbili, IntPtr.Zero);

            //this.elem_Click();
            //HtmlElementCollection elementCollection = this.webBrowser1.Document.GetElementsByTagName("b");
            //if (null != elementCollection)
            //{
            //    foreach (HtmlElement elem in elementCollection)
            //    {
            //        if (elem.GetAttribute("className").ToString().Equals("lanmu"))
            //        {
            //            elem.SetAttribute("className", "lanmuc");
            //            elem.Click += new HtmlElementEventHandler(elem_Click);
            //        }

            //        //Console.WriteLine(elem.InnerHtml+",class="+ elem.GetAttribute("className").ToString());
            //        //Console.WriteLine(elem.GetAttribute("class").ToString());
            //    }
            //}
        }

        

        public void elem_Click(object sender, EventArgs e)
        {
            //timer1 = new Timer();
            //timer1.Interval = 100;
            //timer1.Enabled = true;
            //timer1.Tick += new EventHandler(jcyEventProcessor);//添加事件


            HtmlElement elem = (HtmlElement)sender;
            String url = "https://www.12309.gov.cn" + elem.GetAttribute("url").ToString();
            //Console.WriteLine(url);
            //Console.WriteLine(elem.InnerHtml + ",class=" + elem.GetAttribute("className").ToString()+"url:"+ elem.GetAttribute("url").ToString());
            this.webBrowser1.Navigate(url);

        }

        public void jcyEventProcessor(object sender, EventArgs e)
        {
     
            HtmlElementCollection elementCollection = this.webBrowser1.Document.GetElementsByTagName("b");
            bool isLoad = false;
            if (null != elementCollection)
            {
                //Console.WriteLine(isLoad);
                foreach (HtmlElement elem in elementCollection)
                {
                    if (elem.GetAttribute("className").ToString().Equals("lanmu"))
                    {
                        isLoad = true;
                        elem.SetAttribute("className", "lanmuc");
                        //elem.Click += new HtmlElementEventHandler(elem_Click);
                    }
                }
                
            }
            if (isLoad)
            {
                //Console.WriteLine(isLoad);
                timer1.Stop();
                timer1.Tick -= new EventHandler(jcyEventProcessor);
                timer1 = null;

                HtmlElementCollection elementCollections = this.webBrowser1.Document.GetElementsByTagName("b");
                if (null != elementCollections)
                {
                    foreach (HtmlElement elem in elementCollections)
                    {
                        if (elem.GetAttribute("className").ToString().Equals("lanmuc"))
                        {
                            //elem.SetAttribute("className", "lanmuc");
                            elem.Click += new HtmlElementEventHandler(jcyClick);
                        }

                        Console.WriteLine(elem.InnerHtml+",class="+ elem.GetAttribute("className").ToString());
                        Console.WriteLine(elem.GetAttribute("class").ToString());
                    }

                }
            }
        }

        public void jcyClick(object sender, EventArgs e)
        {
            HtmlElement elem = (HtmlElement)sender;
            String url = "https://www.12309.gov.cn" + elem.GetAttribute("url").ToString();
            //Console.WriteLine(url);
            //Console.WriteLine(elem.InnerHtml + ",class=" + elem.GetAttribute("className").ToString()+"url:"+ elem.GetAttribute("url").ToString());
            this.webBrowser1.Navigate(url);
        }

        private void Window_Error(object sender, HtmlElementErrorEventArgs e)
        {
            e.Handled = true;
        }
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
          
        }
        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }        
        private void ReturnBtn_Click(object sender, EventArgs e)
        {
            if (null != timer1)
            {
                timer1.Stop();
                timer1.Tick -= new EventHandler(jcyEventProcessor);
                timer1 = null;
            }

            this.webBrowser1.Dispose();
            this.Close();         
        }
        //private void webBrowser1_DocumentCompleted_2(object sender, WebBrowserDocumentCompletedEventArgs e)
        //{

        //}
        private void TitleLab_Click(object sender, EventArgs e)
        {

        }

        /// <summary>  
        /// 修改注册表信息来兼容当前程序  
        ///   
        /// </summary>  
        static void SetWebBrowserFeatures(int ieVersion)
        {
            // don't change the registry if running in-proc inside Visual Studio  
            if (LicenseManager.UsageMode != LicenseUsageMode.Runtime)
                return;
            //获取程序及名称  
            var appName = System.IO.Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
            //得到浏览器的模式的值  
            UInt32 ieMode = GeoEmulationModee(ieVersion);
            var featureControlRegKey = @"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\";
            //设置浏览器对应用程序（appName）以什么模式（ieMode）运行  
            Registry.SetValue(featureControlRegKey + "FEATURE_BROWSER_EMULATION",
                appName, ieMode, RegistryValueKind.DWord);
            // enable the features which are "On" for the full Internet Explorer browser  
            //不晓得设置有什么用  
            Registry.SetValue(featureControlRegKey + "FEATURE_ENABLE_CLIPCHILDREN_OPTIMIZATION",
                appName, 1, RegistryValueKind.DWord);


            //Registry.SetValue(featureControlRegKey + "FEATURE_AJAX_CONNECTIONEVENTS",  
            //    appName, 1, RegistryValueKind.DWord);  


            //Registry.SetValue(featureControlRegKey + "FEATURE_GPU_RENDERING",  
            //    appName, 1, RegistryValueKind.DWord);  


            //Registry.SetValue(featureControlRegKey + "FEATURE_WEBOC_DOCUMENT_ZOOM",  
            //    appName, 1, RegistryValueKind.DWord);  


            //Registry.SetValue(featureControlRegKey + "FEATURE_NINPUT_LEGACYMODE",  
            //    appName, 0, RegistryValueKind.DWord);  
        }
        /// <summary>  
        /// 获取浏览器的版本  
        /// </summary>  
        /// <returns></returns>  
        static int GetBrowserVersion()
        {
            int browserVersion = 0;
            using (var ieKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer",
                RegistryKeyPermissionCheck.ReadSubTree,
                System.Security.AccessControl.RegistryRights.QueryValues))
            {
                var version = ieKey.GetValue("svcVersion");
                if (null == version)
                {
                    version = ieKey.GetValue("Version");
                    if (null == version)
                        throw new ApplicationException("Microsoft Internet Explorer is required!");
                }
                int.TryParse(version.ToString().Split('.')[0], out browserVersion);
            }
            //如果小于7  
            if (browserVersion < 7)
            {
                throw new ApplicationException("不支持的浏览器版本!");
            }
            return browserVersion;
        }
        /// <summary>  
        /// 通过版本得到浏览器模式的值  
        /// </summary>  
        /// <param name="browserVersion"></param>  
        /// <returns></returns>  
        static UInt32 GeoEmulationModee(int browserVersion)
        {
            UInt32 mode = 11000; // Internet Explorer 11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 Standards mode.   
            switch (browserVersion)
            {
                case 7:
                    mode = 7000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode.   
                    break;
                case 8:
                    mode = 8000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode.   
                    break;
                case 9:
                    mode = 9000; // Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.                      
                    break;
                case 10:
                    mode = 10000; // Internet Explorer 10.  
                    break;
                case 11:
                    mode = 11000; // Internet Explorer 11  
                    break;
            }
            return mode;
        }

        private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
        {
            // 使其他浏览器无法捕获此事件
            // 阻止了其他浏览器显示网页，而是采用WebBrowser打开网页
            webBrowser1.Url = new Uri(((WebBrowser)sender).StatusText);
            e.Cancel = true;
        }
    }
}
