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.Net;
using DotNetSAPI;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Runtime.Serialization;
using CommonLib;
namespace wcfControlMonitorClient
{

    public partial class FrmClient : Form, WcfControlMonitor.IControlMonitorCallback
    {
        //protected override CreateParams CreateParams
        //{

        //    get
        //    {

        //        CreateParams cp = base.CreateParams;

        //        cp.ExStyle |= 0x02000000;//WS_CLIPCHILDREN   两个窗体叠加时,重叠部分不重绘
        //        return cp;

        //    }

        //}
        int timersum = 0;//20150103增加断网恢复
        Model.MDevice devinfo;
        FrmDeviceStatus _deviceStatus = new FrmDeviceStatus();
        FrmWorkstationStatus _worstation = new FrmWorkstationStatus();
        StringBuilder sql = new StringBuilder();
        DBFactory.DBOperator dbo = CStaticClass.dbo;
        DBFactory.DBOperator dbo1 = new DBFactory.DBOperator();
        SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
        public SpVoice Voice;// = new SpVoice();
        public Model.MDevice[] devlist;
        public int devsn = 0;
        private static FrmClient _formInstance;
        public static FrmClient FormInstance
        {
            get
            {
                if (_formInstance == null)
                {
                    _formInstance = new FrmClient();
                }
                return _formInstance;
            }
            set { _formInstance = value; }
        }
        FrmTaskList Frmlist;
        public FrmClient()
        {
            CommonClassLib.CCarryConvert.WriteDarkCasket("Login", "操作日志", "FrmClient()", "", "");
            InitializeComponent();
            try
            {
                //初始化管理和调度交互状态
                Model.CGetInfo.AddIOControlStatus();
                Model.CGetInfo.AddDeviceKindInfo();
                Model.CGetInfo.AddDeviceInfo();
                Model.CGetInfo.AddDeviceErrors();
                devlist = Model.CGetInfo.DeviceInfo.Values.ToArray<Model.MDevice>();

                DataView dv0 = dbo.ExceSQL("SELECT distinct F_S7Connection,F_DBWGetLength FROM T_Base_Device WHERE (F_DeviceKindIndex = 28)").Tables[0].DefaultView;
                if (dv0.Count > 0)
                {
                    for (int i = 0; i < dv0.Count; i++)
                    {
                        if (CStaticClass.MutiS7ConnReturns.ContainsKey(dv0[i]["F_S7Connection"].ToString()) == false)
                        {
                            CStaticClass.MutiS7ConnReturns.Add(dv0[i]["F_S7Connection"].ToString(), new int[Convert.ToInt32(dv0[i]["F_DBWGetLength"])]);
                        }
                    }
                }

                CStaticClass.SystemName = CommonClassLib.AppSettings.GetValue("SystemName");
                this.notifyIcon1.Text = CStaticClass.SystemName;
                this.Text = CStaticClass.SystemName;
                OPCClient.CCommonOPCClient.Hostname = CommonClassLib.AppSettings.GetValue("HostName");
                OPCClient.CCommonOPCClient.ProgID = CommonClassLib.AppSettings.GetValue("OPCProgID");


                #region 客户端订阅初始化20120428

                DataView dvx;
                DataView dv = dbo.ExceSQL("SELECT F_ReadSubscription, F_DeviceIndex, F_DBW2Address, F_DBWGetLength, F_S7Connection, F_SplitByte FROM T_Base_Device WHERE (F_ReadSubscription IS NOT NULL) AND (F_ReadSubscription =F_DeviceIndex) ORDER BY F_ReadSubscription").Tables[0].DefaultView;

                for (int i = 0; i < dv.Count; i++)
                {
                    dvx = dbo.ExceSQL(string.Format("SELECT (MAX(F_DBW2Address) + F_DBWGetLength) AS maxdbw2 FROM T_Base_Device WHERE (F_ReadSubscription = '{0}')  AND (F_DeviceKindIndex <> 33) GROUP BY F_DBWGetLength ORDER BY maxdbw2 DESC", dv[i]["F_ReadSubscription"])).Tables[0].DefaultView;
                    if (dvx.Count > 0)
                    {
                        if (Convert.ToInt32(dv[i]["F_ReadSubscription"]) == 19001)
                        { }
                        if (CStaticClass.MutiReadSubscriptionDeviceStateReturns.ContainsKey(dv[i]["F_ReadSubscription"].ToString()) == false)
                        {
                            CStaticClass.MutiReadSubscriptionDeviceStateReturns.Add(dv[i]["F_ReadSubscription"].ToString(), new int[Convert.ToInt32(dvx[0]["maxdbw2"]) - Convert.ToInt32(dv[i]["F_DBW2Address"])]);
                        }

                    }
                }
                dv = dbo.ExceSQL("SELECT F_ReadSubscription, F_DeviceIndex, F_DBW2Address, F_DBWGetLength, F_S7Connection, F_SplitByte FROM T_Base_Device WHERE (F_ReadSubscription IS NOT NULL) AND (F_DeviceKindIndex=33)  ORDER BY F_ReadSubscription").Tables[0].DefaultView;

                for (int i = 0; i < dv.Count; i++)
                {
                    if (CStaticClass.MutiReadSubscriptionDeviceSplitReturns.ContainsKey(dv[i]["F_ReadSubscription"].ToString()) == false)
                    {
                        CStaticClass.MutiReadSubscriptionDeviceSplitReturns.Add(dv[i]["F_ReadSubscription"].ToString(), new int[Convert.ToInt32(dv[i]["F_DBWGetLength"])]);
                    }
                }

            }
            catch (Exception ex)
            {
                CommonClassLib.CCarryConvert.WriteDarkCasket("Login", "操作日志", "FrmClient()-catch", ex.StackTrace, ex.Message);
                throw ex;
            }
            #endregion
            #region WeifenLuo
            FrmControlMonitor.FormInstance.Show(this.dockPanel1);
            FrmControlMonitor.FormInstance.DockTo(this.dockPanel1, DockStyle.Fill);
            FrmControlMonitor.FormInstance.AutoScroll = true;
            Frmlist = new FrmTaskList();

            Frmlist.Show(this.dockPanel1);

            Frmlist.DockTo(this.dockPanel1, DockStyle.Bottom);
            Frmlist.DockState = WeifenLuo.WinFormsUI.Docking.DockState.DockBottomAutoHide;
            //Frmlist.AutoHidePortion = 0.125;// (double)Frmlist.Height / (double)this.dockPanel1.Height;
            Frmlist.CloseButton = false;

            // 20110104
            FrmErrorMessage frmErrorMessage = new FrmErrorMessage();
            frmErrorMessage.Show(this.dockPanel1);
            frmErrorMessage.DockTo(this.dockPanel1, DockStyle.Bottom);
            frmErrorMessage.DockState = WeifenLuo.WinFormsUI.Docking.DockState.DockBottomAutoHide;
            //Frmlist.AutoHidePortion = 0.125;// (double)Frmlist.Height / (double)this.dockPanel1.Height;
            frmErrorMessage.CloseButton = false;

            FrmHelp frmHelp = new FrmHelp();

            frmHelp.Show(this.dockPanel1);

            frmHelp.DockTo(this.dockPanel1, DockStyle.Bottom);
            frmHelp.DockState = WeifenLuo.WinFormsUI.Docking.DockState.DockBottomAutoHide;
            //Frmlist.AutoHidePortion = 0.125;// (double)Frmlist.Height / (double)this.dockPanel1.Height;
            frmHelp.CloseButton = false;
            #endregion

        }
        /// <summary>
        /// 客户端事件响应20120428
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void CCommon_UpdateDB(object sender, CUpdateDBChangeEventArgs e)
        {
            if (!CStaticClass.client.IsDisposed)//CStaticClass.WCFOK == true &&
            {
                string errtext = string.Empty;
                this.BeginInvoke(new MethodInvoker(delegate ()
                { DealWithDeviceState(out errtext, e.Deviceindex, e.SplitbyteValue, e.Devicestates); }));

            }
        }
        /// <summary>
        /// 客户端事件响应处理函数20120428
        /// </summary>
        /// <param name="errtext"></param>
        /// <param name="deviceindex"></param>
        /// <param name="splitbyteValue"></param>
        /// <param name="devicestates"></param>
        /// <returns></returns>
        bool DealWithDeviceState(out string errtext, int deviceindex, byte[] splitbyteValue, byte[] devicestates)
        {//deviceindex设备组代表的订阅,首先把设备组按照F_DBW2Address由小到大排序,拆分到具体每个设备
            if ((splitbyteValue == null) && (devicestates == null))
            {//20120420
                errtext = OPCClient.CCommonOPCClient.OpcError;
                SendMessage(string.Format("tsStatus@FrmClient.DealWithDeviceState时,订阅组:{0}发生异常,{1}!", deviceindex, errtext));

                return false;
            }

            errtext = string.Empty; DataView dv = new DataView(); DataView dvsp = new DataView(); DataView dvbc = new DataView();
            int devicebegin = 0; int DBW2Addressbegin = 0; int SplitBytebegin = 0; string S7Connection = string.Empty;
            int SplitByteLength = 0;
            try
            {
                StringBuilder sql = new StringBuilder(string.Format("SELECT F_DeviceIndex, F_DBW2Address, F_DBWGetLength, F_SplitByte,F_S7Connection,F_ManTaskReserve  FROM T_Base_Device WHERE (F_DeviceKindIndex <>33) AND (F_ReadSubscription = '{0}') AND (F_DBW2Address IS NOT NULL) ORDER BY F_DBW2Address", deviceindex));
                dv = dbo1.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    devicebegin = Convert.ToInt32(dv[0]["F_DeviceIndex"]);
                    DBW2Addressbegin = Convert.ToInt32(dv[0]["F_DBW2Address"]);
                    //SplitBytebegin = Convert.ToInt32(dv[0]["F_SplitByte"]);
                    S7Connection = dv[0]["F_S7Connection"].ToString();
                    sql = new StringBuilder(string.Format("SELECT F_DeviceIndex, F_DBW2Address, F_DBWGetLength, F_SplitByte,F_S7Connection,F_ManTaskReserve  FROM T_Base_Device WHERE  (F_DeviceKindIndex =33) AND (F_ReadSubscription = '{0}') ORDER BY F_DBW2Address", deviceindex));

                    dvsp = dbo1.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                    if (dvsp.Count > 0)
                    {
                        SplitByteLength = Convert.ToInt32(dvsp[0]["F_DBWGetLength"]);
                    }
                }
                else
                {
                    sql = new StringBuilder(string.Format("SELECT F_DeviceIndex, F_DBW2Address, F_DBWGetLength, F_SplitByte,F_S7Connection,F_ManTaskReserve  FROM T_Base_Device WHERE (F_DeviceIndex = '{0}') AND (F_DBW2Address IS NOT NULL) ORDER BY F_DBW2Address", deviceindex));
                    dv = dbo1.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                    if (dv.Count > 0)
                    {

                        devicebegin = Convert.ToInt32(dv[0]["F_DeviceIndex"]);
                        DBW2Addressbegin = Convert.ToInt32(dv[0]["F_DBW2Address"]);
                        // SplitBytebegin = Convert.ToInt32(dv[0]["F_SplitByte"]);
                        S7Connection = dv[0]["F_S7Connection"].ToString();
                        sql = new StringBuilder(string.Format("SELECT F_DeviceIndex, F_DBW2Address, F_DBWGetLength, F_SplitByte,F_S7Connection,F_ManTaskReserve  FROM T_Base_Device WHERE  (F_DeviceKindIndex =33) AND (F_ReadSubscription = '{0}') ORDER BY F_DBW2Address", deviceindex));
                        dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                        if (dv.Count > 0)
                        {
                            SplitByteLength = Convert.ToInt32(dv[0]["F_DBWGetLength"]);
                        }
                    }
                    else
                    {//20120420
                        errtext = string.Format("FrmClient.DealWithDeviceState时,订阅组:{0}对应的设备索引不存在!", deviceindex);
                        SendMessage(string.Format("tsStatus@FrmClient.DealWithDeviceState时,订阅组:{0}对应的设备索引不存在!", deviceindex));
                        return false;
                    }
                }
                #region 旧版协议,单独连接取得光电信号
                //if (splitbyteValue != null)
                //{
                //    Array.Copy(splitbyteValue, CStaticClass.MutiReadSubscriptionDeviceSplitReturns[deviceindex.ToString()], splitbyteValue.Length);
                //    dvsp = dbo1.ExceSQL(string.Format("SELECT F_DeviceIndex, F_DBW2Address, F_DBWGetLength, F_SplitByte FROM T_Base_Device WHERE (F_DeviceKindIndex <>31) AND(F_DeviceKindIndex <>33) AND (F_S7Connection  = '{0}') AND (F_DBW2Address IS NOT NULL and F_SplitByte  IS NOT NULL and F_SplitByte >={1} and   F_SplitByte <{1}+{2}) ORDER BY F_DBW2Address", S7Connection, SplitBytebegin,SplitByteLength)).Tables[0].DefaultView;
                //    for (int i = 0; i < dvsp.Count; i++)
                //    {
                //        devinfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(dvsp[i]["F_DeviceIndex"]));

                //        int delta = Convert.ToInt32(dvsp[i]["F_SplitByte"]) - SplitBytebegin;
                //        if (delta < 0) continue;
                //        devinfo.SplitByte_0 = (splitbyteValue[delta] & 1) == 1 ? 1 : 0;
                //        devinfo.SplitByte_1 = (splitbyteValue[delta] & 2) == 2 ? 1 : 0;
                //        devinfo.SplitByte_2 = (splitbyteValue[delta] & 4) == 4 ? 1 : 0;
                //        devinfo.SplitByte_3 = (splitbyteValue[delta] & 8) == 8 ? 1 : 0;
                //        devinfo.SplitByte_4 = (splitbyteValue[delta] & 16) == 16 ? 1 : 0;
                //        devinfo.SplitByte_5 = (splitbyteValue[delta] & 32) == 32 ? 1 : 0;
                //        devinfo.SplitByte_6 = (splitbyteValue[delta] & 64) == 64 ? 1 : 0;
                //        devinfo.SplitByte_7 = (splitbyteValue[delta] & 128) == 128 ? 1 : 0;
                //        Model.CGetInfo.SetDeviceInfo(devinfo);


                //    }
                //}
                #endregion
                int tempdb2addr = 0; StringBuilder sss = new StringBuilder(); StringBuilder barcode = new StringBuilder();
                if (devicestates != null)
                {

                    Array.Copy(devicestates, CStaticClass.MutiReadSubscriptionDeviceStateReturns[deviceindex.ToString()], devicestates.Length);
                    for (int di = 0; di < dv.Count; di++)
                    {

                        int devidx = Convert.ToInt32(dv[di]["F_DeviceIndex"]);
                        devinfo = Model.CGetInfo.GetDeviceInfo(devidx);
                        int taskindex = 0;
                        int state = 0;
                        if (devinfo.DeviceKind == 31)
                        {//解析南京14所得高端自动化的是否有物信号,高位低位信号(I/O信号字节填写在状态字节的后面)
                            #region 解析高端设备状态及探物
                            devinfo = Model.CGetInfo.GetDeviceInfo(devidx);
                            state = (devicestates[tempdb2addr + 0] & 1) == 1 ? 1 : 0;
                            devinfo.SplitByte_0 = (devicestates[tempdb2addr + 4] & 1) == 1 ? 1 : 0;
                            devinfo.SplitByte_1 = (devicestates[tempdb2addr + 4] & 2) == 2 ? 1 : 0;
                            devinfo.SplitByte_2 = (devicestates[tempdb2addr + 4] & 4) == 4 ? 1 : 0;
                            devinfo.SplitByte_3 = (devicestates[tempdb2addr + 4] & 8) == 8 ? 1 : 0;
                            devinfo.SplitByte_4 = (devicestates[tempdb2addr + 4] & 16) == 16 ? 1 : 0;
                            devinfo.SplitByte_5 = (devicestates[tempdb2addr + 4] & 32) == 32 ? 1 : 0;
                            devinfo.SplitByte_6 = (devicestates[tempdb2addr + 4] & 64) == 64 ? 1 : 0;
                            devinfo.SplitByte_7 = (devicestates[tempdb2addr + 4] & 128) == 128 ? 1 : 0;
                            if (devinfo.RunState != 4)//20121203
                            {
                                if (state == 1)
                                {

                                    devinfo.RunState = 0;
                                }
                                else
                                {//0,1,2

                                    devinfo.RunState = 1;


                                    devinfo.ErrorCode = state;


                                }
                            }


                            #region 设备被停用时,不显示真实状态20120820
                            //if (ccf.GetDeviceLockedState(devidx) == -1) devinfo.RunState = 4;//20121203
                            #endregion
                            Model.CGetInfo.SetDeviceInfo(devinfo);
                            //CDeviceStateChangeEventArgs csce = new CDeviceStateChangeEventArgs(devinfo);
                            //OnDeviceState("SControlMonitor.DealWithDeviceState", csce);
                            #endregion
                        }
                        else
                        {
                            //以下代码重新开发CStaticClass.MutiS7ConnReturns改为按照F_ReadSubscription
                            if (devinfo.Dbw2Getlength > 3)
                            {
                                tempdb2addr = Convert.ToInt32(dv[di]["F_DBW2Address"]) - DBW2Addressbegin;
                                taskindex = (devicestates[tempdb2addr + 2] << 8) + devicestates[tempdb2addr + 3];
                                if (devinfo.Dbw2Getlength > 1)
                                {
                                    state = devicestates[tempdb2addr + 1];
                                }
                            }
                            int devkind = devinfo.DeviceKind;
                            #region 新版标准协议,取得设备光电信号
                            int byteprio = 0;
                            switch (devkind)
                            {
                                case 1:
                                    byteprio = 13;
                                    break;
                                case 2:
                                    byteprio = 4;
                                    break;
                                case 4:
                                    byteprio = 8;
                                    break;
                                default:
                                    byteprio = 0;
                                    break;
                            }

                            if (byteprio > 0)
                            {
                                devinfo.SplitByte_0 = (devicestates[tempdb2addr + byteprio] & 1) == 1 ? 1 : 0;
                                devinfo.SplitByte_1 = (devicestates[tempdb2addr + byteprio] & 2) == 2 ? 1 : 0;
                                devinfo.SplitByte_2 = (devicestates[tempdb2addr + byteprio] & 4) == 4 ? 1 : 0;
                                devinfo.SplitByte_3 = (devicestates[tempdb2addr + byteprio] & 8) == 8 ? 1 : 0;
                                devinfo.SplitByte_4 = (devicestates[tempdb2addr + byteprio] & 16) == 16 ? 1 : 0;
                                devinfo.SplitByte_5 = (devicestates[tempdb2addr + byteprio] & 32) == 32 ? 1 : 0;
                                devinfo.SplitByte_6 = (devicestates[tempdb2addr + byteprio] & 64) == 64 ? 1 : 0;
                                devinfo.SplitByte_7 = (devicestates[tempdb2addr + byteprio] & 128) == 128 ? 1 : 0;
                            }
                            #endregion
                            if (state >= 30)
                            {
                                devinfo.ErrorCode = state;
                                devinfo.RunState = 2;
                            }
                            else
                            {//0,1,2
                                if (state == 2)
                                {
                                    devinfo.RunState = 5;
                                }
                                else
                                {
                                    devinfo.RunState = state;
                                }

                                devinfo.ErrorCode = state;


                            }
                            devinfo.TaskNo = taskindex;
                            if ((devinfo.DeviceKind == 1) || (devinfo.DeviceKind == 4))
                            {
                                devinfo.XCoor = devicestates[tempdb2addr + 7] + (devicestates[tempdb2addr + 6] << 8) + (devicestates[tempdb2addr + 5] << 16) + (devicestates[tempdb2addr + 4] << 32);//X坐标
                                if (devinfo.DeviceKind == 1)
                                {
                                    devinfo.YCoor = devicestates[tempdb2addr + 11] + (devicestates[tempdb2addr + 10] << 8) + (devicestates[tempdb2addr + 9] << 16) + (devicestates[tempdb2addr + 8] << 32);//Y坐标
                                }
                            }
                            Model.CGetInfo.SetDeviceInfo(devinfo);
                        }

                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                SendMessage(string.Format("tsStatus@FrmClient.DealWithDeviceState时{0}", ex.StackTrace + ex.Message));

                errtext = string.Format("tsStatus@FrmClient.DealWithDeviceState时{0}", ex.StackTrace + ex.Message);
                return false;
            }
            finally
            {
                dv.Dispose();
                dvbc.Dispose();
                dvsp.Dispose();
            }
        }

        #region wcf回调
        public void SendDeviceInfo(Model.MDevice devinfo)
        {
            try
            {

                if (CStaticClass.WCFOK == false) return;
                if (this.IsDisposed) return;

                Model.CGetInfo.SetDeviceInfo(devinfo);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public IAsyncResult BeginSendDeviceInfo(Model.MDevice devinfo, AsyncCallback acb, object state)
        {

            return state as IAsyncResult;

        }
        public void EndSendDeviceInfo(IAsyncResult ar)
        {

        }
        public IAsyncResult BeginSendMessage(string message, AsyncCallback acb, object state)
        {

            return state as IAsyncResult;

        }
        public void EndSendMessage(IAsyncResult ar)
        {

        }
        public void SendMessage(string message)
        {


            char[] cc = new char[1] { '@' };
            string[] strsplit = message.Split(cc);
            if (strsplit.GetLength(0) > 1)
            {//更新指定控件
                if (strsplit[0] == "tsStatus")
                {
                    if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf(strsplit[1]) < 0)
                    {
                        FrmControlMonitor.FormInstance.FlashPanit("tsStatus", strsplit[1], true);

                    }
                    //tsStatus.Text = strsplit[1];

                }
                else if (strsplit[0] == "notifyIcon1")
                {
                    this.BeginInvoke(new MethodInvoker(delegate ()
                    {
                        notifyIcon1.BalloonTipText = strsplit[1];
                        notifyIcon1.ShowBalloonTip(10000, "警告:", strsplit[1], ToolTipIcon.Warning);
                    }));
                }
            }
            //else
            //{//刷新数据显示
            //    this.dgvManager.BeginInvoke(new MethodInvoker(delegate()
            //    {
            //        sql.Remove(0, sql.Length);
            //        sql.Append("select * from V_Manage_Task where ").Append(CStaticClass.Manstatus);
            //        this.dgvManager.DataSource = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
            //    }));
            //    this.dgvMonitor.BeginInvoke(new MethodInvoker(delegate()
            //    {
            //        sql.Remove(0, sql.Length);
            //        sql.Append("select * from V_Monitor_Task where ").Append(CStaticClass.Monstatus).Append(" order by 设备指令索引 asc ");

            //        this.dgvMonitor.DataSource = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
            //    }));

            //}




        }

        //20140824richard
        public void SendOrderMessage(Model.MonitorInfo mi)
        {

            this.BeginInvoke(new MethodInvoker(delegate ()
            {
                try
                {
                    if (CStaticClass.UserID.ToUpper() == "SA")
                    {
                        CStaticClass.Order = mi.Orderturnon;
                        CStaticClass.ObtainManageTask = mi.Obtaintask;
                        if (CStaticClass.Order == true)
                        {
                            ClickOrderTurnOn();
                        }
                        else
                        {
                            ClickOrderTurnOff();
                        }
                        if (CStaticClass.ObtainManageTask == true)
                        {
                            ClickObtainTask();
                        }
                        else
                        {
                            ClickStopObtainTask();
                        }
                    }
                }
                catch (Exception ex)
                {


                    if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("接收【获取任务和命令开关】广播时:" + ex.Message) < 0)
                    {
                        FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "接收【获取任务和命令开关】广播时:" + ex.Message, true);

                    }
                    //if (tsStatus.Text.IndexOf("接收【获取任务和命令开关】广播时:" + ex.Message) < 0)
                    //{
                    //    tsStatus.ForeColor = Color.Red;
                    //    this.tsStatus.Text += "接收【获取任务和命令开关】广播时:" + ex.Message;
                    //}

                }
            }));



        }
        public IAsyncResult BeginSendOrderMessage(Model.MonitorInfo mi, AsyncCallback callBack, object state)
        {
            return state as IAsyncResult;
        }
        public void EndSendOrderMessage(IAsyncResult ar)
        {

        }
        //20140824richard


