using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using ChuPiao.AutoPrint.Common;
using ChuPiao.AutoPrint.Desktop.AutoEncash;
using ChuPiao.AutoPrint.Desktop.AutoPrint;
using ChuPiao.AutoPrint.Desktop.Machine;
using ChuPiao.AutoPrint.Desktop.Properties;
using ChuPiao.AutoPrint.Desktop.StatusBar;
using ChuPiao.AutoPrint.Machine;
using ChuPiao.AutoPrint.Services;
using ChuPiao.Common.Core.Utils;
using ChuPiao.Common.Enums;
using ChuPiao.Common.Models;
using ChuPiao.Common.Utils;
using log4net;
using ChuPiao.AutoPrint.Services.AutoPrint;
using ChuPiao.AutoPrint.Services.OpenCode;

//using LogUIAppender = AutoPrint.Common.LogUIAppender;

namespace ChuPiao.AutoPrint.Desktop.Workbench
{
    public class DefaultWorkbench : Form
    {
        //TimeSyncService timeSyncService = new TimeSyncService();
        public void InitializeWorkspace()
        {
            this.Icon = ((System.Drawing.Icon)(Resources.Computer));
            // 获取程序集元数据
            Assembly assembly = Assembly.GetExecutingAssembly();
            AssemblyCopyrightAttribute copyright = (AssemblyCopyrightAttribute)AssemblyCopyrightAttribute.GetCustomAttribute(assembly, typeof(AssemblyCopyrightAttribute));
            AssemblyDescriptionAttribute description = (AssemblyDescriptionAttribute)AssemblyDescriptionAttribute.GetCustomAttribute(assembly, typeof(AssemblyDescriptionAttribute));
            
        

            this.Height = 600;
            this.WindowState = FormWindowState.Maximized;
            this.FormClosing+=new FormClosingEventHandler(DefaultWorkbench_FormClosing);
            this.FormClosed += new FormClosedEventHandler(DefaultWorkbench_FormClosed);
            this.Load+=new EventHandler(DefaultWorkbench_Load);
            Attach();
        }

