using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Management;
using US.Browser.IE.BLL;
using System.Threading;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.IO;
using System.Diagnostics;
using System.Configuration;
using System.Web.Configuration;
using Shell32;

namespace US.Browser.IE
{
    /// <summary>
    /// 应用程序 
    /// </summary>
    public partial class StaticClass : Form
    {

        #region 变量区域

        public static StaticClass _USE; //应用启动区域
        RespondWeb _UVE; //webbrower开发功能区
        USMain _UM;
        private static Popup _UPE;//广告页面
        public static string _UST;//启动程序的方式
        private Respond_setting _URE;//浏览器系统设置功能区域
        private static Thread th = null;//线程
        public static string ver = FileVersionInfo.GetVersionInfo(System.Windows.Forms.Application.ExecutablePath).FileVersion;//当前版本
        public static News _UNE;//消息 
        public static string UCON = System.Configuration.ConfigurationSettings.AppSettings["type"];//Config设置
        static System.Windows.Forms.Timer _UDT = null; static Icon ic; static Icon[] aic; static string icoscr = string.Empty; static bool tf;
        public static MouseEventHandler _ume;

        #endregion

        #region 生成应用程序


        /// <summary>
        /// 应用程序初始化
        /// </summary>
        /// <param name="runstr"></param>
        /// <returns></returns>
        public static StaticClass getI(string UST)
        {
            _USE = new StaticClass(); _UST = UST;
            _USE.StaticClass_Load(); return _USE;
        }

        /// <summary>
        /// 多窗口
        /// </summary>
        /// <param name="UTP"></param>
        /// <returns></returns>
        public static StaticClass Restart(string UTP)
        {
            return StaticClass.getI(UTP);
        }

        /// <summary>
        /// 实例化应用程序
        /// </summary>
        /// <returns></returns>
        public static StaticClass getInstance()
        {
            if (BLL.USIE.isnet())
            {
                if (_USE == null) { _USE = new StaticClass(); }//生成任务托盘
                else { _USE.CreateMain(false); }
                return _USE;
            }
            return null;
        }

