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

namespace StorageMeterSystem
{
    public partial class frmMain : Form
    {
        #region
        private string rk_CurPath = Application.StartupPath;  //System.Environment.CurrentDirectory;//获取到当前路径
        private SoundPlayer play_ls = null;
        private string computerSound = ConfigurationManager.AppSettings["ComputerSound"]?.ToString().Trim();

        private decimal iCntTime = 0;
        private List<StorageCollectModel> ltScModel = new List<StorageCollectModel>();
        private BaseDbCls bd = new BaseDbCls();
        private Log l = Log.GetInstance();
        private CoreAppUser appUser = null;
        private int iPic = 0;
        private bool bSaveFlag = false;

        private ProductDataControl collection = new ProductDataControl();
        private MeterWorkStorageActualService actualService = new MeterWorkStorageActualService();
        private MeterWorkCalibrationMainService calibrationMainService = new MeterWorkCalibrationMainService();
        private PbModelDbService<string> PbModelDbService = new PbModelDbService<string>();
        private MeterMonitorNoteService noteService = new MeterMonitorNoteService();

        //Led控制
        private LED_Control led_controler = null;

        private string _controlIp = "";
        #endregion

        public frmMain()
        {
            InitializeComponent();
        }

        #region 事件处理

        private void frmMain_Load(object sender, EventArgs e)
        {
            ucStorageWeightKg2.Visible = false;

            cbPC.SelectedIndex = 0;

            ValueList vlistFlag1 = new ValueList();
            vlistFlag1.ValueListItems.Add("1", "校秤失败");
            vlistFlag1.ValueListItems.Add("2", "校秤成功");
            vlistFlag1.ValueListItems.Add("3", "正在校秤");
            this.ultraGridJl.DisplayLayout.Bands[0].Columns["valueFlag"].ValueList = vlistFlag1;

            ValueList vlistFlag2 = new ValueList();
            vlistFlag2.ValueListItems.Add("1", "成功");
            vlistFlag2.ValueListItems.Add("2", "失败");
            this.ultraGridJl.DisplayLayout.Bands[1].Columns["valueFlag"].ValueList = vlistFlag2;

            ValueList vlistFlag3 = new ValueList();
            vlistFlag3.ValueListItems.Add("0", "作废");
            vlistFlag3.ValueListItems.Add("1", "有效");
            this.ultraGridSj.DisplayLayout.Bands[0].Columns["valueFlag"].ValueList = vlistFlag3;

            _controlIp = GetIP();
            appUser = ((ST_MainForm)(this.MdiParent)).AppUser;

            if (!bd.setBaseDb() || !bd.getBaseDb())
            {
                MessageBox.Show("基础数据载入失败，请稍后重试，或联系管理员");
                return;
            }

            DataTable dt = dtJGPointInfo.Clone();
            string strPointKeys = "";

            foreach (MeterBaseSpotInfo mbsi in PbStorageCache.sportInfos)
            {
                List<MeterWorkStockOnline> lm = PbStorageCache.ltMonitor.Where(s => s.baseSpotNo == mbsi.baseSpotNo).ToList();
                if (lm != null && lm.Count > 0)
                {
                    strPointKeys += lm[0].pointNo + ","; //Meter_Work_Stock_Online表配置了需采集的信息
                    DataRow dr = dt.NewRow();
                    dr["baseSpotNo"] = mbsi.baseSpotNo;
                    dr["baseSpotName"] = mbsi.baseSpotName;
                    dr["validFlag"] = string.IsNullOrEmpty(mbsi.controlIp) ? "未接管" : "已接管";
                    dr["controlIp"] = mbsi.controlIp;
                    dr["weightDiff"] = lm[0].weightDiff;
                    dt.Rows.Add(dr);
                }
            }

            strPointKeys = strPointKeys.Length > 0 ? strPointKeys.Substring(0, strPointKeys.Length - 1) : "";

            ClsControlPack.CopyDataToDatatable(ref dt, ref this.dtJGPointInfo, true);
            ClsControlPack.RefreshAndAutoSize(ultraGridPW);

            #region
            string sql = @"SELECT base_code baseCode,base_name baseName,memo FROM Com_Base_Info where p_base_code='001025' and valid_Flag='1'";
            PbModelDbService<List<ComBaseInfo>> pb = new PbModelDbService<List<ComBaseInfo>>();
            RESTfulResult<List<ComBaseInfo>> rmType = pb.executeSqlDataWf(sql);
            if (rmType.Succeed && rmType.Data != null && rmType.Data.Count > 0)
            {
                ClsControlPack.SetUltraComboDataSource(cmbMatterNo, rmType.Data.ListToDataTable<ComBaseInfo>(), "baseCode", "baseName");
            }
            else
            {
                MessageBox.Show("产品信息载入失败");
                return;
            }

            sql = @"SELECT base_code baseCode,base_name baseName,memo FROM Com_Base_Info where p_base_code='001026' and valid_Flag='1'";
            rmType = pb.executeSqlDataWf(sql);
            if (rmType.Succeed && rmType.Data != null && rmType.Data.Count > 0)
            {
                ClsControlPack.SetUltraComboDataSource(cmbGrade, rmType.Data.ListToDataTable<ComBaseInfo>(), "baseCode", "baseName");
            }
            else
            {
                MessageBox.Show("牌号载入失败");
                return;
            }

            sql = @"SELECT base_code baseCode,base_name baseName,memo FROM Com_Base_Info where p_base_code='001027' and valid_Flag='1'";
            rmType = pb.executeSqlDataWf(sql);
            if (rmType.Succeed && rmType.Data != null && rmType.Data.Count > 0)
            {
                ClsControlPack.SetUltraComboDataSource(cmbStandard, rmType.Data.ListToDataTable<ComBaseInfo>(), "baseCode", "baseName");
            }
            else
            {
                MessageBox.Show("标准载入失败");
                return;
            }

            //cmbBUCKET_NO 桶信息
            //sql = @"select utensil_no,utensil_name,utensil_weight,utensil_type_no,utensil_utensil_name from Meter_Base_Add_Weight where value_flag = '0' and utensil_type_no = '001009001'";
            sql = @"select utensil_name baseName,utensil_weight baseCode from Meter_Base_Add_Weight where value_flag = '0' and utensil_type_no = '001009002'";
            rmType = pb.executeSqlDataWf(sql);
            if (rmType.Succeed && rmType.Data != null && rmType.Data.Count > 0)
            {
                ClsControlPack.SetUltraComboDataSource(cmbBUCKET_NO, rmType.Data.ListToDataTable<ComBaseInfo>(), "baseCode", "baseName");
            }
            else
            {
                MessageBox.Show("桶类型载入失败");
                return;
            }

            //cmbDH 斗号
            //sql = @"select utensil_no,utensil_name,utensil_weight,utensil_type_no,utensil_utensil_name from Meter_Base_Add_Weight where value_flag = '0' and utensil_type_no = '001009001'";
            sql = @"select utensil_no baseName,utensil_weight baseCode from Meter_Base_Add_Weight where value_flag = '0' and utensil_type_no = '001009001'";
            rmType = pb.executeSqlDataWf(sql);
            if (rmType.Succeed && rmType.Data != null && rmType.Data.Count > 0)
            {
                ClsControlPack.SetUltraComboDataSource(cmbDH, rmType.Data.ListToDataTable<ComBaseInfo>(), "baseCode", "baseName");
            }
            else
            {
                MessageBox.Show("斗号载入失败");
                return;
            }
            #endregion

            collection.EventDataCollectionArgs += new ProductDataCollection(EventData);
            collection.Start(strPointKeys.Split(','));

            timer1.Start();
            timer2.Start();

            //ClsControlPack.SetUltraGridRowFilter(ref ultraGridSj, true);
        }

