using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Common;
using com.hnshituo.core.webapp.vo;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win.UltraWinEditors;
using System.Threading;
using Infragistics.Win;
using iCore.Rtdb.RtdbTable;
using System.Text.RegularExpressions;
using JC_MeasuringSystem;

namespace BeltScaleSystem
{


    public partial class BeltScaleMeterControl : UserControl
    {
        public BeltScaleMeterControl()
        {
            InitializeComponent();
            this.DoubleBuffered = true;//设置本窗体
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲
            SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
            UpdateStyles();
        }

        #region  自定义变量
        PreBeltScalePreService PreBeltScalePreService = new PreBeltScalePreService();//预报服务
        MeterWorkBeltActualService MeterWorkBeltActualService = new MeterWorkBeltActualService();//实绩服务
        public  PreBeltScaleForecast beltinfo = new PreBeltScaleForecast();//预报实体
        MeterWorkBeltTiminginfo beltTiminginfo = new MeterWorkBeltTiminginfo();//定时数据实体
        MeterWorkBeltTiminginfo beltTiminginfo1 = new MeterWorkBeltTiminginfo();//定时数据实体
        MeterWorkBeltTimingService meterWorkBeltTimingService = new MeterWorkBeltTimingService();//定时数据接口
        private MeterWorkBeltXiaopiService workBeltXiaopiService = new MeterWorkBeltXiaopiService();//校皮数据接口
        MeterBaseBeltMaterialpmService baseBeltMaterialpmService = new MeterBaseBeltMaterialpmService();//物料系数服务
     //   public Boolean IsXiaolingA = false, IsXiaolingB = false;//是否校零
        FrmMaxBletScale maxscale = null;
        public int BtnType = 0;
        private Log l = Log.GetInstance(); //日志
        List<MeterBaseScalePoint> scalePoints = new List<MeterBaseScalePoint>();//计量点监控数据 目前采用仪表ip
        /// <summary>
        /// 计量点信息
        /// </summary>
        public string sPointNo = "", sPointName = "";
        /// <summary>
        /// 登录人及登陆IP信息
        /// </summary>
        public string sUserId = "", sUserName = "", sIpAddress = "", userClass = "", userGroup = "";
        /// <summary>
        /// 物料参数
        /// </summary>
        public string materialParameter = "", materialParameterB= "", materialParameterImport="", materialParameterImportB="";
        public string oldMat = "";
        private Boolean IsSaveA=false, IsSaveB=false;
        private Boolean Isfrist=true;//第一次进入
        public static Boolean IsMaxBelt = false;//是否为放大
        private delegate void UpdateUIEventHander(object sender, UpdateUIArgs args); //自定义事件用来从线程中更新控件的值
        RESTfulResult<List<MeterWorkBeltActual>> MeterWorkBeltActual_NOW = null;//当前计量的实绩
        MeterBaseOperationLogService LogService = new MeterBaseOperationLogService();//日志服务
        #endregion

