using com.hnshituo.core.webapp.vo;
using Common;
using Common.vo.pb;
using Infragistics.Win.UltraWinEditors;
using JC_MeasuringSystem;
using MeterPlugInLibrary;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Media;
using System.Windows.Forms;

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

        private ComBaseInfoService comBaseInfoService = new ComBaseInfoService(); //基础数服务
        private MeterBaseScalePointService scalePointService = new MeterBaseScalePointService(); //计量点信息服务

        private Log l = Log.GetInstance(); //日志
        private string userId = "", userName = ""; //用户ID用户名
        private string strBaseCode = "";//基础数据主键
        private CoreAppUser appUser = null;//登陆信息

        private string[] strPntNoCollect = null; //所有的计量点
        private List<string> strPntNoList = new List<string>(); //

        private frmHotDeliveryBeltWarn fm = null;//预警界面
        public bool bMsgOpen = false; //是否打开了预警界面提醒
        public bool bWarnFlage = false; //是否继续打开预警界面
        private int iWarnWeight = 0; //预警重量，大于这个值预警

        private string rk_CurPath = Application.StartupPath;  //System.Environment.CurrentDirectory;//获取到当前路径
        private SoundPlayer play_ls = null;//报警声音播放

        public frmHotDeliveryWeightWarn()
        {
            InitializeComponent();
        }

        private void frmHotDeliveryWeightWarn_Load(object sender, EventArgs e)
        {
            userId = ((ST_MainForm)(this.MdiParent)).UserID;
            userName = ((ST_MainForm)(this.MdiParent)).UserName;
            appUser = ((ST_MainForm)(this.MdiParent)).AppUser;

            #region 载入基础信息

            //计量点信息载入cmbPoint;cmbPointUp
            RESTfulResult<List<MeterBaseScalePoint>> rr = scalePointService.doQueryWf(new MeterBaseScalePoint { validFlag = "1", spotTypeNo = "001002004" });
            if (rr.Succeed && rr.Data != null && rr.Data.Count > 0)
            {
                ClsControlPack.SetUltraComboDataSource(cmbPoint, rr.Data.ListToDataTable<MeterBaseScalePoint>(), "collectionCode", "baseSpotName");
            }
            else
            {
                MessageBox.Show("计量点载入失败!");
                return;
            }

            #endregion 载入基础信息
        }

        #region 点击事件

        /// <summary>
        /// 选择计量点的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbPoint_ValueChanged(object sender, EventArgs e)
        {
            //查询预警值
            RESTfulResult<List<ComBaseInfo>> rrComMeterGroop = comBaseInfoService.doQueryBaseList(new ComBaseInfo { validFlag = "1", baseName = cmbPoint.Text });
            if (rrComMeterGroop.Succeed && rrComMeterGroop.Data != null && rrComMeterGroop.Data.Count > 0)
            {
                strBaseCode = rrComMeterGroop.Data[0].baseCode;
                if (!string.IsNullOrEmpty(rrComMeterGroop.Data[0].memo))
                {
                    numLimit.Value = Convert.ToInt32(rrComMeterGroop.Data[0].memo);
                    iWarnWeight = Convert.ToInt32(rrComMeterGroop.Data[0].memo);
                }
            }
            else
            {
                MessageBox.Show("热送磅重量预警值信息载入失败!" + rrComMeterGroop.Message);
                return;
            }
        }

        /// <summary>
        /// 开始监控
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btStart_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cmbPoint.Value + "") || string.IsNullOrEmpty(cmbPoint.Text) || string.IsNullOrEmpty(strBaseCode))
            {
                MessageBox.Show("请先选择一个计量点！");
                return;
            }
            if (btStart.Text.Equals("正在监控"))
            {
                MessageBox.Show("已经监控了一个计量点，若需要更换计量点，请重新打开界面后再进行监控！");
                return;
            }
            btStart.Text = "正在监控";
            strPntNoList.Add((cmbPoint.Value + "").ToUpper());
            strPntNoCollect = strPntNoList.ToArray();//加载所有的计量点，不管有没有接管
            collection.EventHotDeliveryDataCollectionArgs += new EventHotDeliveryDataCollection(weightCollect);//数据采集解析
            collection.Start(strPntNoCollect);//数据采集启动
        }

        /// <summary>
        /// 设置报警值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btSetLimit_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(strBaseCode))
            {
                MessageBox.Show("请先选择计量点的，再更新预警值！");
                return;
            }
            ComBaseInfo baseInfo = new ComBaseInfo();
            baseInfo.baseCode = strBaseCode;
            baseInfo.updateManNo = userId;
            baseInfo.updateManName = userName;
            if (!string.IsNullOrEmpty(numLimit.Text))
            {
                baseInfo.memo = numLimit.Text;
                iWarnWeight = Convert.ToInt32(numLimit.Value);
            }
            RESTfulResult<String> rms = comBaseInfoService.doUpdateWf(baseInfo);
            if (rms.Succeed)
            {
                MessageBox.Show("预警值更新成功！");
            }
            else
            {
                MessageBox.Show("操作失败：" + rms.Data);
                l.WriteLog(19, "操作失败：" + rms.Data + rms.Message);
            }
        }

        #endregion 点击事件

        #region 设置界面重量的值

        /// <summary>
        /// 时间控件监控
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (iWarnWeight > 0 && iWarnWeight < Convert.ToInt32(txtWeight.Text.Replace("kg", "").Trim()))
            {
                //报警一次
                if (!bWarnFlage)
                {
                    lbState.Text = "重量报警";
                    lbState.BackColor = Color.Red;
                    setLable("重量报警");
                    setLable("red");
                    play_ls = new SoundPlayer(rk_CurPath + "\\Sound\\cc.wav");
                    play_ls.PlayLooping();
                    //OpenMsg("当前重量【 " + txtWeight.Text.Replace("kg", "").Trim() + " kg】超出预警值【 " + numLimit.Value + " kg】！");
                    bWarnFlage = true;
                }
            }
        }

        /// <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)
                    {
                        if (cmbPoint.Value.Equals(item.pointid))
                        {
                            setWeightCollect(item.weight + "");
                            if (item.weight == 0 || item.weight < iWarnWeight)
                            {
                                //回零后，下一次继续报警！
                                bWarnFlage = false;
                                if (play_ls!=null)
                                {
                                    play_ls.Stop();
                                }
                                setLable("重量正常");
                                setLable("transparent");
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                //throw;
            }
        }

        /// <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="bGreen"></param>
        public void setWeightCollect(string weight)
        {
            txtWeight.Invoke(new UpdateUIEventHander(UpdateUI_Method), txtWeight, new UpdateUIArgs(weight));
        }

        /// <summary>
        /// label状态赋值
        /// </summary>
        /// <param name="bGreen"></param>
        public void setLable(string value)
        {
            txtWeight.Invoke(new UpdateUIEventHander(UpdateUI_Method), lbState, new UpdateUIArgs(value));
        }

        #endregion 设置界面重量的值

        #region 线程中赋值的控件需使用委托

        private delegate void UpdateUIEventHander(object sender, UpdateUIArgs args); //自定义事件用来从线程中更新控件的值

        public class UpdateUIArgs : EventArgs
        {
            public string textValue { get; private set; }

            public UpdateUIArgs(string textValue)
            {
                this.textValue = textValue;
            }
        }

        /// <summary>
        /// 更新界面的UI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void UpdateUI_Method(object sender, UpdateUIArgs args)
        {
            if (sender is UltraTextEditor)
            {
                if (args.textValue == "" || args.textValue == null)
                {
                    ((UltraTextEditor)sender).Text = "0 kg";
                }
                else
                {
                    ((UltraTextEditor)sender).Text = args.textValue + " kg";
                }
            }
            else if (sender is Button)
            {
                if (args.textValue == "red")
                {
                    ((Button)sender).BackColor = Color.Red;
                    ((Button)sender).ForeColor = Color.White;
                }
                else if (args.textValue == "green")
                {
                    ((Button)sender).BackColor = Color.White;
                    ((Button)sender).ForeColor = Color.Black;
                }
                else
                {
                    ((Label)sender).Text = args.textValue;
                }
            }
            else if (sender is Label)
            {
                if (args.textValue == "red")
                {
                    ((Label)sender).BackColor = Color.Red;
                }
                else if (args.textValue == "transparent")
                {
                    ((Label)sender).BackColor = Color.Transparent;
                }
                else
                {
                    ((Label)sender).Text = args.textValue;
                }
            }
            else if (sender is PictureBox)
            {
                if (args.textValue == "red")
                {
                    ((PictureBox)sender).Load(PbCache.path + "\\image\\icon\\red.gif");
                }
                else
                {
                    ((PictureBox)sender).Load(PbCache.path + "\\image\\icon\\green.gif");
                }
            }
        }

        #endregion 线程中赋值的控件需使用委托

        /// <summary>
        /// 关闭界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmHotDeliveryWeightWarn_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                collection.Stop();
                timer1.Stop();
            }
            catch (Exception ex)
            {
                l.WriteLog(19, "关闭热送磅计量异常：" + ex.Message);
            }
            finally
            {
            }
        }
    }
}