using com.hnshituo.core.webapp.vo;
using Common;
using Infragistics.Win;
using Infragistics.Win.UltraWinEditors;
using Infragistics.Win.UltraWinGrid;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;

namespace MeterModuleLibrary
{
    public partial class ucHotDeliveryBelt : UserControl
    {
        public delegate void EventOpenWarnMsgBelt(string e);

        public ucHotDeliveryBelt()
        {
            InitializeComponent();
        }

        public CoreAppUser appUser = null;//登陆信息
        private Log l = Log.GetInstance();//日志信息
        private ComBaseInfoService comBaseInfoService = new ComBaseInfoService(); //基础数服务
        private PreStorageScaleService preStorageScaleService = new PreStorageScaleService();//热送预报数据服务
        private MeterWorkStorageActualService actualService = new MeterWorkStorageActualService();//热送实绩数据服务
        private MeterWorkStorageSingleWgtService singleWgtService = new MeterWorkStorageSingleWgtService(); //热送单只重量（标准重量）服务
        private MeterWorkStorageCalibrationService calibrationService = new MeterWorkStorageCalibrationService(); //热送校秤服务
        private meterworkzeroalarmservice zeroAlarmService = new meterworkzeroalarmservice();//零点报警服务
        private PreStorageScale preTack = new PreStorageScale(); //预报实体类
        public DbHelper db = null; //服务端请求

        public event EventOpenWarnMsgBelt openWarnMsgBelt; //打开预警弹窗

        private bool bCheckWarn = false;//是否已经进行未勾选自动计量提醒；

        /// <summary>
        /// 计量点
        /// </summary>
        public string sPointNo = "", sPointName = "";

        /// <summary>
        /// 登录人及登陆IP信息;用户选择的预报编号
        /// </summary>
        public string sUserId = "", sUserName = "", sIpAddress = "", sClickPredictionNo = "";

        /// <summary>
        /// 新增的计量表监控数据
        /// </summary>
        public MeterBaseScalePoint drOldData = null, rowPointInfo = null;

        /// <summary>
        /// 初始载入一次数据
        /// </summary>
        private bool flagLoad = true;

        /// <summary>
        /// 数据保存标志；fasle=未保存,可以进行保存操作，true=已保存，不允许重复保存！
        /// </summary>
        private bool flagSaved = false;

        /// <summary>
        /// 重量稳定状态：0稳定，1不稳定,2空磅
        /// </summary>
        private int weightStatus = 2;

        /// <summary>
        /// 重量稳定次数:累计值
        /// </summary>
        private int weightStableTimes = 0, weightStableTimesZero = 0;

        /// <summary>
        /// 重量稳定次数：超过此值则稳定
        /// </summary>
        private int weightStableSchedule = 6, weightStableScheduleZero = 6;

        /// <summary>
        /// 上一次重量：记录上一次重量，用于判断重量是否稳定
        /// </summary>
        private double weightLast = 0, weightLastZero = 0;

        /// <summary>
        /// 重量稳定的差值：默认3kg
        /// </summary>
        private double weightDiff = 3, weightDiffZero = 3;

        /// <summary>
        /// 是否为测试标志位
        /// </summary>
        private bool testFlage = false;

        /// <summary>
        ///完整终端地址:MOXAIP+MOXAPORT
        /// </summary>
        private IPEndPoint serverFullAddr;

        /// <summary>
        /// 连接套接字
        /// </summary>
        private Socket sock;

        /// <summary>
        /// load事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucHotDeliveryBelt_Load(object sender, EventArgs e)
        {
            //ClsControlPack.UseFixedHeader(this.ultraGridActual, "UNCK");
            //ClsControlPack.UseFixedHeader(this.ultraGridActual, "heatNo");
            //ClsControlPack.UseFixedHeader(this.ultraGridActual, "packageNo");

            #region 基础数据载入

            //热送磅班组信息载入cmbMeterGroupUp
            RESTfulResult<List<ComBaseInfo>> rrComMeterGroop = comBaseInfoService.doQueryBaseList(new ComBaseInfo { validFlag = "1", pBaseCode = "001044" });
            if (rrComMeterGroop.Succeed && rrComMeterGroop.Data != null && rrComMeterGroop.Data.Count > 0)
            {
                ClsControlPack.SetUltraComboDataSource(cmbMeterGroup, rrComMeterGroop.Data.ListToDataTable<ComBaseInfo>(), "baseCode", "baseName");
            }
            else
            {
                MessageBox.Show("热送磅班组信息载入失败!");
                return;
            }

            //热送磅班次信息载入cmbMeterClassUp
            RESTfulResult<List<ComBaseInfo>> rrComMeterClass = comBaseInfoService.doQueryBaseList(new ComBaseInfo { validFlag = "1", pBaseCode = "001043" });
            if (rrComMeterClass.Succeed && rrComMeterClass.Data != null && rrComMeterClass.Data.Count > 0)
            {
                ClsControlPack.SetUltraComboDataSource(cmbMeterClass, rrComMeterClass.Data.ListToDataTable<ComBaseInfo>(), "baseCode", "baseName");
            }
            else
            {
                MessageBox.Show("热送磅班次信息载入失败!");
                return;
            }

            //预报表转换
            ValueList vlistFlag1 = new ValueList();
            vlistFlag1.ValueListItems.Add("0", "无效");
            vlistFlag1.ValueListItems.Add("1", "未使用");
            vlistFlag1.ValueListItems.Add("2", "使用中");
            vlistFlag1.ValueListItems.Add("3", "已完成");
            this.ultraGrid1.DisplayLayout.Bands[0].Columns["valueFlag"].ValueList = vlistFlag1;
            //ClsControlPack.SetUltraGridRowFilter(ref ultraGrid1, true);

            //实绩表转换
            ValueList vlistFlag3 = new ValueList();
            vlistFlag3.ValueListItems.Add("0", "无效");
            vlistFlag3.ValueListItems.Add("1", "有效");
            this.ultraGridActual.DisplayLayout.Bands[0].Columns["valueFlag"].ValueList = vlistFlag3;
            //ClsControlPack.SetUltraGridRowFilter(ref ultraGrid2, true);

            #endregion 基础数据载入

            //班次、班组初始化
            if (appUser != null && !string.IsNullOrEmpty(appUser.userClass) && !string.IsNullOrEmpty(appUser.userGroup))
            {
                cmbMeterClass.Text = appUser.userClass;
                cmbMeterGroup.Text = appUser.userGroup;
            }
        }

