using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using WcfControlMonitorLib;
using CommonLib;
using System.Globalization;
using System.Security.Cryptography;//20151019richard
using Microsoft.Win32;//20110602
using System.Diagnostics;//20110602
using System.IO;//20110602
namespace wcfControlMonitorClient
{
    public partial class FrmHost : Form
    {
        Model.MonitorInfo mi;//20140824richard
        //20130122
        private static FrmHost _formInstance;
        //20130122
        public static FrmHost FormInstance
        {
            get
            {
                if (_formInstance == null)
                {
                    _formInstance = new FrmHost();
                }
                return _formInstance;
            }
            set { _formInstance = value; }
        }
        int timersum = 0;//20120513
        int timerefesh = 0;//20150103增加断网恢复
        DBFactory.DBOperator dbo  ; 
        /// <summary>
        /// 
        /// </summary>
        public FrmHost()
        {
            try
            {
                dbo = CStaticClass.dbo;
                InitializeComponent();

                CommonClassLib.LocalisationHelper lh = new CommonClassLib.LocalisationHelper();
                lh.ApplyResource(this);//20131220
                lh.ApplyResource(this.contextMenuStrip1);//20131220
                CStaticClass.SystemName = CommonClassLib.AppSettings.GetValue("SystemName");
                this.notifyIcon1.Text = CStaticClass.SystemName;
                this.Text = CStaticClass.SystemName;
                _host = new ServiceHost(typeof(WcfControlMonitorLib.SControlMonitor));
                _host.Open();
                //Silverlight跨域访问服务
                //policyHost = ClientCrossDomainAccessPolicy.GetHost(_host.BaseAddresses[0].Host);
                //policyHost.Open();
                SControlMonitor.ChannelOpen += new ClientLogEventHandler(SControlMonitor_ChannelOpen);
                SControlMonitor.ClientLogout += new ClientLogEventHandler(SControlMonitor_ClientLogout);
                SControlMonitor.RefreshMonitor += new RefreshMonitorEventHandler(SControlMonitor_RefreshMonitor);
                SControlMonitor.PLCCommonUpdateDB += new CUpdateDBEventHandler(SControlMonitor_PLCCommonUpdateDB);//PLC//20121108
                SControlMonitor.AGVUpdateDB += new CUpdateDBEventHandler(SControlMonitor_AGVUpdateDB);//AGV//20121108
                SControlMonitor.SendBarcode += new CStringInfoEventHandler(SControlMonitor_SendBarcode);
                SControlMonitor.WriteDarkCasket += new CWriteDarkCasketEventHandler(SControlMonitor_WriteDarkCasket);//20121108
                SControlMonitor.SendDeviceOrder += new CSendDeviceOrderEventHandler(SControlMonitor_SendDeviceOrder); ;//20121108
                CommonClassLib.CCarryConvert.WriteDarkCasket("Login", "打开调度系统服务端", "", "", "");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.InnerException, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
        }

        void SControlMonitor_AGVUpdateDB(object sender, CUpdateDBChangeEventArgs e)
        {//20120616
            this.BeginInvoke(new MethodInvoker(delegate()
            { CStaticClass.WcfControl.DealWithListenAGVState_UpdateDB(sender,e); }));
            
        }

        void SControlMonitor_PLCCommonUpdateDB(object sender, CUpdateDBChangeEventArgs e)
        {
            
            string errtext=string.Empty;
            this.BeginInvoke(new MethodInvoker(delegate()
                        {CStaticClass.WcfControl.DealWithDeviceState(out errtext, e.Deviceindex, e.SplitbyteValue, e.Devicestates);}));
            
        }
        void SControlMonitor_SendBarcode(object sender, CStringInfoEventArgs e)
        {
            string errtext = string.Empty;
            this.BeginInvoke(new MethodInvoker(delegate()
            { 
                CStaticClass.WcfControl.WriteDBData(e.Deviceindex,"DB1",e.Barcode+","+e.Confirm.ToString(),out errtext);
                dbo.ExceSQL(string.Format(" update T_Base_PLC_Ask set F_TaskIndex={0} WHERE (F_DeviceIndex = {1})", e.Deviceindex,Convert.ToInt32(sender)));
            }));
            
        }
        void SControlMonitor_SendDeviceOrder(object sender, CSendDeviceOrderEventArgs e)
        {//20121108
            this.BeginInvoke(new MethodInvoker(delegate()
            { CStaticClass.WcfControl.DealWithSendDeviceOrder(sender, e); }));
        }
        void SControlMonitor_WriteDarkCasket(object sender, CWriteDarkCasketEventArgs e)
        {//20121108
            this.BeginInvoke(new MethodInvoker(delegate()
            { CStaticClass.WcfControl.DealWithWriteDarkCasket(sender, e); }));
        }

        void SControlMonitor_CDeviceState(object sender, CDeviceStateChangeEventArgs e)
        {
            try
            {
                SendDeviceInfosToClient(e.Devinfo);
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf("SControlMonitor_CDeviceState:" + ex.StackTrace + ex.Message) < 0)
                {
                    tsStatus.Text += "SControlMonitor_CDeviceState:" + ex.StackTrace + ex.Message;
                }
            }
        }

        void SControlMonitor_RefreshMonitor(RefreshMonitorEventArgs e)
        {
            try
            {
                this.BeginInvoke(new MethodInvoker(delegate()
                {
                    SendMessageToClient(e.RefreshObjectName + "@" + e.RefreshObjectInfo);
                }));
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf("SControlMonitor_RefreshMonitor:" + ex.StackTrace + ex.Message) < 0)
                {
                    tsStatus.Text += "SControlMonitor_RefreshMonitor:" + ex.StackTrace + ex.Message;
                }
            }
        }

