using Tiobon.Core.OPS.Tool.OPS.Tool.Helper;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace Tiobon.Core.OPS.Tool.OPS.Tool.View
{
    public partial class Frm_DBCompare_Step1 : Form
    {
        #region 初始化
        string m_HdisConnStr = string.Empty;
        string m_ConnStr = "";
        string m_FileName = "";
        string m_Version = "";
        SSHHelper sSH;
        public Frm_DBCompare_Step1(string connStr, SSHHelper sSH)
        {
            InitializeComponent();
            m_ConnStr = connStr;
            m_HdisConnStr = connStr;
            this.sSH = sSH;
            //this.txt_fname.Text = $"{Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)}\\v1.0_sql.zip";
            //m_FileName = $"{Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)}\\v1.0_sql.zip";//this.txt_fname.Text.Trim();
            Const.write_task_log($"正在执行数据库比对 {m_ConnStr}");
            timer_Main.Start();
        }

        bool m_Stop = false;
        private void Frm_DBCompare_Step1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                m_Stop = true;
            }
            catch { }
        }
        #endregion

        #region 选择文件
        private void btn_select_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_fname.Text = ofd.FileName;
                    m_FileName = this.txt_fname.Text;
                    if (!Const.Is_BadZip(m_FileName, out string comment))
                    {
                        MessageBox.Show("压缩包已损坏，请检查！");
                        return;
                    }
                    if (string.IsNullOrEmpty(comment))
                    {
                        MessageBox.Show("此文件非研发部打包的正式版本，不允许使用！");
                        return;
                    }
                    if (MessageBox.Show(comment, "请核对文件信息", MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes)
                    {
                        return;
                    }
                    m_Version = m_FileName.Substring(m_FileName.LastIndexOf('\\') + 1).Replace("v", "").Replace("_sql.zip", "").Trim();
                }
            }
        }
        #endregion

        #region 导入
        bool b_In = false;
        object m_LockIn = new object();
        private void btn_Import_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(m_FileName) || !File.Exists(m_FileName))
            {
                MessageBox.Show("文件不存在！", "提示");
                return;
            }
            lock (m_LockIn)
            {
                if (b_In)
                {
                    return;
                }
                else
                {
                    b_In = true;
                }
            }
            progressBar_Main.Minimum = 0;
            progressBar_Main.Value = 0;
            new System.Threading.Thread(Import).Start();
        }

        string sql_file = "";
        private void Zip_conf()
        {
            string path = string.Concat(Directory.GetCurrentDirectory(), "\\sql_conf");

            Const.ExtractZipFile(m_FileName, "sql_conf/", "", null);
            string parePath = SearchFile("CompareConfig.json", path);

            File.Copy(parePath, "Config/CompareConfig.json", true);
            sql_file = SearchFile("hdis.sql", path);
        }
        /// <summary>
        /// 搜索文件名称
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public string SearchFile(string filename, string path)
        {
            string[] temp = Directory.GetFiles(path, filename, SearchOption.AllDirectories);
            if (temp != null && temp.Length > 0) return temp[0];
            return string.Empty;
        }

        int m_PBMax = 0;
        int m_PBValue = 0;
        object m_LockProgressBar = new object();
        private void Import()
        {
            int sum = 0;
            try
            {
                SendLog("", "开始解压数据库与比对配置脚本");
                Zip_conf();
                SendLog("", "导入数据开始");
                FileInfo fileInfo = new FileInfo(sql_file);
                sum = (int)fileInfo.Length;
                lock (m_LockProgressBar)
                {
                    m_PBMax = sum;
                }
                //Regex pattern = new Regex(@"[uU][sS][eE].*[`]?ihdis.*[`]?");

                //导入之前，先清空原有数据库
                string sql = "DROP DATABASE IF EXISTS `hdis_compare`;";
                MySqlHelper.ExecuteNonQuery(m_ConnStr, sql);
                sql = "CREATE DATABASE `hdis_compare`;";
                MySqlHelper.ExecuteNonQuery(m_ConnStr, sql);
                SendLog("", "清理hdis_compare数据库成功");
                m_ConnStr = m_ConnStr.Replace("database=hdis", "database=hdis_compare");
                using (MySqlConnection conn = new MySqlConnection(m_ConnStr))
                {
                    conn.Open();
                    using (StreamReader sr = new StreamReader(new FileStream(sql_file, FileMode.Open, FileAccess.Read)))
                    {
                        int index = 0;
                        int count = 0;
                        StringBuilder sb = new StringBuilder();
                        while (sr.Peek() != -1)
                        {
                            if (m_Stop)
                                break;
                            sql = sr.ReadLine();
                            if (string.IsNullOrEmpty(sql))
                            {
                                if (sb.Length > 0 && index >= 1000)
                                {
                                    using (MySqlTransaction trans = conn.BeginTransaction())
                                    {
                                        sb.AppendLine("USE `hdis_compare`;");
                                        try
                                        {
                                            using (MySqlCommand command = new MySqlCommand(sb.ToString(), conn, trans))
                                            {

                                                command.ExecuteNonQuery();

                                            }
                                            trans.Commit();
                                        }
                                        catch (Exception ex)
                                        {

                                        }
                                    }
                                    sb.Clear();
                                    index = 0;
                                }
                                continue;
                            }
                            if (sql.StartsWith("-- "))
                            {
                                System.Threading.Thread.Sleep(50);
                                lock (m_LockProgressBar)
                                {
                                    m_PBValue = count;
                                }
                                SendLog("", (sql.Contains("-- 正在导出表") ? sql.Replace("-- 正在导出表", "正在导入表") : (sql.Contains("-- 导出") ? sql.Replace("-- 导出", "正在创建") : sql.Replace("-", "").Trim())).Replace("hdis", "hdis_compare").Replace("导出", "导入"));

                                Application.DoEvents();
                                continue;
                            }
                            if (count < 10000)
                            {
                                //防止 误操作
                                if (sql.Trim().ToLower().StartsWith("delete from")
                                    || sql.Trim().ToLower().StartsWith("truncate table")
                                    || sql.Trim().ToLower().StartsWith("drop table"))
                                    continue;
                                if (sql.Contains("`hdis`"))
                                    sql = sql.Replace("`hdis`", "`hdis_compare`");
                            }
                            index++;
                            count += sql.Length;
                            sb.AppendLine(sql);
                        }

                        if (index > 0)
                        {
                            using (MySqlTransaction trans = conn.BeginTransaction())
                            {
                                sb.AppendLine("USE `hdis_compare`;");
                                using (MySqlCommand command = new MySqlCommand(sb.ToString(), conn, trans))
                                {

                                    command.ExecuteNonQuery();

                                }
                                trans.Commit();
                            }
                            sb.Clear();
                            index = 0;
                        }
                    }
                }

                SendLog("", "导入数据完毕");
            }
            catch (Exception ex)
            {
                SendLog("", $"失败：{ex.ToString()}");
            }
            finally
            {
                lock (m_LockIn)
                {
                    b_In = false;
                }
                lock (m_LockProgressBar)
                {
                    m_PBMax = sum;
                    m_PBValue = sum;
                }
            }
        }
        #endregion

        #region 日志操作
        private static List<string> m_LogsTemp = new List<string>();
        private void timer_Main_Tick(object sender, EventArgs e)
        {
            try
            {
                lock (m_Logs)
                {
                    m_LogsTemp.Clear();
                    m_Logs.ForEach(log => m_LogsTemp.Add(log));
                    m_Logs.Clear();
                }

                if (m_LogsTemp.Count > 0)
                {
                    if (this.lb_Logger.Items.Count > 2000)
                        this.lb_Logger.Items.Clear();
                    m_LogsTemp.ForEach(log => this.lb_Logger.Items.Add(log));
                    this.lb_Logger.TopIndex = this.lb_Logger.Items.Count - 1;
                }

                lock (m_LockProgressBar)
                {
                    progressBar_Main.Maximum = m_PBMax;
                    progressBar_Main.Value = m_PBValue;
                }
            }
            catch { }
        }
        private static List<string> m_Logs = new List<string>();
        private void SendLog(string oprator, string msg)
        {
            lock (m_Logs)
            {
                Const.write_log($"[{oprator}] {msg}");
                if (string.IsNullOrEmpty(oprator))
                    m_Logs.Add($"{DateTime.Now.ToString("HH:mm:ss")} {msg}");
                else
                    m_Logs.Add($"{DateTime.Now.ToString("HH:mm:ss")} [{oprator}] {msg}");
            }
        }
        private void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetDataObject(this.lb_Logger.SelectedItem);
        }
        #endregion

        #region 下一步
        private void btn_Next_Click(object sender, EventArgs e)
        {
            this.Hide();
            using (Frm_DBCompare_Step2 f = new Frm_DBCompare_Step2(m_HdisConnStr, m_ConnStr, m_Version, sSH, WindowState))
            {
                f.ShowDialog();
            }
        }
        #endregion

    }
}
