using com.hnshituo.core.webapp.vo;
using Common;
using Common.vo.pb;
using Infragistics.Win.UltraWinGrid;
using JC_MeasuringSystem;
using MeterModuleLibrary;
using MeterPlugInLibrary;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Threading;
using System.Windows.Forms;

namespace BeltScaleSystem

{
    public partial class frmBeltScale : Form
    {
        private BeltScaleDataCollectionControl collection = new BeltScaleDataCollectionControl(); //实时表数据采集



        public frmBeltScale()
        {
            InitializeComponent();
        }
       

        private Log lg = Log.GetInstance();
        private BaseDbCls bd = new BaseDbCls();


        private string userId = "", userName = "";
        private string[] strPntNoCollect = null;
        private List<string> strPntNoList = new List<string>();
        private CoreAppUser userinfo = null;


        private string strIpAddress = "";

        private MeterBaseScalePointService monitorService = new MeterBaseScalePointService();

        private void frmMonitor_Load(object sender, EventArgs e)
        {
            PbCacheMonitor.frmMsgClosingTime = DateTime.Now;

           // timer2.Start();
            userId = ((ST_MainForm)(this.MdiParent)).UserID;
            userName = ((ST_MainForm)(this.MdiParent)).UserName;
            userinfo = ((ST_MainForm)(this.MdiParent)).AppUser;

            #region 载入计量点的信息

            bd.setBaseDbScalePoint();
           // bd.getDbBaseScale();
            setGridData();
            strIpAddress = GetIP();
            foreach (UltraGridRow ugr in ultraGridPW.Rows)
            {
                //strPntNoList.Add(ugr.Cells["collectionCodeA"].Text.Trim());//添加所有的计量点
                //strPntNoList.Add(ugr.Cells["collectionCodeB"].Text.Trim());//添加所有的计量点

                if (ugr.Cells["monitorUserNo"].Text.Trim() != "" && ugr.Cells["monitorUserNo"].Text.Trim() == userName)
                {
                    ugr.Cells["UNCK"].Value = true;
                    BeltScaleMeterControl uc = new BeltScaleMeterControl();
                    //uc.strCollectNo = ugr.Cells["collectionCode"].Text.Trim();
                    uc.Name = "uc" + ugr.Cells["baseSpotNo"].Text;
                    uc.sUserId = userId;
                    uc.sUserName = userName;
                    uc.sIpAddress = strIpAddress;
                    uc.sPointNo = ugr.Cells["baseSpotNo"].Text;
                    uc.sPointName = ugr.Cells["baseSpotName"].Text;
                    uc.BorderStyle = BorderStyle.FixedSingle;

                    flPanel.Controls.Add(uc);
                }
                else
                {
                    ugr.Cells["UNCK"].Value = false;
                }
            }
            //strPntNoCollect = strPntNoList.ToArray();//加载所有的计量点，不管有没有接管
            //collection.EventBeltScaleDataCollectionArgs += new EventBeltScaleDataCollection(weightCollect);//数据采集解析
           // collection.Start(new string[5] { "CAR40", "CAR41", "CAR42", "CAR43", "CAR44" });//数据采集启动

           //collection.Start(strPntNoCollect);//数据采集启动

           // ClsControlPack.RefreshAndAutoSize(this.ultraGridPW);

            #endregion 载入计量点的信息

            //thVoice.Start();
        }

