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

namespace BeltScaleSystem

{
    public partial class FrmMaxBletScale : Form
    {

        #region  参数与常量
        List<MeterBaseScalePoint> scalePoints = new List<MeterBaseScalePoint>();//计量点监控数据 目前采用仪表ip
        PreBeltScalePreService PreBeltScalePreService = new PreBeltScalePreService();//预报服务
        MeterWorkBeltActualService MeterWorkBeltActualService = new MeterWorkBeltActualService();//实绩服务
        private MeterWorkBeltXiaopiService workBeltXiaopiService = new MeterWorkBeltXiaopiService();//校皮数据接口
        MeterBaseBeltMaterialpmService baseBeltMaterialpmService = new MeterBaseBeltMaterialpmService();//物料系数服务
        public PreBeltScaleForecast beltinfo = new PreBeltScaleForecast();//预报实体
        MeterWorkBeltTimingService meterWorkBeltTimingService = new MeterWorkBeltTimingService();//定时数据接口
        private Log l = Log.GetInstance(); //日志
        RESTfulResult<List<MeterWorkBeltActual>> MeterWorkBeltActual_NOW = null;//当前计量的实绩
        private Boolean IsXiaolingA = false, IsXiaolingB = false;//是否校零
        public string oldzeroA="",oldzeroB="";
        public Boolean StartXiaoLingA = false, StartXiaoLingB=false;
        public CalibrateData[] cbDataByControlA = null, cbDataByControlB = null;
        MeterBaseOperationLogService LogService = new MeterBaseOperationLogService();//日志服务
        //页面基础信息
        public string sUserId = "", sUserName = "", sIpAddress = "", userClass = "", userGroup = "";
        public string sPointNo = "", sPointName = "";
        public MeterBaseScalePoint  rowPointInfo = null;//计量点监控信息
        private delegate void UpdateUIEventHander(object sender, UpdateUIArgs args); //自定义事件用来从线程中更新控件的值
        MeterBaseVideoinfo baseVideoinfo = null;//视频类实体
        public int BtnType = 0;
        private Boolean IsSaveA = false, IsSaveB = false;
        private Boolean Isfrist = true;//第一次进入
        /// <summary>
        /// 物料参数
        /// </summary>
        public string materialParameter = "", materialParameterB = "", materialParameterImport = "", materialParameterImportB = "";
        #region 大华SDK相关
        fDisConnectCallBack _DisConnectCallBack;
        fHaveReConnectCallBack _ReConnectCallBack;
        IntPtr _LoginID = IntPtr.Zero;
        IntPtr _LoginID1 = IntPtr.Zero;
        IntPtr _LoginID2 = IntPtr.Zero;
        NET_DEVICEINFO_Ex _DeviceInfo = new NET_DEVICEINFO_Ex();
        IntPtr _PlayID = IntPtr.Zero;
        void DisConnectCallBack(IntPtr lLoginID, IntPtr pchDVRIP, int nDVRPort, IntPtr dwUser)
        {
            this.BeginInvoke(new Action(() =>
            {
            }));
        }
        void ReConnectCallBack(IntPtr lLoginID, IntPtr pchDVRIP, int nDVRPort, IntPtr dwUser)
        {
            this.BeginInvoke(new Action(() =>
            {
            }));
        }
        #endregion
        #endregion

