using SWRIS.Core;
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;

namespace SWRIS.Extensions
{
    public class SimpleLogger
    {
        private string GetFilePath()
        {
            if (DateTime.Now.Date > LastDate.Date)
            {
                FileIndex = 1;
            }
            LogPath = (LogPath.EndsWith("\\") ? LogPath.Substring(0, LogPath.Length - 1) : LogPath);
            string text = string.Format("{0}\\{1}\\{2}{3}.log", new object[]
            {
                LogPath,
                DateTime.Now.ToString("yyyy-MM-dd"),
                FileName,
                FileIndex
            });
            if (!File.Exists(text))
            {
                FileHelper.CreateFile(text, string.Empty);
            }
            string result;
            if (GetFileSize(text) > MaxSize)
            {
                FileIndex++;
                result = GetFilePath();
            }
            else
            {
                LastDate = DateTime.Now;
                result = text;
            }
            return result;
        }

        private long GetFileSize(string filePath)
        {
            return new FileInfo(filePath).Length / 1024L;
        }

        private void Write(string text)
        {
            if (IsAsyn)
            {
                AsynWriteLog(text);
            }
            else
            {
                WriteLog(text);
            }
        }

        private void WriteLog(string text)
        {
            try
            {
                string filePath = GetFilePath();
                using (StreamWriter streamWriter = new StreamWriter(filePath, true))
                {
                    streamWriter.WriteLine(text);
                    streamWriter.Flush();
                }
            }
            catch
            {
            }
        }

        private void AsynWriteLog(string value)
        {
            ThreadPool.QueueUserWorkItem(delegate (object obj)
            {
                try
                {
                    WriteLog(value);
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex.Message, ex);
                }
            });
        }
        private string LogFormat(string content, string logLevel, Exception exception)
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(Environment.NewLine);
            stringBuilder.AppendLine("//==========================================================================================================");
            stringBuilder.AppendFormat("系统时间：{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
            stringBuilder.Append("  ");
            stringBuilder.AppendFormat("当前线程ID：{0}", Thread.CurrentThread.ManagedThreadId);
            stringBuilder.Append(Environment.NewLine);
            stringBuilder.AppendFormat("日志等级：{0}", logLevel);
            stringBuilder.Append(Environment.NewLine);
            stringBuilder.AppendFormat("日志内容：{0}", content);
            if (exception != null)
            {
                stringBuilder.Append(Environment.NewLine);
                stringBuilder.AppendLine("异常信息：");
                stringBuilder.Append(exception.ToLogString());
            }
            return stringBuilder.ToString();
        }

        [Obsolete("记录消息，无任何格式处理，记录系统日志请勿使用该功能")]
        public void LogMessage(string content)
        {
            try
            {
                string filePath = GetFilePath();
                using (StreamWriter streamWriter = new StreamWriter(filePath, true))
                {
                    streamWriter.WriteLine(content);
                    streamWriter.Flush();
                }
            }
            catch
            {
            }
        }
        [Obsolete("删除传入日期前一天的日志信息")]
        public void DeleteLog(DateTime dateTime)
        {
            try
            {
                LogPath = (LogPath.EndsWith("\\") ? LogPath.Substring(0, LogPath.Length - 1) : LogPath);
                string text = string.Format("{0}\\{1}", new object[]
                {
                LogPath,
                dateTime.AddDays(-1).ToString("yyyy-MM-dd")

                });
                if (Directory.Exists(text))
                {
                    Directory.Delete(text, true);
                }

            }
            catch
            {
            }
        }
        public void Log(string content, string level, Exception ex)
        {
#if Debug
            Console.WriteLine(content);
#endif
            string text = LogFormat(content, level, ex);
            Write(text);
        }

        public int MaxSize = 2048;

        public string LogPath = FileHelper.GetPhysicalPath("Log");

        public string FileName = "Log";

        public bool IsAsyn = true;

        private int FileIndex = 1;

        private DateTime LastDate = DateTime.Now;
    }
}
