using FreeSql.Internal.Model;
using MaterialDesignThemes.Wpf;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using Txgy.EWS.Client.Entity;
using Txgy.EWS.Client.Models;
using Txgy.Microseismic.BaseLib.Models;
using System.Windows.Media.Media3D;
using Txgy.EWS.Client.Common.MessageEvents;

namespace Txgy.EWS.Client.Common
{
    public class GlobalData : BindableBase
    {
        //public static bool IsDesign = true;

        public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
        public static UserInfoEntity CurrentUserInfo { get; set; }
        public static List<Task> TaskList = new List<Task>();

        /// <summary>
        /// 事件显示时限，秒
        /// </summary>
        public static int EventShowTimeout = 39600;
        /// <summary>
        /// 平面有效时限，秒
        /// </summary>
        public static int ValidSecend = 432000;
        /// <summary>
        /// 事件到预警平面的距离
        /// </summary>
        public static double PlanToEventDis = 100;
        public static int maxUnbrokenFocal = 0;
        public static int maxFrequency = 0;
        public static List<int> unbrokenSameFocalList = new List<int>();
        public static List<int> frequencyList = new List<int>();
        public static List<Plane> AlarmPlanList { get; set; } = new List<Plane>();
        private static int _curAlarmLevelValue;

        public static int CurAlarmLevelValue
        {
            get { return _curAlarmLevelValue; }
            set 
            { 
                _curAlarmLevelValue = value;
                StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs("CurAlarmLevelValue"));
            }
        }
        private static Brush _curAlarmLevelColor;