        #endregion
        private void Client_FormClosing(object sender, FormClosingEventArgs e)
        {

            if (MessageBox.Show("您确认要关闭" + CStaticClass.SystemName + "吗?", "操作提示:", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.OK)
            {
                e.Cancel = true;
                return;
            }
            try
            {
                ClientLogout();
                OPCClient.CCommonOPCClient.DisConnectOPCServer();//20120428

            }
            catch (Exception ex)
            {

            }
            finally
            {
                FrmLogin.FormInstance.Close();
            }
        }
        void LogCallBack(IAsyncResult ar)
        {
            try
            {
                string strErr = string.Empty;
                if (CStaticClass.WcfControl.EndLogoutClient(out strErr, ar) == true)
                {
                    //if (ar.AsyncState.ToString() == "RegisterClientCallBack")
                    //{
                    //    CStaticClass.WcfControl.BeginRegisterClient(CStaticClass.UserID, "客户端:" + CStaticClass.ClientID + ",用户名:" + CStaticClass.UserID, new AsyncCallback(RegisterClientCallBack), null);
                    //    return;
                    //}
                }
                CStaticClass.WCFOK = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void ClientLogout()
        {
            try
            {
                string errtext = string.Empty;
                CStaticClass.WcfControl.BeginLogoutClient("客户端:" + CStaticClass.ClientID + ",用户名:" + CStaticClass.UserID, new AsyncCallback(LogCallBack), "");
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

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

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

        private void MIManageShow_Click(object sender, EventArgs e)
        {
            FrmAutoCommand.FormInstance.Show();
        }

        private void MIAltMonitor_Click(object sender, EventArgs e)
        {
            FrmModifyMonitor.FormInstance.Show();
        }

        private void MIAltManange_Click(object sender, EventArgs e)
        {
            //FrmModifyManage.FormInstance.ShowDialog();
            FrmModifyManage.FormInstance.Show();
        }

        private void notifyIcon1_BalloonTipShown(object sender, EventArgs e)
        {
            try
            {
                if (null == Voice)
                {
                    Voice = new SpVoice();
                }
                Voice.Speak(notifyIcon1.BalloonTipText, SpFlags);

            }
            catch
            {

            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (CStaticClass.WCFOK == true)
            {
                this.TopMost = true;
                this.Visible = true;
                this.TopMost = false;
                this.WindowState = FormWindowState.Maximized;
            }
        }

        private void tsStatus_TextChanged(object sender, EventArgs e)
        {

        }








        void BuildHandTaskCallBack(IAsyncResult ar)
        {
            string errtext = string.Empty;

            if (CStaticClass.WcfControl.EndBuildHandTask(out errtext, ar) == false)
            {
                //MessageBox.Show(errtext, "操作提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void Client_Load(object sender, EventArgs e)
        {
            try
            {


                //if (CStaticClass.UserID.ToUpper() == "SA")
                //{
                //    this.MMmasterAdmin.Visible = true;
                //}
                //else
                //{
                this.MMmasterAdmin.Visible = false;
                //}
                CommonClassLib.CCarryConvert.WriteDarkCasket("Login", "操作日志", "FrmClient()-准备CreateSubscriptionGroup", "", "");
                OPCClient.CCommonOPCClient.CreateSubscriptionGroup();
                CommonClassLib.CCarryConvert.WriteDarkCasket("Login", "操作日志", "FrmClient()-CreateSubscriptionGroup", "", "");
                OPCClient.CCommonOPCClient.UpdateDB += new CUpdateDBEventHandler(CCommon_UpdateDB);
                if (OPCClient.CCommonOPCClient.OpcError != null)
                {
                    MessageBox.Show(OPCClient.CCommonOPCClient.OpcError);
                }

                #region 添加输送机、穿梭车和堆垛机的单击事件///XAMG



                foreach (PictureBox ctrl in this.groupBox1.Controls.OfType<PictureBox>())

                {

                    if ((ctrl.GetType().ToString() == "System.Windows.Forms.PictureBox") && (ctrl.Tag != null) && (ctrl.Enabled == true))
                    {
                        //ctrl.Click += new EventHandler(ctrl_ClickPic);
                        //ctrl.MouseEnter += new EventHandler(Btn_MouseEnter);

                        //CDDT6增加联机停车按钮

                        if (!ctrl.Tag.ToString().Contains("."))
                        {
                            ctrl.Click += new EventHandler(ctrl_Click_1);
                            ctrl.MouseEnter += new EventHandler(Btn_MouseEnter_Stop);
                        }
                        else
                        {
                            //ctrl.Click += new EventHandler(ctrl_ClickPic);
                            ctrl.MouseEnter += new EventHandler(Btn_MouseEnter);
                        }
                    }
                }


                #endregion
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        private void Btn_MouseEnter_Stop(object sender, EventArgs e)
        {
            string deviceindex = (sender as Control).Tag.ToString();
            devinfo = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(deviceindex));
            if (devinfo != null)
            {
                if (devinfo.SplitByte_6 == 1)
                {
                    deviceindex = string.Format("{0}-未联机停车", devinfo.DeviceIndex);
                }
                if (devinfo.SplitByte_6 == 0)
                {
                    deviceindex = string.Format("{0}-联机停车中", devinfo.DeviceIndex);
                }
            }
            toolTip_DeviceIndex.SetToolTip(sender as Control, deviceindex);
        }

        private void Btn_MouseEnter(object sender, EventArgs e)
        {
            int deviceindex;
            string[] DS; char[] dd = new char[1] { '.' };
            string msg = (sender as Control).Tag.ToString();

            DS = msg.Split(dd);
            if (DS.Length > 0)
            {
                if (int.TryParse(DS[0], out deviceindex))
                {
                    devinfo = Model.CGetInfo.GetDeviceInfo(deviceindex);

                    if (devinfo != null)
                    {
                        msg = devinfo.DeviceName;

                    }

                }
            }


            toolTip_DeviceIndex.SetToolTip(sender as Control, msg);
        }
        private void ctrl_Click_1(object sender, EventArgs e)
        {
            PictureBox px = (PictureBox)sender;
            int DeviceIndexForRunButton = Convert.ToInt32(px.Name.ToString().Substring(px.Name.Length - 5, 5));

            Model.MDevice deviceRun = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(px.Tag.ToString()));
            int iValue = 0;
            iValue = deviceRun.SplitByte_6 == 1 ? 0 : 1;
            CStaticClass.WcfControl.BeginSendDeviceReset(DeviceIndexForRunButton, iValue, new AsyncCallback(SendDeviceResetCallBack), iValue);

        }
        void SendDeviceResetCallBack(IAsyncResult ar)
        {
            string errtext = string.Empty;

            if (CStaticClass.WcfControl.EndSendDeviceReset(out errtext, ar) == false)
            {
                MessageBox.Show(errtext, "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void MIDeviceState_Click(object sender, EventArgs e)
        {
            FrmDeviceInfoEdit.FormInstance.Show();
        }

        private void MIRouteInfo_Click(object sender, EventArgs e)
        {
            FrmRouteEdit.FormInstance.Show();
        }

        private void MIWaitTime_Click(object sender, EventArgs e)
        {
            FrmWaitTime.FormInstance.Show();
        }

        private void MIMonitorConnectInfo_Click(object sender, EventArgs e)
        {
            FrmConnectDB.FormInstance.ConnectType = "Monitor";
            FrmConnectDB.FormInstance.Show();
        }

        private void MIIOStation_Click(object sender, EventArgs e)
        {
            FrmIOStation.FormInstance.Show();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //if (CStaticClass.WCFOK == false) return;
            try
            {
                if (CStaticClass.WcfControl != null)
                {
                    if (CStaticClass.WcfControl.State == CommunicationState.Faulted)
                    {

                        MMServerStatus.Image = wcfControlMonitorClient.Properties.Resources.linkerror;

                        MMServerStatus.ToolTipText = "与服务端连接失败";

                        CStaticClass.WCFOK = false;
                        ReConnectAndRegisterClient();//20160115添加断线重连功能
                    }
                    else
                    {
                        MMServerStatus.Image = wcfControlMonitorClient.Properties.Resources.linkok;
                        //MMServerStatus.Image = wcfControlMonitorClient.Properties.Resources.linkerror;
                        MMServerStatus.ToolTipText = "与服务端连接成功";
                        CStaticClass.WcfControl.BeginHeartbeat(new AsyncCallback(CallBackHeartbeat), null);
                    }
                }



                //devsn++;
                //if (devsn < devlist.Count())
                //{
                //    CStaticClass.WcfControl.BeginSendAllDeviceStates(devlist[devsn].DeviceIndex, new AsyncCallback(SendAllDeviceStatesCallback), null);
                //}
                //else
                //{
                //    devsn = 0;
                //    CStaticClass.WcfControl.BeginSendAllDeviceStates(devlist[devsn].DeviceIndex, new AsyncCallback(SendAllDeviceStatesCallback), null);

                //}
            }
            catch (Exception ex)
            {
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("BeginHeartbeat时:" + ex.Message) < 0)
                {
                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "BeginHeartbeat时:" + ex.Message, true);

                }

                //if (tsStatus.Text.IndexOf("BeginHeartbeat时:" + ex.Message) < 0)
                //{
                //    tsStatus.ForeColor = Color.Red;
                //    this.tsStatus.Text += "BeginHeartbeat时:" + ex.Message;
                //}
                MMServerStatus.Image = wcfControlMonitorClient.Properties.Resources.linkerror;

                CStaticClass.WCFOK = false;
                ReConnectAndRegisterClient();//20160115添加断线重连功能
            }
        }
        public void SendAllDeviceStatesCallback(IAsyncResult ar)
        {
            try
            {
                Model.MDevice dev;
                dev = CStaticClass.WcfControl.EndSendAllDeviceStates(ar);
                if (dev != null)
                {
                    //if(dev.DeviceKind!=1)
                    //{
                    Model.CGetInfo.SetDeviceInfo(dev);
                    //}
                }
                devsn++;
                if (devsn < devlist.Count())
                {
                    CStaticClass.WcfControl.BeginSendAllDeviceStates(devlist[devsn].DeviceIndex, new AsyncCallback(SendAllDeviceStatesCallback), null);
                }
                else
                {
                    //devsn=0;
                    //CStaticClass.WcfControl.BeginSendAllDeviceStates(devlist[devsn].DeviceIndex, new AsyncCallback(SendAllDeviceStatesCallback), null);

                }
            }
            catch (Exception ex)
            {
                this.BeginInvoke(new MethodInvoker(delegate ()
                {
                    if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("SendAllDeviceStatesCallback时:" + ex.Message) < 0)
                    {
                        FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "SendAllDeviceStatesCallback时:" + ex.Message, true);

                    }
                    //   if (tsStatus.Text.IndexOf("SendAllDeviceStatesCallback时:" + ex.Message) < 0)
                    //{
                    //    tsStatus.ForeColor = Color.Red;
                    //    this.tsStatus.Text += "SendAllDeviceStatesCallback时:" + ex.Message;
                    //} 
                }));

                ReRegisterClient();
            }
        }


        private void MITransportTimeout_Click(object sender, EventArgs e)
        {
            FrmTransportTimeout.FormInstance.Show();
        }

        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 MIUserInfoManage_Click(object sender, EventArgs e)
        {
            FrmUsers.FormInstance.Show();
        }

        private void MIAltPassword_Click(object sender, EventArgs e)
        {
            FrmPassword.FormInstance.Show();
        }

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

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

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

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


        private void ctrl_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            _deviceStatus.DeviceIndex = Convert.ToInt32(btn.Tag);
            _deviceStatus.ShowDialog();
        }
        private void ctrl_ClickTxt(object sender, EventArgs e)
        {
            TextBox txt = (TextBox)sender;
            _worstation.DeviceIndex = Convert.ToInt32(txt.Tag);
            _worstation.ShowDialog();
        }
        private void ctrl_ClickPic(object sender, EventArgs e)
        {
            PictureBox btn = (PictureBox)sender;
            _deviceStatus.DeviceIndex = Convert.ToInt32(btn.Tag);
            _deviceStatus.ShowDialog();
        }
        void ReConnectAndRegisterClient()
        {
            try
            {
                CStaticClass.ClientID = Dns.GetHostName();

                var ctx = new InstanceContext(CStaticClass.client);
                CStaticClass.WcfControl = new WcfControlMonitor.ControlMonitorClient(ctx);

                string errtext = string.Empty;
                CommonClassLib.CCarryConvert.WriteDarkCasket("Login", "UserID:" + CStaticClass.UserID + "的操作日志", "尝试重新连接", "", "");
                CStaticClass.WcfControl.BeginRegisterClient(CStaticClass.UserID, "客户端:" + CStaticClass.ClientID + ",用户名:" + CStaticClass.UserID, new AsyncCallback(ReConnectAndRegisterClientCallBack), null);
            }
            catch (Exception ex)
            {

                throw ex;
            }


        }
        void ReConnectAndRegisterClientCallBack(IAsyncResult ar)
        {
            try
            {

                string ErrText = string.Empty;
                if (false == CStaticClass.WcfControl.EndRegisterClient(out ErrText, ar))
                {
                    //MessageBox.Show(ErrText, "登陆错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    CStaticClass.WCFOK = false;

                    return;
                }

                CommonClassLib.CCarryConvert.WriteDarkCasket("Login", "UserID:" + CStaticClass.UserID + "的操作日志", "重连**成功登录系统", "", "");



                //CStaticClass.WcfControl.BeginSendAllDeviceStates(CStaticClass.client.devlist[0].DeviceIndex, new AsyncCallback(CStaticClass.client.SendAllDeviceStatesCallback), null);
                CStaticClass.WCFOK = true;

            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "登陆错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                CStaticClass.WCFOK = false;

                return;
            }
        }

        void ReRegisterClient()
        {
            //CStaticClass.ClientID = Dns.GetHostName();

            //var ctx = new InstanceContext(CStaticClass.client);
            //CStaticClass.WcfControl = new WcfControlMonitor.ControlMonitorClient(ctx);

            //string errtext = string.Empty;

            //CStaticClass.WcfControl.BeginRegisterClient(CStaticClass.UserID, "客户端:" + CStaticClass.ClientID + ",用户名:" + CStaticClass.UserID, new AsyncCallback(RegisterClientCallBack), null);
        }

        void RegisterClientCallBack(IAsyncResult ar)
        {
            try
            {
                string ErrText;
                if (CStaticClass.WcfControl.EndRegisterClient(out ErrText, ar) == true)
                {
                    CStaticClass.WCFOK = true;
                    devsn++;
                    if (devsn < devlist.Count())
                    {
                        CStaticClass.WcfControl.BeginSendAllDeviceStates(devlist[devsn].DeviceIndex, new AsyncCallback(SendAllDeviceStatesCallback), null);
                    }
                    else
                    {
                        devsn = 0;
                        CStaticClass.WcfControl.BeginSendAllDeviceStates(devlist[devsn].DeviceIndex, new AsyncCallback(SendAllDeviceStatesCallback), null);

                    }
                }
                else
                {
                    CStaticClass.WcfControl.BeginLogoutClient("客户端:" + CStaticClass.ClientID + ",用户名:" + CStaticClass.UserID, new AsyncCallback(LogCallBack), "RegisterClientCallBack");

                    this.BeginInvoke(new MethodInvoker(delegate ()
                    {
                        if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("EndRegisterClient时:" + ErrText) < 0)
                        {
                            FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "EndRegisterClient时:" + ErrText, true);

                        }
                        //if (tsStatus.Text.IndexOf("EndRegisterClient时:" + ErrText) < 0)
                        // {
                        //     tsStatus.ForeColor = Color.Red;
                        //     this.tsStatus.Text += "EndRegisterClient时:" + ErrText;
                        // } 
                    }));

                }
            }
            catch (Exception ex)
            {
                this.BeginInvoke(new MethodInvoker(delegate ()
                {
                    if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("EndRegisterClient时:" + ex.Message) < 0)
                    {
                        FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "EndRegisterClient时:" + ex.Message, true);

                    }
                    //   if (tsStatus.Text.IndexOf("EndRegisterClient时:" + ex.Message) < 0)
                    //{
                    //    tsStatus.ForeColor = Color.Red;
                    //    this.tsStatus.Text += "EndRegisterClient时:" + ex.Message;
                    //} 
                }));


            }

        }



        private void MIStartRetrieveTask_Click(object sender, EventArgs e)
        {
            try
            {
                ClickObtainTask();
                CStaticClass.WcfControl.BeginObtainTask("", "UPDATE", new AsyncCallback(CallbackObtainTask), null);
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private void MIStopRetrieveTask_Click(object sender, EventArgs e)
        {
            try
            {
                ClickStopObtainTask();
                CStaticClass.WcfControl.BeginStopObtainTask(new AsyncCallback(CallbackStopObtainTask), null);
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void MITurnOn_Click(object sender, EventArgs e)
        {

            try
            {
                ClickOrderTurnOn();
                CStaticClass.WcfControl.BeginOrderTurnOn(new AsyncCallback(CallbackTurnOn), null);
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

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

                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

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

        void CallbackObtainTask(IAsyncResult ar)
        {
            CStaticClass.WcfControl.EndObtainTask(ar);
        }
        void CallbackStopObtainTask(IAsyncResult ar)
        {
            CStaticClass.WcfControl.EndStopObtainTask(ar);
        }
        void CallbackTurnOn(IAsyncResult ar)
        {
            CStaticClass.WcfControl.EndOrderTurnOn(ar);
        }
        void CallbackTurnOff(IAsyncResult ar)
        {
            CStaticClass.WcfControl.EndOrderTurnOff(ar);
        }
        void CallBackHeartbeat(IAsyncResult ar)
        {
            this.BeginInvoke(new MethodInvoker(delegate ()
                   {
                       try
                       {
                           string errtext = string.Empty;
                           Model.MonitorInfo mi;
                           CStaticClass.WcfControl.EndHeartbeat(out mi, ar);
                           if (CStaticClass.UserID.ToUpper() == "SA")
                           {
                               CStaticClass.Order = mi.Orderturnon;
                               CStaticClass.ObtainManageTask = mi.Obtaintask;
                               if (mi.Orderturnon == true)
                               {
                                   ClickOrderTurnOn();
                               }
                               else
                               {
                                   ClickOrderTurnOff();
                               }
                               if (mi.Obtaintask == true)
                               {
                                   ClickObtainTask();
                               }
                               else
                               {
                                   ClickStopObtainTask();
                               }
                           }
                           if (mi.S7connectOnline.Count > 0)
                           {
                               if (mi.S7connectOnline.ContainsKey("S7 connection_2") && mi.S7connectOnline["S7 connection_2"] == 0)
                               {
                                   MMPLCStatus1.Image = wcfControlMonitorClient.Properties.Resources.linkok;
                                   MMPLCStatus1.ToolTipText = "与PLC连接成功";
                               }
                               else
                               {
                                   MMPLCStatus1.Image = wcfControlMonitorClient.Properties.Resources.linkerror;
                                   MMPLCStatus1.ToolTipText = "与PLC连接失败";
                               }

                               if (mi.S7connectOnline.ContainsKey("S7 connection_2") && mi.S7connectOnline["S7 connection_2"] == 0)
                               {
                                //MMPLCStatus2.Image = wcfControlMonitorClient.Properties.Resources.linkok;
                                //MMPLCStatus2.ToolTipText = "与PLC连接成功";
                            }
                               else
                               {
                                //MMPLCStatus2.Image = wcfControlMonitorClient.Properties.Resources.linkerror;
                                //MMPLCStatus2.ToolTipText = "与PLC连接失败";
                            }

                            //if (mi.S7connectOnline["S7 connection_3"] > 0)
                            //{
                            //    MMPLCStatus3.Image = wcfControlMonitorClient.Properties.Resources.linkerror;
                            //    MMPLCStatus3.ToolTipText = "与PLC连接失败";
                            //}
                            //else
                            //{
                            //    MMPLCStatus3.Image = wcfControlMonitorClient.Properties.Resources.linkok;
                            //    MMPLCStatus3.ToolTipText = "与PLC连接成功";
                            //}
                            //foreach (string ip in mi.TcpIPInitCount.Keys.ToArray())
                            //{
                            //    if (mi.TcpIPInitCount[ip] == 0)
                            //    {

                            //        MMPLCStatus4.Image = wcfControlMonitorClient.Properties.Resources.linkok;
                            //    }
                            //    else
                            //    {
                            //        MMPLCStatus4.Image = wcfControlMonitorClient.Properties.Resources.linkerror;
                            //    }

                            //}

                        }
                           else
                           {
                               MMPLCStatus1.Image = wcfControlMonitorClient.Properties.Resources.linkerror;
                               MMPLCStatus1.ToolTipText = "与PLC连接失败";
                            //MMPLCStatus2.Image = wcfControlMonitorClient.Properties.Resources.linkerror;
                            //MMPLCStatus2.ToolTipText = "与PLC连接失败";
                            //MMPLCStatus3.Image = wcfControlMonitorClient.Properties.Resources.linkerror;
                            //MMPLCStatus3.ToolTipText = "与PLC连接失败";
                            //MMPLCStatus4.Image = wcfControlMonitorClient.Properties.Resources.linkerror;
                        }
                       }
                       catch (Exception ex)
                       {
                           if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("CallBackHeartbeat时:" + ex.Message) < 0)
                           {
                               FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "CallBackHeartbeat时:" + ex.Message, true);

                           }
                        //if (tsStatus.Text.IndexOf("CallBackHeartbeat时:" + ex.Message) < 0)
                        //{
                        //    tsStatus.ForeColor = Color.Red;
                        //    this.tsStatus.Text += "CallBackHeartbeat时:" + ex.Message;
                        //}


                        ReRegisterClient();
                       }
                   }));

        }

        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 MISystemInit2_Click(object sender, EventArgs e)
        {

            FrmSystemInit.FormInstance.Show();
        }

        private void MIManageConnectInfo_Click(object sender, EventArgs e)
        {
            FrmConnectDB.FormInstance.ConnectType = "Manage";
            FrmConnectDB.FormInstance.Show();
        }
        public bool IsEquals(Array array1, Array array2, int arraylength)
        {//20090902新增加arraylength
            //比较类型是否一样 
            if ((array1 == null) || (array2 == null)) return false;
            if (!Object.ReferenceEquals(array1.GetType(), array2.GetType()))
            {
                return false;
            }

            //比较长度是否一样 
            if (array1.GetLength(0) != array2.GetLength(0))
            {
                return false;
            }

            //比较成员是否对应相等 
            ValueType v1, v2;
            for (int i = 0; i < arraylength; i++)
            {
                v1 = (ValueType)array1.GetValue(i);
                v2 = (ValueType)array2.GetValue(i);

                if (!v1.Equals(v2))
                {
                    return false;
                }
            }
            return true;
        }
        string GetBarcodeFromMonitorIndex(int taskindex)
        {
            DataView dvb = new DataView(); StringBuilder sss = new StringBuilder("");
            try
            {

                sss.Append("SELECT  F_TxtParam FROM T_Monitor_Task WHERE (F_MonitorIndex = ").Append(taskindex).Append(")");
                dvb = dbo.ExceSQL(sss.ToString()).Tables[0].DefaultView;
                if (dvb.Count > 0)
                {
                    return dvb[0]["F_TxtParam"].ToString();
                }
                else
                {
                    return "-";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dvb.Dispose();
            }
        }
        int GetMonitorRunTaskIndexFromBarCode(StringBuilder BarCode)
        {//20110216
            DataView dv = new DataView();
            try
            {
                string bc = BarCode.ToString();

                dv = dbo1.ExceSQL(string.Format("SELECT T_Monitor_Task.F_MonitorIndex FROM T_Base_Device,T_Monitor_Task WHERE  T_Base_Device.F_DeviceIndex = T_Monitor_Task.F_DeviceIndex and ((T_Base_Device.F_DeviceKindIndex = 13) OR (T_Base_Device.F_DeviceKindIndex = 31)) and (F_TxtParam = '{0}')  and F_Status>0 order by F_MonitorIndex asc", bc)).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0]["F_MonitorIndex"]);
                }
                else
                {

                    return -1;

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv.Dispose();
            }
        }
        int GetMonitorAskTaskIndexFromBarCode(StringBuilder BarCode)
        {//20110216
            DataView dv = new DataView();
            try
            {
                string bc = BarCode.ToString();

                dv = dbo.ExceSQL(string.Format("SELECT T_Monitor_Task.F_MonitorIndex FROM T_Base_Device,T_Monitor_Task WHERE  T_Base_Device.F_DeviceIndex = T_Monitor_Task.F_DeviceIndex and ((T_Base_Device.F_DeviceKindIndex = 13) OR (T_Base_Device.F_DeviceKindIndex = 31)) and (F_TxtParam = '{0}')  and ((F_Status>0) or (F_SendFlag=2 and F_Status=0)) and F_DeviceCommandIndex=6 order by F_MonitorIndex asc", bc)).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0]["F_MonitorIndex"]);
                }
                else
                {

                    return -1;

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv.Dispose();
            }
        }
        int GetMonitorTaskIndexFromBarCode(StringBuilder BarCode, Model.MDevice devinf)
        {//20110216
            DataView dv = new DataView();
            try
            {
                string bc = BarCode.ToString();

                dv = dbo.ExceSQL(string.Format("SELECT T_Monitor_Task.F_MonitorIndex FROM T_Base_Device,T_Monitor_Task WHERE  T_Base_Device.F_DeviceIndex = T_Monitor_Task.F_DeviceIndex and ((T_Base_Device.F_DeviceKindIndex = 13) OR (T_Base_Device.F_DeviceKindIndex = 31)) and (F_TxtParam = '{0}') and (F_NumParam4 = {1} or F_NumParam4 = {2}) and F_Status>0 order by F_MonitorIndex asc", bc, devinf.DeviceIndex, devinf.DeviceVisual)).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    return Convert.ToInt32(dv[0]["F_MonitorIndex"]);
                }
                else
                {
                    //dv = dbo.ExceSQL(string.Format("SELECT T_Monitor_Task.F_MonitorIndex FROM T_Base_Device,T_Monitor_Task WHERE  T_Base_Device.F_DeviceIndex = T_Monitor_Task.F_DeviceIndex and ((T_Base_Device.F_DeviceKindIndex = 13) OR (T_Base_Device.F_DeviceKindIndex = 31)) and (F_TxtParam = '{0}')  and F_Status>0 order by F_MonitorIndex asc", bc)).Tables[0].DefaultView;
                    //if (dv.Count > 0)
                    //{
                    //    return Convert.ToInt32(dv[0]["F_MonitorIndex"]);
                    //}
                    //else
                    //{
                    return -1;
                    //}
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv.Dispose();
            }
        }
        string GetMonitorTaskStartTime(int taskindex, out int order)
        {//20110216
            DataView dv = new DataView();
            try
            {
                dv = dbo.ExceSQL(string.Format("SELECT F_StartTime,F_DeviceCommandIndex FROM T_Monitor_Task WHERE  F_MonitorIndex={0}", taskindex)).Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    order = Convert.ToInt32(dv[0]["F_DeviceCommandIndex"]);
                    return dv[0]["F_StartTime"].ToString();
                }
                else
                {
                    order = -1;
                    return "-";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dv.Dispose();
            }
        }

        private void MIZCKSetIO_Click(object sender, EventArgs e)
        {
            FrmZCKSetIOStation.FormInstance.Show();
        }

        private void MIErrorSolutions_Click(object sender, EventArgs e)
        {//20151120
            FrmDeviceErrorSolutions.FormInstance.Show();
        }

        private void MITaskCount_Click(object sender, EventArgs e)
        {//20151120
            FrmTaskManage.FormInstance.Show();
        }

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

        private void MIBrowseInterface_Click(object sender, EventArgs e)
        {

            FrmBrowseInterFace.FormInstance.Show();
        }

        private void MIBrowseActivation_Click(object sender, EventArgs e)
        {
            FrmBrowseActivation.FormInstance.Show();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //label1.Text = CStaticClass.WcfControl.State.ToString();
            ////if (CStaticClass.WcfControl.State == CommunicationState.Faulted)
            ////{
            ////}
        }

        private void MIActivation_Click(object sender, EventArgs e)
        {
            FrmBrowseActivation.FormInstance.Show();
        }

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

        private void MIErrorSolutions_Click_1(object sender, EventArgs e)
        {
            FrmDeviceErrorSolutions.FormInstance.Show();
        }

        private void MIApplyHistory_Click(object sender, EventArgs e)
        {
            FrmBrowseApplyLog.FormInstance.Show();
        }

        private void timerFlash_Tick(object sender, EventArgs e)
        {
            foreach (PictureBox ctrl in this.groupBox1.Controls.OfType<PictureBox>())
            {
                if (ctrl.Enabled == false) continue;
                Model.MDevice device = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(ctrl.Tag));
                if (device == null)
                {//20100108

                    continue;
                }
                #region 联机停车
                if (!ctrl.Tag.ToString().Contains("."))
                {
                    device = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(ctrl.Name.ToString().Substring(ctrl.Name.Length - 5, 5)));
                    if (device == null)
                    {//20100108

                        continue;
                    }
                    if (device.DeviceKind == 40)
                    {
                        device = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(ctrl.Tag));

                    }
                    DataView dvRunDevice = dbo.ExceSQL("select f_deviceindex from t_base_device where f_devicekindindex = 1 or f_devicekindindex = 4").Tables[0].DefaultView;
                    for (int i = 0; i < dvRunDevice.Count; i++)
                    {
                        if (ctrl.Tag.ToString() == dvRunDevice[i]["f_deviceindex"].ToString())
                        {
                            Model.MDevice deviceRun = Model.CGetInfo.GetDeviceInfo(Convert.ToInt32(ctrl.Tag.ToString()));
                            if (deviceRun.SplitByte_6 == 1)
                            {
                                ctrl.Image = wcfControlMonitorClient.Properties.Resources.StopButtonUp;

                            }
                            else
                            {
                                ctrl.Image = wcfControlMonitorClient.Properties.Resources.StopButtonDown;
                            }

                        }
                    }
                }
                #endregion
            }
        }



    }
}