using NEIntelligentControl2.Models.Alarm;
using NEIntelligentControl2.Models.Datas;
using NEIntelligentControl2.Models.Messages;
using NEIntelligentControl2.Models.PV;
using NEIntelligentControl2.Models.Windturbine;
using NEIntelligentControl2.Models.WinForms;
using NEIntelligentControl2.Service.WebSocket;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace NEIntelligentControl2.Service.Windturbine
{
    /// <summary>
    /// 光伏和风机详情服务
    /// </summary>
    public class InfoManager
    {
        private WEBHelper _WEBHelper;
        private Dictionary<string, PVDetails> _PVDetails;
        private List<SUN2000Info> _SUN2000Info;
        private AlarmTypeInfo _AlarmTypeInfo;
        private string _Url;
        private string _DataUrl;
        private Dictionary<string, IList<UniformCodeInfo>> _UniformCodesPairs = new Dictionary<string, IList<UniformCodeInfo>>();// 节点缓存
        /// <summary>
        /// 参数对比信息
        /// </summary>
        private Dictionary<string, Dictionary<string, List<ParameterInfo>>> _ParameterInfo = new Dictionary<string, Dictionary<string, List<ParameterInfo>>>();
        public InfoManager(WEBHelper web, UrlManager um)
        {
            _WEBHelper = web;
            _Url = um.ServicePath;
            _DataUrl = um.DataServicePath;
        }


        public AlarmTypeInfo GetAlarmTypeInfo()
        {
            if (_AlarmTypeInfo == null)
            {
                try
                {
                    string text = System.IO.File.ReadAllText("AlarmInfo.json");
                    _AlarmTypeInfo = _WEBHelper.Deserialize<AlarmTypeInfo>(text);
                }
                catch (Exception e) { Console.WriteLine(e.Message); }
            }
            return _AlarmTypeInfo;
        }

        public Dictionary<string, PVDetails> GetPVDetails()
        {
            try
            {
                if (_PVDetails == null)
                {
                    _PVDetails = _WEBHelper.HttpGetJSON<Dictionary<string, PVDetails>>($"{_Url}/api/station/pv_info");
                }
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); }
            return _PVDetails;
        }

        public List<SUN2000Info> GetSUN2000Infos()
        {
            if (_SUN2000Info == null)
            {
                try
                {
                    string text = System.IO.File.ReadAllText("SUN2000Info.json");
                    _SUN2000Info = _WEBHelper.Deserialize<List<SUN2000Info>>(text);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            return _SUN2000Info;
        }

        internal IList<UniformCodeInfo> GetUniformCode(string stationId, string modelId)
        {
            var key = $"{stationId}{modelId}";
            if (_UniformCodesPairs.ContainsKey(key))
            {
                return _UniformCodesPairs[key];
            }
            IList<UniformCodeInfo> list = new List<UniformCodeInfo>();

            string path = Environment.CurrentDirectory;
            string filePath = path + "\\UniformCode.xml";
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(filePath); //加载xml文档
            XmlNode root = xdoc.DocumentElement;

            // 找到对应station节点下的对应model节点下的part节点
            XmlNodeList partNodelist = root.SelectNodes("/root/station[@name='" + stationId + "']/model[@name='" + modelId + "']/part");
            foreach (XmlNode part in partNodelist)
            {
                foreach (XmlNode param in part.SelectNodes("param"))
                {
                    try
                    {
                        UniformCodeInfo data = new UniformCodeInfo();
                        data.PartIndex = part.Attributes["index"].Value;
                        data.PartName = part.Attributes["text"].Value;

                        data.Name = param.Attributes["name"].Value;
                        data.UniformCode = param.Attributes["value"].Value;
                        data.Unit = param.Attributes["unit"].Value;
                        int tindex = 0;
                        data.Index = int.TryParse(param.Attributes["num"].Value, out tindex) ? tindex : 0;
                        data.PlcName = param.Attributes["plcName"] != null ? param.Attributes["plcName"].Value : "";
                        data.WarningNum = param.Attributes["warningNum"] != null ? param.Attributes["warningNum"].Value : "";
                        if (param.Attributes["ratio"] != null)
                        {
                            double.TryParse(param.Attributes["ratio"].Value, out double d);
                            data.Ratio = d;
                        }
                        list.Add(data);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("xml配置读取错误：" + ex.StackTrace);
                    }
                }
            }
            _UniformCodesPairs.Add(key, list);
            return list;
        }

        /// <summary>
        /// 获取参数对比信息
        /// </summary>
        /// <param name="stationId">场站ID</param>
        /// <param name="modleId">机型ID</param>
        /// <returns></returns>
        public List<ParameterInfo> GetParameterInfos(string stationId, string modleId)
        {
            if (_ParameterInfo.Count <= 0)
            {
                try
                {
                    string text = System.IO.File.ReadAllText("ComparisonInfo.json");
                    _ParameterInfo = _WEBHelper.Deserialize<Dictionary<string, Dictionary<string, List<ParameterInfo>>>>(text);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }

            if (_ParameterInfo.Count <= 0 || !_ParameterInfo.ContainsKey(stationId) || !_ParameterInfo[stationId].ContainsKey(modleId)) return new List<ParameterInfo>();
            return _ParameterInfo[stationId][modleId];
        }

        public Dictionary<string ,TsData> GetPointDatas(string windturbineId, string[] ucs)
        {
            Dictionary<string, TsData> dic = _WEBHelper.HttpGetJSON<Dictionary<string, TsData>>($"{_DataUrl}/ts/latest?thingType=windturbine&thingId={windturbineId}&uniformCodes={string.Join(",", ucs)}");
            return dic;
        }

        public Dictionary<string, TsData> GetPointDatasByTags(string[] tags)
        {
            Dictionary<string, TsData> dic = _WEBHelper.HttpGetJSON<Dictionary<string, TsData>>($"{_DataUrl}/ts/latest?keys={string.Join(",", tags)}");
            return dic;
        }

        public List<PointInfo> GetAIPoints(string windId)
        {
            return _WEBHelper.HttpGetJSON<List<PointInfo>>($"{_Url}/windturbinetestingpoint/ai?windturbineid={windId}");
        }

        public List<PointInfo> GetDIPoints(string windId)
        {
            return _WEBHelper.HttpGetJSON<List<PointInfo>>($"{_Url}/windturbinetestingpoint/Di?windturbineid={windId}");
        }
    }
}
