using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using ChuPiao.AutoPrint.Desktop.StatusBar;
using ChuPiao.AutoPrint.Machine;
using ChuPiao.AutoPrint.Services;
using ChuPiao.Common.Models;
using ChuPiao.Common.Utils;
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Core;
using ChuPiao.AutoPrint.Services.AutoPrint;

namespace ChuPiao.AutoPrint.Desktop.Workbench
{
    public partial class LogOutputView : UserControl
    {
        public LogOutputView()
        {
            InitializeComponent();
        }
        private string _currentLogName = "all";
        private MemoryAppender _memoryAppender;

        private void LogOutputView_Load(object sender, EventArgs e)
        {
            try
            {
                this.Dock = DockStyle.Fill;
                this.Text = "日志输出";
                this.flowLayoutPanel1.Controls.Clear();

                //配置MemoryAppender
                _memoryAppender = new MemoryAppender();
                BasicConfigurator.Configure(_memoryAppender);

                RadioButton radioButton = new RadioButton();
                radioButton.Checked = true;
                radioButton.CheckedChanged += new EventHandler(radioButton_CheckedChanged);
                radioButton.Text = "全部日志";
                radioButton.Tag = "all";
                radioButton.Name = "radioButton_all";
                radioButton.AutoSize = true;
                this.flowLayoutPanel1.Controls.Add(radioButton);
                radioButton = new RadioButton();
                radioButton.Checked = false;
                radioButton.CheckedChanged += new EventHandler(radioButton_CheckedChanged);
                radioButton.Text = "系统日志";
                radioButton.Tag = "default";
                radioButton.Name = "radioButton_default";
                radioButton.AutoSize = true;
                this.flowLayoutPanel1.Controls.Add(radioButton);
                foreach (ILotMachine lotMachine in LotMachineService.LotMachineList.Values)
                {
                    M_MachineEntity entity = lotMachine.MachineInfo;
                    ILog log = LogManager.GetLogger(entity.M_Number);
                    radioButton = new RadioButton();
                    radioButton.Checked = false;
                    radioButton.CheckedChanged += new EventHandler(radioButton_CheckedChanged);
                    radioButton.Text = entity.M_Number + "日志";
                    radioButton.Tag = log.Logger.Name;
                    radioButton.Name = "radioButton_" + entity.M_Number;
                    radioButton.AutoSize = true;
                    this.flowLayoutPanel1.Controls.Add(radioButton);
                    //LogUtil.AddMemoryAppender(log, _memoryAppender);
                }
                _logRefreshTimer.Enabled = true;
                toolStripButtonStopBell.Enabled = false;
            }
            catch (Exception exception)
            {
                MessageBox.Show(string.Concat("日志输出窗口加载异常：", exception));
            }
        }
        /// <summary>
        /// 切换日志类别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                this.txtLog.Clear();
                RadioButton radioButton = sender as RadioButton;
                if (radioButton != null && radioButton.Tag != null)
                {
                    _currentLogName = radioButton.Tag.ToString();
                    //if (_currentLogName != "all")
                    //{
                    //    this.txtLog.Lines = LogUtil.GetLastLogContentByName(_currentLogName).ToArray();
                    //    this.txtLog.AppendText(Environment.NewLine);
                    //    this.txtLog.ScrollToCaret();
                    //}
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(string.Concat("切换日志类别异常：", exception));
            }
        }
        //日志显示最大行数
        private const int MAXLOGLINE = 500;
        //日志显示最小行数
        private const int MINLOGLINE = 100;
        /// <summary>
        /// 日志定时刷新事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LogRefreshTimerTick(object sender, EventArgs e)
        {
            try
            {
                LoggingEvent[] events = _memoryAppender.GetEvents();

                if (events != null && events.Length > 0)
                {
                    _memoryAppender.Clear();
                    string logname = _currentLogName;
                    foreach (LoggingEvent loggingEvent in events)
                    {
                        

                        if (loggingEvent.Level.Value >= 60000)
                        {
                            //warn以上级别日志

                            //if (txtWarnLog.Lines.Length > MAXLOGLINE)
                            //{
                            //    //仅保留最近的n行(n=MINLOGLINE)
                            //    string[] tmpArr = new string[MINLOGLINE];
                            //    Array.Copy(txtWarnLog.Lines, txtWarnLog.Lines.Length - MINLOGLINE, tmpArr, 0, MINLOGLINE);
                            //    this.txtWarnLog.Lines = tmpArr;
                            //}

                            string line = string.Format("{0} [{1}] {2} {3} - {4}{5}",
                                                    loggingEvent.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss fff"),
                                                    loggingEvent.ThreadName, loggingEvent.Level.Name,
                                                    loggingEvent.LoggerName, loggingEvent.RenderedMessage,
                                                    Environment.NewLine);
                            txtWarnLog.AppendText(line);
                            txtWarnLog.ScrollToCaret();
    
                            if (BeepUtil.notUseBeep)
                            {
                                toolStripButtonStopBell.Enabled = true;
                                //axWindowsMediaPlayer1.URL = BeepUtil.fileToPlay;
                                //axWindowsMediaPlayer1.settings.autoStart = false;
                                //axWindowsMediaPlayer1.settings.volume = 80;
                                //axWindowsMediaPlayer1.settings.setMode("loop", true);
                                //axWindowsMediaPlayer1.Ctlcontrols.play();
                            }
                            else
                            {
                                StatusBarService.ShowWarnButton();
                            }

                            //有报这个错，就不允许开始出票
                            if (loggingEvent.RenderedMessage.Contains("函数不正确"))
                            {
                                AutoPrintService.isCOMOK = false;
                                MessageService.ShowMessage("COM口异常，不能开启出票!!!请尝试重启软件、电脑", "操作提示");
                            }
                        }
                        else
                        {
                            if (logname != "default" && loggingEvent.Level.Value <= 30000)
                            {
                                //debug日志
                                continue;
                            }

                            //info日志
                            if (logname != "all" && loggingEvent.LoggerName != logname)
                            {
                                //仅显示当前指定类别的日志
                                continue;
                            }
                            //if (txtLog.Lines.Length > MAXLOGLINE)
                            //{
                            //    //仅保留最近的n行(n=MINLOGLINE)
                            //    string[] tmpArr = new string[MINLOGLINE];
                            //    Array.Copy(txtLog.Lines, txtLog.Lines.Length - MINLOGLINE, tmpArr, 0, MINLOGLINE);
                            //    this.txtLog.Lines = tmpArr;
                            //}
                            string line = string.Format("{0} [{1}] {2} {3} - {4}{5}",
                                                    loggingEvent.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss fff"),
                                                    loggingEvent.ThreadName, loggingEvent.Level.Name,
                                                    loggingEvent.LoggerName, loggingEvent.RenderedMessage,
                                                    Environment.NewLine);
                            txtLog.AppendText(line);
                            txtLog.ScrollToCaret();
                        }
                    }
                    if (txtWarnLog.Lines.Length > MAXLOGLINE)
                    {
                        //仅保留最近的n行(n=MINLOGLINE)
                        string[] tmpArr = new string[MINLOGLINE];
                        Array.Copy(txtWarnLog.Lines, txtWarnLog.Lines.Length - MINLOGLINE, tmpArr, 0, MINLOGLINE);
                        this.txtWarnLog.Lines = tmpArr;
                    }
                    if (txtLog.Lines.Length > MAXLOGLINE)
                    {
                        //仅保留最近的n行(n=MINLOGLINE)
                        string[] tmpArr = new string[MINLOGLINE];
                        Array.Copy(txtLog.Lines, txtLog.Lines.Length - MINLOGLINE, tmpArr, 0, MINLOGLINE);
                        this.txtLog.Lines = tmpArr;
                    }
                }
            }
            catch (Exception exception)
            {
                LoggingService.Debug(string.Concat("刷新日志异常：",exception));
            }
            
        }
        /// <summary>
        /// 双击文本框查看日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtLog_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                if (_currentLogName != "all")
                {
                    string[] msgs = LogUtil.GetLastLogContentByName(_currentLogName).ToArray();
                    ShowLogForm form = new ShowLogForm(msgs);
                    form.Show(this);
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(string.Concat("查看日志信息异常：",exception));
            }
        }
        /// <summary>
        /// 复制到剪切板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtonCopy_Click(object sender, EventArgs e)
        {
            ClipboardUtil.SetText(this.txtWarnLog.Text);
        }
        /// <summary>
        /// 剪切到剪切板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtonCut_Click(object sender, EventArgs e)
        {
            ClipboardUtil.SetText(this.txtWarnLog.Text);
            this.txtWarnLog.Text = "";
        }
        /// <summary>
        /// 清空
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtonClear_Click(object sender, EventArgs e)
        {
            this.txtWarnLog.Text = "";
        }
        /// <summary>
        /// 停止报警
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButtonStopBell_Click(object sender, EventArgs e)
        {
            toolStripButtonStopBell.Enabled = false;
            
            if (BeepUtil.notUseBeep)
            {
                //axWindowsMediaPlayer1.Ctlcontrols.stop();
            }
            else
            {
                BeepUtil.Instance().StopCurrent();
            }
        }
    }
}
