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

namespace StorageMeterSystem
{
    public partial class frmMainBF : Form
    {
        #region
        List<StorageCollectModel> ltScModel = new List<StorageCollectModel>();
        private BaseDbCls bd = new BaseDbCls();
        Log l = Log.GetInstance();
        CoreAppUser appUser = null;
        int iPic = 0;

        PbModelDbService<string> pdb = new PbModelDbService<string>();
        MeterMonitorNoteService noteService = new MeterMonitorNoteService();
        MeterWorkStockOnlineService onlineService = new MeterWorkStockOnlineService();
        MeterWorkStorageOnlineService stOnlineService = new MeterWorkStorageOnlineService();

        StorageDataDbCollection collection = new StorageDataDbCollection();
        MeterWorkStorageActualService actualService = new MeterWorkStorageActualService();

        MeterWorkCalibrationMainService calibrationMainService = new MeterWorkCalibrationMainService();

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

        public frmMainBF()
        {
            InitializeComponent();
        }

        #region 事件处理
        private void frmMain_Load(object sender, EventArgs e)
        {
            ucStorageWeightKg2.Visible = false;
            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;


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

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

            DataTable dt = dtJGPointInfo.Clone();

            foreach (MeterBaseSpotInfo mbsi in PbStorageCache.sportInfos)
            {
                int icnt = PbStorageCache.ltMonitor.Where(s => s.baseSpotNo == mbsi.baseSpotNo).Count();
                if (icnt > 0)
                {
                    DataRow dr = dt.NewRow();
                    dr["baseSpotNo"] = mbsi.baseSpotNo;
                    dr["baseSpotName"] = mbsi.baseSpotName;
                    dr["validFlag"] = "";//未接管
                    dt.Rows.Add(dr);
                }
            }
            
            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)
            {
                ValueList vlistMat = new ValueList();
                foreach (ComBaseInfo cbi in rmType.Data)
                {
                    vlistMat.ValueListItems.Add(cbi.baseCode, cbi.baseName);

                }
                cmbMatterNo.ValueList = vlistMat;
            }
            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)
            {
                ValueList vlistGrade = new ValueList();
                foreach (ComBaseInfo cbi in rmType.Data)
                {
                    vlistGrade.ValueListItems.Add(cbi.baseCode, cbi.baseName);

                }
                cmbGrade.ValueList = vlistGrade;
            }
            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)
            {
                ValueList vlistStandard = new ValueList();
                foreach (ComBaseInfo cbi in rmType.Data)
                {
                    vlistStandard.ValueListItems.Add(cbi.baseCode, cbi.baseName);

                }
                cmbStandard.ValueList = vlistStandard;
            }
            else
            {
                MessageBox.Show("标准载入失败");
                return;
            }
            #endregion

            //imageControl.Start();

            collection.EventDataCollectionArgs += new StorageEventDbCollection(EventData);
            collection.Start();

            timer1.Start();
        }

        public void EventData(object o, List<StorageCollectModel> lt)
        {
            //这里每隔0.5秒执行一次
            try
            {
                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);
                    }

                    if (PbStorageCache.sportInfo != null && PbStorageCache.sportInfo.baseSpotNo == sm.pointid)
                    {
                        ucStorageWeightKg1.setWgt(sm.mainWgt);
                        ucStorageWeightKg1.setStable(sm.mainWeightStatus != 1 ? true : false);
                        ucStorageWeightKg2.setWgt(sm.viceWgt);
                        ucStorageWeightKg2.setStable(sm.mainWeightStatus != 1 ? true : false);
                    }
                }
            }
            catch (Exception ex)
            {
                l.WriteLog(0, "frmMeterMain.EventData异常6：" + 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 btnPage_Click(object sender, EventArgs e)
        {
            if (PbStorageCache.sportInfo != null)
            {
                string sql = string.Format("update meter_base_spot_info set COUNT_NUM = '{0}' where base_spot_no='{1}'", txtPageNum.Value, PbStorageCache.sportInfo.baseSpotNo);
                RESTfulResult<string> rm = pdb.executeSqlDataWf(sql);
                if (rm.Succeed)
                {
                    WriteMonitorNote("修改计量点信息纸张总数：" + txtPageNum.Value);
                }
            }
            else 
            {
                txtMsgInfo.Text = "当前未接管任何计量点，无法换纸";
            }
        }

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

            if (!rm.Succeed)
            {
                l.WriteLog(5, "静态衡写入操作日志异常：" + content);
            }
        }

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

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

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                Clean();
            }
            catch { }

            //imageControl.Stop();

            timer1.Stop();

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

        validCalibration vCalib = new validCalibration();
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (PbStorageCache.sportInfo == null) return;

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

            #region
            if (cmbMatterNo.Value == null)
            {
                MessageBox.Show("请选择产品名称");
                return;
            }

            if (cmbGrade.Value == null) 
            {
                MessageBox.Show("请选择牌号");
                return;
            }

            if (cmbStandard.Value == null)
            {
                MessageBox.Show("请选择标准");
                return;
            }
            #endregion



                        DialogResult dr = MessageBox.Show("是否确认保存当前计量数据？", "提示", MessageBoxButtons.OKCancel);
            if (dr == DialogResult.OK)
            {
                btnSave.Enabled = false;
                try
                {
                    string actNo = "";
                    bool flag = SaveDB(out actNo);

                    if (flag)
                    {
                        #region 截取图片信息
                        try
                        {
                            //* 截取屏幕信息
                            Point screenPoint = this.PointToScreen(new Point());
                            Rectangle rect = new Rectangle(screenPoint, this.Size);
                            Image img = new Bitmap(rect.Width, rect.Height);
                            Graphics g = Graphics.FromImage(img);
                            g.CopyFromScreen(rect.X - 1, rect.Y - 1, 0, 0, rect.Size);//"D://file/1.jpg"
                            img.Save(string.Format("{0}imgShort\\tempImg\\{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);
                            //*/
                        }
                        catch
                        {
                            l.WriteLog(5, "截图失败");
                        }
                        #endregion

                        try
                        {
                            QueryInfo();
                        }
                        catch { }
                        CleanForm();

                    }
                    btnSave.Enabled = true;
                }
                catch (Exception ex)
                {
                    btnSave.Enabled = true;

                    txtMsgInfo.Text = "保存失败：" + ex.Message.Trim();
                    l.WriteLog(5, "保存失败：" + ex.Message.Trim());
                }
            }
            else
            {
                btnSave.Enabled = true;
            }
        }

        int iCnt = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            iCnt++;
            if (iCnt % 2 == 0)
            {
                //每秒验证实时监控是否接管
                RESTfulResult<List<MeterWorkStockOnline>> rms = onlineService.doQueryWf(new MeterWorkStockOnline { validFlag = "1" });
                if (rms.Succeed && rms.Data != null && rms.Data.Count > 0)
                {
                    //, userId = appUser.userid
                    if (PbStorageCache.ltCollect == null || PbStorageCache.ltCollect.Count == 0)
                    {
                        Clean();
                        return;
                    }

                    foreach (UltraGridRow ugPW in ultraGridPW.Rows) 
                    {
                        MeterWorkStockOnline mwso = rms.Data.Where(s => s.baseSpotNo == ugPW.Cells["baseSpotNo"].Text.Trim()).FirstOrDefault();
                        if (mwso != null && !string.IsNullOrEmpty(mwso.userId))
                        {
                            ugPW.Cells["validFlag"].Value = "已接管";

                            if (mwso.userId == appUser.userid)
                            {
                                PbStorageCache.collect = PbStorageCache.ltCollect.Where(s => s.pointid == mwso.baseSpotNo).FirstOrDefault();
                                PbStorageCache.sportInfo = PbStorageCache.sportInfos.Where(s => s.baseSpotNo == mwso.baseSpotNo).FirstOrDefault();

                                if (btnStart.Text == "自动派位")
                                {
                                    btnStart.Text = "取消接管";

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

                                    QueryXC();
                                }
                            }
                        }
                        else
                        {
                            ugPW.Cells["validFlag"].Value = "未接管";
                        }
                    }

                    //ClsControlPack.RefreshAndAutoSize(ultraGridPW);
                }
            }

            if (iCnt % 4 == 0)
            {
                if (!bGQ)
                {
                    RESTfulResult<string> rm = stOnlineService.doSaveWf(new MeterWorkStorageOnline { userId = appUser.userid }); //实时在线写入，每隔2秒一次在线状态
                    iCnt = 0;
                }
            }
        }

        private void btnCheckBalance_Click(object sender, EventArgs e)
        {
            if (PbStorageCache.collect != null)
            {
                frmCalibration fc = new frmCalibration();
                fc.userId = appUser.userid;
                fc.userName = appUser.username;
                if (fc.ShowDialog() == DialogResult.OK)
                {
                    txtMsgInfo.Text = "校秤完成";
                    QueryXC();
                }
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (btnStart.Text == "自动派位")
            {
                if (PbStorageCache.sportInfo != null)
                {
                    btnStart.BackColor = Color.Red;
                    btnStart.Text = "取消接管";
                }
            }
            else
            {
                if (PbStorageCache.sportInfo != null)
                {
                    Clean();
                }
                btnStart.BackColor = Color.DodgerBlue;
                btnStart.Text = "自动派位";
            }
        }

        bool bGQ = false;
        private void btnGQ_Click(object sender, EventArgs e)
        {
            if (btnGQ.Text == "挂起")
            {
                btnGQ.Text = "取消挂起";
                btnGQ.BackColor = Color.Red;
                bGQ = true;
                btnStart.Enabled = false;

                btnStart.BackColor = Color.DodgerBlue;
                btnStart.Text = "自动派位";

                if (PbStorageCache.sportInfo != null)
                {
                    Clean();
                }

                try
                {
                    //让用户处于掉线状态
                    string sql = @"update Meter_Work_Storage_Online set last_time=sysdate-1 where user_id='" + appUser.userid + "'";
                    PbModelDbService<string> pb = new PbModelDbService<string>();
                    RESTfulResult<string> rm = pb.executeSqlDataWf(sql);
                }
                catch { }
            }
            else
            {
                btnGQ.Text = "挂起"; //改为非挂起状态
                btnGQ.BackColor = Color.DodgerBlue;
                bGQ = false;
                btnStart.Enabled = true;
            }
        }

        private bool SaveDB(out string actNo)
        {
            actNo = "";
            MeterWorkStorageActual mwraf = new MeterWorkStorageActual();
            mwraf.batchNo = txtBATCH_NO.Text.Trim();
            mwraf.memo = txtMEMO.Text.Trim();
            mwraf.valueFlag = "1";
            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.bucketNo = txtBUCKET_NO.Text;
            mwraf.grossWeight = PbStorageCache.collect.mainWgt;
            mwraf.tareWeight = Convert.ToInt32(txtTARE_WEIGHT.Value);
            mwraf.combinPackageNo = txtCOMBIN_NO.Text.Trim();
            //mwraf.weightType = "0";
            mwraf.baseSpotNo = PbStorageCache.sportInfo.baseSpotNo;
            mwraf.baseSpotNo = PbStorageCache.sportInfo.baseSpotName;

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

        /// <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.collect.pointid;
                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);
            }
        }
        #endregion

        #region 数据初始清理
        private void Clean()
        {
            //*
            PbStorageCache.videoInfo = null;
            //PbStorageCache.dtStartTime = null;
            PbStorageCache.sportInfo = null;
            PbStorageCache.collect = null;
            
            //退出语音登录
            try
            {
                VoiceClose();
                IPVideoClose();
            }
            catch (Exception ex) { }

            try 
            {
                MeterWorkStockOnline mwmUpdate = new MeterWorkStockOnline
                {
                    pointNo = PbStorageCache.sportInfo.baseSpotNo,
                    userId = "",
                    userIp = ""
                };
                RESTfulResult<string> rm = onlineService.doSaveWf(mwmUpdate);
            } catch { }

            setPanelRemovenfo(panel1);

            CleanForm();
            //*/
        }

        private void CleanForm()
        {
            cmbMatterNo.Text = "";
            cmbMatterNo.SelectedIndex = -1;
            txtGroess.Text = "";
            txtPageNum.Value = 0;
            cmbGrade.Text = "";
            cmbGrade.SelectedIndex = -1;
            cmbStandard.Text = "";
            cmbStandard.SelectedIndex = -1;
            txtBLOCK_NUM.Value = 0;
            txtBATCH_NO.Text = "";
            txtPRODUCT_DATE.Value = DateTime.Now;
            txtPACKAGE_NO.Text = "";
            txtSEAL_NO.Text = "";
            txtBUCKET_NO.Text = "";
            txtCOMBIN_NO.Text = "";
            txtMEMO.Text = "";
            txtTARE_WEIGHT.Value = 0;


            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.setWgt(0);
            ucStorageWeightKg2.setStable(true);
        }
        #endregion

        #region 对讲代码
        /// <summary>
        /// 硬盘录像机登录
        /// </summary>
        DhCameraShot cameraShotMain = new DhCameraShot();

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

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

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

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

        }

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

        }

        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);

                        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;
                }
            }
        }

        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.collect != null && urg.Cells["baseSpotNo"].Text == PbStorageCache.collect.pointid)
                    {
                        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) + "";
            }
        }
    }
}
