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 StorageMeterSystem

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

        public frmHotDeliveryBelt()
        {
            InitializeComponent();
        }

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

        private string sVoice = "";
        private Thread thVoice = null;
        private VoicePlay vp = new VoicePlay();
        private string userId = "", userName = "";
        private List<string> strPntNoList = new List<string>();
        private CoreAppUser userInfo = null;
        private string strIpAddress = "";
        private string[] strPntNoCollect = null; //所有的计量点

        private DbHelper db = new DbHelper();
        private MeterBaseScalePointService monitorService = new MeterBaseScalePointService();

        private frmHotDeliveryBeltWarn fm = null;//预警界面
        public bool bMsgOpen = false; //是否打开了语音提醒

        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.setBaseDbScalePointHot();
            bd.getDbBaseScaleHot();
            setGridData();
            strIpAddress = GetIP();

            foreach (UltraGridRow ugr in ultraGridPW.Rows)
            {
                strPntNoList.Add(ugr.Cells["collectionCode"].Text.Trim());//添加所有的计量点
                if (ugr.Cells["monitorUserNo"].Text.Trim() != "")
                {
                    ugr.Cells["UNCK"].Value = true;
                }
                /*
               if (ugr.Cells["monitorUserNo"].Text.Trim() != "" && ugr.Cells["monitorUserNo"].Text.Trim() == userName && ugr.Cells["monitorUserIP"].Text.Trim() == strIpAddress)
               {
                   ugr.Cells["UNCK"].Value = true;
                   ucHotDeliveryBelt uc = new ucHotDeliveryBelt();
                   //uc.strCollectNo = ugr.Cells["collectionCode"].Text.Trim();
                   uc.Name = "uc" + ugr.Cells["scalePointNo"].Text;
                   uc.sUserId = userId;
                   uc.sUserName = userName;
                   uc.sIpAddress = strIpAddress;
                   uc.sPointNo = ugr.Cells["baseSpotNo"].Text;
                   uc.sPointName = ugr.Cells["baseSpotName"].Text;
                   //uc.ucMonitoringEvent += new EventHandler(ucEvent);
                   //uc.evoice += new EventVoice(setsVoice);
                   //****************************************注意下面这个**********************
                   // uc.moxaip = dtPointInfo.Rows[k]["MOXAIP"].ToString().Trim();
                   uc.openWarnMsgBelt += new ucHotDeliveryBelt.EventOpenWarnMsgBelt(OpenMsg);
                   //uc.rowPointInfo = null;
                   uc.BorderStyle = BorderStyle.FixedSingle;
                   uc.db = db;

                   flPanel.Controls.Add(uc);
               }
               else
               {
                   ugr.Cells["UNCK"].Value = false;
               }
                */
            }

            strPntNoCollect = strPntNoList.ToArray();//加载所有的计量点，不管有没有接管
            collection.EventHotDeliveryDataCollectionArgs += new EventHotDeliveryDataCollection(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.ltMeterBaseScalePoint != null && PbCacheMonitor.ltMeterBaseScalePoint.Count > 0)
            {
                foreach (MeterBaseScalePoint mwm in PbCacheMonitor.ltMeterBaseScalePoint)
                {
                    DataRow dr = dt.NewRow();
                    dr["scalePointNo"] = mwm.scalePointNo;
                    dr["baseSpotNo"] = mwm.baseSpotNo;
                    dr["baseSpotName"] = mwm.baseSpotName;
                    dr["monitorUserNo"] = mwm.monitorUserNo;
                    dr["collectionCode"] = mwm.collectionCode;
                    dr["monitorUserIP"] = mwm.monitorUserIP;
                    dt.Rows.Add(dr);
                }
            }

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

        private void VoiceOption(ucHotDeliveryBelt 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="strWarnInfo"></param>
        private void OpenMsg(string strWarnInfo)
        {
            try
            {
                if (!bMsgOpen)
                {
                    if (PbCacheMonitor.frmMsgClosingTime == null)
                    {
                        bMsgOpen = true;
                        fm = frmHotDeliveryBeltWarn.CreateInstrance(this);
                        fm.TopMost = true;
                        fm.setLbTxt(strWarnInfo);
                        fm.Show();
                    }
                    else
                    {
                        TimeSpan secondSpan = new TimeSpan(DateTime.Now.Ticks - PbCacheMonitor.frmMsgClosingTime.Value.Ticks);
                        if (secondSpan.TotalSeconds > 5)
                        {
                            bMsgOpen = true;
                            fm = frmHotDeliveryBeltWarn.CreateInstrance(this);
                            fm.TopMost = true;
                            fm.setLbTxt(strWarnInfo);
                            fm.Show();
                        }
                    }
                }
                /*
                if (!string.IsNullOrEmpty(openPointNo) && fm != null)
                {
                    fm.CloseFrm();
                }
                */
            }
            catch { }
        }

        /// <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;
                                mwm.weightStatus = item.weightStatus;
                                if (mwm.weight < 200)
                                {
                                    //零点值，重量清零时，零点值也清零;
                                    mwm.weightZero = mwm.weight;
                                }
                            }
                            //将采集的重量给监控界面赋值
                            foreach (Control cn in flPanel.Controls)
                            {
                                if (cn.Name.Contains("uc"))
                                {
                                    ucHotDeliveryBelt ucCar = cn as ucHotDeliveryBelt;
                                    if (ucCar.sPointNo == mwm.baseSpotNo)
                                    {
                                        ucCar.rowPointInfo = mwm;
                                    }
                                }
                            }
                        }
                    }
                }
                //foreach (MeterBaseScalePoint mon in PbCacheMonitor.ltMeterBaseScalePoint)
                //{
                //    foreach (Control cn in flPanel.Controls)
                //    {
                //        if (cn.Name.Contains("uc"))
                //        {
                //            ucHotDeliveryBelt ucCar = cn as ucHotDeliveryBelt;
                //            if (ucCar.sPointNo == mon.baseSpotNo)
                //            {
                //                ucCar.rowPointInfo = mon;
                //            }
                //        }
                //    }
                //}
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 重点！！！,已取消，直接从采集信息中拿值
        /// 从主界面向用户控件中插入信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer2_Tick(object sender, EventArgs e)
        {
            try
            {
                //if (bd.getDb())
                if (PbCacheMonitor.ltMeterBaseScalePoint != null)
                {
                    foreach (MeterBaseScalePoint mon in PbCacheMonitor.ltMeterBaseScalePoint)
                    {
                        foreach (Control cn in flPanel.Controls)
                        {
                            if (cn.Name.Contains("uc"))
                            {
                                ucHotDeliveryBelt ucCar = cn as ucHotDeliveryBelt;
                                if (ucCar.sPointNo == mon.baseSpotNo)
                                {
                                    ucCar.rowPointInfo = mon;
                                }
                            }
                        }
                    }
                }
                else
                {
                    lg.WriteLog(4, "未找到实时监控数据");
                }

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

        private void ultraGridPW_CellChange(object sender, CellEventArgs e)
        {
            ultraGridPW.UpdateData();
            UltraGridRow ugr = ultraGridPW.ActiveRow;
            if (ugr != null)
            {
                bd.getDbBaseScaleHot();
                if (ugr.Cells["UNCK"].Value.ToString().ToLower() == "false")
                {
                    //重新查询一下是否已经接管了；
                    MeterBaseScalePoint mwm = PbCacheMonitor.ltMeterBaseScalePoint.Where(s => s.scalePointNo == ugr.Cells["scalePointNo"].Text.Trim()).FirstOrDefault();
                    //先查一次是否接管了
                    if (mwm != null && !string.IsNullOrEmpty(mwm.monitorUserNo) && (!mwm.monitorUserNo.Equals(userName) || !mwm.monitorUserIP.Equals(strIpAddress)))
                    {
                        ugr.Cells["UNCK"].Value = true;
                        MessageBox.Show("当前计量点正在被账号【" + mwm.monitorUserNo + "】接管,接管IP【" + strIpAddress + "】,不允许重复接管！");
                        setGridData();
                        foreach (UltraGridRow ugrRow in ultraGridPW.Rows)
                        {
                            if (ugrRow.Cells["monitorUserNo"].Text.Trim() != "")
                            {
                                ugrRow.Cells["UNCK"].Value = true;
                            }
                            else
                            {
                                ugrRow.Cells["UNCK"].Value = false;
                            }
                        }
                        return;
                    }
                    flPanel.Controls.RemoveByKey("uc" + ugr.Cells["scalePointNo"].Text);
                    RESTfulResult<string> rm = monitorService.doUpdateWf(new MeterBaseScalePoint { scalePointNo = ugr.Cells["scalePointNo"].Text.Trim(), monitorUserNo = "", monitorUserIP = "" });
                    if (!rm.Succeed)
                    {
                        lg.WriteLog(4, "写入取消接管信息失败");
                    }
                }
                else
                {
                    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 + "】接管，接管IP地址【" + mwm.monitorUserIP + "】");
                        setGridData();
                        foreach (UltraGridRow ugrRow in ultraGridPW.Rows)
                        {
                            if (ugrRow.Cells["monitorUserNo"].Text.Trim() != "")
                            {
                                ugrRow.Cells["UNCK"].Value = true;
                            }
                            else
                            {
                                ugrRow.Cells["UNCK"].Value = false;
                            }
                        }
                        return;
                    }

                    ucHotDeliveryBelt uc = new ucHotDeliveryBelt();//点击数据行进行接管
                    //uc.strCollectNo = ugr.Cells["collectionCode"].Text.Trim();
                    uc.Name = "uc" + ugr.Cells["scalePointNo"].Text;
                    uc.sUserId = userId;
                    uc.sUserName = userName;
                    uc.sIpAddress = strIpAddress;
                    uc.sPointNo = ugr.Cells["baseSpotNo"].Text;
                    uc.sPointName = ugr.Cells["baseSpotName"].Text;
                    uc.appUser = userInfo;
                    //uc.ucMonitoringEvent += new EventHandler(ucEvent);
                    //uc.evoice += new EventVoice(setsVoice);
                    //****************************************注意下面这个**********************
                    // uc.moxaip = dtPointInfo.Rows[k]["MOXAIP"].ToString().Trim();
                    uc.openWarnMsgBelt += new ucHotDeliveryBelt.EventOpenWarnMsgBelt(OpenMsg);
                    uc.rowPointInfo = null;
                    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, monitorUserIP = strIpAddress });
                    if (!rm.Succeed)
                    {
                        lg.WriteLog(4, "写入接管信息失败");
                    }
                }
            }

            //点击后，重新查询一遍数据
            bd.getDbBaseScaleHot();
            setGridData();
            foreach (UltraGridRow ugrRow in ultraGridPW.Rows)
            {
                if (ugrRow.Cells["monitorUserNo"].Text.Trim() != "")
                {
                    ugrRow.Cells["UNCK"].Value = true;
                }
            }
        }

        /// <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) + "";
            }
        }

        /// <summary>
        /// 界面关闭方法：还原接管状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmMonitor_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                collection.Stop();
                //timer2.Stop();
                //取消接管所有已接管的计量点
                foreach (UltraGridRow ugr in ultraGridPW.Rows)
                {
                    if (ugr.Cells["monitorUserNo"].Text.Trim() != "" && ugr.Cells["monitorUserNo"].Text.Trim() == userName)
                    {
                        if (ugr.Cells["UNCK"].Value.ToString().ToUpper() == "TRUE")
                        {
                            UpdateCarijeg(new MeterBaseScalePoint { scalePointNo = ugr.Cells["scalePointNo"].Text.Trim(), monitorUserNo = "", monitorUserIP = "" });
                        }
                    }
                }

                if (thVoice != null) thVoice.Abort();
            }
            catch (Exception ex)
            {
                lg.WriteLog(4, "关闭热送磅计量异常：" + ex.Message);
            }
            finally
            {
            }
        }
    }
}