        #region 公共方法
        private void BeltScaleMeterControl_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();//初始化流量曲线
            this.timer1.Start();//流量曲线
            realtime.Start();//实时量采集
            timer2.Start();//定时数据
            Isfrist = false;
        }
        /// <summary>
        /// 解决窗体较多 加载慢的问题
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }
        //更新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;
            }
        }
        //填充窗口表单
        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;
            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("皮带秤计量异常_", "获取仪表ip失败" + rmMonitor.Message);
                return false;
            }
        }
        //字符串分割  用于物料系数  目前没用到
        static string[] strProcess(string str)
        {
            string strProcessed;
            string pass = @"[\t\r\n\s]";
            strProcessed = Regex.Replace(str, pass, "");  //去掉、回车、换行、空格
            int strLength = strProcessed.Length;          //统计经处理后的字符长度
                                                          //判断待处理的字符串长度是否符合要求，并给出提示
            if (strLength % 2 != 0)
            {
                int absenceNum = 2 - strLength % 2;
                string notification = $"注意：请物料系数是否正确！\r\n[提示：数据似乎缺少{absenceNum}位数字数符]";
                MessageBox.Show(notification, "Tips", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            int byteLength = strProcessed.Length / 2;       //统计分割后字符数组长度，数组中每个元素长度为四个字节
            string[] strArrayH = new string[byteLength];    //存放字符串
                                                            //将字符串分割为长度为2的字符数组
            for (int i = 0; i < (byteLength); i = i + 1)
            {
                try
                {
                    strArrayH[i] = strProcessed.Substring(2 * i, 2);//i-起始位置，4-子串长度
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString(), "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    continue;
                }
            }
            return strArrayH;
        }
        //限制不允许输入汉字和特殊字符
        private void A_mat_KeyPress(object sender, KeyPressEventArgs e)
        {
            int keyValue = (int)e.KeyChar;
            if ((keyValue >= 48 && keyValue <= 57) || keyValue == 8 || keyValue == 46)
            {
                if (sender != null && sender is TextBox && keyValue == 46)
                {
                    if (((TextBox)sender).Text.IndexOf(".") >= 0)
                        e.Handled = true;
                    else
                        e.Handled = false;
                }
                else
                    e.Handled = false;
            }
            else
                e.Handled = true;
        }

        private void B_mat_KeyPress(object sender, KeyPressEventArgs e)
        {
            int keyValue = (int)e.KeyChar;
            if ((keyValue >= 48 && keyValue <= 57) || keyValue == 8 || keyValue == 46)
            {
                if (sender != null && sender is TextBox && keyValue == 46)
                {
                    if (((TextBox)sender).Text.IndexOf(".") >= 0)
                        e.Handled = true;
                    else
                        e.Handled = false;
                }
                else
                    e.Handled = false;
            }
            else
                e.Handled = true;
        }

        #endregion


        #region    表格查询相关
        /// <summary>
        /// 预报查询接口
        /// </summary>
        private void queryScale(Boolean IsDoubleClik=true)
        {
            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.AddHours(1).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;
                                if (IsDoubleClik) { 
                                    ultraGrid1_DoubleClickRow_Check(ugr);
                                }
                            }
                        }
                        ClsControlPack.RefreshAndAutoSize(ultraGrid1);
                    }
                    else
                    {
                        ClearFromInfo();
                        dtScaleTable.Clear();
                        ClsControlPack.CopyDataToDatatable(ref dtScaleTable, ref dataTable1, true);
                        ClsControlPack.RefreshAndAutoSize(ultraGrid1);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }
        /// <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);
                        foreach (UltraGridRow ugr in ultraGrid2.Rows)
                        {
                            ugr.Cells["weightDiff"].Value = ugr.Cells["weightDiff"].Value.ToString() + "%";
                            
                        }
                    }
                    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 ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }
        /// <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) {
            try { 
                //重置物料系数
                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();   //物料名称
                    if (oldMat!= mat_nameTxt.Text.ToString()) { 
                        oldMat = mat_nameTxt.Text.ToString();//赋值旧物料
                    }
                    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.newMatClass = ugr.Cells["newMatClass"].Text.Trim();//获取物料类别
                    beltinfo.baseSpotNo = sPointNo;
                    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("进口"))
                        {
                            if (materialParameterImport != getTedValue("parameter_Ted").ToString())
                            {
                               // megA.Text = "物料参数:进口" + materialParameterImport;
                                if (MessageBox.Show("物料参数不一致，是否更改物料参数？", sPointName + " A秤", MessageBoxButtons.YesNo) == DialogResult.Yes)//如果点击“确定”按钮
                                {
                                    updateMatParameter(materialParameterImport, "A");
                                    IsUpdateMatPm = true;
                                }
                            }

                        }
                        if (materialParameter != ""&& !beltinfo.newMatClass.Contains("进口"))
                        {
                            if (materialParameter != getTedValue("parameter_Ted").ToString())
                            {
                               //  megA.Text = "物料参数:国内" + materialParameter;
                                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 != "")
                        {
                            //根据进口或者非进口的来修改物料参数
                            if ( materialParameterImportB != getTedValue("parameter_Ted_1").ToString())
                            {
                               // megB.Text = "物料参数：进口" + materialParameterImportB;
                                if (MessageBox.Show("物料参数不一致，是否更改物料参数？", sPointName + " B秤", MessageBoxButtons.YesNo) == DialogResult.Yes)//如果点击“确定”按钮
                                {
                                    updateMatParameter(materialParameterImportB, "B");
                                    IsUpdateMatPm = true;
                                }
                            }

                        }
                        if (!beltinfo.newMatClass.Contains("进口") && materialParameterB != "")
                        {
                            if ( materialParameterB != getTedValue("parameter_Ted_1").ToString())
                            {
                                //megB.Text = "物料参数：国内" + materialParameterB ;
                                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;
                            }
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }

        }
        //根据预报编码查询实绩
        private void findActualById(string predictionNo) {
            try { 
                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);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }
        /// <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 ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }
        #endregion

        #region   采集赋值
        protected delegate void WeightChangeDelegate(MeasData measData);
        private CoreStrapMeas _strapMeter1 = null;
        private CoreStrapMeas _strapMeter2 = null;
        private double _curTotalWeight1 = 0;//当前累计量
        private double _curTotalWeight2 = 0;
        private double _startWeight1 = 0;//起始量
        private 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("皮带秤计量异常_", "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("皮带秤计量异常_", "B秤打开失败，请检查仪表连接！");
                    return;
                }
            }
        }
        public void WeightChange1(MeasData measData)
        {
            try
            {
                setTedValue("instrument_weight_Ted", Math.Round(measData.Total, 2).ToString());//仪表重量 
                if (IsSaveA) { 
                    setTedValue("cumulative_weight_Ted", Math.Round(measData.Total - _startWeight1, 2).ToString());//累计量
                }
                setTedValue("realtime_amount_Ted", Math.Round(measData.Flow, 2).ToString());//实时量
                setTedValue("belt_speed_Ted", Math.Round(measData.BeltSpeed, 2).ToString());//皮带速度
                setTedValue("temperature_Ted", Math.Round(measData.FieldTemp, 2).ToString());//温度
                setTedValue("parameter_Ted", measData.StdValue.ToString());//物料参数
                _curTotalWeight1 = Math.Round(measData.Total, 2);
                label36.Text = measData.IsConnect ? "" : "仪表连接异常，请检查仪表连接状态！";
                if (measData.IsConnect)
                {
                     label36.Text = measData.MeterStatus ? "" : "A仪表为校秤状态！";
                }
                //向查看控件传输
                if (IsMaxBelt  && maxscale != null)
                {
                    maxscale.measDataA = measData;
                    maxscale._curTotalWeight1 = _curTotalWeight1;
                    maxscale._startWeight1 = _startWeight1;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }
        public void WeightChange2(MeasData measData)
        {
            try
            {
                setTedValue("instrument_weight_Ted_1", Math.Round(measData.Total, 2).ToString());//仪表重量 
                if (IsSaveB) { 
                    setTedValue("cumulative_weight_Ted_1", Math.Round(measData.Total - _startWeight2, 2).ToString());//累计量
                }
                setTedValue("realtime_amount_Ted_1", Math.Round(measData.Flow, 2).ToString());//实时量
                setTedValue("belt_speed_Ted_1", Math.Round(measData.BeltSpeed, 2).ToString());//皮带速度
                setTedValue("temperature_Ted_1", Math.Round(measData.FieldTemp, 2).ToString());//温度
                setTedValue("parameter_Ted_1", measData.StdValue.ToString());//物料参数
                _curTotalWeight2 = Math.Round(measData.Total, 2);
                label37.Text = measData.IsConnect ? "" : "仪表连接异常，请检查仪表连接状态！";
                if (measData.IsConnect)
                {
                    label37.Text = measData.MeterStatus ? "" : "B仪表为校秤状态！";
                }
                //向查看控件传输
                if (IsMaxBelt && maxscale != null)
                {
                    maxscale.measDataB = measData;
                    maxscale._curTotalWeight2 = _curTotalWeight2;
                    maxscale._startWeight2 = _startWeight2;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }

        private StrapMeasType ConvertMeasType(string measTypeStr)
        {
            return StrapMeasType.SA600;
        }
        #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 timer1_Tick(object sender, EventArgs e)
        {
            try {
                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);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }
        #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()
        {
            try { 
                CalibrateData[] cbDatas = _strapMeter1.FreshCalibrateData();
                //向查看控件传输
                if (IsMaxBelt && maxscale != null)
                {
                    maxscale.cbDataByControlA = cbDatas;
                    maxscale.StartXiaoLingA = true;

                    maxscale.oldzeroA = oldzeroTxt.Text;
                    maxscale.oldzeroB = oldzeroTxt_1.Text;
                }
                if (cbDatas != null)
                {
                    for (int i = 0; i < cbDatas.Length; i++)
                    {
                        CalibrateChanged(cbDatas[i], "A");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }
        private void Calibrate1_Tick1()
        {
            try
            {
                CalibrateData[] cbDatas = _strapMeter2.FreshCalibrateData();
                //向查看控件传输
                if (IsMaxBelt && maxscale != null)
                {
                    maxscale.cbDataByControlB = cbDatas;
                    maxscale.StartXiaoLingB = true;
                }
                if (cbDatas != null)
                {
                    for (int i = 0; i < cbDatas.Length; i++)
                    {
                        CalibrateChanged(cbDatas[i], "B");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
}

        public void CalibrateChanged(CalibrateData cbData, String weightType)
        {
            try { 
                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;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }
        //开始校零
        private void startZeroBtn_Click(object sender, EventArgs e)
        {
            try { 
                //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;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }
        //B开始校零
        private void button8_Click(object sender, EventArgs e)
        {
            try { 
                //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;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }
        private string FindScaleZero(string ScaleName)
        {
            try
            {
                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";
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
                return "500";
            }
        }

        //确认校零
        private void button6_Click(object sender, EventArgs e)
        {
            try
            {
                _strapMeter1.ConfirmCalibrateValue();
                timer3.Stop();//关闭线程
                startZeroBtn.Enabled = true;
                xiaopi("A");
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
            //IsXiaolingA = false;
        }
        //确认校零B
        private void ConfirmCalibrate_1_Click(object sender, EventArgs e)
        {
            try { 
                _strapMeter2.ConfirmCalibrateValue();
                timer4.Stop();
                startZeroBtn_1.Enabled = true;
                xiaopi("B");
                //IsXiaolingB = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }
        //放弃校零
        private void button4_Click(object sender, EventArgs e)
        {
             try {
                _strapMeter1.CancelCalibrateZero();
                timer3.Stop();
                startZeroBtn.Enabled = true;
              //  IsXiaolingA = false;
                beltlengthTxt.Text = "";//带长
                maxnumTxt.Text = "";//最大值
                minnumTxt.Text = "";//最小值
                oldzeroTxt.Text = "";//旧零点
                newnumTxt.Text = "";//新零点
                remaining_timeTxt.Text = "";//剩余时间
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }
        //放弃校零B
        private void CancelCalibrate_1_Click(object sender, EventArgs e)
        {
            try
            {
                _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 = "";//剩余时间
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }
        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("皮带秤计量异常_", "计量失败"+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("皮带秤计量异常_", "累积量清零" + 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("皮带秤计量异常_", "累积量清零" + 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(),oldMat);
                   _strapMeter1.setMatParameter(pmBytes);
                    break;
                case "B":
                    Addlog(getTedValue("parameter_Ted_1").ToString(), parameter, ScaleName, predictionNoTxt.Text.ToString(),oldMat);
                    _strapMeter2.setMatParameter(pmBytes);
                    break;
            }
           
        }
        public void Addlog(string materialParameter_old, string materialParameter_new, string scaleName, string preNo,string mat)
        {
            MeterBaseOperationLog log = new MeterBaseOperationLog();
            log.operationId = preNo;
            log.operationPage = "仪表参数";
            log.operationFunction = "修改";
            log.operationBeforeFix = "-计量点:" + sPointName + "-秤台:" + scaleName + "物料："+oldMat+"仪表参数：" + materialParameter_old;
            log.operationAfterFix = "-计量点:" + sPointName + "-秤台:" + scaleName + "物料："+mat_nameTxt.Text.ToString()+"仪表参数：" + 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 timer2_Tick(object sender, EventArgs e)
        {
            DateTime dt = System.DateTime.Now;
            if (dt.Minute == 30 || dt.Minute == 0)
            {
                SaveTimingInfo();
            }

        }
        private void SaveTimingInfo() {
            double diff = 0;
            //A磅定时数据
            beltTiminginfo.scaleName = "A";
            beltTiminginfo.weight = getTedValue("instrument_weight_Ted");//仪表重量
            beltTiminginfo.realtimeAmount = getTedValue("realtime_amount_Ted");//实时量
            beltTiminginfo.beltSpeed = getTedValue("belt_speed_Ted");//皮带速度
            beltTiminginfo.predictionNo = predictionNoTxt.Text.ToString();//预报编号
            beltTiminginfo.createManNo = sUserId;//登录信息
            beltTiminginfo.createManName = sUserName;
            beltTiminginfo.meterClass = userClass;
            beltTiminginfo.meterGroup = userGroup;
            beltTiminginfo.productNo = beltinfo.productNo;
            beltTiminginfo.productName = beltinfo.newMatName;
            beltTiminginfo.forwardingUnitNo = beltinfo.forwardingUnitNo;
            beltTiminginfo.forwardingUnitName = beltinfo.newSupplier; ;//发货单位
            beltTiminginfo.receivingUintNo = beltinfo.receivingUintNo; ;//收货单位
            beltTiminginfo.receivingUintName = beltinfo.receivingUintName;
            beltTiminginfo.baseSpotNo = sPointNo;
            beltTiminginfo.baseSpotName = sPointName;
            beltTiminginfo.weightType = "0";
            beltTiminginfo.packageNo = sPointNo + DateTime.Now.ToString("yyyyMMddHHmmss");
            double Aweight = getTedValue("instrument_weight_Ted")==0?1: getTedValue("instrument_weight_Ted");
            diff = getTedValue("instrument_weight_Ted_1") - Aweight;
            beltTiminginfo.difference = diff == 0 ? 0 : Math.Round((diff / Aweight) * 100, 3);
            if (diff != 0)
            {
                double df = (double)beltTiminginfo.difference;
                beltTiminginfo.weightDiff = Math.Round((df / Aweight) * 100,4);
            }
            RESTfulResult<string> rm = null;
            if (IsSaveA)
            {
                l.WriteLog("皮带秤计量异常_", "定时数据" + "Aweight" + Aweight + "---Bweight"+ getTedValue("instrument_weight_Ted_1")+ "---df" + beltTiminginfo.difference + "---weightDiff"+ beltTiminginfo.weightDiff);
                rm = meterWorkBeltTimingService.doAddWf(beltTiminginfo);
                if (rm.Succeed)
                {
                    MeterWorkBeltTiminginfo beltTiminginfos = new MeterWorkBeltTiminginfo();
                    //A磅定时数据
                    beltTiminginfo.scaleName = "B";
                    beltTiminginfo.weight = getTedValue("instrument_weight_Ted_1");//仪表重量
                    beltTiminginfo.realtimeAmount = getTedValue("realtime_amount_Ted_1");//实时量
                    beltTiminginfo.beltSpeed = getTedValue("belt_speed_Ted_1");//皮带速度
                    if (IsSaveB)
                    {
                        rm = meterWorkBeltTimingService.doAddWf(beltTiminginfo);
                    }
                    if (rm.Succeed)
                    {
                        timer2.Interval = 1000 * 60 * 3;
                        //表格更新
                        querytiminginfo();
                    }
                    else
                    {
                        MessageBox.Show("定时计量失败，请联系技术中心！");
                        l.WriteLog("皮带秤计量异常_", "计量失败" + rm.Message);
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("定时计量失败，请联系技术中心！");
                    l.WriteLog("皮带秤计量异常_", "计量失败" + rm.Message);
                    return;
                }
            }
        }
        int zs = 0;//间隔五秒数据没动静则报警
        double csum1 = 0;
        double csum2 = 0;
        //保存实时量
        private void realtime_Tick(object sender, EventArgs e)
        {
            queryScale(false);//每分钟刷新一次预报  不触发更改样式
            if (IsSaveA || IsSaveB) {
                //A实时量
                beltTiminginfo1.scaleName = "A";
                beltTiminginfo1.realtimeAmount = getTedValue("realtime_amount_Ted");//实时量
                beltTiminginfo1.baseSpotNo = sPointNo;
                beltTiminginfo1.baseSpotName = sPointName;
                beltTiminginfo1.weightType = "1";//实时量
                RESTfulResult<string> rm = meterWorkBeltTimingService.doAddWf(beltTiminginfo1);
                if (rm.Succeed)
                {
                    MeterWorkBeltTiminginfo beltTiminginfos = new MeterWorkBeltTiminginfo();
                    //B实时量
                    beltTiminginfo1.scaleName = "B";
                    beltTiminginfo1.realtimeAmount = getTedValue("realtime_amount_Ted_1");//实时量
                    rm = meterWorkBeltTimingService.doAddWf(beltTiminginfo1);
                    if (!rm.Succeed)
                    {
                        MessageBox.Show("保存实时量失败，请联系技术中心！");
                        l.WriteLog("皮带秤计量异常_", "保存实时量失败" + rm.Message);
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("保存实时量失败，请联系技术中心！");
                    l.WriteLog("皮带秤计量异常_", "保存实时量失败" + rm.Message);
                    return;
                }
            }
            zs = zs + 1;
            if (zs == 5)
            {
                if (sPointNo == "00039")//西区焦粉皮带秤
                {
                    if (getTedValue("realtime_amount_Ted_1") > 0 && getTedValue("belt_speed_Ted_1") > 1)
                    {
                        if (getTedValue("instrument_weight_Ted_1") == csum2)
                        {
                            MessageBox.Show("请注意，" + sPointName + "皮带带速或瞬时流量异常！");
                        }
                    }
                    

                }
                else
                {
                    if (getTedValue("realtime_amount_Ted") > 0 && getTedValue("belt_speed_Ted") > 1 && getTedValue("realtime_amount_Ted_1") > 0 && getTedValue("belt_speed_Ted_1") > 1)
                    {
                        if (getTedValue("instrument_weight_Ted") == csum1|| getTedValue("instrument_weight_Ted_1") == csum2)
                        {
                            MessageBox.Show("请注意，" + sPointName + "皮带带速或瞬时流量异常！");
                        }
                    }
                }
                zs = 0;
                if (sPointNo == "00039")//西区焦粉皮带秤
                {
                    csum2 = getTedValue("instrument_weight_Ted_1");
                }
                else
                {
                    csum1 = getTedValue("instrument_weight_Ted");
                    csum2 = getTedValue("instrument_weight_Ted_1");
                }
            }
        }
        #endregion

        #region  按钮事件  计量
        //查看
        private void checkBtn_Click(object sender, EventArgs e)
        {
            try
            {
                //if (startMerterBtn.Enabled == false && 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;//未计量
                //}
                maxscale = new FrmMaxBletScale();
                maxscale.Name = "maxscale" + sPointNo;
                maxscale.sIpAddress = sIpAddress;
                maxscale.sPointNo = sPointNo;
                maxscale.sPointName = sPointName;
                maxscale.sUserId = sUserId;
                maxscale.sUserName = sUserName;
                maxscale.userClass = userClass;
                maxscale.userGroup = userGroup;
               // maxscale.BtnType = BtnType;
                maxscale.StartPosition = FormStartPosition.CenterScreen;
                maxscale.beltinfo = beltinfo;
                IsMaxBelt = true;
                maxscale.ShowDialog();
                queryScale();
              //  UpdateControl(maxscale.BtnType);
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
            //maxscale.Dispose();
        }
        //新增卫生料计划
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                RESTfulResult<string> rm = PreBeltScalePreService.doAddBeltScalePrediction(findFromInfo());
                if (rm.Succeed)
                {
                    queryScale();
                    MessageBox.Show("新增卫生料预报成功");
                    return;
                }
                else
                {
                    MessageBox.Show("新增实绩失败，请联系技术中心！" + rm.Message);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }
        private PreBeltScaleForecast findFromInfo()
        {
            PreBeltScaleForecast beltinfo = new PreBeltScaleForecast();
            beltinfo.baseSpotNo = sPointNo;//计量点编码
            beltinfo.baseSpotName = sPointName;//计量点
            beltinfo.forwardingUnitNo = "456786";//发货单位编码
            beltinfo.newSupplier = "卫生料专用发货单位";//发货单位
            beltinfo.receivingUintNo = "456789";//收货单位编码
            beltinfo.receivingUintName = "卫生料专用收货单位";
            beltinfo.productNo = "456788";//物料编码
            beltinfo.newMatName = "卫生料";//物料名称
            beltinfo.forwardingWeight = Convert.ToDouble("8888");//发运重量
            beltinfo.orderNo = "WSL-WSL-WSL-WSL-WSL";//合同号
            beltinfo.shipNo = "卫生料船号";//船号
            beltinfo.overstock = DateTime.Now;
            beltinfo.createManNo = sUserId;
            beltinfo.createManName = sUserName;
            return beltinfo;
        }

        //刷新
        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 (getTedValue("instrument_weight_Ted") != 0 && ScaleName == "A")
            {
                return ScaleName + "仪表不为0时不能开始计量！";
            }
            if (getTedValue("instrument_weight_Ted_1") != 0 && ScaleName == "B")
            {
                return ScaleName + "仪表不为0时不能开始计量！";
            }
            if (mat_nameTxt.Text.ToString().Trim()==""|| shippingTxt.Text.ToString().Trim() == ""|| receivingTxt.Text.ToString().Trim() == "")
            {
                return  "物料名称、收发货单位不能为空!";
            }
            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) {
            try
            {
                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)
                {
                    SaveTimingInfo();//开始计量成功时 保存实时量
                    UpdateControl(controlId);
                    loadFrom();
                }
                else
                {
                    MessageBox.Show("计量失败，请联系技术中心！");
                    l.WriteLog("皮带秤计量异常_", "计量失败" + rm.Message);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }
        //A结束计量
        private void endMerterBtn_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否确定结束计量？", sPointName + " A秤", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                string message = checkEndSave("A");
                if (message != "200")
                {
                    MessageBox.Show(message);
                    return;
                }
                EndMerter("A", 3);
            }
        }
        //B结束计量
        private void endMerterBtn_1_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否确定结束计量？", sPointName + " B秤", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                string message = checkEndSave("B");
                if (message != "200")
                {
                    MessageBox.Show(message);
                    return;
                }
                EndMerter("B", 4);
            }
        }
        //结束计量
        private void EndMerter(string ScaleName,int controlId) {
            try
            {
                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("查找原有预报失败，请联系技术中心！" + rms.Message);
                    l.WriteLog("皮带秤计量异常_", "计量失败" + 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)
                {
                    SaveTimingInfo();//结束计量成功时 保存实时量
                    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("计量失败，请联系技术中心！" + rm.Message);
                    _startWeight1 = getTedValue("cumulative_weight_Ted");
                    _startWeight2 = getTedValue("cumulative_weight_Ted_1");
                    l.WriteLog("皮带秤计量异常_", "计量失败" + rm.Message);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }


        }

        //修改A仪表 的物料参数
        private void updateA_mat_Click(object sender, EventArgs e)
        {

            updateMatParameter(A_mat.Text.ToString().Trim(), "A");
        }
        //修改B仪表的物料参数
        private void updateB_mat_Click(object sender, EventArgs e)
        {
            updateMatParameter(B_mat.Text.ToString().Trim(), "B");
        }


        #endregion

        #region 退出关闭
        public void Close()
        {
            try
            {
                if (_strapMeter1 != null)
                {
                    _strapMeter1.Close();
                }
                if (_strapMeter2 != null)
                {
                    _strapMeter2.Close();
                }
                timer1.Stop();
                timer2.Stop();
                timer3.Stop();
                timer4.Stop();
                realtime.Stop();
                beltinfo = null;
                beltTiminginfo = null;
                this.Name = "关闭";
            }
            catch (Exception ex)
            {
                MessageBox.Show("失败" + ex.Message);
                l.WriteLog("皮带秤计量异常_", "失败" + ex.Message);
            }
        }
        #endregion

    }
}
