using HslCommunication;
using HslCommunication.Enthernet.Redis;
using HslCommunication.MQTT;
using MWS.Data.InterFace;
using MWS.Data.Manager;
using MWS.Domain.Dto;
using MWS.Library;
using MWS.Library.Common;
using MWS.Library.Enums;
using MWS.Model;
using MWS.Model.Dto;
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;

namespace MWS.Domain.View.Alert
{
    /// <summary>
    /// RealTimeAlertPage.xaml 的交互逻辑
    /// </summary>
    public partial class RealTimeAlertPage : Page
    {
        private readonly IDevice deviceManager;
        private readonly ITag tagManager;
        private RedisClient _redisClient;
        public List<T_DeviceTag> deviceTags;
        //public MqttClient _mqttClient;
        int mecType = 0;
        int alertType = 0;
        int deviceId = 0;
        public RealTimeAlertPage()
        {
            InitializeComponent();
            _redisClient = new RedisClient("127.0.0.1", 6379, null);
            _redisClient.SelectDB(1);
            tagManager = new TagManager();
            deviceManager = new DeviceManager();
            deviceTags = tagManager.GetTagsByWhere(deviceId);
            BindMecTypeComboBox();
            BindAlertComboBox();
        }
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            BindData();
            //#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[] { "SwitchTagChange", "ValueTagChange" });
            //    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)
        //{
        //    Hashtable changTags = TypeExtension.BinaryToObject(payload) as Hashtable;
        //    //realTimeAlertModel.BindData();
        //    BindData();
        //}
        //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" });
        //                if (!subscribeResult.IsSuccess)
        //                {
        //                    LogHelper.WriteLog("订阅主题失败！Message:" + subscribeResult.Message);
        //                }
        //                // 连接成功后，可以在下方break之前进行订阅，或是数据初始化操作
        //                Console.WriteLine("连接服务器成功！");
        //                break;
        //            }
        //            Console.WriteLine("连接失败，准备5秒后重新连接。");
        //        }
        //    }
        //}

        public void BindData()
        {

            List<RealTimeAlertDto> realTimeAlerts = new List<RealTimeAlertDto>();
            mecType = Convert.ToInt32(cbMecType.SelectedValue);
            alertType = Convert.ToInt32(cbAlertType.SelectedValue);
            var operateResults = _redisClient.ReadHashValues("Alarms");
            foreach (var item in operateResults.Content)
            {
                if (item != null)
                {
                    RealTimeAlertDto realTimeAlert = new RealTimeAlertDto();
                    JObject tagObject = JObject.Parse(item);
                    realTimeAlert.TagId = tagObject.GetValue("TagId").ToSafeInt();
                    realTimeAlert.DeviceId = tagObject.GetValue("DeviceId").ToSafeInt();
                    realTimeAlert.Message = tagObject.GetValue("Message").ToSafeString();
                    realTimeAlert.TriggerTime = (DateTime)tagObject.GetValue("Time");
                    T_DeviceTag temp = deviceTags.Where(c => c.Id == realTimeAlert.TagId).FirstOrDefault();
                    realTimeAlert.MecTypeId = temp.MecType;
                    realTimeAlert.AlertTypeId = temp.SwitchType;
                    realTimeAlert.MecType = Tool.GetEnumDesc(typeof(MecType), temp.MecType);
                    realTimeAlert.AlertType = Tool.GetEnumDesc(typeof(AlertType), temp.SwitchType);
                    realTimeAlerts.Add(realTimeAlert);
                }
            }
            if (mecType > 0)
            {

                realTimeAlerts = realTimeAlerts.Where(c => c.MecTypeId == mecType).ToList();
            }
            if (alertType > 0)
            {
                realTimeAlerts = realTimeAlerts.Where(c => c.AlertTypeId == alertType).ToList();
            }
            lstAlert.ItemsSource = realTimeAlerts;
        }

        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            _redisClient.Dispose();
            //_mqttClient.Dispose();

        }
        private void search_Click(object sender, RoutedEventArgs e)
        {

            BindData();
        }
        /// <summary>
        /// 绑定机构类型
        /// </summary>
        private void BindMecTypeComboBox()
        {
            try
            {
                var query = typeof(MecType).ToArrayList();
                //var mecTypes =
                List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
                
                list= (from KeyValuePair<Enum, string> type in query
                                                           select new KeyValuePair<string, string>(((int)(MecType)type.Key).ToString(), type.Value)).ToList();
                //list.Insert(0, new KeyValuePair<string, string>("0", "全部"));
                //new List<KeyValuePair<string, string>>
                //{
                //    new KeyValuePair<string, string>("0", "全部"),
                //    new KeyValuePair<string, string>("1", "1号料口"),
                //    new KeyValuePair<string, string>("2", "2号料口"),
                //    new KeyValuePair<string, string>("3", "3号料口")
                // };
                cbMecType.ItemsSource = list;
                cbMecType.SelectedValuePath = "Key";
                cbMecType.DisplayMemberPath = "Value";
                cbMecType.SelectedIndex = 0;
            }
            catch (Exception ex)
            {

                throw;
            }

        }
        /// <summary>
        /// 绑定机构类型
        /// </summary>
        private void BindAlertComboBox()
        {
            try
            {
                var query = typeof(AlertType).ToArrayList();
                List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();

                list = (from KeyValuePair<Enum, string> type in query
                        select new KeyValuePair<string, string>(((int)(AlertType)type.Key).ToString(), type.Value)).ToList();
                //list.Insert(0, new KeyValuePair<string, string>("0", "全部"));
                //new List<KeyValuePair<string, string>>
                //{
                //    new KeyValuePair<string, string>("0", "全部"),
                //    new KeyValuePair<string, string>("1", "1号料口"),
                //    new KeyValuePair<string, string>("2", "2号料口"),
                //    new KeyValuePair<string, string>("3", "3号料口")
                // };
                cbAlertType.ItemsSource = list;
                cbAlertType.SelectedValuePath = "Key";
                cbAlertType.DisplayMemberPath = "Value";
                cbAlertType.SelectedIndex = 0;
            }
            catch (Exception ex)
            {

                throw;
            }

        }
    }
}
