using log4net;
using NEIntelligentControl2.Models;
using NEIntelligentControl2.Models.AGC;
using NEIntelligentControl2.Models.Datas;
using NEIntelligentControl2.Models.Messages;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NEIntelligentControl2.Service.AGC
{
    /// <summary>
    /// AGC信息管理
    /// </summary>
    public class AGCManager
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(AGCManager));
        /// <summary>
        /// AGC 信息
        /// </summary>
        public List<AGCInfo> AGCInfos;
        /// <summary>
        /// 标签点
        /// </summary>
        private List<TagInfo> _TagInfos;
        /// <summary>
        /// 需要读取历史的标签点
        /// </summary>
        private List<TagInfo> _HistoryTagInfos;
        /// <summary>
        /// 所有标签点
        /// </summary>
        private string _Tags;
        /// <summary>
        /// 数据路径
        /// </summary>
        private string _Url;
        /// <summary>
        /// 历史数据url
        /// </summary>
        private string _HistoyUrl;
        /// <summary>
        /// 数据路径
        /// </summary>
        private string _DataUrl;
        /// <summary>
        /// 信息路径
        /// </summary>
        private string _UrlInfo;
        private WEBHelper _WEBHelper;
        public AGCManager(WEBHelper web)
        {
            _WEBHelper = web;
            InitUrl();
            Init();
        }

        private void InitUrl()
        {
            try
            {
#if (DEBUG)
                _UrlInfo = ConfigurationManager.AppSettings["ServicePathDebug"];
                _Url = ConfigurationManager.AppSettings["DataServicePathDebug"];
#else
                _UrlInfo = ConfigurationManager.AppSettings["ServicePath"];
                _Url = ConfigurationManager.AppSettings["DataServicePath"];
#endif
            }
            catch (Exception ex)
            {
                Console.WriteLine("读取配置文件[ServicePath]或[DataServicePath]出错！", ex);
            }
        }


        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
            try
            {
                _HistoryTagInfos = new List<TagInfo>();
                _TagInfos = new List<TagInfo>();
                AGCInfos = _WEBHelper.HttpGetJSON<List<AGCInfo>>($"{_UrlInfo}/api/station/agc_net");
                InitTags();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }


        /// <summary>
        /// 初始化标签点
        /// </summary>
        private void InitTags()
        {
            StringBuilder sb = new StringBuilder();
            foreach (var v in AGCInfos)
            {
                FindTags(sb, v.AiPoints);
                FindTags(sb, v.DiPoints);
                FindHistoryTags(v);
                _TagInfos.AddRange(v.AiPoints);
                _TagInfos.AddRange(v.DiPoints);
                _TagInfos.Add(v.Status);
                sb.Append(v.Status.Tag).Append(',');
            }
            _Tags = sb.ToString();
        }

        /// <summary>
        /// 枚举需要读取历史的标签点
        /// </summary>
        private void FindHistoryTags(AGCInfo ai)
        {
            _HistoryTagInfos.Add(ai.Status);

            var vs = ai.AiPoints.Where(p => (p.Type == TagType.PowerSet || p.Type == TagType.ActualPower) && !string.IsNullOrWhiteSpace(p.Tag));
            foreach (var v in vs)
            {
                _HistoryTagInfos.Add(v);
            }
        }

        /// <summary>
        /// 枚举标签
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="points"></param>
        private void FindTags(StringBuilder sb, List<TagInfo> points)
        {
            if (points == null) return;
            foreach (var v in points)
            {
                if (v == null) continue;
                foreach (var vv in v.Tags)
                {
                    if (string.IsNullOrWhiteSpace(vv)) continue;
                    sb.Append(vv).Append(',');
                }
            }
        }

        /// <summary>
        /// 数据刷新
        /// </summary>
        public void RefreshData(System.Windows.FrameworkElement fe)
        {
            try
            {
                if (_DataUrl == null)
                {
                    _DataUrl = $"{_Url}/ts/latest?keys={_Tags}";
                }
                var vs = _WEBHelper.HttpGetJSON<Dictionary<string, TsData>>(_DataUrl);
                fe.Dispatcher.Invoke(() =>
                {
                    try
                    {
                        foreach (var v in _TagInfos)
                        {
                            v.UpdateData(vs);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("曲线上面里" + ex.Message);
                    }
                });
            }
            catch (Exception ex)
            {
                log.Error("曲线上面" + ex.Message);
            }
        }

        /// <summary>
        /// 历史数据刷新
        /// </summary>
        public void RefreshLineData(System.Windows.FrameworkElement fe)
        {
            try
            {
                if (_HistoyUrl == null)
                {
                    _HistoyUrl = $"{_Url}/ts/history/snap?interval=60";
                }
                var dte = DateTime.Now.GetTimeSpan();
                var dts = DateTime.Now.AddHours(-8).GetTimeSpan();
                foreach (var v in _HistoryTagInfos)
                {
                    if (v.Tag == null) continue;
                    var vs = _WEBHelper.HttpGetJSON<List<TsData>>($"{_HistoyUrl}&tagName={v.Tag}&startTs={dts}&endTs={dte}");
                    fe.Dispatcher.Invoke(() => {
                        try {
                            v.UpdateHistoryData(vs);
                        }
                        catch(Exception ex)
                        {
                            log.Error("曲线里" + ex.Message);
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                log.Error("曲线" + ex.Message);
            }
        }
    }
}