        #region timer1事件

        /// <summary>
        /// 时间控制器，每秒钟执行一次
        /// 1、用于重量采集
        /// 2、用于称重保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(sPointName) && !string.IsNullOrEmpty(sPointNo) && flagLoad)
                {
                    lbPointName.Text = sPointName;
                    lbCreateManName.Text = sUserName;
                    queryScale(); //界面第一次加载
                    queryActual(); //界面第一次加载
                    flagLoad = false;
                    flagSaved = false;
                }
                if (rowPointInfo != null && rowPointInfo.weight != null)
                {
                    if (testFlage)
                    {
                        rowPointInfo.weight = Convert.ToDouble(txtWeight.Text.Replace("kg", "").Trim());
                        //rowPointInfo.weightZero = Convert.ToDouble(txtReferWeight.Text.Replace("kg", "").Trim());
                    }
                    //重量小于100，将保存标志位置为未保存；
                    if (rowPointInfo.weight < 100)
                    {
                        flagSaved = false;
                        bCheckWarn = false;
                    }
                    //界面重量显示赋值
                    setWeightCollect(rowPointInfo.weight.ToString());

                    //判断是否为零点；并在界面显示
                    judgmentWeightZero();

                    //判稳逻辑;2021年10月20日切换为自动采集；0.5s一次，6次波动范围在3以内为稳定；
                    //judgmentWeightStatus();

                    //平台的重量判稳逻辑；
                    judgmentWeightStatusPT();
                    //自动保存;
                    if (ckAutoSave.Checked)
                    {
                        //普棒热送00032：重量小于4000kg不进行自动保存操作
                        double collectWeight = Convert.ToDouble(txtWeight.Text.Replace("kg", "").Trim());
                        if ("00032".Equals(sPointNo) && collectWeight < 4000)
                        {
                            return;
                        }
                        if (!flagSaved && weightStatus == 0)
                        {
                            aotuSaveDB();//自动保存
                        }
                    }
                    //未勾选自动计量报警
                    if (!bCheckWarn && !ckAutoSave.Checked && !flagSaved && weightStatus == 0 && !"00033".Equals(sPointNo))
                    {
                        bCheckWarn = true;
                        setMsgMsg(tbMsg, "color", "Red");
                        openWarnMsgBelt(sPointName + "重量已稳定，未勾选【自动计量】！");//回调主界面方法
                    }
                }
                else
                {
                    setMsgInfo(tbMsg, "未采集到重量数据！请联系系统维护人员处理！", "");
                }
            }
            catch (Exception ex)
            {
                l.WriteLog(19, sPointName + "：" + ex.Message);
                throw ex;
            }
        }

        #endregion timer1事件

        #region 按钮点击事件汇总

        /// <summary>
        /// 预报查询按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btQueryInfo_Click(object sender, EventArgs e)
        {
            queryScale(); //预报查询按钮查询预报
            queryActual();//预报查询按钮查询实绩
        }

        /// <summary>
        /// 保存按钮，将预报数据转换为实绩数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btSave_Click(object sender, EventArgs e)
        {
            saveDB(); //手动保存
            queryScale(); //手动保存后，查预报；
            queryActual();//手动保存后，查实绩；
        }

        /// <summary>
        /// 是否自动计量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ckAutoSave_CheckedChanged(object sender, EventArgs e)
        {
            queryScale();//自动计量时复选框变化时，重新查询预报;
        }

        /// <summary>
        /// 手动完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnComplete_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(tbPredictionNo.Text.Trim()))
                {
                    setMsgInfo(tbMsg, "预报编号为空不允许进行[手动完成]！", "");
                    return;
                }
                DialogResult dr = MessageBox.Show("是否将预报[" + tbPredictionNo.Text.Trim() + "]手动完成！", "提示", MessageBoxButtons.OKCancel);
                if (dr == DialogResult.Cancel)
                {
                    return;
                }
                List<PreStorageScale> lt = new List<PreStorageScale>();
                PreStorageScale preStorageUpdate = new PreStorageScale();
                preStorageUpdate.predictionNo = tbPredictionNo.Text.Trim();
                preStorageUpdate.updateManNo = sUserId;
                preStorageUpdate.updateManName = sUserName;
                preStorageUpdate.valueFlag = "3"; //作废;状态(0=无效，1=有效，2=使用中，3=已完成)
                preStorageUpdate.memo = preTack.memo + "；" + DateTime.Now + "司磅工：" + sUserName + "进行[手动完成]操作！";
                lt.Add(preStorageUpdate);

                RESTfulResult<String> rms = preStorageScaleService.doUpdateWf(lt);
                if (rms.Succeed)
                {
                    setMsgInfo(tbMsg, "预报编号[" + preStorageUpdate.predictionNo + "]手动完成，操作成功！", "");
                    queryScale(); //手动完成后，自动查询一次
                }
                else
                {
                    setMsgInfo(tbMsg, "预报编号[" + preStorageUpdate.predictionNo + "]手动完成，操作失败！", "");
                }
            }
            catch (Exception ex)
            {
                l.WriteLog(19, sPointName + "：" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 调整班次
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdateClass_Click(object sender, EventArgs e)
        {
            try
            {
                int iCount = 0;
                ultraGridActual.UpdateData();
                frmHotDeliveryUpdateClass frmPrint = new frmHotDeliveryUpdateClass();
                foreach (UltraGridRow ugr in ultraGridActual.Rows)
                {
                    if (ugr.Cells["UNCK"].Value.ToString().Trim().ToUpper() == "TRUE")
                    {
                        frmPrint.productDateShow = ugr.Cells["productDate"].Text.Trim().Substring(0, 10);
                        frmPrint.meterClassShow = ugr.Cells["meterClass"].Text.Trim();
                        frmPrint.meterGroupShow = ugr.Cells["meterGroup"].Text.Trim();
                        iCount++;
                    }
                }
                if (iCount == 0)
                {
                    setMsgInfo(tbMsg, "请至少勾选一条数据后再进行更新操作！", "");
                    frmPrint.Dispose();
                    return;
                }
                frmPrint.StartPosition = FormStartPosition.CenterScreen;
                frmPrint.callBack += updateActualClass;
                frmPrint.ShowDialog();
                frmPrint.Dispose();
            }
            catch (Exception ex)
            {
                l.WriteLog(19, sPointName + "：" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 跳转到计量实绩维护界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btEditWeightResult_Click(object sender, EventArgs e)
        {
            //ST_MainForm mainForm = new ST_MainForm(new CoreAppUser { userid = sUserId, username = sUserName });
            //ToolStripMenuItem mItem = new System.Windows.Forms.ToolStripMenuItem();
            //mItem.Text = "热送磅实绩维护";
            ////mItem.Tag = new ArrayList() { "页面名称", "页面所属的dll", "具体的页面frm" };
            //mItem.Tag = new ArrayList() { "热送磅实绩维护", "StorageMeterSystem", "frmHotDeliveryActual" };
            ////mItem.Click += new EventHandler(mainForm.SysMenuItem_Click);
            //mainForm.SysMenuItem_Click(mItem, e);
        }

        /// <summary>
        /// 选择实绩进行校秤功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btCalibrationScale_Click(object sender, EventArgs e)
        {
            try
            {
                string msg = "";
                List<MeterWorkStorageActual> lt = new List<MeterWorkStorageActual>();
                ultraGridActual.UpdateData();
                foreach (UltraGridRow ugr in ultraGridActual.Rows)
                {
                    if (ugr.Cells["UNCK"].Value.ToString().Trim().ToUpper() == "TRUE")
                    {
                        MeterWorkStorageActual preStorageUpdate = new MeterWorkStorageActual();
                        preStorageUpdate.actualNo = ugr.Cells["actualNo"].Text.Trim();
                        preStorageUpdate.predictionNo = ugr.Cells["predictionNo"].Text.Trim();
                        preStorageUpdate.actualWeight = Convert.ToDouble(ugr.Cells["actualWeight"].Text.Trim());
                        lt.Add(preStorageUpdate);
                    }
                }
                if (lt == null || lt.Count != 1)
                {
                    setMsgInfo(tbMsg, "校秤需要勾选1条计量实绩数据！", "");
                    return;
                }
                MeterWorkStorageCalibration calibration = new MeterWorkStorageCalibration();
                RESTfulResult<List<MeterWorkStorageSingleWgt>> rms = singleWgtService.doQuery(
                    new MeterWorkStorageSingleWgt { baseSpotNo = sPointNo, valueFlag = "1", weightType = "2" });
                if (rms.Succeed && rms.Data != null && rms.Data.Count > 0)
                {
                    MeterWorkStorageSingleWgt singleWgt = rms.Data[0];
                    calibration.actualWeight = lt[0].actualWeight; //校秤的实际重量(取选中的那条实绩的数据)
                    calibration.wgtNo = lt[0].actualNo; //选中的计量实绩的值，用于更新实绩表的数据

                    calibration.valueFlag = "1"; //状态(1 = 有效，0 = 无效)
                    calibration.createManNo = sUserId;
                    calibration.createManName = sUserName;
                    calibration.baseSpotNo = sPointNo; //校秤计量点的编号
                    calibration.baseSpotName = sPointName;//校秤计量点的名称
                    calibration.baseSpotName = sPointName;//校秤计量点的名称
                    calibration.meterClass = cmbMeterClass.Text;
                    calibration.meterGroup = cmbMeterGroup.Text;
                    calibration.gradeNo = singleWgt.gradeNo;
                    calibration.gradeName = singleWgt.gradeName;
                    calibration.specNo = singleWgt.specNo;
                    calibration.specName = singleWgt.specName;
                    calibration.theoryWeight = singleWgt.singleWeight; //理论重量
                    calibration.theoryWeightDiff = singleWgt.weightDiff; //理论重量差值
                    calibration.actualWeightDiff = calibration.actualWeight - calibration.theoryWeight;//校秤重量与理论重量实际差值
                                                                                                       //实际的偏差值大于理论偏差值
                    if (Math.Abs(Convert.ToDouble(calibration.actualWeightDiff)) > Math.Abs(Convert.ToDouble(calibration.theoryWeightDiff)))
                    {
                        calibration.qualifiedFlag = "0";//状态(1=合格，0=不合格)
                        msg = "校秤未通过！";
                    }
                    else
                    {
                        calibration.qualifiedFlag = "1";
                        msg = "校秤通过！";
                    }
                    RESTfulResult<string> rm = calibrationService.doAddWf(calibration);
                    if (rm.Succeed)
                    {
                        setMsgInfo(tbMsg, "校秤数据保存成功，计量重量：" + calibration.actualWeight + "kg；标准件理论重量：" + calibration.theoryWeight + "kg；重量差值：" + calibration.actualWeightDiff + "kg；" + msg, "");
                        l.WriteLog(8, tbMsg.Text);
                    }
                    else
                    {
                        setMsgInfo(tbMsg, "保存失败：" + rm.Data, "");
                    }
                    queryActual(); //较秤成功，进行实绩查询
                }
                else
                {
                    setMsgInfo(tbMsg, "未查询到秤点的校秤标准重量，不允许进行校秤！", "");
                }
            }
            catch (Exception ex)
            {
                l.WriteLog(19, sPointName + "：" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 按界面重量进行数据采集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btCalibrationSD_Click(object sender, EventArgs e)
        {
            try
            {
                string msg = "";
                MeterWorkStorageCalibration calibration = new MeterWorkStorageCalibration();
                RESTfulResult<List<MeterWorkStorageSingleWgt>> rms = singleWgtService.doQuery(
                    new MeterWorkStorageSingleWgt { baseSpotNo = sPointNo, valueFlag = "1", weightType = "2" });
                if (rms.Succeed && rms.Data != null && rms.Data.Count > 0)
                {
                    MeterWorkStorageSingleWgt singleWgt = rms.Data[0];
                    calibration.valueFlag = "1"; //状态(1 = 有效，0 = 无效)
                    calibration.createManNo = sUserId;
                    calibration.createManName = sUserName;
                    calibration.baseSpotNo = sPointNo; //校秤计量点的编号
                    calibration.baseSpotName = sPointName;//校秤计量点的名称
                    calibration.baseSpotName = sPointName;//校秤计量点的名称
                    calibration.meterClass = cmbMeterClass.Text;
                    calibration.meterGroup = cmbMeterGroup.Text;
                    calibration.gradeNo = singleWgt.gradeNo;
                    calibration.gradeName = singleWgt.gradeName;
                    calibration.specNo = singleWgt.specNo;
                    calibration.specName = singleWgt.specName;
                    calibration.theoryWeight = singleWgt.singleWeight; //理论重量
                    calibration.theoryWeightDiff = singleWgt.weightDiff; //理论重量差值
                    calibration.actualWeight = Convert.ToDouble(txtWeight.Text.Replace("kg", "").Trim()); //校秤的实际重量
                    calibration.actualWeightDiff = calibration.actualWeight - calibration.theoryWeight;//校秤重量与理论重量实际差值
                                                                                                       //实际的偏差值大于理论偏差值
                    if (Math.Abs(Convert.ToDouble(calibration.actualWeightDiff)) > Math.Abs(Convert.ToDouble(calibration.theoryWeightDiff)))
                    {
                        calibration.qualifiedFlag = "0";//状态(1=合格，0=不合格)
                        msg = "校秤未通过！";
                    }
                    else
                    {
                        calibration.qualifiedFlag = "1";
                        msg = "校秤通过！";
                    }
                    RESTfulResult<string> rm = calibrationService.doAddManual(calibration);
                    if (rm.Succeed)
                    {
                        setMsgInfo(tbMsg, "校秤数据保存成功，计量重量：" + calibration.actualWeight + "kg；标准件理论重量：" + calibration.theoryWeight + "kg；重量差值：" + calibration.actualWeightDiff + "kg；" + msg, "");
                        l.WriteLog(8, tbMsg.Text);
                    }
                    else
                    {
                        setMsgInfo(tbMsg, "保存失败：" + rm.Data, "");
                    }
                }
                else
                {
                    setMsgInfo(tbMsg, "未查询到秤点的校秤标准重量，不允许进行校秤！", "");
                }
            }
            catch (Exception ex)
            {
                l.WriteLog(19, sPointName + "：" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 预报编号点击按钮；用于做测试重量置为600kg
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label15_Click(object sender, EventArgs e)
        {
            if (sIpAddress.Contains("192.168.137.1") && rowPointInfo != null)
            {
                testFlage = true;
                setWeightCollect("4000"); //测试重量
                setWeightZero("7");//测试重量
                rowPointInfo.weight = 700;
                rowPointInfo.weightZero = 7;
            }
        }

        /// <summary>
        /// 预报编号点击按钮；用于做测试重量置为600kg
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void label12_Click(object sender, EventArgs e)
        {
            if (sIpAddress.Contains("192.168") && rowPointInfo != null)
            {
                testFlage = true;
                setWeightCollect("0"); //测试重量
                setWeightZero("0");//测试重量
                rowPointInfo.weight = 0;
            }
        }

        /// <summary>
        /// 远程清零
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btClear_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(rowPointInfo.moxaIp) || string.IsNullOrEmpty(rowPointInfo.moxaPort))
            {
                MessageBox.Show("[" + sPointName + "]远程清零的IP及端口未配置，请联系系统管理员！");
                return;
            }
            try
            {
                //设置IP和端口
                serverFullAddr = new IPEndPoint(IPAddress.Parse(rowPointInfo.moxaIp), int.Parse(rowPointInfo.moxaPort));
                sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //指定本地主机地址和端口号
                sock.Connect(serverFullAddr);
                //发送固定的指令“Z“到串口服务器
                byte[] byteSend = System.Text.Encoding.Default.GetBytes("Z");
                byte[] message = new byte[1024];
                string mess = "";
                int bytes = 0;
                try
                {
                    //发送数据
                    sock.Send(byteSend);
                    //接收数据
                    //bytes = sock.Receive(message);
                    //mess = mess + Encoding.Default.GetString(message, 0, bytes);//编码（当接收的字节大于1024的时候应当循环接收，仪表传回的不需要）
                    //do
                    //{
                    //    bytes = newSocket.Receive(message, message.Length, 0);
                    //    mess = mess + Encoding.ASCII.GetString(message, 0, bytes);
                    //}
                    // while (bytes > 0);
                    l.WriteLog(19, rowPointInfo.moxaIp + "：" + rowPointInfo.moxaPort + "：远程清零成功！");
                    MessageBox.Show("远程清零下发指令下发成功，请关注重量变化！");
                }
                catch (Exception ex)
                {
                    sock.Close();
                    MessageBox.Show("远程清零下发指令出现错误，请联系管理员" + ex);
                }
                sock.Close();
            }
            catch (Exception ee)
            {
                MessageBox.Show("连接服务器失败[" + rowPointInfo.moxaIp + "：" + rowPointInfo.moxaPort + "]。。。请联系系统管理员" + ee);
            }
        }

        #endregion 按钮点击事件汇总

        #region 计量相关方法

        /// <summary>
        /// 更新实绩表生产时间、班次、班组
        /// </summary>
        private void updateActualClass(DateTime productDate, string meterClass, string meterGroup)
        {
            try
            {
                int iCount = 0;
                List<MeterWorkStorageActual> lt = new List<MeterWorkStorageActual>();
                ultraGridActual.UpdateData();
                foreach (UltraGridRow ugr in ultraGridActual.Rows)
                {
                    if (ugr.Cells["UNCK"].Value.ToString().Trim().ToUpper() == "TRUE")
                    {
                        MeterWorkStorageActual preStorageUpdate = new MeterWorkStorageActual();
                        preStorageUpdate.actualNo = ugr.Cells["actualNo"].Text.Trim();
                        preStorageUpdate.predictionNo = ugr.Cells["predictionNo"].Text.Trim();
                        preStorageUpdate.updateManNo = sUserId;
                        preStorageUpdate.updateManName = sUserName;
                        preStorageUpdate.productDate = productDate;
                        preStorageUpdate.meterClass = meterClass;
                        preStorageUpdate.meterGroup = meterGroup;

                        lt.Add(preStorageUpdate);
                        iCount++;
                    }
                }
                if (lt == null || lt.Count == 0)
                {
                    setMsgInfo(tbMsg, "请至少勾选一条数据后再进行更新操作！", "");
                    return;
                }
                RESTfulResult<String> rms = actualService.doUpdateClient(lt);
                if (rms.Succeed)
                {
                    setMsgInfo(tbMsg, "共完成" + iCount + "条数据的修改！", "");
                    queryActual(); //更新班次信息后查询
                }
                else
                {
                    setMsgInfo(tbMsg, "修改班次信息失败！", "");
                }
            }
            catch (Exception ex)
            {
                l.WriteLog(19, sPointName + "：" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 自动判断重量是否为零点
        /// </summary>
        private void judgmentWeightZero()
        {
            try
            {
                //零点清零；只有在重量回零的时候，才进行零点清零；
                if (rowPointInfo.weightZero == 0)
                {
                    PbCache.isZeroAlarm = false;
                    weightLast = 0;
                    setWeightZero(rowPointInfo.weightZero.ToString());
                    setStableZero(true);//默认为红色，此处需要变成绿色；
                    return;
                }
                //零点判断及赋值；注意此处不清空零点的值
                if (rowPointInfo.weight < 200 && rowPointInfo.weightZero < 200)
                {
                    if (weightDiffZero > Math.Abs(rowPointInfo.weightZero.Value - weightLastZero))
                    {
                        weightStableTimesZero++;
                    }
                    else
                    {
                        weightStableTimesZero = 0;
                    }
                    //零点值赋值
                    if (weightStableTimesZero > weightStableScheduleZero)
                    {
                        setWeightZero(rowPointInfo.weightZero.ToString());
                        setStableZero(false);//true=绿色，false=红色；控件默认为红色，若从绿色变过来则此处需要变成红色；
                        doInsertZeroAlarm();//新增零点报警的数据
                        l.WriteLog(20, sPointName + "：零点报警，报警值：" + rowPointInfo.weightZero);
                    }
                }
                else
                {
                    PbCache.isZeroAlarm = true;
                    weightStableTimesZero = 0;
                }
                weightLastZero = rowPointInfo.weightZero.Value;
            }
            catch (Exception ex)
            {
                l.WriteLog(19, sPointName + "：" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 自动判断重量是否稳定
        /// </summary>
        private void judgmentWeightStatus()
        {
            try
            {
                if (rowPointInfo.weight > 100)
                {
                    if (weightDiff > Math.Abs(rowPointInfo.weight.Value - weightLast))
                    {
                        weightStableTimes++;
                    }
                    else
                    {
                        weightStableTimes = 0;
                    }

                    if (weightStableTimes > weightStableSchedule)
                    {
                        //理论重量不为0的时候，采集重量需要大于理论重量-800kg才能作为稳定值
                        if (preTack != null && preTack.theoreticalWeight != null && preTack.theoreticalWeight > 0)
                        {
                            if (rowPointInfo.weight > (preTack.theoreticalWeight - 800))
                            {
                                weightStatus = 0;
                                setStableWeight(true);
                            }
                            else
                            {
                                weightStatus = 1;
                                setStableWeight(false);
                            }
                        }
                        else
                        {
                            weightStatus = 0;
                            setStableWeight(true);
                        }
                    }
                    else
                    {
                        weightStatus = 1;
                        setStableWeight(false);
                    }
                    weightLast = rowPointInfo.weight.Value;
                }
                else
                {
                    weightStatus = 2;
                    weightStableTimes = 0;
                    setStableWeight(false);
                }
            }
            catch (Exception ex)
            {
                l.WriteLog(19, sPointName + "：" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 界面重量赋值，平台判断是否稳定
        /// 重量稳定状态：0稳定，1不稳定,2空磅
        /// </summary>
        private void judgmentWeightStatusPT()
        {
            try
            {
                if (rowPointInfo.weight > 100)
                {
                    if (preTack != null && preTack.theoreticalWeight != null && preTack.theoreticalWeight > 0)
                    {
                        if (rowPointInfo.weightStatus == 0 && rowPointInfo.weight > (preTack.theoreticalWeight - 800))
                        {
                            weightStatus = 0;
                            setStableWeight(true);
                        }
                        else
                        {
                            weightStatus = 1;
                            setStableWeight(false);
                        }
                    }
                    else
                    {
                        if (rowPointInfo.weightStatus == 0)
                        {
                            weightStatus = 0;
                            setStableWeight(true);
                        }
                        else
                        {
                            weightStatus = 1;
                            setStableWeight(false);
                        }
                    }
                }
                else
                {
                    weightStatus = 2;
                    setStableWeight(false);
                }
            }
            catch (Exception ex)
            {
                l.WriteLog(19, sPointName + "：" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 自动保存方法
        /// </summary>
        /// <returns></returns>
        private bool aotuSaveDB()
        {
            try
            {              
                if (string.IsNullOrEmpty(tbPredictionNo.Text) && !"00033".Equals(sPointNo))
                {
                    queryScale(); //自动保存前，若预报为空，进行预报查询
                }
                if (flagSaved)
                {
                    setMsgInfo(tbMsg, "已经保存，不允许重复保存！", "");
                    return false;
                }
                bool saveSuccessful = saveDB();
                if (!saveSuccessful)
                {
                    //保存失败不再自动计量；2021年10月20日保存失败也继续计量，避免出现更新导致的服务端异常！
                    //ckAutoSave.Checked = false;
                }
                queryScale(); //自动保存成功，进行预报查询
                queryActual(); //自动保存成功，进行预报查询
                return saveSuccessful;
            }
            catch (Exception ex)
            {
                l.WriteLog(19, sPointName + "：" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 计量保存方法
        /// </summary>
        /// <returns></returns>
        private bool saveDB()
        {
            try
            {
                if (string.IsNullOrEmpty(cmbMeterGroup.Text) || string.IsNullOrEmpty(cmbMeterClass.Text))
                {
                    setMsgInfo(tbMsg, "班次、班组均不允许为空！", "");
                    return false;
                }
                MeterWorkStorageActual storageActual = new MeterWorkStorageActual();
                storageActual.predictionNo = tbPredictionNo.Text.Trim();
                storageActual.netWeight = Convert.ToDouble(txtWeight.Text.Replace("kg", "").Trim());
                storageActual.grossWeight = Convert.ToDouble(txtWeight.Text.Replace("kg", "").Trim()); //采集的重量
                if (storageActual.grossWeight < 100)
                {
                    setMsgInfo(tbMsg, "重量小于100，不允许进行保存！", "");
                    return false;
                }
                //减零点操作
                if (ckMinusZero.Checked && !string.IsNullOrEmpty(numupTareWeight.Text))
                {
                    storageActual.tareWeight = Convert.ToDouble(numupTareWeight.Value);//注意减零点勾选后，直接加上零点的值就可以,此处的±计量员处理；
                    storageActual.netWeight = storageActual.grossWeight + storageActual.tareWeight; //注意：此处是“+”；
                }
                //秤体无法回零时候的操作
                if (!"0".Equals(txtReferWeight.Text.Replace("kg", "").Trim()))
                {
                    storageActual.referWeight = Convert.ToDouble(txtReferWeight.Text.Replace("kg", "").Trim());
                    storageActual.netWeight = storageActual.netWeight - storageActual.referWeight; //注意：此处是“-”；
                }
                storageActual.actualWeight = storageActual.netWeight;
                //产量时间;班组;班次
                storageActual.productDate = dtpProductDate.Value;
                storageActual.meterGroup = cmbMeterGroup.Text;
                storageActual.meterClass = cmbMeterClass.Text;
                storageActual.baseSpotNo = sPointNo;
                storageActual.baseSpotName = sPointName;
                storageActual.createManNo = sUserId;
                storageActual.createManName = sUserName;

                RESTfulResult<string> rm = actualService.doAddHotDeliveryBelt(storageActual);

                if (rm.Succeed)
                {
                    //actNo = rm.Data;
                    setMsgInfo(tbMsg, "保存成功" + rm.Data.Split('#')[1] + "", "");
                    if (storageActual.referWeight != null && storageActual.referWeight > 0)
                    {
                        openWarnMsgBelt(sPointName + "仪表存在底数[ " + storageActual.referWeight + " kg ]，请及时处理！");//回调主界面方法
                    }
                    if (rm.Data.Contains("5支报警") && ultraGrid1.Rows != null && ultraGrid1.Rows.Count == 1)
                    {
                        setMsgMsg(tbMsg, "color", "Red");
                        openWarnMsgBelt(sPointName + "预报仅剩余 5 支，请及时做预报！");//回调主界面方法
                    }
                    else if (rm.Data.Contains("10支报警") && ultraGrid1.Rows != null && ultraGrid1.Rows.Count == 1)
                    {
                        setMsgMsg(tbMsg, "color", "Lime");
                        openWarnMsgBelt(sPointName + "预报仅剩余 10 支，请及时做预报！");//回调主界面方法
                    }
                    else
                    {
                        setMsgMsg(tbMsg, "color", "White");
                    }

                    //实绩重量与预报重量差值报警
                    if (preTack != null && preTack.theoreticalWeight != null && preTack.theoreticalWeight > 0 && preTack.weightDiff > 0)
                    {
                        if (Math.Abs(preTack.theoreticalWeight.Value - storageActual.actualWeight.Value) > preTack.weightDiff.Value)
                        {
                            setMsgInfo(tbMsg, "保存成功" + rm.Data.Split('#')[1] + "；" +
                                "重量偏差超过[" + preTack.weightDiff.Value + "]kg", "");
                            openWarnMsgBelt(sPointName + "偏差超过[" + preTack.weightDiff.Value + "]kg");
                            setMsgMsg(tbMsg, "color", "Red");
                        }
                    }
                    flagSaved = true;
                    return true;
                }
                else
                {
                    setMsgInfo(tbMsg, "本次保存失败：" + rm.Data, "");
                    setMsgMsg(tbMsg, "color", "Red");
                    openWarnMsgBelt(sPointName + "本次保存失败，系统将会重新自动保存，请核查是否保存成功！");//回调主界面方法
                    l.WriteLog(19, "本次保存失败：" + rm.Message);
                    return false;
                }
            }
            catch (Exception ex)
            {
                l.WriteLog(19, sPointName + "：" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 预报查询接口
        /// </summary>
        private void queryScale()
        {
            try
            {
                DataTable dtScaleTable = dataTable1.Clone();
                CommonPage<PreStorageScale> cp = new CommonPage<PreStorageScale>();
                cp.param = new PreStorageScale { valueFlag = "9", baseSpotNo = sPointNo };
                RESTfulResult<List<PreStorageScale>> rms = preStorageScaleService.doQueryWf(cp.param);
                if (rms.Succeed)
                {
                    if (rms.Data != null && rms.Data.Count > 0)
                    {
                        //此处进行倒序排列
                        rms.Data.Sort((a, b) => a.predictionNo.CompareTo(b.predictionNo));
                        dtScaleTable = rms.Data.ListToDataTable<PreStorageScale>();

                        ClsControlPack.CopyDataToDatatable(ref dtScaleTable, ref dataTable1, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGrid1);
                        if (ckAutoSave.Checked)
                        {
                            //自动计量时填充最新的预报到界面;若用户选择了预报，则以用户选择的为准！
                            DataRow[] dr = null;
                            if (!string.IsNullOrEmpty(sClickPredictionNo))
                            {
                                dr = dtScaleTable.Select("predictionNo='" + sClickPredictionNo + "'");
                            }
                            if (dr == null || dr.Length == 0)
                            {
                                dr = dtScaleTable.Select("predictionNo='" + ultraGrid1.Rows[0].Cells["predictionNo"].Text.Trim() + "'");
                                sClickPredictionNo = "";
                            }
                            if (dr != null && dr.Length > 0)
                            {
                                preTack = dr[0].CreateItem<PreStorageScale>();
                            }
                        }
                    }
                    else
                    {
                        dtScaleTable.Clear();
                        preTack = null;
                        ClsControlPack.CopyDataToDatatable(ref dtScaleTable, ref dataTable1, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGrid1);
                    }
                }
                autoAutoFill(preTack); //查询预报后，不管有没有数据，都重新填充一次界面
            }
            catch (Exception ex)
            {
                preTack = null;
                l.WriteLog(19, sPointName + "：" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 实绩查询接口
        /// </summary>
        private void queryActual()
        {
            try
            {
                DataTable dtActualTable = dataTable2.Clone();
                CommonPage<MeterWorkStorageActual> cp = new CommonPage<MeterWorkStorageActual>();

                cp.param = new MeterWorkStorageActual(); //{ valueFlag = "1", baseSpotNo = cmbPoint.Value?.ToString() };
                cp.param.baseSpotNo = sPointNo;
                cp.param.startTime = Convert.ToDateTime(DateTime.Now.AddDays(-0.5).ToString("yyyy-MM-dd") + " 00:00:00").ToString("yyyy-MM-dd HH:mm:ss");
                cp.param.endTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59").ToString("yyyy-MM-dd HH:mm:ss");

                RESTfulResult<List<MeterWorkStorageActual>> rms = actualService.doQuery(cp.param);
                if (rms.Succeed)
                {
                    if (rms.Data != null && rms.Data.Count > 0)
                    {
                        dtActualTable = rms.Data.ListToDataTable<MeterWorkStorageActual>();

                        ClsControlPack.CopyDataToDatatable(ref dtActualTable, ref dataTable2, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGridActual);

                        foreach (UltraGridRow ugr in ultraGridActual.Rows)
                        {
                            if (ugr.Cells["valueFlag"].Value.ToString() == "0")
                            {
                                ugr.Appearance.BackColor = Color.Red;
                            }
                            else
                            {
                                ugr.Appearance.BackColor = Color.White;
                            }
                        }
                    }
                    else
                    {
                        dtActualTable.Clear();
                        ClsControlPack.CopyDataToDatatable(ref dtActualTable, ref dataTable2, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGridActual);
                    }
                }
            }
            catch (Exception ex)
            {
                l.WriteLog(19, sPointName + "：" + ex.Message);
                throw ex;
            }
        }

        /// <summary>
        /// 新增零点报警的数据
        /// </summary>
        private void doInsertZeroAlarm()
        {
            if (!PbCache.isZeroAlarm)
            {
                PbCache.isZeroAlarm = true;
                MeterWorkZeroAlarm workZeroAlarm = new MeterWorkZeroAlarm();
                workZeroAlarm.zeroWeight = PbCache.collect.weight;
                workZeroAlarm.spotTypeNo = PbCache.sportInfo.spotTypeNo;
                workZeroAlarm.spotTypeName = PbCache.sportInfo.spotTypeName;
                workZeroAlarm.baseSpotNo = PbCache.sportInfo.baseSpotNo;
                workZeroAlarm.baseSpotName = PbCache.sportInfo.baseSpotName;
                workZeroAlarm.scalePointNo = PbCache.collect_no;
                workZeroAlarm.createManNo = PbCache.sportInfo.baseSpotNo;
                workZeroAlarm.createManName = PbCache.sportInfo.baseSpotName;
                RESTfulResult<String> rms = zeroAlarmService.doInsertZeroAlarm(workZeroAlarm);
                if (rms.Succeed)
                {
                    l.WriteLog(20, "新增成功：" + workZeroAlarm.baseSpotName + "：" + workZeroAlarm.zeroWeight);
                }
                else
                {
                    l.WriteLog(20, "操作失败：" + workZeroAlarm.baseSpotName + "：" + workZeroAlarm.zeroWeight + rms.Data + rms.Message);
                }
            }
        }

        /// <summary>
        /// 自动填充表格的数据
        /// </summary>
        private void autoAutoFill(PreStorageScale preTack)
        {
            if (preTack == null || string.IsNullOrEmpty(preTack.predictionNo))
            {
                tbPredictionNo.Text = ""; //预报编号
                tbSpecName.Text = ""; //规格
                tbGradeName.Text = ""; //钢号
                tbHeatNo.Text = "";//批次号
                tbPackageNo.Text = "";//顺序号
                tbBlockNum.Text = "";//总支数
            }
            else
            {
                if (string.IsNullOrEmpty(preTack.specName))
                {
                    setMsgInfo(tbMsg, "规格为空，不允许进行计量操作，请联系预报人员进行补充！", "");
                    return;
                }
                if (string.IsNullOrEmpty(preTack.gradeName))
                {
                    setMsgInfo(tbMsg, "钢种为空，不允许进行计量操作，请联系预报人员进行补充！", "");
                    return;
                }
                if (string.IsNullOrEmpty(preTack.heatNo))
                {
                    setMsgInfo(tbMsg, "炉号为空，不允许进行计量操作，请联系预报人员进行补充！", "");
                    return;
                }
                if (string.IsNullOrEmpty(preTack.packageNo))
                {
                    setMsgInfo(tbMsg, "顺序号为空，不允许进行计量操作，请联系预报人员进行补充！", "");
                    return;
                }
                if (string.IsNullOrEmpty(preTack.blockNum))
                {
                    setMsgInfo(tbMsg, "总支数为空，不允许进行计量操作，请联系预报人员进行补充！", "");
                    return;
                }
                tbPredictionNo.Text = preTack.predictionNo; //预报编号
                tbSpecName.Text = preTack.specName; //规格
                tbGradeName.Text = preTack.gradeName; //钢号
                tbHeatNo.Text = preTack.heatNo;//批次号
                tbPackageNo.Text = preTack.packageNo;//顺序号
                tbBlockNum.Text = preTack.blockNum;//总支数
                if (string.IsNullOrEmpty(cmbMeterClass.Text) && string.IsNullOrEmpty(cmbMeterGroup.Text))
                {
                    cmbMeterClass.Text = preTack.meterClass;//班次
                    cmbMeterGroup.Text = preTack.meterGroup; //班组
                }
            }
        }

        #endregion 计量相关方法

        #region 线程中赋值的控件需使用委托

        private delegate void UpdateUIEventHander(object sender, UpdateUIArgs args); //自定义事件用来从线程中更新控件的值

        public class UpdateUIArgs : EventArgs
        {
            public string textValue { get; private set; }

            public UpdateUIArgs(string textValue)
            {
                this.textValue = textValue;
            }
        }

        /// <summary>
        /// 更新界面的UI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void UpdateUI_Method(object sender, UpdateUIArgs args)
        {
            if (sender is UltraTextEditor)
            {
                if (args.textValue == "" || args.textValue == null)
                {
                    ((UltraTextEditor)sender).Text = "0 kg";
                }
                else
                {
                    ((UltraTextEditor)sender).Text = args.textValue + " kg";
                }
            }
            else if (sender is Button)
            {
                if (args.textValue == "red")
                {
                    ((Button)sender).BackColor = Color.Red;
                    ((Button)sender).ForeColor = Color.White;
                }
                else if (args.textValue == "green")
                {
                    ((Button)sender).BackColor = Color.White;
                    ((Button)sender).ForeColor = Color.Black;
                }
                else
                {
                    ((Label)sender).Text = args.textValue;
                }
            }
            else if (sender is PictureBox)
            {
                if (args.textValue == "red")
                {
                    ((PictureBox)sender).Load(PbCache.path + "\\image\\icon\\red.gif");
                }
                else
                {
                    ((PictureBox)sender).Load(PbCache.path + "\\image\\icon\\green.gif");
                }
            }
        }

        /// <summary>
        /// 记录当前的颜色，在线程中窑调用下面的setControl方法前
        /// 可先判断当前的颜色与显示颜色是否一致
        /// 若一致则可不调用setControl，不一致再调用
        /// </summary>
        public bool isWeightCollectGreen = true;

        public bool isWeightZeroGreen = true;

        /// <summary>
        /// 采集重量赋值
        /// </summary>
        /// <param name="bGreen"></param>
        public void setWeightCollect(string weight)
        {
            txtWeight.Invoke(new UpdateUIEventHander(UpdateUI_Method), txtWeight, new UpdateUIArgs(weight));
        }

        private void tableLayoutPanelButton_Paint(object sender, PaintEventArgs e)
        {
        }

        /// <summary>
        /// 采集重量赋值
        /// </summary>
        /// <param name="bGreen"></param>
        public void setWeightZero(string weight)
        {
            txtReferWeight.Invoke(new UpdateUIEventHander(UpdateUI_Method), txtReferWeight, new UpdateUIArgs(weight));
        }

        /// <summary>
        /// 预报实体类点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ultraGrid1_ClickCell(object sender, ClickCellEventArgs e)
        {
            try
            {
                if (ultraGrid1.ActiveRow == null)
                {
                    return;
                }
                //界面赋值
                UltraGridRow ugr = ultraGrid1.ActiveRow;
                if (ugr != null)
                {
                    preTack.predictionNo = ugr.Cells["predictionNo"].Text.Trim(); //预报编号
                    preTack.specName = ugr.Cells["specName"].Text.Trim();         //规格
                    preTack.gradeName = ugr.Cells["gradeName"].Text.Trim();       //钢号
                    preTack.batchNo = ugr.Cells["batchNo"].Text.Trim();           //批次号
                    preTack.heatNo = ugr.Cells["heatNo"].Text.Trim();         //炉号
                    preTack.packageNo = ugr.Cells["packageNo"].Text.Trim();       //顺序号
                    preTack.blockNum = ugr.Cells["blockNum"].Text.Trim();         //总支数
                    preTack.theoreticalWeight = Convert.ToDouble(string.IsNullOrEmpty(ugr.Cells["theoreticalWeight"].Text.Trim()) ? "0" : ugr.Cells["theoreticalWeight"].Text.Trim());    //理论重量
                    preTack.weightDiff = Convert.ToDouble(string.IsNullOrEmpty(ugr.Cells["weightDiff"].Text.Trim()) ? "0" : ugr.Cells["weightDiff"].Text.Trim());    //理论重量差值
                    preTack.meterGroup = ugr.Cells["meterGroup"].Text.Trim();     //班次
                    preTack.meterClass = ugr.Cells["meterClass"].Text.Trim();     //班次
                    preTack.memo = ugr.Cells["memo"].Text.Trim();//备注
                    sClickPredictionNo = preTack.predictionNo; //设置点击的预报编号
                    DialogResult dr = MessageBox.Show("是否将预报[" + preTack.predictionNo + "]设置为当前过磅预报，设置后在预报计量完成前，不会自动更换预报！", "提示", MessageBoxButtons.OKCancel);
                    if (dr == DialogResult.Cancel)
                    {
                        return;
                    }
                    autoAutoFill(preTack); //点击行进行自动填充
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ultraGrid1_ClickCell方法处理异常：" + ex);
            }
        }

        /// <summary>
        /// 重量稳定圆钮
        /// </summary>
        /// <param name="bGreen"></param>
        public void setStableWeight(bool bGreen)
        {
            string sValue = bGreen ? "green" : "red";
            picStableWeight.Invoke(new UpdateUIEventHander(UpdateUI_Method), picStableWeight, new UpdateUIArgs(sValue));
            isWeightCollectGreen = bGreen;
        }

        /// <summary>
        /// 零点报警圆钮
        /// </summary>
        /// <param name="bGreen"></param>
        public void setStableZero(bool bGreen)
        {
            string sValue = bGreen ? "green" : "red";
            picStableZero.Invoke(new UpdateUIEventHander(UpdateUI_Method), picStableZero, new UpdateUIArgs(sValue));
            isWeightZeroGreen = bGreen;
        }

        /// <summary>
        /// 控件值设置
        /// </summary>
        /// <param name="control"></param>
        /// <param name="ResultMessage"></param>
        /// <param name="sType"></param>
        public void setMsgInfo(Control control, string ResultMessage, string sType)
        {
            setMsgMsg(control, ResultMessage, sType);
        }

        /// <summary>
        /// 如果ResultMessage为true或者false，则sType 为0的时候readonly  1为enable  2为visable  3为check
        /// </summary>
        /// <param name="control"></param>
        /// <param name="ResultMessage"></param>
        /// <param name="sType"></param>
        private void setMsgMsg(Control control, string ResultMessage, string sType)
        {
            if (control.InvokeRequired)
            {
                Action<Control, string, string> action = new Action<Control, string, string>(setMsgInfo);
                Invoke(action, new object[] { control, ResultMessage, sType });
            }
            else
            {
                if (ResultMessage == "true" || ResultMessage == "false")
                {
                    switch (sType)
                    {
                        case "1":
                            control.Enabled = ResultMessage == "true" ? true : false;
                            ; break;
                        case "2":
                            control.Visible = ResultMessage == "true" ? true : false;
                            ; break;
                        case "3":
                            ((CheckBox)control).Checked = ResultMessage == "true" ? true : false;
                            break;

                        default: break;
                    }
                }
                else if (ResultMessage == "color")
                {
                    switch (sType)
                    {
                        case "Red":
                            control.BackColor = Color.Red;
                            ; break;
                        case "Lime":
                            control.BackColor = Color.Lime;
                            ; break;
                        case "White":
                            control.BackColor = Color.White;
                            ; break;
                        default: break;
                    }
                }
                else
                {
                    control.Text = ResultMessage == null ? "" : ResultMessage;
                    l.WriteLog(8, sPointName + "：" + tbMsg.Text);
                }
            }
        }

        #endregion 线程中赋值的控件需使用委托
    }
}