using DataLinkMesWork;
using MesDataFunction;
using MesServerWork;
using MesWork.PLC;
using MQTTnet;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Disconnecting;
using MQTTnet.Client.Receiving;
using MQTTnet.Extensions.ManagedClient;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using SystemFramework;
using System.IO;
using System.Net;
using System.Text;
using MesServerFunctions;
using System.Threading.Tasks;
using MesWork;
using System.Drawing;
using MES_SIGNAL_CONF;
using SlMesDbIterface;
using System.Security.Policy;
using MisDataFunDll;


//写死工位号的地方：OP170质量数据、OP150打印机、OP100扫码
//Function 1056 添加判断工位 300 工位 直接给工作完成 其他给允许工作
//Function 1055 扫码完成 自动触发 拧紧判断 不然不知道咋进去

namespace MisDataSaveDate
{
    /// <summary>
    /// 
    /// </summary>
    public partial class MesServerMisDataFun : Form
    {
        public static string WebSvrUrlPort = ConfigurationManager.AppSettings["Url_WebApi"];
        public static int IsWriteMonitorLog = Convert.ToInt32(ConfigurationManager.AppSettings["IsWriteMonitorLog"]);
        public static string OnlineCheckDataUrl = ConfigurationManager.AppSettings["OnlineCheckDataUrl"].ToString();
        public static string ConnectionString_MES = ConfigurationManager.AppSettings["ConnectionString_MES"];
        public static int IsDemoMesServer = Convert.ToInt32(ConfigurationManager.AppSettings["IsDemoMesServer"]);
        public static string IsRecordTagStatus = ConfigurationManager.AppSettings["IsRecordTagStatus"];
        public static string BasicDataTableFile = ConfigurationManager.AppSettings["BasicDataTableFile"];
        public static string PrintURL = ConfigurationManager.AppSettings["PrintURL"];

        /// <summary>
        /// 
        /// </summary>
        InitServer initServer = null;
        /// <summary>
        /// 
        /// </summary>
        static Hashtable hashtableTopicList = new Hashtable();
        /// <summary>
        /// 
        /// </summary>
        static bool OnLineMqtt = false;
        /// <summary>
        /// 
        /// </summary>
        static bool OnLine_SQL = false;
        /// <summary>
        /// 
        /// </summary>
        static bool OnLine_Print = false;
        /// <summary>
        /// 
        /// </summary>
        static bool IsLoopReadShow = false;
        /// <summary>
        /// 允许使用附加功能的变量，只有在系统开始加载Tag时，才允许读取PLC数据
        /// </summary>
        public static bool AllowLoad;
        /// <summary>
        /// 
        /// </summary>
        MesWork.OpcForm opcForm = null;
        /// <summary>
        /// 
        /// </summary>
        public static string WorkStationNum_Now;
        /// <summary>
        /// 
        /// </summary>
        DateTime StartTime;

        public static Color color_Faw = Color.FromArgb(0, 44, 101);//蓝色，大众：0,44,101

        public static Color color_Good = Color.FromArgb(132, 185, 235);//浅蓝，自定义
        public static Color color_Wait = Color.FromArgb(240, 230, 140);//淡黄，显示等待状态
        public static Color color_Bad = SystemColors.ActiveBorder;//灰色，显示操作过程
        public static Color color_Control = SystemColors.Control;//控件默认颜色
        public static Color color_Grey = Color.FromArgb(192, 192, 192);//灰色，Table底色

        public static Color color_Green = Color.FromArgb(22, 161, 136);//绿色
        public static Color color_Yellow = Color.FromArgb(246, 227, 74);//黄色
        public static Color color_Red = Color.FromArgb(255, 0, 0);//红色

        [STAThread]
        static void Main()
        {
            new System.Threading.Mutex(true, "MES_ZK_SVR", out bool bCanRun);
            if (!bCanRun)
            {
                MessageBox.Show("MES中控程序 已经在运行！不可重复启动！");
                return;
            }
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MesServerMisDataFun());
            //new MES_CONF().ShowDialog();
        }



        public MesServerMisDataFun()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            Never_Know.Hello_You_All_Never_Know = Hello_You_All_Never_Know;

            PP.ConnectionString_MES = ConnectionString_MES;
            PP.PrintURL = PrintURL;
            PP.IsDemoMesServer = IsDemoMesServer;
            ApplicationConfig.ConnectionString_MES = ConnectionString_MES;

            CommunicationCheckOnLine();

            var dt_Signal = MisDataFunDll.MisDataFun.dt_Signal();
            var dt_Device = MisDataFunDll.MisDataFun.dt_Device();
            var dt_TagTypeDataType = MisDataFunDll.MisDataFun.dt_TagTypeDataType();

