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
        CCommonFunction ccf = new CCommonFunction();//add by lyj20190312
        //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();
                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)
        {



        }



        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);
                _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();
            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;

            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
            //if (CStaticClass.ObtainManageTask == true)
            {
                string errtext = string.Empty;

                if (CStaticClass.WcfControl.GetAllManageTask(out errtext) == false)
                {
                    if (tsStatus.Text.IndexOf(errtext) < 0)
                    {
                        tsStatus.Text += errtext;
                    }
                }
                #region AGV任务没响应,任务重发

                //int DeviceIdx;
                //int TaskIdx = 0;
                //StringBuilder sql = new StringBuilder();
                //DataView  dvmo =new DataView();
                //sql.Remove(0, sql.Length);
                //sql.Append("SELECT F_DeviceIndex,F_DeviceKindIndex,F_MaxSendCount,F_SendInterval FROM T_Base_Device WHERE F_DeviceKindIndex = 6");
                //DataView  dd = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                //for (int j = 0; j < dd.Count; j++)
                //{
                //    DeviceIdx = Convert.ToInt32(dd[j]["F_DeviceIndex"]);
                //    #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++;
                //        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 (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_SendCount=").Append(scount).Append(",F_Status=0 where F_MonitorIndex=").Append(TaskIdx);
                //                        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
            {
                timerObtainTask.Enabled = true;
            }
        }

        private void timerDisassembleTask_Tick(object sender, EventArgs e)
        {
            timerDisassembleTask.Enabled = false;
            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;
                    }
                }
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf(ex.Message) < 0)
                {
                    tsStatus.Text += ex.Message;
                }
            }
            finally
            {
                timerDisassembleTask.Enabled = true;
            }
        }

        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 >= 70) 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 timer1_Tick(object sender, EventArgs e)
        {
            DataView dv = new DataView();
            try
            {//20121203
                //20130817richard

                CStaticClass.WcfControl.Heartbeat(out mi);
                if (mi.S7connectOnline.Count > 0)
                {
                    try
                    {

                        if (mi.S7connectOnline["S7 connection_1"] == 0)
                        {
                            pbF1S7.Image = wcfControlMonitorClient.Properties.Resources.linkok;
                        }
                        else
                        {
                            pbF1S7.Image = wcfControlMonitorClient.Properties.Resources.linkerror;
                        }
                        //if (mi.S7connectOnline["S7 connection_2"] == 0)
                        //{
                        //    pbF2S7.Image = wcfControlMonitorClient.Properties.Resources.linkok;
                        //}
                        //else
                        //{
                        //    pbF2S7.Image = wcfControlMonitorClient.Properties.Resources.linkerror;
                        //}

                    }
                    catch (Exception eee1) { }

                }
                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])));
                    }
                }
                //timerefesh++;//20150103增加断网恢复//20151120取消断网恢复
                //if (timerefesh > 1)
                //{//20150103增加断网恢复
                //    CStaticClass.WcfControl.RefreshMonitoringMode();
                //    timerefesh = 0;
                //}


                SendMessageToClient("巡检客户端");
            }
            catch (Exception ex)
            {
                if (tsStatus.Text.IndexOf("巡检客户端时:" + ex.StackTrace + ex.Message) < 0)
                {
                    tsStatus.Text += "巡检客户端时:" + ex.StackTrace + ex.Message;
                }
            }
            finally
            {
                dv.Dispose();
            }

        }

        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 = false;
            btStopOut.Visible = false;

            WcfControlMonitorLib.CStaticClass.TestInEnd = false;
            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 lighttimer_Tick(object sender, EventArgs e)
        {

            string sqllight = string.Empty;
            string sqlout = string.Empty;
            DataView dvlight;
            DataView dvout;
            int deviceindex = 0;
            int db1addr = 0;
            int db2addr = 0;
            int converyindex = 0;

            try
            {
                sqllight = "select F_DeviceIndex,F_DeviceName,F_DBW1Address,F_DBW2Address from T_Base_Device " +
                "where F_DeviceKindIndex=20 order by F_DeviceIndex";
                dvlight = dbo.ExceSQL(sqllight).Tables[0].DefaultView;

                if (dvlight.Count > 0)
                {
                    for (int i = 0; i < dvlight.Count; i++)
                    {

                        deviceindex = Convert.ToInt32(dvlight[i]["F_DeviceIndex"]);
                        db1addr = Convert.ToInt32(dvlight[i]["F_DBW1Address"]);
                        db2addr = Convert.ToInt32(dvlight[i]["F_DBW2Address"]);
                        switch (deviceindex)
                        {
                            case 10010:

                                converyindex = 12096;
                                break;
                            case 10020:
                                converyindex = 12094;
                                break;
                            case 10030:
                                converyindex = 12090;
                                break;
                            case 10040:
                                converyindex = 12086;
                                break;
                            case 10050:
                                converyindex = 12082;
                                break;
                            #region  add by lyj20190719
                            case 10070:
                                converyindex = 12092;
                                break;
                            case 10080:
                                converyindex = 12088;
                                break;
                            case 10090:
                                converyindex = 12084;
                                break;
                            #endregion
                        }
                        sqlout = string.Format("select FID from  T_Manage_Task  where FENDDEVICE={0} and FCONTROLTASKTYPE=2", converyindex);
                        dvout = dbo.ExceSQL(sqlout).Tables[0].DefaultView;

                        switch (deviceindex)
                        {
                            case 10010:

                                if (dvout.Count > 0 && CStaticClass.OutLightFlagNum1 < 1)
                                {

                                    SControlMonitor.lightFlag(deviceindex, "2");

                                    CStaticClass.OutLightFlagNum1 = CStaticClass.OutLightFlagNum1 + 1;
                                    CStaticClass.IntLightFlagNum1 = 0;

                                }
                                else if (dvout.Count == 0 && CStaticClass.IntLightFlagNum1 < 1)
                                {
                                    SControlMonitor.lightFlag(deviceindex, "1");
                                    CStaticClass.IntLightFlagNum1 = CStaticClass.IntLightFlagNum1 + 1;
                                    CStaticClass.OutLightFlagNum1 = 0;

                                }
                                break;
                            case 10020:
                                if (dvout.Count > 0 && CStaticClass.OutLightFlagNum2 < 1)
                                {

                                    SControlMonitor.lightFlag(deviceindex, "2");

                                    CStaticClass.OutLightFlagNum2 = CStaticClass.OutLightFlagNum2 + 1;
                                    CStaticClass.IntLightFlagNum2 = 0;

                                }
                                else if (dvout.Count == 0 && CStaticClass.IntLightFlagNum2 < 1)
                                {
                                    SControlMonitor.lightFlag(deviceindex, "1");
                                    CStaticClass.IntLightFlagNum2 = CStaticClass.IntLightFlagNum2 + 1;
                                    CStaticClass.OutLightFlagNum2 = 0;

                                }
                                break;

                            case 10030:
                                if (dvout.Count > 0 && CStaticClass.OutLightFlagNum3 < 1)
                                {

                                    SControlMonitor.lightFlag(deviceindex, "2");

                                    CStaticClass.OutLightFlagNum3 = CStaticClass.OutLightFlagNum3 + 1;
                                    CStaticClass.IntLightFlagNum3 = 0;

                                }
                                else if (dvout.Count == 0 && CStaticClass.IntLightFlagNum3 < 1)
                                {
                                    SControlMonitor.lightFlag(deviceindex, "1");
                                    CStaticClass.IntLightFlagNum3 = CStaticClass.IntLightFlagNum3 + 1;
                                    CStaticClass.OutLightFlagNum3 = 0;

                                }
                                break;

                            case 10040:
                                if (dvout.Count > 0 && CStaticClass.OutLightFlagNum4 < 1)
                                {

                                    SControlMonitor.lightFlag(deviceindex, "2");

                                    CStaticClass.OutLightFlagNum4 = CStaticClass.OutLightFlagNum4 + 1;
                                    CStaticClass.IntLightFlagNum4 = 0;

                                }
                                else if (dvout.Count == 0 && CStaticClass.IntLightFlagNum4 < 1)
                                {
                                    SControlMonitor.lightFlag(deviceindex, "1");
                                    CStaticClass.IntLightFlagNum4 = CStaticClass.IntLightFlagNum4 + 1;
                                    CStaticClass.OutLightFlagNum4 = 0;

                                }
                                break;
                            case 10050:
                                if (dvout.Count > 0 && CStaticClass.OutLightFlagNum5 < 1)
                                {

                                    SControlMonitor.lightFlag(deviceindex, "2");

                                    CStaticClass.OutLightFlagNum5 = CStaticClass.OutLightFlagNum5 + 1;
                                    CStaticClass.IntLightFlagNum5 = 0;

                                }
                                else if (dvout.Count == 0 && CStaticClass.IntLightFlagNum5 < 1)//update 20180912
                                {
                                    SControlMonitor.lightFlag(deviceindex, "1");
                                    CStaticClass.IntLightFlagNum5 = CStaticClass.IntLightFlagNum5 + 1;
                                    CStaticClass.OutLightFlagNum5 = 0;

                                }

                                break;

                            #region  add by lyj20190719
                            case 10070:
                                if (dvout.Count > 0 && CStaticClass.OutLightFlagNum7 < 1)
                                {

                                    SControlMonitor.lightFlag(deviceindex, "2");

                                    CStaticClass.OutLightFlagNum7 = CStaticClass.OutLightFlagNum7 + 1;
                                    CStaticClass.IntLightFlagNum7 = 0;

                                }
                                else if (dvout.Count == 0 && CStaticClass.IntLightFlagNum7 < 1)
                                {
                                    SControlMonitor.lightFlag(deviceindex, "1");
                                    CStaticClass.IntLightFlagNum7 = CStaticClass.IntLightFlagNum7 + 1;
                                    CStaticClass.OutLightFlagNum7 = 0;

                                }
                                break;

                            case 10080:
                                if (dvout.Count > 0 && CStaticClass.OutLightFlagNum8 < 1)
                                {

                                    SControlMonitor.lightFlag(deviceindex, "2");

                                    CStaticClass.OutLightFlagNum8 = CStaticClass.OutLightFlagNum8 + 1;
                                    CStaticClass.IntLightFlagNum8 = 0;

                                }
                                else if (dvout.Count == 0 && CStaticClass.IntLightFlagNum8 < 1)
                                {
                                    SControlMonitor.lightFlag(deviceindex, "1");
                                    CStaticClass.IntLightFlagNum8 = CStaticClass.IntLightFlagNum8 + 1;
                                    CStaticClass.OutLightFlagNum8 = 0;

                                }
                                break;

                            case 10090:
                                if (dvout.Count > 0 && CStaticClass.OutLightFlagNum9 < 1)
                                {

                                    SControlMonitor.lightFlag(deviceindex, "2");

                                    CStaticClass.OutLightFlagNum9 = CStaticClass.OutLightFlagNum9 + 1;
                                    CStaticClass.IntLightFlagNum9 = 0;

                                }
                                else if (dvout.Count == 0 && CStaticClass.IntLightFlagNum9 < 1)
                                {
                                    SControlMonitor.lightFlag(deviceindex, "1");
                                    CStaticClass.IntLightFlagNum9 = CStaticClass.IntLightFlagNum9 + 1;
                                    CStaticClass.OutLightFlagNum9 = 0;

                                }
                                break;

                            #endregion
                        }


                    }
                }
            }
            catch (Exception eltt)
            {

            }
            finally
            {

            }
        }

        private void demoSettimer_Tick(object sender, EventArgs e)
        {
            string sql = string.Empty;
            DataView dv;

            string sqlmanager = string.Empty;
            string sqlstr = string.Empty;
            DataView dvmanger;
            DataView dvbarcode;
            DataView dvfcell;
            string warehouseType = string.Empty;
            string barcode = string.Empty;
            StringBuilder sqlbuffer = new StringBuilder();
            string fcell = string.Empty;
            int flaneno = 0;
            int fstackno = 0;
            string fenddevice = string.Empty;
            string sqlfcell = string.Empty;

            try
            {
                sql = "select * from T_WareHouse_DemoSet";
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;

                if (dv.Count > 0)
                {
                    for (int i = 0; i < dv.Count; i++)
                    {

                        try
                        {

                            warehouseType = dv[i]["FWarehouseType"].ToString();



                            if (Convert.ToInt32(dv[i]["FDemoFlag"]) == 1)
                            {
                                sqlbuffer.Remove(0, sqlbuffer.Length);

                                sqlbuffer.Append("select * from T_Barcode_LayerOrLane  where FwareHouseType='" + warehouseType + "'");
                                dvbarcode = dbo.ExceSQL(sqlbuffer.ToString()).Tables[0].DefaultView;
                                for (int j = 0; j < dvbarcode.Count; j++)
                                {
                                    barcode = dvbarcode[j]["Fbarcode"].ToString();
                                    flaneno = Convert.ToInt32(dvbarcode[j]["Flane"].ToString());
                                    fstackno = Convert.ToInt32(dvbarcode[j]["Fstack"].ToString());
                                    fenddevice = dvbarcode[j]["FendDevice"].ToString();
                                    fcell = dvbarcode[j]["Fcell"].ToString();
                                    sqlmanager = "select * from T_Manage_Task where FPALLETBARCODE='" + barcode + "'";
                                    dvmanger = dbo.ExceSQL(sqlmanager).Tables[0].DefaultView;
                                    sqlfcell = "select * from ST_CELL where FPALLETBARCODE='" + barcode + "' and FCELLCODE='" + fcell + "'";
                                    dvfcell = dbo.ExceSQL(sqlfcell).Tables[0].DefaultView;

                                    if (dvmanger.Count <= 0&&dvfcell.Count>0)
                                    {

                                        int AutoManageIdx = ccf.GetTempManageIdx();//调度任务索引
                                        string dtimes = DateTime.Now.ToString("u");
                                        dtimes = dtimes.Substring(0, dtimes.Length - 1);
                                        sqlstr = string.Format("insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL,FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME,FStartCol,FStartLayer) values ({0},'{1}',{2},{3},{4},{5},'{6}',{7},{8},'{9}',{10},{11},'{12}','{13}',{14},{15})",
                                                                                                     AutoManageIdx, barcode, 2, 2, 1, flaneno, fcell, 1, fenddevice, "-", flaneno, fstackno, "-", dtimes, 0, 0);

                                        dbo.ExceSQL(sqlstr);
                                        CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "演示程序出库任务", "条码:" + barcode.ToString(), "自动任务号:" + AutoManageIdx.ToString() + "***" + "货位编码:" + fcell.ToString());

                                    }
                                }



                            }



                        }
                        catch (Exception ee) { }



                    }


                }

            }
            catch (Exception eltt)
            {

            }
            finally
            {

            }
        }

        private void Timer2_Tick(object sender, EventArgs e)
        {
            timer2.Enabled = false;
            try
            
            {
                //string errtext = string.Empty;
                //if (CStaticClass.WcfControl.updatestatus(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
            {
                timer2.Enabled = true;
            }
        }
        /// <summary>
        /// 定时器:定时发送出入库模式 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InOutModelChange_Tick(object sender, EventArgs e)
        {
            if (MITurnOn.Checked == false) return;
            try
            {
                CStaticClass.WcfControl.SendInOutMessageToPlc();
            }
            catch (Exception ex)
            {

            }
        }
    }

}