using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Common
{
    public class Log
    {
        /// <summary>
        /// 禁止通过new创建实例
        /// </summary>
        private Log() { }

        private static Log log;

        // 定义一个标识确保线程同步
        private static readonly object locker = new object();

        public static Log GetInstance()
        {
            if (log == null)
            {
                lock (locker)
                {
                    if (log == null)
                    {
                        log = new Log();
                    }
                }
            }
            return log;
        }

        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="iType">0智能终端  1数据采集 2网络状态 3计量实绩 4计量监控 5远程计量 6静态衡 7动态衡 8成品秤</param>
        /// <param name="str"></param>
        public void WriteLog(int iType, string str)
        {
            try
            {
                string strLogName = "";
                switch (iType)
                {
                    case 0:
                        strLogName = "计量终端_"; 
                        break;
                    case 1:
                        strLogName = "数据采集_";
                        break;
                    case 2:
                        strLogName = "网络状态_";
                        break;
                    case 3:
                        strLogName = "计量实绩_";
                        break;
                    case 4:
                        strLogName = "计量监控_";
                        break;
                    case 5:
                        strLogName = "远程计量_";
                        break;
                    case 6:
                        strLogName = "静态衡计量_";
                        break;
                    case 7:
                        strLogName = "动态衡计量_";
                        break;
                    case 8:
                        strLogName = "热送磅计量_";
                        break;
                    case 9:
                        strLogName = "提示信息_";
                        break;
                    case 10:
                        strLogName = "打印日志_";
                        break;
                    case 11:
                        strLogName = "静态衡公共事件_";
                        break;
                    case 12:
                        strLogName = "主线程扫码设备_";
                        break;
                    case 13:
                        strLogName = "tryCatch异常_";
                        break;
                    case 14:
                        strLogName = "保存按钮状态_";
                        break;
                    case 15:
                        strLogName = "按钮点击日志_";
                        break;
                    case 16:
                        strLogName = "服务调用日志_";
                        break;
                    case 17:
                        strLogName = "自动卸货日志_";
                        break;
                    case 18:
                        strLogName = "复磅计量_";
                        break;
                    case 19:
                        strLogName = "热送磅计量异常_";
                        break;
                    case 20:
                        strLogName = "零点报警_";
                        break;
                    case 22:
                        strLogName = "皮带秤计量异常_";
                        break;
                    case 23:
                        strLogName = "吊钩秤计量异常_";
                        break;
                    case 24:
                        strLogName = "检化验接口日志_";
                        break;
                    default: 
                        strLogName = "计量终端_"; 
                        break;
                }

                string m_szRunPath;
                m_szRunPath = System.Environment.CurrentDirectory;
                if (System.IO.Directory.Exists(m_szRunPath + "\\log") == false)
                {
                    System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
                }
                string strDate = System.DateTime.Now.ToString("yyyyMMdd");
                string strPathFile = m_szRunPath + "\\log\\" + strDate;
                if (!Directory.Exists(strPathFile))//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(strPathFile);
                }
                System.IO.TextWriter tw = new System.IO.StreamWriter(strPathFile + "\\" + strLogName + strDate + ".log", true);

                tw.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                tw.WriteLine(str);
                tw.WriteLine("\r\n");

                tw.Close();
            }
            catch (Exception ex)
            {

            }
        }
        public class LogTwArray
        {
            public string Name;
            public DateTime LastWriteTime;
            public TextWriter tw = null;
            public string LastText = "";
        }
        static Dictionary<string, List<LogTwArray>> ht_pre = new Dictionary<string, List<LogTwArray>>();
        private static DateTime _lastCleanTime = DateTime.Now;
        private static Mutex mtx = new Mutex();
        static string m_szRunPath = System.Environment.CurrentDirectory;
        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="prefix">日志文件名前缀</param>
        /// <param name="str"></param>
        public  void WriteLog(string prefix, string str)
        {
            string strDate = DateTime.Now.ToString("yyyyMMdd");
            string strPathFile = m_szRunPath + "\\log\\" + strDate;
            List<LogTwArray> tws = null;
            LogTwArray lta = null;
            try
            {
                if (ht_pre.ContainsKey(prefix))
                {
                    tws = ht_pre[prefix];
                }
                else
                {
                    tws = new List<LogTwArray>();
                    if (!Directory.Exists(strPathFile))
                    {
                        Directory.CreateDirectory(strPathFile);
                    }
                    ht_pre.Add(prefix, tws);
                }

                lta = tws.Find(x => x.Name.Equals(strDate));
                if (lta == null || !lta.Name.Equals(strDate))
                {
                    lta = new LogTwArray();
                    lta.Name = strDate;
                    lta.tw = new StreamWriter(strPathFile + "\\" + prefix + "_" + strDate + ".log", true);
                    tws.Add(lta);
                }
                if (lta.LastText.Equals(str)) return;

                lta.LastWriteTime = DateTime.Now;
                lta.tw.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                lta.tw.WriteLine(str);
                lta.tw.WriteLine("\r\n");
                lta.tw.Flush();
                lta.LastText = str;
            }
            catch { }


            if (mtx.WaitOne(0))
            {
                try
                {
                    lock (ht_pre)
                    {
                        DateTime dt = DateTime.Now;
                        if (TimeSpan.FromTicks(dt.Ticks - _lastCleanTime.Ticks).TotalMinutes > 15)
                        {
                            foreach (List<LogTwArray> llta in ht_pre.Values)
                            {
                                List<LogTwArray> llta2 = llta.FindAll(x => TimeSpan.FromTicks(dt.Ticks - x.LastWriteTime.Ticks).TotalMinutes > 15);
                                if (llta2 != null)
                                {
                                    foreach (LogTwArray lt in llta2)
                                    {
                                        lt.tw.Close();
                                    }
                                }
                                llta.RemoveAll(x => TimeSpan.FromTicks(dt.Ticks - x.LastWriteTime.Ticks).TotalMinutes > 15);
                            }
                        }
                    }
                }
                finally
                {
                    mtx.ReleaseMutex();
                }
            }

        }

    }
}
