using HtmlAgilityPack;
using Itrycn_Project2;
using ryCommon;
using ryCommonDb;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace Itrycn_Project2
{
    public partial class FrmStart : RySkins.SKinForm
    {
        /// <summary>
        /// 最大日志数量
        /// </summary>
        private int MaxLogsCount { get; set; } = 1000;
        readonly string[] prog_args;
        public FrmStart(string[] args)
        {
            InitializeComponent();
            prog_args = args;
            //配置软件信息
            notifyIcon1.Text = Soft_ConstInfo.Soft_Title;
            Text = Soft_ConstInfo.Soft_Title + " V" + RySoft.VersionStr;
            if (!Soft_ConstInfo.ShowTray) { notifyIcon1.Visible = false; }
            if (!Soft_ConstInfo.DonateVisabled) { 捐助ToolStripMenuItem.Text = "关于"; }
            if (Soft_ConstInfo.Soft_Url.Length == 0) { 打开官网ToolStripMenuItem.PerformClick(); }
            notifyIcon1.Icon = Icon;
            OlvLogTime.AspectGetter = delegate (object x) { return ((LogInfo)x).LogTime.ToDateTimeStr(); };
            OlvLogText.AspectGetter = delegate (object x) { return ((LogInfo)x).LogText; };
            olvColumn1.AspectGetter = delegate (object x) { return "测试"; };
            LvLogs.FormatRow += delegate (object x, BrightIdeasSoftware.FormatRowEventArgs e) {
            LogInfo item = (LogInfo)e.Model;
            if (item.Color != Color.Black)
            {
                e.Item.ForeColor = item.Color;
            }
            };
            RyQuickSQL mysql = new RyQuickSQL("");
            var a = mysql + "sss";
            pictureBox1.Image = RyImage.LoadPic("C:\\Users\\Administrator\\AppData\\Roaming\\DingTalk\\204132110_v2\\ImageFiles\\2861025\\1729072614_115186169904.webp");
        }
        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="log"></param>
        public void AddLog(string log)
        {
            AddLog(log, "", Color.Black);
        }
        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="log"></param>
        /// <param name="color"></param>
        public void AddLog(string log, Color color)
        {
            AddLog(log, "", color);
        }
        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="log"></param>
        /// <param name="tag"></param>
        /// <param name="color"></param>
        public void AddLog(string log, string tag, Color color)
        {
            try
            {
                this.Invoke(new Action(() =>
                {
                    var count = LvLogs.GetItemCount();
                    if (count > MaxLogsCount)
                    {
                        LvLogs.RemoveObject(LvLogs.GetModelObject(count-1));
                    }
                    LvLogs.InsertObjects(0, new LogInfo[] { new LogInfo() { LogTime = DateTime.Now, LogText = log,LogTag=tag, Color = color } });
                    OlvLogTime.Text = "时间(" + LvLogs.GetItemCount() + ")";
                }));
            }
            catch { }
        }
        private void 显示主窗体ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            var topmost = this.TopMost;
            this.TopMost = true;
            this.Show();
            this.TopMost = topmost;
        }

        private void 退出软件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Application.Exit();
        }
        private void FrmStart_Shown(object sender, EventArgs e)
        {
            ryCommon.Ini ini = new Ini(Soft_ConstInfo.UserDataFolder + "\\Win.dat");
            ini.WriteIni(Soft_ConstInfo.Soft_Id, "hwnd", Handle.ToInt32());
            if (prog_args.Length >= 1)
            {
                //如果是自启动,并且开启了右下角托盘图标,则隐藏自身。
                if (prog_args[0] == Soft_ConstInfo.Soft_Pram && Soft_ConstInfo.ShowTray)
                    this.Hide();
            }
        }

        private void FrmStart_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (Soft_ConstInfo.ShowTray && Public_Config.HideByCloseBtn && e.CloseReason== CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.Hide();
                notifyIcon1.ShowBalloonTip(3000, Soft_ConstInfo.Soft_Title, "软件已经最小化到此处,请右击托盘图标进行关闭。", ToolTipIcon.Info);
                return;
            }
            if (!Soft_MemInfo.IsCanCloseForm)
            {
                e.Cancel = true;
                RySkins.Msg.ShowMsg("当前还有操作正在运行,请稍后关闭软件。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        protected override void WndProc(ref System.Windows.Forms.Message msg)
        {
            switch (msg.Msg)
            {
                case 17189: //处理消息
                    {
                        #region 激活窗体
                        switch (msg.WParam.ToInt32())
                        {
                            case 100://
                                #region 显示界面
                                if ((int)msg.LParam.ToInt32() == 100)
                                {
                                    this.Show();
                                    this.WindowState = FormWindowState.Normal;
                                    this.Top = (Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2;
                                    this.Left = (Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2;
                                    //RyForm.SetActiveWindow(Handle);
                                    RyForm.BringToTop(Handle);
                                    显示主窗体ToolStripMenuItem.PerformClick();
                                    this.BringToFront();
                                    this.Select();
                                    this.Focus();
                                    RyForm.BringToTop(Handle);
                                }
                                #endregion
                                break;
                        }
                        #endregion
                    }
                    break;
                default:
                    base.WndProc(ref msg);//调用基类函数处理非自定义消息。
                    break;
            }
        }

        private void 捐助ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Soft_ConstInfo.DonateVisabled)
            {
                FrmAbout frm = new FrmAbout();
                frm.ShowDialog();
                frm.Dispose();
            }
            else
            {

                RySkins.Msg.ShowMsg(Soft_ConstInfo.AboutText.Replace("#softname#", Soft_ConstInfo.Soft_Title).Replace("#ver#", "V" + RySoft.VersionStr), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }


        private void 打开官网ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ryCommon.RyFiles.OpenUrl(Soft_ConstInfo.Soft_Url);
        }
        
        private void FrmStart_Load(object sender, EventArgs e)
        {
            RyWeb.QuickWeb web = new RyWeb.QuickWeb();
            textBox2.Text = web.Get("https://apkpure.com/cn/animation-throwdown-epic-ccg/com.kongregate.mobile.throwdown.google/download").Html;
            //ryCommon.ApkOp apkOp = new ApkOp();
            //apkOp.AAPT_Path = "E:\\My Datas\\My Codes\\非毕方项目\\Delphi\\公司-批量安装助手XE5\\aapt.exe";
           // var kk= apkOp.Read_Apk("E:\\My Datas\\毕方项目\\Delphi\\IIS防盗链工具\\Res\\ThirdParty\\wwwroot\\update\\taobaov9.apk");
           // objectListView1.InsertObjects(0, new LogInfo[] { new LogInfo() });
            //var en= ryCommon.TxtFileEncoder.GetEncoding(@"E:\My Datas\毕方项目\C#\ryProcessManager\Bin\Debug\SysDb\applist.lst");
            //var hosts = ryCommon.RyFiles.ReadAllText(@"E:\My Datas\毕方项目\C#\ryProcessManager\Bin\Debug\UserDb\Hosts.txt");
            //var result = ryCommon.Hosts.AddHosts(hosts);
            //var kk= ryCommon.ProcessExt.GetPath(24348);
            //var img = RyImage.LoadPic(@"C:\Users\zilin\Desktop\1.jpg");
            //var watermark =new Bitmap(RyImage.LoadPic(@"C:\Users\zilin\Desktop\water.png"));
            //var pos= new List<WatermarkPosition>(new WatermarkPosition[] { WatermarkPosition.FullScreenTile });
            //pictureBox1.Image = img.ReSizeW(300);
            //pictureBox1.Image= img.DrawWatermark(watermark, WatermarkPosition.FullScreenTile, 0,0,20f);
            //ryCommon.PinYin.Convert("李凤鑫");
            Public_Config.LoadSetting();
            //Itrycn_Project.Itrycn_Db.CreateTable();
            //var dbver = Itrycn_Db.GetDbVer();
            //if(dbver==1) //初始版本,并是当前要求的数据库
            //{

            //}
            //else
            //{
            //    MessageBox.Show("不支持当前数据库版本,这可能是以下原因导致的:\r\n1.数据库已损坏;'\r\n2.当前数据库是由新版软件创建的(请更新软件后重试)。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    Application.Exit();
            //    return;
            //}
            //IDbInterface db = new SQLiteDataProvider();
            //if (db.ConnDb(@"E:\My Datas\毕方项目\C#\ryProcessManager\Bin\Debug\UserDb\MyDb.dat|ry3H3Db") == 1)
            //{
            //}
            //db.Free();
            LiveUpdate.RyUpdate update = new LiveUpdate.RyUpdate(Soft_ConstInfo.Update_Url);
            update.CheckUpdate();
            //Thread th = new Thread(Start);
            //th.Start();
            //void Start()
            //{
            //    while(true)
            //    {
            //        LvLogs.ClearObjects();
            //        AddLog("测试测试");
            //        Thread.Sleep(200);
            //    }
            //}
        }

        private void 选项ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmSetting frm = new FrmSetting();
            if(frm.ShowDialog()==DialogResult.OK)
            {
                Public_Config.LoadSetting();
            }
            frm.Dispose();
        }
        /// <summary>
        /// 日志信息
        /// </summary>
        public class LogInfo
        {
            /// <summary>
            /// 日志时间
            /// </summary>
            public DateTime LogTime { get; set; } = DateTime.Now;
            /// <summary>
            /// 日志内容
            /// </summary>
            public string LogText { get; set; }
            /// <summary>
            /// 日志Tag
            /// </summary>
            public string LogTag { get; set; }
            /// <summary>
            /// 日志文字颜色
            /// </summary>
            public Color Color { get; set; } = Color.Black;
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            LvLogs.ClearObjects();
            AddLog("测试测试");
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            //var text = "";
            //try
            //{
            //    HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            //    htmlDoc.LoadHtml(textBox2.Text);
            //    HtmlNodeCollection anchors = htmlDoc.DocumentNode.SelectNodes(textBox1.Text);
            //    if (anchors != null)
            //    {
            //        for (int i = 0; i < anchors.Count; i++)
            //        {
            //            if (text != "") { text += "<br><br>"; }
            //            if (i % 2 == 0)
            //            {
            //                text += "<span style='color:green'>" + System.Web.HttpUtility.HtmlEncode(anchors[i].OuterHtml) + "</span>";
            //            }
            //            else
            //            {
            //                text += "<span style='color:blue'>" + System.Web.HttpUtility.HtmlEncode(anchors[i].OuterHtml) + "</span>";
            //            }
            //        }
            //    }
            //}
            //catch (Exception ex){
            //    text = "<span style='color:red'>" + System.Web.HttpUtility.HtmlEncode(ex.Message) + "</span>";
            //}
            htmlPanel1.Text = System.Web.HttpUtility.HtmlEncode(textBox1.Text);
        }
    }
}
