//using BasicData;
using bizFacade;
//using OpcData;
using System;
using System.Collections;
using System.Data;
using System.Threading;
using System.Windows.Forms;
//using SystemFramework;

using System.Drawing;
//using MesServerWork;
using System.Configuration;
//using MisDataFunction;
using System.Collections.Generic;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Disconnecting;
using MQTTnet.Client.Receiving;
using System.Linq;
using DoWhatPlc;
/// <summary>
/// 
/// </summary>
namespace MisDataSaveDateSim
{

    /// <summary>
    /// 
    /// </summary>
    /// <param name="obj1"></param>
    /// <param name="obj2"></param>
    public delegate void RefreshForm(object obj1, EventArgs obj2);
    /// <summary>
    /// 
    /// </summary>
    public partial class MisData:Form
    {
        /// <summary>
        /// 
        /// </summary>
        public static string BasicDataTableFile = ConfigurationManager.AppSettings["BasicDataTableFile"];
        /// <summary>
        /// 
        /// </summary>
        public static int IsDemoMesServer = Convert.ToInt32(ConfigurationManager.AppSettings["IsDemoMesServer"]);
        /// <summary>
        /// 
        /// </summary>
        public static string MqttUrl = ConfigurationManager.AppSettings["MqttUrl"];
        public static string MqttUrlPLC = ConfigurationManager.AppSettings["MqttUrlPLC"];
        /// <summary>
        /// 
        /// </summary>
        public static string MqttTargetTopic = ConfigurationManager.AppSettings["MqttTargetTopic"];
        public static string MqttTargetTopicPLC = ConfigurationManager.AppSettings["MqttTargetTopicPLC"];
        /// <summary>
        /// 
        /// </summary>
        public static int IsWriteMonitorLog = Convert.ToInt32(ConfigurationManager.AppSettings["IsWriteMonitorLog"]);
        /// <summary>
        /// 
        /// </summary>
        public static string ConnectionString_MES = ConfigurationManager.AppSettings["ConnectionString_MES"];
        /// <summary>
        /// 
        /// </summary>
        public static int WebApiPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WebApiPort"]);
        /// <summary>
        /// 
        /// </summary>
        public static RefreshForm MainFormRefresh, TestPlcStatusDel;
        /// <summary>
        /// 允许使用附加功能的变量，只有在系统开始加载Tag时，才允许读取PLC数据
        /// </summary>
        public static bool AllowLoad;
        /// <summary>
        /// 
        /// </summary>
        public MisData()
        {
            InitializeComponent();

            
         //  CheckForIllegalCrossThreadCalls = false;
          

        }





        private void InitcomboBox_OpNameWebApi()
        {
            List<string> opNameList;
            try
            {
                //全部工位号
                comboBox_OpName.DataSource = opNameList = DtWebApi.OpcDemo.Get_opNameList();


                //FunctionForm_HashiTable.OpName_Hash_Write("OpNameList", opNameList);
                toolStripStatusLabel_WorkStationNum.Text = opNameList.Count.ToString();
                toolStripStatusLabel_DownLine.Text = toolStripStatusLabel_WorkStationNum.Text;
                if (comboBox_OpName.Items.Count > 0)
                {
                    WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString();
                }
            }
            catch { }


        }

        private void listBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            //try
            //{
            //    string cmd;
            //    string opName;
            //    string tagValue;
            //    string[] strList;
            //    if (listBox1.Text != null)
            //    {
            //        strList = listBox1.Text.Split('|');
            //        if (strList.Length >= 4)
            //        {
            //            cmd = strList[1];
            //            opName = strList[2];
            //            tagValue = strList[3];
            //            textBox_Cmd.Text = cmd;
            //            textBox_tagValue.Text = tagValue;
            //        }
            //    }
            //}
            //catch (Exception err)
            //{
            //    ApplicationLog.WriteLog(err, err.Message);

            //}

        }

