using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Txgy.EWS.Client.Common;
using Txgy.EWS.Client.Common.Helpers;
using Txgy.EWS.Client.IDAL;
using Txgy.EWS.Client.Models;
using Txgy.Microseismic.BaseLib.Common;
using Txgy.Microseismic.BaseLib.Entitys;
using Txgy.Microseismic.BaseLib.Helpers;
using Txgy.Microseismic.BaseLib.Models;

namespace Txgy.EWS.Client.DAL
{
    public class RemoteMySQLDataAccess : IRemoteMySQLDataAccess
    {
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        IFreeSql fsql = FreeSqlTencent.tencentRemoteMySQL;
        public string saveWavePath = "";
        public MySqlConnection RemoteConn { get; set; }
        public MySqlCommand Comm { get; set; }
        public MySqlDataAdapter Adap { get; set; }
        private int preSelectCount = 0;
        private static SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
        private string _connectionString => BusinessConfigManager.GetConnectionString("TencetnMySQL");
        int IRemoteMySQLDataAccess.PreSelectCount
        {
            get { return preSelectCount; }
            set { preSelectCount = value; }
        }

        private void Dispose()
        {
            if (Adap != null)
            {
                Adap.Dispose();
                Adap = null;
            }
            if (Comm != null)
            {
                Comm.Dispose();
                Comm = null;
            }
            if (RemoteConn != null)
            {
                RemoteConn.Close();
                RemoteConn.Dispose();
                RemoteConn = null;
            }
        }
        private bool DBConnection()
        {
            string connStr = BusinessConfigManager.GetConnectionString("TencetnMySQL");
            if (RemoteConn == null)
                RemoteConn = new MySqlConnection(connStr);
            try
            {
                if (RemoteConn.State != ConnectionState.Open)
                {
                    RemoteConn.Open();
                }
                return true;
            }
            catch (Exception ex)
            {
                logger.Error("数据库连接失败", ex);
                return false;
            }
        }
        public List<postproeventresult> GetEvents(DateTime startTime, DateTime endTime, int pageIndex, int perPageCount, float minML = -1, float maxML = 0)
        {
            List<postproeventresult> pps = new List<postproeventresult>();
            try
            {
                string startStr = startTime.Year.ToString() + "-" + startTime.Month.ToString("D2") + "-" + startTime.Day.ToString("D2") + "T" +
                   startTime.Hour.ToString("D2") + ":" + startTime.Minute.ToString("D2") + ":" + startTime.Second.ToString("D2");
                string endStr = endTime.Year.ToString() + "-" + endTime.Month.ToString("D2") + "-" + endTime.Day.ToString("D2") + "T" +
                    endTime.Hour.ToString("D2") + ":" + endTime.Minute.ToString("D2") + ":" + endTime.Second.ToString("D2");

                pps = fsql.Select<postproeventresult>()
                    .Where(pp => DateTime.Parse(pp.EventTime) >= startTime && DateTime.Parse(pp.EventTime) <= endTime
                    && pp.ML >= minML && pp.ML <= maxML)
                    .Page(pageNumber: pageIndex, pageSize: perPageCount).ToList();
                return pps;
                //if (DBConnection())
                //{

                //    string courseSql = @"select count(*) from postproeventresult where EventTime>=@stime and EventTime<=@etime
                //    and ML>=@min and ML<=@max";
                //    Comm = new MySqlCommand(courseSql, RemoteConn);
                //    Comm.Parameters.Add(new MySqlParameter("@stime", MySqlDbType.VarChar) { Value = startStr });
                //    Comm.Parameters.Add(new MySqlParameter("@etime", MySqlDbType.VarChar) { Value = endStr });
                //    Comm.Parameters.Add(new MySqlParameter("@min", MySqlDbType.Float) { Value = minML });
                //    Comm.Parameters.Add(new MySqlParameter("@max", MySqlDbType.Float) { Value = maxML });
                //    int selectCount = int.Parse(Convert.ToString(Comm.ExecuteScalar()));

                //    int checkIndex = (pageIndex - 1) * perPageCount;
                //    if (checkIndex >= selectCount)
                //        pageIndex = 1;
                //    // 根据分布取数据
                //    //var v = from q in Context.Set<AutoRegister>().Skip((pageIndex - 1) * perPageCount).Take(perPageCount).ToList()
                //    //        join lc in Context.Set<LicenseColor>() on q.LicenseColorId equals lc.ColorId
                //    //        join ac in Context.Set<AutoColor>() on q.AutoColorId equals ac.ColorId
                //    //        join am in Context.Set<FeeModel>() on q.FeeModeId equals am.FeeModelId
                //    //        where q.State == 1
                //    //        select new
                //    //        {
                //    //            AutoId = q.AutoId,
                //    //            AutoLicense = q.AutoLicense,
                //    //            LColorId = lc.ColorId,
                //    //            LColorName = lc.ColorName,
                //    //            AColorId = ac.ColorId,
                //    //            AColorName = ac.ColorName,
                //    //            FeeModelId = am.FeeModelId,
                //    //            FeeModelName = am.FeeModelName,
                //    //            Description = q.Description
                //    //        };

                //    //result.State = 1;
                //    //result.Message = "";
                //    //result.PageInfo = new PageInfo() { PageIndex = pageIndex, RecordCount = count };
                //    //result.Data = Newtonsoft.Json.JsonConvert.SerializeObject(v.ToList());
                //}
            }
            catch (Exception ex)
            {
                logger.Error($"获取事件列表失败 - 开始时间:{startTime}, 结束时间:{endTime}, 页码:{pageIndex}, 每页数量:{perPageCount}", ex);
                return null;
            }
        }
        public List<MmEventEntity> GetEvents(DateTime startTime, DateTime endTime)
        {
            try
            {
                if (DBConnection())
                {
                    string courseSql = @"select * from " + GlobalConfig.UseResultTable + " where EventTime>=@stime and EventTime<=@etime";

                    Adap = new MySqlDataAdapter(courseSql, RemoteConn);
                    string startStr = startTime.Year.ToString() + "-" + startTime.Month.ToString("D2") + "-" + startTime.Day.ToString("D2") + "T" +
                        startTime.Hour.ToString("D2") + ":" + startTime.Minute.ToString("D2") + ":" + startTime.Second.ToString("D2");
                    string endStr = endTime.Year.ToString() + "-" + endTime.Month.ToString("D2") + "-" + endTime.Day.ToString("D2") + "T" +
                        endTime.Hour.ToString("D2") + ":" + endTime.Minute.ToString("D2") + ":" + endTime.Second.ToString("D2");

                    Adap.SelectCommand.Parameters.Add(new MySqlParameter("@stime", MySqlDbType.VarChar) { Value = startStr });
                    Adap.SelectCommand.Parameters.Add(new MySqlParameter("@etime", MySqlDbType.VarChar) { Value = endStr });
                    Adap.SelectCommand.CommandTimeout = 5;
                    DataTable dataTable = new DataTable();
                    //Adap = null;
                    Adap.Fill(dataTable);

                    List<MmEventEntity> list = new List<MmEventEntity>();

                    foreach (DataRow dr in dataTable.AsEnumerable())
                    {
                        MmEventEntity mm = new MmEventEntity();
                        //mm.WorkAreaID = dr.Field<int>("workarea_id");
                        mm.EventID = dr.Field<int>(GlobalConfig.EventIDColName);
                        mm.EventTimeStr = dr.Field<string>("EventTime");
                        mm.EventTime = DateTime.Parse(dr.Field<string>("EventTime"));
                        mm.X = dr.Field<double>("Y");
                        mm.Y = dr.Field<double>("X");
                        mm.Z = dr.Field<double>("Z");
                        mm.ML = dr.Field<float>("ML");
                        mm.LocSta = dr.Field<int>("LocSta");
                        mm.MLSta = dr.Field<int>("MLSta");
                        mm.Energy = GetEnergy(mm.ML);
                        list.Add(mm);
                    }
                    return list;
                }
            }
            catch (Exception ex)
            {
                logger.Error($"获取事件列表失败 - 开始时间:{startTime}, 结束时间:{endTime}", ex);
                throw;
            }
            finally
            {
                this.Dispose();
            }
            return null;
        }
        public List<MmEventEntity> GetEvents(DateTime startTime, DateTime endTime, double minML, double maxML)
        {
            try
            {
                if (DBConnection())
                {
                    string courseSql = @"select * from " + GlobalConfig.UseResultTable + " where EventTime>=@stime and EventTime<=@etime and (ML>=@minML and ML<=@maxML)";

                    Adap = new MySqlDataAdapter(courseSql, RemoteConn);
                    string startStr = startTime.Year.ToString() + "-" + startTime.Month.ToString("D2") + "-" + startTime.Day.ToString("D2") + "T" +
                        startTime.Hour.ToString("D2") + ":" + startTime.Minute.ToString("D2") + ":" + startTime.Second.ToString("D2");
                    string endStr = endTime.Year.ToString() + "-" + endTime.Month.ToString("D2") + "-" + endTime.Day.ToString("D2") + "T" +
                        endTime.Hour.ToString("D2") + ":" + endTime.Minute.ToString("D2") + ":" + endTime.Second.ToString("D2");

                    Adap.SelectCommand.Parameters.Add(new MySqlParameter("@stime", MySqlDbType.VarChar) { Value = startStr });
                    Adap.SelectCommand.Parameters.Add(new MySqlParameter("@etime", MySqlDbType.VarChar) { Value = endStr });
                    Adap.SelectCommand.Parameters.Add(new MySqlParameter("@minML", MySqlDbType.Double) { Value = minML });
                    Adap.SelectCommand.Parameters.Add(new MySqlParameter("@maxML", MySqlDbType.Double) { Value = maxML });

                    DataTable dataTable = new DataTable();
                    Adap.Fill(dataTable);

                    List<MmEventEntity> list = new List<MmEventEntity>();

                    foreach (DataRow dr in dataTable.AsEnumerable())
                    {
                        MmEventEntity mm = new MmEventEntity();
                        //mm.WorkAreaID = dr.Field<int>("workarea_id");
                        mm.EventID = dr.Field<int>(GlobalConfig.EventIDColName);
                        mm.EventTimeStr = dr.Field<string>("EventTime");
                        mm.EventTime = DateTime.Parse(dr.Field<string>("EventTime"));
                        mm.X = dr.Field<double>("X");
                        mm.Y = dr.Field<double>("Y");
                        mm.Z = dr.Field<double>("Z");
                        mm.ML = dr.Field<float>("ML");
                        mm.LocSta = dr.Field<int>("LocSta");
                        mm.MLSta = dr.Field<int>("MLSta");
                        mm.Energy = GetEnergy(mm.ML);
                        list.Add(mm);
                    }
                    return list;
                }
            }
            catch (Exception ex)
            {
                logger.Error($"获取事件列表失败 - 开始时间:{startTime}, 结束时间:{endTime}, minML:{minML}, maxML:{maxML}", ex);
            }
            finally
            {
                this.Dispose();
            }
            return null;
        }
        public List<MmEventEntity> GetEvents(string QueryStr, SortTarget ssm, int sm, Models.FilterCondition<double> energyFC)
        {
            try
            {
                if (DBConnection())
                {
                    Adap = new MySqlDataAdapter(QueryStr, RemoteConn);
                    DataTable dataTable = new DataTable();
                    Adap.Fill(dataTable);

                    List<MmEventEntity> sqllist = new List<MmEventEntity>();
                    List<MmEventEntity> resultlist = new List<MmEventEntity>();
                    foreach (DataRow dr in dataTable.AsEnumerable())
                    {
                        MmEventEntity mm = new MmEventEntity();
                        //mm.WorkAreaID = dr.Field<int>("workarea_id");
                        mm.EventID = dr.Field<int>(GlobalConfig.EventIDColName);
                        mm.EventTimeStr = dr.Field<string>("EventTime");
                        mm.EventTime = DateTime.Parse(dr.Field<string>("EventTime"));
                        mm.X = dr.Field<double>("Y");
                        mm.Y = dr.Field<double>("X");
                        mm.Z = dr.Field<double>("Z");
                        mm.ML = dr.Field<float>("ML");
                        mm.LocSta = dr.Field<int>("LocSta");
                        mm.MLSta = dr.Field<int>("MLSta");
                        mm.Energy = GetEnergy(mm.ML);
                        sqllist.Add(mm);
                    }
                    if (energyFC.IsUse)
                    {
                        resultlist = sqllist.Where(sl => sl.Energy >= energyFC.Cond2 && sl.Energy <= energyFC.Cond1).ToList();
                    }
                    else
                    {
                        resultlist = sqllist;
                    }
                    switch (ssm)
                    {
                        case SortTarget.Time:
                            resultlist.Sort((x, y) =>
                            {
                                return sm * x.EventTime.CompareTo(y.EventTime);
                            });
                            break;
                        case SortTarget.ML:
                            resultlist.Sort((x, y) =>
                            {
                                return sm * x.ML.CompareTo(y.ML);
                            });
                            break;
                        case SortTarget.Energy:
                            resultlist.Sort((x, y) =>
                            {
                                return sm * x.Energy.CompareTo(y.Energy);
                            });
                            break;
                        case SortTarget.Depth:
                            resultlist.Sort((x, y) =>
                            {
                                return sm * x.Z.CompareTo(y.Z);
                            });
                            break;
                        default:
                            break;
                    }
                    return resultlist;
                }
            }
            catch (Exception ex)
            {
                logger.Error($"根据SQL查询事件失败 - QueryStr:{QueryStr}, SortTarget:{ssm}, SortMode:{sm}", ex);
            }
            finally
            {
                this.Dispose();
            }
            return null;
        }
        /// <summary>
        /// 返回指定数量的最新事件，按发震时刻排序
        /// </summary>
        /// <param name="MaxCnt">数量</param>
        /// <returns></returns>
        public List<MmEventEntity> GetTopEvents(int MaxCnt, int PreCnt)
        {
            try
            {
                if (DBConnection())
                {
                    string CountSql = @"select count('" + GlobalConfig.EventIDColName + "') from " + GlobalConfig.UseResultTable;
                    Comm = new MySqlCommand(CountSql, RemoteConn);
                    int count = int.Parse(Convert.ToString(Comm.ExecuteScalar()));
                    if (count > preSelectCount)
                    {
                        preSelectCount = count;
                    }
                    //Console.WriteLine(count);
                    if (count > PreCnt)
                    {
                        int selCnt = count - PreCnt;
                        if (selCnt > MaxCnt)
                            selCnt = MaxCnt;

                        string courseSql = @"select * from " + GlobalConfig.UseResultTable + " order by " + GlobalConfig.EventIDColName + " desc limit @tcnt";
                        Adap = new MySqlDataAdapter(courseSql, RemoteConn);
                        Adap.SelectCommand.Parameters.Add(new MySqlParameter("@tcnt", MySqlDbType.Int32) { Value = selCnt });
                        DataTable dataTable = new DataTable();
                        Adap.Fill(dataTable);

                        List<MmEventEntity> list = new List<MmEventEntity>();

                        foreach (DataRow dr in dataTable.AsEnumerable())
                        {
                            MmEventEntity mm = new MmEventEntity();
                            //mm.WorkAreaID = dr.Field<int>("workarea_id");
                            mm.EventID = dr.Field<int>(GlobalConfig.EventIDColName);
                            mm.EventTimeStr = dr.Field<string>("EventTime");
                            mm.EventTime = DateTime.Parse(dr.Field<string>("EventTime"));
                            mm.X = dr.Field<double>("Y");
                            mm.Y = dr.Field<double>("X");
                            mm.Z = dr.Field<double>("Z");
                            mm.ML = Math.Round(dr.Field<float>("ML"), 2);
                            mm.LocSta = dr.Field<int>("LocSta");
                            mm.MLSta = dr.Field<int>("MLSta");
                            mm.Energy = GetEnergy(mm.ML);
                            list.Add(mm);
                        }
                        return list;
                    }
                    else
                    {
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error($"获取最新事件失败 - MaxCnt:{MaxCnt}, PreCnt:{PreCnt}", ex);
                throw;
            }
            finally
            {
                this.Dispose();
            }
            return null;
        }
        public bool DownLoadWavedata(string eventTime, string savePath, string saveName, string tableName)
        {
            //bool res = false;
            try
            {
                if (DBConnection())
                {
                    string courseSql = @"select WaveData from " + tableName + " where EventTime=@eventTime";
                    MySqlCommand cmd = new MySqlCommand(courseSql, RemoteConn);
                    cmd.Parameters.AddWithValue("@eventTime", eventTime);
                    MySqlDataReader dr = cmd.ExecuteReader();

                    List<byte> wds = new List<byte>();

                    while (dr.Read()) //开始读数据
                    {
                        byte[] blob;
                        blob = (byte[])dr["wavedata"];
                        if (blob.Length == 0)
                            break;
                        wds.AddRange(blob);
                        //Array.ConstrainedCopy(blob, 0, wd, 0, blob.Length);
                        //Console.WriteLine(blob.Length + ">>>>>>>>>>>");
                        //对数据进行处理
                    }
                    string mseedPath = savePath + saveName + ".mseed";
                    SaveBinaryFile(mseedPath, wds.ToArray());
                    dr.Close();
                    dr.Dispose();

                    courseSql = @"select JsonFile from " + tableName + " where EventTime=@eventTime";
                    cmd = new MySqlCommand(courseSql, RemoteConn);
                    cmd.Parameters.AddWithValue("@eventTime", eventTime);
                    MySqlDataReader drjson = cmd.ExecuteReader();

                    List<byte> jsonList = new List<byte>();
                    while (drjson.Read()) //开始读数据
                    {
                        byte[] blob;
                        blob = (byte[])drjson["JsonFile"];
                        if (blob.Length == 0)
                            break;
                        jsonList.AddRange(blob);
                    }

                    string jsonPath = savePath + saveName + ".json";

                    SaveBinaryFile(jsonPath, jsonList.ToArray());

                    drjson.Close();
                    drjson.Dispose();
                    cmd.Dispose();
                    return true;

                }
            }
            catch (Exception ex)
            {
                logger.Error($"下载波形数据失败 - 事件时间:{eventTime}, 保存路径:{savePath}, 保存名称:{saveName}, 表名:{tableName}", ex);
                throw;
            }
            finally
            {
                this.Dispose();
            }
            return false;
        }
        public void SaveBinaryFile(string fn, byte[] datas)
        {
            FileStream fs = new FileStream(fn, FileMode.OpenOrCreate);
            BinaryWriter binWriter = new BinaryWriter(fs);
            binWriter.Write(datas);
            binWriter.Close();
            fs.Close();
        }

        public MmEventEntity GetEvent(int eventID)
        {
            try
            {
                if (DBConnection())
                {
                    MmEventEntity mm;
                    string courseSql = @"select * from " + GlobalConfig.UseResultTable + " where " + GlobalConfig.EventIDColName + "==@eid";
                    Adap = new MySqlDataAdapter(courseSql, RemoteConn);
                    Adap.SelectCommand.Parameters.Add(new MySqlParameter("@eid", MySqlDbType.VarChar) { Value = eventID });

                    DataTable dataTable = new DataTable();
                    Adap.Fill(dataTable);

                    if (dataTable.Rows.Count > 0)
                    {
                        DataRow dr = dataTable.Rows[0];
                        mm = new MmEventEntity();
                        //mm.WorkAreaID = dr.Field<int>("workarea_id");
                        mm.EventID = dr.Field<int>(GlobalConfig.EventIDColName);
                        mm.EventTimeStr = dr.Field<string>("EventTime");
                        mm.EventTime = DateTime.Parse(dr.Field<string>("EventTime"));
                        mm.X = dr.Field<double>("Y");
                        mm.Y = dr.Field<double>("X");
                        mm.Z = dr.Field<double>("Z");
                        mm.ML = dr.Field<float>("ML");
                        mm.LocSta = dr.Field<int>("LocSta");
                        mm.MLSta = dr.Field<int>("MLSta");
                        mm.Energy = GetEnergy(mm.ML);
                        return mm;
                    }
                    else
                    {
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error($"获取事件详情失败 - 事件ID:{eventID}", ex);
            }
            finally
            {
                this.Dispose();
            }
            return null;
        }

        public MmEventEntity GetEvent(string eventTime)
        {
            try
            {
                if (DBConnection())
                {
                    MmEventEntity mm;
                    string courseSql = @"select * from " + GlobalConfig.UseResultTable + " where EventTime=@etime";
                    Adap = new MySqlDataAdapter(courseSql, RemoteConn);
                    //string startStr = startTime.Year.ToString() + "-" + startTime.Month.ToString("D2") + "-" + startTime.Day.ToString("D2") + "T" +
                    //    startTime.Hour.ToString("D2") + ":" + startTime.Minute.ToString("D2") + ":" + startTime.Second.ToString("D2");
                    //string endStr = endTime.Year.ToString() + "-" + endTime.Month.ToString("D2") + "-" + endTime.Day.ToString("D2") + "T" +
                    //    endTime.Hour.ToString("D2") + ":" + endTime.Minute.ToString("D2") + ":" + endTime.Second.ToString("D2");

                    Adap.SelectCommand.Parameters.Add(new MySqlParameter("@etime", MySqlDbType.VarChar) { Value = eventTime });

                    DataTable dataTable = new DataTable();
                    Adap.Fill(dataTable);
                    if (dataTable.Rows.Count > 0)
                    {
                        DataRow dr = dataTable.Rows[0];
                        mm = new MmEventEntity();
                        //mm.WorkAreaID = dr.Field<int>("workarea_id");
                        mm.EventID = dr.Field<int>(GlobalConfig.EventIDColName);
                        mm.EventTimeStr = dr.Field<string>("EventTime");
                        mm.EventTime = DateTime.Parse(dr.Field<string>("EventTime"));
                        mm.X = dr.Field<double>("Y");
                        mm.Y = dr.Field<double>("X");
                        mm.Z = dr.Field<double>("Z");
                        mm.ML = dr.Field<float>("ML");
                        mm.LocSta = dr.Field<int>("LocSta");
                        mm.MLSta = dr.Field<int>("MLSta");
                        mm.Energy = GetEnergy(mm.ML);
                        return mm;
                    }
                    else
                    {
                        return null;
                    }

                }
            }
            catch (Exception ex)
            {
                logger.Error($"获取事件详情失败 - 事件时间:{eventTime}", ex);
                throw;
            }
            finally
            {
                this.Dispose();
            }
            return null;
        }

        public MmEventEntity GetLastEvent()
        {
            try
            {
                if (DBConnection())
                {
                    MmEventEntity mm;
                    //string courseSql = @"select * from " + GlobalConfig.UseResultTable + " " +
                    //    "where "+GlobalConfig.EventIDColName+"=(select max("+ GlobalConfig.EventIDColName + ") from "+ GlobalConfig.UseResultTable+")";

                    string courseSql = @"select * from " + GlobalConfig.UseResultTable + " " +
                        "order by " + GlobalConfig.EventIDColName + " desc limit 1";
                    Adap = new MySqlDataAdapter(courseSql, RemoteConn);

                    DataTable dataTable = new DataTable();
                    Adap.Fill(dataTable);
                    if (dataTable.Rows.Count > 0)
                    {
                        DataRow dr = dataTable.Rows[0];
                        mm = new MmEventEntity();
                        mm.WorkAreaID = dr.Field<int>("WorkAreaID");
                        mm.EventID = dr.Field<int>(GlobalConfig.EventIDColName);
                        mm.EventTimeStr = dr.Field<string>("EventTime");
                        mm.EventTime = DateTime.Parse(dr.Field<string>("EventTime"));
                        mm.OriginTime = dr.Field<string>("OriginTime");
                        mm.X = dr.Field<double>("Y");
                        mm.Y = dr.Field<double>("X");
                        mm.Z = dr.Field<double>("Z");
                        mm.ML = dr.Field<float>("ML");
                        mm.LocSta = dr.Field<int>("LocSta");
                        mm.MLSta = dr.Field<int>("MLSta");
                        mm.RMS = dr.Field<float>("RMS");
                        mm.Energy = GetEnergy(mm.ML);
                        return mm;
                    }
                    else
                    {
                        return null;
                    }

                }
            }
            catch (Exception ex)
            {
                logger.Error("获取最新事件失败", ex);
                throw;
            }
            finally
            {
                this.Dispose();
            }
            return null;
        }

        public MmEventEntity GetLastEvent(DateTime deadline)
        {
            try
            {
                if (DBConnection())
                {
                    MmEventEntity mm;
                    string deadlineStr = deadline.Year.ToString() + "-" + deadline.Month.ToString("D2") + "-" + deadline.Day.ToString("D2") + "T" +
                        deadline.Hour.ToString("D2") + ":" + deadline.Minute.ToString("D2") + ":" + deadline.Second.ToString("D2");

                    string courseSql = @"select * from " + GlobalConfig.UseResultTable + " where EventTime<=@etime " +
                        "order by " + GlobalConfig.EventIDColName + " desc limit 1";
                    Adap = new MySqlDataAdapter(courseSql, RemoteConn);
                    Adap.SelectCommand.Parameters.Add(new MySqlParameter("@etime", MySqlDbType.VarChar) { Value = deadlineStr });

                    DataTable dataTable = new DataTable();
                    Adap.Fill(dataTable);
                    if (dataTable.Rows.Count > 0)
                    {
                        DataRow dr = dataTable.Rows[0];
                        mm = new MmEventEntity();
                        mm.WorkAreaID = dr.Field<int>("WorkAreaID");
                        mm.EventID = dr.Field<int>(GlobalConfig.EventIDColName);
                        mm.EventTimeStr = dr.Field<string>("EventTime");
                        mm.EventTime = DateTime.Parse(dr.Field<string>("EventTime"));
                        mm.OriginTime = dr.Field<string>("OriginTime");
                        mm.X = dr.Field<double>("Y");
                        mm.Y = dr.Field<double>("X");
                        mm.Z = dr.Field<double>("Z");
                        mm.ML = dr.Field<float>("ML");
                        mm.LocSta = dr.Field<int>("LocSta");
                        mm.MLSta = dr.Field<int>("MLSta");
                        mm.RMS = dr.Field<float>("RMS");
                        mm.Energy = GetEnergy(mm.ML);
                        return mm;
                    }
                    else
                    {
                        return null;
                    }

                }
            }
            catch (Exception ex)
            {
                logger.Error($"获取最新事件失败 - 截止时间:{deadline}", ex);
                throw;
            }
            finally
            {
                this.Dispose();
            }
            return null;
        }

        public List<MmEventEntity> GetLastNewEvents(int resultCount)
        {
            try
            {
                if (DBConnection())
                {
                    //string CountSql = @"select count('" + GlobalConfig.EventIDColName + "') from " + GlobalConfig.UseResultTable;
                    //Comm = new MySqlCommand(CountSql, RemoteConn);
                    //int count = int.Parse(Convert.ToString(Comm.ExecuteScalar()));
                    //if (count > preSelectCount)
                    //{
                    //    preSelectCount = count;
                    //}
                    ////Console.WriteLine(count);

                    //    int selCnt = count - PreCnt;
                    //    if (selCnt > MaxCnt)
                    //        selCnt = MaxCnt;

                    string courseSql = @"select * from " + GlobalConfig.UseResultTable + " order by " + GlobalConfig.EventIDColName + " desc limit @tcnt";
                    Adap = new MySqlDataAdapter(courseSql, RemoteConn);
                    Adap.SelectCommand.Parameters.Add(new MySqlParameter("@tcnt", MySqlDbType.Int32) { Value = resultCount });
                    DataTable dataTable = new DataTable();
                    Adap.Fill(dataTable);

                    List<MmEventEntity> list = new List<MmEventEntity>();

                    foreach (DataRow dr in dataTable.AsEnumerable())
                    {
                        MmEventEntity mm = new MmEventEntity();
                        //mm.WorkAreaID = dr.Field<int>("workarea_id");
                        mm.EventID = dr.Field<int>(GlobalConfig.EventIDColName);
                        mm.EventTimeStr = dr.Field<string>("EventTime");
                        mm.EventTime = DateTime.Parse(dr.Field<string>("EventTime"));
                        mm.X = dr.Field<double>("Y");
                        mm.Y = dr.Field<double>("X");
                        mm.Z = dr.Field<double>("Z");
                        mm.ML = Math.Round(dr.Field<float>("ML"), 2);
                        mm.LocSta = dr.Field<int>("LocSta");
                        mm.MLSta = dr.Field<int>("MLSta");
                        mm.Energy = GetEnergy(mm.ML);
                        list.Add(mm);
                    }
                    return list;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                this.Dispose();
            }
            return null;
        }
        /// <summary>
        /// 异步统计指定时间范围的事件数量
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public async Task<int> StatEventCountAsync(DateTime startTime, DateTime endTime)
        {
            try
            {
                using (MySqlConnection connection = new MySqlConnection(_connectionString))
                {
                    await _semaphore.WaitAsync();
                    await connection.OpenAsync();
                    string startStr = startTime.Year.ToString() + "-" + startTime.Month.ToString("D2") + "-" + startTime.Day.ToString("D2") + "T" +
                                            startTime.Hour.ToString("D2") + ":" + startTime.Minute.ToString("D2") + ":" + startTime.Second.ToString("D2");
                    string endStr = endTime.Year.ToString() + "-" + endTime.Month.ToString("D2") + "-" + endTime.Day.ToString("D2") + "T" +
                        endTime.Hour.ToString("D2") + ":" + endTime.Minute.ToString("D2") + ":" + endTime.Second.ToString("D2");
                    string sqlStr = "SELECT COUNT(*) FROM realtimeeventresult WHERE EventTime>=@stime and EventTime<=@etime";
                    using (MySqlCommand command = new MySqlCommand(sqlStr, connection))
                    {
                        command.Parameters.AddWithValue("@stime", startStr);
                        command.Parameters.AddWithValue("@etime", endStr);

                        using (MySqlDataReader reader = (MySqlDataReader)await command.ExecuteReaderAsync())
                        {
                            while (await reader.ReadAsync())
                            {
                                _semaphore.Release();
                                //Console.WriteLine(reader.GetFieldType(0));
                                // 处理查询结果
                                int cnt = (int)await reader.GetFieldValueAsync<Int64>(0);
                                return cnt;
                            }
                        }
                    }
                    _semaphore.Release();
                }
            }
            catch (Exception ex)
            {
                logger.Error($"统计事件数量失败 - 开始时间:{startTime}, 结束时间:{endTime}", ex);
                // 异常处理代码
                Console.WriteLine($"DownloadDataAsync error: {ex.StackTrace}");
                throw;
            }
            // 如果没有查询到数据，则返回空引用
            return 0;
        }
        /// <summary>
        /// 下载波形和Json数据
        /// </summary>
        /// <param name="eventTimeStr"></param>
        /// <param name="filePath"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public async ValueTask DownloadWaveDataAsync(GridItemEventResult gier, string savePath, Action<GridItemEventResult> callback)
        {
            try
            {
                using (MySqlConnection connection = new MySqlConnection(_connectionString))
                {
                    await _semaphore.WaitAsync();
                    await connection.OpenAsync();
                    string eventTimeStr = gier.EventTime;
                    using (MySqlCommand command = new MySqlCommand("SELECT WaveData,JsonFile FROM realtimewavedatas WHERE EventTime=@et", connection))
                    {
                        command.Parameters.AddWithValue("@et", eventTimeStr);

                        using (MySqlDataReader reader = (MySqlDataReader)await command.ExecuteReaderAsync())
                        {
                            if (await reader.ReadAsync())
                            {
                                string datePath = eventTimeStr.Substring(0, 4) + eventTimeStr.Substring(5, 2) + eventTimeStr.Substring(8, 2);
                                datePath = savePath + datePath;
                                if (!Directory.Exists(datePath))
                                {
                                    Directory.CreateDirectory(datePath);
                                }
                                //未包含后缀名
                                string filePath = datePath + "\\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) + ".01A";
                                //Console.WriteLine("文件路径构建完成!");
                                if (!File.Exists(filePath + ".mseed"))
                                {
                                    //保存MSeed文件
                                    byte[] mseedData = await reader.GetFieldValueAsync<byte[]>(0);
                                    using (FileStream fileStream = new FileStream(filePath + ".mseed", FileMode.Create, FileAccess.Write))
                                    {
                                        await fileStream.WriteAsync(mseedData, 0, mseedData.Length);
                                    }
                                    //Console.WriteLine("MSeed下载完成!");
                                }
                                if (!File.Exists(filePath + ".json"))
                                {
                                    //保存Json文件
                                    byte[] jsonData = await reader.GetFieldValueAsync<byte[]>(1);
                                    using (FileStream fileStream = new FileStream(filePath + ".json", FileMode.Create, FileAccess.Write))
                                    {
                                        await fileStream.WriteAsync(jsonData, 0, jsonData.Length);
                                    }
                                    //Console.WriteLine("Json下载完成!");
                                }
                                // 下载完成后调用回调函数
                                callback?.Invoke(gier);
                            }
                        }
                    }

                }
                // if(_semaphore.AvailableWaitHandle)
            }
            catch (Exception ex)
            {
                logger.Error($"异步下载波形数据失败 - 事件时间:{gier.EventTime}, 保存路径:{savePath}", ex);
                // 异常处理代码
                Console.WriteLine($"DownloadDataAsync error: {ex.StackTrace}");
                throw;
            }
            finally
            {
                _semaphore.Release();
            }
        }

        public async ValueTask DownloadJsonDataAsync(GridItemEventResult gier, string savePath, Action<GridItemEventResult> callback)
        {
            try
            {
                using (MySqlConnection connection = new MySqlConnection(_connectionString))
                {
                    await _semaphore.WaitAsync();
                    await connection.OpenAsync();
                    string eventTimeStr = gier.EventTime;
                    using (MySqlCommand command = new MySqlCommand("SELECT JsonFile FROM realtimewavedatas WHERE EventTime=@et", connection))
                    {
                        command.Parameters.AddWithValue("@et", eventTimeStr);

                        using (MySqlDataReader reader = (MySqlDataReader)await command.ExecuteReaderAsync())
                        {
                            if (await reader.ReadAsync())
                            {
                                string datePath = eventTimeStr.Substring(0, 4) + eventTimeStr.Substring(5, 2) + eventTimeStr.Substring(8, 2);
                                datePath = savePath + datePath;
                                if (!Directory.Exists(datePath))
                                {
                                    Directory.CreateDirectory(datePath);
                                }
                                //未包含后缀名
                                string filePath = datePath + "\\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) + ".01A";
                                //Console.WriteLine("文件路径构建完成!");
                                //if (!File.Exists(filePath + ".mseed"))
                                //{
                                //    //保存MSeed文件
                                //    byte[] mseedData = await reader.GetFieldValueAsync<byte[]>(0);
                                //    using (FileStream fileStream = new FileStream(filePath + ".mseed", FileMode.Create, FileAccess.Write))
                                //    {
                                //        await fileStream.WriteAsync(mseedData, 0, mseedData.Length);
                                //    }
                                //    //Console.WriteLine("MSeed下载完成!");
                                //}
                                if (!File.Exists(filePath + ".json"))
                                {
                                    //保存Json文件
                                    byte[] jsonData = await reader.GetFieldValueAsync<byte[]>(0);
                                    using (FileStream fileStream = new FileStream(filePath + ".json", FileMode.Create, FileAccess.Write))
                                    {
                                        await fileStream.WriteAsync(jsonData, 0, jsonData.Length);
                                    }
                                    //Console.WriteLine("Json下载完成!");
                                }
                                // 下载完成后调用回调函数
                                callback?.Invoke(gier);
                            }
                        }
                    }

                }
                // if(_semaphore.AvailableWaitHandle)
            }
            catch (Exception ex)
            {
                logger.Error($"异步下载JSON数据失败 - 事件时间:{gier.EventTime}, 保存路径:{savePath}", ex);
                // 异常处理代码
                Console.WriteLine($"DownloadDataAsync error: {ex.StackTrace}");
                throw;
            }
            finally
            {
                _semaphore.Release();
            }
        }
        /// <summary>
        /// 查询和下载数据
        /// </summary>
        /// <param name="eventID"></param>
        /// <param name="savePath"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public async Task QueryAndDownloadDataAsync(int eventID, string savePath, Action<GridItemEventResult> callback)
        {
            try
            {
                using (MySqlConnection connection = new MySqlConnection(_connectionString))
                {
                    await _semaphore.WaitAsync();
                    await connection.OpenAsync();

                    string sqlStr = "SELECT * FROM realtimeeventresult order by RTEventID desc limit 1";
                    using (MySqlCommand command = new MySqlCommand(sqlStr, connection))
                    {
                        //command.Parameters.AddWithValue("@eid", eventID);
                        command.CommandTimeout = 2;
                        using (MySqlDataReader reader = (MySqlDataReader)await command.ExecuteReaderAsync())
                        {

                            //如果查询结果集中存在数据，则调用异步下载方法进行数据下载
                            if (await reader.ReadAsync())
                            {
                                int qid = await reader.GetFieldValueAsync<int>(0);
                                //如果查询的事件id大于之前事件的id
                                if (qid > eventID)
                                {
                                    GridItemEventResult gier = new GridItemEventResult();
                                    gier.EventID = qid;
                                    gier.WorkAreaID = await reader.GetFieldValueAsync<int>(1);
                                    gier.EventTime = await reader.GetFieldValueAsync<string>(2);
                                    gier.OTime=DateTime.Parse(gier.EventTime);
                                    gier.OriginTime = await reader.GetFieldValueAsync<string>(3);
                                    gier.Y = await reader.GetFieldValueAsync<double>(4);
                                    gier.X = await reader.GetFieldValueAsync<double>(5);
                                    gier.Z = await reader.GetFieldValueAsync<double>(6);
                                    gier.ML = await reader.GetFieldValueAsync<float>(7);
                                    gier.LocSta = await reader.GetFieldValueAsync<int>(8);
                                    gier.MLSta = await reader.GetFieldValueAsync<int>(9);
                                    gier.RMS = await reader.GetFieldValueAsync<float>(10);
                                    gier.SetEnergy();
                                    _semaphore.Release();
                                    await DownloadJsonDataAsync(gier, savePath, callback).AsTask();
                                    return;
                                    //return gier;
                                }
                            }
                        }
                    }
                }
                _semaphore.Release();
                //return null;
            }
            catch (Exception ex)
            {
                _semaphore.Release();
                logger.Error($"查询和下载数据失败 - 事件ID:{eventID}, 保存路径:{savePath}", ex);
                // 异常处理代码
                Console.WriteLine($"QueryAndDownloadDataAsync error: {ex.StackTrace}");
                throw;
            }
        }

        public async Task QueryAndDownloadDataAsync(int eventID, DateTime endTime, string savePath, Action<GridItemEventResult> callback)
        {
            try
            {
                using (MySqlConnection connection = new MySqlConnection(_connectionString))
                {
                    await _semaphore.WaitAsync();
                    await connection.OpenAsync();
                    string sqlStr = "SELECT * FROM realtimeeventresult WHERE EventTime<=@etime order by RTEventID desc limit 1";

                    string endStr = endTime.Year.ToString() + "-" + endTime.Month.ToString("D2") + "-" + endTime.Day.ToString("D2") + "T" +
                        endTime.Hour.ToString("D2") + ":" + endTime.Minute.ToString("D2") + ":" + endTime.Second.ToString("D2");

                    //string sqlStr = "SELECT * FROM realtimeeventresult order by RTEventID desc limit 1";
                    using (MySqlCommand command = new MySqlCommand(sqlStr, connection))
                    {
                        //command.Parameters.AddWithValue("@eid", eventID);
                        command.Parameters.AddWithValue("@etime", endStr);
                        command.CommandTimeout = 2;
                        using (MySqlDataReader reader = (MySqlDataReader)await command.ExecuteReaderAsync())
                        {

                            //如果查询结果集中存在数据，则调用异步下载方法进行数据下载
                            if (await reader.ReadAsync())
                            {
                                int qid = await reader.GetFieldValueAsync<int>(0);
                                //string etime = await reader.GetFieldValueAsync<string>(1);
                                //如果查询的事件id大于之前事件的id
                                if (qid > eventID)
                                {
                                    GridItemEventResult gier = new GridItemEventResult();
                                    gier.EventID = qid;
                                    gier.WorkAreaID = await reader.GetFieldValueAsync<int>(1);
                                    gier.EventTime = await reader.GetFieldValueAsync<string>(2);
                                    gier.OTime = DateTime.Parse(gier.EventTime);
                                    gier.OriginTime = await reader.GetFieldValueAsync<string>(3);
                                    gier.Y = await reader.GetFieldValueAsync<double>(4);
                                    gier.X = await reader.GetFieldValueAsync<double>(5);
                                    gier.Z = await reader.GetFieldValueAsync<double>(6);
                                    gier.ML = await reader.GetFieldValueAsync<float>(7);
                                    gier.LocSta = await reader.GetFieldValueAsync<int>(8);
                                    gier.MLSta = await reader.GetFieldValueAsync<int>(9);
                                    gier.RMS = await reader.GetFieldValueAsync<float>(10);
                                    gier.SetEnergy();
                                    _semaphore.Release();
                                    Console.WriteLine("gier构建完成!");
                                    await DownloadWaveDataAsync(gier, savePath, callback).AsTask();
                                    return;
                                    //return gier;
                                }

                            }
                        }
                    }

                }
                _semaphore.Release();
                //return null;
            }
            catch (Exception ex)
            {
                _semaphore.Release();
                logger.Error($"按ID查询和下载数据失败 - 事件ID:{eventID}, 保存路径:{savePath}", ex);
                // 异常处理代码
                Console.WriteLine($"QueryAndDownloadDataAsync error: {ex.StackTrace}");
                throw;
            }
        }
        public async Task QueryEventByIDAsync(int eventID, string savePath, Action<GridItemEventResult> callback)
        {
            try
            {
                using (MySqlConnection connection = new MySqlConnection(_connectionString))
                {
                    await _semaphore.WaitAsync();
                    await connection.OpenAsync();
                    string sqlStr = "SELECT * FROM realtimeeventresult WHERE RTEventID=@eid order by RTEventID desc limit 1";

                    //string endStr = endTime.Year.ToString() + "-" + endTime.Month.ToString("D2") + "-" + endTime.Day.ToString("D2") + "T" +
                    //    endTime.Hour.ToString("D2") + ":" + endTime.Minute.ToString("D2") + ":" + endTime.Second.ToString("D2");

                    //string sqlStr = "SELECT * FROM realtimeeventresult order by RTEventID desc limit 1";
                    using (MySqlCommand command = new MySqlCommand(sqlStr, connection))
                    {
                        command.Parameters.AddWithValue("@eid", eventID);
                        //command.Parameters.AddWithValue("@etime", endStr);
                        //command.CommandTimeout = 2;
                        using (MySqlDataReader reader = (MySqlDataReader)await command.ExecuteReaderAsync())
                        {

                            //如果查询结果集中存在数据，则调用异步下载方法进行数据下载
                            if (await reader.ReadAsync())
                            {
                                int qid = await reader.GetFieldValueAsync<int>(0);
                                //string etime = await reader.GetFieldValueAsync<string>(1);
                                //如果查询的事件id大于之前事件的id
                                //if (qid > eventID)
                                {
                                    GridItemEventResult gier = new GridItemEventResult();
                                    gier.EventID = qid;
                                    gier.WorkAreaID = await reader.GetFieldValueAsync<int>(1);
                                    gier.EventTime = await reader.GetFieldValueAsync<string>(2);
                                    gier.OTime = DateTime.Parse(gier.EventTime);
                                    gier.OriginTime = await reader.GetFieldValueAsync<string>(3);
                                    gier.Y = await reader.GetFieldValueAsync<double>(4);
                                    gier.X = await reader.GetFieldValueAsync<double>(5);
                                    gier.Z = await reader.GetFieldValueAsync<double>(6);
                                    gier.ML = await reader.GetFieldValueAsync<float>(7);
                                    gier.LocSta = await reader.GetFieldValueAsync<int>(8);
                                    gier.MLSta = await reader.GetFieldValueAsync<int>(9);
                                    gier.RMS = await reader.GetFieldValueAsync<float>(10);
                                    gier.SetEnergy();
                                    _semaphore.Release();
                                    Console.WriteLine("gier构建完成!");
                                    await DownloadWaveDataAsync(gier, savePath, callback).AsTask();
                                    return;
                                    //return gier;
                                }

                            }
                        }
                    }

                }
                _semaphore.Release();
                //return null;
            }
            catch (Exception ex)
            {
                _semaphore.Release();
                logger.Error($"按ID查询事件失败 - 事件ID:{eventID}, 保存路径:{savePath}", ex);
                // 异常处理代码
                Console.WriteLine($"QueryAndDownloadDataAsync error: {ex.StackTrace}");
                throw;
            }
        }
        public List<GridItemEventResult> GetLastEvents(int lastEventID)
        {
            List<GridItemEventResult> giers= new List<GridItemEventResult>();
            using (MySqlConnection connection = new MySqlConnection(_connectionString))
            {
                string sqlStr = "SELECT * FROM realtimeeventresult where RTEventID>@eid order by RTEventID desc";
                connection.Open();
                using (MySqlCommand command = new MySqlCommand(sqlStr, connection))
                {
                    command.Parameters.AddWithValue("@eid", lastEventID);
                    using (MySqlDataReader reader = (MySqlDataReader)command.ExecuteReader())
                    {
                        //int qid = reader.GetFieldValue<int>(0);
                        //reader.Read();
                        //GridItemEventResult gier = new GridItemEventResult();
                        //gier.EventID = reader.GetFieldValue<int>(0);
                        //gier.WorkAreaID = reader.GetFieldValue<int>(1);
                        //gier.EventTime = reader.GetFieldValue<string>(2);
                        //gier.OriginTime = reader.GetFieldValue<string>(3);
                        //gier.Y = reader.GetFieldValue<double>(4);
                        //gier.X = reader.GetFieldValue<double>(5);
                        //gier.Z = reader.GetFieldValue<double>(6);
                        //gier.ML = reader.GetFieldValue<float>(7);
                        //gier.LocSta = reader.GetFieldValue<int>(8);
                        //gier.MLSta = reader.GetFieldValue<int>(9);
                        //gier.RMS = reader.GetFieldValue<float>(10);
                        //gier.SetEnergy();
                        //giers.Add(gier);
                        while (reader.Read())
                        {                            
                            GridItemEventResult gier = new GridItemEventResult();
                            gier.EventID = reader.GetFieldValue<int>(0);
                            gier.WorkAreaID = reader.GetFieldValue<int>(1);
                            gier.EventTime = reader.GetFieldValue<string>(2);
                            gier.OTime = DateTime.Parse(gier.EventTime);
                            gier.OriginTime = reader.GetFieldValue<string>(3);
                            gier.Y = reader.GetFieldValue<double>(4);
                            gier.X = reader.GetFieldValue<double>(5);
                            gier.Z = reader.GetFieldValue<double>(6);
                            gier.ML = reader.GetFieldValue<float>(7);
                            gier.LocSta = reader.GetFieldValue<int>(8);
                            gier.MLSta = reader.GetFieldValue<int>(9);
                            gier.RMS = reader.GetFieldValue<float>(10);
                            gier.SetEnergy();
                            giers.Add(gier);
                        }
                    }
                }
            }
            return giers;
        }

        public List<GridItemEventResult> GetLastTopEvents(int QueryCount)
        {
            try
            {
                if (DBConnection())
                {
                    string courseSql = @"select * from " + GlobalConfig.UseResultTable + " order by RTEventID desc limit @qc";
                    Adap = new MySqlDataAdapter(courseSql, RemoteConn);
                    Adap.SelectCommand.Parameters.Add(new MySqlParameter("@qc", MySqlDbType.Int32) { Value = QueryCount });
                    //Adap.SelectCommand.CommandTimeout = 5;
                    DataTable dataTable = new DataTable();
                    //Adap = null;
                    Adap.Fill(dataTable);

                    List<GridItemEventResult> list = new List<GridItemEventResult>();

                    foreach (DataRow dr in dataTable.AsEnumerable())
                    {
                        GridItemEventResult mm = new GridItemEventResult();
                        //mm.WorkAreaID = dr.Field<int>("workarea_id");
                        mm.EventID = dr.Field<int>(GlobalConfig.EventIDColName);
                        mm.EventTime = dr.Field<string>("EventTime");
                        mm.OTime = DateTime.Parse(mm.EventTime);
                        mm.OriginTime = dr.Field<string>("EventTime");
                        mm.X = dr.Field<double>("Y");
                        mm.Y = dr.Field<double>("X");
                        mm.Z = dr.Field<double>("Z");
                        mm.ML = dr.Field<float>("ML");
                        mm.LocSta = dr.Field<int>("LocSta");
                        mm.MLSta = dr.Field<int>("MLSta");
                        mm.Energy = GetEnergy(mm.ML);                      
                        list.Add(mm);
                    }
                    return list;
                }
            }
            catch (Exception ex)
            {
                logger.Error($"获取最新事件失败 - 数量:{QueryCount}", ex);
                throw;
            }
            finally
            {
                this.Dispose();
            }
            return null;
        }

        public List<GridItemEventResult> GetGridEvents(DateTime startTime, DateTime endTime, double minML, double maxML)
        {
            try
            {
                if (DBConnection())
                {
                    string courseSql = @"select * from " + GlobalConfig.UseResultTable + " where EventTime>=@stime and EventTime<=@etime and (ML>=@minML and ML<=@maxML)";

                    Adap = new MySqlDataAdapter(courseSql, RemoteConn);
                    string startStr = startTime.Year.ToString() + "-" + startTime.Month.ToString("D2") + "-" + startTime.Day.ToString("D2") + "T" +
                        startTime.Hour.ToString("D2") + ":" + startTime.Minute.ToString("D2") + ":" + startTime.Second.ToString("D2");
                    string endStr = endTime.Year.ToString() + "-" + endTime.Month.ToString("D2") + "-" + endTime.Day.ToString("D2") + "T" +
                        endTime.Hour.ToString("D2") + ":" + endTime.Minute.ToString("D2") + ":" + endTime.Second.ToString("D2");

                    Adap.SelectCommand.Parameters.Add(new MySqlParameter("@stime", MySqlDbType.VarChar) { Value = startStr });
                    Adap.SelectCommand.Parameters.Add(new MySqlParameter("@etime", MySqlDbType.VarChar) { Value = endStr });
                    Adap.SelectCommand.Parameters.Add(new MySqlParameter("@minML", MySqlDbType.Double) { Value = minML });
                    Adap.SelectCommand.Parameters.Add(new MySqlParameter("@maxML", MySqlDbType.Double) { Value = maxML });

                    DataTable dataTable = new DataTable();
                    Adap.Fill(dataTable);

                    List<GridItemEventResult> list = new List<GridItemEventResult>();

                    foreach (DataRow dr in dataTable.AsEnumerable())
                    {
                        GridItemEventResult mm = new GridItemEventResult();
                        //mm.WorkAreaID = dr.Field<int>("workarea_id");
                        mm.EventID = dr.Field<int>(GlobalConfig.EventIDColName);
                        mm.EventTime = dr.Field<string>("EventTime");
                        mm.OTime = DateTime.Parse(mm.EventTime);
                        mm.OriginTime = dr.Field<string>("EventTime");
                        mm.X = dr.Field<double>("Y");
                        mm.Y = dr.Field<double>("X");
                        mm.Z = dr.Field<double>("Z");
                        mm.ML = dr.Field<float>("ML");
                        mm.LocSta = dr.Field<int>("LocSta");
                        mm.MLSta = dr.Field<int>("MLSta");
                        mm.SetEnergy();
                        //mm.Energy = GetEnergy(mm.ML);
                        list.Add(mm);
                    }
                    return list;
                }
            }
            catch (Exception ex)
            {
                logger.Error($"获取网格事件失败 - 开始时间:{startTime}, 结束时间:{endTime}, minML:{minML}, maxML:{maxML}", ex);
                throw;
            }
            finally
            {
                this.Dispose();
            }
            return null;
        }
        public double GetEnergy(double ml)
        {
            double mi = Math.Round(4.83 + 1.47 * ml, 4);
            return Math.Round(Math.Pow(10, mi), 0);
        }
    }
}