        public static Brush CurAlarmLevelColor
        {
            get { return _curAlarmLevelColor; }
            set
            {
                _curAlarmLevelColor = value;
                StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs("CurAlarmLevelColor"));
            }
        }
        //private static AlarmLevelModel curAlarmLevel;
        ///// <summary>
        ///// 当前预警等级
        ///// </summary>
        //public static AlarmLevelModel CurAlarmLevel
        //{
        //    get { return curAlarmLevel; }
        //    set
        //    {
        //        curAlarmLevel= value;
        //        StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs("CurAlarmLevel"));
        //    }
        //}
        private static int _alarmPlanCount=0;
        /// <summary>
        /// 预警平面数量
        /// </summary>
        public static int AlarmPlanCount
        {
            get { return _alarmPlanCount; }
            set 
            { 
                _alarmPlanCount = value;
                StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs("AlarmPlanCount"));
            }
        }
        private static int _midEventCount;
        /// <summary>
        /// 中等能量事件数量
        /// </summary>
        public static int MidEventCount
        {
            get { return _midEventCount; }
            set 
            { 
                _midEventCount = value;
                StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs("MidEventCount"));
            }
        }
        private static List<GridItemEventResult> _queryEventList=new List<GridItemEventResult>();

        public static List<GridItemEventResult> QueryEventList
        {
            get { return _queryEventList; }
            set 
            { 
                _queryEventList = value;
                //StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs("QueryEventList"));
            }
        }
        //private static GridItemEventResult _queryEventListSelected;

        //public static GridItemEventResult QueryEventListSelected
        //{
        //    get { return _queryEventListSelected; }
        //    set 
        //    { 
        //        _queryEventListSelected = value;
        //        StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs("QueryEventListSelected"));
        //        //this.ea.GetEvent<ShowWavesEvent>().Publish(selectGirdItem.EventTime);
        //    }
        //}

        private static ObservableCollection<ReportEventLevel> reportEventLevelList = new ObservableCollection<ReportEventLevel>();
        /// <summary>
        /// 报表事件等级列表
        /// </summary>
        public static ObservableCollection<ReportEventLevel> ReportEventLevelList
        {
            get { return reportEventLevelList; }
            set
            {
                reportEventLevelList = value;
                StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs("EportEventLevelList"));
            }
        }
        private static ObservableCollection<GridItemEventResult> gridEvents = new ObservableCollection<GridItemEventResult>();

        public static ObservableCollection<GridItemEventResult> GridEvents
        {
            get { return gridEvents; }
            set
            {
                gridEvents = value;
                StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs("GridEvents"));
            }
        }
        private static ObservableCollection<GridItemEventResult> searchEvents = new ObservableCollection<GridItemEventResult>();
        public static ObservableCollection<GridItemEventResult> SearchEvents
        {
            get { return searchEvents; }
            set
            {
                searchEvents = value;
                StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs("SearchEvents"));
            }

        }
        public static List<GridItemEventResult> MidEventList=new List<GridItemEventResult>();
        public static List<MmEvent> StatEvents { get; set; } = new List<MmEvent>();
        public static GridItemEventResult LastEvent { get; set; } = new GridItemEventResult();
        public static List<int> ListAlarmEventId = new List<int>();
        
        public static List<GridItemEventResult> ReceivedEvents { get; set; } = new List<GridItemEventResult>();
        public static List<GridItemEventResult> AlarmEvents { get; set; } = new List<GridItemEventResult>();

        private static bool isRunning = false;
        public static bool IsRunning
        {
            get { return isRunning; }
            set
            {
                isRunning = value;
                StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs("SystemLoadingEvent"));
            }
        }
        private static bool appendEvent = false;
        public static bool AppendEvent
        {
            get { return appendEvent; }
            set
            {
                appendEvent = value;
                StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs("AppendEvent"));
            }
        }
        /// <summary>
        /// 深拷贝
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T DeepCopyByReflection<T>(T obj)
        {
            if (obj is string || obj.GetType().IsValueType)
                return obj;

            object retval = Activator.CreateInstance(obj.GetType());
            FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
            foreach (var field in fields)
            {
                try
                {
                    field.SetValue(retval, DeepCopyByReflection(field.GetValue(obj)));
                }
                catch { }
            }

            return (T)retval;
        }
        public static List<MmEvent> FillEvents(List<MmEvent> sourceEvents)
        {
            List<MmEvent> result = new List<MmEvent>();
            foreach (var item in sourceEvents)
            {
                result.Add(new MmEvent
                {
                    X = item.X,
                    Y = item.Y,
                    Z = item.Z,
                    EventID = item.EventID,
                    ML = item.ML,
                    LocSta = item.LocSta,
                    MLSta = item.MLSta,
                    EventTime = item.EventTime,
                    RMS = item.RMS,
                    WorkAreaID = item.WorkAreaID,
                });
            }
            return result;
        }
        public static void PlanesAddEvent(GridItemEventResult pe)
        {
            Point3D point = GlobalConfig.AbsoluteCoord2RelativeCoord(pe);
            foreach (var plane in AlarmPlanList.Where(ap => ap.Valid == true))
            {
                double dis = plane.GetEventToPlaneDistance(point);
                //Debug.WriteLine(dis);
                if (dis <= PlanToEventDis)
                {
                    if (pe.SourceChara == plane.LastSameFocal)
                    {
                        plane.UnbrokenSameFocalCount++;
                        plane.MaxUnbrokenSameFocalCount = plane.UnbrokenSameFocalCount;
                    }
                    else
                    {
                        plane.UnbrokenSameFocalCount = 0;
                    }
                    plane.InRangeEventList.Add(pe);
                    plane.LastSameFocal = pe.SourceChara;
                }
            }
        }
        /// <summary>
        /// 获取主频
        /// </summary>
        /// <param name="mmEvent"></param>
        /// <returns></returns>
        public static int GetDominFreq(string eventTime)
        {
            string downLoadStr = eventTime;
            string datePath = downLoadStr.Substring(0, 4) + downLoadStr.Substring(5, 2) + downLoadStr.Substring(8, 2);
            string jsonStr = "HA." + downLoadStr.Substring(0, 4) + downLoadStr.Substring(5, 2)
                + downLoadStr.Substring(8, 2) + downLoadStr.Substring(10, 3)
                + downLoadStr.Substring(14, 2) + downLoadStr.Substring(17, 2) + ".01" + GlobalConfig.DataTypeString + ".json";
            string jsonFilePath = GlobalConfig.ProjectConfig.MseedFilePath + "\\" + datePath + "\\" + jsonStr;
            int dominantFreq = 0;
            if (File.Exists(jsonFilePath))
            {
                if (new FileInfo(jsonFilePath).Length < 100)
                {
                    return dominantFreq;
                }
                try
                {
                    using (StreamReader sr = System.IO.File.OpenText(jsonFilePath))
                    {
                        JsonTextReader reader = new JsonTextReader(sr);
                        JArray jArray = (JArray)JToken.ReadFrom(reader);
                        //解析普通属性和数组混合的Json文件
                        //数组0是普通属性集合
                        JObject jobj = (JObject)jArray[0];

                        List<double> DominantFreqlist = new List<double>();
                        JArray phaseArr = JArray.FromObject(jobj["phases"]);
                        //List<double> DominantFreqList = new List<double>();
                        for (int i = 0; i < phaseArr.Count; i++)
                        {
                            if (phaseArr[i]["zcr"] != null)
                            {
                                DominantFreqlist.Add(double.Parse(phaseArr[i]["zcr"].ToString()));
                            }
                        }
                        if (DominantFreqlist.Count > 0)
                        {
                            if (DominantFreqlist.Count > 3)
                            {
                                double min = DominantFreqlist.Min();
                                double max = DominantFreqlist.Max();
                                DominantFreqlist.Remove(min);
                                DominantFreqlist.Remove(max);
                                dominantFreq = (int)((DominantFreqlist.Sum() / (double)DominantFreqlist.Count));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    //return 0;
                    throw ex;
                }
            }
            return dominantFreq;
        }
        public static string FocalMechanismType2String(FocalMechanismType fmt)
        {
            string focalStr = "张性";
            switch (fmt)
            {
                case FocalMechanismType.strikeSlip:
                    focalStr = "走滑";
                    break;
                case FocalMechanismType.dipSlip:
                    focalStr = "倾滑";
                    break;
                case FocalMechanismType.unknown:
                    focalStr = "未识别";
                    break;

            }
            return focalStr;
        }
        public static string FocalMechanismIndex2String(int fmt)
        {
            string focalStr = "张性";
            switch (fmt)
            {
                case 0:
                    focalStr = "走滑";
                    break;
                case 1:
                    focalStr = "倾滑";
                    break;
                case 2:
                    focalStr = "张性";
                    break;
                case 3:
                    focalStr = "未识别";
                    break;
            }
            return focalStr;
        }
    }
}
