using log4net;
using NEIntelligentControl2.Models.Datas;
using NEIntelligentControl2.Models.Messages;
using NEIntelligentControl2.Models.Pages;
using NEIntelligentControl2.Models.Windturbine;
using NEIntelligentControl2.Service.WebSocket;
using NEIntelligentControl2.Views.Matrix;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Policy;
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>
    /// 风机AGC融合页面
    /// </summary>
    public partial class PageWindturbineAGC : Page
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(PageWindturbineAGC));
        private readonly IPageAction _IPageAction;
        private readonly WEBHelper _WEBHelper;

        private MessageBridge _MessageBridge;// websocket

        private WindturbineInfoBridge _WindturbineInfoBridge;// 风机信息数据桥
        /// <summary>
        /// 矩阵块
        /// </summary>
        private List<WindBlock> _WindBlocks;

        private bool _IsLoaded;

        private string RFDLTag = "";
        private string MBGLTag = "";
        private string SSGLTag = "";

        private string YFDLTag = "";
        private string NFDLTag = "";
        private string LLGLTag = "";

        private string _Url = "";
        public PageWindturbineAGC(IPageAction action, MessageBridge mb, WEBHelper web)
        {
            InitializeComponent();
            _IPageAction = action;
            _MessageBridge = mb;
            _WEBHelper = web;
            _WindturbineInfoBridge = new WindturbineInfoBridge() { Messaged = OnWindturbineMessage };

            _tbtitle1.Text = "信\n友\n一\n线";
            _tbtitle2.Text = "信\n友\n二\n线";
            _tbtitle3.Text = "信\n友\n三\n线";
            _Url = ConfigurationManager.AppSettings["DataServicePathDebug"];
            RFDLTag = ConfigurationManager.AppSettings["RFDLTag"];
            MBGLTag = ConfigurationManager.AppSettings["MBGLTag"];
            SSGLTag = ConfigurationManager.AppSettings["SSGLTag"];

            YFDLTag = ConfigurationManager.AppSettings["YFDLTag"];
            NFDLTag = ConfigurationManager.AppSettings["NFDLTag"];
            LLGLTag = ConfigurationManager.AppSettings["LLGLTag"];
        }

        private void OnWindturbineMessage(Dictionary<string, WindturbineInfo> obj)
        {
            if (!_IsLoaded)
            {
                InitWindturbine(obj);
                return;
            }
            Dispatcher.Invoke(() =>
            {
                foreach (var v in _WindBlocks)
                {
                    if (!obj.ContainsKey(v.WindturbineId)) continue;
                    v.Update(obj[v.WindturbineId]);
                }
            });
        }

        private void InitWindturbine(Dictionary<string, WindturbineInfo> obj)
        {
            if (obj == null || obj.Count == 0) return;
            _IsLoaded = true;
            _WindBlocks = new List<WindBlock>();
            var ls = obj.Values.ToList();
            ls.Sort((x, y) => x.ID - y.ID);
            Dispatcher.Invoke(() =>
            {
                foreach (var v in ls)
                {
                    WindBlock bs = new WindBlock(v) { WindturbineId = v.WindturbineId };
                    bs.Update(v);
                    _WindBlocks.Add(bs);
                    if ((v.ID >= 1 && v.ID <= 5) || (v.ID >= 11 && v.ID <= 13))
                    {
                        pb1.AddWindturbine(bs);
                    }
                    else if ((v.ID >= 6 && v.ID <= 10) || (v.ID >= 16 && v.ID <= 19))
                    {
                        pb2.AddWindturbine(bs);
                    }
                    else
                    {
                        pb3.AddWindturbine(bs);
                    }
                }
            });
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            //var page = _IPageAction["Matrix.PageMatrix"];
            //_FrameMatrix.Navigate(page);

            var page2 = _IPageAction["AGC.PageAGC"];
            _FrameAGC.Navigate(page2);


            _MessageBridge.Register(_WindturbineInfoBridge);

            Task.Run(RefresData);
        }

        private async void RefresData()
        {
            string url = $"{_Url}/ts/latest?keys={RFDLTag},{YFDLTag},{NFDLTag}";
            while (true)
            {
                try
                {
                    //
                    var vs = GetValues(url);
                    foreach (var v in vs)
                    {
                        log.Warn($"日月年发{v.Value.Ts}:{v.Value.Value}");
                    }

                    if (vs == null || vs.Count == 0) continue;

                    var ss = GetValuesSingle(SSGLTag);
                    log.Warn($"实时{ss.Ts}:{ss.Value}");
                    var mb = GetValuesSingle(MBGLTag);
                    log.Warn($"目标{mb.Ts}:{mb.Value}");
                    var ll = GetValuesSingle(LLGLTag);
                    log.Warn($"理论{ll.Ts}:{ll.Value}");

                    Dispatcher.Invoke(() =>
                    {
                        try
                        {
                            tbps.Text = Math.Round(ss.Value, 2).ToString("0.00");
                            tbpc.Text = Math.Round(mb.Value, 2).ToString("0.00");
                            tbllgl.Text = Math.Round(ll.Value, 2).ToString("0.00");
                        }
                        catch (Exception e)
                        {
                            log.Error($"实时{e.Message}");
                        }
                        try
                        {
                            foreach (var v in vs)
                            {
                                if (v.Key == RFDLTag)
                                {
                                    tbrf.Text = Math.Round(v.Value.Value, 2).ToString("0.00");
                                }
                                if (v.Key == YFDLTag)
                                {
                                    tbyf.Text = Math.Round(v.Value.Value, 2).ToString("0.00");
                                }
                                if (v.Key == NFDLTag)
                                {
                                    var nval = v.Value.Value;
                                    tbly.Text = Math.Round(nval / 50, 2).ToString("0.00");
                                    tbnf.Text = Math.Round(nval, 2).ToString("0.00");
                                }
                            }
                            var date = DateTime.Parse("2023-2-18");
                            var time = (int)(DateTime.Now - date).TotalDays;
                            aqts.Text = $"{619 + time} 天";
                        }
                        catch (Exception e)
                        {
                            log.Error($"日月年发{e.Message}");
                        }
                    });
                }
                catch (Exception e)
                {
                    log.Error($"右下{e.Message}");
                }
                await Task.Delay(1000);
            }
        }

        private Dictionary<string, TsData> GetValues(string url)
        {
            Dictionary<string, TsData> datas = new Dictionary<string, TsData>();
            try
            {
                datas = _WEBHelper.HttpGetJSON<Dictionary<string, TsData>>(url);
            }
            catch { }
            return datas;
        }
        private TsData GetValuesSingle(string key)
        {
            var data = new TsData();
            var url = $"{_Url}/ts/latest?keys={key}";
            try
            {
                var datas = _WEBHelper.HttpGetJSON<Dictionary<string, TsData>>(url);
                if (datas != null && datas.ContainsKey(key))
                {
                    return datas[key];
                }
                return data;
            }
            catch { }
            return data;
        }
    }
}