            Get_SpecialOpList();

            var sql =
       $" SELECT [工位号],[工位名称],[PLC],[PLC代码],[MesDll]" +
       $" FROM [MES_计划BOM_工位与名称] WHERE [工位类型] = 0" +
       $" ORDER BY [工位号]";
            SqlOperation.ExecuteSql(sql, out DataTable dt_SqlOp, out string errorSqlOp);
            dgv_OpName.DataSource = dt_SqlOp;

            var mp = new MesWorkPlc();

            StartTime = Convert.ToDateTime(toolStripStatusLabel_StartTime.Text = DateTime.Now.ToString());
            mp.LoadOPCData(dt_Signal, dt_Device, IsDemoMesServer, IsWriteMonitorLog, true, false, out string error);
            if (error.Length > 0 )
            {
                MessageBox.Show($"信号加载报错：{error}");
                Process.GetCurrentProcess().Kill();
            }

            MesDataFunction.LoadTagTypeCodeID.Load(dt_TagTypeDataType);

            //查询出“全部原始基本数据列表”
            var drs = MesWork.PlcLinkForm.dt_BasicData.Select($"是否启用 = 1 and 变量类型代码=101 or 变量类型代码 = 102  or 变量类型代码 = 105");
            if (drs.Length > 1)
            {
                MIS_BASE.BasicDataTagValue = MesWork.PlcLinkForm.dt_BasicData.Select($"是否启用 = 1 and 变量类型代码=101 or 变量类型代码 = 102  or 变量类型代码 = 105").CopyToDataTable<DataRow>();
                if (MIS_BASE.BasicDataTagValue.Columns.Contains("上限值"))
                {
                    MIS_BASE.BasicDataTagValue.Columns["上限值"].ColumnName = "值上限";
                }
                if (MIS_BASE.BasicDataTagValue.Columns.Contains("下限值"))
                {
                    MIS_BASE.BasicDataTagValue.Columns["下限值"].ColumnName = "值下限";
                }
            }

            // BasicDataTagValue = MesWork.PlcLinkForm.dt_BasicData.Select($"是否启用 = 1 and 监控属性代码 = '{DataLinkMesWork.ApplicationConfig.MES_Code.ToString()}'").CopyToDataTable<DataRow>();
            //查询出“MES_基本数据_测量范围”
            MesServerWork.MIS_BASE.BasicDataTagValueUpDown = MesWork.PlcLinkForm.dt_BasicData;
            if (MesServerWork.MIS_BASE.BasicDataTagValueUpDown.Columns.Contains("上限值"))
            {
                MesServerWork.MIS_BASE.BasicDataTagValueUpDown.Columns["上限值"].ColumnName = "值上限";
            }
            if (MesServerWork.MIS_BASE.BasicDataTagValueUpDown.Columns.Contains("下限值"))
            {
                MesServerWork.MIS_BASE.BasicDataTagValueUpDown.Columns["下限值"].ColumnName = "值下限";
            }
            // 模拟时，写入质量数据
            if (IsDemoMesServer == 1)
            {
                InitBasicDataTagValue();
            }

            // 变量代码与其他字段的对应关系
            MesServerWork.MIS_BASE.InitHashtableTagID();
            toolStripStatusLabel_WorkStationNum.Text = MesWork.PlcLinkForm.opNameList.Count.ToString();

            AllowLoad = true;
            if (IsDemoMesServer == 1)
            {
                toolStripStatusLabel_RunningStatus.Text = "变量模拟";
                toolStripStatusLabel_RunningStatus.BackColor = System.Drawing.Color.Yellow;
            }
            else
            {
                toolStripStatusLabel_RunningStatus.Text = "PLC";
                toolStripStatusLabel_RunningStatus.BackColor = System.Drawing.Color.Green;
            }
            MesWorkPlc.D_OPCTagData_TagDataOnChangeMIS -= OPCTagData_TagDataOnChange;
            MesWorkPlc.D_OPCTagData_TagDataOnChangeMIS += OPCTagData_TagDataOnChange;



            MIS_BASE.InitHashtable_MesServerCode();