        private int iLedWrite = 0;

        public void EventData(object o, List<StorageCollectModel> lt)
        {
            //这里每隔0.5秒执行一次
            try
            {
                if (!bSaveFlag)
                {
                    PbStorageCache.ltCollect = lt;
                    foreach (StorageCollectModel sm in PbStorageCache.ltCollect)
                    {
                        setGridColorInfo(ultraGridPW, sm);

                        if (PbStorageCache.sportInfo == null)
                        {
                            ucStorageWeightKg1.setWgt(0);
                            ucStorageWeightKg1.setStable(true);

                            ucStorageWeightKg2.setWgt(0);
                            ucStorageWeightKg2.setStable(true);
                        }
                        //我在deleteManNo中存的是CAR20之类的数据
                        if (PbStorageCache.sportInfo != null && PbStorageCache.sportInfo.deleteManNo == sm.pointid)
                        {
                            if (!bTest)
                            {
                                iLedWrite++;
                                if (pDHSelected.bFlag && !pBucketSelected.bFlag)
                                {
                                    txtNetWgt.Invoke(new Action(() =>
                                    {
                                        txtNetWgt.Value = (decimal)sm.mainWgt - pDHSelected.dValue;
                                    }));
                                    if (iLedWrite % 2 == 0)
                                    {
                                        led_controler.setStaticLineMsg(PbStorageCache.sportInfo.ledIp, Math.Round(sm.mainWgt, 1) + "kg");
                                        iLedWrite = 0;
                                    }
                                }
                                else if (!pDHSelected.bFlag && pBucketSelected.bFlag)
                                {
                                    txtNetWgt.Invoke(new Action(() =>
                                    {
                                        txtNetWgt.Value = Math.Round((decimal)sm.mainWgt - pBucketSelected.dValue, 1);
                                    }));
                                    //如果选择了桶类型，那么显示的重量是当前重量-皮重，否则显示毛重
                                    if (iLedWrite % 2 == 0)
                                    {
                                        led_controler.setStaticLineMsg(PbStorageCache.sportInfo.ledIp, Math.Round(((decimal)sm.mainWgt - pBucketSelected.dValue), 1) + "kg");
                                        iLedWrite = 0;
                                    }
                                }
                                else
                                {
                                    //如果录入了净重的情况
                                    if (netWgt > 0)
                                    {
                                        txtTARE_WEIGHT.Invoke(new Action(() =>
                                        {
                                            txtTARE_WEIGHT.Value = Math.Round((decimal)sm.mainWgt - netWgt, 1);
                                        }));
                                    }
                                    if (iLedWrite % 2 == 0)
                                    {
                                        led_controler.setStaticLineMsg(PbStorageCache.sportInfo.ledIp, Math.Round(sm.mainWgt, 1) + "kg");
                                        iLedWrite = 0;
                                    }
                                }

                                ucStorageWeightKg1.setWgt(Math.Round(sm.mainWgt, 1));
                                ucStorageWeightKg1.setStable(sm.mainWeightStatus != 1 ? true : false);
                                ucStorageWeightKg2.setWgt(Math.Round(sm.viceWgt, 1));
                                ucStorageWeightKg2.setStable(sm.mainWeightStatus != 1 ? true : false);
                                PbStorageCache.collect = sm;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                l.WriteLog(0, "frmMeterMain.EventData异常8：" + ex.Message);
            }
        }

        private void btnOpenVoice_Click(object sender, EventArgs e)
        {
            if (panel1.Controls.Count > 0)
            {
                if (btnOpenVoice.Text == "打开对讲")
                {
                    VoiceOpen();
                }
                else
                {
                    VoiceClose();
                }
            }
        }

        /// <summary>
        /// 放大图像
        /// </summary>
        private void PictureBoxDoubleClick(object sender, EventArgs e)
        {
            if (iPic != 0)
            {
                if (PbStorageCache.sportInfo != null && PbStorageCache.sportInfo.baseSpotNo == "00015")
                    cameraShotMain.StopRealPlay(iPic + 2);
                else
                    cameraShotMain.StopRealPlay(iPic);
            }
            PictureBox picture = (PictureBox)sender;
            iPic = Convert.ToInt32(picture.Name.Substring(picture.Name.Length - 1, 1));
            plImgShow.Visible = true;

            if (PbStorageCache.sportInfo != null && PbStorageCache.sportInfo.baseSpotNo == "00015")
                cameraShotMain.RealPlay(pictureShow, iPic + 2);
            else
                cameraShotMain.RealPlay(pictureShow, iPic);
        }

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

            if (PbStorageCache.sportInfo != null && PbStorageCache.sportInfo.baseSpotNo == "00015")
                cameraShotMain.StopRealPlay(iPic + 2);
            else
                cameraShotMain.StopRealPlay(iPic);

            iPic = 0;
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            timer1.Stop();
            timer2.Stop();
            try
            {
                collection.Stop();
            }
            catch { }

            try
            {
                Clean();
            }
            catch { }
        }

        private validCalibration vCalib = new validCalibration();

        private void btnSave_Click(object sender, EventArgs e)
        {
            btnClickSave();
        }

        private bool btnSaveFlag = false;

        private void btnClickSave()
        {
            if (PbStorageCache.sportInfo == null) return;
            if (btnSaveFlag) return;

#if DEBUG
            PbCache.isNotValid = true;
#endif
            string msgInfo = "";
            bool isCalibration = vCalib.ValidMethod(new MeterWorkCalibrationMain { baseSpotNo = PbStorageCache.sportInfo.baseSpotNo, valueFlag = "2" }, out msgInfo);
            if (!isCalibration)
            {
                txtMsgInfo.Text = msgInfo;
                return;
            }

            #region
            if (ucStorageWeightKg1.getWgt() < 10)
            {
                //MessageBox.Show("当前重量小于10kg无法计量");
                led_controler.setProductOneLineMsg(PbStorageCache.sportInfo.ledIp, "当前重量过小");
                txtMsgInfo.Text = "当前重量过小，无法计量";
                SoudVoice("重量过小.wav");
                return;
            }

            if (cmbMatterNo.Value == null)
            {
                //MessageBox.Show("请选择产品名称");
                led_controler.setProductOneLineMsg(PbStorageCache.sportInfo.ledIp, "请先选择产品");
                txtMsgInfo.Text = "请选择产品名称，再进行计量";
                SoudVoice("请选择产品名称.wav");
                return;
            }

            if (cmbGrade.Value == null)
            {
                //MessageBox.Show("请选择牌号");
                led_controler.setProductOneLineMsg(PbStorageCache.sportInfo.ledIp, "请先选择牌号");
                txtMsgInfo.Text = "请选择牌号，再进行计量";
                SoudVoice("请选择牌号.wav");
                return;
            }

            if (cmbStandard.Value == null)
            {
                //MessageBox.Show("请选择标准");
                led_controler.setProductOneLineMsg(PbStorageCache.sportInfo.ledIp, "请先选择标准");
                txtMsgInfo.Text = "请选择标准，再进行计量";
                SoudVoice("请选择标准.wav");
                return;
            }
            string strMs = "";
            if (ucStorageWeightKg2.Visible)
            {
                double d = Math.Round(Convert.ToDouble(PbStorageCache.sportInfo.deleteManName), 2);
                if (Math.Round(Math.Abs(ucStorageWeightKg1.getWgt() - ucStorageWeightKg2.getWgt()), 1) > d)
                {
                    strMs = string.Format("双秤差值大于设定值{0}kg，无法计量", d);
                    led_controler.setProductOneLineMsg(PbStorageCache.sportInfo.ledIp, strMs);
                    txtMsgInfo.Text = strMs;
                    SoudVoice("双秤差值大于设定值.wav");
                    return;
                }
            }
            #endregion

            bSaveFlag = true;

            //DialogResult dr = MessageBox.Show(strMs + "是否确认保存当前计量数据？", "提示", MessageBoxButtons.OKCancel);
            //if (dr == DialogResult.OK)
            {
                btnCheckBalance.Enabled = false;
                btnOpenVoice.Enabled = false;
                btnSave.Enabled = false;

                try
                {
                    string actNo = "";
                    bool flag = SaveDB(out actNo);

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

                            /* 最后进行截图操作
                            CameraShotCls cameraShot = new CameraShotCls();
                            cameraShot.CapMethod(actNo);
                            //*/

                            //循环摄像头，然后根据摄像头有多少，则取硬盘录像机多少个通道数据
                            for (uint i = 1; i <= CarCache.cameraShots.Count; i++)
                            {
                                cameraShotMain.CapPicFromVideo(i,
                                    string.Format("{0}\\imgShort\\formalImg\\{1}_{2}_{3}",
                                        AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
                                        PbStorageCache.sportInfo.baseSpotNo,
                                        "S" + actNo, i)
                                );
                            }
                        }
                        catch (Exception ex)
                        {
                            l.WriteLog(8, "截图失败");
                        }
                        #endregion

                        try
                        {
                            QueryInfo();
                        }
                        catch { }

                        #region 数据清理
                        //cmbDH.Text = "";
                        //cmbBUCKET_NO.Text = "";
                        //txtCOMBIN_NO.Text = "";
                        //txtMEMO.Text = "";
                        #endregion

                        try
                        {
                            txtPACKAGE_NO.Text = txtPACKAGE_NO.Text.Trim() == "" ? "1" : (Convert.ToInt32(txtPACKAGE_NO.Text.Trim()) + 1) + "";
                            try
                            {
                                txtSEAL_NO.Text = txtSEAL_NO.Text.Trim() == "" ? "" : (txtSEAL_NO.Text.Trim().Length > 3 ? (txtSEAL_NO.Text.Trim().Substring(0, 3) + (Convert.ToInt32(txtSEAL_NO.Text.Trim().Substring(3, txtSEAL_NO.Text.Trim().Length - 3)) + 1 + "").PadLeft(3, '0')) : "");
                            }
                            catch { }
                        }
                        catch { }

                        SoudVoice("称重完成.wav");
                    }
                }
                catch (Exception ex)
                {
                    txtMsgInfo.Text = "保存失败：" + ex.Message.Trim();
                    l.WriteLog(8, "保存失败：" + ex.Message.Trim());
                }
            }

            bSaveFlag = false;
        }

        private void btnCheckBalance_Click(object sender, EventArgs e)
        {
            if (PbStorageCache.collect != null)
            {
                if (ucStorageWeightKg1.getWgt() < 10)
                {
                    MessageBox.Show("当前重量小于10kg无法校秤");
                    return;
                }

                frmCalibration fc = new frmCalibration();
                fc.cameraShotMain = cameraShotMain;
                fc.userId = appUser.userid;
                fc.userName = appUser.username;
                if (fc.ShowDialog() == DialogResult.OK)
                {
                    txtMsgInfo.Text = "校秤完成";
                    QueryXC();
                }
            }
        }

        private bool SaveDB(out string actNo)
        {
            actNo = "";
            MeterWorkStorageActual mwraf = new MeterWorkStorageActual();
#if DEBUG
            mwraf.predictionNo = DateTime.Now.ToString("yyyyMMddHHmmssfff");
#endif

            mwraf.batchNo = txtBATCH_NO.Text.Trim();
            mwraf.memo = txtMEMO.Text.Trim();
            mwraf.valueFlag = "1";
            mwraf.checkFlag = "0";
            mwraf.createManNo = appUser.userid;
            mwraf.createManName = appUser.username;
            mwraf.createTime = DateTime.Now;
            mwraf.productNo = cmbMatterNo.Value.ToString();
            mwraf.productName = cmbMatterNo.Text.Trim();
            mwraf.gradeNo = cmbGrade.Value.ToString();
            mwraf.gradeName = cmbGrade.Text.Trim();
            mwraf.standardNo = cmbStandard.Value.ToString();
            mwraf.standardName = cmbStandard.Text.Trim();
            mwraf.packageNo = txtPACKAGE_NO.Text.Trim();
            mwraf.blockNum = txtBLOCK_NUM.Value + "";
            mwraf.productDate = txtPRODUCT_DATE.Value;
            mwraf.sealNo = txtSEAL_NO.Text;
            mwraf.deleteManName = txtMEMO.Text.Trim() != "" ? (txtMEMO.Text.Trim() + "|" + cmbBUCKET_NO.Text) : cmbBUCKET_NO.Text; //不记录选的是哪个桶类型或者斗信息

            if (cmbDH.Text.Trim() != "")
            {
                mwraf.memo = mwraf.memo != "" ? (mwraf.memo + "|斗号：" + cmbDH.Text.Trim()) : ("斗号：" + cmbDH.Text.Trim());
            }
            if (cmbBUCKET_NO.Text.Trim() != "")
            {
                mwraf.memo = mwraf.memo != "" ? (mwraf.memo + "|桶类型：" + cmbBUCKET_NO.Text.Trim()) : ("桶类型：" + cmbBUCKET_NO.Text.Trim());
            }

            mwraf.grossWeight = PbStorageCache.collect.mainWgt;
            mwraf.tareWeight = Convert.ToDouble(txtTARE_WEIGHT.Value);
            mwraf.combinPackageNo = txtCOMBIN_NO.Text.Trim();
            //mwraf.weightType = "0";
            mwraf.baseSpotNo = PbStorageCache.sportInfo.baseSpotNo;
            mwraf.baseSpotName = PbStorageCache.sportInfo.baseSpotName;
            mwraf.actualWeight = PbStorageCache.collect.mainWgt;
            mwraf.netWeight = mwraf.grossWeight - mwraf.tareWeight;

            #region eason add 好像存在皮重计算存在小数差值问题，所以如果录入了净重，则皮重是毛-净
            if (netWgt > 0)
            {
                mwraf.netWeight = Math.Round((double)netWgt, 1);
                mwraf.tareWeight = mwraf.grossWeight - mwraf.netWeight;
            }
            #endregion

            #region 2021-06-24 add
            if (txtBucketNo.Value > 0 && txtBucketAddValue.Value > 0)
            {
                if (txtBucketAddValue.Value > 1)
                {
                    mwraf.bucketNo = txtBucketNo.Value + "-" + (txtBucketNo.Value + txtBucketAddValue.Value - 1);
                }
                else
                {
                    mwraf.bucketNo = txtBucketNo.Value + "";
                }
                txtBucketNo.Value += txtBucketAddValue.Value;
            }
            else if (txtBucketNo.Value > 0)
            {
                mwraf.bucketNo = txtBucketNo.Value + "";
            }
            #endregion

            if (ucStorageWeightKg2.Visible)
            {
                mwraf.referWeight = PbStorageCache.collect.viceWgt;
            }

            RESTfulResult<string> rm = actualService.doAddWf(mwraf);
            if (rm.Succeed)
            {
                actNo = rm.Data;
                setMsgInfo(txtMsgInfo, "保存成功", "");
                return true;
            }
            else
            {
                setMsgInfo(txtMsgInfo, "保存失败：" + rm.Message, "");
                l.WriteLog(8, "保存失败：" + rm.Message);
                return false;
            }
        }

        private void QueryInfo()
        {
            if (PbStorageCache.sportInfo != null)
            {
                DataTable dtSj = dataTable1.Clone();

                RESTfulResult<List<MeterWorkStorageActual>> rms = actualService.doQueryWf(new MeterWorkStorageActual { valueFlag = "1", baseSpotNo = PbStorageCache.sportInfo.baseSpotNo });
                if (rms.Succeed && rms.Data != null && rms.Data.Count > 0)
                {
                    dtSj = rms.Data.ListToDataTable<MeterWorkStorageActual>();

                    ClsControlPack.CopyDataToDatatable(ref dtSj, ref dataTable1, true);
                    ClsControlPack.RefreshAndAutoSize(ultraGridSj);

                    foreach (UltraGridRow ugr in ultraGridSj.Rows)
                    {
                        if (ugr.Cells["valueFlag"].Value.ToString() == "0")
                        {
                            ugr.Appearance.BackColor = Color.Red;
                        }
                        else
                        {
                            ugr.Appearance.BackColor = Color.White;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 校秤数据查下
        /// </summary>
        private void QueryXC()
        {
            if (PbStorageCache.sportInfo != null)
            {
                DataTable dtJlM = dtCalibration.Clone();
                DataTable dtJlC = dtBranch.Clone();

                //dtCalibration  dtBranch

                CommonPage<MeterWorkCalibrationMain> cpc = new CommonPage<MeterWorkCalibrationMain>();
                MeterWorkCalibrationMain mwca = new MeterWorkCalibrationMain();
                mwca.baseSpotNo = PbStorageCache.sportInfo.baseSpotNo;
                cpc.param = mwca;
                cpc.pageNum = 1;
                cpc.pageSize = 10;

                RESTfulResult<PbGetSomeModel<MeterWorkCalibrationMain, MeterWorkCalibrationBranch>> rms = calibrationMainService.doQuerySomeWf(cpc);
                if (rms.Succeed && rms.Data != null)
                {
                    dtJlM = rms.Data.one.ListToDataTable<MeterWorkCalibrationMain>();
                    dtJlC = rms.Data.two.ListToDataTable<MeterWorkCalibrationBranch>();

                    dtBranch.Clear();
                    dtCalibration.Clear();

                    ClsControlPack.CopyDataToDatatable(ref dtJlM, ref dtCalibration, true);
                    ClsControlPack.CopyDataToDatatable(ref dtJlC, ref dtBranch, true);

                    ClsControlPack.RefreshAndAutoSize(ultraGridJl, true);
                }
            }
        }

        #endregion

        #region 数据初始清理

        private void Clean()
        {
            updateSport("");

            if (PbStorageCache.sportInfo != null)
            {
                led_controler.setProductOneLineMsg(PbStorageCache.sportInfo.ledIp, "欢迎使用九钢智能计量系统");
            }

            //*
            PbStorageCache.videoInfo = null;
            //PbStorageCache.dtStartTime = null;
            PbStorageCache.sportInfo = null;
            PbStorageCache.collect = null;

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

            setPanelRemovenfo(panel1);

            CleanForm();
            //*/
        }

        private void CleanForm()
        {
            cmbMatterNo.Text = "";
            cmbGrade.Text = "";
            cmbStandard.Text = "";
            txtBLOCK_NUM.Value = 0;
            txtBATCH_NO.Text = "";
            txtPRODUCT_DATE.Value = DateTime.Now;
            txtPACKAGE_NO.Text = "";
            txtSEAL_NO.Text = "";
            cmbBUCKET_NO.Text = "";
            txtCOMBIN_NO.Text = "";
            txtMEMO.Text = "";
            txtTARE_WEIGHT.Value = 0;
            txtMsgInfo.Text = "";
            cmbDH.Text = "";
            netWgt = 0;
            txtNetWgt.Value = 0;
            //cmbDH.Value = null;

            DataTable dtSj = dataTable1.Clone();
            ClsControlPack.CopyDataToDatatable(ref dtSj, ref dataTable1, true);
            ClsControlPack.RefreshAndAutoSize(ultraGridSj);

            dtBranch.Clear();
            dtCalibration.Clear();
            DataTable dtJl = dtCalibration.Clone();
            DataTable dtJlC = dtBranch.Clone();

            ClsControlPack.CopyDataToDatatable(ref dtJl, ref dtCalibration, true);
            ClsControlPack.CopyDataToDatatable(ref dtJlC, ref dtBranch, true);
            ClsControlPack.RefreshAndAutoSize(ultraGridJl);

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

            ucStorageWeightKg2.Visible = false;
            ucStorageWeightKg2.setWgt(0);
            ucStorageWeightKg2.setStable(true);
        }

        #endregion

        #region 对讲代码

        private bool SoudVoice(string soundName)
        {
            string fileUrl = string.Format("{0}\\Sound\\{1}", AppDomain.CurrentDomain.SetupInformation.ApplicationBase, soundName);
            if (computerSound == "1")
            {
                try
                {
                    play_ls = new SoundPlayer(fileUrl);
                    play_ls.Play();
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            else
            {
                return cameraShotMain.SoundVoice(fileUrl);
            }
        }

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

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

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

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

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

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

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

        private void setPicBoxSet()
        {
            if (PbStorageCache.videoChild != null && PbStorageCache.videoChild.Count > 0)
            {
                if (PbStorageCache.sportInfo != null)
                {
                    for (int k = 1; k <= 2; k++)
                    {
                        PictureBox pb = new PictureBox();
                        pb.Name = "pb" + k;
                        pb.Dock = DockStyle.Top;
                        pb.Height = 260;
                        pb.DoubleClick += new EventHandler(PictureBoxDoubleClick);
                        pb.BorderStyle = BorderStyle.FixedSingle;
                        panel1.Controls.Add(pb);
                        ltPicBoxs.Add(pb);

                        if (PbStorageCache.sportInfo.baseSpotNo == "00015")
                            cameraShotMain.RealPlay(pb, k + 2);
                        else
                            cameraShotMain.RealPlay(pb, k);
                    }
                }
            }
        }

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

        /// <summary>
        /// 如果ResultMessage为true或者false，则sType 为0的时候readonly  1为enable  2为visable
        /// </summary>
        /// <param name="control"></param>
        /// <param name="ResultMessage"></param>
        /// <param name="sType"></param>
        private void setPanelRemoveMsg(Panel p)
        {
            if (p.InvokeRequired)
            {
                Action<Panel> action = new Action<Panel>(setPanelRemovenfo);
                Invoke(action, new object[] { p });
            }
            else
            {
                for (int i = p.Controls.Count - 1; i >= 0; i--)
                {
                    p.Controls.RemoveAt(i);
                }
            }
        }

        #endregion

        #region 控件值设置

        //如果ResultMessage为true或者false，则sType 为0的时候readonly  1为enable  2为visable
        public void setMsgInfo(Control control, string ResultMessage, string sType)
        {
            setMsgMsg(control, ResultMessage, sType);
        }

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

                        default: break;
                    }
                }
                else if (ResultMessage == "color")
                {
                    switch (sType)
                    {
                        case "Red":
                            control.BackColor = Color.Red;
                            ; break;
                        case "Lime":
                            control.BackColor = Color.Lime;
                            ; break;
                        default: break;
                    }
                }
                else
                {
                    control.Text = ResultMessage == null ? "" : ResultMessage;
                }
            }
        }

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

        public object GetControlProperty(Control control, string name)
        {
            if (control.InvokeRequired == true)
            {
                GetControlPropertyCallBack CallBack = new GetControlPropertyCallBack(GetControlProperty);
                return control.Invoke(CallBack, new object[] { control, name });
            }
            else
            {
                Type type = control.GetType();
                return type.InvokeMember(name,
                    BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance,
                  null, control, null);
            }
        }

        public void setGridColorInfo(UltraGrid ugr, StorageCollectModel sModel)
        {
            setGridColorMsg(ugr, sModel);
        }

        private void setGridColorMsg(UltraGrid control, StorageCollectModel sModel)
        {
            if (control.InvokeRequired)
            {
                Action<UltraGrid, StorageCollectModel> action = new Action<UltraGrid, StorageCollectModel>(setGridColorInfo);
                Invoke(action, new object[] { control, sModel });
            }
            else
            {
                foreach (UltraGridRow urg in control.Rows)
                {
                    if (PbStorageCache.sportInfo != null && urg.Cells["baseSpotNo"].Text == PbStorageCache.sportInfo.baseSpotNo)
                    {
                        urg.Appearance.BackColor = Color.Red;
                        break;
                    }
                    else if (sModel.pointid == urg.Cells["baseSpotNo"].Text)
                    {
                        if (sModel.mainWgt > 20)
                        {
                            urg.Appearance.BackColor = Color.Orange;
                        }
                        else
                        {
                            urg.Appearance.BackColor = Color.White;
                        }
                        break;
                    }
                }
            }
        }

        #endregion

        public string GetIP()
        {
            try
            {
                IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddr = ipHost.AddressList[0];
                return ipAddr.ToString();
            }
            catch (Exception exp)
            {
                Random rd = new Random();
                return rd.Next(99999, 999999) + "";
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                btnStart.Enabled = false;
                btnCheckBalance.Enabled = false;
                btnOpenVoice.Enabled = false;
                btnSave.Enabled = false;

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

                        btnStart.BackColor = Color.Red;
                        btnStart.Text = "释放";
                        PbStorageCache.sportInfo = PbStorageCache.sportInfos.Where(s => s.baseSpotNo == ugr.Cells["baseSpotNo"].Text.Trim()).FirstOrDefault();

                        led_controler = new LED_Control(PbStorageCache.sportInfo.ledIp);

                        //将主副秤秤体允许偏差值写入
                        PbStorageCache.sportInfo.deleteManName = ugr.Cells["weightDiff"].Text == "" ? "0" : ugr.Cells["weightDiff"].Text.Trim();

                        //controlIp
                        updateSport(_controlIp);

                        int icnt = PbStorageCache.scalePoints.Where(s => s.baseSpotNo == PbStorageCache.sportInfo.baseSpotNo).Count();

                        if (icnt > 1) //双秤
                        {
                            ucStorageWeightKg2.Visible = true;
                        }
                        else //单秤
                        {
                            ucStorageWeightKg2.Visible = false;
                        }

                        bd.getSpot();
                        GetIPVideo(PbStorageCache.videoInfo);
                        setPicBoxSet();

                        #region 增加包号
                        string sql = string.Format("select nvl(max(package_no),'0')+1 baseCode from meter_work_storage_actual where base_spot_no='{0}' and BATCH_NO='{1}'", PbStorageCache.sportInfo.baseSpotNo, txtBATCH_NO.Text.Trim());
                        PbModelDbService<List<ComBaseInfo>> pb = new PbModelDbService<List<ComBaseInfo>>();
                        RESTfulResult<List<ComBaseInfo>> rmType = pb.executeSqlDataWf(sql);
                        if (rmType.Succeed && rmType.Data != null && rmType.Data.Count > 0)
                        {
                            txtPACKAGE_NO.Text = rmType.Data[0].baseCode;
                        }
                        else
                        {
                            l.WriteLog(8, "包号载入失败:" + sql);
                        }

                        QueryInfo();
                        QueryXC();

                        #endregion
                    }
                }
                else
                {
                    btnStart.BackColor = Color.DodgerBlue;
                    btnStart.Text = "接管";

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

                    ucStorageWeightKg2.Visible = false;

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

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

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

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

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

                            cIp = (string.IsNullOrEmpty(msi.controlIp) ? "" : msi.controlIp);
                            if (dr["controlIp"].ToString().Trim() != cIp)
                            {
                                dr["controlIp"] = cIp;
                                bRefash = true;
                            }
                        }
                        dt.Rows.Add(dr.ItemArray);
                    }
                    if (bRefash)
                    {
                        ClsControlPack.CopyDataToDatatable(ref dt, ref this.dtJGPointInfo, true);
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show("timer1_Tick任务异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
                l.WriteLog(13, "timer1_Tick任务异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n" + ex);
            }
        }

        private bool bTest = false;
        /*
        private void button1_Click(object sender, EventArgs e)
        {
            bTest = !bTest;
            if (bTest)
            {
                ucStorageWeightKg1.setWgt((double)numericUpDown1.Value);
                ucStorageWeightKg1.setStable(PbStorageCache.collect.mainWeightStatus != 1 ? true : false);
                ucStorageWeightKg2.setWgt((double)numericUpDown2.Value);
                ucStorageWeightKg2.setStable(PbStorageCache.collect.mainWeightStatus != 1 ? true : false);

                PbStorageCache.collect = new StorageCollectModel
                {
                    mainWgt = (double)numericUpDown1.Value,
                    viceWgt = (double)numericUpDown2.Value,
                    mainWeightStatus = 0,
                    pointid = "CAR20"
                };
                //"172.22.42.34"
            }
        }
        //*/

        private void timer2_Tick(object sender, EventArgs e)
        {
            txtPRODUCT_DATE.Value = DateTime.Now;

            if (ucStorageWeightKg1.getWgt() < 10)
            {
                btnSaveFlag = false;
                if (!btnSave.Enabled)
                {
                    btnSave.Enabled = true;
                    btnCheckBalance.Enabled = true;
                    btnOpenVoice.Enabled = true;
                }
                iCntTime = 0;
            }
            else
            {
                if (ucStorageWeightKg1.isGreen)
                {
                    iCntTime++;
                    if (iCntTime > txtTimeLength.Value)
                    {
                        iCntTime = txtTimeLength.Value;
                    }
                }
                else
                {
                    iCntTime = 0;
                }
            }

            if (iCntTime >= txtTimeLength.Value && cbAuto.Checked && ucStorageWeightKg1.getWgt() > 10 && ucStorageWeightKg1.isGreen && txtBATCH_NO.Text.Trim() != "")
            {
                double wcWgt = Math.Round((double)txtWcWgt.Value, 1);
                double wdWgt = Math.Round((double)txtWdWgt.Value, 1);
                double pzWgt = Math.Round((double)txtTARE_WEIGHT.Value, 1);
                //这里设置1的原因是担心decmial转double可能存在精度丢失导致0的时候大于0的情况，一般应该不会
                if (wdWgt > 1)
                {
                    if (cbPC.Text == "±") { }

                    switch (cbPC.Text.Trim())
                    {
                        case "±":
                            {
                                if (((ucStorageWeightKg1.getWgt() - pzWgt) <= (wdWgt + wcWgt) && (ucStorageWeightKg1.getWgt() - pzWgt) >= (wdWgt - wcWgt)))
                                {
                                    btnClickSave();
                                }
                            }; break;
                        case "+":
                            {
                                if (((ucStorageWeightKg1.getWgt() - pzWgt) <= (wdWgt + wcWgt) && (ucStorageWeightKg1.getWgt() - pzWgt) >= wdWgt))
                                {
                                    btnClickSave();
                                }
                            }; break;
                        case "-":
                            {
                                if (((ucStorageWeightKg1.getWgt() - pzWgt) <= wdWgt && (ucStorageWeightKg1.getWgt() - pzWgt) >= (wdWgt - wcWgt)))
                                {
                                    btnClickSave();
                                }
                            }; break;
                        default:
                            {
                                if (((ucStorageWeightKg1.getWgt() - pzWgt) <= (wdWgt + wcWgt) && (ucStorageWeightKg1.getWgt() - pzWgt) >= (wdWgt - wcWgt)))
                                {
                                    btnClickSave();
                                }
                            }; break;
                    }
                }
                else
                {
                    btnClickSave();
                }
            }
        }

        private PNumberModel pDHSelected = new PNumberModel() { bFlag = false, dValue = 0 };

        private void cmbDH_RowSelected(object sender, RowSelectedEventArgs e)
        {
            txtTARE_WEIGHT.Value = e?.Row?.Cells["baseCode"]?.Value == null ? 0 : Convert.ToDecimal(e?.Row?.Cells["baseCode"]?.Value);
            if (e?.Row?.Cells["baseCode"]?.Value == null)
            {
                pDHSelected.bFlag = false;
                pDHSelected.dValue = txtTARE_WEIGHT.Value;
            }
            else
            {
                pDHSelected.bFlag = true;
                pDHSelected.dValue = txtTARE_WEIGHT.Value;
            }
            cmbBUCKET_NO.Enabled = !pDHSelected.bFlag;
            setNetWgt();
        }

        private PNumberModel pBucketSelected = new PNumberModel() { bFlag = false, dValue = 0 };

        private void cmbBUCKET_NO_RowSelected(object sender, RowSelectedEventArgs e)
        {
            txtTARE_WEIGHT.Value = e?.Row?.Cells["baseCode"]?.Value == null ? 0 : Convert.ToDecimal(e?.Row?.Cells["baseCode"]?.Value);
            if (e?.Row?.Cells["baseCode"]?.Value == null)
            {
                pBucketSelected.bFlag = false;
                pBucketSelected.dValue = txtTARE_WEIGHT.Value;
            }
            else
            {
                pBucketSelected.bFlag = true;
                pBucketSelected.dValue = txtTARE_WEIGHT.Value;
            }
            cmbDH.Enabled = !pBucketSelected.bFlag;
            setNetWgt();
        }

        private void setNetWgt()
        {
            if (!pDHSelected.bFlag && !pBucketSelected.bFlag)
            {
                txtNetWgt.Invoke(new Action(() =>
                {
                    txtNetWgt.Value = 0;
                }));
            }
        }

        private decimal netWgt = 0;

        private void txtNetWgt_ValueChanged(object sender, EventArgs e)
        {
            netWgt = txtNetWgt.Value;
        }

        private void txtBATCH_NO_MouseLeave(object sender, EventArgs e)
        {
            if (PbStorageCache.sportInfo != null)
            {
                string sql = string.Format("select nvl(max(package_no),'0') baseCode from meter_work_storage_actual t where length(package_no)=(select max(length(package_no)) from meter_work_storage_actual where base_spot_no = '{0}' and BATCH_NO = '{1}') and base_spot_no='{0}' and BATCH_NO='{1}'", PbStorageCache.sportInfo.baseSpotNo, txtBATCH_NO.Text.Trim());
                PbModelDbService<List<ComBaseInfo>> pb = new PbModelDbService<List<ComBaseInfo>>();
                RESTfulResult<List<ComBaseInfo>> rmType = pb.executeSqlDataWf(sql);
                if (rmType.Succeed && rmType.Data != null && rmType.Data.Count > 0)
                {
                    if (rmType.Data[0].baseCode != "0" && rmType.Data[0].baseCode.Length > 0)
                    {
                        try
                        {
                            string[] str = rmType.Data[0].baseCode.Split('-');
                            txtPACKAGE_NO.Value = Convert.ToInt32(rmType.Data[0].baseCode.Split('-')[str.Length - 1]) + 1;
                        }
                        catch { }
                    }
                    else
                    {
                        txtPACKAGE_NO.Text = "1";
                    }
                }
                else
                {
                    l.WriteLog(8, "包号载入失败:" + sql);
                }

                #region eason add 2021-06-24增加通号新增
                sql = string.Format("select nvl(max(bucket_no),'0') baseName from meter_work_storage_actual t where length(bucket_no)=(select max(length(bucket_no)) from meter_work_storage_actual where base_spot_no = '{0}' and BATCH_NO = '{1}') and base_spot_no='{0}' and BATCH_NO='{1}'", PbStorageCache.sportInfo.baseSpotNo, txtBATCH_NO.Text.Trim());
                rmType = pb.executeSqlDataWf(sql);
                if (rmType.Succeed && rmType.Data != null && rmType.Data.Count > 0)
                {
                    if (rmType.Data[0].baseName != "0" && rmType.Data[0].baseName.Length > 0)
                    {
                        try
                        {
                            string[] str = rmType.Data[0].baseName.Split('-');
                            txtBucketNo.Value = Convert.ToInt32(rmType.Data[0].baseName.Split('-')[str.Length - 1]) + 1;
                        }
                        catch { }
                    }
                    else if (txtBucketAddValue.Value > 0)
                    {
                        txtBucketNo.Value = 1;
                    }
                }
                else
                {
                    l.WriteLog(8, "初始箱号载入失败:" + sql);
                }
                #endregion
            }
        }

        private void cbAuto_CheckedChanged(object sender, EventArgs e)
        {
            if (cbAuto.Checked && txtBATCH_NO.Text.Trim() == "")
            {
                MessageBox.Show("请先输入批号");
                cbAuto.Checked = false;
                return;
            }
            btnSave.Visible = !cbAuto.Checked;
            btnCheckBalance.Visible = !cbAuto.Checked;

            label3.Visible = cbAuto.Checked;
            txtWdWgt.Visible = cbAuto.Checked;
            cbPC.Visible = cbAuto.Checked;
            txtWcWgt.Visible = cbAuto.Checked;

            if (!cbAuto.Checked)
            {
                txtWdWgt.Value = 0;
                txtWcWgt.Value = 0;
            }
        }
    }

    public class PNumberModel
    {
        public bool bFlag { get; set; }
        public decimal dValue { get; set; }
    }
}