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.Data;
using System.Drawing;
using System.Linq;
using System.Media;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StorageMeterSystem
{
    public partial class frmGlodMain : Form
    {
        public frmGlodMain()
        {
            InitializeComponent();
        }


        #region
        SoundPlayer play_ls = null;

        decimal iCntTime = 0, iCntMainTIme = 0; //iCntTime副秤计时器，CntMainTIme主秤计时器
        List<StorageCollectModel> ltScModel = new List<StorageCollectModel>();
        private BaseGlodDbCls bd = new BaseGlodDbCls();
        Log l = Log.GetInstance();
        CoreAppUser appUser = null;
        bool bSaveFlag = false, bSaveFlagM = false;

        ProductDataControl collectionM = new ProductDataControl();
        ProductDataControl collectionF = new ProductDataControl();

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

        MeterWorkStorageActual actualForLims = null, actualForLimsMain = null;

        List<MeterWorkStockOnline> lmo = new List<MeterWorkStockOnline>();
        string _controlIp = "";
        #endregion


        #region 事件处理
        private void frmGlodMain_Load(object sender, EventArgs e)
        {
            cbPC.SelectedIndex = 0;

            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 PbStorageGlodCache.sportInfos)
            {
                List<MeterWorkStockOnline> lm = PbStorageGlodCache.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);

                    lmo.AddRange(lm);
                }
            }

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


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

            collectionF.EventDataCollectionArgs += new ProductDataCollection(EventDataF);
            collectionM.EventDataCollectionArgs += new ProductDataCollection(EventDataM);


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

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

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

                        if (PbStorageGlodCache.sportInfo == null)
                        {
                            ucStorageWeightG1.setWgt(0);
                            ucStorageWeightG1.setStable(true);
                        }
                        if (!bTest)
                        {
                            ucStorageWeightG1.setWgt(Math.Round(sm.mainWgt, 3));
                            ucStorageWeightG1.setStable(sm.mainWeightStatus != 1 ? true : false);
                            PbStorageGlodCache.collectF = sm;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                l.WriteLog(0, "frmMeterMain.EventData异常8：" + ex.Message);
            }
        }

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

                        if (PbStorageGlodCache.sportInfo == null)
                        {
                            ucStorageWeightG2.setWgt(0);
                            ucStorageWeightG2.setStable(true);
                        }
                        if (!bTest)
                        {
                            ucStorageWeightG2.setWgt(Math.Round(sm.mainWgt, 3));
                            ucStorageWeightG2.setStable(sm.mainWeightStatus != 1 ? true : false);
                            PbStorageGlodCache.collectM = sm;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                l.WriteLog(0, "frmMeterMain.EventData异常8：" + ex.Message);
            }
        }


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

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

            try
            {
                Clean();
            }
            catch { }
        }

        validCalibration vCalib = new validCalibration();
        private void btnSave_Click(object sender, EventArgs e)
        {
            btnClickSave();//手动副秤保存
        }

        private void btnSaveMain_Click(object sender, EventArgs e)
        {
            btnClickSaveMain();
        }

        #region 副秤保存
        bool btnSaveFlag = false;
        private void btnClickSave()
        {
            if (PbStorageGlodCache.sportInfo == null) return;
            if (btnSaveFlag) return;

            string msgInfo = "";
            bool isCalibration = vCalib.ValidMethod(new MeterWorkCalibrationMain { baseSpotNo = PbStorageGlodCache.sportInfo.baseSpotNo, valueFlag = "2" }, out msgInfo);
            if (!isCalibration)
            {
                txtMsgInfoV.Text = msgInfo;
                return;
            }

            #region
            if (ucStorageWeightG1.getWgt() < 100)
            {
                txtMsgInfoV.Text = "当前重量过小，无法计量";
                SoudVoice("重量过小.wav");
                return;
            }

            if (txtMatterNo.Text.Trim() == "")
            {
                txtMsgInfoV.Text = $"批次[{txtBATCH_NO.Text.Trim()}]未找到检验数据";
                SoudVoice("该批号未找到检验数据.wav");
                return;
            }
            #endregion

            bSaveFlag = true;
            btnSave.Enabled = false;

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

                if (flag)
                {
                    btnSaveFlag = true;
                    bFQuery = false;
                    #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,
                            PbStorageGlodCache.sportInfo.baseSpotNo,
                            "G" + actNo,
                            1), System.Drawing.Imaging.ImageFormat.Jpeg);

                    }
                    catch (Exception ex)
                    {
                        l.WriteLog(8, "截图失败");
                    }
                    #endregion

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

        private bool SaveDB(out string actNo)
        {
            actNo = "";
            MeterWorkStorageActual mwraf = new MeterWorkStorageActual();
            mwraf.predictionNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + 1;

            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 = actualForLims?.productNo;
            mwraf.productName = txtMatterNo.Text.Trim();
            mwraf.gradeNo = actualForLims?.gradeNo;
            mwraf.gradeName = txtGrade.Text.Trim();
            mwraf.standardNo = actualForLims?.standardNo;
            mwraf.standardName = txtStandard.Text.Trim();
            mwraf.packageNo = txtPACKAGE_NO.Text.Trim();
            mwraf.blockNum = txtBLOCK_NUM.Value +"";
            mwraf.productDate = txtPRODUCT_DATE.Value;
            

            //mwraf.grossWeight = PbStorageGlodCache.collect.mainWgt;
            //mwraf.tareWeight = Convert.ToDouble(txtFirst_WEIGHT.Value);
            //mwraf.weightType = "0";
            mwraf.baseSpotNo = PbStorageGlodCache.sportInfo.baseSpotNo;
            mwraf.baseSpotName = PbStorageGlodCache.sportInfo.baseSpotName;

            mwraf.referWeight = PbStorageGlodCache.collectF.mainWgt;


            RESTfulResult<string> rm = actualService.doAddWf(mwraf);
            if (rm.Succeed)
            {
                actNo = rm.Data;
                setMsgInfo(txtMsgInfoV, $"批次：{txtBATCH_NO.Text.Trim()},块号：{txtPACKAGE_NO.Value}，保存成功", "");
                return true;
            }
            else
            {
                setMsgInfo(txtMsgInfoV, "保存失败" + rm.Message, "");
                l.WriteLog(8, "保存失败" + rm.Message);
                return false;
            }
        }
        #endregion

        #region 主秤保存
        bool btnSaveFlagMain = false; 
        private void btnClickSaveMain()
        {
            if (PbStorageGlodCache.sportInfo == null) return;
            if (btnSaveFlagMain) return;

            string msgInfo = "";
            bool isCalibration = vCalib.ValidMethod(new MeterWorkCalibrationMain { baseSpotNo = PbStorageGlodCache.sportInfo.baseSpotNo, valueFlag = "2" }, out msgInfo);
            if (!isCalibration)
            {
                txtMsgInfoM.Text = msgInfo;
                return;
            }

            #region
            if (ucStorageWeightG2.getWgt() < 100)
            {
                txtMsgInfoM.Text = "当前重量过小，无法计量";
                SoudVoice("重量过小.wav");
                return;
            }

            if (txtMatterNoMain.Text.Trim() == "")
            {
                txtMsgInfoM.Text = $"批次[{txtBATCH_NOMain.Text.Trim()}]未找到检验数据";
                SoudVoice("该批号未找到检验数据.wav");
                return;
            }

            if (actualForLimsMain == null) 
            {
                txtMsgInfoM.Text = $"批次[{txtBATCH_NOMain.Text.Trim()}]未找到副秤计量数据";
                return;
            }

            double wcWgt = Math.Round((double)txtWcWgt.Value, 3);
            double wdWgt = Math.Round((double)txtFirst_WEIGHT.Value, 3);
            //这里设置1的原因是担心decmial转double可能存在精度丢失导致0的时候大于0的情况，一般应该不会
            if (wdWgt > 0)
            {
                switch (cbPC.Text.Trim())
                {
                    case "+":
                        {
                            if ((ucStorageWeightG2.getWgt() > (wdWgt + wcWgt) || ucStorageWeightG2.getWgt() < wdWgt))
                            {
                                txtMsgInfoM.Text = $"双秤差值大于设定值{txtWcWgt.Value}g，无法计量";
                                SoudVoice("双秤差值大于设定值.wav");
                                return;
                            }
                        }; break;
                    case "-":
                        {
                            if ((ucStorageWeightG2.getWgt() > wdWgt || ucStorageWeightG2.getWgt() < (wdWgt - wcWgt)))
                            {
                                txtMsgInfoM.Text = $"双秤差值大于设定值{txtWcWgt.Value}g，无法计量";
                                SoudVoice("双秤差值大于设定值.wav");
                                return;
                            }
                        }; break;
                    default:
                        {
                            if ((ucStorageWeightG2.getWgt() > (wdWgt + wcWgt) || ucStorageWeightG2.getWgt() < (wdWgt - wcWgt)))
                            {
                                txtMsgInfoM.Text = $"双秤差值大于设定值{txtWcWgt.Value}g，无法计量";
                                SoudVoice("双秤差值大于设定值.wav");
                                return;
                            }
                        }; break;
                }
            }
            #endregion

            bSaveFlagM = true;
            btnSaveMain.Enabled = false;

            try
            {
                bool flag = SaveDBMain();

                if (flag)
                {
                    bMainQuery = false;
                    btnSaveFlagMain = 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,
                            PbStorageGlodCache.sportInfo.baseSpotNo,
                            "G" + actualForLimsMain.actualNo,
                            2), System.Drawing.Imaging.ImageFormat.Jpeg);

                    }
                    catch (Exception ex)
                    {
                        l.WriteLog(8, "截图失败");
                    }
                    #endregion

                    try
                    {
                        QueryInfo();
                    }
                    catch { }

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

        private bool SaveDBMain()
        {
            MeterWorkStorageActual mwraf = new MeterWorkStorageActual();
            
            mwraf.actualNo = actualForLimsMain.actualNo;
            mwraf.memo = txtMEMOMain.Text.Trim();
            
            mwraf.actualWeight = ucStorageWeightG2.getWgt();
            mwraf.netWeight = ucStorageWeightG2.getWgt();
            List<MeterWorkStorageActual> ltU = new List<MeterWorkStorageActual>();
            ltU.Add(mwraf);

            RESTfulResult<int> rm = actualService.doUpdateWf(ltU);
            if (rm.Succeed)
            {
                setMsgInfo(txtMsgInfoM, $"批次：{txtBATCH_NOMain.Text.Trim()},块号：{txtPACKAGE_NOMain.Value}，保存成功", "");
                return true;
            }
            else
            {
                setMsgInfo(txtMsgInfoM, "保存失败：" + rm.Message, "");
                l.WriteLog(8, "保存失败：" + rm.Message);
                return false;
            }
        }
        #endregion

        /// <summary>
        /// 如果输入了批次号则只查一个批次的数据，如果没有批次号则查当天所有的
        /// 查询的数据是主秤计量的数据
        /// </summary>
        private void QueryInfo()
        {
            if (PbStorageGlodCache.sportInfo != null)
            {
                DataTable dtSj = dataTable1.Clone();

                RESTfulResult<List<MeterWorkStorageActual>> rms = actualService.doQueryWf(new MeterWorkStorageActual { valueFlag = "1", baseSpotNo = PbStorageGlodCache.sportInfo.baseSpotNo, batchNo = txtBATCH_NOMain.Text.Trim() });
                if (rms.Succeed && rms.Data != null && rms.Data.Count > 0)
                {
                    rms.Data = rms.Data.Where(s => s.netWeight != null && s.netWeight > 0).ToList();
                    if (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;
                    }
                }
            }
        }

      
        #endregion

        #region 数据初始清理
        private void Clean()
        {
            updateSport("");
            //*
            PbStorageGlodCache.sportInfo = null;
            PbStorageGlodCache.collectM = null;
            PbStorageGlodCache.collectF = null;

            CleanForm();
            //*/
        }

        private void CleanForm()
        {
            txtMatterNo.Text = "";
            txtGrade.Text = "";
            txtStandard.Text = "";
            txtBLOCK_NUM.Value = 0;
            txtBATCH_NO.Text = "";
            txtPRODUCT_DATE.Value = DateTime.Now;
            txtPACKAGE_NO.Value = 0;
            txtMEMO.Text = "";
            txtFirst_WEIGHT.Value = 0;
            txtMsgInfoV.Text = "";

            txtMatterNoMain.Text = "";
            txtGradeMain.Text = "";
            txtStandardMain.Text = "";
            txtBLOCK_NUMMain.Value = 0;
            txtBATCH_NOMain.Text = "";
            txtPRODUCT_DATEMain.Value = DateTime.Now;
            txtPACKAGE_NOMain.Value = 0;
            txtMEMOMain.Text = "";
            txtMsgInfoM.Text = "";



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

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

            ucStorageWeightG2.setWgt(0);
            ucStorageWeightG2.setStable(true);
        }
        #endregion

        #region 声音播放，现场无音箱等，所以注释
        private bool SoudVoice(string soundName)
        {
            //string fileUrl = string.Format("{0}\\Sound\\{1}", AppDomain.CurrentDomain.SetupInformation.ApplicationBase, soundName);
            try
            {
                //play_ls = new SoundPlayer(fileUrl);
                //play_ls.Play();
                return true;
            }
            catch
            {
                return false;
            }
        }
        #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;
                }
            }
        }

        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 (PbStorageGlodCache.sportInfo != null && urg.Cells["baseSpotNo"].Text == PbStorageGlodCache.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;
                btnSave.Enabled = false;
                btnSaveMain.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;
                        }


                        
                        PbStorageGlodCache.sportInfo = PbStorageGlodCache.sportInfos.Where(s => s.baseSpotNo == ugr.Cells["baseSpotNo"].Text.Trim()).FirstOrDefault();

                        string pointM = lmo.Where(s => s.baseSpotNo == PbStorageGlodCache.sportInfo.baseSpotNo && s.weightFlag == "2").FirstOrDefault()?.pointNo;
                        string pointF = lmo.Where(s => s.baseSpotNo == PbStorageGlodCache.sportInfo.baseSpotNo && s.weightFlag == "1").FirstOrDefault()?.pointNo;


                        collectionF.Start(new string[1] { pointF });
                        collectionM.Start(new string[1] { pointM });

                        btnStart.BackColor = Color.Red;
                        btnStart.Text = "释放";

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

                        //controlIp
                        updateSport(_controlIp);


                        #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}'", PbStorageGlodCache.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();

                        #endregion
                    }
                }
                else
                {
                    try { collectionF.Stop(); }
                    catch { }
                    try { collectionM.Stop(); }
                    catch { }

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

                    btnStart.BackColor = Color.DodgerBlue;
                    btnStart.Text = "接管";

                    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;
                btnSave.Enabled = true;
                btnSaveMain.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, (PbStorageGlodCache.sportInfo == null ? "" : PbStorageGlodCache.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 (PbStorageGlodCache.sportInfo != null && PbStorageGlodCache.sportInfo.baseSpotNo != null)
                {
                    RESTfulResult<string> rm = noteService.doAddWf(new MeterMonitorNote
                    {
                        baseSpotNo = PbStorageGlodCache.sportInfo.baseSpotNo,
                        baseSpotName = PbStorageGlodCache.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)
                {
                    //PbStorageGlodCache.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);
            }
        }

        bool bTest = false;
        //*
        private void button1_Click(object sender, EventArgs e)
        {
            bTest = !bTest;
            if (bTest) 
            {
                ucStorageWeightG1.setWgt(1000);
                ucStorageWeightG1.setStable(true);
                PbStorageGlodCache.collectF = new StorageCollectModel
                {
                    mainWgt = 1000,
                    pointid = "CAR24"
                };

                /*
                ucStorageWeightG2.setWgt(1000);
                ucStorageWeightG2.setStable(true);
                PbStorageGlodCache.collectM = new StorageCollectModel
                {
                    mainWgt = 1000,
                    pointid = "CAR25"
                };
                //*/
            }
        }
        //*/

        //完成计量后会设置为false，当没有进行查询且重量小于10g的情况下进行一次查询
        bool bMainQuery = false;
        bool bFQuery = false;

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

            if (PbStorageGlodCache.sportInfo != null)
            {
                #region 副秤保存
                if (ucStorageWeightG1.getWgt() < 10)
                {
                    btnSaveFlag = false;
                    if (!btnSave.Enabled)
                    {
                        btnSave.Enabled = true;
                    }
                    iCntTime = 0;

                    try
                    {
                        if (!bFQuery && !btnSaveFlag)
                        {
                            if (txtBLOCK_NUM.Value > 0)
                            {
                                bFQuery = true;
                                if (txtPACKAGE_NO.Text.Trim() == "")
                                {
                                    txtPACKAGE_NO.Value = 0;
                                }
                                else
                                {
                                    int m = Convert.ToInt32(txtPACKAGE_NO.Text.Trim()) + 1;
                                    if (m >= txtBLOCK_NUM.Value)
                                    {
                                        try
                                        {
                                            if (txtBATCH_NO.Text.Trim().ToUpper().IndexOf("SIX") == 0)
                                            {
                                                //金锭SI企业代码，X-1kg代码，21年代码，001批次，01块号  SIX2100101
                                                txtBATCH_NO.Text = $"SIX{Convert.ToInt32(txtBATCH_NO.Text.Trim().Substring(3, txtBATCH_NO.Text.Trim().Length - 3)) + 1}";
                                            }
                                            else if (txtBATCH_NO.Text.Trim().ToUpper().IndexOf("SI") == 0)
                                            {
                                                //银锭一批十块，第二块是SI2100011，第三块是SI2100012，一直到SI2100019
                                                txtBATCH_NO.Text = $"SI{Convert.ToInt32(txtBATCH_NO.Text.Trim().Substring(2, txtBATCH_NO.Text.Trim().Length - 2)) + 1}";
                                            }
                                            else if (txtBATCH_NO.Text.Trim().ToUpper().IndexOf("Z") == 0)
                                            {
                                                //12.5Kg的批号格式是Z21000101，一批一块
                                                txtBATCH_NO.Text = $"Z{Convert.ToInt32(txtBATCH_NO.Text.Trim().Substring(1, txtBATCH_NO.Text.Trim().Length - 1)) + 1}";
                                            }
                                            else
                                            {
                                                txtMsgInfoM.Text = $"批号【{txtBATCH_NO.Text}】格式不在提供的累加规则格式中，请手动输入新的批号!";
                                                txtBATCH_NO.Text = "";
                                                txtBATCH_NO.Focus();
                                            }
                                        }
                                        catch
                                        {
                                            txtMsgInfoM.Text = $"批号【{txtBATCH_NO.Text}】格式不在提供的累加规则格式中，请手动输入新的批号!";
                                            txtBATCH_NO.Text = "";
                                            txtBATCH_NO.Focus();
                                        }

                                        txtPACKAGE_NO.Value = 0;
                                    }
                                    else
                                    {
                                        txtPACKAGE_NO.Value += 1;
                                    }
                                }
                            }
                        }
                    }
                    catch { }
                }
                else
                {
                    if (ucStorageWeightG1.isGreen)
                    {
                        iCntTime++;
                        if (iCntTime > txtTimeLength.Value)
                        {
                            iCntTime = txtTimeLength.Value;
                        }
                    }
                    else
                    {
                        iCntTime = 0;
                    }
                }


                if (iCntTime >= txtTimeLength.Value && cbAuto.Checked && ucStorageWeightG1.getWgt() > 100 && ucStorageWeightG1.isGreen && txtBATCH_NO.Text.Trim() != "")
                {
                    btnClickSave();
                }
                #endregion

                #region 主秤保存
                if (ucStorageWeightG2.getWgt() < 10)
                {
                    //在自动计量的情况下，自动找副秤计量的最后一条数据，然后填充。假如要手动录入的情况不要选自动计量
                    if (cbAuto.Checked)
                    {
                        if (!bMainQuery && !btnSaveFlagMain)
                        {
                            txtMatterNoMain.Text = "";
                            txtGradeMain.Text = "";
                            txtStandardMain.Text = "";
                            txtBLOCK_NUMMain.Value = 0;
                            txtBATCH_NOMain.Text = "";
                            txtPACKAGE_NOMain.Value = 0;
                            txtMEMOMain.Text = "";
                            txtMsgInfoM.Text = "";

                            if (txtBATCH_NOMain.Text.Trim() == "") //如果前一次已经计量完成或者还没有给定批次信息的情况下，则查找最近的副秤计量数据填充
                            {
                                bMainQuery = true;
                                BindMainControlValue();
                            }
                        }
                    }

                    btnSaveFlagMain = false;
                    if (!btnSaveMain.Enabled)
                    {
                        btnSaveMain.Enabled = true;
                    }
                    iCntMainTIme = 0;
                }
                else
                {
                    //在自动计量的情况下，自动找副秤计量的最后一条数据，然后填充。假如要手动录入的情况不要选自动计量
                    if (cbAuto.Checked)
                    {
                        if (txtBATCH_NOMain.Text.Trim() == "") //还没有给定批次信息且重量大于10g的情况下，则查找最近的副秤计量数据填充
                        {
                            BindMainControlValue();
                        }
                    }

                    if (ucStorageWeightG2.isGreen)
                    {
                        iCntMainTIme++;
                        if (iCntMainTIme > txtTimeLength.Value)
                        {
                            iCntMainTIme = txtTimeLength.Value;
                        }
                    }
                    else
                    {
                        iCntMainTIme = 0;
                    }
                }

                if (iCntMainTIme >= txtTimeLength.Value && cbAuto.Checked && ucStorageWeightG2.getWgt() > 100 && ucStorageWeightG2.isGreen && txtBATCH_NOMain.Text.Trim() != "")
                {
                    btnClickSaveMain();
                }
                #endregion
            }
        }


        private void BindMainControlValue() 
        {
            actualForLimsMain = null;
            string sqlLims = $@"select actual_no     actualNo,
                                       prediction_no predictionNo,
                                       batch_no      batchNo,
                                       product_no    productNo,
                                       product_name  productName,
                                       grade_no      gradeNo,
                                       grade_name    gradeName,
                                       standard_no   standardNo,
                                       standard_name standardName,
                                       package_no    packageNo,
                                       block_num     blockNum,
                                       refer_weight  referWeight
                                    from METER_WORK_STORAGE_ACTUAL t
                                    where base_spot_no = '{PbStorageGlodCache.sportInfo.baseSpotNo}'
                                    and value_flag = '1'
                                    and t.prediction_no = (select max(prediction_no)
                                                            from METER_WORK_STORAGE_ACTUAL
                                                            where base_spot_no = '{PbStorageGlodCache.sportInfo.baseSpotNo}'
                                                                and value_flag = '1' and (net_weight is null or net_weight<1) )";
            PbModelDbService<List<MeterWorkStorageActual>> pbModelDbServiceLims = new PbModelDbService<List<MeterWorkStorageActual>>();
            RESTfulResult<List<MeterWorkStorageActual>> rESLims = pbModelDbServiceLims.executeSqlDataWf(sqlLims);
            if (rESLims.Succeed && rESLims.Data != null && rESLims.Data.Count > 0)
            {
                txtBATCH_NOMain.Text = rESLims.Data[0].batchNo;
                txtPACKAGE_NOMain.Value = Convert.ToInt32(rESLims.Data[0].packageNo);

                txtMatterNoMain.Text = rESLims.Data[0].productName;
                txtGradeMain.Text = rESLims.Data[0].gradeName;
                txtStandardMain.Text = rESLims.Data[0].standardName;
                txtBLOCK_NUMMain.Value = Convert.ToInt32(rESLims.Data[0].blockNum);
                txtMEMOMain.Text = rESLims.Data[0].memo;
                txtFirst_WEIGHT.Value = (decimal)rESLims.Data[0].referWeight.Value;
                actualForLimsMain = rESLims.Data[0];
            }
            else 
            {
                //setMsgInfo(txtMsgInfoM, "当前计量点不存在已进行副秤计量未进行主秤计量的数据", "");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            bTest = !bTest;
            if (bTest)
            {
                ucStorageWeightG2.setWgt(800);
                ucStorageWeightG2.setStable(true);
                PbStorageGlodCache.collectM = new StorageCollectModel
                {
                    mainWgt = 1000,
                    pointid = "CAR25"
                };
            }
        }

        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;

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

        private void txtBATCH_NO_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13) 
            {
                BatchNoChange();
            }
        }

        /*
        private void txtBATCH_NO_ValueChanged(object sender, EventArgs e)
        {
            BatchNoChange();
        }
        //*/

        private void BatchNoChange() 
        {
            actualForLims = null;
            
            if (bTest)
            {
                actualForLims = new MeterWorkStorageActual
                {
                    productNo = "0001",
                    productName = txtMatterNo.Text,
                    gradeNo = "0001",
                    gradeName = txtGrade.Text,
                    standardNo = "测试标准",
                    standardName = txtStandard.Text
                };
                return;
            }
            //return;
            
            txtMatterNo.Text = "";
            txtGrade.Text = "";
            txtStandard.Text = "";

            //根据批次号查询检化验的表数据，此sql需丁老板那边给定
            string sqlLims = $@"select batch_no batchNo,mat_no productNo,mat_name productName,grade_no_jd gradeNo,grade_name_jd gradeName from LIMS_SAMPLE_JUDGE
                                  where batch_no='{txtBATCH_NO.Text.Trim()}";
            PbModelDbService<List<MeterWorkStorageActual>> pbModelDbServiceLims = new PbModelDbService<List<MeterWorkStorageActual>>();
            RESTfulResult<List<MeterWorkStorageActual>> rESLims = pbModelDbServiceLims.executeSqlDataWf(sqlLims);
            if (rESLims.Succeed && rESLims.Data != null && rESLims.Data.Count > 0)
            {
                txtMatterNo.Text = rESLims.Data[0].productName;
                txtGrade.Text = rESLims.Data[0].gradeName;
                //txtStandard.Text = rESLims.Data[0].standardName;
                txtMsgInfoV.Text = "";

                actualForLims = rESLims.Data[0];
            }
            else
            {
                txtMsgInfoV.Text = $"批号[{txtBATCH_NO.Text.Trim()}]找不到检验数据，时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}\n\r";
            }
        }

    }
}