        void SControlMonitor_DataChange(object sender, CDataChangeEventArgs e)
        {
            try
            {
                SendMessageToClient(sender.ToString());
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf("SControlMonitor_DataChange:" + ex.StackTrace + ex.Message) < 0)
                {
                    tsStatus.Text += "SControlMonitor_DataChange:" + ex.StackTrace + ex.Message;
                }
            }
        }

        void SControlMonitor_ClientLogout(ClientLogEventArgs e)
        {
            try
            {
                AddList1Info(e.clientInfo);//20120503
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf("SControlMonitor_ClientLogout:" + ex.StackTrace + ex.Message) < 0)
                {
                    tsStatus.Text += "SControlMonitor_ClientLogout:" + ex.StackTrace + ex.Message;
                }
            }
        }

        void SControlMonitor_ChannelOpen(ClientLogEventArgs e)
        {
            try
            {
                AddList1Info(e.clientInfo);//20120503
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf("SControlMonitor_ChannelOpen:" + ex.StackTrace + ex.Message) < 0)
                {
                    tsStatus.Text += "SControlMonitor_ChannelOpen:" + ex.StackTrace + ex.Message;
                }
            }
        }
        private ServiceHost _host = null;
        private ServiceHost policyHost = null;
        private void FrmHost_Load(object sender, EventArgs e)
        {

            MITurnOn_Click(sender, e);
            MIStartRetrieveTask_Click(sender, e);

        }



        private void MIDataClear_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确认清空调度系统的调度队列和设备指令队列数据吗?这个操作将导致调度系统丢失当前记录的所有数据,并且使系统恢复到初始状态!", "操作提示:", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                return;
            }
            string errtext=string.Empty;
            if (CStaticClass.WcfControl.DataClear(out errtext) == false)
            {
                MessageBox.Show(errtext, "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

        }
       
        void SendMessageToClient(string strmessage)
        {
            
            IClient cl=null;
            try
            {
                if(AddList1Info(strmessage)==false)return ;//20130510
                var list = WcfControlMonitorLib.SControlMonitor.ClientCallbackLists;
                if (list == null || list.Count == 0)
                {
                    return;
                }
                
                lock (list)
                {
                    foreach (System.Collections.DictionaryEntry client in list)
                    {
                        // Broadcast
                        cl = (IClient)client.Key;
                        //string aa = client.Value.ToString();
                        //this.BeginInvoke(new MethodInvoker(delegate()
                        //{
                        //20140824richard
                        if (strmessage == "巡检客户端")
                        {
                            cl.BeginSendOrderMessage(mi, new AsyncCallback(SendOrderMessageCallback), mi);
                        }
                        else
                        {
                            cl.BeginSendMessage(strmessage, new AsyncCallback(sendMessageCallback), strmessage);

                        }
                        //20140824richard
                        //}));

                    }

                }
            }
            catch (Exception ex)
            {
                if (cl != null)
                {
                    WcfControlMonitorLib.SControlMonitor.ClientCallbackLists.Remove(cl);
                    WcfControlMonitorLib.SControlMonitor.ClientShowLists.Remove(cl);
                }
                AddList1Info(string.Format("SendMessageToClient时异常:{0}", ex.Message));//20120503
                //if (listBox1.Items.Count >= 100) listBox1.Items.Clear();
                //this.listBox1.Items.Add(string.Format("SendMessageToClient时异常:{0},{1}" , ex.Message,DateTime.Now.ToString("u")));
            }
        }
        void SendOrderMessageCallback(IAsyncResult ar)
        {

        }
        void sendMessageCallback(IAsyncResult ar)
        {
            try
            {
                this.BeginInvoke(new MethodInvoker(delegate()
                {

                    string sem = (string)ar.AsyncState;
                    AddList1Info(sem);//20120503
                    //if (listBox1.Items.Count >= 100) listBox1.Items.Clear();
                    //if (listBox1.Items.Count >= 1) 
                    //{
                    //    if (this.listBox1.Items[listBox1.Items.Count - 1].ToString().IndexOf(sem) >= 0) return;
                    //}
                    //if (sem == "巡检客户端") return;
                    //listBox1.Items.Add(DateTime.Now.ToLongTimeString()+sem);

                }));
            }
            catch (Exception ex)
            {
                this.BeginInvoke(new MethodInvoker(delegate()
                {
                    if (tsStatus.Text.IndexOf("巡检客户端sendMessageCallback:" + ex.StackTrace + ex.Message) < 0)
                    {
                        tsStatus.Text += "巡检客户端sendMessageCallback:" + ex.StackTrace + ex.Message;
                    }
                }));
            }
        }
        void SendDeviceInfosToClient(Model.MDevice devinfo)
        {
            IClient cl = null;
            try
            {
                var list = WcfControlMonitorLib.SControlMonitor.ClientCallbackLists;
                if (list == null || list.Count == 0)
                    return;
                lock (list)
                {
                    foreach (System.Collections.DictionaryEntry client in list)
                    {
                        // Broadcast
                        cl = (IClient)client.Key;
                        cl.BeginSendDeviceInfo(devinfo, new AsyncCallback(sendDeviceInfosCallback), null);

                    }

                }
            }
            catch (Exception ex)
            {
                if (cl != null)
                {
                    WcfControlMonitorLib.SControlMonitor.ClientCallbackLists.Remove(cl);
                    WcfControlMonitorLib.SControlMonitor.ClientShowLists.Remove(cl);
                }
                AddList1Info(string.Format("SendDeviceInfosToClient时异常:{0}", ex.Message));//20120503
                //if (listBox1.Items.Count >= 100) listBox1.Items.Clear();
                //this.listBox1.Items.Add(string.Format("SendDeviceInfosToClient时异常:{0},{1}" , ex.Message , DateTime.Now.ToString("u")));
            }
        }

        void sendDeviceInfosCallback(IAsyncResult ar)
        {
            
        }
        private void FrmHost_FormClosing(object sender, FormClosingEventArgs e)
        {
            //if (MessageBox.Show("您确认要关闭"+CStaticClass.SystemName+"吗?", "操作提示:", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
            //{
            //    e.Cancel = true;
            //    return;
            //}
            if (_host != null)
            {
                SControlMonitor.ChannelOpen -= new ClientLogEventHandler(SControlMonitor_ChannelOpen);
                SControlMonitor.ClientLogout -= new ClientLogEventHandler(SControlMonitor_ClientLogout);
                SControlMonitor.DataChange -= new CDataSourceChangeEventHandler(SControlMonitor_DataChange);
                SControlMonitor.RefreshMonitor -= new RefreshMonitorEventHandler(SControlMonitor_RefreshMonitor);
                SControlMonitor.CDeviceState -= new CDeviceStateChangeEventHandler(SControlMonitor_CDeviceState);
                SControlMonitor.PLCCommonUpdateDB -= new CUpdateDBEventHandler(SControlMonitor_PLCCommonUpdateDB);
                SControlMonitor.SendBarcode -= new CStringInfoEventHandler(SControlMonitor_SendBarcode);
                #region  zcy 20210418
                SControlMonitor.AGVUpdateDB -= new CUpdateDBEventHandler(SControlMonitor_AGVUpdateDB);//AGV//20121108
                SControlMonitor.SendBarcode -= new CStringInfoEventHandler(SControlMonitor_SendBarcode);
                SControlMonitor.WriteDarkCasket -= new CWriteDarkCasketEventHandler(SControlMonitor_WriteDarkCasket);//20121108
                SControlMonitor.SendDeviceOrder -= new CSendDeviceOrderEventHandler(SControlMonitor_SendDeviceOrder); ;//20121108
                #endregion
                
                _host.Close();
                IDisposable host = _host as IDisposable;
                host.Dispose();
            }
            CommonClassLib.AppSettings.dbo.Close();
            CommonClassLib.AppSettings.dboM.Close();
            CommonClassLib.CCarryConvert.WriteDarkCasket("Login", "退出调度系统服务端", "", "", "");
        }

        private void MIStartRetrieveTask_Click(object sender, EventArgs e)
        {
            if (MITurnOn.Checked == true)
            {
                this.Text = CStaticClass.SystemName + "【开始获取任务!】" + "【正在执行自动命令!】";//20120510
            }
            else
            {
                this.Text = CStaticClass.SystemName + "【开始获取任务!】";//20120510
            }
            CStaticClass.WcfControl.ObtainTask("", "UPDATE");
            MIStopRetrieveTask.Enabled = true;
            //CStaticClass.ObtainManageTask = true;
            MIStartRetrieveTask.Checked = true;
            MIStopRetrieveTask.Checked = false;
        }

        private void MIStopRetrieveTask_Click(object sender, EventArgs e)
        {
            if (MITurnOn.Checked == true)
            {
                this.Text = CStaticClass.SystemName + "【正在执行自动命令!】";//20120510
            }
            else
            {
                this.Text = CStaticClass.SystemName;//20120510
            }
            CStaticClass.WcfControl.StopObtainTask();
            //CStaticClass.ObtainManageTask = false;
            //20120510CStaticClass.WcfControl.StopObtainTask();
            ToolStripMenuItem tsm;
            for (int i = 0; i < MIStartRetrieveTask.DropDown.Items.Count; i++)
            {
                tsm = (ToolStripMenuItem)MIStartRetrieveTask.DropDown.Items[i];
                tsm.Checked = false;
            }
            MIStartRetrieveTask.Checked = false;
            MIStartRetrieveTask.Enabled = true;
            
            MIStopRetrieveTask.Enabled = false;
            MIStopRetrieveTask.Checked = true;
        }
        void ToolStripMenu_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem tsm; bool ifget = false;

            DataView dv;
            char[] cc = new char[1] { ':' };
            int laneway = 0; StringBuilder minz = new StringBuilder(); StringBuilder maxz = new StringBuilder();
            StringBuilder wherez = new StringBuilder();
            ToolStripMenuItem aa = (ToolStripMenuItem)sender;

            if (aa.Name == "MCAll")
            {
                if (aa.Checked == true)
                {
                    aa.Checked = false;
                    CStaticClass.WcfControl.ObtainTask("", "UPDATE");

                }
                else
                {
                    aa.Checked = true;
                    CStaticClass.WcfControl.ObtainTask(" or (1=1) ", "UPDATE");

                }
                //20100625修正不能获取站台到站台的任务

                for (int i = 0; i < MIStartRetrieveTask.DropDown.Items.Count; i++)
                {

                    tsm = (ToolStripMenuItem)MIStartRetrieveTask.DropDown.Items[i];
                    if (tsm.Name != "MCAll")
                    {

                        tsm.Checked = aa.Checked;

                    }

                }

                //20100625修正不能获取站台到站台的任务

            }
            else
            {
                laneway = Convert.ToInt32(aa.Text.Split(cc)[1]);
                dv = dbo.ExceSQL("select min(f_z) as minZ from st_cell where flaneway=" + laneway + "").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    if (dv[0]["minZ"].ToString().Length == 1)
                    {
                        minz = minz.Append("'0").Append(dv[0]["minZ"].ToString()).Append("-00-00'");
                    }
                    else
                    {
                        minz = minz.Append("'" + dv[0]["minZ"].ToString()).Append("-00-00'");
                    }

                }
                dv = dbo.ExceSQL("select max(f_z) as maxZ from st_cell where flaneway=" + laneway + "").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    if (dv[0]["maxZ"].ToString().Length == 1)
                    {
                        maxz = maxz.Append("'0").Append(dv[0]["maxZ"].ToString()).Append("-999-99'");
                    }
                    else
                    {
                        maxz = maxz.Append("'" + dv[0]["maxZ"].ToString()).Append("-999-99'");
                    }
                }
                wherez.Append(" or ((START_DEVICE_CODE between ").Append(minz).Append(" and ").Append(maxz).Append(" ) or  (END_DEVICE_CODE between ").Append(minz).Append(" and ").Append(maxz).Append("))");
                if (aa.Checked == true)
                {
                    aa.Checked = false;
                    //20100625修正不能获取站台到站台的任务
                    CStaticClass.WcfControl.ObtainTask(wherez.ToString(), "REPLACE");
                    

                    ToolStripMenuItem cm = new ToolStripMenuItem();
                    ToolStripMenuItem all = (ToolStripMenuItem)MIStartRetrieveTask.DropDown.Items["MCAll"];
                    CStaticClass.WcfControl.ObtainTask(" or (1=1) ", "REPLACE");
                    all.Checked = false;
                    StringBuilder wherez1 = new StringBuilder();

                    for (int ii = 0; ii < MIStartRetrieveTask.DropDown.Items.Count; ii++)
                    {
                        //20101208
                        minz.Remove(0, minz.Length);
                        maxz.Remove(0, maxz.Length);

                        cm = (ToolStripMenuItem)MIStartRetrieveTask.DropDown.Items[ii];
                        if ((cm.Checked == true) && (cm.Name != aa.Name) && (cm.Name != "MCAll"))
                        {
                            laneway = Convert.ToInt32(cm.Text.Split(cc)[1]);
                            dv = dbo.ExceSQL("select min(f_z) as minZ from st_cell where flaneway=" + laneway + "").Tables[0].DefaultView;
                            if (dv.Count > 0)
                            {
                                if (dv[0]["minZ"].ToString().Length == 1)
                                {
                                    minz = minz.Append("'0").Append(dv[0]["minZ"].ToString()).Append("-00-00'");
                                }
                                else
                                {
                                    minz = minz.Append("'" + dv[0]["minZ"].ToString()).Append("-00-00'");
                                }

                            }
                            dv = dbo.ExceSQL("select max(f_z) as maxZ from st_cell where flaneway=" + laneway + "").Tables[0].DefaultView;
                            if (dv.Count > 0)
                            {
                                if (dv[0]["maxZ"].ToString().Length == 1)
                                {
                                    maxz = maxz.Append("'0").Append(dv[0]["maxZ"].ToString()).Append("-999-99'");
                                }
                                else
                                {
                                    maxz = maxz.Append("'" + dv[0]["maxZ"].ToString()).Append("-999-99'");
                                }
                            }
                            wherez1.Append(" or ((START_DEVICE_CODE between ").Append(minz).Append(" and ").Append(maxz).Append(" ) or  (END_DEVICE_CODE between ").Append(minz).Append(" and ").Append(maxz).Append("))");

                        }

                    }
                    CStaticClass.WcfControl.ObtainTask(wherez1.ToString(), "APPEND");
                    
                    //20100625修正不能获取站台到站台的任务
                }
                else
                {
                    aa.Checked = true;

                    CStaticClass.WcfControl.ObtainTask(wherez.ToString(), "APPEND");
                }
            }

            MIStartRetrieveTask_Click(sender, e);

            for (int i = 0; i < MIStartRetrieveTask.DropDown.Items.Count; i++)
            {
                tsm = (ToolStripMenuItem)MIStartRetrieveTask.DropDown.Items[i];
                if (tsm.Checked == true)
                {
                    ifget = true;
                }
            }
            if (ifget == false)
            {
                MIStopRetrieveTask_Click(sender, e);

            }
        }

        private void MITurnOn_Click(object sender, EventArgs e)
        {
            MITurnOff.Enabled = true;
            MITurnOn.Enabled = false;
            tsmTurnOff.Enabled = true;
            tsmTurnOn.Enabled = false;

            tsmTurnOff.Checked = false;
            tsmTurnOn.Checked = true;
            MITurnOff.Checked = false;
            MITurnOn.Checked = true;
            //CStaticClass.Order = true;
            CStaticClass.WcfControl.OrderTurnOn();

            #region 重新打开命令开关时,调用两次 Timer
            timerAGVReConnect.Enabled = true;
            //CommonClassLib.CCarryConvert.WriteDarkCasket("测试", "MITurnOn_Click", "0", "打开命令开关", "");
            #endregion

            if (MIStartRetrieveTask.Checked == true)
            {
                this.Text = CStaticClass.SystemName + "【开始获取任务!】" + "【正在执行自动命令!】";
            }
            else
            {
                this.Text = CStaticClass.SystemName + "【正在执行自动命令!】";
            }
            //20120510CStaticClass.WcfControl.OrderTurnOn();
        }

        private void MITurnOff_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确认要“关闭命令开关”吗?如果“关闭命令开关”将导致调度计算机与所有设备通讯中断!", "操作提示:", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
            {
                return;
            }
            

            CStaticClass.WcfControl.OrderTurnOff();
            //CStaticClass.Order = false;
            MITurnOff.Enabled = false;
            MITurnOn.Enabled = true;
            tsmTurnOff.Enabled = false;
            tsmTurnOn.Enabled = true;

            tsmTurnOn.Checked = false;
            tsmTurnOff.Checked = true;
            MITurnOn.Checked = false;
            MITurnOff.Checked = true;

            #region 重新打开命令开关时,调用两次 Timer
            timerAGVReConnect.Enabled = false;
            #endregion

            if (MIStartRetrieveTask.Checked == true)
            {
                this.Text = CStaticClass.SystemName + "【开始获取任务!】";
            }
            else
            {
                this.Text = CStaticClass.SystemName;
            }
            //20120510CStaticClass.WcfControl.OrderTurnOff();
        }

        private void timerObtainTask_Tick(object sender, EventArgs e)
        {
            timerObtainTask.Enabled = false;
            try
            {
                string errtext = string.Empty;

                if (CStaticClass.WcfControl.GetAllManageTask(out errtext) == false)
                {
                    if (tsStatus.Text.IndexOf(errtext) < 0)
                    {
                        tsStatus.Text += errtext;
                    }
                }
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf(ex.Message) < 0)
                {
                    tsStatus.Text += ex.Message;
                }
            }
            finally
            {
                timerObtainTask.Enabled = true;
            }
        }

        private void timerDisassembleTask_Tick(object sender, EventArgs e)
        {
            timerDisassembleTask.Enabled = false;
            DataView dvmo = new DataView();
            DataView dd = new DataView();
            try
            //if (CStaticClass.Order == true)
            {
                string errtext = string.Empty;
                if (CStaticClass.WcfControl.DisassembleTask(out errtext) == false)
                {
                    if (tsStatus.Text.IndexOf(errtext) < 0)
                    {
                        tsStatus.Text += errtext;
                    }
                }
                #region AGV任务没响应,任务重发

                int DeviceIdx;
                int TaskIdx = 0;
                StringBuilder sql = new StringBuilder();
                
                sql.Remove(0, sql.Length);
                sql.Append("SELECT F_DeviceIndex,F_DeviceKindIndex,F_MaxSendCount,F_SendInterval FROM T_Base_Device WHERE F_DeviceKindIndex = 6");
                dd = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                for (int j = 0; j < dd.Count; j++)
                {
                    DeviceIdx = Convert.ToInt32(dd[j]["F_DeviceIndex"]);
                    //判断AGV控制台是否已经连接成功

                    if (CStaticClass.WcfControl.IfConnectAGVPC(DeviceIdx) == false)//20170705
                    {
                        continue;
                    }
                    #region 发送后规定时间内没报开始或者读取数据成功需要进行超时重发,重发超限时报错
                    sql.Remove(0, sql.Length);
                    sql.Append("select F_MonitorIndex,F_DeviceIndex,F_SendCount,F_StartTime,F_Status,F_AgvNo from T_Monitor_Task where F_DeviceIndex=").Append(DeviceIdx).Append(" and f_status=1 and F_SendFlag='1'");
                    dvmo = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;//20100905只重发主任务
                    if (dvmo.Count > 0)
                    {//20110510


                        TaskIdx = Convert.ToInt32(dvmo[0]["F_MonitorIndex"]);

                        int scount = Convert.ToInt32(dvmo[0]["F_SendCount"]);

                        scount++;//此处应该判断AGV控制台是否已经连接,只有在已经连接的情况下++才是合理的
                        if (scount > Convert.ToInt32(dd[j]["F_MaxSendCount"]))
                        {
                            //发送次数超限报警
                            sql.Remove(0, sql.Length);
                            sql.Append("update T_Monitor_Task set F_Status=999 where F_Status<>999 and F_MonitorIndex=").Append(TaskIdx);//20110505
                            dbo.ExceSQL(sql.ToString());

                        }
                        else
                        {
                            //DateTime.Now.AddMilliseconds
                            if (dvmo[0]["F_StartTime"].ToString() != "-")
                            {
                                //if (Convert.ToDateTime(dvmo[0]["F_StartTime"].ToString().Substring(0, 19), CultureInfo.CurrentCulture).AddMilliseconds(Convert.ToDouble(dd[j]["F_SendInterval"])) <= DateTime.Now)
                                if (Convert.ToDateTime(dvmo[0]["F_StartTime"].ToString(), CultureInfo.CurrentCulture).AddMilliseconds(Convert.ToDouble(dd[j]["F_SendInterval"])) <= DateTime.Now)//20170923
                                {

                                    //if (dvmo[0]["F_AgvNo"] == DBNull.Value)
                                    //{
                                        sql.Remove(0, sql.Length);
                                        sql.Append("update T_Base_Device set F_LockedState=0 where F_DeviceIndex=").Append(DeviceIdx);
                                        dbo.ExceSQL(sql.ToString());
                                        sql.Remove(0, sql.Length);
                                        sql.Append("update T_Monitor_Task set F_Status=0 where F_MonitorIndex=").Append(TaskIdx);
                                        //sql.Append("update T_Monitor_Task set F_SendCount=").Append(scount).Append(",F_Status=0 where F_MonitorIndex=").Append(TaskIdx);//20170923
                                        dbo.ExceSQL(sql.ToString());
                                    //}
                                    CommonClassLib.CCarryConvert.WriteDarkCasket("GetDeviceState", "超时重发", DeviceIdx.ToString(), "设备指令索引:" + TaskIdx.ToString() + ",重新发送命令!");
                                }
                            }
                        }
                    }

                    #endregion
                }
                #endregion
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf(ex.Message ) < 0)
                {
                    tsStatus.Text += ex.Message;
                }
            }
            finally
            {
                timerDisassembleTask.Enabled = true;
                dd.Dispose();
                dvmo.Dispose();
            }
        }

        private void timerSendOrder_Tick(object sender, EventArgs e)
        {
            timerSendOrder.Enabled = false;
            try
            //if (CStaticClass.Order == true)
            {
                string errtext = string.Empty;
                if (CStaticClass.WcfControl.StartSendDeviceOrder(out errtext) == false)
                {
                    if (tsStatus.Text.IndexOf(errtext) < 0)
                    {
                        tsStatus.Text += errtext;
                    }
                }
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf(ex.Message) < 0)
                {
                    tsStatus.Text += ex.Message;
                }
            }
            finally
            {
                timerSendOrder.Enabled = true;
            }
        }

        private void MISeeDarket_Click(object sender, EventArgs e)
        {
            FrmBrowseDarkCasket.FormInstance.Show();
        }

        private void MIDarketFileSet_Click(object sender, EventArgs e)
        {
            FrmDarkCasket.FormInstance.Show();
        }

        private void MIAutoTaskHistory_Click(object sender, EventArgs e)
        {
            FrmBrowseAotoTaskLog.FormInstance.Show();
        }

        

        private void MMExitSystem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void MISystemInit_Click(object sender, EventArgs e)
        {
            FrmSystemInit.FormInstance.Show();
        }

        private void toolStripMenuItem13_Click(object sender, EventArgs e)
        {
            MITurnOn_Click(sender, e);
        }

        private void toolStripMenuItem14_Click(object sender, EventArgs e)
        {
            MITurnOff_Click(sender, e);
        }

        private void toolStripMenuItem9_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripMenuItem8_Click(object sender, EventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Maximized;
        }

        private void toolStripMenuItem10_Click(object sender, EventArgs e)
        {
            this.Visible = false;
        }

        

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
          
            this.TopMost = true;
            this.Visible = true;
            this.TopMost = false;
            this.WindowState = FormWindowState.Maximized;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
        }
        
        /// <summary>
        /// 20120503向列表框增加显示内容
        /// </summary>
        /// <param name="txtinfo"></param>
        /// <returns></returns>
        bool AddList1Info(string txtinfo)
        {
            try
            {
                if (txtinfo.IndexOf("巡检客户端") >= 0) return true;
                if (listBox1.Items.Count >= 30) listBox1.Items.Clear();
                foreach (object li in listBox1.Items)
                {
                    if (li.ToString().IndexOf(txtinfo) >= 0)
                    {
                        //listBox1.Items.Remove(li);
                        //listBox1.Items.Add(DateTime.Now.ToLongTimeString() + txtinfo);
                        return false;
                    }
                }
                listBox1.Items.Add(DateTime.Now.ToLongTimeString() + txtinfo);
                return true;
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf("巡检客户端AddList1Info:" + ex.StackTrace + ex.Message) < 0)
                {
                    tsStatus.Text += "巡检客户端AddList1Info:" + ex.StackTrace + ex.Message;
                }
                return false;
            }
        }

        

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                this.listBox2.Items.Clear();
                var list = WcfControlMonitorLib.SControlMonitor.ClientCallbackLists;
                if (list == null || list.Count == 0)
                    return;
                lock (list)
                {
                    foreach (System.Collections.DictionaryEntry client in list)
                    {
                        listBox2.Items.Add(client.Value.ToString());

                    }

                }
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf("刷新客户端时:" + ex.StackTrace + ex.Message) < 0)
                {
                    tsStatus.Text += "刷新客户端时:" + ex.StackTrace + ex.Message;
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (listBox2.SelectedItem == null) return;
                var list = WcfControlMonitorLib.SControlMonitor.ClientCallbackLists;
                foreach (System.Collections.DictionaryEntry client in list)
                {
                    if (client.Value.ToString() == listBox2.SelectedItem.ToString())
                    {
                        WcfControlMonitorLib.SControlMonitor.ClientShowLists.Remove(client.Key);
                        WcfControlMonitorLib.SControlMonitor.ClientCallbackLists.Remove(client.Key);
                        button4_Click(sender, e);
                        return;
                    }

                }
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf("注销客户端时:" + ex.StackTrace + ex.Message) < 0)
                {
                    tsStatus.Text += "注销客户端时:" + ex.StackTrace + ex.Message;
                }
            }
        }
        void ClickObtainTask()
        {
            if (MITurnOn.Checked == true)
            {
                if (this.Text != CStaticClass.SystemName + "【开始获取任务!】" + "【正在执行自动命令!】")
                {
                    this.Text = CStaticClass.SystemName + "【开始获取任务!】" + "【正在执行自动命令!】";
                }
            }
            else
            {
                if (this.Text != CStaticClass.SystemName + "【开始获取任务!】")
                {
                    this.Text = CStaticClass.SystemName + "【开始获取任务!】";
                }
            }
            MIStartRetrieveTask.Checked = true;
            MIStartRetrieveTask.Enabled = false;
            MIStopRetrieveTask.Checked = false;
            MIStopRetrieveTask.Enabled = true;
        }
        void ClickStopObtainTask()
        {
            if (MITurnOn.Checked == true)
            {
                if (this.Text != CStaticClass.SystemName + "【正在执行自动命令!】")
                {
                    this.Text = CStaticClass.SystemName + "【正在执行自动命令!】";
                }
            }
            else
            {
                if (this.Text != CStaticClass.SystemName)
                {
                    this.Text = CStaticClass.SystemName;
                }
            }

            MIStartRetrieveTask.Checked = false;
            MIStartRetrieveTask.Enabled = true;
            MIStopRetrieveTask.Enabled = false;
            MIStopRetrieveTask.Checked = true;
        }
        void ClickOrderTurnOn()
        {
            if (MIStartRetrieveTask.Checked == true)
            {
                if (this.Text != CStaticClass.SystemName + "【开始获取任务!】" + "【正在执行自动命令!】")
                {
                    this.Text = CStaticClass.SystemName + "【开始获取任务!】" + "【正在执行自动命令!】";
                }
            }
            else
            {
                if (this.Text != CStaticClass.SystemName + "【正在执行自动命令!】")
                {
                    this.Text = CStaticClass.SystemName + "【正在执行自动命令!】";
                }
            }
            MITurnOff.Enabled = true;
            MITurnOn.Enabled = false;
            MITurnOff.Checked = false;
            MITurnOn.Checked = true;
        }
        void ClickOrderTurnOff()
        {

            if (MIStartRetrieveTask.Checked == true)
            {
                if (this.Text != CStaticClass.SystemName + "【开始获取任务!】")
                {
                    this.Text = CStaticClass.SystemName + "【开始获取任务!】";
                }
            }
            else
            {
                if (this.Text != CStaticClass.SystemName)
                {
                    this.Text = CStaticClass.SystemName;
                }
            }

            MITurnOff.Enabled = false;
            MITurnOn.Enabled = true;
            MITurnOn.Checked = false;
            MITurnOff.Checked = true;
        }
        private void ClearMemory()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

        int UserTimeOut = 0;//用于过期判断时间
        /// <summary>
        /// 触发心跳诊断的定时器
        /// </summary>
        /// <returns></returns>
        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            DataView dv = new DataView();
            try
            {//20121203
                //20130817richard
                
                CStaticClass.WcfControl.Heartbeat(out mi);
                #region PLC连接状态
                if (mi.S7connectOnline.Count > 0)
                {
                    if (mi.S7connectOnline.ContainsKey("S7 connection_2") && mi.S7connectOnline["S7 connection_2"] == 0 && mi.Orderturnon == true)
                    {
                        MMConnection1.Image = wcfControlMonitorClient.Properties.Resources.linkok;
                    }
                    else
                    {
                        //20191101 使用 Scout@LOCALSERVER 模拟 PLC 时,能够正确显示连接状态
                        if (mi.S7connectOnline.ContainsKey("@LOCALSERVER") && mi.S7connectOnline["@LOCALSERVER"] == 0)
                        {
                            MMConnection1.Image = wcfControlMonitorClient.Properties.Resources.linkok;
                        }
                        else
                        {
                            MMConnection1.Image = wcfControlMonitorClient.Properties.Resources.linkerror;
                        }
                    }

                   

                }
                #endregion
               
                if (mi.Orderturnon == true)
                {
                    ClickOrderTurnOn();
                }
                else
                {
                    ClickOrderTurnOff();
                }
                if (mi.Obtaintask == true)
                {
                    ClickObtainTask();
                }
                else
                {
                    ClickStopObtainTask();
                }
                timersum++;//20120513
                
                if (timersum > 60)//20120513
                {
                    //listBox1.Items.Clear();
                    timersum = 0;
                    dv = dbo.ExceSQL("SELECT  T_Monitor_Task.F_MonitorIndex,T_Base_Device.F_DeviceIndex FROM T_Base_Device,T_Monitor_Task where T_Base_Device.F_DeviceIndex = T_Monitor_Task.F_DeviceIndex and (T_Base_Device.F_DeviceKindIndex = 1 OR T_Base_Device.F_DeviceKindIndex = 4) and F_Status>0  and F_StartTime<>'-' and (datediff(MINUTE,CONVERT(datetime,SUBSTRING( F_StartTime,1,19),120),GETDATE()) >5)").Tables[0].DefaultView;
                    for (int i = 0; i < dv.Count; i++)
                    {
                        CStaticClass.WcfControl.ActionError(Convert.ToInt32(dv[i][1]), Convert.ToInt32(dv[i][0]), 999);
                        CStaticClass.dbo.ExecuteSql(string.Format("update T_Base_Device set F_ErrorTaskNo=0 where F_ErrorTaskNo={0}", Convert.ToInt32(dv[i][0])));
                    }
                }
                #region 断网恢复
                //timerefesh++;//20150103增加断网恢复//20151120取消断网恢复
                //if (timerefesh > 1)
                //{//20150103增加断网恢复
                //    CStaticClass.WcfControl.RefreshMonitoringMode();
                //    timerefesh = 0;
                //}
                #endregion

                SendMessageToClient("巡检客户端");

                #region 客户端过期
                UserTimeOut++;
                if (UserTimeOut >= 360)
                {
                    UserTimeOut = 0;
                    string DES = CommonClassLib.AppSettings.GetValue("AGVTaskCount");
                    string des = CStaticClass.WcfControl.Md5Decrypt(DES);
                    string[] date = des.Split('|');
                    if (date[1].ToString() == "over")
                    {
                        try
                        {
                            var list = WcfControlMonitorLib.SControlMonitor.ClientCallbackLists;
                            foreach (System.Collections.DictionaryEntry client in list)
                            {
                                WcfControlMonitorLib.SControlMonitor.ClientShowLists.Remove(client.Key); WcfControlMonitorLib.SControlMonitor.ClientCallbackLists.Remove(client.Key);
                                button4_Click(sender, e);
                                return;
                            }
                        }
                        catch (Exception ex)
                        {
                            if (tsStatus.Text.IndexOf("注销客户端时:" + ex.StackTrace + ex.Message) < 0)
                            {
                                tsStatus.Text += "注销客户端时:" + ex.StackTrace + ex.Message;
                            }
                            return;
                        }
                    }
                    DateTime limittime = Convert.ToDateTime(date[1].ToString());
                    if (limittime < DateTime.Now)
                    {
                        try
                        {
                            var list = WcfControlMonitorLib.SControlMonitor.ClientCallbackLists;
                            foreach (System.Collections.DictionaryEntry client in list)
                            {
                                WcfControlMonitorLib.SControlMonitor.ClientShowLists.Remove(client.Key);
                                WcfControlMonitorLib.SControlMonitor.ClientCallbackLists.Remove(client.Key);
                                button4_Click(sender, e);
                                return;
                            }
                        }
                        catch (Exception ex)
                        {
                            if (tsStatus.Text.IndexOf("注销客户端时:" + ex.StackTrace + ex.Message) < 0)
                            {
                                tsStatus.Text += "注销客户端时:" + ex.StackTrace + ex.Message;
                            }
                            return;
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf("巡检客户端时:"+ex.StackTrace+ex.Message) < 0)
                {
                    tsStatus.Text += "巡检客户端时:" + ex.StackTrace + ex.Message;
                }
            }
            finally
            {
                dv.Dispose();
                timer1.Enabled = true;
            }
            
        }

        private void btStartTest_Click(object sender, EventArgs e)
        {
            WcfControlMonitorLib.CStaticClass.StopTestLane = false;

            btStartTest.Visible = false;
            btStopTest.Visible = true;

            WcfControlMonitorLib.CStaticClass.TestOutEnd = false;
            btStopOut.Visible = true;
            btStopOut.BackColor = Color.White;

            WcfControlMonitorLib.CStaticClass.TestInEnd = false;
            btStopIn.Visible = true;
            btStopIn.BackColor = Color.White;

            try
            { 
                //托盘库库前测试
                int[] station =new  int[]{12013,12012,12011,12010,12009,12008,12007};

                for(int i=0;i<station.Length;i++)
                {
                    //查找有货的货位
                    //生成任务
                }
              }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        private void btStopTest_Click(object sender, EventArgs e)
        {
            WcfControlMonitorLib.CStaticClass.StopTestLane = true;
            btStartTest.Visible = true;
            btStopTest.Visible = false;
            //Graphics g = this.tabControl1.TabPages[0].CreateGraphics();

            WcfControlMonitorLib.CStaticClass.TestOutEnd = true;
            btStopOut.Visible = false;

            WcfControlMonitorLib.CStaticClass.TestInEnd = true;
            btStopIn.Visible = false;
        }

        private void btStopOut_Click(object sender, EventArgs e)
        {
            WcfControlMonitorLib.CStaticClass.TestOutEnd = true;
            btStopOut.BackColor = Color.Gray;
        }

        private void btStopIn_Click(object sender, EventArgs e)
        {
            WcfControlMonitorLib.CStaticClass.TestInEnd = true;
            btStopIn.BackColor = Color.Gray;
        }

        private void btcelltest_Click(object sender, EventArgs e)
        {

            FrmLaneTest.FormInstance.ShowDialog();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FrmBrowseCellStatus.FormInstance.Show();
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            FrmDeviceErrorLog.FormInstance.Show();
        }

        private void MIBackUpDataBase_Click(object sender, EventArgs e)
        {
            try
            {
                //string str = CStaticClass.GetDBName();

                string localFilePath;
                string saveFilepath = "D:\\";
                string DBName = CStaticClass.GetDBName();
                saveFileDialog1.Title = "备份调度系统数据库...";
                saveFileDialog1.FileName = string.Format("{0}{1}.Bak", DBName, DateTime.Now.ToString("yyyyMMddHHmmss"));
                saveFileDialog1.Filter = "备份文件(*.Bak)|*.Bak|所有文件(*.*)|*.*";

                if (System.IO.Directory.Exists(saveFilepath))//文件目录是否存在
                {
                    saveFileDialog1.InitialDirectory = saveFilepath;
                }

                saveFileDialog1.RestoreDirectory = true;
                //saveFileDialog1.CheckFileExists = true;
                saveFileDialog1.CheckPathExists = true;
                saveFileDialog1.OverwritePrompt = true;

                if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
                {

                    localFilePath = saveFileDialog1.FileName.ToString();


                    string sql = string.Format("Backup database {0} to disk = '{1}'", DBName, localFilePath); //MyTest为远程数据库名称,也可以改成用变量传入
                    dbo.ExceSQL(sql);

                    //下面判断文件是否生成来确定是否备份成功
                    if (System.IO.File.Exists(localFilePath))
                    {
                        MessageBox.Show("数据库备份成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    else
                    {
                        MessageBox.Show("数据库备份失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }

                    //还原是一样的.只是sql改成"RESTORE FILELISTONLY  FROM DISK ='路径'"
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
        static public bool ExistsWinRAR()
        {
            RegistryKey the_Reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
            return !string.IsNullOrEmpty(the_Reg.GetValue("").ToString());
        }
        /// <summary>
        /// 将目录压缩为.RAR文件
        /// </summary>
        /// <param name="patch">源目录</param>
        /// <param name="rarPatch">目的目录</param>
        /// <param name="rarName">压缩文件名称,如包含目录名称可以不制定rarpatch</param>
        public bool CompressRAR(string patch, string rarPatch, string rarName)
        {
            bool flag = false;
            string the_rar;
            RegistryKey the_Reg;
            object the_Obj;
            string the_Info;
            ProcessStartInfo the_StartInfo;
            Process the_Process;
            try
            {
                the_Reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
                the_Obj = the_Reg.GetValue("");
                the_rar = the_Obj.ToString();
                the_Reg.Close();
                //the_rar = the_rar.Substring(1, the_rar.Length - 7);//该行可能有问题?
                //Directory.CreateDirectory(patch);//使用已有目录
                //命令参数
                //the_Info = " a    " + rarName + " " + @"C:Test?70821.txt"; //文件压缩
                the_Info = string.Format("A -r -ep1 \"{0}\" {1}\"", rarName, patch);//路径中含有空格的处理-加入\
                the_StartInfo = new ProcessStartInfo();
                the_StartInfo.FileName = the_rar;
                the_StartInfo.Arguments = the_Info;
                the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                //打包文件存放目录,如果文件名中包含目录信息则可以不指定
                //the_StartInfo.WorkingDirectory = rarPatch;
                the_Process = new Process();
                the_Process.StartInfo = the_StartInfo;
                the_Process.Start();
                the_Process.WaitForExit();

                if (the_Process.HasExited)
                {
                    if (the_Process.ExitCode == 0)
                    {
                        flag = true;
                    }
                }
                the_Process.Close();

            }
            catch (Exception ex)
            {
                throw ex;
            }

            return flag;
        }
        /// <summary>
        /// 压缩多个文件夹
        /// </summary>
        /// <param name="patch">源文件夹</param>
        /// <param name="rarPatch">目的目录</param>
        /// <param name="rarName">被压缩文件的名称</param>
        /// <returns></returns>
        public bool CompressRARS(string[] patch, string rarPatch, string rarName)
        {
            bool isflags = false;
            if (patch != null)
            {
                foreach (string path in patch)
                {
                    try
                    {
                        isflags = CompressRAR(path, rarPatch, rarName);
                    }
                    catch { isflags = false; }

                }
            }

            return isflags;
        }
        private void MIBackUpDarkCasket_Click(object sender, EventArgs e)
        {
            try
            {
                if (ExistsWinRAR())
                {

                    //string SourceFilePath = System.Environment.CurrentDirectory + "\\DarkCasket";
                    //string SourcePath = System.Environment.CurrentDirectory + "\\ErrorDarkCasket";
                    string DBName = CStaticClass.GetDBName();
                    string[] SourceFilePath = new String[2];
                    SourceFilePath[0] = string.Format("{0}{1}", System.Environment.CurrentDirectory, "\\DarkCasket");
                   // SourceFilePath[1] = string.Format("{0}{1}", System.Environment.CurrentDirectory, "\\ErrorDarkCasket");
                    SourceFilePath[1] = string.Format("{0}{1}", System.Environment.CurrentDirectory, "\\LoginDarkCasket");
                   // SourceFilePath[3] = string.Format("{0}{1}", System.Environment.CurrentDirectory, "\\ReceiveAGVDarkCasket");
                    string localFilePath;
                    string saveFilepath = "D:\\";
                    //string newFileName;
                    saveFileDialog1.Title = "备份黑匣子...";
                    saveFileDialog1.FileName = string.Format("{0}{1}DarkCasket", DBName, DateTime.Now.ToString("yyyyMMddHHmmss"));
                    saveFileDialog1.Filter = "WinRAR文件(*.rar)|*.rar";

                    if (System.IO.Directory.Exists(saveFilepath))//文件目录是否存在
                    {
                        saveFileDialog1.InitialDirectory = saveFilepath;
                    }

                    saveFileDialog1.RestoreDirectory = true;

                    saveFileDialog1.CheckPathExists = true;
                    saveFileDialog1.OverwritePrompt = true;

                    if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
                    {

                        localFilePath = saveFileDialog1.FileName.ToString();
                        saveFilepath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\") + 1);//获得路径,不含文件名
                        //newFileName=localFilePath.Substring(localFilePath.LastIndexOf("\\")+1);//获得文件名,不含路径

                        //CompressRAR(SourceFilePath,saveFilepath,newFileName);
                        bool ifsuccess = CompressRARS(SourceFilePath, saveFilepath, localFilePath);
                        //下面判断文件是否生成来确定是否备份成功
                        if (ifsuccess == true && System.IO.File.Exists(localFilePath))
                        {
                            MessageBox.Show("黑匣子文件备份并压缩成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        }
                        else
                        {
                            MessageBox.Show("黑匣子文件备份失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }

                        //还原是一样的.只是sql改成"RESTORE FILELISTONLY  FROM DISK ='路径'"
                    }

                }
                else
                {
                    MessageBox.Show("未安装WinRAR,无法完成备份!请安装WinRAR之后再尝试备用或直接进行手工备份!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
          CGetState  cgs= new CGetState();
            cgs.ActionStartRun(10001, 123);
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            string a;
            CStaticClass.WcfControl.GetAllCellString(out a);
            //CStaticClass.WcfControl.GetOneDeviceOrCellString(0,0, "02-03-01",out  a);
            CStaticClass.WcfControl.GetOneDeviceOrCellString(22012, 0, "", out  a);
        }

        private void timerAGVReConnect_Tick(object sender, EventArgs e)
        {
            timerAGVReConnect.Enabled = false;
            try
            {
                
                string errtext = string.Empty;
                if (CStaticClass.WcfControl.ReConnectAGVPC(out errtext) == false)
                {
                    if (tsStatus.Text.IndexOf(errtext) < 0)
                    {
                        tsStatus.Text += errtext;
                    }
                }
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf(ex.Message) < 0)
                {
                    tsStatus.Text += ex.Message;
                }
            }
            finally
            {
                timerAGVReConnect.Enabled = true;
            }
        }

        /// <summary>
        /// 测试&调试 PLC
        /// </summary>
        private void button2_Click_2(object sender, EventArgs e)
        {
            byte[] _Sdata;
            string _Sdatastr;
            _Sdatastr = string.Format("@{0};{1};{2};{3};{4}!",1,2,3,4,5);
            _Sdata = System.Text.Encoding.ASCII.GetBytes(_Sdatastr);
            _Sdatastr = System.Text.Encoding.ASCII.GetString(_Sdata);
        }

        private void button2_Click_3(object sender, EventArgs e)
        {

            //string Enddevice = "12023";
            //string[] EndGroup = Enddevice.Split(';');
            //if (EndGroup.Length < 2)
            //{ }
            ////string a = "11001";
            ////string b = "";
            ////char[] cc = new char[1] { ';' };
            ////string[] stacksa = a.Split(cc);
            ////string[] stacksb = b.Split(cc);
            //byte[] bytes = new byte[4] { 67, 172, 241, 236 };
            ////byte[] newbytes = bytes.Reverse().ToArray();
            //float a = CommonClassLib.CCarryConvert.ByteToFloat(bytes);
            ////dealwith
            //string errtext = string.Empty;
            //int device = 32019;
            //byte[] _bytes1 = new byte[10];
            //byte[] _bytes2 = new byte[10];
            //CStaticClass.WcfControl.DealWithDeviceState(out errtext, device, _bytes1, _bytes2);
            //byte[] b = new byte[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            ////CStaticClass.dbo.ExecuteSqlInsertImg(string.Format("update T_Base_Users set erjinzhi=@fs  where f_userid='admin'"), b);
            //DataView dv = dbo.ExceSQL("select erjinzhi  from T_Base_Users  where f_userid='admin'").Tables[0].DefaultView;
            //if (dv.Count > 0)
            //{
            //    Byte[] Files = (Byte[])dv[0]["erjinzhi"];

            //}
        }

        private void timerInLight_Tick(object sender, EventArgs e)
        {
            timerInLight.Enabled = false;
            try         
            {
                string errtext = string.Empty;
                if (CStaticClass.WcfControl.SetInLight(out errtext) == false)
                {
                    if (tsStatus.Text.IndexOf(errtext) < 0)
                    {
                        tsStatus.Text += errtext;
                    }
                }
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf(ex.Message) < 0)
                {
                    tsStatus.Text += ex.Message;
                }
            }
            finally
            {
                timerInLight.Enabled = true;
            }
        }

        /// <summary>
        /// WXSS项目的双向输送线入库灯
        /// </summary>
        private void timerPLCAsk_Tick(object sender, EventArgs e)
        {
            timerInLight.Enabled = false;
            try
            {
                string errtext = string.Empty;
                if (CStaticClass.WcfControl.SetInLight(out errtext) == false)
                {
                    if (tsStatus.Text.IndexOf(errtext) < 0)
                    {
                        tsStatus.Text += errtext;
                    }
                }
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf(ex.Message) < 0)
                {
                    tsStatus.Text += ex.Message;
                }
            }
            finally
            {
                timerInLight.Enabled = true;
            }
        }

        #region 切换语言功能,未完成
        private void MIEnglish_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("切换语言需要关闭程序重新启动!", "操作提示:", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
            {
                return;
            }
            CommonClassLib.AppSettings.SetValue("Language", "English");
            MMExitSystem_Click(sender, e);
        }

        private void MIChinese_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("切换语言需要关闭程序重新启动!", "操作提示:", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
            {
                return;
            }
            CommonClassLib.AppSettings.SetValue("Language", "Chinese");
            MMExitSystem_Click(sender, e);

        }



        /// <summary>
        /// 环形穿梭车、AGV数据库任务接口,获得任务状态定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerGetSouthLRGVState_Click(object sender, EventArgs e)
        {
            timerSSAR.Enabled = false;
            try

            {
                string errtext = string.Empty;

                

                //if (CStaticClass.WcfControl.GetARGVState(CCommonFunctionSSAR.NORTHLRGV, out errtext) == false)
                //{
                //    if (tsStatus.Text.IndexOf(errtext) < 0)
                //    {
                //        tsStatus.Text += errtext;
                //    }
                //}
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf(ex.Message) < 0)
                {
                    tsStatus.Text += ex.Message;
                }
            }
            finally
            {
                timerSSAR.Enabled = true;
            }

        }
        private void timerGetNorthLRGVState_Click(object sender, EventArgs e)
        {
            timerSSAR.Enabled = false;
            try
            //if (CStaticClass.ObtainManageTask == true)
            {
                string errtext = string.Empty;

                
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf(ex.Message) < 0)
                {
                    tsStatus.Text += ex.Message;
                }
            }
            finally
            {
                timerSSAR.Enabled = true;
            }

        }

        
        #endregion


        /*
                              .::::.
                            .::::::::.
                           :::::::::::  
                       ..:::::::::::'
                     '::::::::::::'
                       .::::::::::
                  '::::::::::::::..
                       ..::::::::::::.
                     ``::::::::::::::::
                      ::::``:::::::::'        .:::.
                     ::::'   ':::::'       .::::::::.
                   .::::'      ::::     .:::::::'::::.
                  .:::'       :::::  .:::::::::' ':::::.
                 .::'        :::::.:::::::::'      ':::::.
                .::'         ::::::::::::::'         ``::::.
            ...:::           ::::::::::::'              ``::.
           ````':.          ':::::::::'                  ::::..
                              '.:::::'                    ':'````..
       */


    }

}