using HslCommunication;
using HslCommunication.Enthernet.Redis;
using HslCommunication.MQTT;
using MWS.Data.InterFace;
using MWS.Data.Manager;
using MWS.Domain.View.SystemManage;
using MWS.Library;
using MWS.Library.Common;
using MWS.Model;
using MWS.Model.Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;

namespace MWS.Domain
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        private Thread Thread = null;
        private Thread AlertThread = null;
        public MqttClient _mqttClient;
        private RedisClient _redisClient;
        private readonly XmlNode XnMenu;
        private XmlNodeList XsubMenu;
        private int teamId=0;
        private IWeight weightManager;
        private bool isThreadRun = false;
        //private List<T_AlertRecord> alertTagModels;
        private int CurrentCount = 0;
        private int TotalCount = 0;
        public MainWindow()
        {
            InitializeComponent();
            weightManager = new WeightManager();
            //alertTagModels = new List<T_AlertRecord>();
            _redisClient = new RedisClient("127.0.0.1", 6379, null);
            _redisClient.SelectDB(1);
            XmlDocument doc = new XmlDocument();
            doc.Load(@"Assets/Config/MenuData.xml");
            XmlNode xn = doc.SelectSingleNode("MenuData");
            XnMenu = xn;
            mainMenu.ItemsSource = xn;
            XmlElement xe = (XmlElement)xn.FirstChild;

            XmlNodeList xns = xe.SelectNodes("SubMenu");

            foreach (XmlNode item in xns)
            {
                XmlElement xne = (XmlElement)item;
                if (xne.GetAttribute("IsShow") == "False")
                {
                    xe.RemoveChild(item);
                }
            }
            mainFrame.NavigationService.Navigate(
             new Uri(xe.Attributes["Uri"].Value,
             UriKind.Relative));
            _redisClient.ListLeftPush("currentUrl", xe.Attributes["Uri"].Value.ToString());
            _redisClient.ListTrim("currentUrl", 0, 0);

            subNavigation.Visibility = Visibility.Collapsed;
            int k = 0;
            foreach (XmlNode xn1 in xe.SelectNodes("SubMenu"))
            {
                XmlElement xne = (XmlElement)xn1;
                if (k == 0)
                {
                    xne.SetAttribute("Bg", "#1CAAFD");
                    xne.SetAttribute("FontColor", "#FFFFFFFF");
                }
                else
                {
                    xne.SetAttribute("Bg", "#364B5B");
                    xne.SetAttribute("FontColor", "#8e9cac");
                }
                k++;
            }

            XsubMenu = xns;
            subMenu.ItemsSource = xe.SelectNodes("SubMenu");
            //tbCraneName.Text = CacheUtil.GetCrane().CraneName;
            MainThreadRun();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var operateResultTemps = _redisClient.ReadKey("CurrentTeam");

            if (operateResultTemps.Content != null)
            {
                JObject tagObject = JObject.Parse(operateResultTemps.Content);
                teamId = Convert.ToInt32(tagObject.GetValue("Id"));
                txtAlertMessage.Text = tagObject.GetValue("Name").ToSafeString();
            }
            var result = weightManager.GetTotal(0, teamId);
            txtTeamCount.Text = (result != null ? result : 0).ToString();

            result = weightManager.GetTotal(0, 0);
            txtDailyCount.Text = (result != null ? result : 0.00).ToString();
            setTaskAtFixedTime();
            #region MQTT
            var mqttPort = ConfigurationManager.AppSettings["MqttPort"];
            _mqttClient = new MqttClient(new MqttConnectionOptions
            {
                ClientId = Guid.NewGuid().ToString("N").ToUpper(),
                IpAddress = "127.0.0.1",
                Port = mqttPort.ToInt(),
            });
            var operateResult = _mqttClient.ConnectServer();
            if (!operateResult.IsSuccess)
            {
                LogHelper.WriteLog("MQTT服务连接失败！错误：" + operateResult.Message);
            }
            else
            {
                var subscribeResult = _mqttClient.SubscribeMessage(new string[] { "TeamChange", "WeighingData", "AlertTagChange" });
                if (!subscribeResult.IsSuccess)
                {
                    LogHelper.WriteLog("订阅主题失败！Message:" + subscribeResult.Message);
                }
                _mqttClient.OnMqttMessageReceived += MqttClient_OnMqttMessageReceived;
                _mqttClient.OnNetworkError += MqttClient_OnNetworkError;
            }
            #endregion


        }
        private void MqttClient_OnMqttMessageReceived(MqttClient client, string topic, byte[] payload)
        {
            try
            {
                //Hashtable changTags = TypeExtension.BinaryToObject(payload) as Hashtable;
                var changeJson = Encoding.UTF8.GetString(payload);
                //var changeDto = JsonConvert.DeserializeObject<ManualCalibrationDto>(changeJson);

                switch (topic)
                {
                    case "TeamChange":
                        TeamChange(changeJson);
                        break;
                    case "WeighingData":
                        WeightTotal(changeJson);
                        break;
                    case "AlertTagChange":
                        //AlertChange();
                        break;

                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("主题："+topic+",错误消息："+ex.Message);
            }
           

        }
        private void MqttClient_OnNetworkError(object sender, EventArgs e)
        {
            // 当网络异常的时候触发，可以在此处重连服务器
            if (sender is MqttClient client)
            {
                // 开始重连服务器，直到连接成功为止
                Console.WriteLine("网络异常，准备5秒后重新连接。");
                while (true)
                {
                    // 每隔5秒重连
                    Thread.Sleep(5000);
                    Console.WriteLine("准备重新连接服务器...");
                    OperateResult connect = client.ConnectServer();
                    if (connect.IsSuccess)
                    {
                        var subscribeResult = client.SubscribeMessage(new string[] { "SwitchTagChange", "ValueTagChange","AlertTagChange" });
                        if (!subscribeResult.IsSuccess)
                        {
                            LogHelper.WriteLog("订阅主题失败！Message:" + subscribeResult.Message);
                        }
                        // 连接成功后，可以在下方break之前进行订阅，或是数据初始化操作
                        Console.WriteLine("连接服务器成功！");
                        break;
                    }
                    Console.WriteLine("连接失败，准备5秒后重新连接。");
                }
            }
        }
        private void StackPanel_Click(object sender, RoutedEventArgs e)
        {
            MenuItem mi = e.OriginalSource as MenuItem;
            XmlElement xe = mi.Header as XmlElement;
            XmlNodeList nl = XnMenu.SelectNodes("MainMenu");
            
            //选中后改变当前选中项背景色，选中图片
            foreach (XmlNode item in nl)
            {
                XmlElement xe1 = (XmlElement)item;
                if (xe1.GetAttribute("Name").Equals(xe.GetAttribute("Name")))
                {
                    xe1.SetAttribute("Active", "Assets/Images/selected.png");
                    xe1.SetAttribute("FontColor", "#8e9cac");
                    xe1.SetAttribute("Bg", "#162129");
                }
                else
                {
                    xe1.SetAttribute("FontColor", "#8e9cac");

                    xe1.RemoveAttribute("Active");
                    xe1.RemoveAttribute("Bg");
                }
            }
            mainMenu.ItemsSource = nl;

            mainFrame.NavigationService.Navigate(
               new Uri(xe.Attributes["Uri"].Value,
               UriKind.Relative));
            _redisClient.ListLeftPush("currentUrl", xe.Attributes["Uri"].Value.ToString());
            _redisClient.ListTrim("currentUrl", 0, 0);
            //子项重新加载。
            XmlNodeList xns = xe.SelectNodes("SubMenu");
            if (xns.Count>0)
            {
                subNavigation.Visibility = Visibility.Visible;
                foreach (XmlNode item in xns)
                {
                    XmlElement xne = (XmlElement)item;
                    if (xne.GetAttribute("IsShow") == "False")
                    {
                        xe.RemoveChild(item);
                    }
                }
                int i = 0;
                foreach (XmlNode xn1 in xe.SelectNodes("SubMenu"))
                {
                    XmlElement xne = (XmlElement)xn1;
                    if (i == 0)
                    {
                        xne.SetAttribute("Bg", "#1CAAFD");
                        xne.SetAttribute("FontColor", "#FFFFFFFF");
                    }
                    else
                    {
                        xne.SetAttribute("Bg", "#364B5B");
                        xne.SetAttribute("FontColor", "#8e9cac");
                    }
                    i++;
                }

                XsubMenu = xns;
                subMenu.ItemsSource = xe.SelectNodes("SubMenu");
            }
            else
            {
                subNavigation.Visibility = Visibility.Collapsed;
            }
            //导航到最新页
           
        }
        private void MainThreadRun()
        {
            if (!isThreadRun)
            {

                AlertThread = new Thread(AlertThreadServer)
                {
                    IsBackground = true
                };
                AlertThread.Start();
                isThreadRun = true;
            }
            else
            {
                isThreadRun = false;
            }
        }
        internal void TeamChange(string changTags)
        {
            Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
            {
                JObject tagObject;
                //object changTag;
                //changTag = changTags["CurrentTeam"];
                if (changTags != null)
                {
                    tagObject = JObject.Parse(changTags.ToString());
                    teamId = tagObject.GetValue("Id").ToSafeInt();
                    string tempName = tagObject.GetValue("Name").ToSafeString();
                    var result = weightManager.GetTotal(0, teamId);
                    txtTeamCount.Text = (result != null ? result : 0.00).ToString();
                    txtAlertMessage.Text = tempName;
                }
            }));
        }
        /// <summary>
        /// 推送时重新获取
        /// </summary>
        //internal void AlertChange()
        //{
        //    var alertResultTemps = _redisClient.ReadHashValues("Alarms");
        //    alertTagModels = new List<T_AlertRecord>();
        //    if (alertResultTemps.Content != null)
        //    {
        //        CurrentCount = 0;
        //        foreach (var item in alertResultTemps.Content)
        //        {
        //            JObject tagObject = JObject.Parse(item);
        //            T_AlertRecord alertTag = new T_AlertRecord();
        //            alertTag.TagId = Convert.ToInt32(tagObject.GetValue("TagId"));
        //            alertTag.DeviceId = Convert.ToInt16(tagObject.GetValue("DeviceId"));
        //            alertTag.Message = tagObject.GetValue("Message").ToString();
        //            alertTag.TriggerTime = Convert.ToDateTime(tagObject.GetValue("Time"));
        //            alertTagModels.Add(alertTag);
        //        }
        //        TotalCount = alertTagModels.Count;
        //    }
        //}
        /// <summary>
        /// 重量增加时调用
        /// </summary>
        /// <param name="changTags"></param>
        //internal void WeightTotal(Hashtable changTags
        internal void WeightTotal(string changeJson)
        {
            Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
            {
                //var changeDto = JsonConvert.DeserializeObject<>(changeJson);
                JObject tagObject;
                //object changTag;
                //changTag = changTags["WeighingData"];
                if (changeJson != null)
                {
                    tagObject = JObject.Parse(changeJson.ToString());
                    int tempTeamId = tagObject.GetValue("TeamId").ToSafeInt();
                    int tempDeviceId = tagObject.GetValue("DeviceId").ToSafeInt();
                    double netWeight = Convert.ToDouble(tagObject.GetValue("NetWeight"));

                    var result = weightManager.GetTotal(0, 0);

                    txtTeamCount.Text = (Convert.ToDouble(txtTeamCount.Text) + netWeight).ToString("0.00");
                    //txtDailyCount.Text = (Convert.ToDouble(txtDailyCount.Text) + (result != null ? Convert.ToInt32(result) / 100 : 0)).ToString();
                    txtDailyCount.Text = (result != null ? result : 0.00).ToString();

                }
            }));
        }

       
   
        private void AlertThreadServer()
        {
            while (true)
            {
                if (isThreadRun)
                {
                    Thread.Sleep(1000);
                    Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
                    {

                        TimeChange();
                    }));
                }
                else
                {
                    break;
                }
                // 再次检测连接是否关闭
                if (!isThreadRun) { Thread.Sleep(100); break; }
            }
        }
        
        private void TimeChange()
        {
            txtNowTime.Text = DateTime.Now.ToString();
            //try
            //{
            //    if (TotalCount > 0)
            //    {
            //        if (CurrentCount < TotalCount)
            //        {
            //            //txtAlertMessage.Text = alertTagModels[CurrentCount].Message;
            //            //txtNowTime.Text = alertTagModels[CurrentCount].TriggerTime.ToString();
            //            CurrentCount++;
            //        }
            //        else
            //        {
            //            CurrentCount = 0;
            //        }
            //    }
            //    else
            //    {
            //        //txtAlertMessage.Text = "无";
            //        txtNowTime.Text = DateTime.Now.ToString();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    CurrentCount = 0;
            //    LogHelper.WriteLog("报警轮询错误：" + ex.Message);
            //}
           
        }


        /// <summary>
        /// 固定时间设置任务
        /// </summary>
        private void setTaskAtFixedTime()
        {
            Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
            {
                DateTime now = DateTime.Now;
                DateTime oneOClock = DateTime.Today.AddHours(0.01); //凌晨8：00
                if (now > oneOClock)
                {
                    oneOClock = oneOClock.AddDays(1.0);
                }
                int msUntilFour = (int)((oneOClock - now).TotalMilliseconds);

                var t = new System.Threading.Timer(doAt1AM);
                t.Change(msUntilFour, Timeout.Infinite);

            }));
        }

        //要执行的任务
        private void doAt1AM(object state)
        {
            Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
            {
                //执行功能...
                txtDailyCount.Text = "0";

            }));
            //再次设定
            setTaskAtFixedTime();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void SubMemu_Click(object sender, RoutedEventArgs e)
        {
            MenuItem mi = e.OriginalSource as MenuItem;
            XmlElement xe = mi.Header as XmlElement;

            foreach (XmlNode item in XsubMenu)
            {
                XmlElement xne = (XmlElement)item;
                if (xne.Attributes["Name"].Equals(xe.Attributes["Name"]))
                {
                    xne.SetAttribute("Bg", "#1CAAFD");
                    xne.SetAttribute("FontColor", "#FFFFFFFF");
                }
                else
                {
                    xne.SetAttribute("Bg", "#364B5B");
                    xne.SetAttribute("FontColor", "#8e9cac");
                }
            }
            mainFrame.NavigationService.Navigate(
                new Uri(xe.Attributes["Uri"].Value,
                UriKind.Relative));

            //将url放入redis
            _redisClient.ListLeftPush("currentUrl", xe.Attributes["Uri"].Value.ToString());
            _redisClient.ListTrim("currentUrl", 0, 0);
            //CacheUtil.SetCurrentPageUri(xe.Attributes["Uri"].Value.ToString());
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            CloseWindow closWindow = new CloseWindow();
            closWindow.ShowDialog();
            if (closWindow.isMinized)
            {
                this.WindowState = WindowState.Minimized;
            }
            //this.Close();
        }

     
    }
}
