using NEIntelligentControl2.Models.Alarm;
using NEIntelligentControl2.Models.Messages;
using NEIntelligentControl2.Models.Pages;
using NEIntelligentControl2.Models.Windturbine;
using NEIntelligentControl2.Service.WebSocket;
using NEIntelligentControl2.Views.AGC;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
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 NEIntelligentControl2.Pages.Home
{

    /// <summary>
    /// 主页页面
    /// </summary>
    public partial class HomePage : Page, IMessage
    {
        private readonly string FaultType = ConfigurationManager.AppSettings["SubscribeRuntimeFault"];          // 故障列表类型
        private readonly string AlarmType = ConfigurationManager.AppSettings["SubscribeRuntimeAlarm"];          // 报警类型

        private MessageBridge _MessageBridge;
        private WEBHelper _WEBHelper;

        private string _Url;

        public List<string> MessageTypes { get; set; }

        private WindturbineInfoBridge _WindturbineInfoBridge;
        private TagManager _TagManager;

        public HomePage(MessageBridge mb,WEBHelper web, TagManager tm)
        {
            InitializeComponent();
            _MessageBridge = mb;
            _WEBHelper = web;
            _TagManager = tm;
            MessageTypes = new List<string>() { FaultType, AlarmType };
            _WindturbineInfoBridge = new WindturbineInfoBridge() { Messaged = OnWindturbineInfoMessage };
            try
            {
#if (DEBUG)
                _Url = ConfigurationManager.AppSettings["AlarmPathDebug"];
#else
                _Url = ConfigurationManager.AppSettings["AlarmPath"];
#endif
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private void OnWindturbineInfoMessage(Dictionary<string, WindturbineInfo> vs)
        {
            _SCMCard.UpdateData(vs);
            _MMCard.UpdateData(vs);
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            _TagManager.TagChanged?.Invoke(new List<Models.Station.StationInfo>());
            _MessageBridge.Register(this);  // 订阅消息
            _MessageBridge.Register(_WindturbineInfoBridge);  // 订阅消息
            Task.Run(LoadAlarmHistory);             // 加载报警历史值
        }

        /// <summary>
        /// 加载报警历史值
        /// </summary>
        private void LoadAlarmHistory()
        {
            DateTime dt = DateTime.Now.AddDays(-1);
            AlarmPage ap = _WEBHelper.HttpGetJSON<AlarmPage>($"{_Url}/alarm/history/page?pagenum=1&pagesize=1000&category1=SYZ&starttime={dt.ToString("yyyy-MM-dd HH:mm:ss")}&endtime={DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
            _SACard.UpdateAlarmData(ap);
        }

        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            _MessageBridge.Unregister(this);// 取消订阅消息
            _MessageBridge.Unregister(_WindturbineInfoBridge);
        }

        public async Task OnMessage(object message)
        {
            await Task.Run(() =>
            {
                var stomp = message as StompMessage;
                if (stomp == null || !stomp.Headers.ContainsKey("destination")) return;
                var type = stomp.Headers["destination"];

                if (type == FaultType)// 故障列表
                {
                    UpdateRuntimeFault(stomp);
                }
                else if (type == AlarmType)// 报警列表
                {
                    UpdateRuntimeAlert(stomp);
                }
            });
        }

        private void UpdateRuntimeAlert(StompMessage stomp)
        {
            List<AlarmInfo> fis = _WEBHelper.Deserialize<List<AlarmInfo>>(stomp.Body);
            foreach (var v in fis)
            {
                if (v.Category1 != "FJ")
                {
                    _SACard.UpdateAlarmData(v);
                }
                else
                {
                    _WTACard.UpdateAlarmData(v);
                }
            }
        }

        /// <summary>
        /// 更新故障列表
        /// </summary>
        private void UpdateRuntimeFault(StompMessage stomp)
        {
            List<FaultInfoModel> faultInfoModel = _WEBHelper.Deserialize<List<FaultInfoModel>>(stomp.Body);
            if (faultInfoModel == null) return;
            foreach (var v in faultInfoModel)
            {
                if (v.FaultInfo.Category1 != "FJ")
                {
                    _SACard.UpdateAlarmData(v.FaultInfo);
                }
                else
                {
                    _WTACard.UpdateAlarmData(v.FaultInfo);
                }
            }
        }

        /// <summary>
        /// AGC场站选择改变事件，勿删
        /// </summary>
        private void AAGCCard_SelectionChanged(object sender, RoutedEventArgs e)
        {
            SimpleAGCCard sc = e.OriginalSource as SimpleAGCCard;
            if (sc == null) return;
            int index = (int)sc.Tag;
            _DAGCCard.ChangeCard(index);
        }
    }
}
