using System.ComponentModel;
using System.Data;
using System.Text;

namespace PowerEasy.WebFuture.DataMigrations.Foundation.Log
{
    /// <summary>
    /// 日志帮助类。
    /// </summary>
    public static class LogHelper
    {
        /// <summary>
        /// 窗体文本控件。
        /// </summary>
        public static TextBox TextBox { get; set; }

        /// <summary>
        /// 后台工作者实例。
        /// </summary>
        public static BackgroundWorker BackgroundWorker { get; set; }

        /// <summary>
        /// 写日志。
        /// </summary>
        /// <param name="logMessage">日志信息。</param>
        public static void WriteLog(string logMessage)
        {
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "/Logs/", $"log{DateTime.Now.ToString("yyyy-MM-dd")}.txt");
            FileInfo fileInfo = new FileInfo(path);
            if (!Directory.Exists(fileInfo.DirectoryName))
            {
                Directory.CreateDirectory(fileInfo.DirectoryName);
            }

            try
            {
                using (StreamWriter streamWriter = new StreamWriter(path, true, Encoding.GetEncoding("utf-8")))
                {
                    streamWriter.WriteLine(DateTime.Now.ToString() + "  " + logMessage);
                }
            }
            catch
            {
                ////throw new FileNotFoundException(ex.ToString());
            }
        }

        /// <summary>
        /// 写异常到日志。
        /// </summary>
        /// <param name="ae">异常信息。</param>
        /// <param name="dataTable">异常出现的表。</param>
        public static void WriteExceptionLog(Exception ae, DataTable dataTable = null)
        {
            var logMessage = string.Empty;
            if (dataTable == null)
            {
                logMessage = DateTime.Now.ToString("yyyy -MM-dd HH:mm:ss") + @"
                                        -----------------------异常信息---------------------
                                        异常详细信息：\r\n" + ae.Message + @"
                                        堆栈：" + ae.StackTrace + @"
                                        -----------------------------------------------------/\r\n";
            }
            else
            {
                logMessage = DateTime.Now.ToString("yyyy -MM-dd HH:mm:ss") + @"
                                        -----------------------异常信息---------------------
                                        数据表" + dataTable.TableName + @"发生异常
                                        异常详细信息：\r\n" + ae.Message + @"
                                        堆栈：" + ae.StackTrace + @"
                                        -----------------------------------------------------/\r\n";
            }

            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "/Logs/", $"log{DateTime.Now.ToString("yyyy-MM-dd")}.txt");
            FileInfo fileInfo = new FileInfo(path);
            if (!Directory.Exists(fileInfo.DirectoryName))
            {
                Directory.CreateDirectory(fileInfo.DirectoryName);
            }

            try
            {
                using (StreamWriter streamWriter = new StreamWriter(path, true, Encoding.GetEncoding("utf-8")))
                {
                    streamWriter.WriteLine(DateTime.Now.ToString() + "  " + logMessage);
                }
            }
            catch (Exception ex)
            {
                throw new FileNotFoundException(ex.ToString());
            }
        }

        /// <summary>
        /// 写异常到日志和窗体控件里面。
        /// </summary>
        /// <param name="logMessage">异常信息。</param>
        public static void WriteLogAndFormLog(string logMessage)
        {
            WriteLog(logMessage);

            LogHelper.TextBox.AppendText(logMessage + Environment.NewLine);
        }

        /// <summary>
        /// 异步写异常到日志和窗体控件里面。
        /// </summary>
        /// <param name="logMessage">异常信息。</param>
        public static void WriteLogAndFormLogByAsyn(string logMessage)
        {
            WriteLog(logMessage);

            LogHelper.TextBox.Invoke(new EventHandler(delegate
            {
                LogHelper.TextBox.Text += logMessage;
                LogHelper.TextBox.SelectionStart = LogHelper.TextBox.Text.Length;
                LogHelper.TextBox.ScrollToCaret();
            }));
        }

        /// <summary>
        /// 迁移完成输出日志。
        /// </summary>
        /// <param name="modelName">表名。</param>
        /// <param name="allStatus">状态。</param>
        public static void FinishWriteLogAndFormLogByAsyn(string modelName, bool allStatus)
        {
            var log = string.Empty;
            if (allStatus)
            {
                log = $"********************{modelName}表迁移完成********************\r\n\r\n";
            }
            else
            {
                log = $"********************{modelName}表迁移失败，异常请查看日志！********************\r\n\r\n";
            }

            WriteLog(log);

            LogHelper.TextBox.Invoke(new EventHandler(delegate
            {
                LogHelper.TextBox.Text += log;
                LogHelper.TextBox.SelectionStart = LogHelper.TextBox.Text.Length;
                LogHelper.TextBox.ScrollToCaret();
            }));
        }

        /// <summary>
        /// 迁移过程输出日志。
        /// </summary>
        /// <param name="modelName">表名。</param>
        /// <param name="status">状态。</param>
        /// <param name="count">数量。</param>
        public static void IngWriteLogAndFormLogByAsyn(string modelName, bool status, int count)
        {
            var log = string.Empty;
            if (status)
            {
                log = $"********************{modelName}表迁移成功数量:{count}********************\r\n\r\n";
            }
            else
            {
                log = $"********************{modelName}表迁移失败，异常请查看日志！********************\r\n\r\n";
            }

            WriteLog(log);

            LogHelper.TextBox.Invoke(new EventHandler(delegate
            {
                LogHelper.TextBox.Text += log;
                LogHelper.TextBox.SelectionStart = LogHelper.TextBox.Text.Length;
                LogHelper.TextBox.ScrollToCaret();
            }));
        }

        /// <summary>
        /// 迁移开始输出日志。
        /// </summary>
        /// <param name="modelName">表名。</param>
        public static void StartWriteLogAndFormLogByAsyn(string modelName)
        {
            var log = $"********************开始插入{modelName}模型数据********************\r\n\r\n";

            WriteLog(log);

            LogHelper.TextBox.Invoke(new EventHandler(delegate
            {
                LogHelper.TextBox.Text += log;
                LogHelper.TextBox.SelectionStart = LogHelper.TextBox.Text.Length;
                LogHelper.TextBox.ScrollToCaret();
            }));
        }
    }
}