        /// <summary>
        /// 无参数构造
        /// </summary>
        public StaticClass()
        {
            InitializeComponent(); //实例化右键菜单
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// 托盘加载完毕启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StaticClass_Load()
        {
            bool _UTF = _UST.IndexOf("-background") != -1; _URE = new Respond_setting(); //浏览器设置区域
            this._UM = CreateMain(_UTF); _UPE = new Popup(_UM); UpdateCue.NewUpCF(_USE); _UNE = new News(_UM._USY);
            _UVE = new RespondWeb(null, _UM._USY); System.Windows.Forms.Timer _UTM = new System.Windows.Forms.Timer();
            _UTM.Tick += new EventHandler(delegate(object sender, EventArgs e) { _UTM.Stop(); _UTM.Dispose(); _UPE.Show(); });
            _UTM.Interval = 600000; _UTM.Start();
        }

        /// <summary>
        /// 创建主窗体
        /// </summary>
        /// <returns></returns>
        public USMain CreateMain(bool UTF)
        {
            USMain _UM = new USMain();
            System.Windows.Forms.Timer _UTM = new System.Windows.Forms.Timer(); _UTM.Tick += new EventHandler(delegate(object sender, EventArgs e) //窗体加载等待
            {
                aic = new Icon[] { new System.Drawing.Icon(Application.StartupPath + "//logo.ico"), new System.Drawing.Icon(Application.StartupPath + "//head.ico") };
                StaticClass.postUseBE(); _UTM.Stop(); _UTM.Dispose(); _UTM = null; if (!UTF && BLL.USIE.isnet()) { _UM.Show(); }
            });
            _UTM.Interval = 1; _UTM.Start(); return _UM;
        }

        /// <summary>
        /// 浏览器关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void StaticClass_Disposed(object sender, System.EventArgs e)
        {
            Process _UPE = System.Diagnostics.Process.GetCurrentProcess();
            BLL.WindowHWND.freem(); this.USIcon.Dispose(); this.IconMenu.Dispose();
            _UPE.Kill(); _UPE.Close(); _UPE.Dispose();
        }

        #endregion

        #region 托盘闪烁使用

        /// <summary>
        /// 闪烁
        /// </summary>
        public static void _twstart(string img, string tf, string ue, WebBrowser wb, RespondWeb rf)
        {
            sjxxs(tf, ue, wb, rf);
            if (_UDT == null) { icoscr = img; _traytwinkle(img); }
            else if (ic == null || icoscr != img) { if (ic != null) { ic.Dispose(); } icoscr = img; ic = geticon(img); }
        }

        /// <summary>
        /// 关闭闪烁
        /// </summary>
        public static void _twstop()
        {
            if (_UDT != null) { _UDT.Stop(); _UDT.Dispose(); } _UDT = null; icoscr = string.Empty;
            if (_USE.USIcon.Icon != aic[0]) { _USE.USIcon.Icon = aic[0]; } if (ic != null) { ic.Dispose(); ic = null; }
        }

        /// <summary>
        /// 闪烁开始
        /// </summary>
        /// <param name="img"></param>
        public static void _traytwinkle(object img)
        {
            _UDT = new System.Windows.Forms.Timer(); tf = true; string iimg = (string)img;
            if (ic != null) { ic.Dispose(); } ic = geticon(iimg); ic = ic == null ? aic[1] : ic; _USE.USIcon.Text = "查看消息";
            _UDT.Tick += new EventHandler(_UDT_Tick); _UDT.Interval = 800; _UDT.Start();
        }

        /// <summary>
        /// 闪烁变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void _UDT_Tick(object sender, EventArgs e)
        {
            Icon _ic = tf ? ic : aic[0];
            if (_ic == null) { _twstop(); }
            else { _USE.USIcon.Icon = _ic; tf = !tf; }
        }

        /// <summary>
        /// 闪烁按钮添加事件
        /// </summary>
        public static void sjxxs(string tf, string ue, WebBrowser wb, RespondWeb rf)
        {
            NotifyIcon icn = StaticClass._USE.USIcon;
            icn.MouseClick -= _ume; //取消相同事件
            _ume = new MouseEventHandler(delegate(object sender, MouseEventArgs me)
            {
                if (me.Button == MouseButtons.Left)
                {
                    icn.MouseClick -= _ume; icn.Text = "云端";
                    rf.OpenLook(new object[] { tf, ue }, wb); StaticClass._twstop();
                }
            });
            icn.MouseClick += _ume; //添加事件
        }


        /// <summary>
        /// 获取icon
        /// </summary>
        /// <param name="img"></param>
        /// <returns></returns>
        public static Icon geticon(string img)
        {
            Icon ic = null;
            try
            {
                System.Net.HttpWebRequest webrq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(img);
                System.Net.HttpWebResponse webres = (System.Net.HttpWebResponse)webrq.GetResponse();
                if (webres.StatusCode == System.Net.HttpStatusCode.OK && webres.ContentLength > 0)
                {
                    using (Stream stream = webres.GetResponseStream())
                    {
                        using (Image image = Image.FromStream(stream))
                        {
                            using (Bitmap bmp = new Bitmap(image, new Size(16, 16)))
                            {
                                ic = Icon.FromHandle(bmp.GetHicon());
                                bmp.Dispose();
                            }
                            image.Clone(); image.Dispose();
                        }
                        stream.Close(); stream.Dispose();
                    }
                }
                webrq.Abort(); webres.Close();
            }
            catch (Exception e) { BLL.WindowHWND.freem(); }
            return ic;
        }

        #endregion

        #region 托盘点击

        /// <summary>
        /// 点击查看
        /// </summary>
        public void Show_Click()
        {
            if (BLL.USIE.isnet())
            {
                int i; List<Form> _UFL = USMain._UFL; Form _UF; this_sfb();
                for (i = 0; i < _UFL.Count; i++)
                {
                    _UF = _UFL[i]; if (_UF.Visible == false) { _UF.Show(); } this._UVE.fouscwindow();
                    if (_UF.WindowState == FormWindowState.Minimized) { _UF.WindowState = FormWindowState.Normal; }
                }
            }
            //else { MessageBox.Show("请连接网络！"); }
        }

        /// <summary>
        /// 窗体添加
        /// </summary>
        public void this_sfb()
        {
            if (US.Browser.IE.USMain._UFL.Count > 0)
            {
                USMain USM = (USMain)US.Browser.IE.USMain._UFL[0];
                List<WebBrowser> L_WB = USM._USY._UBL;
                if (L_WB.Count <= 0)
                {
                    WebBrowser _UWB = USM._USY._UWB;
                    _UWB.Document.InvokeScript("_addTag", new Object[] { "http://www.1473.cn" });
                }
            }
        }

        #region 右键菜单功能区域

        /// <summary>
        /// 显示窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IconMenuShow_Click(object sender, EventArgs e)
        {
            Show_Click();
        }

        /// <summary>
        /// 点击查看云端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void USIcon_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left) { Show_Click(); }
        }
        /// <summary>
        /// 查看设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuSetting_Click(object sender, EventArgs e)
        {
            _URE.SetProxy();
        }

