using LiveCharts;
using NEIntelligentControl2.Models;
using NEIntelligentControl2.Models.Datas;
using NEIntelligentControl2.Models.Messages;
using NEIntelligentControl2.Models.PV;
using NEIntelligentControl2.Service.WebSocket;
using NEIntelligentControl2.Service.Windturbine;
using NEIntelligentControl2.Views.Infos;
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.Shapes;

namespace NEIntelligentControl2.Windows.PV
{
    /// <summary>
    /// 光伏详情页窗口
    /// </summary>
    public partial class InverterInfoWindow : Window
    {
        public static readonly DependencyProperty StatusProperty = DependencyProperty.Register("Status", typeof(PVState), typeof(InverterInfoWindow));

        public PVState Status { get => (PVState)GetValue(StatusProperty); set => SetValue(StatusProperty, value); }
        /// <summary>
        /// 矩阵块
        /// </summary>
        public PVBlock Block { get; set; }
        /// <summary>
        /// 名称
        /// </summary>
        public string PVName { get => $"{Info?.Name} {Block?.PVName}"; }
        public bool IsSUN2000 { get => Block?.Info.Model == "SUN2000"; }
        /// <summary>
        /// 信息
        /// </summary>
        private PVDetails Info { get; set; }
        /// <summary>
        /// 测点们
        /// </summary>
        private List<PVTagInfo> _TagInfos;
        /// <summary>
        /// 需要读取历史的测点们
        /// </summary>
        private List<PVTagInfo> _HistoryTagInfos;
        /// <summary>
        /// 所有UniformCode
        /// </summary>
        private string _Codes;
        /// <summary>
        /// 是否活跃
        /// </summary>
        private bool _IsActived;
        /// <summary>
        /// 数据请求url
        /// </summary>
        private string _Url = "";


        /// <summary>
        /// 温度数据（历史）
        /// </summary>
        private ChartValues<double> _CVTemperature { get; set; } = new ChartValues<double>();
        /// <summary>
        /// 功率数据（历史）
        /// </summary>
        private ChartValues<double> _CVPower { get; set; } = new ChartValues<double>();
        /// <summary>
        /// 光照数据（历史）
        /// </summary>
        private ChartValues<double> _CVSunshine { get; set; } = new ChartValues<double>();
        private WEBHelper _WEBHelper;
        private InfoManager _InfoService;
        private UrlManager _UrlManager;

        public InverterInfoWindow(WEBHelper web, InfoManager iss, UrlManager um)
        {
            InitializeComponent();
            _WEBHelper = web;
            _InfoService = iss;
            _LineChartTemperature.Values = _CVTemperature;
            _LineChartPower.Values = _CVPower;
            _LineChartSunshine.Values = _CVSunshine;
            _UrlManager = um;
            _Url = _UrlManager.DataServicePath;
        }


        private async void RefreshHistoryData()
        {
            while (_IsActived)
            {
                try
                {
                    foreach (var v in _HistoryTagInfos)
                    {
                        DateTime de = DateTime.Now;
                        DateTime ds = de.AddHours(-5);

                        var url = $"{_Url}/ts/history/snap?thingType=windturbine&thingId={Block.Id}&uniformCode={v.Code}&startTs={ds.GetTimeSpan()}&endTs={de.GetTimeSpan()}&interval=321";
                        var vs = _WEBHelper.HttpGetJSON<List<TsData>>(url);
                        Dispatcher.Invoke(() =>
                        {
                            v.UpdateHistoryData(vs);
                        });
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                await Task.Delay(7000);
            }
        }

        /// <summary>
        /// 刷新数据
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private async void RefreshData()
        {
            var url = $"{_Url}/ts/latest?thingType=windturbine&thingId={Block.Id}&uniformCodes={_Codes}";
            while (_IsActived)
            {
                try
                {
                    var vs = _WEBHelper.HttpGetJSON<Dictionary<string, TsData>>(url);
                    Dispatcher.Invoke(() =>
                    {
                        foreach (var v in _TagInfos)
                        {
                            v.UpdateValue(vs);
                        }
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                await Task.Delay(2000);
            }
        }

        /// <summary>
        /// 初始化UniformCode
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void InitCodes()
        {
            StringBuilder sb = new StringBuilder();
            foreach (var v in _TagInfos)
            {
                sb.Append(v.Code).Append(',');
            }
            _Codes = sb.ToString();
        }

        /// <summary>
        /// 初始化标签点信息
        /// </summary>
        private void InitTagInfos()
        {
            _TagInfos = new List<PVTagInfo>();
            var infos = _InfoService.GetPVDetails();
            if (infos == null) return;
            if (!infos.ContainsKey(Block.Info.Station)) return;
            Info = infos[Block.Info.Station];
            var vs = Info.CodeInfos?.Where(p => !p.IsIgnore);
            if (vs == null) return;
            foreach (var v in vs)
            {
                InverterPoint ip = new InverterPoint() { TagInfo = v, PVId = Block.Id };
                _UGSid.Children.Add(ip);
                _TagInfos.Add(v);
            }
            _HistoryTagInfos = Info.CodeInfos.Where(ci => ci.Type != PVTagType.Other).ToList();
            foreach (var v in _HistoryTagInfos)
            {
                v.HistoryValueChanged = HistoryValueChanged;
            }
        }

        /// <summary>
        /// 历史数据改变
        /// </summary>
        private void HistoryValueChanged(PVTagInfo pi, List<TsData> tds)
        {
            if (tds == null) return;
            AddAxisX(tds);
            switch (pi.Type)
            {
                case PVTagType.Power:
                    SetCahrValues(_CVPower, tds);
                    break;
                case PVTagType.Sunshine:
                    SetCahrValues(_CVSunshine, tds);
                    break;
                case PVTagType.Temperature:
                    SetCahrValues(_CVTemperature, tds);
                    break;
            }
        }

        /// <summary>
        /// 添加横坐标
        /// </summary>
        private void AddAxisX(List<TsData> val)
        {
            List<string> vs = new List<string>();
            DateTime dtStand = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
            foreach (var v in val)
            {
                DateTime dt = dtStand.AddMilliseconds(v.Ts);
                vs.Add(dt.ToShortTimeString());
            }
            if (vs.Count <= 0) return;
            _ChartAxisX.Labels = vs;
        }

        /// <summary>
        /// 设置图表数据 
        /// </summary>
        private void SetCahrValues(ChartValues<double> cv, List<TsData> values)
        {
            if (values == null || values.Count <= 0)
            {
                if (cv.Count <= 0)
                {
                    for (int i = 0; i < 56; ++i)
                    {
                        cv.Add(0);
                    }
                }
            }
            else
            {
                cv.Clear();
                foreach (var v in values)
                {
                    cv.Add(Math.Round(v.Value, 2));
                }
                Console.WriteLine("获得数据");
            }
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                this.DragMove();
            }
            catch { }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _IsActived = false;
            this.Close();
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount < 2 || !IsSUN2000) return;
            SUN2000InfoWindow.Show(this);
        }

        /// <summary>
        /// 显示光伏详情页
        /// </summary>
        internal static void Show(PVBlock ib)
        {
            InverterInfoWindow iiw = App.ServiceProvider.GetService(typeof(InverterInfoWindow)) as InverterInfoWindow;
            iiw.Block = ib;
            iiw.Owner = Application.Current.MainWindow;
            iiw.Status = ib.Status;
            iiw.ShowDialog();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            InitTagInfos();
            InitCodes();
            _IsActived = true;
            Task.Run(RefreshData);
            Task.Run(RefreshHistoryData);
        }
    }
}