        private void DefaultWorkbench_Load(object sender, System.EventArgs e)
        {
            try
            {
                tabPageAutoPrint.autoPrintToolStrip.toolStripComboBox_timetype.ComboBox.SelectedIndex = 0;
            }
            catch (Exception exception)
            {
                MessageBox.Show("DefaultWorkbench_Load()异常。错误信息：" + exception.Message, "错误提示", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
            try
            {
                new MethodInvoker(InitInThread).BeginInvoke(null, null);
            }
            catch (Exception exception)
            {
                LoggingService.Warn(string.Concat("DefaultWorkbench_Load()异常。错误信息：",exception.Message));
            }
        }
        private void InitInThread()
        {
            try
            {
               
            }
            catch (Exception exception)
            {
                LoggingService.Info(string.Concat("显示主备数据库异常。错误信息：",exception.Message));
            }
            

            //string IP = NetHelper.GetIpAddress();
            //timeSyncService.Start();
            /*try
            {
                //与数据库服务器同步时间
                LoggingService.Info("【与数据库服务器同步时间】开始同步...");
                TimeSynDao timeSynDao = new TimeSynDao();
                DateTime dbTime = timeSynDao.GetDate();
                string temp = ComputerExe.SetSystemTime(dbTime);
                LoggingService.Info("【与数据库服务器同步时间】" + temp);
            }
            catch (Exception ex)
            {
                LoggingService.Info("【与数据库服务器同步时间】异常：" + ex.Message + "\r\n" + ex.StackTrace);
            }*/
            //try
            //{
            //    //压缩当天前的日志文件
            //    LoggingService.Info("【压缩日志文件】开始压缩...");

            //    //压缩autoprintlot日志
            //    //获得log4net.xml配置文件中fileappend中配置的路径
            //    string logpath = Log4netUtil.FileAppendPath("default");
            //    if (!string.IsNullOrEmpty(logpath) && Directory.Exists(logpath))
            //    {
            //        string[] dirs = Directory.GetDirectories(logpath);
            //        if (null != dirs)
            //        {
            //            //当天的目录名，需要被排除在压缩目录外
            //            string todayname = DateTime.Now.ToString("yyyy-MM-dd");
            //            string yesterdayname = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
            //            //目录名，生成的压缩文件名中会用到
            //            string dirname;
            //            //从app.config的appsetting中取到配置的共享日志路径，再加上taskserver一起组成taskserver日志压缩文件目录
            //            string autoprintlot_sharedir = ConfigurationManager.AppSettings["LogShareDir"] + "Autoprintlot\\" + IP + "\\";
            //            if (!Directory.Exists(autoprintlot_sharedir))
            //            {
            //                Directory.CreateDirectory(autoprintlot_sharedir);
            //            }
            //            //压缩文件路径=日志压缩文件目录+压缩文件名
            //            string desdir;

            //            foreach (string dir in dirs)
            //            {
            //                if (dir.IndexOf(todayname) < 0)//&& dir.IndexOf(yesterdayname) < 0
            //                {
            //                    dirname = dir.Substring(dir.LastIndexOf("\\") + 1);
            //                    desdir = autoprintlot_sharedir + dirname + "_" + DateTime.Now.ToString("HHmmssfff") + ".zip";
            //                    LoggingService.Info("【压缩日志文件】" + dir + " => " + desdir);
            //                    SharpZipUtil.ZipFile(dir, desdir);
            //                    LoggingService.Info("【压缩日志文件】成功！");
            //                    LoggingService.Info("【压缩日志文件】删除" + dir);
            //                    Directory.Delete(dir, true);
            //                    LoggingService.Info("【压缩日志文件】成功！");
            //                }
            //            }
            //        }
            //    }

            //    foreach (string macnumber in LotMachineService.LotMachineList.Keys)
            //    {
            //        //获得log4net.xml配置文件中fileappend中配置的路径
            //        logpath = Log4netUtil.FileAppendPath(macnumber);
            //        if (!string.IsNullOrEmpty(logpath) && Directory.Exists(logpath))
            //        {
            //            string[] dirs = Directory.GetDirectories(logpath);
            //            if (null != dirs)
            //            {
            //                //当天的目录名，需要被排除在压缩目录外
            //                string todayname = DateTime.Now.ToString("yyyy-MM-dd");
            //                string yesterdayname = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
            //                //目录名，生成的压缩文件名中会用到
            //                string dirname;
            //                //从app.config的appsetting中取到配置的共享日志路径，再加上taskserver一起组成taskserver日志压缩文件目录
            //                string logsharedir = ConfigurationManager.AppSettings["LogShareDir"];
            //                //string machine_sharedir = ConfigurationManager.AppSettings["LogShareDir"] + "Machine\\" + macnumber + "\\";
            //                //if (!Directory.Exists(machine_sharedir))
            //                //{
            //                //    Directory.CreateDirectory(machine_sharedir);
            //                //}
            //                //压缩文件路径=日志压缩文件目录+压缩文件名
            //                string desdir;

            //                foreach (string dir in dirs)
            //                {
            //                    //if (-1 == dir.IndexOf(todayname))
            //                    if (dir.IndexOf(todayname) < 0)//&& dir.IndexOf(yesterdayname) < 0
            //                    {
            //                        dirname = dir.Substring(dir.LastIndexOf("\\") + 1);
            //                        desdir = Path.Combine(logsharedir, "Machine");//机器日志目录
            //                        desdir = Path.Combine(desdir, dirname);//日期
            //                        if (!Directory.Exists(desdir))
            //                        {
            //                            Directory.CreateDirectory(desdir);
            //                        }
            //                        string filename = string.Concat(macnumber, "_", dirname, "_", DateTime.Now.ToString("HHmmssfff"),".zip");
            //                        desdir = Path.Combine(desdir, filename);

            //                        //desdir = machine_sharedir + dirname + "_" + DateTime.Now.ToString("ssfff") + ".zip";
            //                        LoggingService.Info("【压缩日志文件】" + dir + " => " + desdir);
            //                        SharpZipUtil.ZipFile(dir, desdir);
            //                        LoggingService.Info("【压缩日志文件】成功！");
            //                        LoggingService.Info("【压缩日志文件】删除" + dir);
            //                        Directory.Delete(dir, true);
            //                        LoggingService.Info("【压缩日志文件】成功！");
            //                    }
            //                }
            //            }
            //        }
            //    }

            //    //压缩machine日志



            //    LoggingService.Info("【压缩日志文件】结束压缩...");

            //}
            //catch (Exception ex)
            //{
            //    LoggingService.Info("【压缩日志文件】异常：" + ex.Message + "\r\n" + ex.StackTrace);
            //}
        }

        void DefaultWorkbench_FormClosed(object sender, FormClosedEventArgs e)
        {
            
        }

        private void  DefaultWorkbench_FormClosing(object sender, FormClosingEventArgs e)
        {
            //timeSyncService.Stop();

            DateTime now =DateTime.Now.AddHours(-7);
            MachineReportTime reportTime = MachineReportTimeList.GetCurrentTime(3);
            if (reportTime.To.ToShortDateString() == now.ToShortDateString()) 
            {
                MessageBox.Show(string.Format("今天下班前需要上传 {0}({1:yyyyMMdd} - {2:yyyyMMdd}) 的月报", reportTime.DisplayMember, reportTime.From, reportTime.To));
            }
            reportTime = MachineReportTimeList.GetCurrentTime(2);
            if (reportTime.To.ToShortDateString() == now.ToShortDateString())
            {
                MessageBox.Show(string.Format("今天下班前需要上传 {0}({1:yyyyMMdd} - {2:yyyyMMdd}) 的周报", reportTime.DisplayMember, reportTime.From, reportTime.To));
            }
            reportTime = MachineReportTimeList.GetCurrentTime(1);
            MessageBox.Show(string.Format("今天下班前需要上传 {0}({1:yyyyMMdd} - {2:yyyyMMdd}) 的天报", reportTime.DisplayMember, reportTime.From, reportTime.To));

            if (DialogResult.OK != MessageBox.Show("下班前上传时段、缴款报表了么？确认关闭软件？", "上传报表提醒", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning))
            {
                e.Cancel = true;
                return;
            }


            LotMachineService.SaveLastPrintCounter();

            ExpectTaskService.Stop();

            foreach (AutoPrintView autoPrintView in this.tabPageAutoPrint.LotMachineViewList)
            {
                M_MachineEntity machineEntity = autoPrintView.Service.LotMachine.MachineInfo;
                if (machineEntity.M_Status != (int)MachineStatusEnum.Stopped)
                {
                    MessageService.ShowMessage(string.Concat("彩票机",machineEntity.M_Number,"不在停止状态，不得关闭软件！"));
                    e.Cancel = true;
                    return;
                }
                //autoPrintView.Checked();
                //autoPrintView.Stop();

                autoPrintView.StopWorkThread();
            }

            LogUIAppender.StopShowLog();

            
            foreach (ILotMachine lotmachine in LotMachineService.LotMachineList.Values)
            {
                //停止彩票机上虚拟设备
                lotmachine.StopDriver();

                //更改彩票机的状态
                lotmachine.MachineInfo.M_LoginStatus = 0;
                lotmachine.MachineInfo.M_Status = (int)MachineStatusEnum.Stopped;

            }
            int i = 0;
            while (i<2000)
            {
                Thread.Sleep(100);
                Application.DoEvents();
                i += 100;
            }
        }

        private TabControl tabControl;
        private AutoPrintTabPage tabPageAutoPrint;
        //private LogTabControl tabControlLog;
        
        private void Attach()
        {
            this.SuspendLayout();
            this.Controls.Clear();

            Panel panel = new Panel();
            panel.SuspendLayout();

            SplitContainer splitContainer = new SplitContainer();
            splitContainer.SuspendLayout();

            splitContainer.Height = this.Height;
            splitContainer.Dock = DockStyle.Fill;
            splitContainer.Orientation = Orientation.Horizontal;
            splitContainer.FixedPanel = FixedPanel.Panel2;
            //splitContainer.SplitterDistance = this.Height * 4 / 5;
            if(LotMachineService.LotMachineList.Count<=4)
            {
                splitContainer.SplitterDistance = this.Height * 2 / 3;
            }
            else
            {
                splitContainer.SplitterDistance = this.Height * 4 / 5;
            }
            //splitContainer.Panel1.BackColor = Color.Blue;
            //splitContainer.Panel2.BackColor = Color.Red;


            tabControl=new TabControl();
            tabControl.Dock = DockStyle.Fill;

            tabPageAutoPrint=new AutoPrintTabPage();   
            tabControl.TabPages.Add(tabPageAutoPrint);

            AutoEncashTabPage tabPageAutoEncash = new AutoEncashTabPage();
            tabControl.TabPages.Add(tabPageAutoEncash);

         

          

            //MachineConfigTabPage tabPageConfig=new MachineConfigTabPage();
            //tabControl.TabPages.Add(tabPageConfig);

            splitContainer.Panel1.Controls.Add(tabControl);

            /*tabControlLog=new LogTabControl();
            tabControlLog.Dock = DockStyle.Fill;
            LogUIAppender.RichTextBoxAlertLog = tabControlLog.richTextBoxAlertLogs;
            LogUIAppender.RichTextBoxLogs = new Dictionary<string, RichTextBox>();
            LogUIAppender.RichTextBoxLogs.Add("default", tabControlLog.richTextBoxSystemLogs);
            foreach (KeyValuePair<string, RichTextBox> keyValuePair in tabControlLog.richTextBoxMachineLogDictionary)
            {
                LogUIAppender.RichTextBoxLogs.Add(keyValuePair.Key,keyValuePair.Value);
            }
            LogUIAppender.ShowAlertLogEvent += new EventHandler(LogUIAppender_ShowAlertLogEvent);

            splitContainer.Panel2.Controls.Add(tabControlLog);*/
            LogOutputView logOutputView=new LogOutputView();
            //logOutputView.Dock = DockStyle.Fill;
            //splitContainer.Panel2.Dock = DockStyle.Fill;
            //logOutputView.Width = splitContainer.Panel2.Width;
            //logOutputView.Height = splitContainer.Panel2.Height;
            splitContainer.Panel2.Controls.Add(logOutputView);
            

            
            //panel.BackColor = System.Drawing.SystemColors.ActiveCaption;
            panel.Dock = DockStyle.Fill;
            panel.Controls.Add(splitContainer);

            this.Controls.Add(panel);

            StatusStrip statusStrip = (StatusStrip) StatusBarService.Control;
            this.Controls.Add(statusStrip);

            panel.ResumeLayout(false);
            splitContainer.ResumeLayout(false);

            this.ResumeLayout(false);
        }

        /*void LogUIAppender_ShowAlertLogEvent(object sender, EventArgs e)
        {
            try
            {
                //WorkbenchSingleton.SafeThreadCall(new Action(SetTab));
                WorkbenchSingleton.SafeThreadAsyncCall(new Action(SetTab));
                StatusBarService.ShowWarnButton();
            }
            catch (Exception exception)
            {
                LoggingService.Error(string.Concat("LogUIAppender_ShowAlertLogEvent异常。错误信息：", exception.Message));
            }
            
        }
        private void SetTab()
        {
            try
            {
                tabControlLog.SelectedTab = tabControlLog.tabPageAlertLogs;
            }
            catch (Exception exception)
            {
                LoggingService.Error(string.Concat("SetTab异常。错误信息：",exception.Message));
            }
            
            
        }*/
        
    }
}
