using ICSharpCode.SharpZipLib.Zip;
using Tiobon.Core.OPS.Tool.OPS.Tool.Helper;
using Tiobon.Core.OPS.Tool.OPS.Tool.Src;
using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Tiobon.Core.OPS.Tool.OPS.Tool.View
{
    public partial class Frm_Main : Form
    {
        #region 初始化变量
        readonly Main_method _method = new Main_method();
        bool ischeckselect = false;
        DateTime _run_time;
        Thread Flash_Sys_Info;
        bool Clear_Image { set; get; }
        #endregion

        #region 单实例模式
        public static Frm_Main frm_Main = null;
        public Frm_Main()
        {
            InitializeComponent();
            _method.End_Init = End;
            Flash_Sys_Info = new Thread(Get_Sys_Info);
            Flash_Sys_Info.Start();
            Const.ReadMultiEnv();
            var mes = Const.MultiEnvs.Where(o => o.Ip == Const.config.ip).Select(o => o.Name).ToArray();

            this.cmb_MultiEnv.Items.Clear();

            this.cmb_MultiEnv.Items.AddRange(mes);
            if (mes.Any())
                this.cmb_MultiEnv.Text = this.cmb_MultiEnv.Items[0].ToString();
        }

        private void Get_Sys_Info()
        {
            while (true)
            {
                string sys_status = _method.Get_sysstatus();
                if (string.IsNullOrEmpty(sys_status))
                {
                    sys_status = "获取系统状态失败";
                }
                else
                {
                    toolStripStatusLabel4.Text = sys_status;
                }
                toolStripStatusLabel1.Text = $"时间：" + DateTime.Now.ToString("HH:mm:ss");
                Thread.Sleep(1000);
                //break;
            }
        }

        public static Frm_Main Createfrm_Main()
        {
            if (frm_Main == null)
                frm_Main = new Frm_Main();
            return frm_Main;
        }
        #endregion

        #region 安装
        private void btn_install_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_filepath.Text))
            {
                return;
            }
            //if (Const.config.system != "Linux")
            //{
            //    MessageBox.Show("只支持linux服务器！");
            //    return;
            //}
            Clear_Image = cb_clear_image.Checked;

            if (File.Exists(txt_filepath.Text))
            {
                Const.config.localfile_path = txt_filepath.Text;
                if (!Const.Is_BadZip(Const.config.localfile_path, out string comment))
                {
                    MessageBox.Show("压缩包已损坏，请检查！");
                    return;
                }
                if (string.IsNullOrEmpty(comment))
                {
                    MessageBox.Show("此文件非研发部打包的正式版本，不允许使用！");
                    return;
                }
                if (MessageBox.Show(comment, "请核对文件信息", MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes)
                {
                    return;
                }

                if (!comment.Trim().StartsWith("Installation Package"))
                {
                    if (MessageBox.Show($"选择的文件为升级包，不建议直接安装。确定继续使用？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes)
                    {
                        return;
                    }
                }
                //检测工具是否有更新
                if (Update_Tools())
                {
                    return;
                }
                timer_Timeout.Enabled = true;
                lbl_usetime.Text = "已用时间：";
                _run_time = DateTime.Now;
                foreach (Control item in Controls)
                {
                    if (item.Name != "link_catlog")
                        item.Enabled = false;
                }
                Task.Factory.StartNew(() =>
                {
                    _method.New_Install(Clear_Image);
                });

            }
            else
            {
                MessageBox.Show("文件不存在，请检查！");
                return;
            }
        }
        #endregion

        #region 操作完毕触发事件
        public void End(bool suc)
        {
            Invoke(new Action(() =>
            {
                timer_Timeout.Enabled = false;
                foreach (Control item in Controls)
                {
                    item.Enabled = true;
                }
                lbl_log.Text = "";
                lbl_version.Text = _method.Get_Version();
                if (lbl_version.Text != "未安装")
                {
                    btn_update.Enabled = true; ;
                    btn_install.Enabled = false;
                }
                else
                {
                    btn_update.Enabled = false;
                    btn_install.Enabled = true;
                }

                if (suc)
                {
                    if (MessageBoxEx.Show("操作完成，是否打开首页测试？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start($"http://{Const.config.ip}:{ihdis_port}00");
                    }
                }
            }));
        }
        #endregion

        #region 更新
        private void btm_update_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_filepath.Text))
            {
                return;
            }
            //if (Const.config.system != "Linux")
            //{
            //    MessageBox.Show("只支持linux服务器！");
            //    return;
            //}

            Clear_Image = cb_clear_image.Checked;

            if (File.Exists(txt_filepath.Text))
            {
                Const.config.localfile_path = txt_filepath.Text;
                if (!Const.Is_BadZip(Const.config.localfile_path, out string comment))
                {
                    MessageBox.Show("压缩包已损坏，请检查！");
                    return;
                }
                if (string.IsNullOrEmpty(comment))
                {
                    MessageBox.Show("此文件非研发部打包的正式版本，不允许使用！");
                    return;
                }

                if (MessageBox.Show(comment, "请核对文件信息", MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes)
                {
                    return;
                }

                if (!comment.Trim().StartsWith("Upgrade Package"))
                {
                    if (MessageBox.Show($"选择的文件为安装包，不建议直接升级。确定继续使用？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes)
                    {
                        return;
                    }
                }
                //检查是否已经执行数据库脚本
                //if (Const.config.system != "Linux")
                //{
                var dbresult = _method.Get_DbVersion();
                if (dbresult.Item1 && !string.IsNullOrEmpty(dbresult.Item2))
                {
                    var ver = Const.config.localfile_path.Substring(Const.config.localfile_path.LastIndexOf('\\') + 1).Replace(".zip", "");
                    if (dbresult.Item2 != ver)
                    {
                        if (MessageBox.Show($"当前数据库版本为：{dbresult.Item2}\r\n待升级的主版本为：{ver}\r\n建议先比对数据库文件，再执行升级操作，是否继续升级主版本？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes)
                        {
                            return;
                        }
                    }
                }
                //}
                //检测工具是否有更新
                if (Update_Tools())
                {
                    return;
                }
                timer_Timeout.Enabled = true;
                lbl_usetime.Text = "已用时间：";
                _run_time = DateTime.Now;
                foreach (Control item in Controls)
                {
                    if (item.Name != "link_catlog")
                        item.Enabled = false;
                }
                Task.Factory.StartNew(() =>
                {
                    _method.New_Update(Clear_Image, comment);
                });
            }
            else
            {
                MessageBox.Show("文件不存在，请检查！");
                return;
            }
        }
        #endregion

        #region 选择文件
        private void btn_selectfile_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Multiselect = false;//该值确定是否可以选择多个文件
                ofd.Title = "请选择文件";
                ofd.Filter = "插件zip文件|*.zip";
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    this.txt_filepath.Text = ofd.FileName;
                }
            }
        }
        #endregion

        #region 查看日志
        private void link_catlog_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                string fname = AppDomain.CurrentDomain.BaseDirectory + "Logs\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
                System.Diagnostics.Process.Start("explorer.exe", "/select," + fname);
            }
            catch { }
        }
        #endregion

        #region 耗时
        private void timer_Timeout_Tick(object sender, EventArgs e)
        {
            lbl_log.Text = Const.read_task_log();
            var total = DateTime.Now.Subtract(_run_time);
            lbl_usetime2.Text = $"{total.Minutes}:{total.Seconds}";
        }
        #endregion

        #region 初始化
        private void Frm_Main_Load(object sender, EventArgs e)
        {
            if (Const.config.system == "Linux")
            {
                this.Text = "运维工具" + $" {Const.config.name} {Const.config.ip}";
            }
        }
        #endregion

        #region 退出
        private void Frm_Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (ischeckselect)
            {
                _method.stop_test();
                Frm_Login.Create_Login().Show();
                frm_Main = null;
                ischeckselect = false;
            }
            else
            {
                Environment.Exit(0);
            }
        }

        private void 退出ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }
        #endregion

        #region 工具管理
        private void mysql管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var version = _method.Get_Version();
            if (lbl_version.Text != "未安装")
            {
                try
                {
                    System.Diagnostics.Process.Start($"http://{Const.config.ip}:{ihdis_port}21");
                }
                catch (Exception ex)
                {
                    var log = ex.ToString();
                    Const.write_log(log);
                    MessageBox.Show(log, "提示");
                }
            }
            else
            {
                MessageBox.Show("该环境尚未安装！", "提示");
            }
        }

        private void mQ管理ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var version = _method.Get_Version();
            if (lbl_version.Text != "未安装")
            {
                try
                {
                    System.Diagnostics.Process.Start($"http://{Const.config.ip}:{ihdis_port}81");
                }
                catch (Exception ex)
                {
                    var log = ex.ToString();
                    Const.write_log(log);
                    MessageBox.Show(log, "提示");
                }
            }
            else
            {
                MessageBox.Show("该环境尚未安装！", "提示");
            }
        }

        private void redis管理ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var version = _method.Get_Version();
            if (lbl_version.Text != "未安装")
            {
                try
                {
                    System.Diagnostics.Process.Start($"http://{Const.config.ip}:{ihdis_port}22");
                }
                catch (Exception ex)
                {
                    var log = ex.ToString();
                    Const.write_log(log);
                    MessageBox.Show(log, "提示");
                }
            }
            else
            {
                MessageBox.Show("该环境尚未安装！", "提示");
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var version = _method.Get_Version();
            if (lbl_version.Text != "未安装")
            {
                try
                {
                    System.Diagnostics.Process.Start($"http://{Const.config.ip}:{ihdis_port}23");
                }
                catch (Exception ex)
                {
                    var log = ex.ToString();
                    Const.write_log(log);
                    MessageBox.Show(log, "提示");
                }
            }
            else
            {
                MessageBox.Show("该环境尚未安装！", "提示");
            }
        }
        #endregion

        #region 数据库比对工具
        private void tsmi_DbCompare_Click(object sender, EventArgs e)
        {

            var version = _method.Get_Version();
            if (lbl_version.Text != "未安装")
            {
                var installpath = Const.config.install_item_dir;
                var tmp = installpath.Split('/');
                var server = Const.config.ip;
                var port = $"{ihdis_port}90";
                var password = Const.config.db_passwd;
                var userid = "jlmedcompare";

                #region 处理云数据库
                if (Const.config.IsCloudDB)
                {
                    var connectionString = Const.config.CloudDBConnectionString;
                    var connectionString1 = connectionString.Split(';');
                    if(connectionString1.Length == 4)
                    {
                        server = connectionString1[0];
                        port = connectionString1[1];
                        userid = connectionString1[2];
                        password = connectionString1[3];
                    }
                }
                #endregion

                using (Frm_DBCompare_Step1 f = new Frm_DBCompare_Step1($"server = {server}; port = {port}; userid = {userid}; password = {password};database=hdis;sslmode=none;allowPublicKeyRetrieval=true;", _method.sSH))
                {
                    f.ShowDialog();
                    f.TopMost = true;
                }
            }
            else
            {
                MessageBox.Show("该环境尚未安装，请安装后在进行数据库比对！", "提示");
            }
        }
        #endregion

        #region 定时备份
        private void 定时备份ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Frm_Backup backup = new Frm_Backup();
            backup.ShowDialog();
        }

        #endregion

        #region 更新运维工具
        private bool Update_Tools()
        {
            //版本号提示
            ZipFile entry = new ZipFile(this.txt_filepath.Text);
            var ziptxt = entry.ZipFileComment;
            string[] sArray = Regex.Split(ziptxt, "ToolsVersion", RegexOptions.IgnoreCase);
            string version = "";
            if (sArray.Length > 1)
            {
                version = sArray[0].Trim();
            }
            var localversion = File.Exists("config/Version.ini") ? File.ReadAllText("config/Version.ini").Split('\n')[0].Replace("[", "").Replace("]", "").Replace("\r", "") : "";
            if (!string.IsNullOrEmpty(version) && localversion != version)
            {
                MessageBox.Show("运维工具不是最新版本，请更新", "提示");
                return true;
            }
            return false;
        }
        #endregion

        #region 切换服务器
        private void 选择服务器ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                ischeckselect = true;
                this.Close();
            }
            catch (Exception ex)
            {
                var log = ex.ToString();
                Const.write_log(log);
                MessageBox.Show(log, "提示");
            }
        }
        #endregion

        #region 数据导出
        /// <summary>
        /// 数据导出方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataExportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool pathSelect = false;

            if (ExportView == null || ExportView.IsDisposed)
            {
                string filePath = string.Empty;

                #region 设置文件路径
                using (FolderBrowserDialog path = new FolderBrowserDialog())
                {
                    if (path.ShowDialog() == DialogResult.OK)
                    {
                        /*
                         * 如果文件存在则直接覆盖掉
                         */
                        if (System.IO.File.Exists($"{path.SelectedPath}\\hdis_{Const.config.ip.Replace(".", "_")}_{DateTime.Now.ToString("yyyy_MM_dd")}.sql"))
                        {
                            if (MessageBox.Show("文件已存在，是否覆盖？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                            {
                                return;
                            }
                            else
                            {
                                pathSelect = true;
                                filePath = $"{path.SelectedPath}\\hdis_{Const.config.ip.Replace(".", "_")}_{DateTime.Now.ToString("yyyy_MM_dd")}.sql";//返回文件的完整路径   
                                File.Delete(filePath);
                            }
                        }
                        else
                        {
                            pathSelect = true;
                            filePath = $"{path.SelectedPath}\\hdis_{Const.config.ip.Replace(".", "_")}_{DateTime.Now.ToString("yyyy_MM_dd")}.sql";//返回文件的完整路径   
                        }
                    }
                }
                #endregion

                if (pathSelect)
                {
                    string install_dir = Const.config.install_dir;
                    string install_dir_item = Const.config.install_item_dir;
                    string user = Const.config.db_user;
                    string password = Const.config.db_passwd;

                    ExportView = new Frm_DataExport(install_dir, install_dir_item, _method, filePath, "root", password);
                    ExportView.ShowDialog();
                }
            }
            else
            {
                ExportView.ShowDialog();
            }
        }
        private Frm_DataExport ExportView { set; get; }
        #endregion

        #region 模块管理
        private void 模块管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (Frm_Moudule frm_Moudule = new Frm_Moudule())
                frm_Moudule.ShowDialog();
        }
        #endregion

        #region 多套管理
        private void 多套管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (Frm_MultiEnvironment f = new Frm_MultiEnvironment())
            {
                f.ShowDialog();
                var mes = Const.MultiEnvs.Where(o => o.Ip == Const.config.ip).Select(o => o.Name).ToArray();

                cmb_MultiEnv.Items.Clear();

                this.cmb_MultiEnv.Items.AddRange(mes);
                if (mes.Any())
                    this.cmb_MultiEnv.Text = this.cmb_MultiEnv.Items[0].ToString();
            }
        }
        #endregion

        #region 多环境切换
        string ihdis_port = "600";
        private void cmb_MultiEnv_SelectedIndexChanged(object sender, EventArgs e)
        {
            var item = Const.MultiEnvs.Where(o => o.Ip == Const.config.ip && o.Name == this.cmb_MultiEnv.Text).FirstOrDefault();
            Const.config.install_item_dir = Const.config.install_dir + "/" + item.FileName;
            ihdis_port = item.DefaultPort;

            lbl_version.Text = _method.Get_Version();

            if (lbl_version.Text != "未安装")
            {
                btn_update.Enabled = true; ;
                btn_install.Enabled = false;
            }
            else
            {
                btn_update.Enabled = false;
                btn_install.Enabled = true;
            }
        }
        #endregion

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

        private void AboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (Form_About f = new Form_About())
            {
                f.ShowDialog();
            }
        }
    }
}
