using com.hnshituo.core.webapp.vo;
using Common;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using JC_MeasuringSystem;
using MeterPlugInLibrary;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows.Forms;

namespace RailMeterSystem
{
    public partial class frmStaticMain : Form
    {
        #region

        //实时表数据采集 第一个是静态1，第二个是静态2
        private StaticDataCollectionControl collection1 = new StaticDataCollectionControl();

        private StaticDataCollectionControl collection2 = new StaticDataCollectionControl();

        //图片控制器含图片压缩及上传sftp
        //ImageControl imageControl = new ImageControl();

        /// <summary>
        /// 基础数据载入
        /// </summary>
        private BaseDbCls bd = new BaseDbCls();

        private Log l = Log.GetInstance();
        private string userId = "", userName = "";
        private int iPic = 0;
        private bool isEditCarNo = false; //是否编辑车号
        private string oldEditCarNo = "";//上一次编辑的车号
        private CoreAppUser appUser = null;

        private StaticCollectModel scModel1 = new StaticCollectModel(); //静态1
        private StaticCollectModel scModel2 = new StaticCollectModel(); //静态2
        #endregion

        #region 查询服务

        private int searchLimit = 3; //用于卡控查询，定时任务每1s加一次，若小于2则不会查询数据；

        //计量预报
        private PreRailwayScale preTack = null;

        //一次计量重量
        private MeterWorkRailwayActFirst first = null;

        private PreRailwayScaleService PreService = new PreRailwayScaleService();//查询预报信息
        private MeterWorkRailwayActualService mwas = new MeterWorkRailwayActualService();//计量结净数据
        private MeterWorkRailwayActFirstService railwayActFirstService = new MeterWorkRailwayActFirstService();//一次计量数据
        private MeterBaseMatterInfoService matterService = new MeterBaseMatterInfoService();//查询计量基础信息

        #endregion

        #region 下拉框相关事件

        //===============下拉框相关变量===============
        private ListBox show;              //智能拼音输入时弹出的表框

        private DataTable dtMaterial;
        private int showLocation = 0;
        //===============下拉框相关变量=============
        #endregion

        //===============自重计量相关变量===========
        private bool isUsedFactoryWeight = false; //是否使用自重

        private double tareWeight = 0;//皮重
        //===============自重计量相关变量===========

        public frmStaticMain()
        {
            InitializeComponent();
        }

        #region 数据初始清理