        /// <summary>
        /// 计量点信息
        /// </summary>
        public void setGridData()
        {
            DataTable dt = dtJGPointInfo.Clone();
            if (PbCacheMonitor.sportInfoList!=null&& PbCacheMonitor.sportInfoList.Count>0&& PbCacheMonitor.ltMeterBaseScalePoint != null && PbCacheMonitor.ltMeterBaseScalePoint.Count > 0)
            {

                foreach (MeterBaseScalePoint mwm in PbCacheMonitor.ltMeterBaseScalePoint)
                {
                    if (!mwm.scalePointName.Contains("焦粉")&&!mwm.scalePointName.Contains("备用")) {
                        DataRow dr = dt.NewRow();
                        dr["scalePointNo"] = mwm.scalePointNo;
                        dr["baseSpotNo"] = mwm.baseSpotNo;
                        dr["baseSpotName"] = mwm.baseSpotName;
                        dr["monitorUserNo"] = mwm.monitorUserNo;
                        dr["collectionCodeA"] = mwm.collectionCode;
                        dr["collectionCodeB"] = mwm.collectionCodeB;
                        dt.Rows.Add(dr);
                    }
                  
                }

                //for (int i=0; i<PbCacheMonitor.sportInfoList.Count;i++) {
                //    DataRow dr = dt.NewRow();
                //    dr["baseSpotNo"] = PbCacheMonitor.sportInfoList[i].baseSpotNo;
                //    dr["baseSpotName"] = PbCacheMonitor.sportInfoList[i].baseSpotName;
                //    for (int j= 0; j < PbCacheMonitor.ltMeterBaseScalePoint.Count;j++)
                //    {
                //        if (PbCacheMonitor.ltMeterBaseScalePoint[j].baseSpotNo == PbCacheMonitor.sportInfoList[i].baseSpotNo &&
                //            PbCacheMonitor.ltMeterBaseScalePoint[j].scalePointNo.Contains("001")){
                //            dr["monitorUserNo"] = PbCacheMonitor.ltMeterBaseScalePoint[j].monitorUserNo;
                //            dr["collectionCodeA"] = PbCacheMonitor.ltMeterBaseScalePoint[j].collectionCode;
                //            dr["scalePointNo"] = PbCacheMonitor.ltMeterBaseScalePoint[j].scalePointNo;
                //        }
                //        if (PbCacheMonitor.ltMeterBaseScalePoint[j].baseSpotNo == PbCacheMonitor.sportInfoList[i].baseSpotNo && 
                //            PbCacheMonitor.ltMeterBaseScalePoint[j].scalePointNo.Contains("002")) {
                //            dr["collectionCodeB"] = PbCacheMonitor.ltMeterBaseScalePoint[j].collectionCode;
                            
                //        }
                        
                //    }
                //        dt.Rows.Add(dr);
                //}
                
            }

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

        private string openPointNo = "";

        private void VoiceOption(BeltScaleMeterControl um, bool bMainUm)
        {
            if (PbCacheMonitor.ltMeterBaseScalePoint == null || PbCacheMonitor.ltMeterBaseScalePoint.Count == 0)
            {
                MessageBox.Show("获取计量点信息异常，请稍后再试");
                return;
            }

            MeterBaseScalePoint monitor = PbCacheMonitor.ltMeterBaseScalePoint.Where(s => s.baseSpotNo == um.sPointNo).FirstOrDefault();
            if (monitor == null)
            {
                MessageBox.Show("获取当前计量点信息异常，请稍后再试");
                return;
            }
        }

        /// <summary>
        /// 修改数据到接管表
        /// </summary>
        private void UpdateCarijeg(MeterBaseScalePoint monitor)
        {
            RESTfulResult<string> rms = monitorService.doUpdateWf(monitor);
            if (!rms.Succeed)
            {
                lg.WriteLog(4, "写入数据失败");
            }
        }

        /// <summary>
        /// 重量采集
        /// </summary>
        /// <param name="o"></param>
        /// <param name="e"></param>
        private void weightCollect(object o, List<CollectModel> e)
        {
            try
            {
                if (e != null)
                {
                    foreach (var item in e)
                    {
                        foreach (MeterBaseScalePoint mwm in PbCacheMonitor.ltMeterBaseScalePoint)
                        {
                            if (mwm.collectionCode.Equals(item.pointid))
                            {
                                mwm.weight = item.weight;
                            }
                            if (mwm.collectionCodeB.Equals(item.pointid))
                            {
                                mwm.weightB = item.weight;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 重点！！！
        /// 从主界面向用户控件中插入信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer2_Tick(object sender, EventArgs e)
        {
            try
            {
                foreach (MeterBaseScalePoint mon in PbCacheMonitor.ltMeterBaseScalePoint)
                {
                    foreach (Control cn in flPanel.Controls)
                    {
                        if (cn.Name.Contains("uc"))
                        {
                            BeltScaleMeterControl uc = cn as BeltScaleMeterControl;
                            if (uc.sPointNo == mon.baseSpotNo)
                            {
                             //   uc.rowPointInfo = mon;
                            }
                        }
                    }
                }

                //if (bd.getDb())
                //{
                   
                //}
                //else
                //{
                //    lg.WriteLog(4, "未找到实时监控数据");
                //}

                //*/
            }
            catch (Exception ex)
            {
                lg.WriteLog(4, "数据库连接异常"+ex.Message);
            }
        }

        private void ultraGridPW_CellChange(object sender, CellEventArgs e)
        {
            ultraGridPW.UpdateData();
            UltraGridRow ugr = ultraGridPW.ActiveRow;
            if (ugr != null)
            {
                if (ugr.Cells["UNCK"].Value.ToString().ToLower() == "false")
                {
                    BeltScaleMeterControl uc = (BeltScaleMeterControl)flPanel.Controls["uc" + ugr.Cells["baseSpotNo"].Text];
                    flPanel.Controls.RemoveByKey("uc" + ugr.Cells["baseSpotNo"].Text);
                    uc.Close();
                    RESTfulResult<string> rm = monitorService.doUpdateWf(new MeterBaseScalePoint { scalePointNo = ugr.Cells["scalePointNo"].Text.Trim(), monitorUserNo = "" });
                    if (!rm.Succeed)
                    {
                        lg.WriteLog(4, "写入取消接管信息失败");
                    }

                }
                else
                {

                    bd.setBaseDbScalePoint();
                    MeterBaseScalePoint mwm = PbCacheMonitor.ltMeterBaseScalePoint.Where(s => s.scalePointNo == ugr.Cells["scalePointNo"].Text.Trim()).FirstOrDefault();
                    //先查一次是否接管了
                    if (mwm != null && !string.IsNullOrEmpty(mwm.monitorUserNo))
                    {
                        ugr.Cells["UNCK"].Value = false;
                        MessageBox.Show("当前计量点已被账号【" + mwm.monitorUserNo + "】接管");
                        return;
                    }

                    BeltScaleMeterControl uc = new BeltScaleMeterControl();//点击数据行进行接管

                    //uc.strCollectNo = ugr.Cells["collectionCode"].Text.Trim();
                    uc.Name = "uc" + ugr.Cells["baseSpotNo"].Text;
                    uc.sUserId = userId;
                    uc.sUserName = userName;
                    uc.sIpAddress = strIpAddress;
                    uc.sPointNo = ugr.Cells["baseSpotNo"].Text;
                    uc.sPointName = ugr.Cells["baseSpotName"].Text;
                    uc.userClass = userinfo.userClass;
                    uc.userGroup = userinfo.userGroup;
                    //uc.ucMonitoringEvent += new EventHandler(ucEvent);
                    //uc.evoice += new EventVoice(setsVoice);
                    //****************************************注意下面这个**********************
                    // uc.moxaip = dtPointInfo.Rows[k]["MOXAIP"].ToString().Trim();
                    //uc.openMsg += new EventOpenMsg(OpenMsg);
                    uc.BorderStyle = BorderStyle.FixedSingle;

                  //  uc.db = db;
                    flPanel.Controls.Add(uc);
                   


                    RESTfulResult<string> rm = monitorService.doUpdateWf(new MeterBaseScalePoint { scalePointNo = ugr.Cells["scalePointNo"].Text.Trim(), monitorUserNo = userName });
                    if (!rm.Succeed)
                    {
                        lg.WriteLog(4, "写入接管信息失败");
                    }
                }
            }
        }


        /// <summary>
        /// 界面关闭方法：还原接管状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmMonitor_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
              

                List<UltraGridRow> uGrid = GridHelper.UltraGridGetChooseRows(ultraGridPW, "UNCK");
                if (uGrid.Count == 0)
                {
                    return;
                }
                foreach (UltraGridRow ugr in uGrid)
                {
                    if (ugr.Cells["UNCK"].Value.ToString().ToUpper() == "TRUE")
                    {
                        UpdateCarijeg(new MeterBaseScalePoint { scalePointNo = ugr.Cells["scalePointNo"].Text.Trim(), monitorUserNo = "", monitorUserIP = "" });
                        BeltScaleMeterControl u = (BeltScaleMeterControl)flPanel.Controls["uc" + ugr.Cells["baseSpotNo"].Text];
                        flPanel.Controls.RemoveByKey("uc" + ugr.Cells["baseSpotNo"].Text);
                        u.Close();
                        ugr.Cells["UNCK"].Value = false;
                    }
                }



            }
            catch (Exception ex)
            {
                lg.WriteLog(4, "关闭皮带秤计量异常：" + ex.Message);
            }
            finally
            {
                
            }
        }

        private void flPanel_ControlRemoved(object sender, ControlEventArgs e)
        {
           // string aa = e.Control.Name;
        }

        /// <summary>
        /// 获取IP地址
        /// </summary>
        /// <returns></returns>
        public string GetIP()
        {
            try
            {
                IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddr = ipHost.AddressList[0];
                return ipAddr.ToString();
            }
            catch (Exception ex)
            {
                Random rd = new Random();
                MessageBox.Show("GetIP方法异常，请关闭界面并稍后打开，或联系管理员！\r\n异常原因:\r\n!" + ex);
                lg.WriteLog(13, "GetIP方法异常：" + ex.Message);
                return rd.Next(99999, 999999) + "";
            }
        }
    }
}