using NEIntelligentControl2.Models.AGC;
using NEIntelligentControl2.Models.Datas;
using NEIntelligentControl2.Models.Messages;
using NEIntelligentControl2.Service.WebSocket;
using SVGViewer.Models.Info;
using SVGViewer.Views;
using System;
using System.Collections.Generic;
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.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace NEIntelligentControl2.Views.BoostStation
{
    /// <summary>
    /// 升压站缩略图视图
    /// </summary>
    public partial class ThumbnailView : UserControl
    {
        public static readonly DependencyProperty IsAlarmProperty = DependencyProperty.Register("IsAlarm", typeof(bool), typeof(ThumbnailView), new PropertyMetadata(IsAlarmChanged));

        public bool IsAlarm { get => (bool)GetValue(IsAlarmProperty); set => SetValue(IsAlarmProperty, value); }

        public Action<string> DoubleClicked { get; set; }

        private bool _IsLoaded;

        private ShapeInfo shapeInfo;
        private Dictionary<string, ShapeInfo> customizeShapes;
        private WEBHelper _WEBHelper;
        private UrlManager _UrlManager;
        /// <summary>
        /// 数据地址
        /// </summary>
        private string _Url = "";
        private Dictionary<string, List<SVGViewer.Models.Info.TagInfo>> _TagInfos = new Dictionary<string, List<SVGViewer.Models.Info.TagInfo>>();
        public ThumbnailView(ShapeInfo v, Dictionary<string, ShapeInfo> customizeShapes)
        {
            InitializeComponent();
            shapeInfo = v;
            this.customizeShapes = customizeShapes;
            _WEBHelper = App.ServiceProvider.GetService(typeof(WEBHelper)) as WEBHelper;
            _UrlManager = App.ServiceProvider.GetService(typeof(UrlManager)) as UrlManager;
            Init();
        }

        private void Init()
        {
            var sv = new SVGCanvas(shapeInfo, customizeShapes, false);
            _vb.Child = sv;
            _TBTitle.Text = shapeInfo.Name;


            var taginfos = shapeInfo.GetAllTagInfos();
            _TagInfos = taginfos.GroupBy(v => v.Tag).ToDictionary(v => v.Key, v => v.ToList());

            var keys = string.Join(",", _TagInfos.Keys);
            _Url += $"{_UrlManager.DataServicePath}/ts/latest?keys={keys}";
        }



        private static void IsAlarmChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue == e.OldValue) return;
            var tv = d as ThumbnailView;
            if ((bool)e.NewValue)
            {
                SolidColorBrush sb = new SolidColorBrush();
                ColorAnimation ca = new ColorAnimation();
                ca.From = Color.FromRgb(0xFF, 0x71, 0x71);
                ca.To = Color.FromRgb(0xDB, 0x33, 0x33);
                ca.AutoReverse = true;
                ca.RepeatBehavior = RepeatBehavior.Forever;
                ca.Duration = new Duration(TimeSpan.FromSeconds(0.5));
                sb.BeginAnimation(SolidColorBrush.ColorProperty, ca);
                tv._bd.Background = sb;
            }
            else
            {
                tv._bd.Background = new SolidColorBrush(Color.FromRgb(0x2B, 0x77, 0xDC));
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            _IsLoaded = true;
            Task.Factory.StartNew(RefreshData);
        }

        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            _IsLoaded = false;
        }

        private async void RefreshData()
        {
            while (_IsLoaded)
            {
                try
                {
                    var vs = _WEBHelper.HttpGetJSON<Dictionary<string, TsData>>(_Url);
                    if (vs != null && vs.Count > 0)
                    {
                        Dispatcher?.Invoke(() =>
                        {
                            foreach (var v in vs)
                            {
                                if (!_TagInfos.ContainsKey(v.Key)) continue;
                                var tgs = _TagInfos[v.Key];
                                foreach (var tg in tgs)
                                {
                                    tg.Value = v.Value.Value;
                                }
                            }
                        });
                    }
                    Console.WriteLine($"刷新:{shapeInfo.Id}");
                }
                catch { }

                await Task.Delay(2000);
            }
        }

        private void UserControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount < 2 || DoubleClicked == null) return;
            DoubleClicked.Invoke(shapeInfo.Id);
        }
    }
}