        private void Clean()
        {
            try
            {
                setMsgInfo(lbPointName, "", "");

                updateSport("");

                PbStaticRailwayCache.videoInfo = null;
                PbStaticRailwayCache.dtStartTime = null;
                PbStaticRailwayCache.sportInfo = null;
                PbStaticRailwayCache.collect = null;
                first = null;

                //退出语音登录
                try
                {
                    VoiceClose();
                    IPVideoClose();
                }
                catch (Exception ex)
                {
                }
                setPanelRemovenfo(panel1);

                CleanForm(); //Clean方法
            }
            catch (Exception ex)
            {
                MessageBox.Show("Clean方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "Clean方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        private void CleanForm()
        {
            try
            {
                isUsedFactoryWeight = false; //是否使用自重
                btnZZWgt.BackColor = Color.DodgerBlue; //点击保存后，复磅按钮重新变原色
                tareWeight = 0; //自重置为0
                strCarNo = "";
                PbStaticRailwayCache.dtStartTime = null;
                ucStaticTrackMeterInfo1.setPreTrackInfo(new PreRailwayScale { });

                //DataTable dtYb = dtRailwayScale.Clone();
                //setGridInfo(ultraGrid1, dtYb, this.dtRailwayScale);

                //DataTable dtSj = this.dtRailwayActFirst;
                //setGridInfo(ultraGrid2, dtSj, this.dtRailwayActFirst);

                //DataTable dtQxp = this.dtRailwayActual.Clone();
                //setGridInfo(ultraGrid3, dtQxp, this.dtRailwayActual);

                ucStorageWeightT1.setWgt(0);
                ucStorageWeightT1.setStable(true);

                ucStorageWeightT2.setWgt(0);
                ucStorageWeightT2.setStable(true);

                setMsgInfo(pl1, "Color", "Lime");
                setMsgInfo(pl2, "Color", "Lime");
                setMsgInfo(pl3, "Color", "Lime");
                //setMsgInfo(cmbCarType, "单秤", ""); //2021年4月26日 称重完成后，不在恢复成单秤的状态

                setMsgInfo(txtGroess, "", "");
                setMsgInfo(txtTare, "0", "");
                setMsgInfo(txtNet, "", "");
                //setMsgInfo(txtCarNo, "", ""); //2021年4月28日 不再清空车号，因为又会将车号再写上来，也需要进行复磅保存
            }
            catch (Exception ex)
            {
                //MessageBox.Show("CleanForm方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "CleanForm方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        #endregion

        #region 对讲代码

        /// <summary>
        /// 硬盘录像机登录
        /// </summary>
        private DhCameraShot cameraShotMain = new DhCameraShot();

        /// <summary>
        /// 必须先打开连接
        /// </summary>
        private bool GetIPVideo(MeterBaseVideoinfo video)
        {
            try
            {
                cameraShotMain.ip = video.videoip;
                cameraShotMain.port = video.vdoPort;
                cameraShotMain.uid = video.vdoUser;
                cameraShotMain.pwd = video.vdoPwd;

                cameraShotMain.Connection();
            }
            catch (Exception ex)
            {
                setMsgInfo(txtMsgInfo, "视频连接打开失败：" + ex.Message, "");
                return false;
            }
            return true;
        }

        /// <summary>
        ///  必须先打开视频，然后再打开语音
        /// </summary>
        private void VoiceOpen()
        {
            try
            {
                if (cameraShotMain.StartTalk())
                {
                    btnOpenVoice.Text = "关闭对讲";
                }
            }
            catch (Exception ex)
            {
                setMsgInfo(txtMsgInfo, "打开语音失败：" + ex.Message, "");
            }
        }

        /// <summary>
        /// 关闭语音对讲
        /// </summary>
        private void VoiceClose()
        {
            try
            {
                if (cameraShotMain.StopTalk())
                {
                    setMsgInfo(btnOpenVoice, "打开对讲", "");
                }
            }
            catch (Exception ex)
            {
                setMsgInfo(txtMsgInfo, "打开对讲失败：" + ex.Message, "");
            }
        }

        /// <summary>
        /// 关闭视频
        /// </summary>
        private void IPVideoClose()
        {
            try
            {
                cameraShotMain.Close();
            }
            catch (Exception ex)
            {
                setMsgInfo(txtMsgInfo, "关闭对讲失败：" + ex.Message, "");
            }
        }

        private List<PictureBox> ltPicBoxs = new List<PictureBox>();

        /// <summary>
        /// 加载图相框
        /// </summary>
        private void setPicBoxSet()
        {
            try
            {
                if (PbStaticRailwayCache.videoChild != null && PbStaticRailwayCache.videoChild.Count > 0)
                {
                    if (PbStaticRailwayCache.sportInfo != null)
                    {
                        if (PbStaticRailwayCache.sportInfo.baseSpotNo == "00010")
                        {
                            for (int k = 1; k <= 2; k++)
                            {
                                PictureBox pb = new PictureBox();
                                pb.Name = "pb" + k;
                                pb.Dock = DockStyle.Top;
                                pb.Height = 260;
                                pb.DoubleClick += new EventHandler(PictureBoxDoubleClick);
                                pb.BorderStyle = BorderStyle.FixedSingle;
                                panel1.Controls.Add(pb);
                                ltPicBoxs.Add(pb);

                                cameraShotMain.RealPlay(pb, k);
                            }
                        }
                        else
                        {
                            for (int k = 3; k <= 4; k++)
                            {
                                PictureBox pb = new PictureBox();
                                pb.Name = "pb" + k;
                                pb.Dock = DockStyle.Top;
                                pb.Height = 260;
                                pb.DoubleClick += new EventHandler(PictureBoxDoubleClick);
                                pb.BorderStyle = BorderStyle.FixedSingle;
                                panel1.Controls.Add(pb);
                                ltPicBoxs.Add(pb);

                                cameraShotMain.RealPlay(pb, k);
                            }
                        }

                        #region 室内摄像头
                        PictureBox pb5 = new PictureBox();
                        pb5.Name = "pb5";
                        pb5.Dock = DockStyle.Top;
                        pb5.Height = 260;
                        pb5.DoubleClick += new EventHandler(PictureBoxDoubleClick);
                        pb5.BorderStyle = BorderStyle.FixedSingle;
                        panel1.Controls.Add(pb5);
                        ltPicBoxs.Add(pb5);
                        cameraShotMain.RealPlay(pb5, 5);
                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("setPicBoxSet载入录像异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "setPicBoxSet载入录像异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        public void setPanelRemovenfo(Panel control)
        {
            setPanelRemoveMsg(control);
        }

        /// <summary>
        /// 如果ResultMessage为true或者false，则sType 为0的时候readonly  1为enable  2为visable
        /// </summary>
        /// <param name="control"></param>
        /// <param name="ResultMessage"></param>
        /// <param name="sType"></param>
        private void setPanelRemoveMsg(Panel p)
        {
            try
            {
                if (p.InvokeRequired)
                {
                    Action<Panel> action = new Action<Panel>(setPanelRemovenfo);
                    Invoke(action, new object[] { p });
                }
                else
                {
                    for (int i = p.Controls.Count - 1; i >= 0; i--)
                    {
                        p.Controls.RemoveAt(i);
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("setPanelRemove移除界面控件异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "setPanelRemove移除界面控件异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        #endregion

        #region 控件值设置

        //如果ResultMessage为true或者false，则sType 为0的时候readonly  1为enable  2为visable
        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)
        {
            try
            {
                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 "GreenYellow":
                                control.BackColor = Color.GreenYellow;
                                ; break;
                            default: break;
                        }
                    }
                    else
                    {
                        control.Text = ResultMessage == null ? "" : ResultMessage;
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("setMsgMsg设置控件值异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "setMsgMsg设置控件值异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        private delegate object GetControlPropertyCallBack(Control control, string name);

        /// <summary>
        /// 设置控件的值
        /// </summary>
        /// <param name="control"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public object GetControlProperty(Control control, string name)
        {
            try
            {
                if (control.InvokeRequired == true)
                {
                    GetControlPropertyCallBack CallBack = new GetControlPropertyCallBack(GetControlProperty);
                    return control.Invoke(CallBack, new object[] { control, name });
                }
                else
                {
                    Type type = control.GetType();
                    return type.InvokeMember(name,
                        BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance,
                      null, control, null);
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("GetControlProperty设置控件的值异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "setMsgMsg设置控件值异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                return null;
            }
        }

        /// <summary>
        /// 设置颜色提醒
        /// </summary>
        /// <param name="pointNo"></param>
        /// <param name="sType">1橘色提醒，2白色 3红色</param>
        private void setGridColor(UltraGrid control, string pointNo, string sType)
        {
            if (control != null && control.Rows != null && control.Rows.Count > 0 && !string.IsNullOrEmpty(pointNo) && !string.IsNullOrEmpty(sType))
            {
                setGridColorMsg(control, pointNo, sType);
            }
        }

        private void setGridColorMsg(UltraGrid control, string pointNo, string sType)
        {
            try
            {
                if (ultraGridPW.InvokeRequired)
                {
                    Action<UltraGrid, string, string> action = new Action<UltraGrid, string, string>(setGridColor);
                    Invoke(action, new object[] { control, pointNo, sType });
                }
                else
                {
                    if (control != null && control.Rows != null && control.Rows.Count > 0)
                    {
                        foreach (UltraGridRow ugr in control.Rows)
                        {
                            if (ugr.Cells["baseSpotNo"].Text == pointNo)
                            {
                                switch (sType)
                                {
                                    case "1":
                                        if (string.IsNullOrEmpty(ugr.Cells["controlIp"].Text))
                                        {
                                            ugr.Appearance.BackColor = Color.Orange;
                                        };
                                        break;

                                    case "2":
                                        ugr.Appearance.BackColor = Color.White;
                                        break;

                                    case "3":
                                        ugr.Appearance.BackColor = Color.Red;
                                        break;
                                }
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("setGridColorMsg设置颜色异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "setGridColorMsg设置颜色异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        public void setGridInfo(UltraGrid control, DataTable dt1, DataTable dt2)
        {
            setGridMsg(control, dt1, dt2);
        }

        /// <summary>
        /// 如果ResultMessage为true或者false，则sType 为0的时候readonly  1为enable  2为visable
        /// </summary>
        /// <param name="control"></param>
        /// <param name="ResultMessage"></param>
        /// <param name="sType"></param>
        private void setGridMsg(UltraGrid p, DataTable dt1, DataTable dt2)
        {
            try
            {
                if (p.InvokeRequired)
                {
                    Action<UltraGrid, DataTable, DataTable> action = new Action<UltraGrid, DataTable, DataTable>(setGridInfo);
                    Invoke(action, new object[] { p, dt1, dt2 });
                }
                else
                {
                    ClsControlPack.CopyDataToDatatable(ref dt1, ref dt2, true);
                    ClsControlPack.RefreshAndAutoSize(p);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("setGridMsg设置界面的值异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "setGridMsg设置界面的值异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        #endregion

        #region 事件处理
        private string _controlIp = "";

        private void frmStaticMain_Load(object sender, EventArgs e)
        {
            try
            {   //初始化时间控件的值
                dateTimeStart.Value = DateTime.Now.Date;
                dateTimeEnd.Value = DateTime.Now.Date.AddDays(1).AddSeconds(-1);

                _controlIp = GetIP();
                if (!_controlIp.Contains("192") && !_controlIp.Contains("168")) //只有在测试环境，【测试】按钮才有效
                {
                    button1.Visible = false;
                    button1.Enabled = false;
                }
                userId = ((ST_MainForm)(this.MdiParent)).UserID;
                userName = ((ST_MainForm)(this.MdiParent)).UserName;
                appUser = ((ST_MainForm)(this.MdiParent)).AppUser;

                collection1.EventDataCollectionArgs += new StaticEventDataCollection(EventData);//数据采集1
                collection2.EventDataCollectionArgs += new StaticEventDataCollection(EventData2);//数据采集2txtTare

                //状态(0：未配车；1：未使用；2：已使用；3：已作废；4：正使用)
                //ultraGrid1.DisplayLayout.Bands[0].Columns["valueFlag"].ValueList = GetValueListByString("0:未配车,1:未使用,2:已使用,3:已作废,4:正使用");
                //ultraGridScaleHis.DisplayLayout.Bands[0].Columns["valueFlag"].ValueList = GetValueListByString("0:未配车,1:未使用,2:已使用,3:已作废,4:正使用");

                if (!bd.setBaseDb())
                {
                    MessageBox.Show("基础数据载入失败，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n");
                    l.WriteLog(13, "基础数据载入失败，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n");
                    return;
                }
                else
                {
                    timer1.Start();
                    timerSearchLimit.Start();
                    List<MeterBaseSpotInfo> lt = PbStaticRailwayCache.sportInfos.Where(s => s.baseSpotName.Contains("静态")).ToList();
                    dtJGPointInfo.Clear(); //2021年4月22日 杨秀东新加
                    DataTable dt = dtJGPointInfo.Clone();
                    foreach (MeterBaseSpotInfo mbsi in lt)
                    {
                        DataRow dr = dt.NewRow();
                        dr["baseSpotNo"] = mbsi.baseSpotNo;
                        dr["baseSpotName"] = mbsi.baseSpotName;
                        dr["validFlag"] = string.IsNullOrEmpty(mbsi.controlIp) ? "未接管" : "已接管";
                        dt.Rows.Add(dr);
                    }
                    ClsControlPack.CopyDataToDatatable(ref dt, ref this.dtJGPointInfo, true);
                    ClsControlPack.RefreshAndAutoSize(ultraGridPW);

                    lbPointName.Text = "";
                    lbMeterMan.Text = userName;
                    //imageControl.Start();

                    collection2.Start("CAR11"); //白家嘴计检站静态衡一
                    collection1.Start("CAR12"); //白家嘴计检站静态衡二   这个有2个秤点
                }

                //=====================下拉界面相关事件========================
                //下拉框测试
                loadMaterialInfo();

                //智能输入弹出框设置
                show = new ListBox();
                this.Controls.Add(show);
                show.Size = new Size(500, 480); //设置show的宽度和长度
                show.Visible = false;
                show.ScrollAlwaysVisible = true;
                show.BringToFront();
                show.Font = new Font("宋体", 14.25f, FontStyle.Bold);
                show.DoubleClick += new EventHandler(show_DoubleClick);
                show.KeyPress += new KeyPressEventHandler(show_KeyPress);
                show.Leave += new EventHandler(show_Leave);

                //=====================下拉界面相关事件========================
            }
            catch (Exception ex)
            {
                MessageBox.Show("frmStaticMain_Load方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "frmStaticMain_Load方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        /// <summary>
        /// 打开关闭语音对讲
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenVoice_Click(object sender, EventArgs e)
        {
            try
            {
                if (panel1.Controls.Count > 0)
                {
                    if (btnOpenVoice.Text == "打开对讲")
                    {
                        VoiceOpen();
                    }
                    else
                    {
                        VoiceClose();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("btnOpenVoice_Click打开对讲异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "btnOpenVoice_Click打开对讲异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        /// <summary>
        /// 使用自重
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnZZWgt_Click(object sender, EventArgs e)
        {
            try
            {
                if (preTack == null || string.IsNullOrEmpty(ucStaticTrackMeterInfo1.predictionNo))
                {
                    MessageBox.Show("[预报单号]为空不允许进行保存操作，请选择预报信息后再点击[使用自重]按钮！");
                    return;
                }
                if (first != null)
                {
                    MessageBox.Show("存在有效的一次计量数据，请先回皮再使用自重进行计量！");
                    return;
                }
                btnZZWgt.BackColor = Color.Gray; //点击使用自重以后，就变为灰色；
                isUsedFactoryWeight = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("btnZZWgt_Click使用自重方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "btnZZWgt_Click使用自重方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        /// <summary>
        /// 复磅操作；
        /// 1、客户端复磅时提醒要复磅的重量是多少；
        /// 2、服务端在服务端更新最近的一条重量记录，将原来的记录写在memo中；若存在二次计量记录则进行更新，并将原来的记录写在memo中；
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRecover_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtCarNo.Text.Trim()) || !(txtCarNo.Text.Trim().Length == 7))
                {
                    MessageBox.Show("车号[" + txtCarNo.Text.Trim() + "]" + "为空或车号长度不等于7，不能进行 [ 复磅 ] 操作！");
                    return;
                }

                RESTfulResult<List<MeterWorkRailwayActFirst>> RESTfulResultRecent = railwayActFirstService.doQuerySelectSta(new MeterWorkRailwayActFirst()
                {
                    pageNum = 1,
                    pageSize = 10,
                    railwayNo = txtCarNo.Text.Trim()
                });
                if (RESTfulResultRecent.Succeed && RESTfulResultRecent.Data != null && RESTfulResultRecent.Data.Count > 0)
                {
                    string lastWeight = RESTfulResultRecent.Data[0].meterWeight.ToString();
                    string actualFirstNo = RESTfulResultRecent.Data[0].actualFirstNo.ToString(); ;
                    if (PbStaticRailwayCache.sportInfo != null && PbStaticRailwayCache.collect != null && PbStaticRailwayCache.collect.mainWgt > 1000)
                    {
                        switch (PbStaticRailwayCache.sportInfo.baseSpotNo)
                        {
                            case "00011":
                                if (cmbCarType.Text.Trim() == "双秤")
                                {
                                    PbStaticRailwayCache.lockWgt = PbStaticRailwayCache.collect.mainWgt + PbStaticRailwayCache.collect.viceWgt;
                                }
                                else
                                {
                                    PbStaticRailwayCache.lockWgt = PbStaticRailwayCache.collect.mainWgt;
                                }
                                ; break;
                            case "00010":
                                PbStaticRailwayCache.lockWgt = PbStaticRailwayCache.collect.mainWgt;
                                ; break;
                        }
                    }
                    string msg = "上一次的计量重量为 [ " + Convert.ToDouble(lastWeight) / 1000 + " ]T 复磅后重量为[ " + PbStaticRailwayCache.lockWgt / 1000 + " ]T,是否继续保存！";
                    DialogResult dr = MessageBox.Show(msg, "提示", MessageBoxButtons.OKCancel);
                    if (dr == DialogResult.OK)
                    {
                        try
                        {
                            bool flag = SaveRecover(actualFirstNo);
                            if (flag)
                            {
                                MessageBox.Show("[" + strCarNo + "]复磅成功!");
                                QueryCarNo(); //计量完成后查询一次数据
                                querySacle();//计量预报查询；查询所有有效的预报
                                queryFirst(); //查询100条一次计量记录
                                queryActual(); //查询100条二次计量记录

                                queryFirst2(); //查询100条一次计量记录
                                queryActual2(); //查询100条二次计量记录

                                CleanForm(); //保存成功，清空文本框
                            }
                            else
                            {
                                MessageBox.Show("[" + strCarNo + "]复磅失败!");
                            }
                        }
                        catch (Exception ex)
                        {
                            btnSave.Enabled = true;
                            MessageBox.Show("[" + strCarNo + "]复磅失败!");
                            txtMsgInfo.Text = strCarNo + "复磅失败：" + ex.Message.Trim();
                            l.WriteLog(5, strCarNo + "复磅失败：" + ex.Message.Trim());
                        }
                    }
                }
                isEditCarNo = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("btnRecover_Click复磅方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "btnRecover_Click复磅方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        /// <summary>
        /// 保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnSave.BackColor.Equals(Color.Gray))
                {
                    MessageBox.Show("[" + strCarNo + "]" + "已经保存成功，不能重复点击 [ 保存 ] 按钮！");
                    return;
                }
                //预报为空不允许进行保存操作
                if (preTack == null || string.IsNullOrEmpty(ucStaticTrackMeterInfo1.predictionNo))
                {
                    MessageBox.Show("[预报单号]为空不允许进行保存操作，请选择预报信息后再点击[保存]按钮！");
                    return;
                }

                //2021年5月31日 添加校验
                if (isUsedFactoryWeight && string.IsNullOrEmpty(txtTare.Text))
                {
                    MessageBox.Show("使用自重计量时，皮重不允许为空，请输入皮重后，再点击[保存]按钮！");
                    return;
                }

                //2021年6月14日 添加硫酸使用自重的提示
                if (!String.IsNullOrEmpty(ucStaticTrackMeterInfo1.matterName) && "硫酸".Equals(ucStaticTrackMeterInfo1.matterName)
                    && (string.IsNullOrEmpty(txtTare.Text) || txtTare.Text.Length < 5))
                {
                    string msg = "计量【硫酸】时，没有【皮重】或者【自重】信息或皮重信息未完整录入,是否继续保存！";
                    DialogResult dr = MessageBox.Show(msg, "提示", MessageBoxButtons.OKCancel);
                    if (dr == DialogResult.Cancel) return;
                }

                if (PbStaticRailwayCache.sportInfo != null && PbStaticRailwayCache.collect != null && PbStaticRailwayCache.collect.mainWgt > 1000)
                {
                    switch (PbStaticRailwayCache.sportInfo.baseSpotNo)
                    {
                        case "00011":
                            if (cmbCarType.Text.Trim() == "双秤")
                            {
                                PbStaticRailwayCache.lockWgt = PbStaticRailwayCache.collect.mainWgt + PbStaticRailwayCache.collect.viceWgt;
                            }
                            else
                            {
                                PbStaticRailwayCache.lockWgt = PbStaticRailwayCache.collect.mainWgt;
                            }
                            ; break;
                        case "00010":
                            PbStaticRailwayCache.lockWgt = PbStaticRailwayCache.collect.mainWgt;
                            ; break;
                    }

                    tareWeight = Convert.ToDouble(txtTare.Value) * 1000; //自重的皮重
                    PbStaticRailwayCache.lockCarNo = txtCarNo.Text.Trim(); //界面车号
                    DialogResult dr = MessageBox.Show("是否确认保存当前计量数据？", "提示", MessageBoxButtons.OKCancel);

                    if (dr == DialogResult.OK)
                    {
                        try
                        {
                            string actNo = "";
                            bool flag = SaveDB(out actNo);

                            if (flag)
                            {
                                #region 截取图片信息
                                try
                                {
                                    //* 截取屏幕信息
                                    Point screenPoint = this.PointToScreen(new Point());
                                    Rectangle rect = new Rectangle(screenPoint, this.Size);
                                    Image img = new Bitmap(rect.Width, rect.Height);
                                    Graphics g = Graphics.FromImage(img);
                                    g.CopyFromScreen(rect.X - 1, rect.Y - 1, 0, 0, rect.Size);//"D://file/1.jpg"
                                    img.Save(string.Format("{0}imgShort\\formalImg\\{1}_{2}_{3}.jpg",
                                        AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
                                        PbStaticRailwayCache.sportInfo.baseSpotNo,
                                        "R" + actNo,
                                        (PbStaticRailwayCache.videoChild.Count + 1)), System.Drawing.Imaging.ImageFormat.Jpeg);

                                    //* 最后进行截图操作
                                    CameraShotCls cameraShot = new CameraShotCls();
                                    //cameraShot.CapMethod(actNo);
                                    cameraShot.CapMethodFromVideo(actNo);
                                    //*/
                                }
                                catch
                                {
                                    l.WriteLog(5, PbStaticRailwayCache.lockCarNo + "截图失败");
                                }
                                #endregion

                                MessageBox.Show("[" + strCarNo + "]保存成功!");
                                btnSave.BackColor = Color.Gray; //2021年4月10日，保存后，只有车号变更才能够重新点击保存；
                                QueryCarNo(); //计量完成后查询一次数据
                                querySacle();//计量预报查询；查询所有有效的预报
                                queryFirst(); //查询100条一次计量记录
                                queryActual(); //查询100条二次计量记录

                                queryFirst2(); //查询100条一次计量记录
                                queryActual2(); //查询100条二次计量记录

                                CleanForm(); //保存成功，清空文本框
                            }
                            else
                            {
                                MessageBox.Show("[" + strCarNo + "]保存失败!");
                            }
                        }
                        catch (Exception ex)
                        {
                            btnSave.Enabled = true;
                            MessageBox.Show("[" + strCarNo + "]保存失败!");
                            txtMsgInfo.Text = strCarNo + "保存失败：" + ex.Message.Trim();
                            l.WriteLog(5, strCarNo + "保存失败：" + ex.Message.Trim());
                        }
                    }
                }
                isEditCarNo = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("btnSave_Click保存方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "btnSave_Click保存方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        /// <summary>
        /// 存储计量数据
        /// </summary>
        /// <returns></returns>
        private bool SaveDB(out string actNo)
        {
            actNo = "";
            try
            {
                MeterWorkRailwayActFirst mwraf = new MeterWorkRailwayActFirst();
                EntityBase<PreRailwayScale> entityBase = new EntityBase<PreRailwayScale>();
                preTack = (preTack == null ? new PreRailwayScale() : preTack);

                mwraf = entityBase.format<MeterWorkRailwayActFirst>(preTack, mwraf);
                mwraf.meterWeight = PbStaticRailwayCache.lockWgt;
                if (isUsedFactoryWeight)
                {
                    mwraf.railwayFactoryWeight = tareWeight;
                }
                mwraf.createManNo = userId;
                mwraf.createManName = userName;
                mwraf.createTime = DateTime.Now;
                mwraf.meterGroup = appUser.userGroup;
                mwraf.meterClass = appUser.userClass;
                mwraf.railwayNo = strCarNo;
                mwraf.baseSpotNo = PbStaticRailwayCache.sportInfo.baseSpotNo;
                mwraf.baseSpotName = PbStaticRailwayCache.sportInfo.baseSpotName;

                RESTfulResult<string> rm = railwayActFirstService.doAddWfStatic(mwraf);
                if (rm.Succeed)
                {
                    actNo = rm.Data;
                    isLockWgt = true;
                    setMsgInfo(txtMsgInfo, strCarNo + "保存成功", "");
                    return true;
                }
                else
                {
                    setMsgInfo(txtMsgInfo, strCarNo + "保存失败：" + rm.Message, "");
                    l.WriteLog(5, strCarNo + "保存失败：" + rm.Message);
                    return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Clean方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
            return false;
        }

        /// <summary>
        /// 复磅保存操作
        /// </summary>
        /// <param name="actNo"></param>
        /// <returns></returns>
        private bool SaveRecover(string actualFirstNo)
        {
            try
            {
                MeterWorkRailwayActFirst mwraf = new MeterWorkRailwayActFirst();
                mwraf.actualFirstNo = actualFirstNo;
                mwraf.meterWeight = PbStaticRailwayCache.lockWgt;
                mwraf.createManNo = userId;
                mwraf.createManName = userName;
                mwraf.createTime = DateTime.Now;
                mwraf.meterGroup = appUser.userGroup;
                mwraf.meterClass = appUser.userClass;
                mwraf.railwayNo = strCarNo;
                mwraf.baseSpotNo = PbStaticRailwayCache.sportInfo.baseSpotNo;
                mwraf.baseSpotName = PbStaticRailwayCache.sportInfo.baseSpotName;

                RESTfulResult<string> rm = railwayActFirstService.doAddWfRecover(mwraf);
                if (rm.Succeed)
                {
                    isLockWgt = true;
                    setMsgInfo(txtMsgInfo, strCarNo + "复磅成功", "");
                    return true;
                }
                else
                {
                    setMsgInfo(txtMsgInfo, strCarNo + "复磅失败：" + rm.Message, "");
                    l.WriteLog(5, strCarNo + "复磅失败：" + rm.Message);
                    return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Clean方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
            return false;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnStart.Text != "释放")
                {
                    UltraGridRow ugr = ultraGridPW.ActiveRow;
                    if (ugr != null)
                    {
                        if (!string.IsNullOrEmpty(ugr.Cells["controlIp"].Text) && ugr.Cells["controlIp"].Text != _controlIp)
                        {
                            MessageBox.Show("当前计量点已被他人接管");
                            return;
                        }

                        btnStart.BackColor = Color.Red;
                        btnStart.Text = "释放";
                        PbStaticRailwayCache.sportInfo = PbStaticRailwayCache.sportInfos.Where(s => s.baseSpotNo == ugr.Cells["baseSpotNo"].Text.Trim()).FirstOrDefault();
                        //controlIp
                        updateSport(_controlIp);
                        if (PbStaticRailwayCache.sportInfo.baseSpotNo == "00011")
                        {
                            ucStorageWeightT2.Visible = true;
                            pl3.Visible = true;
                            cmbCarType.Enabled = true;
                        }
                        else
                        {
                            ucStorageWeightT2.Visible = false;
                            pl3.Visible = false;
                            setMsgInfo(cmbCarType, "单秤", "");
                            cmbCarType.Enabled = false;
                        }
                        lbPointName.Text = PbStaticRailwayCache.sportInfo.baseSpotName;

                        bd.getSpot();
                        GetIPVideo(PbStaticRailwayCache.videoInfo);
                        setPicBoxSet();
                    }
                }
                else
                {
                    btnStart.BackColor = Color.DodgerBlue;
                    btnStart.Text = "接管";

                    foreach (UltraGridRow ugrs in ultraGridPW.Rows)
                    {
                        ugrs.Appearance.BackColor = Color.White;
                    }

                    ucStorageWeightT2.Visible = false;
                    pl3.Visible = false;

                    Clean();//释放按钮
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("btnStart_Click接管按钮异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "btnStart_Click接管按钮异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        private PbModelDbService<string> pdb = new PbModelDbService<string>();
        private MeterMonitorNoteService noteService = new MeterMonitorNoteService();

        /// <summary>
        /// 修改监控表的状态
        /// </summary>
        /// <param name="controlIp"></param>
        private void updateSport(string controlIp)
        {
            try
            {
                string sql = string.Format("update meter_base_spot_info set CONTROL_IP = '{0}' where CONTROL_IP='{1}' or base_spot_no='{2}'", controlIp, _controlIp, (PbStaticRailwayCache.sportInfo == null ? "" : PbStaticRailwayCache.sportInfo.baseSpotNo));
                RESTfulResult<string> rm = pdb.executeSqlDataWf(sql);
                if (rm.Succeed)
                {
                    WriteMonitorNote("修改meter_base_spot_info接管状态为" + (string.IsNullOrEmpty(controlIp) ? "取消接管" : "接管"));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("updateSport方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "updateSport方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        private void WriteMonitorNote(string content)
        {
            try
            {
                if (PbStaticRailwayCache.sportInfo != null && PbStaticRailwayCache.sportInfo.baseSpotNo != null)
                {
                    RESTfulResult<string> rm = noteService.doAddWf(new MeterMonitorNote
                    {
                        baseSpotNo = PbStaticRailwayCache.sportInfo.baseSpotNo,
                        baseSpotName = PbStaticRailwayCache.sportInfo.baseSpotName,
                        operationContent = content,//str + chk.Text,
                        carNo = txtCarNo.Text.Trim(),
                        meterManNo = appUser.userid,
                        meterManName = appUser.username,
                        meterNoteSource = "5"
                    });

                    if (!rm.Succeed)
                    {
                        l.WriteLog(5, "静态衡写入操作日志异常：" + content);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("WriteMonitorNote方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "WriteMonitorNote方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        /// <summary>
        /// 放大图像
        /// </summary>
        private void PictureBoxDoubleClick(object sender, EventArgs e)
        {
            if (iPic != 0)
            {
                cameraShotMain.StopRealPlay(iPic);
            }
            PictureBox picture = (PictureBox)sender;
            iPic = Convert.ToInt32(picture.Name.Substring(picture.Name.Length - 1, 1));
            plImgShow.Visible = true;
            cameraShotMain.RealPlay(pictureShow, iPic);
        }

        /// <summary>
        /// 不显示大图
        /// </summary>
        private void pictureShow_DoubleClick(object sender, EventArgs e)
        {
            plImgShow.Visible = false;
            cameraShotMain.StopRealPlay(iPic);
            iPic = 0;
        }

        private void frmStaticMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                Clean(); //关闭按钮
            }
            catch { }

            timer1.Stop();
            timerSearchLimit.Stop();
            //imageControl.Stop();

            try
            {
                collection1.Stop();
            }
            catch { }

            try
            {
                collection2.Stop();
            }
            catch { }
        }

        #endregion

        #region 数据采集部分
        private bool iWgtChange1 = true; //重量初次大于500
        private bool bTest = false;
        private string strCarNo = "";
        private bool isLockWgt = false;//是否锁定重量

        /// <summary>
        /// 数据采集；双称
        /// </summary>
        private void EventData(object o, StaticCollectModel e)
        {
            //这里每隔0.5秒执行一次
            try
            {
                #region

#if DEBUG
                //*
                if (bTest)
                {
                    e.carno = "";//功能测试
                    e.mainWgt = 10000;//rd.Next(40000, 50000);
                    e.viceWgt = 0;
                    e.firstRed = "0";
                    e.secondRed = "0";
                    e.thirdRed = "1";
                    e.carType = "车型1";
                }
                //*/
#endif

                if (PbStaticRailwayCache.sportInfo != null && PbStaticRailwayCache.sportInfo.baseSpotNo == "00011")
                {
                    //此处需要调整，车号要能够进行编辑
                    if (!string.IsNullOrEmpty(e.carno) && e.carno != strCarNo && PbStaticRailwayCache.collect != null)
                    {
                        if (e.mainWgt > 1000 && !isEditCarNo)
                        {
                            strCarNo = e.carno;
                            if (!string.IsNullOrEmpty(strCarNo))
                            {
                                //QueryCarNo(); //采集时，车号有变化，查询一次数据;2021年4月23日注释；车号change的事件中会查询一次数据
                            }
                        }
                        if (string.IsNullOrEmpty(cmbCarType.Text.Trim()))
                        {
                            setMsgInfo(cmbCarType, "单秤", "");

                            foreach (ComBaseInfo cbi in PbStaticRailwayCache.ltCarType)
                            {
                                if (cbi.baseName == e.carType && cbi.baseName.Contains("双"))
                                {
                                    setMsgInfo(cmbCarType, "双秤", "");
                                }
                            }
                        }
                    }
                }

                scModel1.mainWgt = e.mainWgt;
                scModel1.viceWgt = e.viceWgt;
                scModel1.weightStatus = e.weightStatus;
                scModel1.datetime = e.datetime;
                scModel1.carType = e.carType;//车型
                scModel1.firstRed = e.firstRed;//红外1
                scModel1.secondRed = e.secondRed;//红外2
                scModel1.thirdRed = e.thirdRed;//红外3
                if (!isEditCarNo) //为false的时候车号才会重新赋值
                {
                    scModel1.carno = e.carno;
                }

                if (PbStaticRailwayCache.sportInfo != null && PbStaticRailwayCache.sportInfo.baseSpotNo == "00011")
                {
                    PbStaticRailwayCache.collect = scModel1;
                    setMsgInfo(pl1, "Color", e.firstRed != "0" ? "Red" : "Lime");
                    setMsgInfo(pl2, "Color", e.firstRed != "0" ? "Red" : "Lime");
                    setMsgInfo(pl3, "Color", e.firstRed != "0" ? "Red" : "Lime");
                }

                //重量大于500的情况下
                if (e.mainWgt > 1000)
                {
                    l.WriteLog(1, string.Format("双秤：车号：{0},主重：{1},副重{2},车型{3}", e.carno, e.mainWgt, e.viceWgt, e.carType));
                    if (PbStaticRailwayCache.sportInfo != null && PbStaticRailwayCache.sportInfo.baseSpotNo == "00011")
                    {
                        //if (!PbStaticRailwayCache.isLockFrm)
                        {
                            if (!isEditCarNo) //为false的时候车号才会重新赋值
                            {
                                setMsgInfo(txtCarNo, scModel1.carno, "");
                            }
                            ucStorageWeightT1.setWgt(scModel1.mainWgt);
                            ucStorageWeightT1.setStable(scModel1.weightStatus != 1 ? true : false);

                            ucStorageWeightT2.setWgt(scModel1.viceWgt);
                            ucStorageWeightT2.setStable(scModel1.weightStatus != 1 ? true : false);
                        }

                        if (iWgtChange1)
                        {
                            setMsgInfo(btnSave, "true", "1");
                        }

                        if (PbStaticRailwayCache.dtStartTime == null)
                            PbStaticRailwayCache.dtStartTime = DateTime.Now;

                        iWgtChange1 = false;

                        int metWgt = 0;
                        string strTxt = GetControlProperty(cmbCarType, "Text").ToString().Trim();
                        if (strTxt == "双秤")
                        {
                            metWgt = scModel1.viceWgt + scModel1.mainWgt;
                        }
                        else
                        {
                            metWgt = scModel1.mainWgt;
                        }
                        if (!isLockWgt) //若已经称重保存成功则不再界面重量不再变化
                        {
                            if (first != null)
                            {
                                //一毛一皮正常结净
                                if (metWgt > first.meterWeight)
                                {
                                    if (isUsedFactoryWeight)
                                    {
                                        setMsgInfo(txtGroess, Math.Round(Convert.ToDouble(metWgt) / 1000, 2) + "", "");
                                        if (string.IsNullOrEmpty(txtTare.Text) || txtTare.Text.Length < 5)
                                        {
                                            setMsgInfo(txtNet, Math.Round(Convert.ToDouble(metWgt) / 1000, 2) + "", "");
                                            return;
                                        }
                                        setMsgInfo(txtNet, Math.Round(Math.Round(Convert.ToDouble(metWgt) / 1000, 2) - Convert.ToDouble(txtTare.Value), 2) + "", "");
                                    }
                                    else
                                    {
                                        //界面重量大于一次计量重量；则当前为皮重
                                        setMsgInfo(txtGroess, Math.Round(Convert.ToDouble(metWgt) / 1000, 2) + "", "");
                                        setMsgInfo(txtTare, Math.Round(Convert.ToDouble(first.meterWeight) / 1000, 2) + "", "");
                                        setMsgInfo(txtNet, Math.Round(Convert.ToDouble(metWgt) / 1000 - Convert.ToDouble(first.meterWeight) / 1000, 2) + "", "");
                                    }
                                }
                                else
                                {
                                    //界面重量小于一次计量重量；则当前为毛重；
                                    //setMsgInfo(txtGroess, first.meterWeight + "", "");
                                    //setMsgInfo(txtTare, metWgt + "", "");
                                    //setMsgInfo(txtNet, (first.meterWeight - metWgt) + "", "");

                                    //2021年4月19日 将毛重的取值从【meterWeight】变更为【meterBalanceWeight】
                                    setMsgInfo(txtGroess, Math.Round(Convert.ToDouble(first.meterBalanceWeight) / 1000, 2) + "", "");
                                    setMsgInfo(txtTare, Math.Round(Convert.ToDouble(metWgt) / 1000, 2) + "", "");
                                    setMsgInfo(txtNet, Math.Round(Convert.ToDouble(first.meterBalanceWeight) / 1000 - Convert.ToDouble(metWgt) / 1000, 2) + "", "");
                                }
                            }
                            else
                            {
                                if (isUsedFactoryWeight)
                                {
                                    //使用自重进行结净，自重为自己输入的
                                    setMsgInfo(txtGroess, Math.Round(Convert.ToDouble(metWgt) / 1000, 2) + "", "");
                                    if (string.IsNullOrEmpty(txtTare.Text) || txtTare.Text.Length < 5)
                                    {
                                        setMsgInfo(txtNet, Math.Round(Convert.ToDouble(metWgt) / 1000, 2) + "", "");
                                        return; //2021年5月31日 使用自重计量时，若界面为空则不处理
                                    }
                                    //setMsgInfo(txtTare, Convert.ToDouble(txtTare.Value) + "", "");
                                    setMsgInfo(txtNet, Math.Round(Convert.ToDouble((metWgt / 1000) - txtTare.Value), 2) + "", "");
                                }
                                else
                                {
                                    setMsgInfo(txtGroess, Math.Round(Convert.ToDouble(metWgt) / 1000, 2) + "", "");
                                    setMsgInfo(txtTare, "", "");
                                    setMsgInfo(txtNet, "", "");
                                }
                            }
                        }

                        setGridColor(ultraGridPW, "00011", "3");
                    }
                    else
                    {
                        setGridColor(ultraGridPW, "00011", "1");
                    }
                }
                else
                {
                    //重量小于1000
                    if (PbStaticRailwayCache.sportInfo != null && PbStaticRailwayCache.sportInfo.baseSpotNo == "00011")
                    {
                        CleanForm(); //重量小于1000清空文本框
                        setMsgInfo(txtCarNo, "", "");
                        setGridColor(ultraGridPW, "00011", "3");
                        isEditCarNo = false;
                    }
                    else
                    {
                        setGridColor(ultraGridPW, "00011", "2");
                    }
                    //重量小于1000,可以点击保存按钮；按钮言颜色正常；车号编辑状态为false（初始化）；
                    btnSave.BackColor = Color.DodgerBlue;
                    iWgtChange1 = true;
                }
                #endregion
            }
            catch (Exception ex)
            {
                //MessageBox.Show("frmMeterMain.EventData数据采集异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "frmMeterMain.EventData数据采集异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        #endregion

        #region 数据采集部分
        private bool iWgtChange2 = true; //重量初次大于500

        /// <summary>
        /// 数据采集；单称
        /// </summary>
        private void EventData2(object o, StaticCollectModel e)
        {
            //这里每隔0.5秒执行一次
            try
            {
                if (bTest)
                {
                    e.carno = "";//功能测试
                    e.mainWgt = 0;//rd.Next(40000, 50000);
                    e.viceWgt = 0;
                    e.firstRed = "0";
                    e.secondRed = "0";
                    e.thirdRed = "1";
                    e.carType = "车型1";
                }

                #region
                if (PbStaticRailwayCache.sportInfo != null && PbStaticRailwayCache.sportInfo.baseSpotNo == "00010")
                {
                    if (!string.IsNullOrEmpty(e.carno) && e.carno != strCarNo && PbStaticRailwayCache.collect != null)
                    {
                        if (e.mainWgt > 1000 && !isEditCarNo)
                        {
                            strCarNo = e.carno;
                            if (!string.IsNullOrEmpty(strCarNo))
                            {
                                //QueryCarNo(); //采集时，车号有变化，查询一次数据//2021年4月23日注释；车号change的事件中会查询一次数据
                            }
                        }
                        if (string.IsNullOrEmpty(cmbCarType.Text.Trim()))
                        {
                            setMsgInfo(cmbCarType, "单秤", "");
                        }
                    }
                }

                scModel2.mainWgt = e.mainWgt;
                scModel2.weightStatus = e.weightStatus;
                //PbStaticRailwayCache.collect.parkStatus = e.parkStatus;
                scModel2.datetime = e.datetime;
                //PbStaticRailwayCache.collect.licType = e.licType;
                if (!isEditCarNo)
                {
                    scModel2.carno = e.carno;
                }

                if (PbStaticRailwayCache.sportInfo != null && PbStaticRailwayCache.sportInfo.baseSpotNo == "00010")
                {
                    PbStaticRailwayCache.collect = scModel2;
                    setMsgInfo(pl1, "Color", e.firstRed != "0" ? "Red" : "Lime");
                    setMsgInfo(pl2, "Color", e.firstRed != "0" ? "Red" : "Lime");
                    setMsgInfo(pl3, "Color", e.firstRed != "0" ? "Red" : "Lime");
                    //PbStaticRailwayCache.ltCarType
                }

                //重量大于500的情况下
                if (e.mainWgt > 1000)
                {
                    l.WriteLog(1, string.Format("单秤：车号：{0},主重：{1},副重{2},车型{3}", e.carno, e.mainWgt, e.viceWgt, e.carType));
                    if (PbStaticRailwayCache.sportInfo != null && PbStaticRailwayCache.sportInfo.baseSpotNo == "00010")
                    {
                        //if (!PbStaticRailwayCache.isLockFrm)
                        {
                            if (!isEditCarNo) //为false的时候车号才会重新赋值
                            {
                                setMsgInfo(txtCarNo, scModel2.carno, "");
                            }
                            ucStorageWeightT1.setWgt(scModel2.mainWgt);
                            ucStorageWeightT1.setStable(scModel2.weightStatus != 1 ? true : false);
                        }

                        if (iWgtChange2)
                        {
                            setMsgInfo(btnSave, "true", "1");
                        }

                        if (PbStaticRailwayCache.dtStartTime == null)
                            PbStaticRailwayCache.dtStartTime = DateTime.Now;

                        iWgtChange2 = false;

                        int metWgt = 0;
                        string strTxt = GetControlProperty(cmbCarType, "Text").ToString().Trim();
                        if (strTxt == "双秤")
                        {
                            metWgt = scModel2.viceWgt + scModel2.mainWgt;
                        }
                        else
                        {
                            metWgt = scModel2.mainWgt;
                        }

                        if (first != null)
                        {
                            //一毛一皮正常结净
                            if (metWgt > first.meterWeight)
                            {
                                //界面重量大于一次计量重量；则当前为皮重
                                if (isUsedFactoryWeight)
                                {
                                    setMsgInfo(txtGroess, Math.Round(Convert.ToDouble(metWgt) / 1000, 2) + "", "");
                                    if (string.IsNullOrEmpty(txtTare.Text) || txtTare.Text.Length < 5)
                                    {
                                        setMsgInfo(txtNet, Math.Round(Convert.ToDouble(metWgt) / 1000, 2) + "", "");
                                        return;
                                    }
                                    setMsgInfo(txtNet, Math.Round(Math.Round(Convert.ToDouble(metWgt) / 1000, 2) - Convert.ToDouble(txtTare.Value), 2) + "", "");
                                }
                                else
                                {
                                    setMsgInfo(txtGroess, Math.Round(Convert.ToDouble(metWgt) / 1000, 2) + "", "");
                                    setMsgInfo(txtTare, Math.Round(Convert.ToDouble(first.meterWeight) / 1000, 2) + "", "");
                                    setMsgInfo(txtNet, Math.Round(Convert.ToDouble(metWgt) / 1000 - Convert.ToDouble(first.meterWeight) / 1000, 2) + "", "");
                                }
                            }
                            else
                            {
                                //界面重量小于一次计量重量；则当前为毛重；
                                //setMsgInfo(txtGroess, first.meterWeight + "", "");
                                //setMsgInfo(txtTare, metWgt + "", "");
                                //setMsgInfo(txtNet, (first.meterWeight - metWgt) + "", "");

                                //2021年4月19日 将毛重的取值从【meterWeight】变更为【meterBalanceWeight】
                                setMsgInfo(txtGroess, Math.Round(Convert.ToDouble(first.meterBalanceWeight) / 1000, 2) + "", "");
                                setMsgInfo(txtTare, Math.Round(Convert.ToDouble(metWgt) / 1000, 2) + "", "");
                                setMsgInfo(txtNet, Math.Round(Convert.ToDouble(first.meterBalanceWeight) / 1000 - Convert.ToDouble(metWgt) / 1000, 2) + "", "");
                            }
                        }
                        else
                        {
                            if (isUsedFactoryWeight)
                            {
                                //使用自重进行结净，自重为自己输入的
                                setMsgInfo(txtGroess, Math.Round(Convert.ToDouble(metWgt) / 1000, 2) + "", "");
                                String st = txtTare.Text;
                                if (string.IsNullOrEmpty(txtTare.Text) || txtTare.Text.Length < 5)
                                {
                                    setMsgInfo(txtNet, Math.Round(Convert.ToDouble(metWgt) / 1000, 2) + "", "");
                                    return;
                                    //txtTare.Value = 0; //注意numericupdown控件Text和Value是两个值，value不会清空，不这么处理，皮重框会一直有个值。
                                    //txtTare.Text = "0";
                                }

                                //setMsgInfo(txtTare, Convert.ToDouble(txtTare.Value) + "", "");
                                setMsgInfo(txtNet, Math.Round(Convert.ToDouble((metWgt / 1000) - txtTare.Value), 2) + "", "");
                            }
                            else
                            {
                                setMsgInfo(txtGroess, Math.Round(Convert.ToDouble(metWgt) / 1000, 2) + "", "");
                                setMsgInfo(txtTare, "", "");
                                setMsgInfo(txtNet, "", "");
                            }
                        }

                        setGridColor(ultraGridPW, "00010", "3");
                    }
                    else
                    {
                        setGridColor(ultraGridPW, "00010", "1");
                    }
                }
                else
                {
                    if (PbStaticRailwayCache.sportInfo != null && PbStaticRailwayCache.sportInfo.baseSpotNo == "00010")
                    {
                        CleanForm(); //00010重量小于1000清空
                        setMsgInfo(txtCarNo, "", "");
                        setGridColor(ultraGridPW, "00010", "3");
                        isEditCarNo = false;
                    }
                    else
                    {
                        setGridColor(ultraGridPW, "00010", "2");
                    }

                    iWgtChange2 = true;
                }
                #endregion
            }
            catch (Exception ex)
            {
                //MessageBox.Show("frmMeterMain.EventData2数据采集异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "frmMeterMain.EventData2数据采集异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        #endregion

        #region 数据操作

        /// <summary>
        /// 按车号查询数据
        /// </summary>
        private void QueryCarNo()
        {
            //查询频率限制，每2s钟查询一次数据
            //if (searchLimit > 1)
            //{
            //    searchLimit = 0;
            //}
            //else
            //{
            //    return;
            //}

            int count = 0;
            try
            {
                if (!string.IsNullOrEmpty(strCarNo))
                {
                    first = null;
                    count = 1;

                    //通过车号查询计量预报;2021年5月15日 调整预报查询的接口
                    RESTfulResult<List<PreRailwayScale>> rmx = PreService.doQueryJLByCar(new PreRailwayScale { railwayNo = strCarNo, railwayTypeNo = "001019001" });
                    count = 2;
                    try
                    {
                        dtRailwayScale.Clear();
                        DataTable dt = dtRailwayScale.Clone();
                        if (rmx.Succeed && rmx.Data != null && rmx.Data.Count > 0)
                        {
                            dt = rmx.Data.ListToDataTable<PreRailwayScale>();
                        }
                        ClsControlPack.CopyDataToDatatable(ref dt, ref this.dtRailwayScale, true);
                        foreach (var item in this.ultraGrid1.Rows)
                        {
                            item.Cells["valueFlag"].Value = GetTrackType(item.Cells["valueFlag"].Value.ToString());
                            item.Cells["grossWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["grossWeight"].Value.ToString()) ? "0" : item.Cells["grossWeight"].Value.ToString()) / 1000;
                            item.Cells["tareWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["tareWeight"].Value.ToString()) ? "0" : item.Cells["tareWeight"].Value.ToString()) / 1000;
                            item.Cells["netWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["netWeight"].Value.ToString()) ? "0" : item.Cells["netWeight"].Value.ToString()) / 1000;
                        }
                        ClsControlPack.RefreshAndAutoSize(ultraGrid1);
                        if (ultraGrid1 != null && ultraGrid1.Rows != null && ultraGrid1.Rows.Count > 0)
                        {
                            foreach (UltraGridRow ugr in ultraGrid1.Rows)
                            {
                                ugr.Appearance.BackColor = Color.White;//背景颜色重置
                            }
                            if (ultraGrid1.Rows.Count == 1 && !isLockWgt) //等于1时自动赋值并且没有计量完成
                            {
                                DataRow[] dr = dtRailwayScale.Select("predictionNo='" + ultraGrid1.Rows[0].Cells["predictionNo"].Text.Trim() + "'");
                                if (dr != null && dr.Length > 0)
                                {
                                    preTack = dr[0].CreateItem<PreRailwayScale>();
                                    ucStaticTrackMeterInfo1.setPreTrackInfo(preTack);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("预报数据查询出现异常，请联系系统维护人员处理！异常原因\r\n" + ex);
                        l.WriteLog(13, "预报数据查询框异常，位置【" + count + "】" + ex);
                    }

                    //dtRailwayActFirst.Clear();
                    //一次计量数据查询：仅查询当前车号有效的数据；存在则毛皮净写入界面
                    RESTfulResult<List<MeterWorkRailwayActFirst>> RESTfulResult = railwayActFirstService.doQueryWf(new MeterWorkRailwayActFirst { railwayNo = strCarNo, valueFlag = "1" });
                    if (RESTfulResult.Succeed)
                    {
                        if (RESTfulResult.Data != null && RESTfulResult.Data.Count > 0)
                        {
                            if (RESTfulResult.Data.Count == 1) //等于1时自动赋值并且没有计量完成
                            {
                                if (!isLockWgt)
                                {
                                    first = RESTfulResult.Data[0];
                                    PbStaticRailwayCache.strCode = first.predictionNo;
                                    try
                                    {
                                        if (rmx.Succeed && rmx.Data != null && rmx.Data.Count > 0)
                                        {
                                            PreRailwayScale ptsQ = rmx.Data.Where(s => s.predictionNo == RESTfulResult.Data[0].predictionNo).FirstOrDefault();
                                            if (ptsQ != null && ptsQ.predictionNo != "" && !txtMsgInfo.Text.Contains("保存成功"))
                                            {
                                                //2021年4月21日 杨秀东处理，若提示信息包含保存成功，则不再给界面赋值
                                                ucStaticTrackMeterInfo1.setPreTrackInfo(ptsQ);
                                                preTack = ptsQ;
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show("一次计量数据查询出现异常，请联系系统维护人员处理！异常原因:\r\n" + ex);
                                        l.WriteLog(13, "车号[" + strCarNo + "]一次计量数据查询框异常位置【" + count + "】" + ex);
                                    }
                                }
                            }
                            else
                            {
                                setMsgInfo(txtMsgInfo, "车号[" + strCarNo + "]存在多条未结净的数据，不允许进行计量操作！", "");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                l.WriteLog(11, "QueryCarNo中出现异常:" + ex.Message);
                MessageBox.Show("QueryCarNo方法中出现异常，请联系系统维护人员处理！异常原因:\r\n" + ex);
            }
        }

        /// <summary>
        /// 预报查询
        /// </summary>
        private void querySacle()
        {
            try
            {
                dtRailwayScaleHis.Clear();
                PreRailwayScale info = new PreRailwayScale();
                info.pageNum = 1;
                info.pageSize = 1000;
                if (!string.IsNullOrEmpty(dateTimeStart.Text)) //查询开始时间
                    info.startTime = dateTimeStart.Text;
                if (!string.IsNullOrEmpty(dateTimeEnd.Text)) //查询结束时间
                    info.endTime = dateTimeEnd.Text;
                if (!string.IsNullOrEmpty(cbMaterial.Text))//物资名称
                    info.matterName = cbMaterial.Text.Trim();
                if (!string.IsNullOrEmpty(txtCarNoSearch.Text.Trim())) //车号
                    info.railwayNo = txtCarNoSearch.Text.Trim();

                RESTfulResult<List<PreRailwayScale>> rmx = PreService.doQueryWfTime(info);
                DataTable dt = dtRailwayScaleHis.Clone();
                if (rmx.Succeed && rmx.Data != null && rmx.Data.Count > 0)
                {
                    dt = rmx.Data.ListToDataTable<PreRailwayScale>();
                }

                /**
                RESTfulResult<List<PreRailwayScale>> rmx = PreService.doQueryTenWf(new PreRailwayScale { railwayTypeNo = "001019001" });
                DataTable dt = dtRailwayScale.Clone();
                if (rmx.Succeed && rmx.Data != null && rmx.Data.Count > 0)
                {
                    dt = rmx.Data.ListToDataTable<PreRailwayScale>();
                }
                */

                ClsControlPack.CopyDataToDatatable(ref dt, ref this.dtRailwayScaleHis, true);
                foreach (var item in this.ultraGridScaleHis.Rows)
                {
                    item.Cells["valueFlag"].Value = GetTrackType(item.Cells["valueFlag"].Value.ToString());
                }
                ClsControlPack.RefreshAndAutoSize(ultraGridScaleHis);
            }
            catch (Exception ex)
            {
                MessageBox.Show("querySacle预报数据查询出现异常，请联系系统维护人员处理！异常原因\r\n" + ex);
                l.WriteLog(13, "querySacle预报数据查询框异常，异常原因\r\n" + ex);
            }
        }

        /// <summary>
        /// 查询100条一次计量记录
        /// </summary>
        private void queryFirst()
        {
            try
            {
                //最近的100条一次计量数据数据查询
                dtRailwayActFirst.Clear();
                MeterWorkRailwayActFirst info = new MeterWorkRailwayActFirst();
                info.pageNum = 1;
                info.pageSize = 1000;
                info.valueFlag = "4";
                info.baseSpotNo = "00010";  //00010;白家嘴计检站静态衡一
                if (!string.IsNullOrEmpty(dateTimeStart.Text)) //查询开始时间
                    info.createTime1 = dateTimeStart.Text;
                if (!string.IsNullOrEmpty(dateTimeEnd.Text)) //查询结束时间
                    info.createTime2 = dateTimeEnd.Text;
                if (!string.IsNullOrEmpty(cbMaterial.Text))//物资名称
                    info.matterName = cbMaterial.Text.Trim();
                if (!string.IsNullOrEmpty(txtCarNoSearch.Text.Trim())) //车号
                    info.railwayNo = txtCarNoSearch.Text.Trim();

                RESTfulResult<List<MeterWorkRailwayActFirst>> RESTfulResultRecent = railwayActFirstService.doQuerySelectSta(info);
                if (RESTfulResultRecent.Succeed && RESTfulResultRecent.Data != null && RESTfulResultRecent.Data.Count > 0)
                {
                    DataTable dts = dtRailwayActFirst.Clone();

                    dts = RESTfulResultRecent.Data.ListToDataTable<MeterWorkRailwayActFirst>();
                    ClsControlPack.CopyDataToDatatable(ref dts, ref this.dtRailwayActFirst, true);
                    foreach (var item in this.ultraGrid2.Rows)
                    {
                        item.Cells["meterWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["meterWeight"].Value.ToString()) ? "0" : item.Cells["meterWeight"].Value.ToString()) / 1000;
                        item.Cells["meterBalanceWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["meterBalanceWeight"].Value.ToString()) ? "0" : item.Cells["meterBalanceWeight"].Value.ToString()) / 1000;
                        item.Cells["railwayFactoryWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["railwayFactoryWeight"].Value.ToString()) ? "0" : item.Cells["railwayFactoryWeight"].Value.ToString()) / 1000;
                    }
                    ClsControlPack.RefreshAndAutoSize(ultraGrid2);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("最近的一次计量数据数据查询，请联系系统维护人员处理！异常原因:\r\n" + ex);
                l.WriteLog(13, "车号[" + strCarNo + "]一次计量数据查询框异常,异常原因：" + ex);
            }
        }


        /// <summary>
        /// 查询100条一次计量记录;衡二
        /// </summary>
        private void queryFirst2()
        {
            try
            {
                //最近的100条一次计量数据数据查询
                dtRailwayActFirst2.Clear();
                MeterWorkRailwayActFirst info = new MeterWorkRailwayActFirst();
                info.pageNum = 1;
                info.pageSize = 1000;
                info.valueFlag = "4";
                info.baseSpotNo = "00011";  //00011;白家嘴计检站静态衡二
                if (!string.IsNullOrEmpty(dateTimeStart.Text)) //查询开始时间
                    info.createTime1 = dateTimeStart.Text;
                if (!string.IsNullOrEmpty(dateTimeEnd.Text)) //查询结束时间
                    info.createTime2 = dateTimeEnd.Text;
                if (!string.IsNullOrEmpty(cbMaterial.Text))//物资名称
                    info.matterName = cbMaterial.Text.Trim();
                if (!string.IsNullOrEmpty(txtCarNoSearch.Text.Trim())) //车号
                    info.railwayNo = txtCarNoSearch.Text.Trim();

                RESTfulResult<List<MeterWorkRailwayActFirst>> RESTfulResultRecent = railwayActFirstService.doQuerySelectSta(info);
                if (RESTfulResultRecent.Succeed && RESTfulResultRecent.Data != null && RESTfulResultRecent.Data.Count > 0)
                {
                    DataTable dts = dtRailwayActFirst2.Clone();

                    dts = RESTfulResultRecent.Data.ListToDataTable<MeterWorkRailwayActFirst>();
                    ClsControlPack.CopyDataToDatatable(ref dts, ref this.dtRailwayActFirst2, true);
                    foreach (var item in this.ultraGridFirst2.Rows)
                    {
                        item.Cells["meterWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["meterWeight"].Value.ToString()) ? "0" : item.Cells["meterWeight"].Value.ToString()) / 1000;
                        item.Cells["meterBalanceWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["meterBalanceWeight"].Value.ToString()) ? "0" : item.Cells["meterBalanceWeight"].Value.ToString()) / 1000;
                        item.Cells["railwayFactoryWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["railwayFactoryWeight"].Value.ToString()) ? "0" : item.Cells["railwayFactoryWeight"].Value.ToString()) / 1000;
                    }
                    ClsControlPack.RefreshAndAutoSize(ultraGridFirst2);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("最近的一次计量数据数据查询，请联系系统维护人员处理！异常原因:\r\n" + ex);
                l.WriteLog(13, "车号[" + strCarNo + "]一次计量数据查询框异常,异常原因：" + ex);
            }
        }

        /// <summary>
        /// 查询100条结净计量记录
        /// </summary>
        private void queryActual()
        {
            try
            {
                //计量结净数据查询
                MeterWorkRailwayActual mwca = new MeterWorkRailwayActual();
                mwca.pageNum = 1;
                mwca.pageSize = 1000;
                mwca.flag = "0";
                mwca.valueFlag = "0";
                mwca.netSpot3No = "00010";  //00010;白家嘴计检站静态衡一
                if (!string.IsNullOrEmpty(dateTimeStart.Text)) //查询开始时间
                    mwca.createTime1 = dateTimeStart.Text;
                if (!string.IsNullOrEmpty(dateTimeEnd.Text)) //查询结束时间
                    mwca.createTime2 = dateTimeEnd.Text;
                if (!string.IsNullOrEmpty(cbMaterial.Text.Trim()))//物资名称
                    mwca.matterName = cbMaterial.Text.Trim();
                if (!string.IsNullOrEmpty(txtCarNoSearch.Text.Trim())) //车号
                    mwca.railwayNo = txtCarNoSearch.Text.Trim();

                dtRailwayActual.Clear();
                RESTfulResult<List<MeterWorkRailwayActual>> RESTfulResultRecent = mwas.doQuerySelectView(mwca);
                if (RESTfulResultRecent.Succeed && RESTfulResultRecent.Data != null && RESTfulResultRecent.Data.Count > 0)
                {
                    DataTable dts = dtRailwayActual.Clone();
                    if (RESTfulResultRecent.Data != null && RESTfulResultRecent.Data.Count > 0)
                    {
                        dts = RESTfulResultRecent.Data.ListToDataTable<MeterWorkRailwayActual>();
                    }
                    ClsControlPack.CopyDataToDatatable(ref dts, ref this.dtRailwayActual, true);
                    foreach (var item in this.ultraGrid3.Rows)
                    {
                        item.Cells["grossWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["grossWeight"].Value.ToString()) ? "0" : item.Cells["grossWeight"].Value.ToString()) / 1000;
                        item.Cells["tareWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["tareWeight"].Value.ToString()) ? "0" : item.Cells["tareWeight"].Value.ToString()) / 1000;
                        item.Cells["netWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["netWeight"].Value.ToString()) ? "0" : item.Cells["netWeight"].Value.ToString()) / 1000;
                    }
                    ClsControlPack.RefreshAndAutoSize(ultraGrid3);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("净重数据查询出现异常，请联系系统维护人员处理！异常原因:\r\n" + ex);
                l.WriteLog(13, "结净数据查询框异常，异常原因：" + ex);
            }
        }

        /// <summary>
        /// 查询100条结净计量记录；衡二
        /// </summary>
        private void queryActual2()
        {
            try
            {
                //计量结净数据查询
                MeterWorkRailwayActual mwca = new MeterWorkRailwayActual();
                mwca.pageNum = 1;
                mwca.pageSize = 1000;
                mwca.flag = "0";
                mwca.valueFlag = "0";
                mwca.netSpot3No = "00011";  //00011;白家嘴计检站静态衡二
                if (!string.IsNullOrEmpty(dateTimeStart.Text)) //查询开始时间
                    mwca.createTime1 = dateTimeStart.Text;
                if (!string.IsNullOrEmpty(dateTimeEnd.Text)) //查询结束时间
                    mwca.createTime2 = dateTimeEnd.Text;
                if (!string.IsNullOrEmpty(cbMaterial.Text.Trim()))//物资名称
                    mwca.matterName = cbMaterial.Text.Trim();
                if (!string.IsNullOrEmpty(txtCarNoSearch.Text.Trim())) //车号
                    mwca.railwayNo = txtCarNoSearch.Text.Trim();

                dtRailwayActual2.Clear();
                RESTfulResult<List<MeterWorkRailwayActual>> RESTfulResultRecent = mwas.doQuerySelectView(mwca);
                if (RESTfulResultRecent.Succeed && RESTfulResultRecent.Data != null && RESTfulResultRecent.Data.Count > 0)
                {
                    DataTable dts = dtRailwayActual2.Clone();
                    if (RESTfulResultRecent.Data != null && RESTfulResultRecent.Data.Count > 0)
                    {
                        dts = RESTfulResultRecent.Data.ListToDataTable<MeterWorkRailwayActual>();
                    }
                    ClsControlPack.CopyDataToDatatable(ref dts, ref this.dtRailwayActual2, true);
                    foreach (var item in this.ultraGridActual2.Rows)
                    {
                        item.Cells["grossWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["grossWeight"].Value.ToString()) ? "0" : item.Cells["grossWeight"].Value.ToString()) / 1000;
                        item.Cells["tareWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["tareWeight"].Value.ToString()) ? "0" : item.Cells["tareWeight"].Value.ToString()) / 1000;
                        item.Cells["netWeight"].Value = double.Parse(string.IsNullOrEmpty(item.Cells["netWeight"].Value.ToString()) ? "0" : item.Cells["netWeight"].Value.ToString()) / 1000;
                    }
                    ClsControlPack.RefreshAndAutoSize(ultraGridActual2);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("净重数据查询出现异常，请联系系统维护人员处理！异常原因:\r\n" + ex);
                l.WriteLog(13, "结净数据查询框异常，异常原因：" + ex);
            }
        }

        private int iTime = 0;

        /// <summary>
        /// 定时任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                #region 每2秒查一次接管数据,若接管则改变状态 controlIp
                if (iTime % 2 == 0)
                {
                    MeterBaseSpotInfoService service = new MeterBaseSpotInfoService();
                    RESTfulResult<List<MeterBaseSpotInfo>> rms = service.doQueryWf(new MeterBaseSpotInfo { validFlag = "1", spotTypeNo = "001002002" });
                    if (rms.Succeed && rms.Data != null && rms.Data.Count > 0)
                    {
                        PbStaticRailwayCache.sportInfos = rms.Data;
                        string str = "";
                        string cIp = "";
                        bool bRefash = false;
                        DataTable dt = dtJGPointInfo.Clone();
                        foreach (DataRow dr in dtJGPointInfo.Rows)
                        {
                            MeterBaseSpotInfo msi = rms.Data.Where(s => s.baseSpotNo == dr["baseSpotNo"].ToString().Trim()).FirstOrDefault();
                            if (msi != null && msi.baseSpotNo != null)
                            {
                                str = (string.IsNullOrEmpty(msi.controlIp) ? "未接管" : "已接管");
                                if (dr["validFlag"].ToString().Trim() != str)
                                {
                                    dr["validFlag"] = str;
                                    bRefash = true;
                                }

                                cIp = (string.IsNullOrEmpty(msi.controlIp) ? "" : msi.controlIp);
                                if (dr["controlIp"].ToString().Trim() != cIp)
                                {
                                    dr["controlIp"] = cIp;
                                    bRefash = true;
                                }
                            }
                            dt.Rows.Add(dr.ItemArray);
                        }
                        if (bRefash)
                        {
                            ClsControlPack.CopyDataToDatatable(ref dt, ref this.dtJGPointInfo, true);
                        }
                    }
                }
                #endregion

                #region 10分钟刷新一次数据
                if (iTime < 600)
                {
                    iTime++;
                    if (iTime == 600)
                    {
                        //*
                        try
                        {
                            //秤上没有车时，每隔10分钟获取一次基础数据
                            if (PbStaticRailwayCache.collect != null && PbStaticRailwayCache.collect.mainWgt < 1000) //大于1t才认为有车厢
                            {
                                if (bd.setBaseDb())
                                {
                                    l.WriteLog(0, "十分钟获取基础数据成功");
                                }
                                else
                                {
                                    l.WriteLog(0, "十分钟获取基础数据失败");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            l.WriteLog(0, "十分钟获取基础数据失败：" + ex.Message);
                        }
                        //*/
                    }
                }
                else
                {
                    iTime = 0;
                }
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show("timer1_Tick任务异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "timer1_Tick任务异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        #region 10分钟刷新一次数据

        /// <summary>
        /// 使用定时任务，确保查询的时间间隔大于1s
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerSearchLimit_Tick(object sender, EventArgs e)
        {
            searchLimit++;
        }

        #endregion

        /// <summary>
        /// 测试按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            bTest = !bTest;
        }

        /// <summary>
        /// 预报数据双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ultraGrid1_DoubleClick(object sender, EventArgs e)
        {
            int count = 0;
            try
            {
                if (this.ultraGrid1 == null || this.ultraGrid1.Rows.Count == 0)
                {
                    return;
                }
                UltraGridRow ugr = this.ultraGrid1.ActiveRow;
                ugr.Appearance.BackColor = Color.GreenYellow; //选中后，设置背景颜色为绿色
                count = 1;
                if (ugr != null && !string.IsNullOrEmpty(txtCarNo.Text))
                {
                    count = 2;
                    DataRow[] dr = dtRailwayScale.Select("predictionNo='" + ugr.Cells["predictionNo"].Text.Trim() + "'");
                    count = 3;
                    if (dr != null && dr.Length > 0)
                    {
                        count = 4;
                        preTack = dr[0].CreateItem<PreRailwayScale>();
                        count = 5;
                        ucStaticTrackMeterInfo1.setPreTrackInfo(preTack);
                    }
                }
            }
            catch (Exception ex)
            {
                l.WriteLog(13, "frmMeterMain.ultraGrid1_DoubleClick方法异常【" + count + "】：" + ex.Message);
                MessageBox.Show("预报数据双击事件异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n!" + ex);
            }
        }

        #endregion

        /// <summary>
        /// 选择的sheet页变了，则重新查询数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uTab_SelectedTabChanged(object sender, Infragistics.Win.UltraWinTabControl.SelectedTabChangedEventArgs e)
        {
            //QueryCarNo(); //选择的sheet页变了，则重新查询数据
        }

        /// <summary>
        /// 车牌变更事件
        /// 车号变更后，界面的提示信息也需要清空
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtCarNo_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //2021年4月10日 车号改变车号改变后，界面按钮颜色变为正常颜色；同时可以点击
                //提示信息框清空
                if (oldEditCarNo.Equals(txtCarNo.Text.Trim())) return;
                //if (string.IsNullOrEmpty(txtCarNo.Text.Trim()) || txtCarNo.Text.Length == 0) { };

                oldEditCarNo = txtCarNo.Text.Trim();

                strCarNo = txtCarNo.Text.ToString().Trim(); //全局变量赋值
                scModel1.carno = strCarNo;
                scModel2.carno = strCarNo;

                if (txtCarNo.Text.Length > 0 && txtCarNo.Text.Length != 7)
                {
                    btnSave.BackColor = Color.DodgerBlue;
                    isLockWgt = false;//不锁定界面重量
                    setMsgInfo(txtMsgInfo, "", ""); //清空信息提示框
                    isEditCarNo = true;
                }
                //车号为7位的时候，查询一下数据
                if (txtCarNo.Text.Length == 7)
                {
                    searchLimit = 3; //置为3，可以强制查询
                    isLockWgt = false;//不锁定界面重量
                    strCarNo = txtCarNo.Text.ToString().Trim(); //全局变量赋值
                    scModel1.carno = strCarNo;
                    scModel2.carno = strCarNo;
                    btnSave.BackColor = Color.DodgerBlue;
                    //isEditCarNo = true;  //车号为7位的时候，还是保持原来的标志位；当点击保存按钮后，不管是否保存成功，都讲isEditCarNo = false（自动获取车号状态）;
                    QueryCarNo(); //车号有变化的时候，查询一次数据
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("txtCarNo_TextChanged处理异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n!" + ex);
                l.WriteLog(13, "txtCarNo_TextChanged处理异常：" + ex.Message);
            }
        }

        /// <summary>
        /// 获取IP地址
        /// </summary>
        /// <returns></returns>
        public string GetIP()
        {
            try
            {
                IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddr = ipHost.AddressList[0];
                return ipAddr.ToString();
            }
            catch (Exception ex)
            {
                Random rd = new Random();
                MessageBox.Show("GetIP方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n!" + ex);
                l.WriteLog(13, "GetIP方法异常：" + ex.Message);
                return rd.Next(99999, 999999) + "";
            }
        }

        /// <summary>
        /// 查询进一个月的计量数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (searchLimit > 1)
            {
                QueryCarNo();//点击查询按钮查询数据
                querySacle();//计量预报查询；查询所有有效的预报
                queryFirst(); //查询100条一次计量记录
                queryActual(); //查询100条二次计量记录

                queryFirst2(); //查询100条一次计量记录
                queryActual2(); //查询100条二次计量记录
            }
            else
            {
                MessageBox.Show("请 2 秒钟之后再点击查询操作！");
            }
        }

        /// <summary>
        /// 车号刷新按钮，点击后车号获取模式变为【自动】
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAutoCarNo_Click(object sender, EventArgs e)
        {
            isLockWgt = false;//不锁定界面重量
            isEditCarNo = false; //刷新后，自动获取车号
            oldEditCarNo = ""; //车号验证中的旧车号
            searchLimit = 3;
            btnZZWgt.BackColor = Color.DodgerBlue;//刷新后，不再进行自重处理；
            isUsedFactoryWeight = false;

            btnSave.BackColor = Color.DodgerBlue; //刷新后，可以点击保存；
            setMsgInfo(txtMsgInfo, "", ""); //清空信息提示框
            QueryCarNo();//点击刷新后，重新查询一下数据
        }

        /// <summary>
        /// 下拉框公共方法：初始化物资名称下拉框
        /// </summary>
        private void loadMaterialInfo()
        {
            try
            {
                RESTfulResult<List<MeterBaseMatterInfo>> rmx = matterService.doQueryListLike(new MeterBaseMatterInfo { validFlag = "1", pageNum = 1, pageSize = 9999 });

                if (rmx.Succeed && rmx.Data != null && rmx.Data.Count > 0)
                {
                    dtMaterial = rmx.Data.ListToDataTable<MeterBaseMatterInfo>();
                }
                if (dtMaterial != null)
                {
                    DataRow dr = dtMaterial.NewRow();
                    dtMaterial.Rows.InsertAt(dr, 0);
                    cbMaterial.DataSource = dtMaterial;

                    cbMaterial.DisplayMember = "matterName";
                    cbMaterial.ValueMember = "matterNo";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("品名初始化失败  " + ex.ToString());
            }
        }

        /// <summary>
        /// 下拉框公共方法：光标离开的接口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbMaterial_Leave(object sender, EventArgs e)
        {
            try
            {
                if (show == null)
                {
                    return;
                }

                if (show.Focused == false)
                {
                    show.Visible = false;
                }
            }
            catch (System.Exception exp)
            {
                //WriteLog(exp.Message);
            }
        }

        /// <summary>
        /// 下拉框公共方法：物资名称下拉框字符串改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbMaterial_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (show == null || this.cbMaterial.Focused == false)
                {
                    return;
                }

                ChangeString(sender);

                show.Location = new Point(220, 169); //设置焦点的位置
                showLocation = 1;
                int sign = 0;
                if (cbMaterial.Text.Length == 0)
                {
                    show.Visible = false;
                }
                else
                {
                    for (int i = 0; i < cbMaterial.Text.Length; i++)
                    {
                        if (Char.IsLower(cbMaterial.Text[i]) == false && Char.IsUpper(cbMaterial.Text[i]) == false)  //是否纯字母
                        {
                            sign = 1;
                            break;
                        }
                    }

                    if (sign == 0)
                    {
                        show.Items.Clear();
                        string text = cbMaterial.Text;
                        text = text.ToUpper();

                        DataRow[] matchRows = null;

                        matchRows = this.dtMaterial.Select("MATTER_NAME LIKE '%" + text + "%'"); //MNEMONIC_CODE 助记码
                        //if (matchRows.Length > 200)
                        //{
                        //    return;
                        //}

                        foreach (DataRow dr in matchRows)
                        {
                            show.Items.Add(dr["MATTERNAME"].ToString());
                        }

                        show.Visible = true;
                    }
                    else
                    {
                        show.Visible = false;
                    }
                }
            }
            catch (System.Exception exp)
            {
                //WriteLog(exp.Message);
            }
        }

        /// <summary>
        /// 下拉框公共方法：字符串变化
        /// </summary>
        /// <param name="sender"></param>
        private void ChangeString(object sender)
        {
            if (sender is TextBox)
            {
                TextBox tb = (TextBox)sender;
                for (int i = 0; i < tb.Text.Length; i++)
                {
                    int isChange = 0;
                    char newChar = FullCodeToHalfCode(tb.Text[i], ref isChange);
                    if (isChange == 1)
                    {
                        tb.Text = tb.Text.Replace(tb.Text[i], newChar);
                        tb.SelectionStart = i + 1;
                    }
                }
            }
            else if (sender is ComboBox)
            {
                ComboBox cb = (ComboBox)sender;

                for (int i = 0; i < cb.Text.Length; i++)
                {
                    int isChange = 0;
                    char newChar = FullCodeToHalfCode(cb.Text[i], ref isChange);
                    if (isChange == 1)
                    {
                        cb.Text = cb.Text.Replace(cb.Text[i], newChar);
                        cb.SelectionStart = i + 1;
                    }
                }
            }
        }

        /// <summary>
        /// 下拉框公共方法：编码转换
        /// </summary>
        /// <param name="c"></param>
        /// <param name="isChange"></param>
        /// <returns></returns>
        private char FullCodeToHalfCode(char c, ref int isChange)
        {
            //得到c的编码
            byte[] bytes = System.Text.Encoding.Unicode.GetBytes(c.ToString());

            int H = Convert.ToInt32(bytes[1]);
            int L = Convert.ToInt32(bytes[0]);

            //得到unicode编码
            int value = H * 256 + L;

            //是全角
            if (value >= 65281 && value <= 65374)
            {
                int halfvalue = value - 65248;//65248是全半角间的差值。
                byte halfL = Convert.ToByte(halfvalue);

                bytes[0] = halfL;
                bytes[1] = 0;
                isChange = 1;
            }
            else if (value == 12288)
            {
                int halfvalue = 32;
                byte halfL = Convert.ToByte(halfvalue);

                bytes[0] = halfL;
                bytes[1] = 0;
                isChange = 1;
            }
            else
            {
                isChange = 0;
                return c;
            }

            //将bytes转换成字符
            string ret = System.Text.Encoding.Unicode.GetString(bytes);

            return Convert.ToChar(ret);
        }

        /// <summary>
        /// 下拉框公共方法：双击选中智能输入列表中的内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void show_DoubleClick(object sender, EventArgs e)
        {
            if (show.SelectedIndex >= 0 && show.SelectedIndex >= 0)
            {
                if (showLocation == 1)
                {
                    this.cbMaterial.Text = show.Items[show.SelectedIndex].ToString();
                    this.cbMaterial.Focus();
                }
                show.Visible = false;
            }
        }

        /// <summary>
        /// 下拉框公共方法：键盘按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void show_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13 && show.SelectedIndex >= 0)
            {
                if (showLocation == 1)
                {
                    this.cbMaterial.Text = show.Items[show.SelectedIndex].ToString();
                    this.cbMaterial.Focus();
                }
                show.Visible = false;
            }
            else if ((e.KeyChar >= 65 && e.KeyChar <= 90) || (e.KeyChar >= 97 && e.KeyChar <= 122))
            {
                if (showLocation == 1)
                {
                    show.Items.Clear();
                    this.cbMaterial.Focus();
                    string text = this.cbMaterial.Text + e.KeyChar;
                    this.cbMaterial.Text = text;
                    this.cbMaterial.SelectionStart = cbMaterial.Text.Length;
                }
            }
        }

        /// <summary>
        /// 下拉框公共方法： 输入框失去焦点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void show_Leave(object sender, EventArgs e)
        {
            show.Hide();
        }

        /// <summary>
        /// 设置字段显示的别名
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static ValueList GetValueListByString(string str)
        {
            ValueList vlist = new ValueList();
            try
            {
                string[] strs = str.Split(',');
                for (int i = 0; i < strs.Length; i++)
                {
                    string[] strss = strs[i].Split(':');
                    vlist.ValueListItems.Add(strss[0], strss[1]);
                }
            }
            catch (Exception ex)
            {
            }
            return vlist;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="strCode"></param>
        /// <returns></returns>
        public static string GetTrackType(string strCode)
        {
            string valueFlag = ""; //状态（0：未配车；1：未使用；2：已使用；3：已作废；4：正使用）
            switch (strCode)
            {
                case "0": valueFlag = "未配车"; break;
                case "1": valueFlag = "未使用"; break;
                case "2": valueFlag = "已使用"; break;
                case "3": valueFlag = "已作废"; break;
                case "4": valueFlag = "正使用"; break;
                default:
                    break;
            }
            return valueFlag;
        }
    }
}