        public FrmMaxBletScale()
        {
            InitializeComponent();
            try
            {
                _DisConnectCallBack = new fDisConnectCallBack(DisConnectCallBack);
                _ReConnectCallBack = new fHaveReConnectCallBack(ReConnectCallBack);
                NETClient.Init(_DisConnectCallBack, IntPtr.Zero, null);
                NETClient.SetAutoReconnect(_ReConnectCallBack, IntPtr.Zero);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }

        #region 采集数据
        public MeasData measDataA;
        public MeasData measDataB;

        #endregion

        #region #更新控件数据
        //更新UltraTextEditor、Button控件值Convert.ToDouble(txtWeight.Text.Replace("kg", "").Trim())
        private void setTedValue(string Ted, string values)
        {
            try
            {
                switch (Ted)
                {
                    //A磅
                    case "instrument_weight_Ted"://仪表重量
                        this.instrument_weight_Ted.Invoke(new UpdateUIEventHander(UpdateUI_Method), instrument_weight_Ted, new UpdateUIArgs(values, "t"));
                        break;
                    case "cumulative_weight_Ted"://当前累计量
                        this.cumulative_weight_Ted.Invoke(new UpdateUIEventHander(UpdateUI_Method), cumulative_weight_Ted, new UpdateUIArgs(values, "t"));
                        break;
                    case "realtime_amount_Ted"://实时量
                        this.realtime_amount_Ted.Invoke(new UpdateUIEventHander(UpdateUI_Method), realtime_amount_Ted, new UpdateUIArgs(values, "t/h"));
                        break;
                    case "belt_speed_Ted"://皮带速度
                        this.belt_speed_Ted.Invoke(new UpdateUIEventHander(UpdateUI_Method), belt_speed_Ted, new UpdateUIArgs(values, "m/s"));
                        break;
                    case "temperature_Ted"://温度
                        this.temperature_Ted.Invoke(new UpdateUIEventHander(UpdateUI_Method), temperature_Ted, new UpdateUIArgs(values, "℃"));
                        break;
                    case "parameter_Ted"://物料参数
                        this.parameter_Ted.Invoke(new UpdateUIEventHander(UpdateUI_Method), parameter_Ted, new UpdateUIArgs(values, ""));
                        break;
                    //B磅
                    case "instrument_weight_Ted_1"://仪表重量
                        this.instrument_weight_Ted_1.Invoke(new UpdateUIEventHander(UpdateUI_Method), instrument_weight_Ted_1, new UpdateUIArgs(values, "t"));
                        break;
                    case "cumulative_weight_Ted_1"://当前累计量
                        this.cumulative_weight_Ted_1.Invoke(new UpdateUIEventHander(UpdateUI_Method), cumulative_weight_Ted_1, new UpdateUIArgs(values, "t"));
                        break;
                    case "realtime_amount_Ted_1"://实时量
                        this.realtime_amount_Ted_1.Invoke(new UpdateUIEventHander(UpdateUI_Method), realtime_amount_Ted_1, new UpdateUIArgs(values, "t/h"));
                        break;
                    case "belt_speed_Ted_1"://皮带速度
                        this.belt_speed_Ted_1.Invoke(new UpdateUIEventHander(UpdateUI_Method), belt_speed_Ted_1, new UpdateUIArgs(values, "m/s"));
                        break;
                    case "temperature_Ted_1"://温度
                        this.temperature_Ted_1.Invoke(new UpdateUIEventHander(UpdateUI_Method), temperature_Ted_1, new UpdateUIArgs(values, "℃"));
                        break;
                    case "parameter_Ted_1"://物料参数
                        this.parameter_Ted_1.Invoke(new UpdateUIEventHander(UpdateUI_Method), parameter_Ted_1, new UpdateUIArgs(values, ""));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }
        //更新UltraTextEditor、Button控件值
        private double getTedValue(string Ted)
        {
            try
            {
                switch (Ted)
                {
                    //A磅
                    case "instrument_weight_Ted"://仪表重量
                        return Convert.ToDouble(instrument_weight_Ted.Text.Replace("t", "").Trim());
                    case "cumulative_weight_Ted"://当前累计量
                        return Convert.ToDouble(cumulative_weight_Ted.Text.Replace("t", "").Trim());
                    case "realtime_amount_Ted"://实时量
                        return Convert.ToDouble(realtime_amount_Ted.Text.Replace("t/h", "").Trim());
                    case "belt_speed_Ted"://皮带速度
                        return Convert.ToDouble(belt_speed_Ted.Text.Replace("m/s", "").Trim());
                    case "temperature_Ted"://温度
                        return Convert.ToDouble(temperature_Ted.Text.Replace("℃", "").Trim());
                    case "parameter_Ted"://物料参数
                        return Convert.ToDouble(parameter_Ted.Text);
                    //B磅
                    case "instrument_weight_Ted_1"://仪表重量
                        return Convert.ToDouble(instrument_weight_Ted_1.Text.Replace("t", "").Trim());
                    case "cumulative_weight_Ted_1"://当前累计量
                        return Convert.ToDouble(cumulative_weight_Ted_1.Text.Replace("t", "").Trim());
                    case "realtime_amount_Ted_1"://实时量
                        return Convert.ToDouble(realtime_amount_Ted_1.Text.Replace("t/h", "").Trim());
                    case "belt_speed_Ted_1"://皮带速度
                        return Convert.ToDouble(belt_speed_Ted_1.Text.Replace("m/s", "").Trim());
                    case "temperature_Ted_1"://温度
                        return Convert.ToDouble(temperature_Ted_1.Text.Replace("℃", "").Trim());
                    case "parameter_Ted_1"://物料参数
                        return Convert.ToDouble(parameter_Ted_1.Text);

                    default:
                        return 0;
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }
        /// <summary>
        /// 更新界面的UI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void UpdateUI_Method(object sender, UpdateUIArgs args)
        {
            if (sender is UltraTextEditor)
            {
                if (args.textValue == "" || args.textValue == null)
                {
                    ((UltraTextEditor)sender).Text = "0 " + args.unitValue;
                }
                else
                {
                    ((UltraTextEditor)sender).Text = args.textValue + " " + args.unitValue;
                }
            }
            else if (sender is Button)
            {
                if (args.textValue == "red")
                {
                    ((Button)sender).BackColor = Color.Red;
                    ((Button)sender).ForeColor = Color.White;
                }
                else if (args.textValue == "green")
                {
                    ((Button)sender).BackColor = Color.White;
                    ((Button)sender).ForeColor = Color.Black;
                }
                else
                {
                    ((Label)sender).Text = args.textValue;
                }
            }
        }
        public class UpdateUIArgs : EventArgs
        {
            public string textValue { get; private set; }
            public string unitValue { get; private set; }
            public UpdateUIArgs(string textValue, string unit)
            {
                this.textValue = textValue;
                this.unitValue = unit;
            }
        }
        #endregion


        //初始化加载
        private void FrmMaxBletScale_Load(object sender, EventArgs e)
        {
            if (!findMoxa())
            {
                MessageBox.Show("仪表ip获取失败！");
                return;
            }
            InitScaleInfo(scalePoints[0].moxaIp == "" ? "" : scalePoints[0].moxaIp, scalePoints[1].moxaIp == "" ? "" : scalePoints[1].moxaIp);
            loadFrom();//加载数据
            InitFrm();//初始化界面
            InitGraph();//初始化流量曲线
            timer1.Start();
            timer2.Start();
            InitVidio();//连接视频
            //UpdateControl(BtnType);
            Isfrist = false;
        }

        #region    表格查询相关 按钮事件
        /// <summary>
        /// 预报查询接口
        /// </summary>
        private void queryScale()
        {
            try
            {
                DataTable dtScaleTable = dataTable1.Clone();
                CommonPage<PreBeltScaleForecast> cp = new CommonPage<PreBeltScaleForecast>();
                cp.startTime = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd HH:mm:ss");
                cp.endTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                cp.param = new PreBeltScaleForecast { valueFlag = "8", baseSpotNo = sPointNo }; //状态为8时  查询1和2
                RESTfulResult<List<PreBeltScaleForecast>> rms = PreBeltScalePreService.doQueryTenWf(cp);
                if (rms.Succeed)
                {
                    if (rms.Data != null && rms.Data.Count > 0)
                    {
                        dtScaleTable = rms.Data.ListToDataTable<PreBeltScaleForecast>();

                        ClsControlPack.CopyDataToDatatable(ref dtScaleTable, ref dataTable1, true);
                        foreach (UltraGridRow ugr in ultraGrid1.Rows)
                        {
                            if (ugr.Cells["valueFlag"].Value.ToString() == "2")
                            {
                                ugr.Appearance.BackColor = Color.YellowGreen;
                                ultraGrid1_DoubleClickRow_Check(ugr);
                            }
                            else
                            {
                                ugr.Appearance.BackColor = Color.White;
                            }
                        }
                        ClsControlPack.RefreshAndAutoSize(ultraGrid1);
                    }
                    else
                    {
                        dtScaleTable.Clear();
                        ClsControlPack.CopyDataToDatatable(ref dtScaleTable, ref dataTable1, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGrid1);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 定时数据查询接口
        /// </summary>
        private void querytiminginfo()
        {
            try
            {
                DataTable dtTmingTable = dataTable3.Clone();
                CommonPage<MeterWorkBeltTiminginfo> cp = new CommonPage<MeterWorkBeltTiminginfo>();
                cp.startTime = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd HH:mm:ss");
                cp.endTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                cp.param = new MeterWorkBeltTiminginfo { valueFlag = "1", baseSpotNo = sPointNo, scaleName = "A", weightType = "0" };
                RESTfulResult<List<MeterWorkBeltTiminginfo>> rms = meterWorkBeltTimingService.doQueryWf(cp);
                DataTable dtTmingTable1 = dataTable4.Clone();
                CommonPage<MeterWorkBeltTiminginfo> cp1 = new CommonPage<MeterWorkBeltTiminginfo>();
                cp1.startTime = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd HH:mm:ss");
                cp1.endTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                cp1.param = new MeterWorkBeltTiminginfo { valueFlag = "1", baseSpotNo = sPointNo, scaleName = "B", weightType = "0" };
                RESTfulResult<List<MeterWorkBeltTiminginfo>> rms1 = meterWorkBeltTimingService.doQueryWf(cp1);
                if (rms.Succeed && rms1.Succeed)
                {
                    if (rms.Data != null && rms.Data.Count > 0)
                    {
                        dtTmingTable = rms.Data.ListToDataTable<MeterWorkBeltTiminginfo>();

                        ClsControlPack.CopyDataToDatatable(ref dtTmingTable, ref dataTable3, true);

                        ClsControlPack.RefreshAndAutoSize(ultraGrid2);
                    }
                    else
                    {
                        dtTmingTable.Clear();
                        ClsControlPack.CopyDataToDatatable(ref dtTmingTable, ref dataTable3, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGrid2);
                    }
                    if (rms1.Data != null && rms1.Data.Count > 0)
                    {
                        dtTmingTable1 = rms1.Data.ListToDataTable<MeterWorkBeltTiminginfo>();

                        ClsControlPack.CopyDataToDatatable(ref dtTmingTable1, ref dataTable4, true);

                        ClsControlPack.RefreshAndAutoSize(ultraGrid3);
                    }
                    else
                    {
                        dtTmingTable1.Clear();
                        ClsControlPack.CopyDataToDatatable(ref dtTmingTable1, ref dataTable4, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGrid3);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 双击grid 赋值预报
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ultraGrid1_DoubleClickRow(object sender, DoubleClickRowEventArgs e)
        {
            try
            {
                UltraGridRow row = ultraGrid1.ActiveRow;
                if (ultraGrid1.ActiveRow == null)
                {
                    return;
                }
                if (startMerterBtn.Enabled == true && startMerterBtn_1.Enabled == true)
                {   //在计量过程中不允许替换预报
                    //界面赋值
                    ultraGrid1_DoubleClickRow_Check(row);
                }
                else
                {
                    if (row.Cells["valueFlag"].Text.Trim() == "使用中")
                    {
                        ultraGrid1_DoubleClickRow_Check(row);
                    }
                    else
                    {
                        MessageBox.Show("在计量过程中不允许更换其他预报！");
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ultraGrid1_ClickCell方法处理异常：" + ex);
            }
        }
        private void ultraGrid1_DoubleClickRow_Check(UltraGridRow ugr)
        {
            //重置物料系数
            materialParameter = "";
            materialParameterB = "";
            materialParameterImport = "";
            materialParameterImportB = "";
            CommonPage<PreBeltScaleForecast> cp = new CommonPage<PreBeltScaleForecast>();
            cp.param = new PreBeltScaleForecast { valueFlag = "8", baseSpotNo = sPointNo }; //状态为8时  查询1和2
            if (ugr != null)
            {
                beltinfo.predictionNo = ugr.Cells["predictionNo"].Text.Trim(); //预报编号
                beltinfo.newMatName = ugr.Cells["newMatName"].Text.Trim();   //物料名称
                beltinfo.newSupplier = ugr.Cells["newSupplier"].Text.Trim();//发货单位
                beltinfo.receivingUintName = ugr.Cells["receivingUintName"].Text.Trim(); //收货单位
                beltinfo.forwardingUnitNo = ugr.Cells["forwardingUnitNo"].Text.Trim();//发货单位编号
                beltinfo.receivingUintNo = ugr.Cells["receivingUintNo"].Text.Trim();//收货单位编号
                beltinfo.productNo = ugr.Cells["productNo"].Text.Trim();//物料编号
                beltinfo.valueFlag = ugr.Cells["valueFlag"].Text.Trim();//状态
                autoAutoFill(beltinfo);
                beltinfo.baseSpotNo = sPointNo;
                beltinfo.newMatClass = ugr.Cells["newMatClass"].Text.Trim();//状态
                beltinfo.valueFlag = "1";
                cp.memo1 = "A";
                cp.param = beltinfo;
                RESTfulResult<List<MeterBasemeterMaterialpm>> rms = baseBeltMaterialpmService.doQueryByBeltType(cp);
                if (rms.Data.Count > 0 && !Isfrist)
                {
                    materialParameter = rms.Data[0].materialParameter.ToString();
                    materialParameterImport = rms.Data[0].materialParameterImport.ToString();
                    Boolean IsUpdateMatPm = false;
                    //根据进口或者非进口的来修改物料参数
                    if (materialParameterImport != "" && beltinfo.newMatClass.Contains("进口"))
                    {
                        megA.Text = "物料参数:进口" + materialParameterImport;
                        if (materialParameterImport != getTedValue("parameter_Ted").ToString())
                        {
                            if (MessageBox.Show("物料参数不一致，是否更改物料参数？", sPointName + " A秤", MessageBoxButtons.YesNo) == DialogResult.Yes)//如果点击“确定”按钮
                            {
                                updateMatParameter(materialParameterImport, "A");
                                IsUpdateMatPm = true;
                            }
                        }

                    }
                    if (materialParameter != "" && !beltinfo.newMatClass.Contains("进口"))
                    {
                        megA.Text = "物料参数:国内" + materialParameter;
                        if (materialParameter != getTedValue("parameter_Ted").ToString())
                        {
                            if (MessageBox.Show("物料参数不一致，是否更改物料参数？", sPointName + " A秤", MessageBoxButtons.YesNo) == DialogResult.Yes)//如果点击“确定”按钮
                            {
                                updateMatParameter(materialParameter, "A");
                                IsUpdateMatPm = true;
                            }
                        }
                    }

                    cp.memo1 = "B";
                    rms = baseBeltMaterialpmService.doQueryByBeltType(cp);
                    if (rms.Data.Count > 0)
                    {
                        materialParameterB = rms.Data[0].materialParameter.ToString();
                        materialParameterImportB = rms.Data[0].materialParameterImport.ToString();
                    }
                    if (beltinfo.newMatClass.Contains("进口") && materialParameterImportB != "")
                    {
                        megB.Text = "物料参数：进口" + materialParameterImportB;
                        //根据进口或者非进口的来修改物料参数
                        if (materialParameterImportB != getTedValue("parameter_Ted_1").ToString())
                        {
                            if (MessageBox.Show("物料参数不一致，是否更改物料参数？", sPointName + " B秤", MessageBoxButtons.YesNo) == DialogResult.Yes)//如果点击“确定”按钮
                            {
                                updateMatParameter(materialParameterImportB, "B");
                                IsUpdateMatPm = true;
                            }
                        }

                    }
                    if (!beltinfo.newMatClass.Contains("进口") && materialParameterB != "")
                    {
                        megB.Text = "物料参数：国内" + materialParameterB;
                        if (materialParameterB != getTedValue("parameter_Ted_1").ToString())
                        {
                            if (MessageBox.Show("物料参数不一致，是否更改物料参数？", sPointName + " B秤", MessageBoxButtons.YesNo) == DialogResult.Yes)//如果点击“确定”按钮
                            {
                                updateMatParameter(materialParameterB, "B");
                                IsUpdateMatPm = true;
                            }
                        }
                    }
                    if (IsUpdateMatPm)
                    {
                        MessageBox.Show("更改系数完成，请核对！");
                    }

                }

            }
            if (MeterWorkBeltActual_NOW != null && MeterWorkBeltActual_NOW.Data != null)
            {
                if (MeterWorkBeltActual_NOW.Data.Count == 1)
                {
                    if (MeterWorkBeltActual_NOW.Data[0].scaleName == "A")
                    {
                        if (MeterWorkBeltActual_NOW.Data[0].endTime != null)
                        {
                            startMerterBtn.Enabled = true; IsSaveA = false;
                        }
                        else
                        {
                            startMerterBtn.Enabled = false; IsSaveA = true;
                        }
                    }
                    if (MeterWorkBeltActual_NOW.Data[0].scaleName == "B")
                    {
                        if (MeterWorkBeltActual_NOW.Data[0].endTime != null)
                        {
                            startMerterBtn_1.Enabled = true; IsSaveB = false;
                        }
                        else
                        {
                            startMerterBtn_1.Enabled = false; IsSaveB = true;
                        }
                    }
                }
                else if (MeterWorkBeltActual_NOW.Data.Count == 2)
                {
                    if (MeterWorkBeltActual_NOW.Data[0].scaleName == "A")
                    {
                        if (MeterWorkBeltActual_NOW.Data[0].endTime == null && MeterWorkBeltActual_NOW.Data[0].startTime != null)
                        {
                            _startWeight1 = Convert.ToDouble(MeterWorkBeltActual_NOW.Data[0].startWeight);
                            IsSaveA = true;
                            UpdateControl(1);//A开始计量
                        }
                    }
                    if (MeterWorkBeltActual_NOW.Data[0].scaleName == "B")
                    {
                        if (MeterWorkBeltActual_NOW.Data[0].endTime == null && MeterWorkBeltActual_NOW.Data[0].startTime != null)
                        {
                            UpdateControl(2);//B开始计量
                            _startWeight2 = Convert.ToDouble(MeterWorkBeltActual_NOW.Data[0].startWeight);
                            IsSaveB = true;
                        }
                    }

                    if (MeterWorkBeltActual_NOW.Data[1].scaleName == "A")
                    {
                        if (MeterWorkBeltActual_NOW.Data[1].endTime == null && MeterWorkBeltActual_NOW.Data[1].startTime != null)
                        {
                            _startWeight1 = Convert.ToDouble(MeterWorkBeltActual_NOW.Data[1].startWeight);
                            IsSaveA = true;
                            UpdateControl(1);//A开始计量
                        }
                    }
                    if (MeterWorkBeltActual_NOW.Data[1].scaleName == "B")
                    {
                        if (MeterWorkBeltActual_NOW.Data[1].endTime == null && MeterWorkBeltActual_NOW.Data[1].startTime != null)
                        {
                            UpdateControl(2);//B开始计量
                            _startWeight2 = Convert.ToDouble(MeterWorkBeltActual_NOW.Data[1].startWeight);
                            IsSaveB = true;
                        }
                    }

                }
            }

        }
        //根据预报编码查询实绩
        private void findActualById(string predictionNo)
        {
            MeterWorkBeltActual_NOW = null;//清空
            CommonPage<MeterWorkBeltActual> cp2 = new CommonPage<MeterWorkBeltActual>();
            MeterWorkBeltActual meterWorkBeltActual = new MeterWorkBeltActual();
            if (predictionNoTxt.Text.Trim() != "")
            {
                meterWorkBeltActual.valueFlag = "1";
                meterWorkBeltActual.baseSpotNo = sPointNo;
                meterWorkBeltActual.predictionNo = predictionNo;
                cp2.param = meterWorkBeltActual;
                MeterWorkBeltActual_NOW = MeterWorkBeltActualService.doQuery(cp2.param);
            }
        }
        /// <summary>
        /// 实绩查询接口
        /// </summary>  
        private void queryActual()
        {
            try
            {
                DataTable dtScaleTable = dataTable5.Clone();
                CommonPage<MeterWorkBeltActual> cp = new CommonPage<MeterWorkBeltActual>();
                cp.param = new MeterWorkBeltActual
                {
                    valueFlag = "1",
                    baseSpotNo = sPointNo,
                    startTime = DateTime.Now
                };
                cp.startTime = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd HH:mm:ss");
                cp.endTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                RESTfulResult<List<MeterWorkBeltActual>> rms = MeterWorkBeltActualService.doQueryAndMultiple(cp);
                if (rms.Succeed)
                {
                    if (rms.Data != null && rms.Data.Count > 0)
                    {
                        dtScaleTable = rms.Data.ListToDataTable<MeterWorkBeltActual>();
                        ClsControlPack.CopyDataToDatatable(ref dtScaleTable, ref dataTable5, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGridActual);
                    }
                    else
                    {
                        dtScaleTable.Clear();
                        ClsControlPack.CopyDataToDatatable(ref dtScaleTable, ref dataTable5, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGridActual);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion

        #region 流量曲线
        private StrapSeries _series1 = new StrapSeries();
        private StrapSeries _series2 = new StrapSeries();
        private const int _maxPointCount = 300;
        //初始化流量曲线
        private void InitGraph() {
            ultraChart1.Series.Clear();
            ultraChart2.Series.Clear();
            ultraChart1.Series.Add(_series1);
            ultraChart2.Series.Add(_series2);
            StrapDataPoint point = new StrapDataPoint();
            point.NumericValue = 0;
            point.TimeValue = DateTime.Now.AddSeconds(-_maxPointCount);
            _series1.Points.Add(point);
            _series2.Points.Add(point);
            ultraChart1.Tooltips.Format = Infragistics.UltraChart.Shared.Styles.TooltipStyle.LabelPlusDataValue;
            ultraChart2.Tooltips.Format = Infragistics.UltraChart.Shared.Styles.TooltipStyle.LabelPlusDataValue;
        }
        private void timer2_Tick(object sender, EventArgs e)
        {
            DateTime now = DateTime.Now;
            string endTimeStr = now.ToString("HH:mm:ss");
            string startTimeStr = now.AddSeconds(-_maxPointCount).ToString("HH:mm:ss");
            lbl_EndTime1.Text = endTimeStr;
            lbl_EndTime2.Text = endTimeStr;
            lbl_StartTime1.Text = startTimeStr;
            lbl_StartTime2.Text = startTimeStr;

            StrapDataPoint point = new StrapDataPoint();
            point.TimeValue = now;
            point.NumericValue = Convert.ToDouble(getTedValue("realtime_amount_Ted"));
            point.Label = "时间:" + point.TimeValue.ToString("HH:mm:ss") + "\r\n流量";
            _series1.Points.Add(point);
            if (_series1.Points.Count > _maxPointCount)
            {
                _series1.Points.RemoveAt(0);
            }

            point = new StrapDataPoint();
            point.TimeValue = now;
            point.NumericValue = Convert.ToDouble(getTedValue("realtime_amount_Ted_1"));
            point.Label = "时间:" + point.TimeValue.ToString("HH:mm:ss") + "\r\n流量";
            _series2.Points.Add(point);
            if (_series2.Points.Count > _maxPointCount)
            {
                _series2.Points.RemoveAt(0);
            }
        }
        #endregion

        #region 公共方法
        /// <summary>
        /// 定时器  更新数据
        /// </summary>
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (measDataA != null)
                {
                    setTedValue("instrument_weight_Ted", Math.Round(measDataA.Total, 2).ToString());//仪表重量 
                    if (IsSaveA)
                    {
                        setTedValue("cumulative_weight_Ted", Math.Round(measDataA.Total - _startWeight1, 2).ToString());//累计量
                    }
                    setTedValue("realtime_amount_Ted", Math.Round(measDataA.Flow, 2).ToString());//实时量
                    setTedValue("belt_speed_Ted", Math.Round(measDataA.BeltSpeed, 2).ToString());//皮带速度
                    setTedValue("temperature_Ted", Math.Round(measDataA.FieldTemp, 2).ToString());//温度
                    setTedValue("parameter_Ted", measDataA.StdValue.ToString());//物料参数
                    _curTotalWeight1 = Math.Round(measDataA.Total, 2);
                    if ((measDataA.IsConnect ? "" : "2") != "")
                    {
                        label36.Text = "仪表连接异常！";
                        return;
                    }
                    if ((measDataA.MeterStatus ? "" : "2") != "")
                    {
                        label36.Text = "仪表为校秤状态！";
                        return;
                    }
                }
                if (measDataB != null)
                {
                    setTedValue("instrument_weight_Ted_1", Math.Round(measDataB.Total, 2).ToString());//仪表重量 
                    if (IsSaveB) {
                        setTedValue("cumulative_weight_Ted_1", Math.Round(measDataB.Total - _startWeight2, 2).ToString());//累计量
                    }
                    setTedValue("realtime_amount_Ted_1", Math.Round(measDataB.Flow, 2).ToString());//实时量
                    setTedValue("belt_speed_Ted_1", Math.Round(measDataB.BeltSpeed, 2).ToString());//皮带速度
                    setTedValue("temperature_Ted_1", Math.Round(measDataB.FieldTemp, 2).ToString());//温度
                    setTedValue("parameter_Ted_1", measDataB.StdValue.ToString());//物料参数
                    _curTotalWeight1 = Math.Round(measDataB.Total, 2);
                    if ((measDataB.IsConnect ? "" : "2") != "")
                    {
                        label37.Text = "仪表连接异常！";
                        return;
                    }
                    if ((measDataB.MeterStatus ? "" : "2") != "")
                    {
                        label37.Text = "仪表为校秤状态！";
                        return;
                    }

                }

                if (StartXiaoLingA) {
                    if (startZeroBtn.Enabled==true) {
                         startZeroBtn.Enabled = false;
                    }
                    CalibrateData[] cbDatas = cbDataByControlA;
                        oldzeroTxt.Text = oldzeroA;
                    if (cbDatas != null)
                    {
                        for (int i = 0; i < cbDatas.Length; i++)
                        {
                            CalibrateChanged(cbDatas[i], "A");
                        }
                    }
                 }
                if (StartXiaoLingB)
                {
                    if (startZeroBtn_1.Enabled == true)
                    {
                        startZeroBtn_1.Enabled = false;
                    }
                    CalibrateData[] cbDatas = cbDataByControlB;
                        oldzeroTxt_1.Text = oldzeroB;
                    if (cbDatas != null)
                    {
                        for (int i = 0; i < cbDatas.Length; i++)
                        {
                            CalibrateChanged(cbDatas[i], "B");
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("异常" + ex.Message);
                return;
            }
        }

        //初始化监控视频
        private void InitVidio()
                {
                    if (!findvidioIp())
                    {
                        MessageBox.Show("获取录像机ip失败！");
                        return;
                    }
                    else
                    {
                        // ips = spotInfo.videoIp.Split(',');
                    }
                    if (baseVideoinfo != null)
                    {
                        if (IntPtr.Zero == _LoginID)
                        {
                            if (baseVideoinfo.position1 != null && baseVideoinfo.position1 != "")
                            {
                                _LoginID = NETClient.LoginWithHighLevelSecurity(baseVideoinfo.position1, Convert.ToUInt16(baseVideoinfo.vdoPort), baseVideoinfo.vdoUser, baseVideoinfo.vdoPwd, EM_LOGIN_SPAC_CAP_TYPE.TCP, IntPtr.Zero, ref _DeviceInfo);
                            }
                            if (baseVideoinfo.position2 != null && baseVideoinfo.position2 != "")
                            {
                                _LoginID1 = NETClient.LoginWithHighLevelSecurity(baseVideoinfo.position2, Convert.ToUInt16(baseVideoinfo.vdoPort), baseVideoinfo.vdoUser, baseVideoinfo.vdoPwd, EM_LOGIN_SPAC_CAP_TYPE.TCP, IntPtr.Zero, ref _DeviceInfo);
                            }
                            if (baseVideoinfo.position3 != null && baseVideoinfo.position3 != "")
                            {
                                _LoginID2 = NETClient.LoginWithHighLevelSecurity(baseVideoinfo.position3, Convert.ToUInt16(baseVideoinfo.vdoPort), baseVideoinfo.vdoUser, baseVideoinfo.vdoPwd, EM_LOGIN_SPAC_CAP_TYPE.TCP, IntPtr.Zero, ref _DeviceInfo);
                            }
                            if (IntPtr.Zero == _LoginID)
                            {
                                MessageBox.Show(NETClient.GetLastError());
                                return;
                            }

                            if (IntPtr.Zero == _PlayID)
                            {
                                if (baseVideoinfo.position1 != "" && baseVideoinfo.position1 != null)
                                {
                                    _PlayID = NETClient.RealPlay(_LoginID, 0, this.pictureBox1.Handle);
                                }
                                if (baseVideoinfo.position2 != "" && baseVideoinfo.position2 != null)
                                {
                                    _PlayID = NETClient.RealPlay(_LoginID1, 0, this.pictureBox2.Handle);
                                }
                                if (baseVideoinfo.position3 != "" && baseVideoinfo.position3 != null)
                                {
                                    _PlayID = NETClient.RealPlay(_LoginID2, 0, this.pictureBox3.Handle);
                                }
                                if (IntPtr.Zero == _PlayID)
                                {
                                    MessageBox.Show(NETClient.GetLastError());
                                    return;
                                }
                                bool ret = NETClient.RenderPrivateData(_PlayID, true);
                                if (!ret)
                                {
                                    MessageBox.Show(NETClient.GetLastError());
                                    return;
                                }
                            }
                            else
                            {
                                NETClient.RenderPrivateData(_PlayID, false);
                                NETClient.StopRealPlay(_PlayID);
                                _PlayID = IntPtr.Zero;
                                this.pictureBox1.Refresh();
                                this.pictureBox2.Refresh();
                                this.pictureBox3.Refresh();
                            }
                        }
                    }
                }
        //查询录像机ip
        private bool findvidioIp()
        {
            MeterBaseVideoinfoService mbvs = new MeterBaseVideoinfoService();
            RESTfulResult<List<MeterBaseVideoinfo>> rm = mbvs.doQueryWf(new MeterBaseVideoinfo { pointtype = "皮带秤", pointid = sPointNo });
            if (rm.Succeed && rm.Data != null && rm.Data.Count > 0)
            {
                baseVideoinfo = rm.Data[0];
                return true;
            }
            else
            {
                return false;
            }

        }


        //填充窗口表单
        private void autoAutoFill(PreBeltScaleForecast forecast)
        {
            if (forecast == null || string.IsNullOrEmpty(forecast.predictionNo))
            {
                return;
            }
            //A磅
            predictionNoTxt.Text = forecast.predictionNo; //预报编号
            mat_nameTxt.Text = forecast.newMatName; //物料
            shippingTxt.Text = forecast.newSupplier; //发货
            receivingTxt.Text = forecast.receivingUintName;//收货
            findActualById(forecast.predictionNo);
        }
        //加载表格数据
        private void loadFrom()
        {
            //预报表转换
            ValueList vlistFlag1 = new ValueList();
            vlistFlag1.ValueListItems.Add("0", "无效");
            vlistFlag1.ValueListItems.Add("1", "未使用");
            vlistFlag1.ValueListItems.Add("2", "使用中");
            vlistFlag1.ValueListItems.Add("3", "已完成");
            this.ultraGrid1.DisplayLayout.Bands[0].Columns["valueFlag"].ValueList = vlistFlag1;
            //验证是否为校零状态
            if (StartXiaoLingA)
            {
                startZeroBtn.Enabled = false;
            }
            else {
                startZeroBtn.Enabled = true;
            }
            if (StartXiaoLingB)
            {
                startZeroBtn_1.Enabled = false;
            }
            else
            {
                startZeroBtn_1.Enabled = true;
            }
            queryActual();
            queryScale();
            querytiminginfo();
        }
        //初始化加载界面
        private void InitFrm()
        {
            this.PntNameLabel.Text = sPointName;//计量点
            this.UserNameLabel.Text = sUserName;//计量员

            //设置grid不可编辑
            GridHelper.SetExcludeColumnsActive(ultraGrid1.DisplayLayout.Bands[0], "");
            GridHelper.SetExcludeColumnsActive(ultraGrid2.DisplayLayout.Bands[0], "");
            GridHelper.SetExcludeColumnsActive(ultraGrid3.DisplayLayout.Bands[0], "");
            GridHelper.SetExcludeColumnsActive(ultraGridActual.DisplayLayout.Bands[0], "");


        }
        //清空计量预报数据
        private void ClearFromInfo()
        {
            predictionNoTxt.Text = ""; //预报编号
            mat_nameTxt.Text = ""; //物料
            shippingTxt.Text = ""; //发货
            receivingTxt.Text = "";//收货
        }
        //修改计量按钮样式
        private void UpdateControl(int id)
        {
            switch (id)
            {
                case 0://默认
                    startMerterBtn.Enabled = true;
                    startMerterBtn_1.Enabled = true;
                    ClearFromInfo();//清空预报
                    break;
                case 1:
                    startMerterBtn.Enabled = false;
                    break;
                case 2:
                    startMerterBtn_1.Enabled = false;
                    break;
                case 3:
                    startMerterBtn.Enabled = true;
                    if (startMerterBtn_1.Enabled == true)
                    {
                        ClearFromInfo();//清空预报
                    }
                    break;
                case 4:
                    startMerterBtn_1.Enabled = true;
                    if (startMerterBtn.Enabled == true)
                    {
                        ClearFromInfo();//清空预报
                    }
                    break;
                case 9:
                    startMerterBtn.Enabled = false;
                    startMerterBtn_1.Enabled = false;
                    break;

            }

        }
        private void startMerterBtn_EnabledChanged(object sender, EventArgs e)
        {
            if (startMerterBtn.Enabled == true)
            {
                startMerterBtn.BackColor = Color.LimeGreen;
                endMerterBtn.BackColor = Color.Silver;
                endMerterBtn.Enabled = false;

            }
            else
            {
                startMerterBtn.BackColor = Color.Silver;
                endMerterBtn.BackColor = Color.LimeGreen;
                endMerterBtn.Enabled = true;

            }
        }
        private void startMerterBtn_1_EnabledChanged(object sender, EventArgs e)
        {
            if (startMerterBtn_1.Enabled == true)
            {
                startMerterBtn_1.BackColor = Color.LimeGreen;
                endMerterBtn_1.BackColor = Color.Silver;
                endMerterBtn_1.Enabled = false;
            }
            else
            {
                startMerterBtn_1.BackColor = Color.Silver;
                endMerterBtn_1.BackColor = Color.LimeGreen;
                endMerterBtn_1.Enabled = true;
            }
        }
        //A开始校零
        private void startZeroBtn_EnabledChanged(object sender, EventArgs e)
        {
            if (startZeroBtn.Enabled == true)//开始校零为true时
            {
                startZeroBtn.BackColor = Color.LimeGreen;//开始
                ConfirmCalibrate.BackColor = Color.Silver;//确认
                ConfirmCalibrate.Enabled = false;
                CancelCalibrate.BackColor = Color.Silver;//放弃
                CancelCalibrate.Enabled = false;
                ClearTotal.BackColor = Color.LimeGreen;//累计量清零
                ClearTotal.Enabled = true;
            }
            else
            {
                startZeroBtn.BackColor = Color.Silver;//开始
                ConfirmCalibrate.BackColor = Color.LimeGreen;//确认
                ConfirmCalibrate.Enabled = true;
                CancelCalibrate.BackColor = Color.LimeGreen;//放弃
                CancelCalibrate.Enabled = true;
                ClearTotal.BackColor = Color.Silver;//累计
                ClearTotal.Enabled = true;
                ClearTotal.BackColor = Color.Silver;//累计
                ClearTotal.Enabled = false;
            }

        }

        private void startZeroBtn_1_EnabledChanged(object sender, EventArgs e)
        {
            if (startZeroBtn_1.Enabled == true)//开始校零为true时
            {
                startZeroBtn_1.BackColor = Color.LimeGreen;//开始
                ConfirmCalibrate_1.BackColor = Color.Silver;//确认
                ConfirmCalibrate_1.Enabled = false;
                CancelCalibrate_1.BackColor = Color.Silver;//放弃
                CancelCalibrate_1.Enabled = false;
                ClearTotal_1.BackColor = Color.LimeGreen;//累计
                ClearTotal_1.Enabled = false;
                ClearTotal_1.BackColor = Color.LimeGreen;//累计
                ClearTotal_1.Enabled = true;
            }
            else
            {
                startZeroBtn_1.BackColor = Color.Silver;//开始
                ConfirmCalibrate_1.BackColor = Color.LimeGreen;//确认
                ConfirmCalibrate_1.Enabled = true;
                CancelCalibrate_1.BackColor = Color.LimeGreen;//放弃
                CancelCalibrate_1.Enabled = true;
                ClearTotal_1.BackColor = Color.Silver;//累计
                ClearTotal_1.Enabled = true;
                ClearTotal_1.BackColor = Color.Silver;//累计
                ClearTotal_1.Enabled = false;
            }
        }
        //查找moxaip
        private Boolean findMoxa()
        {
            MeterBaseScalePointService monitorService = new MeterBaseScalePointService();
            RESTfulResult<List<MeterBaseScalePoint>> rmMonitor = monitorService.doQueryWf(new MeterBaseScalePoint { validFlag = "1", baseSpotNo = sPointNo });
            if (rmMonitor.Succeed)
            {
                scalePoints = rmMonitor.Data;
                return true;
            }
            else
            {
                l.WriteLog(22, "获取仪表ip失败" + rmMonitor.Message);
                return false;
            }
        }
        #endregion

        #region   采集赋值
        protected delegate void WeightChangeDelegate(MeasData measData);
        private CoreStrapMeas _strapMeter1 = null;
        private CoreStrapMeas _strapMeter2 = null;
        public double _curTotalWeight1 = 0;//当前累计量
        public double _curTotalWeight2 = 0;
        public double _startWeight1 = 0;//起始量
        public double _startWeight2 = 0;
        public void OnWeightChanged1(object sender, MeasEventArgs e)
        {

            string aa = this.Name;
            if (!_strapMeter1.IsClose)
            {
                WeightChangeDelegate dlg = new WeightChangeDelegate(WeightChange1);
                Invoke(dlg, e.Value);
            }


        }
        public void OnWeightChanged2(object sender, MeasEventArgs e)
        {

            if (!_strapMeter1.IsClose)
            {
                string aa = this.Name;
                WeightChangeDelegate dlg = new WeightChangeDelegate(WeightChange2);
                Invoke(dlg, e.Value);
            }

        }
        private void InitScaleInfo(string measaddr1, string measaddr2)
        {
            string meastype1 = "SA600";
            string meastype2 = "SA600";
            if (!string.IsNullOrEmpty(meastype1) && !string.IsNullOrEmpty(measaddr1))
            {
                _strapMeter1 = new CoreStrapMeas(ConvertMeasType(meastype1));
                _strapMeter1.onMeasChanged += new MeasChangedEventHandler(OnWeightChanged1);
                if (!_strapMeter1.Open(measaddr1))
                {
                    MessageBox.Show("A秤打开失败，请检查仪表连接！");
                    l.WriteLog(22, "A秤打开失败，请检查仪表连接！");
                    return;
                }
            }
            if (!string.IsNullOrEmpty(meastype2) && !string.IsNullOrEmpty(measaddr2))
            {
                _strapMeter2 = new CoreStrapMeas(ConvertMeasType(meastype2));
                _strapMeter2.onMeasChanged += new MeasChangedEventHandler(OnWeightChanged2);
                if (!_strapMeter2.Open(measaddr2))
                {

                    MessageBox.Show("B秤打开失败，请检查仪表连接！");
                    l.WriteLog(22, "B秤打开失败，请检查仪表连接！");
                    return;
                }
            }
        }
        public void WeightChange1(MeasData measData)
        {
            try
            {
            }
            catch (Exception ex)
            {
                MessageBox.Show("异常" + ex.Message);
                return;
            }
        }
        public void WeightChange2(MeasData measData)
        {
            try
            {
            }
            catch (Exception ex)
            {
                MessageBox.Show("异常" + ex.Message);
                return;
            }
        }

        private StrapMeasType ConvertMeasType(string measTypeStr)
        {
            return StrapMeasType.SA600;
        }
        #endregion

        #region 校零赋值
        private delegate void TimerDelegate();
        //A 校零定时器
        private void timer3_Tick(object sender, EventArgs e)
        {
            Thread thread = new Thread(new ThreadStart(Calibrate1_TickDelegate));
            thread.Start();
        }
        //B 校零定时器
        private void timer4_Tick(object sender, EventArgs e)
        {
            Thread thread = new Thread(new ThreadStart(Calibrate1_TickDelegate1));
            thread.Start();
        }
        private void Calibrate1_TickDelegate()
        {
            TimerDelegate td = new TimerDelegate(Calibrate1_Tick);
            Invoke(td);
        }
        private void Calibrate1_TickDelegate1()
        {
            TimerDelegate td = new TimerDelegate(Calibrate1_Tick1);
            Invoke(td);
        }
        private void Calibrate1_Tick()
        {
            CalibrateData[] cbDatas =_strapMeter1.FreshCalibrateData();
            if (cbDatas != null)
            {
                for (int i = 0; i < cbDatas.Length; i++)
                {
                    CalibrateChanged(cbDatas[i], "A");
                }
            }
        }
        private void Calibrate1_Tick1()
        {
            CalibrateData[] cbDatas = _strapMeter1.FreshCalibrateData();
            if (cbDatas != null)
            {
                for (int i = 0; i < cbDatas.Length; i++)
                {
                    CalibrateChanged(cbDatas[i], "B");
                }
            }
        }

        public void CalibrateChanged(CalibrateData cbData, String weightType)
        {
            if (cbData == null) return;

            switch (weightType)
            {
                case "A":
                    beltlengthTxt.Text = Math.Round(cbData.MeasLength, 3).ToString();//带长
                    maxnumTxt.Text = Math.Round(cbData.MaxValue, 3).ToString();//最大值
                    minnumTxt.Text = Math.Round(cbData.MinValue, 3).ToString();//最小值
                   // oldzeroTxt.Text = Math.Round(cbData.OldZero, 3).ToString();//旧零点
                    newnumTxt.Text = Math.Round(cbData.NewZero, 5).ToString();//新零点
                    remaining_timeTxt.Text = cbData.RemainSeconds.ToString();//剩余时间
                    if (cbData.DevStatus)
                    {
                        timer3.Stop();
                        ConfirmCalibrate.Enabled = true; //确认校零
                    }
                    break;
                case "B":
                    beltlengthTxt_1.Text = Math.Round(cbData.MeasLength, 3).ToString();//带长
                    maxnumTxt_1.Text = Math.Round(cbData.MaxValue, 3).ToString();//最大值
                    minnumTxt_1.Text = Math.Round(cbData.MinValue, 3).ToString();//最小值
                    //oldzeroTxt_1.Text = Math.Round(cbData.OldZero, 3).ToString();//旧零点
                    newnumTxt_1.Text = Math.Round(cbData.NewZero, 5).ToString();//新零点
                    remaining_timeTxt_1.Text = cbData.RemainSeconds.ToString();//剩余时间
                    if (cbData.DevStatus)
                    {
                        timer4.Stop();
                        ConfirmCalibrate_1.Enabled = true;
                    }
                    break;
            }
        }
        //开始校零
        private void startZeroBtn_Click(object sender, EventArgs e)
        {
            //if (startMerterBtn.Enabled==false) {
            //    MessageBox.Show("计量中不允许校零！");
            //    return;
            //}
            string oldzero = FindScaleZero("A");
            if (oldzero == "500" || oldzero == "600")
            {
                oldzero = "";
                MessageBox.Show("A秤查询旧零点出错或者是没查到");
            }
            //根据计量点查找最后的零点
            oldzeroTxt.Text = oldzero;
            if (predictionNoTxt.Text == "")
            {
                MessageBox.Show("预报不能为空，请选择预报后再校零。");
                return;
            }
            if (_strapMeter1 != null)
            {
                _strapMeter1.StartCalibrateZero();
                timer3.Start();
                startZeroBtn.Enabled = false;//开始校零后禁用【开始校零】按钮
                IsXiaolingA = true;
            }
        }
        //B开始校零
        private void button8_Click(object sender, EventArgs e)
        {
            //if (startMerterBtn_1.Enabled == false)
            //{
            //    MessageBox.Show("计量中不允许校零！");
            //    return;
            //}
            string oldzero = FindScaleZero("B");
            if (oldzero == "500")
            {
                oldzero = "";
                MessageBox.Show("B秤查询旧零点出错或者是没查到！");
            }
            //根据计量点查找最后的零点
            oldzeroTxt_1.Text = oldzero;
            if (predictionNoTxt.Text == "")
            {
                MessageBox.Show("预报不能为空，请选择预报后再校零。");
                return;
            }
            if (_strapMeter2 != null)
            {
                _strapMeter2.StartCalibrateZero();
                timer4.Start();
                startZeroBtn_1.Enabled = false;
                IsXiaolingB = true;
            }
        }
        private string FindScaleZero(string ScaleName)
        {
            CommonPage<MeterWorkBeltXiaopi> cp = new CommonPage<MeterWorkBeltXiaopi>();
            MeterWorkBeltXiaopi beltXiaopi = new MeterWorkBeltXiaopi();
            beltXiaopi.baseSpotNo = sPointNo;//计量点编码
            beltXiaopi.scaleName = ScaleName;//秤体
            cp.memo1 = "2";//查询旧零点
            cp.param = beltXiaopi;
            RESTfulResult<List<MeterWorkBeltXiaopi>> result = workBeltXiaopiService.doQueryWf(cp);
            if (result.Succeed)
            {
                if (result.Data != null && result.Data.Count > 0)
                {
                    return result.Data[0].newZero.ToString();
                }
                else
                {
                    return "500";
                }
            }
            return "500";
        }

        //确认校零
        private void button6_Click(object sender, EventArgs e)
        {
            _strapMeter1.ConfirmCalibrateValue();
            timer3.Stop();//关闭线程
            startZeroBtn.Enabled = true;

            xiaopi("A");
            IsXiaolingA = false;

        }
        //确认校零B
        private void ConfirmCalibrate_1_Click(object sender, EventArgs e)
        {
            _strapMeter2.ConfirmCalibrateValue();
            timer4.Stop();
            startZeroBtn_1.Enabled = true;

            xiaopi("B");
            IsXiaolingB = false;
        }
        //放弃校零
        private void button4_Click(object sender, EventArgs e)
        {
            _strapMeter1.CancelCalibrateZero();
            timer3.Stop();
            startZeroBtn.Enabled = true;
            IsXiaolingA = false;
            beltlengthTxt.Text = "";//带长
            maxnumTxt.Text = "";//最大值
            minnumTxt.Text = "";//最小值
            oldzeroTxt.Text = "";//旧零点
            newnumTxt.Text = "";//新零点
            remaining_timeTxt.Text = "";//剩余时间
        }
        //放弃校零B
        private void CancelCalibrate_1_Click(object sender, EventArgs e)
        {
            _strapMeter2.CancelCalibrateZero();
            timer4.Stop();
            startZeroBtn_1.Enabled = true;
            IsXiaolingB = false;
            beltlengthTxt_1.Text = "";//带长
            maxnumTxt_1.Text = "";//最大值
            minnumTxt_1.Text = "";//最小值
            oldzeroTxt_1.Text = "";//旧零点
            newnumTxt_1.Text = "";//新零点
            remaining_timeTxt_1.Text = "";//剩余时间
        }
        public void xiaopi(string ScaleName)
        {
            // 校皮：预报、时间、ScaleName 、计量点编码、计量点名称、新零点、物料
            MeterWorkBeltXiaopi beltXiaopi = new MeterWorkBeltXiaopi();
            beltXiaopi.predictionNo = predictionNoTxt.Text;//预报编号
            if (ScaleName == "A")
            {
                beltXiaopi.newZero = newnumTxt.Text.ToString().Trim() == "" ? 0 : Convert.ToDouble(newnumTxt.Text.ToString());
            }
            else if (ScaleName == "B")
            {
                beltXiaopi.newZero = newnumTxt_1.Text.ToString() == "" ? 0 : Convert.ToDouble(newnumTxt_1.Text.ToString());
            }
            if (beltXiaopi.newZero == 0)
            {
                MessageBox.Show("新零点为空，校零失败！");
                return;
            }
            beltXiaopi.baseSpotNo = sPointNo;//计量点编码
            beltXiaopi.baseSpotName = sPointName;//计量点
            beltXiaopi.productNo = beltinfo.productNo;//物料编码
            beltXiaopi.productName = mat_nameTxt.Text;//物料名称
            beltXiaopi.createManNo = sUserId;//用户id
            beltXiaopi.createManName = sUserName;//用户名称
            beltXiaopi.scaleName = ScaleName;//秤体
            RESTfulResult<string> rm = workBeltXiaopiService.doAddWf(beltXiaopi);
            if (rm.Succeed)
            {
                if ((!label36.Text.Contains("为校秤状态") && ScaleName == "A") || (!label37.Text.Contains("为校秤状态") && ScaleName == "B"))
                {
                    MessageBox.Show(ScaleName + "秤确认校零成功！");
                }
                else
                {
                    MessageBox.Show("请注意"+ScaleName + "秤红色提示是否还在确认是否校零成功！");
                }
                return;
            }
            else
            {
                MessageBox.Show("计量失败，请联系技术中心！");
                l.WriteLog(22, "计量失败" + rm.Message);
                return;
            }
        }
        //累计量清零
        private void ClearTotal_Click(object sender, EventArgs e)
        {
            try
            {
                if (startMerterBtn.Enabled == true && endMerterBtn.Enabled == false)
                {
                    if (_strapMeter1 != null && MessageBox.Show("是否确定清零？", sPointName + " A秤", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {

                        startZeroBtn.Enabled = false;
                        _strapMeter1.ClearTotal();
                        startZeroBtn.Enabled = true;
                    }
                }
                else
                {
                    MessageBox.Show("此船未结束，不允许清零！");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("累积量清零" + ex.Message);
                l.WriteLog(22, "累积量清零" + ex.Message);
            }
        }
        //累计量清零 B
        private void ClearTotal_1_Click(object sender, EventArgs e)
        {
            try
            {
                if (startMerterBtn_1.Enabled == true && endMerterBtn_1.Enabled == false)
                {
                    if (_strapMeter2 != null && MessageBox.Show("是否确定清零？", sPointName + " B秤", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        ClearTotal_1.Enabled = false;
                        _strapMeter2.ClearTotal();
                        ClearTotal_1.Enabled = true;
                    }
                }
                else
                {
                    MessageBox.Show("此船未结束，不允许清零！");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("累积量清零" + ex.Message);
                l.WriteLog(22, "累积量清零" + ex.Message);
            }
        }
        //显示差值
        private void remaining_timeTxt_TextChanged(object sender, EventArgs e)
        {
            if (remaining_timeTxt.Text.Trim() == "0" && newnumTxt.Text.Trim() != "" && oldzeroTxt.Text.Trim() != "")
            {
                differenceTxt.Text = (Math.Round(Convert.ToDouble(newnumTxt.Text.Trim()), 6) - Math.Round(Convert.ToDouble(oldzeroTxt.Text.Trim()), 6)).ToString("0.00000");

            }
        }
        private void remaining_timeTxt_1_TextChanged(object sender, EventArgs e)
        {
            if (remaining_timeTxt_1.Text.Trim() == "0" && newnumTxt_1.Text.Trim() != "" && oldzeroTxt_1.Text.Trim() != "")
            {
                differenceTxt_1.Text = (Math.Round(Convert.ToDouble(newnumTxt_1.Text.Trim()), 6) - Math.Round(Convert.ToDouble(oldzeroTxt_1.Text.Trim()), 6)).ToString("0.00000");

            }
        }

        #endregion


        #region 修改仪表物料参数
        private void updateMatParameter(string parameter, string ScaleName)
        {// (10)21003   (16)520b
            int pm = Convert.ToInt32(Convert.ToDouble(parameter) * 10000);
            byte[] C = intToBytes2(pm);
            byte[] pmBytes = new byte[2];
            pmBytes[0] = C[2];
            pmBytes[1] = C[3];
            switch (ScaleName)
            {
                case "A":
                    Addlog(getTedValue("parameter_Ted").ToString(), parameter, ScaleName, predictionNoTxt.Text.ToString());
                    _strapMeter1.setMatParameter(pmBytes);
                    break;
                case "B":
                    Addlog(getTedValue("parameter_Ted_1").ToString(), parameter, ScaleName, predictionNoTxt.Text.ToString());
                    _strapMeter2.setMatParameter(pmBytes);
                    break;
            }

        }
        public void Addlog(string materialParameter_old, string materialParameter_new, string scaleName, string preNo)
        {
            MeterBaseOperationLog log = new MeterBaseOperationLog();
            log.operationId = preNo;
            log.operationPage = "仪表参数";
            log.operationFunction = "修改";
            log.operationBeforeFix = "-计量点:" + sPointName + "-秤台:" + scaleName + "仪表参数：" + materialParameter_old;
            log.operationAfterFix = "-计量点:" + sPointName + "-秤台:" + scaleName + "仪表参数：" + materialParameter_new;
            log.logType = "皮带秤";
            log.logTypeCode = "001002005";
            log.createManNo = sUserId;
            log.createManName = sUserName;
            RESTfulResult<string> rESTfulResult = LogService.AddLog(log);
            if (!rESTfulResult.Succeed)
            {
                MessageBox.Show("新增日志错误" + rESTfulResult.Message);
                return;
            }
        }
        public static byte[] intToBytes2(int value)
        {
            byte[] src = new byte[4];
            src[0] = (byte)((value >> 24) & 0xFF);
            src[1] = (byte)((value >> 16) & 0xFF);
            src[2] = (byte)((value >> 8) & 0xFF);
            src[3] = (byte)(value & 0xFF);
            return src;
        }
        #endregion

        #region  按钮事件  计量
        //返回按钮
        private void checkBtn_Click(object sender, EventArgs e)
        {
            if (IsXiaolingA == true|| IsXiaolingB == true) {
                MessageBox.Show("在查看控件校零时不能返回！");
                return;
            }
            if (_strapMeter1 != null)
            {
                _strapMeter1.Close();
            }
            if (_strapMeter2 != null)
            {
                _strapMeter2.Close();
            }
            //if (this.startMerterBtn.Enabled == false && this.startMerterBtn_1.Enabled == false)
            //{
            //    BtnType = 9;//都在计量
            //}
            //if (startMerterBtn.Enabled == false && startMerterBtn_1.Enabled == true)
            //{
            //    BtnType = 1;//A开始计量
            //}
            //if (startMerterBtn.Enabled == true && startMerterBtn_1.Enabled == false)
            //{
            //    BtnType = 2;//B开始计量
            //}
            //if (this.startMerterBtn.Enabled == true && this.startMerterBtn_1.Enabled == true)
            //{
            //    BtnType = 0;//未计量
            //}
            //退出监控
            NETClient.Logout(_LoginID);
            NETClient.Logout(_LoginID1);
            NETClient.Logout(_LoginID2);
            _LoginID = IntPtr.Zero;
            _LoginID1 = IntPtr.Zero;
            _LoginID2 = IntPtr.Zero;
            //  _AttachID = IntPtr.Zero;
            _PlayID = IntPtr.Zero;
            this.pictureBox1.Refresh();
            this.pictureBox2.Refresh();
            this.pictureBox3.Refresh();
            this.timer1.Stop();
            this.timer2.Stop();
            timer3.Stop();
            timer4.Stop();

            Close();
            Dispose();
        }

        private void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                ShowPictureBox sp = new ShowPictureBox(_PlayID,_LoginID);
                sp.Name = "P1";
                SetShowWin(sp);
            }
            catch { }
        }
        private void pictureBox2_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                ShowPictureBox sp = new ShowPictureBox(_PlayID, _LoginID1);
                sp.Name = "P2";
                SetShowWin(sp);
            }
            catch { }

        }

        private void pictureBox3_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                ShowPictureBox sp = new ShowPictureBox(_PlayID, _LoginID2);
                sp.Name = "P3";
                SetShowWin(sp);
            }
            catch { }

        }
        private Form tempForm_ = null;
        private void SetShowWin(Form form1)
        {
            try
            {
                Form temp_ = null;
                if (tempForm_ != null) temp_ = Application.OpenForms[tempForm_.Name];
                if (temp_ == null)
                {
                    tempForm_ = null;
                    tempForm_ = form1;
                    tempForm_.Show();
                }
                else
                {
                    temp_.Activate();
                    temp_.WindowState = FormWindowState.Normal;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        //刷新
        private void flashBtn_Click(object sender, EventArgs e)
        {
            loadFrom();
        }
        //A开始计量
        private void startMerterBtn_Click(object sender, EventArgs e)
        {
            string message = checkStartSave("A");
            if (message != "200")
            {
                MessageBox.Show(message);
                return;
            }

            StartMeter("A", 1);
        }
        //B开始计量
        private void button11_Click(object sender, EventArgs e)
        {
            string message = checkStartSave("B");
            if (message != "200")
            {
                MessageBox.Show(message);
                return;
            }

            StartMeter("B", 2);
        }
        //开始计量之前的效验
        private string checkStartSave(string ScaleName)
        {
            if (predictionNoTxt.Text == "")
            {
                return "请选择预报在进行计量！";
            }
            else if (predictionNoTxt.Text.ToString() != beltinfo.predictionNo)
            {
                return "核对预报是否错误！";
            }
            if (mat_nameTxt.Text.ToString().Trim() == "" || shippingTxt.Text.ToString().Trim() == "" || receivingTxt.Text.ToString().Trim() == "")
            {
                return "物料名称、收发货单位不能为空!";
            }
            if (getTedValue("instrument_weight_Ted") != 0 && ScaleName == "A")
            {
                return ScaleName + "仪表不为0时不能开始计量！";
            }
            if (getTedValue("instrument_weight_Ted_1") != 0 && ScaleName == "B")
            {
                return ScaleName + "仪表不为0时不能开始计量！";
            }

            if (MeterWorkBeltActual_NOW != null && MeterWorkBeltActual_NOW.Data != null)
            {
                if (MeterWorkBeltActual_NOW.Data.Count == 1)
                {
                    if (MeterWorkBeltActual_NOW.Data[0].scaleName == ScaleName && MeterWorkBeltActual_NOW.Data[0].predictionNo == predictionNoTxt.Text.ToString() && MeterWorkBeltActual_NOW.Data[0].endTime != null)
                    {
                        return "预报" + predictionNoTxt.Text.ToString() + "----" + ScaleName + "秤已计量！请勿重复计量！";
                    }
                }
            }
            bool IsHaveUse = false;
            for (int i = 1; i < ultraGrid1.Rows.Count; i++)
            {
                string value = ultraGrid1.Rows[i].Cells["valueFlag"].Text.ToString();
                if (value.Contains("0") || value.Contains("使用中"))
                {
                    IsHaveUse = true;
                }
            }
            if (IsHaveUse)
            {
                return "存在未完成计量的预报，请双击该预报结束计量或者找计量班长作废该预报！";
            }
            return "200";
        }
        //结束计量之前的效验
        private string checkEndSave(string ScaleName)
        {
            //if (getTedValue("instrument_weight_Ted") == 0 && ScaleName == "A")
            //{
            //    return ScaleName + "仪表为0时不能结束计量！";
            //}
            //if (getTedValue("instrument_weight_Ted_1") == 0  && ScaleName == "B")
            //{
            //    return ScaleName + "仪表为0时不能结束计量！";
            //}
            if (predictionNoTxt.Text == "")
            {
                return "预报为空，不能结束";
            }
            else if (predictionNoTxt.Text.ToString() != beltinfo.predictionNo)
            {
                return "核对预报是否错误！";
            }

            return "200";
        }

        //开始计量
        private void StartMeter(string ScaleName, int controlId)
        {
            MeterWorkBeltActual beltActual = new MeterWorkBeltActual();
            beltActual.predictionNo = predictionNoTxt.Text;//预报编号
            if (ScaleName == "A")
            {
                beltActual.startWeight = getTedValue("instrument_weight_Ted");
            }
            else if (ScaleName == "B")
            {
                beltActual.startWeight = getTedValue("instrument_weight_Ted_1");
            }
            // beltActual.startTime = DateTime.Now.ToString();
            beltActual.baseSpotNo = sPointNo;//计量点编码
            beltActual.baseSpotName = sPointName;//计量点
            beltActual.forwardingUnitNo = beltinfo.forwardingUnitNo;//发货单位编码
            beltActual.newSupplier = shippingTxt.Text;//发货单位
            beltActual.receivingUintNo = beltinfo.receivingUintNo;//收货单位编码
            beltActual.receivingUintName = receivingTxt.Text;//收货单位
            beltActual.productNo = beltinfo.productNo;//物料编码
            beltActual.newMatName = mat_nameTxt.Text;//物料名称
            beltActual.createManNo = sUserId;//用户id
            beltActual.createManName = sUserName;//用户名称
            beltActual.meterClass = userClass;//班级班组
            beltActual.meterGroup = userGroup;
            beltActual.scaleName = ScaleName;//秤体
            beltActual.heatNo = "1";//表示为开始计量的创建
            RESTfulResult<string> rm = MeterWorkBeltActualService.doAddWf(beltActual);
            if (rm.Succeed)
            {
                UpdateControl(controlId);
                loadFrom();
            }
            else
            {
                MessageBox.Show("计量失败，请联系技术中心！");
                l.WriteLog(22, "计量失败" + rm.Message);
            }
        }
        //A结束计量
        private void endMerterBtn_Click(object sender, EventArgs e)
        {
            string message = checkEndSave("A");
            if (message != "200")
            {
                MessageBox.Show(message);
                return;
            }
            EndMerter("A", 3);
        }
        //B结束计量
        private void endMerterBtn_1_Click(object sender, EventArgs e)
        {
            string message = checkEndSave("B");
            if (message != "200")
            {
                MessageBox.Show(message);
                return;
            }
            EndMerter("B", 4);
        }
        //结束计量
        private void EndMerter(string ScaleName, int controlId)
        {
            CommonPage<MeterWorkBeltActual> cp = new CommonPage<MeterWorkBeltActual>();
            cp.param = new MeterWorkBeltActual { valueFlag = "1", baseSpotNo = sPointNo, scaleName = ScaleName, predictionNo = predictionNoTxt.Text.ToString() };
            RESTfulResult<List<MeterWorkBeltActual>> rms = MeterWorkBeltActualService.doQuery(cp.param);
            if (!rms.Succeed)
            {
                MessageBox.Show("查找原有预报失败，请联系技术中心！");
                l.WriteLog(22, "计量失败" + rms.Message);
                return;
            }
            MeterWorkBeltActual beltActual = new MeterWorkBeltActual();
            if (ScaleName == "A")
            {
                beltActual.endWeight = getTedValue("instrument_weight_Ted");
            }
            else if (ScaleName == "B")
            {
                beltActual.endWeight = getTedValue("instrument_weight_Ted_1");
            }
            beltActual.startWeight = rms.Data[0].startWeight;
            beltActual.actualNo = rms.Data[0].actualNo;
            beltActual.predictionNo = predictionNoTxt.Text;//预报编号
            beltActual.updateManNo = sUserId;
            beltActual.updateManName = sUserName;
            RESTfulResult<string> rm = MeterWorkBeltActualService.endMeter(beltActual);
            if (rm.Succeed)
            {
                UpdateControl(controlId);
                if (ScaleName == "A")
                {
                    IsSaveA = false;
                    _startWeight1 = 0;
                    setTedValue("cumulative_weight_Ted", "0");//累计量
                }
                else
                {
                    IsSaveB = false;
                    _startWeight2 = 0;
                    setTedValue("cumulative_weight_Ted_1", "0");//累计量
                }
                loadFrom();
            }
            else
            {
                MessageBox.Show("计量失败，请联系技术中心！");
                _startWeight1 = getTedValue("cumulative_weight_Ted");
                _startWeight2 = getTedValue("cumulative_weight_Ted_1");
                l.WriteLog(22, "计量失败" + rm.Message);
                return;
            }


        }


        #endregion
    }

}