using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using ChuPiao.AutoPrint.Common;
using ChuPiao.AutoPrint.Desktop.Dialogs;
using ChuPiao.AutoPrint.Desktop.KeyBoard;
using ChuPiao.AutoPrint.Machine;
using ChuPiao.AutoPrint.Machine.Models;
using ChuPiao.AutoPrint.Services;
using ChuPiao.AutoPrint.Services.AutoPrint;
using ChuPiao.Common.Enums;
using ChuPiao.Common.Models;
using ChuPiao.Common.Utils;
using ChuPiao.Office.Services;
using ChuPiao.AutoPrint.Configuration;

namespace ChuPiao.AutoPrint.Desktop.AutoPrint
{
    public class AutoPrintTabPage : TabPage
    {
        private string _localConfig_SetNullPosition = "SetNullPosition";

        public AutoPrintToolStrip autoPrintToolStrip ;
        public AutoPrintTabPage()
        {
            this.Text = "半自动出票";
            this.Dock = DockStyle.Fill;

            ToolStripContainer toolStripContainer = new ToolStripContainer();
            toolStripContainer.Dock = DockStyle.Fill;

            autoPrintToolStrip = new AutoPrintToolStrip();
            autoPrintToolStrip.ToolStripButtonSelect.Click += new EventHandler(ToolStripButtonSelect_Click);
            autoPrintToolStrip.ToolStripButtonStart.Click += new EventHandler(ToolStripButtonStart_Click);
            autoPrintToolStrip.ToolStripButtonStop.Click += new EventHandler(ToolStripButtonStop_Click);
            autoPrintToolStrip.ToolStripButtonContinue.Click += new EventHandler(ToolStripButtonContinue_Click);
            autoPrintToolStrip.ToolStripButtonLimitError.Click += new EventHandler(ToolStripButtonLimitError_Click);
            autoPrintToolStrip.ToolStripButtonForceStop.Click += new EventHandler(ToolStripButtonForceStop_Click);
            autoPrintToolStrip.ToolStripButtonRestartDriver.Click += new EventHandler(ToolStripButtonRestartDriver_Click);
            autoPrintToolStrip.ToolStripButtonReGetdata.Click += new EventHandler(ToolStripButtonReGetdata_Click);
            autoPrintToolStrip.ToolStripButtonGetCacheTicket.Click += new EventHandler(ToolStripButtonGetCacheTicket_Click);
            autoPrintToolStrip.ToolStripButtonGetLastTicket.Click += new EventHandler(ToolStripButtonGetLastTicket_Click);
            autoPrintToolStrip.ToolStripButtonLogin.Click += new EventHandler(ToolStripButtonLogin_Click);
            //autoPrintToolStrip.ToolStripButtonEnterSaleGui.Click += new EventHandler(ToolStripButtonEnterSaleGui_Click);
            autoPrintToolStrip.ToolStripButtonEnterTopGui.Click += new EventHandler(ToolStripButtonEnterTopGui_Click);
            autoPrintToolStrip.ToolStripButtonTest.Click += new EventHandler(ToolStripButtonTest_Click);
            
            autoPrintToolStrip.ToolStripButtonClear.Click += new EventHandler(ToolStripButtonClear_Click);
           
            autoPrintToolStrip.ToolStripButtonUse.Click += new EventHandler(ToolStripButtonUse_Click);
            autoPrintToolStrip.ToolStripButtonAddMachine.Click += new EventHandler(ToolStripButtonAddMachine_Click);
            autoPrintToolStrip.ToolStripButtonDeleteMachine.Click += new EventHandler(ToolStripButtonDeleteMachine_Click);
            autoPrintToolStrip.ToolStripButtonEditComputer.Click += new EventHandler(ToolStripButtonEditComputer_Click);
            autoPrintToolStrip.ToolStripButtonReportKeyboard.Click += new EventHandler(ToolStripButtonReportKeyboard_Click);
            autoPrintToolStrip.ToolStripButtonSetKeyInterval.Click += new EventHandler(ToolStripButtonSetKeyInterval_Click);
            //autoPrintToolStrip.ToolStripButtonReloadConfig.Click += new EventHandler(ToolStripButtonReloadConfig_Click);
            //autoPrintToolStrip.ToolStripButtonTestChangePlay.Click += new EventHandler(ToolStripButtonTestChangePlay_Click);
            //autoPrintToolStrip.ToolStripButtonTestScanner.Click += new EventHandler(ToolStripButtonTestScanner_Click);
            //autoPrintToolStrip.ToolStripButtonImportConfig.Click += new EventHandler(ToolStripButtonImportConfig_Click);

            autoPrintToolStrip.ToolStripButtonPrintCurrentDayReport.Click += new EventHandler(ToolStripButtonPrintCurrentDayReport_Click);
            autoPrintToolStrip.ToolStripButtonUpdateMoney.Click += new EventHandler(ToolStripButtonUpdateMoney_Click);

            autoPrintToolStrip.toolStripComboBox_timetype.SelectedIndexChanged += new System.EventHandler(this.toolStripComboBox_timetype_SelectedIndexChanged);
            autoPrintToolStrip.toolStripComboBox_timeselect.SelectedIndexChanged += new System.EventHandler(this.toolStripComboBox_timeselect_SelectedIndexChanged);


            toolStripContainer.TopToolStripPanel.Controls.Add(autoPrintToolStrip);

            TableLayoutPanel tableLayoutPanel = new TableLayoutPanel();
            tableLayoutPanel.Dock = DockStyle.Fill;
            tableLayoutPanel.AutoScroll = true;
            tableLayoutPanel.AutoSize = true;
            tableLayoutPanel.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            tableLayoutPanel.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.OutsetDouble;

            if (LotMachineService.LotMachineList.Count <= 4)
            {
                tableLayoutPanel.ColumnCount = 2;
                tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
                tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
                tableLayoutPanel.RowCount = 2;
                tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
                tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
             
            }
            else if (LotMachineService.LotMachineList.Count <= 8)
            {
                tableLayoutPanel.ColumnCount = 4;
                tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
                tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
                tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
                tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
                tableLayoutPanel.RowCount = 2;
                tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
                tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            }
            else if (LotMachineService.LotMachineList.Count <= 12)
            {
                tableLayoutPanel.ColumnCount = 4;
                tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
                tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
                tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
                tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
                tableLayoutPanel.RowCount = 3;
                tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 30F));
                tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 30F));
                tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 30F));
            }
            else if (LotMachineService.LotMachineList.Count <= 16)
            {
                tableLayoutPanel.ColumnCount = 4;
                tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
                tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
                tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
                tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F));
                tableLayoutPanel.RowCount = 4;
                tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 25F));
                tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 25F));
                tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 25F));
                tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 25F));
            }
            else
            { 
                //超过16台暂时展示不了
            }

            //留空位置设置
            string setNullPosition = LocalConfigUtil.GetConfig(_localConfig_SetNullPosition);
            int position=0;
            if (setNullPosition != null && Int32.TryParse(setNullPosition, out position))
            {
                if (position > 0 && position <= LotMachineService.LotMachineList.Count && LotMachineService.LotMachineList.Count < tableLayoutPanel.ColumnCount * tableLayoutPanel.RowCount)
                {
                    int row = (position - 1) / tableLayoutPanel.ColumnCount;
                    int column = (position - 1) % tableLayoutPanel.ColumnCount;
                    tableLayoutPanel.Controls.Add(new Label(), column, row);
                }
            }

            AutoPrintServiceManager.ServiceList.Clear();
            foreach (KeyValuePair<string, ILotMachine> keyValuePair in LotMachineService.LotMachineList)
            {
                AutoPrintService service = new AutoPrintService();
                service.LotMachine = keyValuePair.Value;
                service.StatusChanged += new EventHandler<MachineStatusArgs>(service_StatusChanged);
                AutoPrintView view = new AutoPrintView();
                //view.LotMachine = keyValuePair.Value;
                view.Service = service;
                AutoPrintServiceManager.ServiceList.Add(keyValuePair.Key, service);
                view.CheckedChanged += new EventHandler(view_CheckedChanged);


                view.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
                tableLayoutPanel.Controls.Add(view);

                LotMachineViewList.Add(view);

                //机器默认为停止状态
                keyValuePair.Value.MachineInfo.M_Status = (int)MachineStatusEnum.Stopped;
               
            }

            toolStripContainer.ContentPanel.Controls.Add(tableLayoutPanel);
            //System.Windows.Forms.Panel panel1 = new System.Windows.Forms.Panel();
            //panel1.AutoScroll = true;
            //panel1.Dock = DockStyle.Fill;
            //panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            //panel1.Controls.Add(tableLayoutPanel);
            //toolStripContainer.ContentPanel.Controls.Add(panel1);

            Controls.Add(toolStripContainer);
            _safeInvoker = new UIThreadInvoker();

        }

        private int _selectedtimetype = 0;
        private string _selectedtimename = "";
        private void toolStripComboBox_timetype_SelectedIndexChanged(object sender, EventArgs e)
        {
            //autoPrintToolStrip.toolStripComboBox_timeselect.ComboBox.DataSource = null;
            autoPrintToolStrip.toolStripComboBox_timeselect.Items.Clear();

            string typestr = autoPrintToolStrip.toolStripComboBox_timetype.Text;

            if (typestr == "天")
            {
                _selectedtimetype = 1;
            }
            else if (typestr == "周")
            {
                _selectedtimetype = 2;
            }
            else if (typestr == "月")
            {
                _selectedtimetype = 3;
            }

            List<MachineReportTime> timelist = MachineReportTimeList.GetTimeList(_selectedtimetype);
            if (timelist.Count > 0)
            {
                
                foreach (MachineReportTime item in timelist)
                {
                    autoPrintToolStrip.toolStripComboBox_timeselect.Items.Add(item);
                }
                //居然有的机器绑定不了 2020.12.17
                //autoPrintToolStrip.toolStripComboBox_timeselect.ComboBox.DataSource = timelist;
                autoPrintToolStrip.toolStripComboBox_timeselect.ComboBox.DisplayMember = "DisplayMember";
                autoPrintToolStrip.toolStripComboBox_timeselect.ComboBox.SelectedIndex = 0;
            }
        }

        private void toolStripComboBox_timeselect_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (null != autoPrintToolStrip.toolStripComboBox_timeselect.ComboBox.SelectedItem)
            {
                MachineReportTime entity = autoPrintToolStrip.toolStripComboBox_timeselect.ComboBox.SelectedItem as MachineReportTime;
                _selectedtimename = entity.ValueMember;

                autoPrintToolStrip.toolStripTextBoxPlayBeginDate.DateTimePicker.Value = entity.From;
                autoPrintToolStrip.toolStripTextBoxPlayEndDate.DateTimePicker.Value = entity.To;
            }
        }

        void ToolStripButtonSetKeyInterval_Click(object sender, EventArgs e)
        {
            new DlgSetKeyInterval().ShowDialog();
        }

        void ToolStripButtonDeleteMachine_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK != MessageBox.Show("请确认要删除彩票机？", "确认", MessageBoxButtons.OKCancel))
            {
                return;
            }

            int selectedMachineNum = 0;
            foreach (AutoPrintView lotMachineView in LotMachineViewList)
            {
                if (lotMachineView.IsSelected)
                {
                    selectedMachineNum++;

                    AutoPrintServiceManager.MachineXmlEntityDic.Remove(lotMachineView.Service.LotMachine.MachineInfo.M_Number);
                    
                }
            }
            if (selectedMachineNum == 0)
            {
                MessageService.ShowMessage("请选择彩票机", "操作提示");
            }
            else
            {
                MachineXmlConfig.SaveMachineList(new List<MachineXmlEntity>(AutoPrintServiceManager.MachineXmlEntityDic.Values));
                MessageService.ShowMessage("删除彩票机信息成功，重启软件后生效。");
            }
        }


        void ToolStripButtonEditComputer_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    string address = NetHelper.GetPhysicalAddress();
            //    M_ComputerService computerservice = new M_ComputerService();
            //    M_ComputerEntity computer = computerservice.GetComputerByIdentifier(address);
            //    DlgComputerEdit dlgMachine = new DlgComputerEdit(computer);
            //    DialogResult dlgMachineResult = dlgMachine.ShowDialog();
            //}
            //catch (Exception exception)
            //{
            //    MessageService.ShowMessage(string.Concat("修改控制电脑异常。错误信息：", exception.Message));
            //}

            new DlgComputerEdit(AutoPrintServiceManager.Computer).ShowDialog();
            
        }

        void ToolStripButtonRestartDriver_Click(object sender, EventArgs e)
        {
            try
            {
                List<ILotMachine> lotMachines = new List<ILotMachine>();
                foreach (AutoPrintView lotMachineView in LotMachineViewList)
                {
                    if (lotMachineView.IsSelected && lotMachineView.Service.LotMachine.MachineInfo.M_Status == (int)MachineStatusEnum.Stopped)
                    {
                        ILotMachine lotMachine = lotMachineView.Service.LotMachine;
                        lotMachines.Add(lotMachine);
                    }
                }
                if (lotMachines.Count > 0)
                {
                    List<string > macnumbers=new List<string>();
                    foreach (ILotMachine lotMachine in lotMachines)
                    {
                        lotMachine.ReStartDriver();
                        macnumbers.Add(lotMachine.MachineInfo.M_Number);
                    }
                    string msg = string.Concat("重启驱动程序完成，机器号：", string.Join(",",macnumbers.ToArray()));
                    //MessageBox.Show(msg, "操作提示", MessageBoxButtons.OK);
                    MessageService.ShowMessage(msg,"操作提示");
                }
                else
                {
                    MessageBox.Show("请选择机器号，并确认是否处于停止出票状态！", "操作提示", MessageBoxButtons.OK);
                }
            }
            catch (Exception exception)
            {
                MessageService.ShowMessage(string.Concat("重启驱动程序异常。错误信息：", exception.Message));
            }
        }
        void ToolStripButtonReGetdata_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (AutoPrintView lotMachineView in LotMachineViewList)
                {
                    lotMachineView.ReGetdata();
                }
            }
            catch (Exception exception)
            {
                MessageService.ShowMessage(string.Concat("重新获取异常。错误信息：", exception.Message));
            }
        }
        void ToolStripButtonGetCacheTicket_Click(object sender, EventArgs e)
        {
            try
            {
                List<ILotMachine> lotMachines = new List<ILotMachine>();
                foreach (AutoPrintView lotMachineView in LotMachineViewList)
                {
                    if (lotMachineView.IsSelected && lotMachineView.Service.LotMachine.MachineInfo.M_Status == (int)MachineStatusEnum.Stopped)
                    {
                        ILotMachine lotMachine = lotMachineView.Service.LotMachine;
                        lotMachines.Add(lotMachine);
                    }
                }
                if (lotMachines.Count > 0)
                {
                    List<string> macnumbers = new List<string>();
                    foreach (ILotMachine lotMachine in lotMachines)
                    {
                        lotMachine.Log.Info("执行获取彩票机数据");
                        CaptureDataInfo dataInfo= lotMachine.GetCacheTicket();
                        if(dataInfo.CaptureDataBytes.Length>0)
                        {
                            LotMachineService.PrintETicket(lotMachine.MachineInfo.M_Number,dataInfo.CaptureDataBytes);
                        }
                        macnumbers.Add(lotMachine.MachineInfo.M_Number);
                    }
                    //string msg = string.Concat("重启驱动程序完成，机器号：", string.Join(",", macnumbers.ToArray()));
                    //MessageBox.Show(msg, "操作提示", MessageBoxButtons.OK);
                    //MessageService.ShowMessage(msg, "操作提示");
                }
                else
                {
                    MessageBox.Show("请选择机器号，并确认是否处于停止出票状态！", "操作提示", MessageBoxButtons.OK);
                }
            }
            catch (Exception exception)
            {
                MessageService.ShowMessage(string.Concat("获取彩票机数据异常。错误信息：", exception.Message));
            }
        }
        void ToolStripButtonGetLastTicket_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (AutoPrintView lotMachineView in LotMachineViewList)
                {
                    lotMachineView.GetAndPrintLastTicket();
                }
            }
            catch (Exception exception)
            {
                MessageService.ShowMessage(string.Concat("获取最后一张票异常。错误信息：", exception.Message));
            }
        }


       

        void ToolStripButtonEnterSaleGui_Click(object sender, EventArgs e)
        {
            int selectedMachineNum = 0;
            foreach (AutoPrintView lotMachineView in LotMachineViewList)
            {
                if (lotMachineView.IsSelected)
                {
                    selectedMachineNum++;
                    lotMachineView.Service.LotMachine.EnterSaleGui();
                }
            }
            if (selectedMachineNum == 0)
            {
                MessageService.ShowMessage("请选择机器号", "操作提示");
            }
        }
        void ToolStripButtonEnterTopGui_Click(object sender, EventArgs e)
        {
            int selectedMachineNum = 0;
            foreach (AutoPrintView lotMachineView in LotMachineViewList)
            {
                if (lotMachineView.IsSelected)
                {
                    selectedMachineNum++;
                    lotMachineView.ReturnTopGui();
                    //lotMachineView.Service.LotMachine.ReturnTopGui();
                }
            }
            if (selectedMachineNum == 0)
            {
                MessageService.ShowMessage("请选择机器号", "操作提示");
            }
        }

       

        

      

        void ToolStripButtonReloadConfig_Click(object sender, EventArgs e)
        {
            try
            {
                int selectedMachineNum = 0;
                List<string> selectedMachineList = new List<string>();
                foreach (AutoPrintView lotMachineView in LotMachineViewList)
                {
                    if (lotMachineView.IsSelected)
                    {
                        selectedMachineNum++;
                        selectedMachineList.Add(lotMachineView.Service.LotMachine.MachineInfo.M_Number);
                    }
                }
                if (selectedMachineNum == 0)
                {
                    MessageService.ShowMessage("请选择机器号", "操作提示");
                }
                List<string> sucMachineList = new List<string>();
                List<string> failMachineList = new List<string>();
                foreach (AutoPrintView lotMachineView in LotMachineViewList)
                {
                    if (lotMachineView.IsSelected)
                    {
                        selectedMachineNum++;
                        selectedMachineList.Add(lotMachineView.Service.LotMachine.MachineInfo.M_Number);
                        //重新加载配置
                        bool result= lotMachineView.Service.ReloadConfig();
                        if (result)
                        {
                            sucMachineList.Add(lotMachineView.Service.LotMachine.MachineInfo.M_Number);
                        }
                        else
                        {
                            failMachineList.Add(lotMachineView.Service.LotMachine.MachineInfo.M_Number);
                        }
                    }
                }
                StringBuilder msgBuilder = new StringBuilder();
                if (sucMachineList.Count > 0)
                {
                    msgBuilder.AppendFormat("{0}重新加载配置成功。", string.Join(",", sucMachineList.ToArray()));
                }
                if (failMachineList.Count > 0)
                {
                    msgBuilder.AppendFormat("{0}重新加载配置失败。", string.Join(",", failMachineList.ToArray()));
                }
                string msg = msgBuilder.ToString();
                if (!string.IsNullOrEmpty(msg))
                {
                    //LoggingService.Info(msg);
                    MessageService.ShowMessage(msg, "操作提示");
                }
            }
            catch (Exception exception)
            {
                MessageService.ShowMessage(string.Concat("重新加载配置异常。错误信息：", exception.Message));
            }
        }

        void ToolStripButtonReportKeyboard_Click(object sender, EventArgs e)
        {
            try
            {
                List<ILotMachine> lotMachines=new List<ILotMachine>();
                foreach (AutoPrintView lotMachineView in LotMachineViewList)
                {
                    if (lotMachineView.IsSelected && lotMachineView.Service.LotMachine.MachineInfo.M_Status==(int)MachineStatusEnum.Stopped)
                    {
                        lotMachines.Add(lotMachineView.Service.LotMachine);
                    }
                }
                if(lotMachines.Count>0)
                {
                    MachineKeyBoard reportKeyBoard = new MachineKeyBoard(lotMachines);
                    reportKeyBoard.Show();
                }
                else
                {
                    MessageBox.Show("请选择机器号，并确认是否处于停止出票状态！", "操作提示", MessageBoxButtons.OK);
                }
                
            }
            catch (Exception exception)
            {
                MessageService.ShowMessage(string.Concat("报表键盘异常。错误信息：",exception.Message));
            }
        }

        void ToolStripButtonAddMachine_Click(object sender, EventArgs e)
        {
            try
            {
                string address = NetHelper.GetPhysicalAddress();
                
                DlgMachine dlgMachine = new DlgMachine();
                DialogResult dlgMachineResult = dlgMachine.ShowDialog();
            }
            catch (Exception exception)
            {
                MessageService.ShowMessage(string.Concat("新增机器异常。错误信息：",exception.Message));
            }
        }

        

        void ToolStripButtonUse_Click(object sender, EventArgs e)
        {
            int selectedMachineNum = 0;
            List<string> selectedMachineList = new List<string>();
            foreach (AutoPrintView lotMachineView in LotMachineViewList)
            {
                if (lotMachineView.IsSelected)
                {
                    selectedMachineNum++;
                    selectedMachineList.Add(lotMachineView.Service.LotMachine.MachineInfo.M_Number);
                }
            }
            if (selectedMachineNum == 0)
            {
                MessageService.ShowMessage("请选择机器号", "操作提示");
            }
            List<string> sucMachineList = new List<string>();
            List<string> failMachineList = new List<string>();
            foreach (AutoPrintView lotMachineView in LotMachineViewList)
            {
                if (lotMachineView.IsSelected)
                {
                    selectedMachineNum++;
                    selectedMachineList.Add(lotMachineView.Service.LotMachine.MachineInfo.M_Number);
                    //禁用机器
                    bool result = lotMachineView.Service.UseMachine();
                    if (result)
                    {
                        sucMachineList.Add(lotMachineView.Service.LotMachine.MachineInfo.M_Number);
                    }
                    else
                    {
                        failMachineList.Add(lotMachineView.Service.LotMachine.MachineInfo.M_Number);
                    }
                }
            }
            StringBuilder msgBuilder = new StringBuilder();
            if (sucMachineList.Count > 0)
            {
                msgBuilder.AppendFormat("启用机器{0}成功。", string.Join(",", sucMachineList.ToArray()));
            }
            if (failMachineList.Count > 0)
            {
                msgBuilder.AppendFormat("启用机器{0}失败。", string.Join(",", failMachineList.ToArray()));
            }
            string msg = msgBuilder.ToString();
            if (!string.IsNullOrEmpty(msg))
            {
                //LoggingService.Info(msg);
                MessageService.ShowMessage(msg, "操作提示");
            }
        }

       

        void ToolStripButtonClear_Click(object sender, EventArgs e)
        {
            try
            {
                int selectedMachineNum = 0;
                foreach (AutoPrintView lotMachineView in LotMachineViewList)
                {
                    if (lotMachineView.IsSelected)
                    {
                        selectedMachineNum++;
                        lotMachineView.Clear();
                    }
                }
                if (selectedMachineNum == 0)
                {
                    MessageService.ShowMessage("请选择机器号", "操作提示");
                }
            }
            catch (Exception ex)
            {
                LoggingService.Error(string.Concat("清除合计异常。",ex));
            }
            
        }

        void ToolStripButtonPrintCurrentDayReport_Click(object sender, EventArgs e)
        {
            MachineReportTime entity = autoPrintToolStrip.toolStripComboBox_timeselect.ComboBox.SelectedItem as MachineReportTime;
            if (DialogResult.OK != MessageBox.Show(string.Format("将上传 {0}({1:yyyyMMdd} - {2:yyyyMMdd}) 的 {3} 时段报表", entity.DisplayMember, entity.From, entity.To, autoPrintToolStrip.toolStripComboBox_timetype.Text), "确认", MessageBoxButtons.OKCancel))
            {
                return;
            }

            try
            {
                int selectedMachineNum = 0;
                foreach (AutoPrintView lotMachineView in LotMachineViewList)
                {
                    if (lotMachineView.IsSelected)
                    {
                        selectedMachineNum++;
                        lotMachineView.PrintDayReport(_selectedtimetype,_selectedtimename, autoPrintToolStrip.toolStripTextBoxPlayBeginDate.DateTimePicker.Value, autoPrintToolStrip.toolStripTextBoxPlayEndDate.DateTimePicker.Value);
                    }
                }
                if (selectedMachineNum == 0)
                {
                    MessageService.ShowMessage("请选择机器号", "操作提示");
                    return;
                }
            }
            catch (Exception ex)
            {
                LoggingService.Error(string.Concat("上传天报表异常。", ex));
            }
            
        }

        void ToolStripButtonUpdateMoney_Click(object sender, EventArgs e)
        {

            try
            {
                int selectedMachineNum = 0;
                foreach (AutoPrintView lotMachineView in LotMachineViewList)
                {
                    if (lotMachineView.IsSelected)
                    {
                        selectedMachineNum++;
                        lotMachineView.UpdateMoney();
                    }
                }
                if (selectedMachineNum == 0)
                {
                    MessageService.ShowMessage("请选择机器号", "操作提示");
                    return;
                }
            }
            catch (Exception ex)
            {
                LoggingService.Error(string.Concat("上传缴款报表异常。", ex));
            }

        }
        

        void ToolStripButtonTest_Click(object sender, EventArgs e)
        {
            try
            {
                int selectedMachineNum = 0;
                foreach (AutoPrintView lotMachineView in LotMachineViewList)
                {
                    if (lotMachineView.IsSelected)
                    {
                        selectedMachineNum++;
                        lotMachineView.Test();
                    }
                }
                if (selectedMachineNum == 0)
                {
                    MessageService.ShowMessage("请选择机器号", "操作提示");
                }
            }
            catch (Exception ex)
            {
                LoggingService.Error(string.Concat("打印测试票异常。", ex));
            }
            
        }

        void ToolStripButtonLogin_Click(object sender, EventArgs e)
        {
            try
            {
                int selectedMachineNum = 0;
                foreach (AutoPrintView lotMachineView in LotMachineViewList)
                {
                    if (lotMachineView.IsSelected)
                    {
                        selectedMachineNum++;
                        lotMachineView.Login();
                    }
                }
                if (selectedMachineNum == 0)
                {
                    MessageService.ShowMessage("请选择机器号", "操作提示");
                }
            }
            catch (Exception ex)
            {
                LoggingService.Error(string.Concat("登录异常。", ex));
            }
            
        }

        void view_CheckedChanged(object sender, EventArgs e)
        {
            UpdateToolBarStatus();
        }

        void service_StatusChanged(object sender, MachineStatusArgs e)
        {
            LoggingService.Debug(string.Concat("更新工具栏界面",e.MachineStatus));
            //WorkbenchSingleton.SafeThreadCall(new Action(UpdateToolBarStatus));
            WorkbenchSingleton.SafeThreadAsyncCall(new Action(UpdateToolBarStatus));

            //_safeInvoker.SafeInvoke(new Action(UpdateToolBarStatus), null);

            //UpdateToolBarStatus();
        }
        private ISafeInvoker _safeInvoker;
        //private readonly object lockobj=new object();
        private void UpdateToolBarStatus()
        {
            try
            {
                //lock (lockobj)
                //{
                //}
                    bool hasSelected = false;
                    bool isEnabledStart = false;
                    bool isEnabledStop = false;
                bool isEnabledContinue = false;
                    foreach (AutoPrintView lotMachineView in LotMachineViewList)
                    {
                        if (lotMachineView.IsSelected)
                        {
                            hasSelected = true;
                            MachineStatusEnum status =
                                (MachineStatusEnum)lotMachineView.Service.LotMachine.MachineInfo.M_Status;
                            switch (status)
                            {
                                case MachineStatusEnum.Stopping:
                                    isEnabledStart = false;
                                    isEnabledStop = false;
                                    break;
                                case MachineStatusEnum.Stopped:
                                    isEnabledStart = true;
                                    break;
                                case MachineStatusEnum.Printing:
                                    isEnabledStop = true;
                                    break;
                                case MachineStatusEnum.Error:
                                    isEnabledContinue = true;
                                    break;
                            }
                        }
                    }
                    if (!hasSelected)
                    {
                        autoPrintToolStrip.ToolStripButtonStart.Enabled = false;
                        autoPrintToolStrip.ToolStripButtonStop.Enabled = false;
                        autoPrintToolStrip.ToolStripButtonContinue.Enabled = false;
                        autoPrintToolStrip.ToolStripButtonLimitError.Enabled = false;

                        autoPrintToolStrip.ToolStripButtonClear.Enabled = false;
                        autoPrintToolStrip.ToolStripButtonLogin.Enabled = false;
                        autoPrintToolStrip.ToolStripButtonTest.Enabled = false;
                        autoPrintToolStrip.ToolStripButtonUpdateMoney.Enabled = false;
                        autoPrintToolStrip.ToolStripButtonEnterTopGui.Enabled = false;
                        autoPrintToolStrip.ToolStripButtonForbid.Enabled = false;
                        autoPrintToolStrip.ToolStripButtonUse.Enabled = false;
                        autoPrintToolStrip.ToolStripButtonGetCacheTicket.Enabled = false;
                        autoPrintToolStrip.ToolStripButtonPrintCurrentDayReport.Enabled = false;
                        autoPrintToolStrip.ToolStripButtonRestartDriver.Enabled = false;
                        autoPrintToolStrip.ToolStripButtonTransfer.Enabled = false;
                        //autoPrintToolStrip.ToolStripButtonTestScanner.Enabled = false;
                        autoPrintToolStrip.ToolStripButtonGetLastTicket.Enabled = false;
                        autoPrintToolStrip.ToolStripButtonReGetdata.Enabled = false;
                    }
                    else
                    {
                        autoPrintToolStrip.ToolStripButtonStart.Enabled = isEnabledStart;
                        autoPrintToolStrip.ToolStripButtonStop.Enabled = isEnabledStop;
                        autoPrintToolStrip.ToolStripButtonContinue.Enabled = isEnabledContinue;
                        autoPrintToolStrip.ToolStripButtonLimitError.Enabled = isEnabledContinue;

                        autoPrintToolStrip.ToolStripButtonClear.Enabled = true;
                        autoPrintToolStrip.ToolStripButtonLogin.Enabled = true;
                        autoPrintToolStrip.ToolStripButtonTest.Enabled = true;
                        autoPrintToolStrip.ToolStripButtonUpdateMoney.Enabled = true;
                        autoPrintToolStrip.ToolStripButtonEnterTopGui.Enabled = true;
                        autoPrintToolStrip.ToolStripButtonForbid.Enabled = true;
                        autoPrintToolStrip.ToolStripButtonUse.Enabled = true;
                        autoPrintToolStrip.ToolStripButtonGetCacheTicket.Enabled = true;
                        autoPrintToolStrip.ToolStripButtonPrintCurrentDayReport.Enabled = true;
                        autoPrintToolStrip.ToolStripButtonRestartDriver.Enabled = true;
                        autoPrintToolStrip.ToolStripButtonTransfer.Enabled = true;
                        //autoPrintToolStrip.ToolStripButtonTestScanner.Enabled = true;
                        autoPrintToolStrip.ToolStripButtonGetLastTicket.Enabled = true;
                        autoPrintToolStrip.ToolStripButtonReGetdata.Enabled = true;
                    }
                
            }
            catch (Exception exception)
            {
                LoggingService.Debug(string.Concat("更新工具栏界面异常。错误信息：", exception.Message));
            }
        }
        private void UpdateToolBarStatus2()
        {
            try
            {

                bool hasSelected = false;
                bool isEnabledStart = false;
                bool isEnabledStop = false;
                foreach (AutoPrintView lotMachineView in LotMachineViewList)
                {
                    if (lotMachineView.IsSelected)
                    {
                        hasSelected = true;
                        MachineStatusEnum status =
                            (MachineStatusEnum)lotMachineView.Service.LotMachine.MachineInfo.M_Status;
                        switch (status)
                        {
                            case MachineStatusEnum.Stopping:
                                isEnabledStart = false;
                                isEnabledStop = false;
                                break;
                            case MachineStatusEnum.Stopped:
                                isEnabledStart = true;
                                break;
                            case MachineStatusEnum.Printing:
                                isEnabledStop = true;
                                break;
                        }
                    }
                }
                if (!hasSelected)
                {
                    autoPrintToolStrip.ToolStripButtonStart.Enabled = false;
                    autoPrintToolStrip.ToolStripButtonStop.Enabled = false;
                    autoPrintToolStrip.ToolStripButtonClear.Enabled = false;
                    autoPrintToolStrip.ToolStripButtonLogin.Enabled = false;
                    autoPrintToolStrip.ToolStripButtonTest.Enabled = false;
                    autoPrintToolStrip.ToolStripButtonUpdateMoney.Enabled = false;
                }
                else
                {
                    autoPrintToolStrip.ToolStripButtonClear.Enabled = true;
                    autoPrintToolStrip.ToolStripButtonLogin.Enabled = true;
                    autoPrintToolStrip.ToolStripButtonTest.Enabled = true;
                    autoPrintToolStrip.ToolStripButtonUpdateMoney.Enabled = true;

                    autoPrintToolStrip.ToolStripButtonStart.Enabled = isEnabledStart;
                    autoPrintToolStrip.ToolStripButtonStop.Enabled = isEnabledStop;
                }
            }
            catch (Exception exception)
            {
                LoggingService.Debug(string.Concat("更新工具栏界面异常。错误信息：", exception.Message));
            }
        }

        //public void SetControlEnable(Control control, bool state)
        //{
        //    if (control.InvokeRequired) //在辅助线程内
        //    {
        //        Action<Control, bool> action = new Action<Control, bool>(SetControlEnable);
        //        action.Invoke(control, state);
        //    }
        //    else
        //    {
        //        control.Enabled = state;
        //    }
        //}

        /// <summary>
        /// 停止出票
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ToolStripButtonStop_Click(object sender, EventArgs e)
        {
            int selectedMachineNum = 0;
            foreach (AutoPrintView lotMachineView in LotMachineViewList)
            {
                if (lotMachineView.IsSelected)
                {
                    selectedMachineNum++;
                    lotMachineView.Stop();
                }
            }

            if (selectedMachineNum == 0)
            {
                MessageService.ShowMessage("请选择机器号", "操作提示");
            }
        }
        /// <summary>
        /// 继续出票
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ToolStripButtonContinue_Click(object sender, EventArgs e)
        {
            int selectedMachineNum = 0;
            foreach (AutoPrintView lotMachineView in LotMachineViewList)
            {
                if (lotMachineView.IsSelected)
                {
                    selectedMachineNum++;
                    lotMachineView.Continue();
                }
            }

            if (selectedMachineNum == 0)
            {
                MessageService.ShowMessage("请选择机器号", "操作提示");
            }
        }

        void ToolStripButtonLimitError_Click(object sender, EventArgs e)
        {
            int selectedMachineNum = 0;
            foreach (AutoPrintView lotMachineView in LotMachineViewList)
            {
                if (lotMachineView.IsSelected)
                {
                    selectedMachineNum++;
                    lotMachineView.ClearLimitError();
                }
            }

            if (selectedMachineNum == 0)
            {
                MessageService.ShowMessage("请选择机器号", "操作提示");
            }
        }

        /// <summary>
        /// 强行停止当前票
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ToolStripButtonForceStop_Click(object sender, EventArgs e)
        {
            try
            {
                List<string> selectedMachineList=new List<string>();
                foreach (AutoPrintView lotMachineView in LotMachineViewList)
                {
                    if (lotMachineView.IsSelected)
                    {
                        selectedMachineList.Add(lotMachineView.Service.LotMachine.MachineInfo.M_Number);
                    }
                }

                if (selectedMachineList.Count == 0)
                {
                    MessageService.ShowMessage("请选择机器号", "操作提示");
                    return;
                }
                DialogResult dialogResult = MessageBox.Show(WorkbenchSingleton.MainForm,
                                                            string.Concat("你确定要强行停止",
                                                                          string.Join(",", selectedMachineList.ToArray()),
                                                                          "的当前票吗"), "操作提示", MessageBoxButtons.YesNo,
                                                            MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                if(dialogResult==DialogResult.Yes)
                {
                    foreach (AutoPrintView lotMachineView in LotMachineViewList)
                    {
                        if (lotMachineView.IsSelected)
                        {
                            lotMachineView.ForceStop();
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                MessageService.ShowMessage(string.Concat("强行停止当前票异常。错误信息：",exception.Message), "操作提示");
            }
            
        }
        /// <summary>
        /// 启动出票
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ToolStripButtonStart_Click(object sender, EventArgs e)
        {
            if (!AutoPrintService.isCOMOK)
            {
                MessageService.ShowMessage("COM口异常，不能开启出票!!!请尝试重启软件、电脑", "操作提示");
                return;
            }

            int selectedMachineNum = 0;
            foreach (AutoPrintView lotMachineView in LotMachineViewList)
            {
                if(lotMachineView.IsSelected)
                {
                    selectedMachineNum++;
                    lotMachineView.Start();
                }
            }
            if(selectedMachineNum==0)
            {
                MessageService.ShowMessage("请选择机器号","操作提示");
            }
        }
        /// <summary>
        /// 反选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ToolStripButtonSelect_Click(object sender, EventArgs e)
        {
            foreach (AutoPrintView lotMachineView in LotMachineViewList)
            {
                lotMachineView.ReverseSelect();
            }
        }

        public List<AutoPrintView> LotMachineViewList=new List<AutoPrintView>();



    }
}
