using DynStatDisk.App.Com;
using DynStatDisk.App.Model;
using HslCommunication;
using HslCommunication.BasicFramework;
using HslCommunication.Profinet.Melsec;
using NLog;
using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static HslCommunication.Profinet.Knx.KnxCode;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace DynStatDisk.App
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
            this.ControlBox = false;
        }

        //日志的实例化
        private static Logger logger { get; set; } = LogManager.GetCurrentClassLogger();
        //FSqlContext.FDb实例

        /// <summary>
        /// 位置信息
        /// </summary>
        public MachineLocation LocationInfo { get; set; }

        //通信组件
        private MelsecMcNet _MelsecMcNet { get; set; } = null;

        /// <summary>
        /// 照片集合数据
        /// </summary>
        public List<PhotoImage> ListPhotoImage { get; set; } = new List<PhotoImage>();

        /// <summary>
        /// 集合数据
        /// </summary>
        public List<DynStatDiskModel> ListDynStatDiskModel { get; set; }

        //服务器参数
        public String ServerIP;
        public IPAddress ServerIPAddress;
        public bool ServerLinkState = false;
        public string HandScanPort = string.Empty;
        public string HandScanPortRate = string.Empty;
        public bool PLCLinkState = false;

        public string CurrentMachineNameStr = "动静盘-KP";


        //pictureBox1
        Image pbImageOK = Image.FromFile(@"Images\ok.png");
        Image pbImageNG = Image.FromFile(@"Images\no.png");
        Image pbImageWait = Image.FromFile(@"Images\Wait.png");
        Image pbImageQuestion = Image.FromFile(@"Images\Question.png");

        Image pbImageProofOK = Image.FromFile(@"Images\圆On.png");
        Image pbImageProofNG = Image.FromFile(@"Images\圆Off.png");
        Image pbImageProofWait = Image.FromFile(@"Images\Wait.png");

        /// <summary>
        /// PLC信号模型
        /// </summary>
        private PLCSglModel pLCSglModel { get; set; }

        /// <summary>
        /// 当前工件的间隙数据
        /// </summary>
        private GapData CurGapData { get; set; } = new GapData();

        /// <summary>
        /// 运行过程状态，比如条码好了后，是判断的状态，为On,托盘过后为Off的状态
        /// </summary>
        private bool RunProcessState = false;

        ///// <summary>
        ///// 特殊机种
        ///// </summary>
        //private bool SpecialModels { get; set; }

        /////////////////////////////////////////////////////
        /// <summary>
        /// 线程定义
        /// </summary>
        ////////////////////////////////////////////////////

        /// <summary>
        /// 通信监听
        /// </summary>
        public Thread ListenNetThread;

        /// <summary>
        /// PLC通信监听
        /// </summary>
        public Thread PLCScanThread;
        /// <summary>
        /// 实时更新UI线程
        /// </summary>
        public Thread RtUpdateThread;

        /// <summary>
        /// 仪表数据
        /// </summary>
        private string MeterSourceData { get; set; } = string.Empty;
        public string MeterSeriaScanPort { get; set; } = string.Empty;
        public string MeterSeriaScanPortRate { get; set; } = string.Empty;
        public bool MeterSeriaPortLinkState { get; set; } = false;

        /// <summary>
        /// 当前用户名
        /// </summary>
        public string CurrentOperationNo = string.Empty;

        public string CurrentOperationNoUserLevel = string.Empty;


        //更新UI控件的委托，委托变量的类型的定义-方法的类型的定义
        public delegate void UpdateUIDelegate();
        UpdateUIDelegate _UpdateUIDelegate;//更新界面控件的委托

        public delegate void ReceiveMeterDataDelegate(string data);
        ReceiveMeterDataDelegate _ReceiveMeterDataDelegate;


        #region "字段信息"

        /////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// 数据字段
        /// </summary>
        /////////////////////////////////////////////////////////////////////////
        public OperateResult<string> OperateResultCylinderNo;
        public OperateResult<bool[]> OperateResultBit;
        public OperateResult<Int16[]> OperateResultInt;

        /// <summary>
        /// 当前选择的机种信息数据
        /// </summary>
        public DynStatDiskModel SelectedDynStatDiskModelInfo;

        /// <summary>
        /// 当前的筒体号
        /// </summary>
        private string CurrentReadCylinderNo { get; set; } = string.Empty;

        /// <summary>
        /// 筒体号
        /// </summary>
        private string CurrentCylinderNo { get; set; } = string.Empty;

        /// <summary>
        /// 筒体号前8位
        /// </summary>
        private string CurrentCylinderNoFirst8 { get; set; } = string.Empty;


        /// <summary>
        /// 筒体号后5位
        /// </summary>
        private string CurrentCylinderNoLast5 { get; set; } = string.Empty;

        /// <summary>
        /// 当前的序列号
        /// </summary>
        private string CurrentSerialNo { get; set; } = string.Empty;

        /// <summary>
        /// 当前的机番号
        /// </summary>
        private string CurrentModelNo { get; set; } = string.Empty;

        /// <summary>
        /// 当前的防错信息使能
        /// </summary>
        private bool CurrentProofState { get; set; }


        /// <summary>
        /// 端子连接器
        /// </summary>
        private string CurrentTerminalConnect { get; set; } = string.Empty;

        /// <summary>
        /// 绝缘垫片
        /// </summary>
        private string CurrentInsulatPad { get; set; } = string.Empty;

        /// <summary>
        /// 电器盒盖
        /// </summary>
        private string CurrentDynStatDiskConver { get; set; } = string.Empty;

        #endregion

        /// <summary>
        /// 信号集合状态
        /// </summary>
        public List<StateModel> ListStateModel { get; set; }

        /// <summary>
        /// 操作集合结果数据 ListStateModel的结果赋值给这个的总结果数据
        /// </summary>
        public List<OpActionState> ListOpActionState { get; set; }

        /// <summary>
        /// 防呆的实时启用状态，在工件过来时开始判断防呆，工件流走后不做防呆判断 跟防呆使能不一样，那个是全局的使能
        /// </summary>
        private bool ProofRtEnableState { get; set; } = true;

        ///// <summary>
        ///// 防呆防错使能状态
        ///// </summary>
        //private bool ProofEnable { get; set; } = true;

        //界面相关参数
        public int UIScan = 400;
        private int CurrentPallet = 0;
        private int TotalPalletCount = 0;

        public bool ThreadEnable = true;

        /// <summary>
        /// 欧式机构编号前缀
        /// </summary>
        private string ConfigEuroNoFirst { get; set; } = "欧式机构编号前缀";

        /// <summary>
        /// 欧式机构编号后缀
        /// </summary>
        private string ConfigEuroNoLast { get; set; } = "欧式机构编号后缀";

        /// <summary>
        /// 静盘编号前缀
        /// </summary>
        private string ConfigStaticDiskFirst { get; set; } = "静盘编号前缀";

        /// <summary>
        /// 静盘编号后缀
        /// </summary>
        private string ConfigStaticDiskLast { get; set; } = "静盘编号后缀";

        /// <summary>
        /// PLCIp
        /// </summary>
        private string PLCIP { get; set; }

        /// <summary>
        /// PLC Port
        /// </summary>
        private int PLCPort { get; set; }

        #region 功能界面按钮事件

        /// <summary>
        /// 关闭按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("你确定要关闭程序系统吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning))
            {
                ThreadEnable = false;
                // 断开连接
                _MelsecMcNet?.ConnectClose();

                if (LocationInfo == MachineLocation.KP)
                {
                    MeterSeria?.Close();
                }

                // 断开连接

                //busRtuClient.Close();
                //if (busRtuClient.IsOpen() == true)
                //{
                //    busRtuClient.Close();
                //}

                //if (MeterSeria.IsOpen == true)
                //{
                //    MeterSeria.Close();
                //}

                //if (HandSerialPort.IsOpen == true)
                //{
                //    HandSerialPort.Close();
                //}
                //axActUtlTypeE71.Close();
                //WeighSerialPortThread.Abort();
                //HearPulseThread.Abort();


                //初始化状态 上一次的值和配置
                switch (LocationInfo)
                {
                    case MachineLocation.KP:

                        UpdateOrInsert(LocationInfo.ToString(), ConfigEuroNoFirst, txtEuroNoFirst.Text.Trim());
                        UpdateOrInsert(LocationInfo.ToString(), ConfigEuroNoLast, txtEuroNoLast.Text.Trim());
                        UpdateOrInsert(LocationInfo.ToString(), ConfigStaticDiskFirst, txtStaticDiskFirst.Text.Trim());
                        UpdateOrInsert(LocationInfo.ToString(), ConfigStaticDiskLast, txtStaticDiskLast.Text.Trim());
                        break;
                    case MachineLocation.G:

                        UpdateOrInsert(LocationInfo.ToString(), ConfigEuroNoFirst, txtEuroNoFirst.Text.Trim());
                        UpdateOrInsert(LocationInfo.ToString(), ConfigEuroNoLast, txtEuroNoLast.Text.Trim());
                        UpdateOrInsert(LocationInfo.ToString(), ConfigStaticDiskFirst, txtStaticDiskFirst.Text.Trim());
                        UpdateOrInsert(LocationInfo.ToString(), ConfigStaticDiskLast, txtStaticDiskLast.Text.Trim());
                        break;
                    default:
                        break;
                }


                this.Close();
                System.Environment.Exit(System.Environment.ExitCode);

            }

        }

        private void btnHistory_Click(object sender, EventArgs e)
        {
            if (CurrentOperationNo != "")
            {
                //frmHistoryData.CreateInstrance().ShowDialog();
            }
            else
            {
                MessageBox.Show("请先登录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnLog_Click(object sender, EventArgs e)
        {
            //frmMessageBox.CreateInstrance("流水号和机种型号不匹配，请检查！").ShowDialog();
            //frmLogin.CreateInstrance(CurrentMachineName).ShowDialog();
            this.TabControlMain.SelectedIndex = 1;
        }

        private void btnLogout_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("你确定注销当前用户吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning))
            {
                //_MelsecMcNet.Write("D1000", (short)3);

                CurrentOperationNo = "";
                CurrentOperationNoUserLevel = "";
                tslCurrentUser.Text = "当前用户：未登录";
                tslCurrentUser.BackColor = Color.Red;
                tslCurrentUser.ForeColor = Color.White;

                this.TabControlMain.SelectedIndex = 1;
            }
        }

        private void btnUserManage_Click(object sender, EventArgs e)
        {
            if (CurrentOperationNo != "")
            {
                if (CurrentOperationNoUserLevel == "管理员")
                {
                    FrmUserManage.CreateInstrance(CurrentOperationNoUserLevel).ShowDialog();
                }
                else
                {
                    MessageBox.Show("你不是管理员，无法操作用户管理！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("请先登录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnSystemSet_Click(object sender, EventArgs e)
        {
            if (CurrentOperationNo != "")
            {
                TabControlMain.SelectedIndex = 2;
            }
            else
            {
                MessageBox.Show("请先登录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnModelMatch_Click(object sender, EventArgs e)
        {
            if (CurrentOperationNo != "")
            {
                frmMachineModelConfig.CreateInstrance().ShowDialog();
            }
            else
            {
                MessageBox.Show("请先登录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        #endregion

        private void Main_Load(object sender, EventArgs e)
        {
            try
            {

                if (ConfigHelper.GetValue("Location") == "KP")
                {
                    LocationInfo = MachineLocation.KP;
                    PLCIP = ConfigHelper.GetValue("KPPLCIp");
                    PLCPort = int.Parse(ConfigHelper.GetValue("KPPLCPort"));
                    PanelGap.Visible = true;
                    PanelRight.Visible = true;
                    PanelOther.Visible = true;

                    //串口初始化
                    SerialPortLinkInitial(LocationInfo);

                    CurrentMachineNameStr = "动静盘安装-KP";
                    LoginTitle.Text = CurrentMachineNameStr;
                }
                else
                {
                    LocationInfo = MachineLocation.G;
                    PLCIP = ConfigHelper.GetValue("GPLCIp");
                    PLCPort = int.Parse(ConfigHelper.GetValue("GPLCPort"));

                    CurrentMachineNameStr = "动静盘安装-G";

                    LoginTitle.Text = CurrentMachineNameStr;

                    PanelGap.Visible = false;
                    PanelRight.Visible = false;
                    PanelOther.Visible = false;
                    label33.Visible = false;
                    txtExhCoveBatch.Visible = false;
                }

                ServerIP = ConfigHelper.GetValue("ServerIP");

                //RtMeterRatio = int.Parse(ConfigHelper.GetValue("MeterRatio"));

                frmMachineModelConfig.CreateInstrance().MachineModelConfigChanged += Main_MachineModelConfigChanged;

                //ProofEnable = bool.Parse(ConfigHelper.GetValue("ProofEnable"));

                //获取程序的配置信息
                var SqlCon = ConfigHelper.GetValue("connecting");

                //FSqlContext.FDb.Select<DynStatDiskInstall>().ToList();

                ListDynStatDiskModel = FSqlContext.FDb.Select<DynStatDiskModel>().ToList();
                //foreach (var item in ListDynStatDiskModel)
                //{
                //    ListPhotoImage.Add(new PhotoImage()
                //    {
                //        MachineModel = item.ModelNo,

                //    });
                //}

                //初始化状态 上一次的值和配置
                switch (LocationInfo)
                {
                    case MachineLocation.KP:
                        var lastInfo1 = FSqlContext.FDb.Select<LastStateInfo>().Where(a => a.MachineName == "KP" && a.AttributeName == ConfigEuroNoFirst).OrderByDescending(a => a.CreateTime).ToList();
                        if (lastInfo1 != null && lastInfo1.Count > 0)
                        {
                            txtEuroNoFirst.Text = lastInfo1.FirstOrDefault().AttributeValue;
                        }
                        var lastInfo2 = FSqlContext.FDb.Select<LastStateInfo>().Where(a => a.MachineName == "KP" && a.AttributeName == ConfigEuroNoLast).OrderByDescending(a => a.CreateTime).ToList();
                        if (lastInfo2 != null && lastInfo2.Count > 0)
                        {
                            txtEuroNoLast.Text = lastInfo2.FirstOrDefault().AttributeValue;
                        }
                        var lastInfo3 = FSqlContext.FDb.Select<LastStateInfo>().Where(a => a.MachineName == "KP" && a.AttributeName == ConfigStaticDiskFirst).OrderByDescending(a => a.CreateTime).ToList();
                        if (lastInfo3 != null && lastInfo3.Count > 0)
                        {
                            txtStaticDiskFirst.Text = lastInfo3.FirstOrDefault().AttributeValue;
                        }
                        var lastInfo4 = FSqlContext.FDb.Select<LastStateInfo>().Where(a => a.MachineName == "KP" && a.AttributeName == ConfigStaticDiskLast).OrderByDescending(a => a.CreateTime).ToList();
                        if (lastInfo4 != null && lastInfo4.Count > 0)
                        {
                            txtStaticDiskLast.Text = lastInfo4.FirstOrDefault().AttributeValue;
                        }
                        break;
                    case MachineLocation.G:
                        var lastInfo21 = FSqlContext.FDb.Select<LastStateInfo>().Where(a => a.MachineName == "G" && a.AttributeName == ConfigEuroNoFirst).OrderByDescending(a => a.CreateTime).ToList();
                        if (lastInfo21 != null && lastInfo21.Count > 0)
                        {
                            txtEuroNoFirst.Text = lastInfo21.FirstOrDefault().AttributeValue;
                        }
                        var lastInfo22 = FSqlContext.FDb.Select<LastStateInfo>().Where(a => a.MachineName == "G" && a.AttributeName == ConfigEuroNoLast).OrderByDescending(a => a.CreateTime).ToList();
                        if (lastInfo22 != null && lastInfo22.Count > 0)
                        {
                            txtEuroNoLast.Text = lastInfo22.FirstOrDefault().AttributeValue;
                        }
                        var lastInfo23 = FSqlContext.FDb.Select<LastStateInfo>().Where(a => a.MachineName == "G" && a.AttributeName == ConfigStaticDiskFirst).OrderByDescending(a => a.CreateTime).ToList();
                        if (lastInfo23 != null && lastInfo23.Count > 0)
                        {
                            txtStaticDiskFirst.Text = lastInfo23.FirstOrDefault().AttributeValue;
                        }
                        var lastInfo24 = FSqlContext.FDb.Select<LastStateInfo>().Where(a => a.MachineName == "G" && a.AttributeName == ConfigStaticDiskLast).OrderByDescending(a => a.CreateTime).ToList();
                        if (lastInfo24 != null && lastInfo24.Count > 0)
                        {
                            txtStaticDiskLast.Text = lastInfo24.FirstOrDefault().AttributeValue;
                        }
                        break;
                    default:
                        break;
                }

                LoadLvGapColumn();

                //PLC通信的连接
                _MelsecMcNet = new MelsecMcNet();
                _MelsecMcNet.IpAddress = PLCIP;
                _MelsecMcNet.Port = 6000;
                _MelsecMcNet.ConnectClose();

                _MelsecMcNet.ConnectTimeOut = 3000; // 连接3秒超时
                OperateResult connect = _MelsecMcNet.ConnectServer();
                if (connect.IsSuccess)//初始连接状态的显示判断
                {
                    //MessageBox.Show(HslCommunication.StringResources.Language.ConnectedSuccess);
                    //_MelsecMcNet.Write("M504", true);
                }
                else
                {
                    MessageBox.Show(connect.Message + Environment.NewLine + "ErrorCode: " + connect.ErrorCode);
                }



                pLCSglModel = new PLCSglModel();
                pLCSglModel.CylinderNoSglEvent += PLCSglModel_CylinderNoSglEvent;
                pLCSglModel.PalletPassSglEvent += PLCSglModel_PalletPassSglEvent;
                pLCSglModel.TongZhiGuiSglEvent += PLCSglModel_TongZhiGuiSglEvent;


                //委托实例化
                _UpdateUIDelegate = new UpdateUIDelegate(UpdateUIMethod);

                _ReceiveMeterDataDelegate = new ReceiveMeterDataDelegate(ReceiveMeterDataMethod);


                ListStateModel = new List<StateModel>()
            {
                new StateModel("端子连接器","A",new List<BitStateSgl>(){
                    new BitStateSgl("接近开关1",false),
                    new BitStateSgl("接近开关2",false),
                    new BitStateSgl("接近开关3",false),
                }),
                new StateModel("端子连接器","B",new List<BitStateSgl>(){
                    new BitStateSgl("接近开关4",false),
                    new BitStateSgl("接近开关5",false),
                    new BitStateSgl("接近开关6",false),
                    new BitStateSgl("光纤传感器",false),
                }),
                new StateModel("端子连接器","C",new List<BitStateSgl>(){
                    new BitStateSgl("接近开关4",false),
                    new BitStateSgl("接近开关5",false),
                    new BitStateSgl("接近开关6",false)
                }),
                new StateModel("端子连接器","无",new List<BitStateSgl>(){
                    //new BitStateSgl("虚拟开关-无",false)
                }),

                new StateModel("绝缘垫片","A",new List<BitStateSgl>(){
                    new BitStateSgl("安全光栅1",false)
                }),
                new StateModel("绝缘垫片","B",new List<BitStateSgl>(){
                    new BitStateSgl("安全光栅1",false)
                }),
                new StateModel("绝缘垫片","C",new List<BitStateSgl>(){
                    new BitStateSgl("安全光栅1",false)
                }),
                new StateModel("绝缘垫片","D",new List<BitStateSgl>(){
                    new BitStateSgl("安全光栅2",false)
                }),
                new StateModel("绝缘垫片","E",new List<BitStateSgl>(){
                    new BitStateSgl("安全光栅2",false)
                }),
                new StateModel("绝缘垫片","F",new List<BitStateSgl>(){
                    new BitStateSgl("安全光栅2",false)
                }),
                new StateModel("绝缘垫片","无",new List<BitStateSgl>(){
                    //new BitStateSgl("虚拟开关-无",false)
                }),

                new StateModel("电器盒","A",new List<IntStateSgl>(){
                    new IntStateSgl("扭矩枪信号",0,4)
                }),
                new StateModel("电器盒","B",new List<IntStateSgl>(){
                    new IntStateSgl("扭矩枪信号",0,4)
                }),
                new StateModel("电器盒","C",new List<IntStateSgl>(){
                    new IntStateSgl("扭矩枪信号",0,4)
                }),
                new StateModel("电器盒","无",new List<IntStateSgl>(){
                    //new IntStateSgl("虚拟开关-无",0,4)
                })
            };

                foreach (var item in ListStateModel)
                {
                    item.StateSglSglEvent += Item_StateSglSglEvent;
                }

                ListOpActionState = new List<OpActionState>()
                {
                    new OpActionState("端子连接器","A"),
                    new OpActionState("绝缘垫片","A"),
                    new OpActionState("电器盒","A"),
                };

                //ListPhotoImage

                //网络状态扫描
                ListenNetThread = new Thread(new ThreadStart(ListenNetMethod));
                ListenNetThread.Start();

                // 启动PLC更新数据的线程;
                PLCScanThread = new Thread(new ThreadStart(PLCScanThreadMethod));
                PLCScanThread.Start();

                RtUpdateThread = new Thread(new ThreadStart(RtUpdateThreadMethod));
                RtUpdateThread.Start();

            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
            }
        }

        /// <summary>
        /// 机种模型更改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Main_MachineModelConfigChanged(object sender, EventArgs e)
        {
            ListDynStatDiskModel = FSqlContext.FDb.Select<DynStatDiskModel>().ToList();
        }

        /// <summary>
        /// 通止规的信号模型
        /// </summary>
        /// <param name="UpdateValue"></param>
        /// <param name="UpdateName"></param>
        private void PLCSglModel_TongZhiGuiSglEvent(bool UpdateValue, string UpdateName)
        {
            BeginInvoke(new Action(() =>
            {
                if (UpdateValue)
                {
                    lblTongZhiGui.BackColor = Color.LimeGreen;
                }
                else
                {
                    lblTongZhiGui.BackColor = Color.DarkGray;
                }
            }));
        }

        /// <summary>
        /// 托盘流走信号，清除一些HMI显示状态
        /// </summary>
        /// <param name="UpdateValue"></param>
        /// <param name="UpdateName"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void PLCSglModel_PalletPassSglEvent(bool UpdateValue, string UpdateName)
        {
            //FSqlContext.FDb.Insert<DynStatDiskInstall>(new DynStatDiskInstall()
            //{

            //}).ExecuteAffrows();

            BeginInvoke(new Action(() =>
            {
                //lblTerminalConnect.Text = "无";
                //lblInsulatPad.Text = "无";
                //lblDynStatDiskConver.Text = "无";

                //pbTerminalConnect.Image = pbImageWait;
                //pbInsulatPad.Image = pbImageWait;
                //pbDynStatDiskConver.Image = pbImageWait;

                //pbESHOP.Image = null;

                //txtSerialNo.Text = "";
                //txtModelNo.Text = "";

                //btnTruePass.BackColor = Color.Transparent;

                //btnHandPass.BackColor = Color.Coral;
                txtEuroNo.Text = "";
                txtDynStaticDiskNo.Text = "";

                RunProcessState = false;

                txtCylinderNo.Text = "";
                txtEuroSeriesNo.Text = "";
                txtStaticDiskNoW.Text = "";

                lblSubmitMsg.Visible = false;

                lblCylinderNoAlarmMsg.Visible = false;

                //间隙数据删除
                txtOtherGapGroup.Text = "";
                txtOtherGapValue.Text = "";
                CurGapData.Group = "";
                CurGapData.Gap = "";
                CurGapData.Result = "";

                if (cbxDefaultOK.Checked)
                {
                    rbPartCountOK.Checked = true;
                    rbBracketOilOK.Checked = true;
                    rbSpiralScrewOK.Checked = true;
                    rbDynStaticNoSameOK.Checked = true;
                    rbDynStaticNoBreakOK.Checked = true;
                    rbLiquidInjeMachOK.Checked = true;
                }


            }));


        }


        /// <summary>
        /// 每个产品达到要求注册的方法
        /// </summary>
        /// <param name="UpdateValue"></param>
        /// <param name="Name"></param>
        /// <param name="Category"></param>
        private void Item_StateSglSglEvent(bool UpdateValue, string Name, string Category)
        {
            switch (Name)
            {
                //case "端子连接器":
                //    ListOpActionState.Find(a => a.Name == Name).CurrentResult = true;
                //    BeginInvoke(new Action(() =>
                //    {
                //        pbTerminalConnect.Image = pbImageOK;
                //    }));
                //    break;
                //case "绝缘垫片":
                //    ListOpActionState.Find(a => a.Name == Name).CurrentResult = true;
                //    BeginInvoke(new Action(() =>
                //    {
                //        pbInsulatPad.Image = pbImageOK;
                //    }));
                //    break;
                //case "电器盒":
                //    ListOpActionState.Find(a => a.Name == Name).CurrentResult = true;
                //    BeginInvoke(new Action(() =>
                //    {
                //        pbDynStatDiskConver.Image = pbImageOK;
                //    }));
                //    break;
                //default:
                //    break;
            }

            //综合判断一下是否三个都为OK了
            if (ListOpActionState.Find(a => a.Name == "端子连接器").CurrentResult &&
                ListOpActionState.Find(a => a.Name == "绝缘垫片").CurrentResult &&
                ListOpActionState.Find(a => a.Name == "电器盒").CurrentResult)
            {
                _MelsecMcNet.Write("M10", true);

                BeginInvoke(new Action(() =>
                {
                    //btnTruePass.BackColor = Color.LimeGreen;
                }));
            }

        }


        /// <summary>
        /// PLC信号模型中条码准备完毕信号
        /// </summary>
        /// <param name="UpdateValue"></param>
        /// <param name="UpdateName"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void PLCSglModel_CylinderNoSglEvent(bool UpdateValue, string UpdateName)
        {
            //获取机种番号
            if (!string.IsNullOrEmpty(CurrentReadCylinderNo) && CurrentReadCylinderNo.Length > 4)
            {
                CurrentModelNo = CurrentReadCylinderNo.Substring(0, 4);
                CurrentCylinderNoFirst8 = CurrentReadCylinderNo.Substring(0, 8);
                CurrentCylinderNoLast5 = CurrentReadCylinderNo.Substring(CurrentReadCylinderNo.Length - 5);

                BeginInvoke(new Action(() =>
                {
                    txtCylinderNo.Text = CurrentReadCylinderNo;
                    txtCylinderNoFirst8.Text = CurrentCylinderNoFirst8;
                    txtCylinderNoLast5.Text = CurrentCylinderNoLast5;

                    //数据读取成功后，控制焦点，等待让操作人员输入数据
                    txtEuroSeriesNo.Focus();
                }));
            }

            RunProcessState = true;

            //
            //var ModelInfo = ListDynStatDiskModel.Where(a => a.ModelNo == CurrentModelNo).OrderByDescending(a => a.CreateTime).ToList();
            //if (ModelInfo != null && ModelInfo.Count > 0)
            //{
            //    SelectedDynStatDiskModelInfo = ModelInfo.FirstOrDefault();

            //    ListOpActionState.Find(a => a.Name == "端子连接器").CurrentCategory = SelectedDynStatDiskModelInfo.TerminalConnect;
            //    ListOpActionState.Find(a => a.Name == "端子连接器").CurrentResult = false;
            //    ListOpActionState.Find(a => a.Name == "绝缘垫片").CurrentCategory = SelectedDynStatDiskModelInfo.InsulatPad;
            //    ListOpActionState.Find(a => a.Name == "绝缘垫片").CurrentResult = false;
            //    ListOpActionState.Find(a => a.Name == "电器盒").CurrentCategory = SelectedDynStatDiskModelInfo.DynStatDiskConver;
            //    ListOpActionState.Find(a => a.Name == "电器盒").CurrentResult = false;



            //    //为无的话，则直接判断未OK
            //    //if (SelectedDynStatDiskModelInfo.TerminalConnect == "无")
            //    //{
            //    //    //ListOpActionState.Find(a => a.Name == "端子连接器").CurrentResult = true;
            //    //    ListStateModel.Find(a => a.Name == "端子连接器" && a.Category == "无").Result = false;
            //    //    ListStateModel.Find(a => a.Name == "端子连接器" && a.Category == "无").Result = true;
            //    //}
            //    //if (SelectedDynStatDiskModelInfo.InsulatPad == "无")
            //    //{
            //    //    //ListOpActionState.Find(a => a.Name == "绝缘垫片").CurrentResult = true;
            //    //    ListStateModel.Find(a => a.Name == "绝缘垫片" && a.Category == "无").Result = false;
            //    //    ListStateModel.Find(a => a.Name == "绝缘垫片" && a.Category == "无").Result = true;
            //    //}
            //    //if (SelectedDynStatDiskModelInfo.DynStatDiskConver == "无")
            //    //{
            //    //    //ListOpActionState.Find(a => a.Name == "电器盒").CurrentResult = true;
            //    //    ListStateModel.Find(a => a.Name == "电器盒" && a.Category == "无").Result = false;
            //    //    ListStateModel.Find(a => a.Name == "电器盒" && a.Category == "无").Result = true;
            //    //}

            //    //if (!ProofEnable)
            //    //{
            //    //    ListStateModel.Find(a => a.Name == "端子连接器" && a.Category == "无").Result = false;
            //    //    ListStateModel.Find(a => a.Name == "端子连接器" && a.Category == "无").Result = true;

            //    //    ListStateModel.Find(a => a.Name == "绝缘垫片" && a.Category == "无").Result = false;
            //    //    ListStateModel.Find(a => a.Name == "绝缘垫片" && a.Category == "无").Result = true;

            //    //    ListStateModel.Find(a => a.Name == "电器盒" && a.Category == "无").Result = false;
            //    //    ListStateModel.Find(a => a.Name == "电器盒" && a.Category == "无").Result = true;

            //    //}


            //    BeginInvoke(new Action(() =>
            //    {
            //        //lblTerminalConnect.Text = SelectedDynStatDiskModelInfo.TerminalConnect;
            //        //lblInsulatPad.Text = SelectedDynStatDiskModelInfo.InsulatPad;
            //        //lblDynStatDiskConver.Text = SelectedDynStatDiskModelInfo.DynStatDiskConver;
            //        //pbESHOP.Image = ListPhotoImage.Find(a => a.MachineModel == SelectedDynStatDiskModelInfo.ModelNo).ImageInfo;
            //    }));

            //}
            //else
            //{
            //    MessageBox.Show("当前模板中没有找到对应的机种番号，请添加后再使用", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //}

        }


        /// <summary>
        /// 更新界面数据
        /// </summary>
        private void UpdateUIMethod()
        {

        }






        /// <summary>
        /// 网络监控线程
        /// </summary>
        private void ListenNetMethod()
        {
            while (ThreadEnable)
            {
                Thread.Sleep(20000);
                try
                {
                    // 判断是否读取成功
                    var result = _MelsecMcNet.Read("D0", 1);
                    if (result.IsSuccess)
                    {

                        PLCLinkState = true;

                    }
                    else
                    {
                        PLCLinkState = false;
                    }

                    using (Ping ping = new Ping())
                    {
                        PingReply pingReply = ping.Send(ServerIP);
                        if (pingReply.Status == IPStatus.Success)
                        {
                            ServerLinkState = true;
                        }
                        else
                        {
                            ServerLinkState = false;
                        }
                    }
                    //Ping ping = new Ping();

                    //仪表状态
                    if (LocationInfo == MachineLocation.KP)
                    {
                        if (MeterSeria.IsOpen)
                        {
                            MeterSeriaPortLinkState = true;
                        }
                        else
                        {
                            MeterSeriaPortLinkState = false;
                            MeterSeria.Open();
                        }
                    }


                    this.BeginInvoke(new Action(() =>
                    {
                        if (PLCLinkState)
                        {
                            tslPLC.Text = "PLC连接：正常";
                            tslPLC.BackColor = Color.Green;
                        }
                        else
                        {
                            tslPLC.Text = "PLC连接：失败";
                            tslPLC.BackColor = Color.Red;
                        }


                        if (ServerLinkState)
                        {
                            tslServer.Text = "服务器线路：正常";
                            tslServer.BackColor = Color.Green;
                        }
                        else
                        {
                            tslServer.Text = "服务器线路：失败";
                            tslServer.BackColor = Color.Red;
                        }

                        if (LocationInfo == MachineLocation.KP)
                        {
                            if (MeterSeriaPortLinkState)
                            {
                                tslMeterSeria.Text = "西马量仪端口：打开";
                                tslMeterSeria.BackColor = Color.Green;
                            }
                            else
                            {
                                tslMeterSeria.Text = "西马量仪端口：关闭";
                                tslMeterSeria.BackColor = Color.Red;
                            }
                        }
                        else
                        {
                            tslMeterSeria.Text = "--";
                            tslMeterSeria.BackColor = Color.Green;
                        }


                    }));
                }
                catch (Exception ex)
                {
                    logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                    //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
                }
            }
        }

        /// <summary>
        /// PLC扫描数据
        /// </summary>
        private void PLCScanThreadMethod()
        {
            try
            {
                while (ThreadEnable)
                {
                    Thread.Sleep(UIScan);


                    if (LocationInfo == MachineLocation.G)
                    {
                        OperateResultBit = _MelsecMcNet.ReadBool("M6000", 30);
                        if (OperateResultBit != null && OperateResultBit.IsSuccess == true)
                        {
                            //条码准备完毕信号
                            //pLCSglModel.CodeEnable = OperateResultBit.Content[20];
                            pLCSglModel.PalletPassEnable = OperateResultBit.Content[2];

                            pLCSglModel.TongZhiGuiEnable = OperateResultBit.Content[0];
                        }
                    }
                    else
                    {
                        //Todo
                        //OperateResultCylinderNo = _MelsecMcNet.ReadString("D10", 7);
                        //if (OperateResultCylinderNo != null && OperateResultCylinderNo.IsSuccess == true)
                        //{
                        //    //当前的实时数据
                        //    CurrentReadCylinderNo = OperateResultCylinderNo.Content.Trim();
                        //}

                        OperateResultBit = _MelsecMcNet.ReadBool("M6000", 30);
                        if (OperateResultBit != null && OperateResultBit.IsSuccess == true)
                        {
                            //条码准备完毕信号
                            //pLCSglModel.CodeEnable = OperateResultBit.Content[20];
                            pLCSglModel.PalletPassEnable = OperateResultBit.Content[2];

                            pLCSglModel.TongZhiGuiEnable = OperateResultBit.Content[0];
                        }
                    }



                    //OperateResultInt = _MelsecMcNet.ReadInt16("D0", 2);
                    //if (OperateResultInt != null && OperateResultInt.IsSuccess == true)
                    //{

                    //}

                    ////赋值给模型
                    //if (ProofRtEnableState)
                    //{
                    //    foreach (var item in ListOpActionState)
                    //    {
                    //        if (item.Name != "电器盒")
                    //        {
                    //            //先赋值一个初始的On的值，后面循环给这个结果赋值
                    //            ListStateModel.Find(a => a.Name == item.Name && a.Category == item.CurrentCategory).TempBitValue = true;
                    //            foreach (var itemCell in ListStateModel.Find(a => a.Name == item.Name && a.Category == item.CurrentCategory).ListBitStateSgl)
                    //            {
                    //                ListStateModel.Find(a => a.Name == item.Name && a.Category == item.CurrentCategory).TempBitValue = ListStateModel.Find(a => a.Name == item.Name && a.Category == item.CurrentCategory).TempBitValue && itemCell.State;
                    //            }

                    //            //如果 端子连接器 C 并且光纤传感器为On的话，则不判断结果，此时结果不对的。
                    //            if (ListStateModel.Find(a => a.Name == "端子连接器" && a.Category == "B").ListBitStateSgl.Find(a => a.SglName == "光纤传感器").State &&
                    //                item.Name == "端子连接器" && item.CurrentCategory == "C"
                    //                )
                    //            {

                    //            }
                    //            else
                    //            {
                    //                ListStateModel.Find(a => a.Name == item.Name && a.Category == item.CurrentCategory).Result = ListStateModel.Find(a => a.Name == item.Name && a.Category == item.CurrentCategory).TempBitValue;
                    //            }

                    //        }
                    //        else
                    //        {
                    //            ListStateModel.Find(a => a.Name == item.Name && a.Category == item.CurrentCategory).TempBitValue = true;
                    //            foreach (var itemCell in ListStateModel.Find(a => a.Name == item.Name && a.Category == item.CurrentCategory).ListIntStateSgl)
                    //            {
                    //                ListStateModel.Find(a => a.Name == item.Name && a.Category == item.CurrentCategory).TempBitValue = ListStateModel.Find(a => a.Name == item.Name && a.Category == item.CurrentCategory).TempBitValue && (itemCell.State >= 4);
                    //            }
                    //            ListStateModel.Find(a => a.Name == item.Name && a.Category == item.CurrentCategory).Result = ListStateModel.Find(a => a.Name == item.Name && a.Category == item.CurrentCategory).TempBitValue;
                    //        }

                    //    }
                    //}

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        private void RtUpdateThreadMethod()
        {
            try
            {
                while (ThreadEnable)
                {
                    Thread.Sleep(UIScan);




                    this.BeginInvoke(_UpdateUIDelegate);
                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtUserName.Text))
                {
                    MessageBox.Show("请输入用户名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (string.IsNullOrEmpty(txtPassword.Text))
                {
                    MessageBox.Show("请输入密码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                var ListUser = FSqlContext.FDb.Select<TbUser>().Where(a => a.UserName == txtUserName.Text.Trim() && a.MachineName == CurrentMachineNameStr).ToList();
                if (ListUser != null && ListUser.Count() > 0)
                {
                    if (ListUser.FirstOrDefault().Password == txtPassword.Text.Trim())
                    {
                        MessageBox.Show("登录成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Main_PopUserNameEvent(txtPassword.Text.Trim(), ListUser.FirstOrDefault().AccessLevel);

                        this.TabControlMain.SelectedIndex = 0;

                        txtUserName.Text = "";
                        txtPassword.Text = "";
                        //PopUserNameEvent(txtUserName.Text.Trim());
                        //this.Close();

                    }
                    else
                    {
                        MessageBox.Show("密码错误！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    MessageBox.Show("当前用户不存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }


        /// <summary>
        /// 用户登录的事件发布方法
        /// </summary>
        /// <param name="UserName"></param>
        private void Main_PopUserNameEvent(string UserName, string UserLevel)
        {
            try
            {
                CurrentOperationNo = UserName;
                CurrentOperationNoUserLevel = UserLevel;
                Invoke(new Action(() =>
                {
                    tslCurrentUser.Text = "当前用户：" + CurrentOperationNo;
                    tslCurrentUser.BackColor = Color.Green;
                    tslCurrentUser.ForeColor = Color.White;
                }));
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        /// <summary>
        /// 确认放行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTruePass_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 手动放行-空托盘放行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnHandPass_Click(object sender, EventArgs e)
        {
            _MelsecMcNet.Write("M11", true);

            //btnHandPass.BackColor = Color.LimeGreen;

        }

        private void cbxProof_CheckStateChanged(object sender, EventArgs e)
        {
            //if (cbxProof.CheckState == CheckState.Checked)
            //{
            //    ProofEnable = true;
            //    ConfigHelper.SetValue("ProofEnable", "True");

            //    //CurrentMeterEnableState = true;
            //    //txtUpperSdUpperDiff_Rt.ReadOnly = false;
            //    //btnUpperSdSaveCurrent.Enabled = true;
            //    //btnUpperSdSaveCurrent.Focus();
            //}
            //else
            //{
            //    ProofEnable = false;
            //    ConfigHelper.SetValue("ProofEnable", "false");
            //    //CurrentMeterEnableState = false;
            //    //txtUpperSdUpperDiff_Rt.ReadOnly = true;
            //    //btnUpperSdSaveCurrent.Enabled = false;
            //    //txtUpperSdUpperDiffSave.Focus();
            //}
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            TabControlMain.SelectedIndex = 0;
        }

        //private void cbxSystemProof_CheckStateChanged(object sender, EventArgs e)
        //{
        //    if (cbxSystemProof.CheckState == CheckState.Checked)
        //    {
        //        //cbxProof.CheckState = CheckState.Checked;
        //        ProofEnable = true;
        //        ConfigHelper.SetValue("ProofEnable", "True");

        //        //CurrentMeterEnableState = true;
        //        //txtUpperSdUpperDiff_Rt.ReadOnly = false;
        //        //btnUpperSdSaveCurrent.Enabled = true;
        //        //btnUpperSdSaveCurrent.Focus();
        //    }
        //    else
        //    {
        //        //cbxProof.CheckState = CheckState.Unchecked;
        //        ProofEnable = false;
        //        ConfigHelper.SetValue("ProofEnable", "false");
        //        //CurrentMeterEnableState = false;
        //        //txtUpperSdUpperDiff_Rt.ReadOnly = true;
        //        //btnUpperSdSaveCurrent.Enabled = false;
        //        //txtUpperSdUpperDiffSave.Focus();
        //    }
        //}

        #region 按键的触发
        private void txtEuroSeriesNo_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {
                    //通过需要调取欧式机构编号信息

                    if (!string.IsNullOrEmpty(txtEuroSeriesNo.Text.Trim()))
                    {
                        txtEuroNo.Text = txtEuroNoFirst.Text + txtEuroSeriesNo.Text.Trim() + txtEuroNoLast.Text;
                    }

                    txtStaticDiskNoW.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }



        #endregion


        #region 仪表通信

        /// <summary>
        /// 仪表串口通信初始化MeterSeria
        /// </summary>
        private void SerialPortLinkInitial(MachineLocation Location)
        {
            try
            {
                string SerialPort = "COM2";
                int SerialRate = 9600;

                switch (Location)
                {
                    case MachineLocation.KP:
                        SerialPort = ConfigHelper.GetValue("KPSerialPort");
                        SerialRate = int.Parse(ConfigHelper.GetValue("KPSerialRate"));
                        //设置通讯端口号及波特率、数据位、停止位和校验位。N-8-1
                        MeterSeria.PortName = SerialPort;
                        MeterSeria.BaudRate = SerialRate;
                        MeterSeria.Parity = System.IO.Ports.Parity.None;
                        MeterSeria.DataBits = 8;
                        MeterSeria.StopBits = System.IO.Ports.StopBits.One;
                        //打开端口
                        MeterSeria.Open();
                        break;
                    case MachineLocation.G:
                        //SerialPort = ConfigHelper.GetValue("LowerSdPort");
                        //SerialRate = int.Parse(ConfigHelper.GetValue("LowerSdRate"));
                        //SerialPort = "Port3";
                        //SerialRate = 9600;
                        break;
                    default:
                        break;
                }

            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }


        /// <summary>
        /// 仪表接口数据
        /// 触发时发送数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MeterSeria_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                // 接收数据
                List<byte> buffer = new List<byte>();
                byte[] data = new byte[1024];
                while (true)
                {
                    Thread.Sleep(20);
                    if (MeterSeria.BytesToRead < 1)
                    {
                        break;
                    }

                    int recCount = MeterSeria.Read(data, 0, Math.Min(MeterSeria.BytesToRead, data.Length));

                    byte[] buffer2 = new byte[recCount];
                    Array.Copy(data, 0, buffer2, 0, recCount);
                    buffer.AddRange(buffer2);
                }

                if (buffer.Count == 0) return;

                MeterSourceData = SoftBasic.GetAsciiStringRender(buffer.ToArray());
                _ReceiveMeterDataDelegate.BeginInvoke(MeterSourceData, null, null);//接收和处理数据程序

                //if (MeterSeria.BytesToRead > 0)
                //{
                //    Thread.Sleep(20);
                //    //RuntimeWeightValue = "";
                //    MeterSourceData = MeterSeria.ReadExisting().ToString();
                //    Console.WriteLine($"时间：{DateTime.Now.ToString()}-消息：{MeterSourceData}");
                //    //u = AllRuntimeWeightValue.Length;
                //    if (MeterSourceData.Length > 1)
                //    {
                //        _ReceiveMeterDataDelegate.BeginInvoke(MeterSourceData, null, null);//接收和处理数据程序
                //        //checkBoxCodeDataDelegate.BeginInvoke(BoxUseData, null, null);
                //    }
                //    MeterSeria.DiscardInBuffer();//丢弃缓冲区的数据

                //    //lblRuntimeCalcuResult.BeginInvoke(updateCalcuResultData, new object[] { 3 });

                //}
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }

        }

        /// <summary>
        /// 当前生成的Gap值
        /// </summary>
        private GapData CurGenGapData { get; set; }

        /// <summary>
        /// 仪表消息流数据
        /// </summary>
        private StringBuilder MeterMsgStream { get; set; } = new StringBuilder();

        /// <summary>
        /// 仪表数据接收信息状态
        /// 每个产品有要做两次，第一次是标准的产品的，获取分组信息
        /// 第二次是获取测量信息
        /// </summary>
        private string MeterDataState { get; set; } = "L1";

        /// <summary>
        /// 测量标准件的分组信息
        /// </summary>
        private string MeterDataStandardGroup { get; set; }

        /// <summary>
        /// 是否进行间隙的检测
        /// </summary>
        private bool IsCheckMeterGap { get; set; } = false;

        /// <summary>
        /// 接受仪表发动的数据
        /// </summary>
        /// <param name="data"></param>
        private void ReceiveMeterDataMethod(string data)
        {
            if (!string.IsNullOrEmpty(data))
            {

                //logger.Error(data);
                //string result = Encoding.Default.GetString(data.ToHexBytes());
                //TODO解析数据-解析方法-分类
                //截取两个头和尾部字符串
                //if (data.StartsWith("CC"))
                //{
                //}

                if (MeterDataState == "L1")
                {
                    //当前是获取标准件的分组信息
                    var ArrData = data.Split(',');
                    if (ArrData.Length > 16)
                    {
                        //获取分组信息
                        MeterDataStandardGroup = ArrData[13].Trim();
                        MeterDataState = "L2";
                        BeginInvoke(new Action(() =>
                        {
                            lblMeterDataState.Text = "等待测量件";
                        }));
                    }
                }
                else if (MeterDataState == "L2")
                {
                    //当前是获取标准件的分组信息
                    var ArrData = data.Split(',');
                    if (ArrData.Length > 16)
                    {
                        CurGenGapData = new GapData()
                        {
                            Gap = ArrData[4].Trim(),
                            Group = MeterDataStandardGroup,// ArrData[13].Trim(),
                            //Result = ArrData[12].Trim(),
                            Result = ArrData[8].Trim(),
                            Time = DateTime.Now,
                            TimeId = DateTime.Now.ToString("yyyyMMddHHmmssfff")
                        };

                        ListGapData.Add(CurGenGapData);

                        MeterDataState = "L1";
                        BeginInvoke(new Action(() =>
                        {
                            InsertLvGapResult(CurGenGapData.Gap, CurGenGapData.Result, CurGenGapData.Group, CurGenGapData.TimeId);
                            lblMeterDataState.Text = "等待标准件";
                        }));
                    }
                }


            }
            else
            {

            }
        }


        #endregion

        private void txtStaticDiskNoW_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {
                    if (!string.IsNullOrEmpty(txtStaticDiskNoW.Text.Trim()))
                    {
                        txtDynStaticDiskNo.Text = txtStaticDiskFirst.Text + txtStaticDiskNoW.Text.Trim() + txtStaticDiskLast.Text;
                    }

                    txtEuroCastNo.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        private void txtEuroCastNo_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {
                    //if (!CurrentMeterEnableState)//不启用仪表需要检查手动输入的数据
                    //{

                    //}

                    txtStaticDiskCastNo.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        private void txtStaticDiskCastNo_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {
                    //if (!CurrentMeterEnableState)//不启用仪表需要检查手动输入的数据
                    //{

                    //}

                    if (LocationInfo == MachineLocation.KP)
                    {
                        txtExhCoveBatch.Focus();
                    }
                    else
                    {
                        btnTrue.Focus();
                    }


                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        /// <summary>
        /// CylinderNoLast5 操作的话，则证明扫码枪异常，是人工手动输入的信息
        /// 此时输入完成后，代表条码准备完毕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtCylinderNoLast5_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {
                    //条码人工输入完毕，进行操作
                    //获取机种番号
                    if (string.IsNullOrEmpty(txtCylinderNoFirst8.Text.Trim()))
                    {
                        MessageBox.Show("【筒体号前8位】未发现输入数据，请确认！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    if (txtCylinderNoFirst8.Text.Trim().Length != 8)
                    {
                        MessageBox.Show("【筒体号前8位】未满足8位数据，请确认！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    if (string.IsNullOrEmpty(txtCylinderNoLast5.Text.Trim()))
                    {
                        MessageBox.Show("【筒体号后5位】未发现输入数据，请确认！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    if (txtCylinderNoLast5.Text.Trim().Length != 5)
                    {
                        MessageBox.Show("【筒体号后5位】未满足5位数据，请确认！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    CurrentReadCylinderNo = txtCylinderNoFirst8.Text.Trim() + txtCylinderNoLast5.Text.Trim();
                    //赋值数据
                    txtCylinderNo.Text = CurrentReadCylinderNo;
                    CurrentModelNo = CurrentReadCylinderNo.Substring(0, 4);
                    //数据读取成功后，控制焦点，等待让操作人员输入数据
                    txtEuroSeriesNo.Focus();


                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }


        #region 特殊处理

        /// <summary>
        /// 间隙数据集合
        /// </summary>
        private List<GapData> ListGapData { get; set; } = new List<GapData>();

        /// <summary>
        /// 选中的Gap
        /// </summary>
        private GapData SelectedGapData { get; set; }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadLvGapColumn()
        {
            ColumnHeader h0 = new ColumnHeader();
            ColumnHeader h1 = new ColumnHeader();
            ColumnHeader h2 = new ColumnHeader();
            ColumnHeader h3 = new ColumnHeader();
            ColumnHeader h4 = new ColumnHeader();
            ColumnHeader h5 = new ColumnHeader();
            ColumnHeader h6 = new ColumnHeader();
            ColumnHeader h7 = new ColumnHeader();
            ColumnHeader h8 = new ColumnHeader();
            ColumnHeader h9 = new ColumnHeader();
            ColumnHeader h10 = new ColumnHeader();
            ColumnHeader h11 = new ColumnHeader();
            ColumnHeader h12 = new ColumnHeader();
            ColumnHeader h13 = new ColumnHeader();

            h1.TextAlign = HorizontalAlignment.Center;
            h2.TextAlign = HorizontalAlignment.Center;
            h3.TextAlign = HorizontalAlignment.Center;
            h4.TextAlign = HorizontalAlignment.Center;
            h5.TextAlign = HorizontalAlignment.Center;
            h6.TextAlign = HorizontalAlignment.Center;
            h7.TextAlign = HorizontalAlignment.Center;
            h8.TextAlign = HorizontalAlignment.Center;
            h9.TextAlign = HorizontalAlignment.Center;
            h10.TextAlign = HorizontalAlignment.Center;
            h11.TextAlign = HorizontalAlignment.Center;
            h12.TextAlign = HorizontalAlignment.Center;
            h13.TextAlign = HorizontalAlignment.Center;

            h0.Width = 20;
            h1.Width = 100;
            h2.Width = 90;
            h3.Width = 90;
            h4.Width = 0;
            h5.Width = 420;
            h6.Width = 150;
            h7.Width = 0;
            h8.Width = 0;
            h9.Width = 40;
            h10.Width = 100;
            h11.Width = 100;
            h12.Width = 100;
            h13.Width = 0;

            h0.Text = "";
            h1.Text = "间隙";
            h2.Text = "结论";
            h3.Text = "分组";
            h4.Text = "";
            h5.Text = "";
            h6.Text = "";
            h7.Text = "";
            h8.Text = "";
            h9.Text = "";

            h10.Text = "";
            h11.Text = "";
            h12.Text = "";
            h13.Text = "";
            //h14.Text = "";

            LvGap.Columns.AddRange(new ColumnHeader[] { h0, h1, h2, h3, h4 });
            LvGap.View = View.Details;
        }

        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="Gap"></param>
        /// <param name="Result"></param>
        /// <param name="Gorup"></param>
        private void InsertLvGapResult(string Gap, string Result, string Gorup, string TimeId)
        {
            ListViewItem lvi = new ListViewItem();
            lvi.ImageIndex = 0;
            lvi.Text = "";
            lvi.SubItems.Add(Gap.ToString());
            lvi.SubItems.Add(Result.ToString());
            lvi.SubItems.Add(Gorup.ToString());
            lvi.SubItems.Add(TimeId.ToString());
            this.LvGap.Items.Add(lvi);
        }


        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadLvGapData()
        {
            LvGap.Items.Clear();
            //InitialLoadList.Clear();
            //加载数据

            if (ListGapData.Count > 0)
            {
                var data = ListGapData.OrderBy(a => a.Time).ToList();
                foreach (var item in data)
                {
                    InsertLvGapResult(item.Gap,
                        item.Result,
                        item.Result,
                        item.TimeId
                      );
                }

            }
        }

        /// <summary>
        /// 选中LvGap 改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LvGap_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (LvGap.SelectedIndices.Count > 0 && LvGap.SelectedIndices != null && LvGap.FocusedItem != null)
            {
                SelectedGapData = new GapData();
                SelectedGapData.Gap = LvGap.FocusedItem.SubItems[1].Text;
                SelectedGapData.Result = LvGap.FocusedItem.SubItems[2].Text;
                SelectedGapData.Group = LvGap.FocusedItem.SubItems[3].Text;
                SelectedGapData.TimeId = LvGap.FocusedItem.SubItems[4].Text;

            }
        }



        #endregion

        /// <summary>
        /// 提交数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTrue_Click(object sender, EventArgs e)
        {
            if (lblTongZhiGui.BackColor != Color.LimeGreen)
            {
                MessageBox.Show("请检查通止规信息！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                return;
            }


            //返回的数据
            int ReturnData = 0;

            if (LocationInfo == MachineLocation.KP)
            {

                if (string.IsNullOrEmpty(txtCylinderNo.Text.Trim()))
                {
                    MessageBox.Show("请检查筒体号是否有空的数据！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    return;
                }
                if (string.IsNullOrEmpty(txtDynStaticDiskNo.Text.Trim()))
                {
                    MessageBox.Show("请检查动盘号是否有空的数据！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    return;
                }
                if (string.IsNullOrEmpty(txtEuroNo.Text.Trim()))
                {
                    MessageBox.Show("请检查欧式机构编号是否有空的数据！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    return;
                }
                if (string.IsNullOrEmpty(txtStaticDiskCastNo.Text.Trim()))
                {
                    MessageBox.Show("请检查欧式机构铸件号是否有空的数据！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    return;
                }
                

                if (IsCheckMeterGap)
                {
                    if (string.IsNullOrEmpty(CurGapData.Gap.Trim()))
                    {
                        MessageBox.Show("请检查工件间隙值是否有空的数据！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                        return;
                    }
                    if (string.IsNullOrEmpty(CurGapData.Group.Trim()))
                    {
                        MessageBox.Show("请检查工件分组是否有空的数据！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                        return;
                    }
                    if (string.IsNullOrEmpty(CurGapData.Result.Trim()))
                    {
                        MessageBox.Show("请检查工件结果是否有空的数据！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                        return;
                    }
                }


                ReturnData = FSqlContext.FDb.Insert<KPDynStaticMach>(new KPDynStaticMach()
                {
                    CylinderNo = txtCylinderNo.Text.Trim(),
                    DynaDiskNo = txtDynStaticDiskNo.Text.Trim(),
                    EuropMacine = txtEuroNo.Text.Trim(),
                    OpNo = CurrentOperationNo,
                    StaDskCastNo = txtStaticDiskCastNo.Text.Trim(),
                    StaticDiskNo = txtDynStaticDiskNo.Text.Trim(),
                    EuopMaDifValue = txtOtherGapValue.Text,
                    CreateTime = DateTime.Now,
                    MeterGap = CurGapData.Gap,
                    MeterGroup = CurGapData.Group,
                    MeterResult = CurGapData.Result

                    //BracketOil = GetRbValue(rbPartCountOK, rbPartCountNG),
                    //DynStaticNoBreak = GetRbValue(rbDynStaticNoBreakOK, rbDynStaticNoBreakNG),
                    //DynStaticNoSame = GetRbValue(rbDynStaticNoSameOK, rbDynStaticNoSameNG),
                    //PartCount = GetRbValue(rbPartCountOK, rbPartCountNG),
                    //SpiralScrew = GetRbValue(rbSpiralScrewOK, rbSpiralScrewNG),
                    //LiquidInjeMach = GetRbValue(rbLiquidInjeMachOK, rbLiquidInjeMachNG),
                    //CylinderNo = txtCylinderNo.Text.Trim(),
                    //DynStaticDiskNo = txtDynStaticDiskNo.Text.Trim(),
                    //EuroCastNo = txtEuroCastNo.Text.Trim(),
                    //EuroNo = txtEuroNo.Text.Trim(),
                    //EuroSeriesNo = txtEuroSeriesNo.Text.Trim(),
                    //OtherBracket = txtOtherBracket.Text.Trim(),
                    //OtherDynDisk = txtOtherDynDisk.Text.Trim(),
                    //OtherEuro = txtOtherEuro.Text.Trim(),
                    //OtherGapGroup = txtOtherGapGroup.Text.Trim(),
                    //OtherGapResult = "",
                    //OtherGapValue = "",
                    //StaticDiskCastNo = txtStaticDiskCastNo.Text.Trim(),
                    //StaticDiskNoW = txtStaticDiskNoW.Text.Trim(),

                }).ExecuteAffrows();

                if (ReturnData > 0)
                {
                    lblSubmitMsg.Visible = true;
                    txtCylinderNo.Text = "";
                    //提交数据成功，发送托盘放行
                    _MelsecMcNet.Write("M6001", true);
                }
            }
            else
            {
                if (string.IsNullOrEmpty(txtCylinderNo.Text.Trim()))
                {
                    MessageBox.Show("请检查筒体号是否有空的数据！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    return;
                }
                if (string.IsNullOrEmpty(txtDynStaticDiskNo.Text.Trim()))
                {
                    MessageBox.Show("请检查动盘号是否有空的数据！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    return;
                }
                if (string.IsNullOrEmpty(txtEuroNo.Text.Trim()))
                {
                    MessageBox.Show("请检查欧式机构编号是否有空的数据！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    return;
                }
                if (string.IsNullOrEmpty(txtStaticDiskCastNo.Text.Trim()))
                {
                    MessageBox.Show("请检查欧式机构铸件号是否有空的数据！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    return;
                }


                //GDynStaticMach
                ReturnData = FSqlContext.FDb.Insert<GDynStaticMach>(new GDynStaticMach()
                {
                    CylinderNo = txtCylinderNo.Text.Trim(),
                    DynaDiskNo = txtDynStaticDiskNo.Text.Trim(),
                    EuropMacine = txtEuroNo.Text.Trim(),
                    OpNo = CurrentOperationNo,
                    StaDskCastNo = txtStaticDiskCastNo.Text.Trim(),
                    StaticDiskNo = txtStaticDiskCastNo.Text.Trim(),
                    CreateTime = DateTime.Now,

                }).ExecuteAffrows();

                if (ReturnData > 0)
                {
                    lblSubmitMsg.Visible = true;
                    txtCylinderNo.Text = "";

                    //提交数据成功，发送托盘放行
                    _MelsecMcNet.Write("M6001", true);
                }
            }

            try
            {
                //if条件检测按下的是不是Enter键
                if (ReturnData > 0)
                {


                    txtCylinderNo.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }

        }

        private void txtCylinderNo_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {
                    if (txtCylinderNo.Text.Length > 4)
                    {

                        var Data = ListDynStatDiskModel.Where(a => a.ModelNo == txtCylinderNo.Text.Trim().Substring(0, 4)).ToList();
                        if (Data != null && Data.Count > 0)
                        {

                            //判定首字符是否能匹配
                            if (!string.IsNullOrEmpty(txtStaticDiskFirst.Text.Trim()))
                            {
                                if (Data.FirstOrDefault().DynStatDiskKeyMatch != txtStaticDiskFirst.Text.Substring(0, 1))
                                {
                                    MessageBox.Show("动静盘编号首字符未匹配！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    txtCylinderNo.Focus();
                                    return;
                                }
                            }
                            else
                            {
                                MessageBox.Show("静盘编号前缀为空，请输入后再进行！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                txtCylinderNo.Focus();
                                return;
                            }


                            if (Data.FirstOrDefault().GapInfo == "检测")
                            {
                                IsCheckMeterGap = true;

                                BeginInvoke(new Action(() =>
                                {
                                    PanelGap.Enabled = true;
                                    PanelRight.Enabled = true;

                                    lblCylinderNoAlarmMsg.Visible = false;

                                    //进行间隙数据的移位
                                    if (LvGap.Items.Count > 0)
                                    {
                                        txtOtherGapGroup.Text = LvGap.Items[0].SubItems[3].Text;
                                        txtOtherGapValue.Text = LvGap.Items[0].SubItems[1].Text;
                                        //txtOtherResult.Text=LvGap.Items[0].SubItems[2].Text;

                                        CurGapData.Group = LvGap.Items[0].SubItems[3].Text;
                                        CurGapData.Gap = LvGap.Items[0].SubItems[1].Text;
                                        CurGapData.Result = LvGap.Items[0].SubItems[2].Text;

                                        var findata = ListGapData.Find(a => a.TimeId == LvGap.Items[0].SubItems[4].Text);
                                        if (findata != null)
                                        {
                                            ListGapData.Remove(findata);

                                            LvGap.Items.RemoveAt(LvGap.Items[0].Index);
                                            //LvGap.Update();
                                        }
                                    }
                                    else
                                    {
                                        //MessageBox.Show("没有检测的间隙数据？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                                    }

                                }));
                            }
                            else
                            {
                                IsCheckMeterGap = false;

                                BeginInvoke(new Action(() =>
                                {
                                    PanelGap.Enabled = false;
                                    PanelRight.Enabled = false;

                                    lblCylinderNoAlarmMsg.Visible = false;
                                }));
                            }

                            txtEuroSeriesNo.Focus();
                        }
                        else
                        {
                            BeginInvoke(new Action(() =>
                            {
                                lblCylinderNoAlarmMsg.Visible = true;
                                lblCylinderNoAlarmMsg.Text = "未找到配置机种信息，无法知道是否需要检测数据";
                            }));

                            txtEuroSeriesNo.Focus();
                            //lblCylinderNoAlarmMsg
                        }


                        //MessageBox.Show("您在textBox1里按下了回车键");
                    }
                    else
                    {
                        BeginInvoke(new Action(() =>
                        {
                            lblCylinderNoAlarmMsg.Visible = true;
                            lblCylinderNoAlarmMsg.Text = "筒体号长度不足，无法解析机种信息";
                        }));

                        txtCylinderNo.Focus();
                    }




                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }


        private string GetRbValue(RadioButton Ok, RadioButton Ng)
        {
            if (!Ok.Checked)
            {
                return "OK";
            }
            return "NG";

        }

        #region Radio选项数据焦点数据

        private void rbPartCountNG_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {


                    btnTrue.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        private void rbBracketOilNG_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {


                    btnTrue.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        private void rbSpiralScrewNG_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {


                    btnTrue.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        private void rbDynStaticNoSameNG_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {


                    btnTrue.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        private void rbDynStaticNoBreakNG_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {


                    btnTrue.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        private void rbLiquidInjeMachNG_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {


                    btnTrue.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }



        private void rbBracketOilOK_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {


                    btnTrue.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        private void rbSpiralScrewOK_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {


                    btnTrue.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        private void rbDynStaticNoSameOK_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {


                    btnTrue.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        private void rbDynStaticNoBreakOK_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {


                    btnTrue.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        private void rbLiquidInjeMachOK_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {


                    btnTrue.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }


        #endregion


        private void rbPartCountOK_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {


                    btnTrue.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }


        /// <summary>
        /// 更新或者插入数据
        /// </summary>
        private void UpdateOrInsert(string MachineName, string AttributeName, string AttributeValue)
        {
            var Data = FSqlContext.FDb.Select<LastStateInfo>().Where(a => a.MachineName == MachineName && a.AttributeName == AttributeName).OrderByDescending(a => a.CreateTime).ToList();
            if (Data != null && Data.Count > 0)
            {
                FSqlContext.FDb.Update<LastStateInfo>()
                    .Set(a => a.AttributeValue, AttributeValue)
                    .Where(a => a.MachineName == MachineName && a.AttributeName == AttributeName)
                    .ExecuteAffrows();
            }
            else
            {
                FSqlContext.FDb.Insert<LastStateInfo>(new LastStateInfo()
                {
                    AttributeName = AttributeName,
                    MachineName = MachineName,
                    AttributeValue = AttributeValue
                }).ExecuteAffrows();
            }
        }

        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            ThreadEnable = false;
            // 断开连接
            _MelsecMcNet?.ConnectClose();
        }

        private void btnLVGapDelete_Click(object sender, EventArgs e)
        {
            if (LvGap.SelectedIndices != null && LvGap.SelectedIndices.Count > 0 && SelectedGapData != null)
            {
                var findata = ListGapData.Find(a => a.TimeId == SelectedGapData.TimeId);
                if (findata != null)
                {
                    ListGapData.Remove(findata);
                    SelectedGapData = null;

                    LvGap.Items.RemoveAt(LvGap.SelectedItems[0].Index);
                    //LvGap.Update();
                }
            }
            else
            {
                MessageBox.Show("请选中后再操作！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ReceiveMeterDataMethod("+00.0000,+00.0000,+00.0000,        ,+00.0000,        ,        ,        ,      OK,     -OK,     -OK,     -OK,      OK,     -OK,      OK,      OK,      OK,01,098,2024-08-23,16:12:47");
        }

        private void btnMove_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtOtherGapGroup.Text.Trim()))
            {
                //不为空时方式多次Move，把数据都移除完了并删除了，理论上来说，一个产品只能移动一个
                if (DialogResult.Cancel == MessageBox.Show("检测到当前【间隙信息】已经存在，是否还要继续？点击【确定】则继续，点击【取消】则中止", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning))
                {
                    return;
                }
            }

            if (LvGap.Items.Count > 0)
            {
                txtOtherGapGroup.Text = LvGap.Items[0].SubItems[3].Text;
                txtOtherGapValue.Text = LvGap.Items[0].SubItems[1].Text;
                //txtOtherResult.Text=LvGap.Items[0].SubItems[2].Text;

                CurGapData.Group = LvGap.Items[0].SubItems[3].Text;
                CurGapData.Gap = LvGap.Items[0].SubItems[1].Text;
                CurGapData.Result = LvGap.Items[0].SubItems[2].Text;

                var findata = ListGapData.Find(a => a.TimeId == LvGap.Items[0].SubItems[4].Text);
                if (findata != null)
                {
                    ListGapData.Remove(findata);

                    LvGap.Items.RemoveAt(LvGap.Items[0].Index);
                    //LvGap.Update();
                }
            }
            else
            {
                MessageBox.Show("没有检测的间隙数据？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            }


        }

        private void txtOtherDynDisk_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {


                    txtOtherEuro.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        private void txtOtherEuro_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {


                    txtOtherBracket.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        private void txtOtherBracket_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {


                    btnTrue.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        private void btnOtherDelete_Click(object sender, EventArgs e)
        {
            txtOtherGapGroup.Text = "";
            txtOtherGapValue.Text = "";

        }

        private void txtExhCoveBatch_KeyDown(object sender, KeyEventArgs e)
        {
            //LocationInfo
            try
            {
                //if条件检测按下的是不是Enter键
                if (e.KeyCode == Keys.Enter)
                {


                    btnTrue.Focus();
                    //MessageBox.Show("您在textBox1里按下了回车键");

                }
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("ErrSource : {0} ErrMsg : {1}", ex.StackTrace.ToString(), ex.Message.ToString()));
                //insertLogToDBDelegate.BeginInvoke(1, "UpdateUIMethod异常", ex.Message.ToString() + ex.StackTrace.Substring(ex.StackTrace.Length - 40, 40), null, null);
            }
        }

        private void cbxDefaultOK_CheckStateChanged(object sender, EventArgs e)
        {

        }

        private void txtEuroSeriesNo_Enter(object sender, EventArgs e)
        {
            txtEuroSeriesNo.BackColor = Color.SkyBlue;
        }

        private void txtEuroSeriesNo_Leave(object sender, EventArgs e)
        {
            txtEuroSeriesNo.BackColor=SystemColors.Window;
        }

        private void txtStaticDiskNoW_Enter(object sender, EventArgs e)
        {
            txtStaticDiskNoW.BackColor = Color.SkyBlue;
        }

        private void txtStaticDiskNoW_Leave(object sender, EventArgs e)
        {
            txtStaticDiskNoW.BackColor = SystemColors.Window;
        }

        private void txtCylinderNo_Enter(object sender, EventArgs e)
        {
            txtCylinderNo.BackColor = Color.SkyBlue;
        }

        private void txtCylinderNo_Leave(object sender, EventArgs e)
        {
            txtCylinderNo.BackColor = SystemColors.Window;
        }

        private void txtEuroCastNo_Enter(object sender, EventArgs e)
        {
            txtEuroCastNo.BackColor = Color.SkyBlue;
        }

        private void txtEuroCastNo_Leave(object sender, EventArgs e)
        {
            txtEuroCastNo.BackColor = SystemColors.Window;
        }

        private void txtStaticDiskCastNo_Enter(object sender, EventArgs e)
        {
            txtStaticDiskCastNo.BackColor = Color.SkyBlue;
        }

        private void txtStaticDiskCastNo_Leave(object sender, EventArgs e)
        {
            txtStaticDiskCastNo.BackColor = SystemColors.Window;
        }

        private void txtExhCoveBatch_Enter(object sender, EventArgs e)
        {
            txtExhCoveBatch.BackColor = Color.SkyBlue;
        }

        private void txtExhCoveBatch_Leave(object sender, EventArgs e)
        {
            txtExhCoveBatch.BackColor = SystemColors.Window;
        }
    }
}