            // 获得Function调用信息
            MisDataFunDll.MisDataFun.GetMesServerCodeAndMesDll(out MisDataFunDll.MisDataFun.hashtable_MesServerCode, out MisDataFunDll.MisDataFun.hashtable_MesDll);
            MisDataFunDll.MisDataFun.GetBaseData_tagTable_TagName(out MisDataFunDll.MisDataFun.hashtable_TagName, out MisDataFunDll.MisDataFun.hashtable_TagTypeTagName);
            FuntionMesRead.GetAlarmInit();

        }

        // 获取特殊工位列表
        static public void Get_SpecialOpList()
        {
            string procedureName = "MES_特殊工位定义表_查询";
            SqlParameter[] thisParms = new SqlParameter[0];
            DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms, out DataTable dt);
            var specialOpList = new Dictionary<string, string[]>();
            foreach (DataRow row in dt.Rows)
            {
                string type = row["type"].ToString();
                string[] opList = row["opList"].ToString().Split(',');
                specialOpList[type] = opList;
            }

            PP.SpecialOpList = specialOpList;
        }


        public void SaveData_Load(object sender, EventArgs e)
        {
            MyLog4Net.MyLogHelper.LogCommit += MyLogHelper_LogCommit;
            MqttLink();
            initServer = new InitServer(WebSvrUrlPort);
            Thread.Sleep(200);
            MesWorkPlc.StartServer();      //开启监控服务
            new TaskFactory().StartNew(delegate ()
            {
                DataTable dt;
                MisDataFunDll.MisDataFun.Alarm_Moby_Search(out dt);
                DataTable dt1 = MisDataFunDll.MisDataFun.GetCheckOpName();
                for (int i = 0; i < dt1.Rows.Count; i++)
                {
                    string opName = dt1.Rows[i]["工位号"].ToString();
                    FuntionMesRead.Alarm_Insert_Init(opName);
                }
            });
        }
        /// <summary>
        /// 模拟时，写入质量数据
        /// </summary>
        private void InitBasicDataTagValue()
        {
            string tagID;
            double tagValue;
            //写工位总合格标志  变量类型代码=21
            for (int i = 0; i < MesWork.PlcLinkForm.dt_BasicData.Rows.Count; i++)
            {
                if (MesWork.PlcLinkForm.dt_BasicData.Rows[i]["变量类型代码"].ToString() == "21")
                {
                    tagID = MesWork.PlcLinkForm.dt_BasicData.Rows[i]["TagID"].ToString();
                    MesServerWork.MIS_BASE.Write_TagID(tagID, 1);
                }
            }
            if (MesServerWork.MIS_BASE.BasicDataTagValue != null)
            {
                for (int i = 0; i < MesServerWork.MIS_BASE.BasicDataTagValue.Rows.Count; i++)
                {
                    try
                    {
                        switch (Convert.ToInt32(MesServerWork.MIS_BASE.BasicDataTagValue.Rows[i]["变量排序"]))
                        {

                            case 0:
                                tagID = MesServerWork.MIS_BASE.BasicDataTagValue.Rows[i]["TagID"].ToString();
                                MesServerWork.MIS_BASE.Write_TagID(tagID, 1);
                                break;
                            case 1:
                            case 2:
                            case 3:
                                tagID = MesServerWork.MIS_BASE.BasicDataTagValue.Rows[i]["TagID"].ToString();
                                tagValue = Convert.ToDouble(MesServerWork.MIS_BASE.BasicDataTagValue.Rows[i]["列位置"]) * 100
                                    + Convert.ToDouble(MesServerWork.MIS_BASE.BasicDataTagValue.Rows[i]["变量排序"]) / 100;
                                MesServerWork.MIS_BASE.Write_TagID(tagID, tagValue);
                                break;
                         
                        }
                    }
                    catch { }
                }
            }
        }

        #region mqtt相关
        private async Task MqttLink()
        {
            List<MqttTopicFilter> TopicFilterList = new List<MqttTopicFilter>();
            string url;
            string TopicList;
            string[] TopicListFunItems;
            string[] TopicListItems;
            url = ConfigurationManager.AppSettings["MqttUrl"];
            TopicList = ConfigurationManager.AppSettings["TopicList"];
            TopicListItems = TopicList.Split('|');
            for (int i = 0; i < TopicListItems.Length; i++)
            {
                TopicListFunItems = TopicListItems[i].Split(',');
                hashtableTopicList.Add(TopicListFunItems[0], TopicListFunItems[1]);
            }

            await Mqtt.StartAsync();

            foreach (var topic in TopicListItems)
            {
                TopicListFunItems = topic.Split(',');

                Mqtt.mqttClient.SubscribeAsync(new MqttTopicFilter { Topic = TopicListFunItems[0] });
            }
            Mqtt.mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnSubscriberConnected);
            Mqtt.mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnSubscriberDisconnected);
            Mqtt.mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnSubscriberMessageReceived);

        }
        private string Hello_You_All_Never_Know(string[] args)
        {
            return Guid.NewGuid().ToString() + Guid.NewGuid().ToString();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="x"></param>
        private void OnSubscriberConnected(MqttClientConnectedEventArgs x)
        {
            MyLog4Net.MyLogHelper.Info("Mqtt：", "Mqtt连接成功！");
            OnLineMqtt = true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="x"></param>
        private void OnSubscriberDisconnected(MqttClientDisconnectedEventArgs x)
        {
            try
            {
                MyLog4Net.MyLogHelper.Error("Mqtt：", "Mqtt断开连接！Reason：" + x.Reason);
                OnLineMqtt = false;
            }
            catch (Exception err)
            {
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="x"></param>
        public void OnSubscriberMessageReceived(MqttApplicationMessageReceivedEventArgs x)
        {
            ThreadPool.QueueUserWorkItem(MIS_Funtion_WEB, x);
        }
        #endregion

        /// <summary>
        /// mqtt 接收web和barcode数据
        /// </summary>
        /// <param name="e"></param>
        public void MIS_Funtion_WEB(object e)
        {
            try
            {
                MqttApplicationMessageReceivedEventArgs x = (MqttApplicationMessageReceivedEventArgs)e;
                var rec = x.ApplicationMessage.ConvertPayloadToString();
                MisDataFunDll.MisDataFun.TransferInfToMES(rec);
            }
            catch (Exception ex)
            {
                //MIS_Funtion(topicFunItem, "Exception:" + ex.Message);
            }
        }
   

        static public void TagTypeCodeID_Insert(string opName, string TagTypeCodeID, string TagID, string TagValue, DateTime arrivedTime, DateTime leavedTime, int TimeDiff)
        {
            string procedureName;
            procedureName = "测量数据设备状态日志_增加数据";
            SqlParameter[] thisParms = new SqlParameter[7];
            thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName);
            thisParms[1] = new System.Data.SqlClient.SqlParameter("@信号类型代码", TagTypeCodeID);
            thisParms[2] = new System.Data.SqlClient.SqlParameter("@TagID", TagID);
            thisParms[3] = new System.Data.SqlClient.SqlParameter("@TagValue", TagValue);
            thisParms[4] = new System.Data.SqlClient.SqlParameter("@到达时间", arrivedTime);
            thisParms[5] = new System.Data.SqlClient.SqlParameter("@离开时间", leavedTime);
            thisParms[6] = new System.Data.SqlClient.SqlParameter("@在线时间", TimeDiff);
            DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms);
        }

        static public void DeviceStatusSave(string opName, string TagTypeCodeID,  string TagValue)
        {
            string procedureName;
            procedureName = "MES_设备停机时间_增加";
            SqlParameter[] thisParms = new SqlParameter[3];
            thisParms[0] = new System.Data.SqlClient.SqlParameter("@工位号", opName);
            thisParms[1] = new System.Data.SqlClient.SqlParameter("@TagTypeID", TagTypeCodeID);
            thisParms[2] = new System.Data.SqlClient.SqlParameter("@TagValue", TagValue);
            DataAccess.ExecuteStoredProcedure(procedureName, ref thisParms);
        }

        private void MisDataFun_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("您确认要退出MES程序吗？该操作会停止MES进行数据处理！", "", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                Process.GetCurrentProcess().Kill();
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void timer_Status_Tick(object sender, EventArgs e)
        {
            timer_Status.Enabled = false;
            Show_OnLineState();

            if (!AllowLoad) return;
            Runtime_Thread();

            timer_Status.Enabled = true;
        }

        private void Show_OnLineState()
        {
            OnLineState_C(pb_OnLine_Print, OnLine_Print);
            OnLineState_C(pb_OnLine_SQL, OnLine_SQL);
            OnLineState_C(pb_OnLine_MQTT, OnLineMqtt);
        }
        private void CommunicationCheckOnLine()
        {

            new Thread(new ThreadStart(delegate ()
            {
                while (true)
                {
                    try
                    {
                        OnLine_SQL = DataLinkMesWork.SQLCommon.ExecuteDataTable("select getdate()", ConnectionString_MES, out DataTable dt, out string err);
                    }
                    catch (Exception) { }
                    Thread.Sleep(5000);
                }
            }))
            { IsBackground = true }.Start();

            new Thread(new ThreadStart(delegate ()
            {
                var ip = PrintURL.Split(':')[0];
                while (true)
                {
                    try
                    {
                        OnLine_Print = new System.Net.NetworkInformation.Ping().Send(ip).Status == System.Net.NetworkInformation.IPStatus.Success;
                    }
                    catch (Exception) { }
                    Thread.Sleep(5000);
                }
            }))
            { IsBackground = true }.Start();

        }
        private void OnLineState_C(PictureBox pb, bool onLine)
        {
            pb.Image = onLine ? global::MisDataFun.Properties.Resources.连接状态
                    : global::MisDataFun.Properties.Resources.断开状态;
        }
        private void MyLogHelper_LogCommit(object sender, MyLog4Net.MyLogEventArgs e)
        {
            var module = e.Module;
            var message = e.Message;

            var log = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff") + " " + module + " " + message + "\r\n";
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() =>
                {
                    this.richTextBox1_mqtt.AppendText(log);
                    this.richTextBox1_mqtt.Focus();
                }));
            }
            else
            {
                this.richTextBox1_mqtt.AppendText(log);
                this.richTextBox1_mqtt.Focus();
            }

        }
     

        public void OPCTagData_TagDataOnChange(DeviceDriver_BasicData. CustomeEvetnArgs e)
        {

            // 处理MIS业务 保存数据
            // ThreadPool.QueueUserWorkItem(Function.MIS_Funtion, e);
            // 处理MES业务 Function
            ThreadPool.QueueUserWorkItem(TagData_MisData_TagDataOnChangeCustomeEvetnArgs, e);
            //ThreadPool.QueueUserWorkItem(TagData_MisData_TagDataOnChange, e);
            // 设备状态日志
            ThreadPool.QueueUserWorkItem(TagTypeCodeID_TagDataOnChange, e);
            //发送通讯服务器  MES web界面显示用 加工位号
            ThreadPool.QueueUserWorkItem(TransferInfToWebServer, e);
            //改变控件状态
            //showMessagePLCInvoke(e);
            //更新状态窗口控件状态
            //ExcutePlcChange(e);
        }
        /// <summary>
        /// 发送信号变化到function
        /// </summary>
        /// <param name="msgEvent"></param>
        private void TagData_MisData_TagDataOnChangeCustomeEvetnArgs(object msgEvent)
        {
            try
            {
                var e = (DeviceDriver_BasicData.CustomeEvetnArgs)msgEvent;
                var OpName = e.OpName.ToString();//工位号
                var MesCode = e.TagType.ToString();//变量类型代码
                var tagValue = e.TagValue;//变量（0或者1）
                var TagTypeCodeID = e.TagTypeCodeID.ToString();//变量类型代码
                var TagID = e.TagID.ToString();
                var cmd = MIS_BASE.hashtable_TagTypeTagName[MesCode];
                var mesServerdllName = GetMesServeDllByOpName(OpName);
                var fun = "fun_" + cmd;
                var mesServerCode = GetMesServerCodeByOpName(OpName);
                var rvMsg = JsonConvert.SerializeObject(e);

                if (cmd == null)
                {
                    cmd = MesCode;
                }
                var msg = $"PLC|{cmd}|{OpName}|{rvMsg}";

                try
                {
                    if (TagTypeCodeID == "14")
                    {
                        MIS_BASE.Write_TagValueByTagTypeID(15, OpName, tagValue);
                        return;
                    }
                    if (TagTypeCodeID == "103")
                    {
                        FuntionMesRead.Send_AlarmMsg(TagID, Convert.ToInt32(tagValue).ToString());
                    }
                }
                catch (Exception err)
                {
                    return;
                }
                MisDataFunDll.MisDataFun.TransferInfToMES(msg);
                // asyncSendMessagePLC(mesServerdllName, msg, OpName);
            }
            catch (Exception err)
            {
                ApplicationLog.WriteLog(err, "TagData_Lable_TagDataOnChange");
            }
        }

        /// <summary>
        /// 根据工位号获取MesServerCode
        /// </summary>
        /// <param name="OpName"></param>
        /// <returns></returns>
        private static int GetMesServerCodeByOpName(string OpName)
        {
            try
            {
                if (MesServerWork.MIS_BASE.hashtable_MesServerCode.ContainsKey(OpName))
                {
                    return Convert.ToInt32(MesServerWork.MIS_BASE.hashtable_MesServerCode[OpName]);
                }
                return 0;
            }
            catch
            {
                return 0;
            }
        }
        /// <summary>
        /// 根据工位号获取MesServerDll
        /// </summary>
        /// <param name="OpName"></param>
        /// <returns></returns>
        private static string GetMesServeDllByOpName(string OpName)
        {
            try
            {
                if (MesServerWork.MIS_BASE.hashtable_MesDll.ContainsKey(OpName))
                {
                    return MesServerWork.MIS_BASE.hashtable_MesDll[OpName].ToString();
                }
                return "";
            }
            catch (Exception err)
            {
                ApplicationLog.WriteLog(err, "GetMesServeDllByOpName");
                return "";
            }
        }
        /// <summary>
        /// 数据库记录信号变化
        /// </summary>
        /// <param name="msg"></param>
        private void TagTypeCodeID_TagDataOnChange(object msgEvent)
        {
            if (IsRecordTagStatus != "1") return;

            try
            {
                DeviceDriver_BasicData.CustomeEvetnArgs e = (DeviceDriver_BasicData.CustomeEvetnArgs)msgEvent;

                string tagValue;
                if (e.TagValue == null) return;

                switch (e.TagValue.ToString().ToLower())
                {
                    case "1":
                    case "true":
                        tagValue = "1";
                        break;
                    default:
                        tagValue = "0";
                        break;
                }

                string TagTypeCodeID;
                string opName;
                string TagID;
                string TagValue;
                DateTime arrivedTime;
                DateTime leavedTime;
                int TimeDiff;
                opName = e.OpName.ToString();
                TagValue = tagValue;
                TagTypeCodeID = e.TagTypeCodeID.ToString();
                TagID = e.TagID.ToString();
                leavedTime = Convert.ToDateTime(e.TimeStamp);
                arrivedTime = Convert.ToDateTime(e.TimeStampBefore);
                TimeDiff = Convert.ToInt32(e.TagKeepTime);

                if (TagTypeCodeID != "14" && TagTypeCodeID != "15")
                {
                    TagTypeCodeID_Insert(opName, TagTypeCodeID, TagID, TagValue, arrivedTime, leavedTime, TimeDiff);
                }
                if (TagTypeCodeID == "1002")
                {
                    DeviceStatusSave(opName, TagTypeCodeID,TagValue);
                }
            }
            catch (Exception err)
            {
                ApplicationLog.WriteLog(err, "TagTypeCodeID_TagDataOnChange");
            }

        }
        /// <summary>
        /// 向MES通讯服务器发送消息
        /// </summary>
        /// <param name="msg"></param>
        private void TransferInfToWebServer(object msg1)
        {
            int tagType;
            string opName;
            DeviceDriver_BasicData.CustomeEvetnArgs msgEvent = (DeviceDriver_BasicData.CustomeEvetnArgs)msg1;
            //e值不能为空
            if (msgEvent.TagValue == null) return;
            tagType = Convert.ToInt32(msgEvent.TagType);
            opName = msgEvent.OpName.ToString();

            if (!MesServerWork.MIS_BASE.m_WorkStart_OpName.ContainsKey(opName)) return;  //当前系统是否存在该工位 

            string cmd;
            string tagValue;
            string msgSvr;
            try
            {
                switch (Convert.ToInt32(msgEvent.TagValueType))
                {
                    case 11:
                        tagValue = (Convert.ToInt32(msgEvent.TagValue)).ToString();
                        break;
                    default:
                        tagValue = msgEvent.TagValue.ToString();
                        break;
                }
                cmd = MIS_BASE.hashtable_TagTypeTagName[tagType.ToString()];
                if (Convert.ToInt32(MIS_BASE.hashtable_WebTagTypeChange[cmd]) == 0 && MIS_BASE.hashtable_WebTagTypeChange[cmd] != null) return;

                if (cmd != "" && cmd != null)
                {
                    msgSvr = "MES|" + cmd + "|" + opName + "|" + tagValue;
                }
                else
                {
                    return;
                }
                //MES web界面显示用
                MIS_SendMessage.asyncSendMessageQos0(msgSvr);
            }
            catch (Exception err)
            {
                ApplicationLog.WriteLog(err, "TransferInfToWebServer");
            }
        }
   
        private void button_ReadData_Click(object sender, EventArgs e)
        {
            
        }
        

        private void ToolStripMenuItem_PlcDebug_Click(object sender, EventArgs e)
        {
            if (opcForm != null)
            {
                opcForm.Close();
                opcForm.Dispose();
                opcForm = null;
            }

            opcForm = new MesWork.OpcForm(IsDemoMesServer);
            opcForm.Show();
        }
        /// <summary>
        /// 关于迈思按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 关于迈思ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.meswork.com");
        }
        /// <summary>
        /// 版本信息按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 版本信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            VersionsInformation VersionForm = new VersionsInformation();
            VersionForm.ShowDialog();
        }
     
        private void button2_Click(object sender, EventArgs e)
        {
            FuntionMesRead.GetAlarmInit();
            MyLog4Net.MyLogHelper.Info($"报警更新：", "报警信息更新完成！");
            //SendMessageFun.AsyncSendMessage_Materials_BarCode_Box("OP250", 1, "这是物料码", "这是批次码", "请继续进行物料验证!");

        }

        private void WritePLCBoolData_Click(int TagTypeCodeId)
        {
            string OpName = WorkStationNum_Now;
            string tagValue = MIS_BASE.Read_TagValueByTagTypeID(TagTypeCodeId, OpName).ToString();
            bool tagValueBool = false;
            if (tagValue.ToLower() == "true" || tagValue == "1")
            {
                tagValueBool = false;
            }
            else
            {
                tagValueBool = true;
            }

            MIS_BASE.Write_TagValueByTagTypeID(TagTypeCodeId, OpName, tagValueBool);
        }
        private void WorkStartPLC_Click(object sender, EventArgs e)
        {
            WritePLCBoolData_Click(2);
        }

        private void PartLoadPLC_Click(object sender, EventArgs e)
        {
            WritePLCBoolData_Click(43);
        }

        private void EngineGetOverMES_Click(object sender, EventArgs e)
        {
            WritePLCBoolData_Click(5);
        }

        private void EngineGetOverPLC_Click(object sender, EventArgs e)
        {
            WritePLCBoolData_Click(44);
        }

        private void allowWorkMES_Click(object sender, EventArgs e)
        {
            WritePLCBoolData_Click(66);
        }

        private void allowSavePLC_Click(object sender, EventArgs e)
        {
            WritePLCBoolData_Click(19);
        }

        private void saveOverMES_Click(object sender, EventArgs e)
        {
            WritePLCBoolData_Click(20);
        }

        private void workOverMES_Click(object sender, EventArgs e)
        {
            WritePLCBoolData_Click(7);
        }

        private void toolPoweredPLC_Click(object sender, EventArgs e)
        {
            WritePLCBoolData_Click(1000);
        }

        private void toolStartPLC_Click(object sender, EventArgs e)
        {
            WritePLCBoolData_Click(1001);
        }

        private void toolErrorPLC_Click(object sender, EventArgs e)
        {
            WritePLCBoolData_Click(1002);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MIS_BASE.Write_TagValueByTagTypeID(200, WorkStationNum_Now, "001MBE0700000QF3D0000001");
            MIS_BASE.Write_TagValueByTagTypeID(201, WorkStationNum_Now, "001MBE0700000QF3D0000002");
            MIS_BASE.Write_TagValueByTagTypeID(202, WorkStationNum_Now, "001MBE0700000QF3D0000003");
            MIS_BASE.Write_TagValueByTagTypeID(203, WorkStationNum_Now, "001MBE0700000QF3D0000004");
            MIS_BASE.Write_TagValueByTagTypeID(204, WorkStationNum_Now, "001MBE0700000QF3D0000005");
            MIS_BASE.Write_TagValueByTagTypeID(205, WorkStationNum_Now, "001MBE0700000QF3D0000006");
            MIS_BASE.Write_TagValueByTagTypeID(206, WorkStationNum_Now, "001MBE0700000QF3D0000007");
            MIS_BASE.Write_TagValueByTagTypeID(207, WorkStationNum_Now, "001MBE0700000QF3D0000008");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                var bodydata = File.ReadAllText("电芯段测试数据.json");
                var mrh = JsonConvert.DeserializeObject<msgResHeader>(Post(OnlineCheckDataUrl, bodydata));
                if (mrh.Code == "200")
                {
                    MyLog4Net.MyLogHelper.Error("EngineTypeGetOver", "请求发送成功！详细信息查看日志");
                }
                else
                {
                    MyLog4Net.MyLogHelper.Error("EngineTypeGetOver", "【接收上传质量数据接口】失败");
                }
            }
            catch (Exception err)
            {
                MyLog4Net.MyLogHelper.Error("EngineTypeGetOver", err.Message);
            }

            try
            {
                var bodydata = File.ReadAllText("其他段测试数据.json");
                var mrh = JsonConvert.DeserializeObject<msgResHeader>(Post(OnlineCheckDataUrl, bodydata));
                if (mrh.Code == "200")
                {
                    MyLog4Net.MyLogHelper.Error("EngineTypeGetOver", "请求发送成功！详细信息查看日志");
                }
                else
                {
                    MyLog4Net.MyLogHelper.Error("EngineTypeGetOver", "【接收上传质量数据接口】失败");
                }
            }
            catch (Exception err)
            {
                MyLog4Net.MyLogHelper.Error("EngineTypeGetOver", err.Message);
            }
        }


        public static string Post(string url, string content)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/json";
            req.Timeout = 30000;
            #region 添加Post 参数
            byte[] data = Encoding.UTF8.GetBytes(content);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        private void button17_Click(object sender, EventArgs e)
        {
            MIS_BASE.Read_EngineID_MES(WorkStationNum_Now, out string EngineID_MES);
            MIS_BASE.Read_EngineTypeID_MES(WorkStationNum_Now, out int EngineTypeID_MES);
            MIS_BASE.Write_TagValueByTagTypeID(10, WorkStationNum_Now, EngineID_MES);
            MIS_BASE.Write_TagValueByTagTypeID(9, WorkStationNum_Now, EngineTypeID_MES);
            MIS_BASE.Write_TagValueByTagTypeID(80, WorkStationNum_Now, 12);
        }

        private void button18_Click(object sender, EventArgs e)
        {
            string EngineID = textBox1_EngineID.Text;
            string EngineTypeID = textBox2_EngineTypeID.Text;
            string palletCode = textBox3_palletCode.Text;

            MIS_BASE.Write_TagValueByTagTypeID(10, WorkStationNum_Now, EngineID);
            MIS_BASE.Write_TagValueByTagTypeID(9, WorkStationNum_Now, EngineTypeID);
            MIS_BASE.Write_TagValueByTagTypeID(80, WorkStationNum_Now, palletCode);
        }

        private void button19_Click(object sender, EventArgs e)
        {
            WritePLCBoolData_Click(59);
        }


        /// <summary>
        /// 界面上的开启时间
        /// </summary>
        void Runtime_Thread()
        {
            try
            {
                DateTime Now = DateTime.Now;
                TimeSpan x = Now.Subtract(StartTime);
                toolStripStatusLabel_RunTime.Text = x.Days.ToString() + "天" + x.Hours.ToString("00") + "小时" + x.Minutes.ToString("00") + "分" + x.Seconds.ToString("00") + "秒";
            }
            catch (Exception err)
            {
                ApplicationLog.WriteLog(err, err.Message);
            }
        }

        private void cb_F5_CheckedChanged(object sender, EventArgs e)
        {
            var interval = Convert.ToInt32(txt_Interval.Text);

            if (IsLoopReadShow = cb_F5.Checked)
            {
                var t = new Thread(new ParameterizedThreadStart(LoopReadShowTask));
                t.IsBackground = true;
                t.Start(interval);
            }
        }

        private void toolStripStatusLabel_RunTime_Click(object sender, EventArgs e)
        {
        }

        public void LoopReadShowTask(object _interval)
        {
            var interval = (int)_interval;
            while (true) 
            {
                try
                {
                    if (IsLoopReadShow == false)
                    {
                        return;
                    }

                    ShowSignal(txt_PLC_9,  WorkStationNum_Now);
                    ShowSignal(txt_PLC_10, WorkStationNum_Now);
                    ShowSignal(txt_PLC_11, WorkStationNum_Now);
                    ShowSignal(txt_PLC_39, WorkStationNum_Now);

                    ShowSignal(btn_PLC_2, WorkStationNum_Now);
                    ShowSignal(btn_PLC_43, WorkStationNum_Now);
                    ShowSignal(btn_MES_5, WorkStationNum_Now);

                    ShowSignal(btn_PLC_44, WorkStationNum_Now);
                    ShowSignal(btn_MES_66, WorkStationNum_Now);


                    ShowSignal(btn_PLC_19, WorkStationNum_Now);
                    ShowSignal(btn_MES_20, WorkStationNum_Now);
                    ShowSignal(btn_MES_7, WorkStationNum_Now);

                    ShowSignal(btn_PLC_1000, WorkStationNum_Now);
                    ShowSignal(btn_PLC_1001, WorkStationNum_Now);
                    ShowSignal(btn_PLC_1002, WorkStationNum_Now);
                    ShowSignal(btn_PLC_59, WorkStationNum_Now);
                   
                }
                catch (Exception err)
                {
                }
                Thread.Sleep(interval);
            }
          
        }


        public void ShowSignal(Control c,string opName)
        {
            var tagTypeCodeID = Convert.ToInt32(c.Name.Split('_')[2]);
            if (c is TextBox)
            {
                try
                {
                    c.Text = PlcLinkForm.ReadPLC(tagTypeCodeID, opName).ToString();

                }
                catch (Exception err)
                {
                    c.Text = "不存在该信号！";
                }
            }
            if (c is Button)
            {
                try
                {
                    c.BackColor = PlcLinkForm.ReadPLC(tagTypeCodeID, opName).ToString().ToLower()
                      .Replace("true", "1").Replace("false", "0") == "1"
                      ? color_Green : color_Bad;
                }
                catch (Exception err)
                {
                    c.BackColor = color_Red;
                }
            }
           
        }

        private void panel_Signal_Conf_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            new MES_CONF().ShowDialog();
        }

        private void button20_Click(object sender, EventArgs e)
        {
            PrinterCommandCenter.PrintToPrinter("OP150", textBox1_EngineID.Text);
        }

        private void dgv_OpName_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                if (AllowLoad)
                {
                    WorkStationNum_Now = dgv_OpName.CurrentRow.Cells["OpCode"].Value.ToString();
                }
            }
        }

        private void button19_Click_1(object sender, EventArgs e)
        {
            Get_SpecialOpList();
        }

        private void button21_Click(object sender, EventArgs e)
        {
            PrinterCommandCenter.PrintToPrinter("OP490-1", textBox1_EngineID.Text);
        }
    }
}