        private void button_Write_Click(object sender, EventArgs e)
        {
            try
            {
                short tagValue_int;
                string tagValue_str;
                byte tagValue_byte;
                bool tagValue_bool;
                int tagType;
                int tagDataType;
                string cmd = textBox_Cmd.Text;
                string opName = WorkStationNum_Now;
                string tagValue = textBox_tagValue.Text;
                HashtableList htList = DtWebApi.OpcDemo.GetHashtableList();

                tagType = Convert.ToInt32(htList.hashtable_TagType[cmd]);

                tagDataType = Convert.ToInt32(htList.hashtable_TagTypeDataType[tagType.ToString()]);
                switch (tagDataType)
                {
                    case 2:
                        tagValue_int = Convert.ToInt16(tagValue);
                        WriteAnyData_Thread(tagType, opName, tagValue_int);
                        break;
                    case 8:
                        tagValue_str = tagValue.ToString();
                        WriteAnyData_Thread(tagType, opName, tagValue_str);
                        break;
                    case 17:
                        tagValue_byte = Convert.ToByte(tagValue);
                        WriteAnyData_Thread(tagType, opName, tagValue_byte);
                        break;
                    case 11:
                        tagValue_bool = Convert.ToBoolean(Convert.ToInt32(tagValue));
                        WriteAnyData_Thread(tagType, opName, tagValue_bool);
                        break;
                }

            }
            catch (Exception err)
            {
                MessageBox.Show("输入命令异常，请重新输入！");
                //ApplicationLog.WriteLog(err, err.Message);

            }
        }

        private void button_Read_Click(object sender, EventArgs e)
        {
            try
            {
                int tagType;
                string cmd = textBox_Cmd.Text;
                string opName = WorkStationNum_Now;
                string tagValue = textBox_tagValue.Text;

                HashtableList htList = DtWebApi.OpcDemo.GetHashtableList();

                tagType = Convert.ToInt32(htList.hashtable_TagType[cmd]);

                QualityDataQueryStruct QualityStruct = new QualityDataQueryStruct(opName, tagType, textBox_tagValue_Read);
                Thread t = new Thread(new ParameterizedThreadStart(ReadPLC_ByTagType_Thread));
                t.Start(QualityStruct);
            }
            catch (Exception err)
            {
               // ApplicationLog.WriteLog(err, err.Message);

            }
        }

        void ReadPLC_ByTagType_Thread(object obj)
        {
            //try
            //{
            //    QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj;
            //    TextBox tbx = (TextBox)QualityStruct.Ctrl;

            //    tbx.Text = ReadPLC(QualityStruct.tagType, QualityStruct.OpName).ToString();
            //}
            //catch (Exception err)
            //{
            //    ApplicationLog.WriteLog(err, err.Message);
            //}
        }


        bool isWorkStart;
        private void timer_WorkStart_Tick(object sender, EventArgs e)
        {
            //if (isWorkStart)
            //    isWorkStart = false;
            //else
            //    isWorkStart = true;
            //if (isWorkStart)
            //{
            //    textBox_tagValue.Text = "1";
            //    button_Write_Click(null, null);
            //}
            //else
            //{
            //    textBox_tagValue.Text = "0";
            //    button_Write_Click(null, null);
            //}
        }

        private void checkBox_WorkStart_CheckedChanged(object sender, EventArgs e)
        {
            //if (textBox_Cmd.Text == "" && checkBox_WorkStart.Checked)
            //{
            //    MessageBox.Show("请选择命令");
            //    checkBox_WorkStart.Checked = false;
            //    return;
            //}
            //if (checkBox_WorkStart.Checked)
            //{
            //    timer_WorkStart.Enabled = true;
            //    listBox1.Enabled = false;
            //    textBox_Cmd.ReadOnly = true;
            //}
            //else
            //{
            //    timer_WorkStart.Enabled = false;
            //    listBox1.Enabled = true;
            //    textBox_Cmd.ReadOnly = false;
            //}

        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            //timer_WorkStart.Interval = Convert.ToInt32(numericUpDown1.Value) * 1000;
        }

