using LiveCharts;
using LiveCharts.Configurations;
using NEIntelligentControl2.Models.AGC;
using NEIntelligentControl2.Models.Datas;
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.AGC
{
    /// <summary>
    /// AGC卡片
    /// </summary>
    public partial class AGCCard : UserControl
    {
        // ------------依赖属性------------
        public static readonly DependencyProperty StatusProperty = DependencyProperty.Register("Status", typeof(double), typeof(AGCCard));
        public static readonly DependencyProperty RestrictionValueProperty = DependencyProperty.Register("RestrictionValue", typeof(string), typeof(AGCCard));
        /// <summary>
        /// 状态
        /// </summary>
        public double Status { get => (double)GetValue(StatusProperty); set => SetValue(StatusProperty, value); }
        /// <summary>
        /// 限电值
        /// </summary>
        public string RestrictionValue { get => GetValue(RestrictionValueProperty) as string; set => SetValue(RestrictionValueProperty, value); }
        private AGCInfo info;
        /// <summary>
        /// 信息
        /// </summary>
        public AGCInfo Info { get => info; set { info = value; InitInfo(); } }

        private IEnumerable<TagInfo> _PowerTags;
        /// <summary>
        /// 有功设定数据（历史）
        /// </summary>
        private ChartValues<TsData> _CVPowerSet { get; set; } = new ChartValues<TsData>();
        /// <summary>
        /// 实发有功数据（历史）
        /// </summary>
        private ChartValues<TsData> _CVPower { get; set; } = new ChartValues<TsData>();

        private int _CountUpdate;
        public AGCCard()
        {
            InitializeComponent();
            _LSPowerSet.Values = _CVPowerSet;
            _LSPower.Values = _CVPower;
            _LSPower.Configuration = _LSPowerSet.Configuration = Mappers.Xy<TsData>().X(d => d == null ? 0 : d.Ts).Y(d => d == null ? 0 : Math.Round(d.Value,2));
            _ChartAxisX.LabelFormatter = x => TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddMilliseconds(x).ToShortTimeString();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void InitInfo()
        {
            if (info == null)
            {
                return;
            }
            _UGMain.Children.Clear();
            info.Status.ValueChanged = (v) => Status = v;
            foreach (var v in info.AiPoints)
            {
                AGCTag at = new AGCTag() { Info = v };
                _UGMain.Children.Add(at);
            }
            foreach (var v in info.DiPoints)
            {
                AGCTag at = new AGCTag() { Info = v, IsDiPoint = true };
                _UGDiPoint.Children.Add(at);
            }
            var vs = info.AiPoints.Where(ap => ap.Type == TagType.PowerSet || ap.Type == TagType.ActualPower);
            _PowerTags = vs;
            foreach (var v in vs)
            {
                v.HistoryValueChanged = HistoryValueChanged;
            }

            var rv = info.AiPoints.Where(ap => ap.Type == TagType.PowerSet).FirstOrDefault();
            rv.ValueChanged += PowerSetChanged;
        }

        /// <summary>
        /// 有功设定值改变
        /// </summary>
        private void PowerSetChanged(double obj)
        {
            RestrictionValue = (1 - (obj / info.InstalledCapacity)).ToString("p");
            UpdateHistoryData();
        }

        private void UpdateHistoryData()
        {
            ++_CountUpdate;
            if (_CountUpdate < 30) return;
            long ts = _PowerTags.Max(t => t.Ts);
            foreach (var v in _PowerTags)
            {
                var td = new TsData() { Ts = ts, Value = v.Value };
                if (v.Type == TagType.PowerSet)
                {
                    AddData(_CVPowerSet, td);
                }
                else
                {
                    AddData(_CVPower, td);
                }
            }
            _CountUpdate = 0;
        }

        private void AddData(ChartValues<TsData> cv, TsData td)
        {
            if (cv.Count > 0)
            {
                var v = cv[cv.Count - 1];
                if (v.Ts >= td.Ts) return;
            }
            cv.Add(td);
            RemoveData(_CVPowerSet, td.Ts);
        }

        private void RemoveData(ChartValues<TsData> cv, long ts)
        {
            List<TsData> list = new List<TsData>();
            var d = ts - 28800000;
            foreach (var v in cv)
            {
                if (v.Ts >= d) break;
                list.Add(v);
            }
            foreach(var v in list)
            {
                cv.Remove(v);
            }
        }

        /// <summary>
        /// 历史值改变
        /// </summary>
        private void HistoryValueChanged(TagInfo arg1, List<TsData> arg2)
        {
            if (arg2 == null || arg2.Count <= 0) return;
            if (arg1.Type == TagType.PowerSet)
            {
                UpdateHistoryData(_CVPowerSet, arg2);
            }
            else
            {
                UpdateHistoryData(_CVPower, arg2);
            }
            //_WLCMain.UpdateData(arg1, arg2);
        }

        private void UpdateHistoryData(ChartValues<TsData> cv, List<TsData> arg2)
        {
            cv.Clear();
            foreach (var v in arg2)
            {
                cv.Add(v);
            }
        }
    }
}
