using Arction.Licensing; using Arction.Wpf.SignalProcessing; using LiveCharts.Defaults; using log4net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NPOI.SS.Formula.Functions; using Prism.Commands; using Prism.Events; using Prism.Mvvm; using Prism.Regions; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Configuration; using System.Data; using System.Data.SqlTypes; using System.Diagnostics; using System.IO; using System.Linq; using System.Media; using System.Reflection; using System.Runtime.Remoting.Contexts; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web.UI.WebControls; using System.Windows; using System.Windows.Documents; using System.Windows.Forms; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; using Txgy.EWS.Client.Common; using Txgy.EWS.Client.Common.Enums; using Txgy.EWS.Client.Common.Helpers; using Txgy.EWS.Client.Common.MessageEvents; using Txgy.EWS.Client.Entity; using Txgy.EWS.Client.FocalMechanism.Model; using Txgy.EWS.Client.IBLL; using Txgy.EWS.Client.ILog; using Txgy.EWS.Client.Models; using Txgy.EWS.Client.PageModule.Models; using Txgy.EWS.Client.PageModule.Services; using Txgy.Microseismic.BaseLib.Entitys; using Txgy.Microseismic.BaseLib.Models; using Unity; using static Txgy.EWS.Client.Common.GlobalConfig; namespace Txgy.EWS.Client.PageModule.ViewModels { public class EventListViewModel : BindableBase, INavigationAware { private readonly IEventAggregator ea; private readonly ISearchMsEventBLL searchMsEventBLL; private readonly ILogHelper _logHelper; //private readonly IRemoteDownloadDataBLL remoteDownloadDataBLL; Dispatcher _dispatcher; IFreeSql fsqlTencent = FreeSqlTencent.tencentRemoteMySQL; IFreeSql fsqlSqLite = FreeSqlLocalSqLite.freeLocalSqLite; private int middleEventCount = 0; /// /// 中等能量事件数量 /// public int MiddleEventCount { get { return middleEventCount; } set { SetProperty(ref middleEventCount, value); } } private double middleEnergy; /// /// 中等能量事件 /// public double MiddleEnergy { get { return middleEnergy; } set { SetProperty(ref middleEnergy, value); } } private FilterCondition _timeFC; public FilterCondition TimeFC { get { return _timeFC; } set { _timeFC = value; } } private FilterCondition _mlFC; public FilterCondition MLFC { get { return _mlFC; } set { _mlFC = value; } } private FilterCondition _energyFC; public FilterCondition EnergyFC { get { return _energyFC; } set { _energyFC = value; } } private FilterCondition _depthFC; public FilterCondition DepthFC { get { return _depthFC; } set { _depthFC = value; } } private FilterCondition _eastFC; public FilterCondition EastFC { get { return _eastFC; } set { _eastFC = value; } } private FilterCondition _northFC; public FilterCondition NorthFC { get { return _northFC; } set { _northFC = value; } } private SelectSort _selectSortMode; public SelectSort SelectSortMode { get { return _selectSortMode; } set { SetProperty(ref _selectSortMode, value); } } private DateTime _startTime; public DateTime StartTime { get { return _startTime; } set { SetProperty(ref _startTime, value); } } private DateTime _endTime; public DateTime EndTime { get { return _endTime; } set { SetProperty(ref _endTime, value); } } private int _searchCount = 0; public int SearchCount { get { return _searchCount; } set { SetProperty(ref _searchCount, value); } } private string _likeCondition; public string LikeCondition { get { return _likeCondition; } set { SetProperty(ref _likeCondition, value); } } private int _sortMode = 1; /// ///// 排序模式:-1=降序;1=升序; /// public int SortMode { get { return _sortMode; } set { SetProperty(ref _sortMode, value); } } private List middleEnergyEvents = new List(); public List MiddleEnergyEvents { get { return middleEnergyEvents; } set { SetProperty(ref middleEnergyEvents, value); } } private bool isCanRun = true; public bool IsCanRun { get { return isCanRun; } set { SetProperty(ref isCanRun, value); } } /// /// 刷新间隔(s) /// private int refreshInterval = 3; public int RefreshInterval { get { return refreshInterval; } set { SetProperty(ref refreshInterval, value); } } private string runSpan = "0"; public string RunSpan { get { return runSpan; } set { SetProperty(ref runSpan, value); } } private double alarmThreshold = 1; /// /// 报警阈值:J /// public double AlarmThreshold { get { return alarmThreshold; } set { SetProperty(ref alarmThreshold, value); } } public DateTime SystemRunTime { get; set; } /// /// 报警等级列表 /// public List ListAlarmLevel; public List ListAlramMusic { get; set; } SoundPlayer alarmPlayer = new SoundPlayer(); private bool canPlayAlarmSound = true; public bool CanPlayAlarmSound { get { return canPlayAlarmSound; } set { SetProperty(ref canPlayAlarmSound, value); } } private ObservableCollection _queryEventList; public ObservableCollection QueryEventList { get { return _queryEventList; } set { SetProperty(ref _queryEventList, value); } } private GridItemEventResult _queryEventListSelected; public GridItemEventResult QueryEventListSelected { get { return _queryEventListSelected; } set { SetProperty(ref _queryEventListSelected, value); if (value != null) { this.ea.GetEvent().Publish(QueryEventListSelected.EventTime); this.ea.GetEvent().Publish(QueryEventListSelected); } } } private Visibility checkBarVis = Visibility.Collapsed; public Visibility CheckBarVis { get { return checkBarVis; } set { SetProperty(ref checkBarVis, value); } } public ICommand QueryCommand { get => new Prism.Commands.DelegateCommand(() => { CheckBarVis = Visibility.Visible; List results=null; Task.Run(() => { DateTime st = TimeFC.Cond1; DateTime et = TimeFC.Cond2; results = SearchEvents(st, et); }).ContinueWith(t=> { if (results != null) { GlobalData.QueryEventList = new List(results); QueryEventList = new ObservableCollection(results); var mes = results.Where(rs => rs.Energy >= MiddleEnergy).ToList(); MiddleEnergyEvents = mes; MiddleEventCount = mes.Count(); this.ea.GetEvent().Publish(results); } }).ContinueWith(t2 => { CheckBarVis = Visibility.Collapsed; }); }); } private ICommand _searchEventsCommand; public ICommand SearchEventsCommand => _searchEventsCommand ?? (_searchEventsCommand = new Prism.Commands.DelegateCommand(async () => await ExecuteSearchEventsCommand())); public EventListViewModel(IUnityContainer unityContainer, IEventAggregator ea, ISearchMsEventBLL searchMsEventBLL, ILogHelper logHelper) { _dispatcher = unityContainer.Resolve(); this.ea = ea; this._logHelper = logHelper; this.searchMsEventBLL = searchMsEventBLL; int yy = DateTime.Now.Year; int mm = DateTime.Now.Month; int ss = DateTime.Now.Day; StartTime = new DateTime(yy, mm, ss).AddDays(-1); EndTime = new DateTime(yy, mm, ss); TimeFC = new FilterCondition(true, StartTime, EndTime); EastFC = new FilterCondition(false, GlobalConfig.ProjectConfig.WorkArea.EMax, GlobalConfig.ProjectConfig.WorkArea.EMin); NorthFC = new FilterCondition(false, GlobalConfig.ProjectConfig.WorkArea.NMax, GlobalConfig.ProjectConfig.WorkArea.NMin); DepthFC = new FilterCondition(false, GlobalConfig.ProjectConfig.WorkArea.ZMax, GlobalConfig.ProjectConfig.WorkArea.ZMin); MLFC = new FilterCondition(false, 0, -2); EnergyFC = new FilterCondition(false, 20000, 0); SelectSortMode = SelectSort.Time; MiddleEnergy = 200; if (GlobalData.QueryEventList != null) { QueryEventList = new ObservableCollection(GlobalData.QueryEventList); } } private async Task ExecuteSearchEventsCommand() { DateTime st = TimeFC.Cond1; DateTime et = TimeFC.Cond2; CheckBarVis = Visibility.Visible; List results = await SearchEventsAsync(st, et); if (results != null) { GlobalData.QueryEventList = new List(results); QueryEventList = new ObservableCollection(results); var mes = results.Where(rs => rs.Energy >= MiddleEnergy).ToList(); MiddleEnergyEvents = mes; MiddleEventCount = mes.Count; this.ea.GetEvent().Publish(results); } CheckBarVis = Visibility.Collapsed; } public async Task> SearchEventsAsync(DateTime searchStartTime, DateTime searchEndTime) { string findStr = BuildSqlQuery(searchStartTime, searchEndTime); var list = await fsqlTencent.Select().WithSql(findStr).ToListAsync(); // 使用 Task.WhenAll 并行处理每个事件 var eventTasks = list.Select(item => ProcessEventItem(item)); var eventResults = await Task.WhenAll(eventTasks); List results = eventResults.ToList(); SearchCount = results.Count; return results; } private async Task ProcessEventItem(RemoteRealtimeResultEntity item) { // ... 您原来的逻辑,处理每个事件 // 确保任何 IO 操作都是异步的 GridItemEventResult se = new GridItemEventResult(item, true); string eventTimeStr = se.EventTime; string datePath = eventTimeStr.Substring(0, 4) + eventTimeStr.Substring(5, 2) + eventTimeStr.Substring(8, 2); string dataFilePath = GlobalConfig.ProjectConfig.MseedFilePath + "\\" + datePath + "\\"; string dataFileName = "HA." + eventTimeStr.Substring(0, 4) + eventTimeStr.Substring(5, 2) + eventTimeStr.Substring(8, 2) + eventTimeStr.Substring(10, 3) + eventTimeStr.Substring(14, 2) + eventTimeStr.Substring(17, 2) + ".01" + GlobalConfig.DataTypeString; string jsonStr = ".json"; MmEvent curMmEvent = new MmEvent(); curMmEvent.EventTimeStr = eventTimeStr; curMmEvent.X = se.X; curMmEvent.Y = se.Y; curMmEvent.RMS = se.RMS; curMmEvent.DominantFreq = 15; await ComputeFMAsync(curMmEvent); //获取主频 curMmEvent.DominantFreq = GlobalData.GetDominFreq(eventTimeStr); //查询事件Json文件是否已下载 if (File.Exists(dataFilePath + dataFileName + jsonStr)) { FileInfo fileInfo = new FileInfo(dataFilePath + dataFileName + jsonStr); if (fileInfo.Length > 1024) { ComputeFM(curMmEvent); //获取主频 curMmEvent.DominantFreq = GlobalData.GetDominFreq(eventTimeStr); } } else { #region 同步方式 int res = new DownloadJsonFile().Download(eventTimeStr, dataFilePath, dataFileName + jsonStr, GlobalConfig.UseWaveDataTable); if (res > -1) { FileInfo fileInfo2 = new FileInfo(dataFilePath + dataFileName + jsonStr); if (fileInfo2.Length > 2000) { ComputeFM(curMmEvent); //获取主频 curMmEvent.DominantFreq = GlobalData.GetDominFreq(eventTimeStr); } } #endregion } se.SourceChara = (int)curMmEvent.FocalType; se.Direction = curMmEvent.Direction; se.DominantFreq = (int)curMmEvent.DominantFreq; se.SetEnergy(); return se; } private string BuildSqlQuery(DateTime searchStartTime, DateTime searchEndTime) { string findStr = ""; if (TimeFC.IsUse) { DateTime st = searchStartTime; DateTime et = searchEndTime; string startStr = st.Year.ToString() + "-" + st.Month.ToString("D2") + "-" + st.Day.ToString("D2") + "T" + st.Hour.ToString("D2") + ":" + st.Minute.ToString("D2") + ":" + st.Second.ToString("D2"); string endStr = et.Year.ToString() + "-" + et.Month.ToString("D2") + "-" + et.Day.ToString("D2") + "T" + et.Hour.ToString("D2") + ":" + et.Minute.ToString("D2") + ":" + et.Second.ToString("D2"); findStr += " where (EventTime>='" + startStr + "' and EventTime<'" + endStr + "')"; } if (MLFC.IsUse || EnergyFC.IsUse || DepthFC.IsUse || EastFC.IsUse || NorthFC.IsUse) { if (MLFC.IsUse) { findStr += " and (ML>=" + MLFC.Cond2 + " and ML<" + MLFC.Cond1 + ")"; } //if (EnergyFC.IsUse) //{ // findStr += " and (ML>=" + EnergyFC.Cond2 + " and ML<" + EnergyFC.Cond1 + ")"; //} if (DepthFC.IsUse) { findStr += " and (Z>=" + DepthFC.Cond2 + " and Z<" + DepthFC.Cond1 + ")"; } if (EastFC.IsUse) { findStr += " and (Y>=" + EastFC.Cond2 + " and Y<" + EastFC.Cond1 + ")"; } if (NorthFC.IsUse) { findStr += " and (X>=" + NorthFC.Cond2 + " and X<" + NorthFC.Cond1 + ")"; } if (SortMode == 1) { } } var queryBuilder = new StringBuilder("select * from "); queryBuilder.Append(GlobalConfig.UseResultTable); queryBuilder.Append(findStr); return queryBuilder.ToString(); } private async Task ComputeFMAsync(MmEvent curMmEvent) { string downLoadStr = curMmEvent.EventTimeStr; 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(11, 2) + downLoadStr.Substring(14, 2) + downLoadStr.Substring(17, 2) + ".01" + GlobalConfig.DataTypeString + ".json"; string jsonFilePath = Path.Combine(GlobalConfig.ProjectConfig.MseedFilePath, datePath); int fileSize = 0; // 注意:这里我们使用了异步的文件存在检查方法 if (!await Task.Run(() => File.Exists(Path.Combine(jsonFilePath, jsonStr)))) { fileSize = await DownloadJsonFile.DownloadAsync(downLoadStr, jsonFilePath, jsonStr, GlobalConfig.UseWaveDataTable); } if (fileSize > 2000) { using (StreamReader sr = new StreamReader(Path.Combine(jsonFilePath, jsonStr), Encoding.UTF8, true, 1024)) { curMmEvent.JsonFile = Path.Combine(jsonFilePath, jsonStr); using (JsonTextReader reader = new JsonTextReader(sr)) { JArray jArray = await JArray.LoadAsync(reader); //解析普通属性和数组混合的Json文件 //数组0是普通属性集合 JObject jobj = (JObject)jArray[0]; curMmEvent.SetEnergy(); curMmEvent.Phases = new Dictionary(); JArray phaseArr = JArray.FromObject(jobj["phases"]); for (int i = 0; i < phaseArr.Count; i++) { if (phaseArr[i]["first_motion_direct"] != null) { curMmEvent.Phases.Add(phaseArr[i]["id"].ToString().Substring(3, 3), int.Parse(phaseArr[i]["first_motion_direct"].ToString())); } } } } FMMap fmMap = CreateFM(curMmEvent, GlobalConfig.ProjectConfig.WorkArea.EMin, GlobalConfig.ProjectConfig.WorkArea.NMin); ComputationResult cr = GlobalConfig.fmCore.ComputeResult(fmMap); if (cr == null) return; curMmEvent.FocalType = cr.FocalType; curMmEvent.Direction = cr.Direction; } } public List SearchEvents(DateTime searchStartTime, DateTime searchEndTime) { List results = new List(); string findStr = "select * from " + GlobalConfig.UseResultTable; if (TimeFC.IsUse) { DateTime st = searchStartTime; DateTime et = searchEndTime; string startStr = st.Year.ToString() + "-" + st.Month.ToString("D2") + "-" + st.Day.ToString("D2") + "T" + st.Hour.ToString("D2") + ":" + st.Minute.ToString("D2") + ":" + st.Second.ToString("D2"); string endStr = et.Year.ToString() + "-" + et.Month.ToString("D2") + "-" + et.Day.ToString("D2") + "T" + et.Hour.ToString("D2") + ":" + et.Minute.ToString("D2") + ":" + et.Second.ToString("D2"); findStr += " where (EventTime>='" + startStr + "' and EventTime<'" + endStr + "')"; } if (MLFC.IsUse || EnergyFC.IsUse || DepthFC.IsUse || EastFC.IsUse || NorthFC.IsUse) { if (MLFC.IsUse) { findStr += " and (ML>=" + MLFC.Cond2 + " and ML<" + MLFC.Cond1 + ")"; } //if (EnergyFC.IsUse) //{ // findStr += " and (ML>=" + EnergyFC.Cond2 + " and ML<" + EnergyFC.Cond1 + ")"; //} if (DepthFC.IsUse) { findStr += " and (Z>=" + DepthFC.Cond2 + " and Z<" + DepthFC.Cond1 + ")"; } if (EastFC.IsUse) { findStr += " and (Y>=" + EastFC.Cond2 + " and Y<" + EastFC.Cond1 + ")"; } if (NorthFC.IsUse) { findStr += " and (X>=" + NorthFC.Cond2 + " and X<" + NorthFC.Cond1 + ")"; } if (SortMode == 1) { } } var list = fsqlTencent.Select() .WithSql(findStr).ToList(); if (list != null) { foreach (var item in list) { GridItemEventResult se = new GridItemEventResult(item, true); string eventTimeStr = se.EventTime; string datePath = eventTimeStr.Substring(0, 4) + eventTimeStr.Substring(5, 2) + eventTimeStr.Substring(8, 2); string dataFilePath = GlobalConfig.ProjectConfig.MseedFilePath + "\\" + datePath + "\\"; string dataFileName = "HA." + eventTimeStr.Substring(0, 4) + eventTimeStr.Substring(5, 2) + eventTimeStr.Substring(8, 2) + eventTimeStr.Substring(10, 3) + eventTimeStr.Substring(14, 2) + eventTimeStr.Substring(17, 2) + ".01" + GlobalConfig.DataTypeString; string jsonStr = ".json"; MmEvent curMmEvent = new MmEvent(); curMmEvent.EventTimeStr = eventTimeStr; curMmEvent.X = se.X; curMmEvent.Y = se.Y; curMmEvent.RMS = se.RMS; curMmEvent.DominantFreq = 15; //查询事件Json文件是否已下载 if (File.Exists(dataFilePath + dataFileName + jsonStr)) { FileInfo fileInfo = new FileInfo(dataFilePath + dataFileName + jsonStr); if (fileInfo.Length > 1024) { ComputeFM(curMmEvent); //获取主频 curMmEvent.DominantFreq = GlobalData.GetDominFreq(eventTimeStr); } } else { #region 同步方式 int res = new DownloadJsonFile().Download(eventTimeStr, dataFilePath, dataFileName + jsonStr, GlobalConfig.UseWaveDataTable); if (res > -1) { FileInfo fileInfo2 = new FileInfo(dataFilePath + dataFileName + jsonStr); if (fileInfo2.Length > 2000) { ComputeFM(curMmEvent); //获取主频 curMmEvent.DominantFreq = GlobalData.GetDominFreq(eventTimeStr); } } #endregion } //Random dominRnd = new Random((int)DateTime.Parse(curMmEvent.EventTimeStr).Ticks); //int dominFreq = (int)curMmEvent.DominantFreq; //if (curMmEvent.DominantFreq < 14) //{ // dominFreq = dominRnd.Next(26, 80); //} //se.DominantFreq = dominFreq; se.SourceChara = (int)curMmEvent.FocalType; se.Direction = curMmEvent.Direction; se.DominantFreq = (int)curMmEvent.DominantFreq; se.SetEnergy(); results.Add(se); } } SearchCount = results.Count; return results; } public void ComputeFM(MmEvent mmEvent) { string downLoadStr = mmEvent.EventTimeStr; 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 + "\\"; if (!File.Exists(jsonFilePath + jsonStr)) { new DownloadJsonFile().Download(downLoadStr, jsonFilePath, jsonStr, GlobalConfig.UseWaveDataTable); } using (StreamReader sr = System.IO.File.OpenText(jsonFilePath + jsonStr)) { mmEvent.JsonFile = jsonFilePath + jsonStr; JsonTextReader reader = new JsonTextReader(sr); JArray jArray = (JArray)JToken.ReadFrom(reader); //解析普通属性和数组混合的Json文件 //数组0是普通属性集合 JObject jobj = (JObject)jArray[0]; //mmEvent.SetEnergy(); //mmEvent.Energy= mmEvent.Phases = new Dictionary(); JArray phaseArr = JArray.FromObject(jobj["phases"]); for (int i = 0; i < phaseArr.Count; i++) { if (phaseArr[i]["first_motion_direct"] != null) { mmEvent.Phases.Add(phaseArr[i]["id"].ToString().Substring(3, 3), int.Parse(phaseArr[i]["first_motion_direct"].ToString())); } } } FMMap fmMap = CreateFM(mmEvent, GlobalConfig.ProjectConfig.WorkArea.EMin, GlobalConfig.ProjectConfig.WorkArea.NMin); ComputationResult cr = GlobalConfig.fmCore.ComputeResult(fmMap); if (cr == null) return; mmEvent.FocalType = cr.FocalType; mmEvent.Direction = cr.Direction; } public FMMap CreateFM(MmEvent mmEvent, double BaseX, double BaseY) { FMMap fmMap = new FMMap(); fmMap.X = mmEvent.X - BaseX; fmMap.Y = mmEvent.Y - BaseY; fmMap.R = mmEvent.RMS; foreach (var item in mmEvent.Phases) { if (item.Value == -1) { fmMap.negStation.Add(item.Key); } else { fmMap.posStation.Add(item.Key); } } return fmMap; } bool CanStartMonitor() { return !GlobalData.IsRunning; } private void PutSamplesToChart(DataGeneratedEventArgs args) { //(Application.Current. as View).chart1.BeginUpdate(); } public void MSeed2Asc(string filePath, string savePath) { using (Process compiler = new Process()) { compiler.StartInfo.FileName = "mseed2ascii.exe"; compiler.StartInfo.Arguments = filePath + " -o " + savePath; compiler.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; compiler.Start(); compiler.WaitForExit(); } } public void OnNavigatedTo(NavigationContext navigationContext) { } public bool IsNavigationTarget(NavigationContext navigationContext) { return false; } public void OnNavigatedFrom(NavigationContext navigationContext) { //throw new NotImplementedException(); } } }