        static Thread ReadQuality_t = null;
        private void ReadQualityData(string opName)
        {
            try
            {
                if (ReadQualityRunning) return;
                ReadQualityRunning = true;
                QualityDataQueryStruct QltyQueryStr = new QualityDataQueryStruct(opName, listView_ShowQualityData);

                ReadQuality_t = new Thread(new ParameterizedThreadStart(ReadQualityData_Thread));
                ReadQuality_t.Start(QltyQueryStr);

            }
            catch (Exception err)
            {
                //ApplicationLog.WriteLog(err, err.Message);

            }
        }
        private void ReadQualityDataUpdate(string opName)
        {
            try
            {
                if (ReadQualityRunning) return;
                ReadQualityRunning = true;
                QualityDataQueryStruct QltyQueryStr = new QualityDataQueryStruct(opName, listView_ShowQualityData);

                ReadQuality_t = new Thread(new ParameterizedThreadStart(ReadQualityData_Thread_Update));
                ReadQuality_t.Start(QltyQueryStr);

            }
            catch (Exception err)
            {
                //ApplicationLog.WriteLog(err, err.Message);

            }
        }
        public QualityDataType[] ThisWorkStationData
        { get; set; }
        static bool ReadQualityRunning = false;
        void ReadQualityData_Thread(object obj)
        {
            int fTime = 0;
            try
            {

                QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj;

                ListView listViewTemp = (ListView)QualityStruct.Ctrl;
                ListViewItem listViewItem = null;
                string[] listViewItemString = new string[5];
                if (listViewTemp.InvokeRequired)
                {
                    Action ActionDelegate = () => { listViewTemp.Items.Clear(); };
                    listViewTemp.Invoke(ActionDelegate);
                }
                else
                {
                    listViewTemp.Items.Clear();
                }

                System.Collections.Concurrent.ConcurrentDictionary<string, object> cd = new System.Collections.Concurrent.ConcurrentDictionary<string, object>();
                List<DoWhatPlc.TagIDTagFormat> cdTagIDTagFormat = null;
                //if (cb_MonitorData.Checked)
                //{

                //    cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupMonitor(QualityStruct.OpName);
                //    //cd = MesWork.PlcLinkForm.ReadPLC_GroupMonitor(QualityStruct.OpName);
                //}
                //if (cb_QdData.Checked)
                //{
                //    cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData_Qd(QualityStruct.OpName);
                //    //cd = MesWork.PlcLinkForm.ReadPLC_GroupData_Qd(QualityStruct.OpName);
                //}
                //if (cb_MonitorData.Checked == false & cb_QdData.Checked == false)
                //{
                //    cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName);
                //    //cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName);
                //}
                //if (cb_MonitorData.Checked == true & cb_QdData.Checked == true)
                //{
                //    cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName);
                //    //cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName);
                //}

                cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName);

                if (cdTagIDTagFormat == null) return;
                foreach (var item in cdTagIDTagFormat)
                {
                    if (!cd.ContainsKey(item.TagID))
                    {
                        cd.TryAdd(item.TagID, item.TF);
                    }
                }
                //排序
                var result2 = from pair in cd orderby pair.Key select pair;
                ThisWorkStationData = new QualityDataType[cd.Count];
                var sortResult2 = from pair in cd orderby pair.Key descending select pair;
                //cd.o.OrderBy(p => p.Value.Speed);
                //foreach (KeyValuePair<string, object> _cd in cd)
                foreach (KeyValuePair<string, object> _cd in result2)
                {
                    var tagID = _cd.Key;
                    var TF = (DoWhatPlc.TagFormat)_cd.Value;

                    listViewItemString[0] = TF.OpName;
                    listViewItemString[3] = TF.TagID;
                    listViewItemString[1] = TF.ItemName;
                    listViewItemString[2] = TF.TagValue.ToString();
                    listViewItemString[4] = TF.TagTypeCodeID.ToString();

                    listViewItem = new ListViewItem(listViewItemString);
                    //if (TF.IsMonitor == 1)
                    //{
                    //   // listViewItem.BackColor = Color.LimeGreen;
                    //}
                    //if (listViewTemp.InvokeRequired)
                    //{
                    //    Action<ListViewItem> ActionDelegate = (x) => { listViewTemp.Items.Add(x); };
                    //    listViewTemp.BeginInvoke(ActionDelegate, listViewItem);
                    //}
                    //else
                    {
                        listViewTemp.Items.Add(listViewItem);
                    }

                    QualityDataType t00 = new QualityDataType();
                    t00.opName = TF.OpName;
                    t00.tagID = TF.TagID;
                    t00.tagTypeID = TF.TagTypeID;
                    t00.tagValue = TF.TagValue;
                    ThisWorkStationData[fTime] = t00;
                    //ThisWorkStationData[fTime].opName = TF.OpName;
                    //ThisWorkStationData[fTime].tagID = TF.TagID;
                    //ThisWorkStationData[fTime].tagTypeID = TF.TagTypeID;
                    //ThisWorkStationData[fTime].tagValue = TF.TagValue;

                    
                       fTime++;

                }
                InitFormBtnColorUpdate();
                ReadQualityRunning = false;
            }
            catch (Exception err)
            {
                ReadQualityRunning = false;
               // ApplicationLog.WriteLog(err, err.Message);

            }



        }

        void ReadQualityData_Thread_Update(object obj)
        {
            try
            {

                QualityDataQueryStruct QualityStruct = (QualityDataQueryStruct)obj;

                ListView listViewTemp = (ListView)QualityStruct.Ctrl;
                ListViewItem listViewItem = null;
                string[] listViewItemString = new string[4];


                System.Collections.Concurrent.ConcurrentDictionary<string, object> cd = new System.Collections.Concurrent.ConcurrentDictionary<string, object>();
                List<DoWhatPlc.TagIDTagFormat> cdTagIDTagFormat = null;
                //if (cb_MonitorData.Checked)
                //{

                //    cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupMonitor(QualityStruct.OpName);
                //    //cd = MesWork.PlcLinkForm.ReadPLC_GroupMonitor(QualityStruct.OpName);
                //}
                //if (cb_QdData.Checked)
                //{
                //    cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData_Qd(QualityStruct.OpName);
                //    //cd = MesWork.PlcLinkForm.ReadPLC_GroupData_Qd(QualityStruct.OpName);
                //}
                //if (cb_MonitorData.Checked == false & cb_QdData.Checked == false)
                //{
                //    cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName);
                //    //cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName);
                //}
                //if (cb_MonitorData.Checked == true & cb_QdData.Checked == true)
                //{
                //    cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName);
                //    //cd = MesWork.PlcLinkForm.ReadPLC_GroupData(QualityStruct.OpName);
                //}
                cdTagIDTagFormat = DtWebApi.OpcDemo.ReadPLC_GroupData(QualityStruct.OpName);

                if (cdTagIDTagFormat == null) return;
                foreach (var item in cdTagIDTagFormat)
                {
                    if (!cd.ContainsKey(item.TagID))
                    {
                        cd.TryAdd(item.TagID, item.TF);
                    }
                }
                //listView_ShowQualityData
                string tagID;
                for(int i=0;i< listView_ShowQualityData.Items.Count;i++)
                {
                    tagID = listView_ShowQualityData.Items[i].SubItems[3].Text;
                    var TF = (DoWhatPlc.TagFormat)cd[tagID];
                    listView_ShowQualityData.Items[i].SubItems[2].Text = TF.TagValue.ToString();
                }

                listView_ShowQualityData.Invalidate();
                ReadQualityRunning = false;
                InitFormBtnColorUpdate();
            }
            catch (Exception err)
            {
                ReadQualityRunning = false;
                // ApplicationLog.WriteLog(err, err.Message);

            }
        }


        public void InitFormBtnColorUpdate()
        {
            try
            {
                //if (!Cbx_StatusDisplay.Checked) return;
                string OpName = WorkStationNum_Now;
                foreach (Control GroupBox in this.groupBox_SignialSimulator.Controls)
                {
                    foreach (Control Btn in GroupBox.Controls)
                    {
                        if (Btn.Name.Length < 8) continue;
                        if (Btn.Name.Substring(0, 8) == "Btn_PLC_" || Btn.Name.Substring(0, 8) == "Btn_MES_")
                        {
                            ControlData Ctrl1 = new ControlData(Btn, OpName);
                            Thread t = new Thread(new ParameterizedThreadStart(InitFormBtn_Thread_Update));
                            t.Start(Ctrl1);
                        }
                    }
                }
            }
            catch (Exception err)
            {
                //ApplicationLog.WriteLog(err, err.Message);

            }


        }

        void InitFormBtn_Thread_Update(Object obj)
        {
            try
            {
                ControlData Btn = (ControlData)obj;

                //test = ReadPLC(Btn.TagType, Btn.opName);

                //bool Result = Convert.ToBoolean(test);
                ListViewItem li = listView_ShowQualityData.Items.Cast<ListViewItem>().First(x => x.SubItems[4].Text == Btn.TagType.ToString() && x.SubItems[0].Text == Btn.opName);
                var result = li.SubItems[2].Text;
                bool Result = false;
                switch (result.ToLower())
                {
                    case "true":
                    case "1":
                        Result = true;
                        break;
                }
                if (Btn.btn.InvokeRequired)
                {
                    Action<System.Drawing.Color> actionDelegate = (x) => { Btn.btn.BackColor = x; };
                    if (Result)
                    {
                        Btn.btn.BeginInvoke(actionDelegate, System.Drawing.Color.Green);
                    }
                    else
                    {
                        Btn.btn.BeginInvoke(actionDelegate, System.Drawing.Color.SlateGray);
                    }
                }
                else
                {
                    if (Result)
                    {
                        Btn.btn.BackColor = System.Drawing.Color.Green;
                    }
                    else
                    {
                        Btn.btn.BackColor = System.Drawing.Color.SlateGray;
                    }
                }
            }
            catch (Exception err)
            {
                ControlData Btn = (ControlData)obj;
                //ApplicationLog.WriteLog(err, err.Message + "采集数据值：" + "；按钮名称：" + test + Btn.btn.Name + "工位号" + WorkStationNum_Now);
            }
        }


        private void button_ReadData_Click(object sender, EventArgs e)
        {
            WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString();
            ReadQualityData(WorkStationNum_Now);

        }


        private void comboBox_OpName_SelectedIndexChanged(object sender, EventArgs e)
        {
            WorkStationNum_Now = comboBox_OpName.SelectedValue.ToString();
            ReadQualityData(WorkStationNum_Now);

        }


        private void listView_ShowQualityData_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                var items = listView_ShowQualityData.SelectedItems;
                QualityDataType SelectData = new QualityDataType();
                ListView.SelectedIndexCollection index = new ListView.SelectedIndexCollection(listView_ShowQualityData);
                SelectData = ThisWorkStationData[index[0]];
                WriteQualityValueForm WriteForm = new WriteQualityValueForm(SelectData, this);
                WriteForm.ShowDialog();
            }
            catch (Exception err)
            {
                //ApplicationLog.WriteLog(err, err.Message);

            }
        }

        private void groupBox_SignialSimulatorBtn_Click(object sender, EventArgs e)
        {
            WriteBoolSignalByFormBtn(sender);
        }

        private void Btn_Write_PLC_Click(object sender, EventArgs e)
        {
            WriteNormalDataBygroupBox_SignialSimulatorWriteBtn(sender);
        }

        private void Btn_Write_MES_Click(object sender, EventArgs e)
        {
            WriteNormalDataBygroupBox_SignialSimulatorWriteBtn(sender);
        }


      

        private void Btn_Read_PLC_Click(object sender, EventArgs e)
        {
            ReadPLC_ProductInfo();

        }

        private void Btn_Read_MES_Click(object sender, EventArgs e)
        {
            ReadMES_ProductInfo();
        }

        private void MisData_FormClosed(object sender, FormClosedEventArgs e)
        {
            //notifyIcon_MIS.Visible = false;
            //this.Dispose();
            //Application.Exit();
            //System.Environment.Exit(0);
        }

        private void toolStripMenuItem_Show_Click(object sender, EventArgs e)
        {
            //this.Show();
            //this.WindowState = FormWindowState.Normal;
            //this.Activate();
        }

        private void toolStripMenuItem_Hide_Click(object sender, EventArgs e)
        {
            //this.Hide();
            //if (PlcChange != null)
            //{

            //    Sencondform.Invoke(SecondFormClose);
            //    ToolStripMenuItem_VWSStatus.Checked = false;

            //}

        }

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



        public static string WorkStationNum_Now;
        private void MisData_FormClosing(object sender, FormClosingEventArgs e)
        {
            //notifyIcon_MIS.Visible = false;
            //if (MessageBox.Show("你确定要退出程序吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            //{
            //    notifyIcon_MIS.Visible = false;
            //    e.Cancel = false;

            //    //判断SecondForm是否关闭
            //    if (PlcChange != null)
            //    {
            //        Sencondform.BeginInvoke(SecondFormClose);
            //    }

            //    StopServer();
            //    MesWork.Mqtt.StopAsync();

            //}
            //else
            //{
            //    notifyIcon_MIS.Visible = true;
            //    e.Cancel = true;

            //}
        }


        private void ToolStripMenuItem_PrintScreen_Click(object sender, EventArgs e)
        {

            //PrintMainForm_Thread();

        }

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

        private void ToolStripMenuItem_SaveLog_Click(object sender, EventArgs e)
        {
            //SavePLCMessage SavePlcMSG = new SavePLCMessage();
            //SavePlcMSG.SavePlcMessage_Thread(richTextBox_MessagePLC.Text);
        }


        private void ToolStripMenuItem_LockForm_Click(object sender, EventArgs e)
        {
            //MainFormLock = new MainAct(LockMainForm);
            //MainFormUnlock = new MainAct(UnLockForm);
            //MainLockConfirm LockConfirm = new MainLockConfirm(this, Sencondform);
            //LockConfirm.ShowDialog();



        }

        private void ToolStripMenuItem_VWSStatus_Click(object sender, EventArgs e)
        {
            //if (PlcChange == null)
            //{
            //    OpenSecondForm_Thread();

            //}
            //else
            //{
            //    Sencondform.BeginInvoke(SecondFormClose);
            //    ToolStripMenuItem_VWSStatus.Checked = false;
            //}

        }




        private void MToolStripMenuItem_AboutMacroinf_Click(object sender, EventArgs e)
        {
            //System.Diagnostics.Process.Start("https://www.meswork.com");
        }

        private void toolStripMenuItem_HVersion_Click(object sender, EventArgs e)
        {
            //VersionsInformation VersionForm = new VersionsInformation();
            //VersionForm.ShowDialog();
        }


        private void MisData_Load(object sender, EventArgs e)
        {

             InitcomboBox_OpNameWebApi();



            //MesWork.Mqtt.StartAsync(MqttUrl);
            //MesWork.Mqtt.mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected);
            //MesWork.Mqtt.mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected);
            //MesWork.Mqtt.mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived);
        }





        bool EToolStripMenuItem_EquipAlarm_Visiable = false;

      

        private void ToolStripMenuItem_HHelp_Click(object sender, EventArgs e)
        {
            //string file = Environment.CurrentDirectory + "\\MisData操作手册.pdf";
            //string str = file.Replace("\\bin\\Debug", "\\PDF\\MisData说明文档.pdf");
            //System.Diagnostics.Process.Start(file);
        }

        /// <summary>
        /// 程序集界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStripMenuItem_Assembly_Click(object sender, EventArgs e)
        {
            //AssemblyManagement AssemblyView = new AssemblyManagement();
            //AssemblyView.ShowDialog();
        }
        //MesWork.OpcForm opcForm = null;
        private void TSM_DebugPage_Click(object sender, EventArgs e)
        {
            //if (opcForm != null)
            //{
            //    opcForm.Close();
            //    opcForm.Dispose();
            //    opcForm = null;
            //}

            //opcForm = new MesWork.OpcForm(IsDemoMesServer);
            //opcForm.Show();


        }

        private void button1_Click(object sender, EventArgs e)
        {
            //WritePLC("71015001", 1);
            //WritePLC("71015002", 1.1);
            //WritePLC("71015003", 2.2);

            //WritePLC("71015004", 0);
            //WritePLC("71015005", 3.3);
            //WritePLC("71015006", 4.4);

        }

        private void label_OpNameList_DoubleClick(object sender, EventArgs e)
        {
            InitcomboBox_OpNameWebApi();
        }

        private void listView_ShowQualityData_Click(object sender, EventArgs e)
        {
            //if (GlobalEventInterface.E_DeviceSignalSimGantt_TransmitTagToDeviceSignalSim != null)
            //{
            //    GlobalEventInterface.E_DeviceSignalSimGantt_TransmitTagToDeviceSignalSim(currTagID, currTagName);
            //}
        }

        private void listView_ShowQualityData_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(listView_ShowQualityData.SelectedItems.Count>0)
            {
                string opName = listView_ShowQualityData.SelectedItems[0].SubItems[0].Text;
                string itemName = listView_ShowQualityData.SelectedItems[0].SubItems[1].Text;
                string tagName = opName + "-"+ itemName;
                string tagID  = listView_ShowQualityData.SelectedItems[0].SubItems[3].Text;
                int tagFrom = 2;
                string tagIDCopy = "";
                if (radioButton_PlcSignl.Checked)
                {
                    textBox_Base_TagID.Text = tagID;
                    //textBox_Base_Item.Text = itemName;
                    //if (GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim != null)
                    //{
                    //    GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim(tagID, tagName, tagFrom, opName, tagIDCopy);
                    //}
                }
                else if(radioButton_PlcSignl_Copy.Checked)
                {
                    tagFrom = 4;
                    if (radioButton_Base.Checked)
                    {
                        textBox_Base_TagID.Text = tagID;
                        textBox_Base_Item.Text = itemName;
                    }
                    else if(radioButton_Copy.Checked)
                    {
                        textBox_Copy_TagID.Text = tagID;
                        textBox_Copy_Item.Text = itemName;
                    }
                    tagID = textBox_Base_TagID.Text;
                    tagName = opName + "-" + textBox_Base_Item.Text+"[拷贝信号："+ textBox_Copy_Item.Text+"]";
                    tagIDCopy = textBox_Copy_TagID.Text;
                    //if (GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim != null)
                    //{
                    //    GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim(tagID, tagName, tagFrom, opName, tagIDCopy);
                    //}
                }
            }
        }

        private void radioButton_PartCodeSanner_Click(object sender, EventArgs e)
        {
            radioButton_Base.Checked = true;
            radioButton_Base.Enabled = false;
            radioButton_Copy.Enabled = false;
            if (radioButton_PartCodeSanner.Checked)
            {
                var tagID = Guid.NewGuid().ToString();
                string opName = comboBox_OpName.Text;
                string tagName = opName + "-" + "扫描条码";
                int tagFrom = 3;
                string tagIDCopy = "";
                //GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim(tagID, tagName, tagFrom, opName,tagIDCopy);
            }
        }

        private void radioButton_PlcSignl_CheckedChanged(object sender, EventArgs e)
        {
            radioButton_Base.Checked = true;
            radioButton_Base.Enabled = false;
            radioButton_Copy.Enabled = false;
        }



        private void radioButton_PlcSignl_Click(object sender, EventArgs e)
        {
            radioButton_Base.Checked = true;
            radioButton_Base.Enabled = false;
            radioButton_Copy.Enabled = false;
        }

        private void radioButton_PlcSignl_Copy_Click(object sender, EventArgs e)
        {
            radioButton_Base.Enabled = true;
            radioButton_Copy.Enabled = true;
            if (listView_ShowQualityData.SelectedItems.Count < 1) return;
            string opName = listView_ShowQualityData.SelectedItems[0].SubItems[0].Text;
            string tagName;
            string tagID ;
            int tagFrom ;
            string tagIDCopy ;

            if (radioButton_PlcSignl_Copy.Checked)
            {
                tagFrom = 4;
                tagID = textBox_Base_TagID.Text;
                tagName = opName + "-" + textBox_Base_Item.Text;
                tagIDCopy = textBox_Copy_TagID.Text;
                //if (GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim != null)
                //{
                //    GlobalEventInterface.E_MisDataPlcTagIDSignal_TransmitTagToDeviceSignalSim(tagID, tagName, tagFrom, opName, tagIDCopy);
                //}
            }
        }

        private void cb_MonitorData_Click(object sender, EventArgs e)
        {

            if (cb_MonitorData.Checked)
            {
                UpdateForm_IsRun = true;
                Thread mythread = new Thread(new ThreadStart(UpdateForm));
                //将线程设为后台运行
                mythread.IsBackground = true;
                mythread.Start();
            }
            else
            {
                UpdateForm_IsRun = false;
            }

        }

        private void timer_ReadTagValues_Tick(object sender, EventArgs e)
        {
          //  UpdateForm();
        }
        bool UpdateForm_IsRun = false;
        private void UpdateForm()
        {
            while(UpdateForm_IsRun)
            {
                if (listView_ShowQualityData.Items.Count > 0)
                {
                    ReadQualityDataUpdate(WorkStationNum_Now);
                }
                else
                {
                    ReadQualityData(WorkStationNum_Now);
                }
                InitFormBtnColorUpdate();
                Thread.Sleep(1500);

            }

        }
        private void EToolStripMenuItem_EquipAlarm_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    if (!EToolStripMenuItem_EquipAlarm.Checked)
            //    {

            //        groupBox_WorkStationQuality.Width = 307;
            //        groupBox_WorkStationQuality.Height = 313;
            //        listView_ShowQualityData.Width = 294;
            //        listView_ShowQualityData.Height = 234;
            //        button_ReadData_Click(null, null);
            //        groupBox_Alarm.Visible = true;
            //        EToolStripMenuItem_EquipAlarm.Checked = true;
            //        EToolStripMenuItem_EquipAlarm_Visiable = true;
            //    }
            //    else
            //    {
            //        groupBox_Alarm.Visible = false;

            //        groupBox_WorkStationQuality.Width = 307;
            //        groupBox_WorkStationQuality.Height = 642;
            //        listView_ShowQualityData.Width = 294;
            //        listView_ShowQualityData.Height = 572;
            //        button_ReadData_Click(null, null);
            //        EToolStripMenuItem_EquipAlarm.Checked = false;
            //    }
            //}
            //catch (Exception err)
            //{
            //    ApplicationLog.WriteLog(err, err.Message);

            //}
        }

    }
}