        /// <summary>
        /// 关闭浏览器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void exit_Click(object sender, EventArgs e)
        {
            StaticClass_Disposed(sender, e);
        }

        /// <summary>
        /// 消息提醒
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void NS_Click(object sender, System.EventArgs e)
        {
            if (BLL.USIE.isnet()) { StaticClass._UNE.init(true); }
        }

        /// <summary>
        /// 弹出校园资讯
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void zx_Click(object sender, System.EventArgs e)
        {
            if (BLL.USIE.isnet()) { _UPE.ZJTC(true); }
        }

        /// <summary>
        /// 更新检查
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Newst_Click(object sender, EventArgs e)
        {
            if (BLL.USIE.isnet()) { if (!UpdateCue._UDE.showp(false)) { MessageBox.Show("版本已为最新, 感谢支持。"); }; }
        }

        /// <summary>
        /// 意见反馈
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Feedback_Click(object sender, EventArgs e)
        {
            if (BLL.USIE.isnet()) { _UVE.OpenLook(new object[] { "pb", "['3c779543-bc1a-4851-af22-af9ba97a5f33']" }, null); }
        }

        #endregion

        #endregion

        #region 使用功能区域

        /// <summary>
        /// 关闭浏览器
        /// </summary>
        /// <param name="form"></param>
        public static void CloseSoft(Form UF)
        {
            List<Form> _UF = USMain._UFL; _UF.Remove(UF); UF.Dispose();
            if (_UF.Count == 0) { _USE.Close(); _USE.Dispose(); System.Environment.Exit(0); }
        }

        /// <summary>
        /// 隐藏图标
        /// </summary>
        /// <param name="i"></param>
        protected override void SetVisibleCore(bool ITF)
        {
            base.SetVisibleCore(false);
        }

        #endregion

        #region  获取数据

        /// <summary>
        /// 添加装机用户信息
        /// </summary>
        public static void postUseBE()
        {
            string _UOS = getUseOS(); string[] _UIP = getUseMac();
            try { USClientCommunicate.PostPage("http://collect.1473.cn", "POST", delegate(string a) { if (a == "") { USClientCommunicate.PostPage("http://collect.1473.cn", "POST", delegate(string c) { }, "mode=", "UseBE_IN", "{ UIP:'" + _UIP[1] + "',UsOS:'" + _UOS + "',UsMac:'" + _UIP[0] + "'}"); } }, "mode=", "UseBE_SEL", "{ UsMac:'" + _UIP[0] + "'}").Replace("[", "").Replace("]", ""); }
            catch (Exception e) { return; }
        }

        /// <summary>
        /// 获取用户操作系统信息
        /// </summary>
        /// <returns></returns>
        public static string getUseOS()
        {
            return System.Environment.OSVersion.VersionString;
        }

        /// <summary>
        /// 获取IP信息
        /// </summary>
        /// <returns></returns>
        public static string[] getUseMac()
        {
            ManagementClass _UMC = new ManagementClass("Win32_NetworkAdapterConfiguration");//获取客户端网络信息
            ManagementObjectCollection _UNI = _UMC.GetInstances(); string[] _UNIP = new string[2];
            foreach (ManagementObject i in _UNI)
            {
                if (Convert.ToBoolean(i["ipEnabled"]) == true) { _UNIP[0] = i["MacAddress"].ToString(); _UNIP[1] = (i["IPAddress"] as string[])[0]; }
            }
            return _UNIP;
        }

        #endregion

    }
}
