using NEIntelligentControl2.Models.Windturbine;
using NEIntelligentControl2.Models.WinForms;
using NEIntelligentControl2.Service.Windturbine;
using System;
using System.Collections.Generic;
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.Views.Infos
{
    /// <summary>
    /// 风机详情弹窗视图
    /// </summary>
    public partial class WindturbineDetailsView : UserControl
    {
        private IList<UniformCodeInfo> UniformCodeInfos;
        private WindturbineInfo info;
        private List<WindturbineDetailsCard> _Cards;

        private DateTime _DataRefreshTime;
        private InfoManager _InfoManager;
        private string[] _UniformCodes;

        public string ToolTipValue { get => tbcontent.Text; internal set => tbcontent.Text = value; }

        public WindturbineDetailsView(WindturbineInfo windturbineInfo)
        {
            InitializeComponent();
            info = windturbineInfo;
            tbtitle.Text = windturbineInfo.WindturbineId;
            _Cards = new List<WindturbineDetailsCard>();
            _InfoManager = App.GetService<InfoManager>();
            Init();
        }

        /// <summary>
        /// 刷新数据
        /// </summary>
        internal void RefreshData()
        {
            if ((DateTime.Now - _DataRefreshTime).TotalSeconds < 5) return;

            Task.Run(() =>
            {
                try
                {
                    var vs = _InfoManager.GetPointDatas(info.WindturbineId, _UniformCodes);
                    Dispatcher.Invoke(() =>
                    {
                        foreach(var v in _Cards)
                        {
                            v.RefreshData(vs);
                        }
                    });
                }
                catch { }

            });

            _DataRefreshTime = DateTime.Now;
        }

        private void Init()
        {
            UniformCodeInfos = App.GetService<InfoManager>().GetUniformCode(info.StationId, info.ModelId);
            var gp = UniformCodeInfos.GroupBy(u => u.PartName);
            foreach(var v in gp)
            {
                WindturbineDetailsCard windturbineDetailsCard = new WindturbineDetailsCard() { CardTitle = v.Key, Items = v.ToList(), Info = info };
                _Cards.Add(windturbineDetailsCard);
                sp.Children.Add(windturbineDetailsCard);
            }

            _UniformCodes = UniformCodeInfos.Select(u => u.UniformCode).ToArray();
        }
    }
}
