using GalaSoft.MvvmLight.Command;
using HandyControl.Controls;
using LiveCharts.Helpers;
using Microsoft.Win32;
using NPOI.OpenXmlFormats.Dml;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection.Emit;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Shell;
using Txgy.EWS.Client.Common;
using Txgy.EWS.Client.Common.Enums;
using Txgy.EWS.Client.Entity;
using Txgy.EWS.Client.FocalMechanism.Core;
using Txgy.EWS.Client.Models;
using Txgy.EWS.Client.PageModule.Services;
using Txgy.Microseismic.BaseLib.Models;
using WW.OpenGL.Win;
using HorizontalAlignment = NPOI.SS.UserModel.HorizontalAlignment;
using VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment;
using FmGrid = Txgy.EWS.Client.FocalMechanism.Model.FmGrid;
using FMStation = Txgy.EWS.Client.FocalMechanism.Model.FMStation;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Txgy.EWS.Client.FocalMechanism.Model;
using Txgy.EWS.Client.Common.Helpers;
using OxyPlot.Axes;
using OxyPlot.Legends;
using OxyPlot.Series;
using OxyPlot;
using LineStyle = OxyPlot.LineStyle;
using System.Windows.Media.Imaging;
using Txgy.EWS.Client.PageModule.Views;
using System.Windows.Controls;
using System.Windows.Media;
using Prism.Ioc;
using Arction.Wpf.Charting;
using Arction.Wpf.Charting.Views.View3D;
using Arction.Wpf.Charting.Axes;
using OxyPlot.Wpf;
using Arction.Wpf.Charting.Series3D;
using System.Windows.Documents;
using Prism.Events;
using Txgy.EWS.Client.Common.MessageEvents;
using System.Windows;
using Prism.Regions;

namespace Txgy.EWS.Client.PageModule.ViewModels
{
    public class ReportViewModel : BindableBase, INavigationAware
    {
        IFreeSql fsqlTencent = FreeSqlTencent.tencentRemoteMySQL;
        ReportFreqImage reportFreqImage = new ReportFreqImage();
        CultureInfo culture = new CultureInfo("zh-CN");
        private IEventAggregator ea;

        byte[] freqBytes = null;
        byte[] middleEventPlanBytes = null;
        byte[] middleEventStereoBytes = null;
        byte[] legendBytes = null;
        public string dayFreqImagePath;
        public int dayFreqImageWidth = 1485;
        public int dayFreqImageHeight = 585;
        public int reportDayListFirstRow = 35;
        public int reportEventListCols = 10;
        /// <summary>
        /// 查询模式：0：自定义查询；1：日报；2：周报；3：月报
        /// </summary>
        public int SelectType = 0;
        #region 三维视图参数
        int _widthRS = 100;
        int _heightRS = 50;
        int _depthRS = 100;
        double _sideRotationRS = 0;
        double _horizontalRotationRS = -30;
        double _verticalRotationRS = 30;
        WallXZ _topWall;
        WallYZ _leftWall;
        WallYZ _rightWall;
        WallXZ _bottomWall;
        WallXY _backWall;
        WallXY _frontWall;
        AxisX3D _axisXPri3D;
        AxisY3D _axisYPri3D;
        AxisZ3D _axisZPri3D;
        public double _scale = 1;
        SizeDoubleXYZ eventSize;
        #endregion
        //private bool _isSelectAll;
        ///// <summary>
        ///// datagrid全选
        ///// </summary>
        //public bool IsSelectAll
        //{
        //    get { return _isSelectAll; }
        //    set
        //    {
        //        SetProperty(ref _isSelectAll, value);
        //        if (DataItems != null)
        //        {
        //            foreach (var item in DataItems)
        //            {
        //                item.IsSelected = _isSelectAll;
        //            }
        //        }
        //    }
        //}
        private int middleEventCount = 0;
        /// <summary>
        /// 中等能量事件数量
        /// </summary>
        public int MiddleEventCount
        {
            get { return middleEventCount; }
            set
            {
                SetProperty(ref middleEventCount, value);
            }
        }

        private double middleEnergy;
        /// <summary>
        /// 中等能量事件
        /// </summary>
        public double MiddleEnergy
        {
            get { return middleEnergy; }
            set
            {
                SetProperty(ref middleEnergy, value);
            }
        }

        private FilterCondition<DateTime> _timeFC;

        public FilterCondition<DateTime> TimeFC
        {
            get { return _timeFC; }
            set { _timeFC = value; }
        }
        private FilterCondition<double> _mlFC;

        public FilterCondition<double> MLFC
        {
            get { return _mlFC; }
            set { _mlFC = value; }
        }
        private FilterCondition<double> _energyFC;

        public FilterCondition<double> EnergyFC
        {
            get { return _energyFC; }
            set { _energyFC = value; }
        }

        private FilterCondition<double> _depthFC;

        public FilterCondition<double> DepthFC
        {
            get { return _depthFC; }
            set { _depthFC = value; }
        }
        private FilterCondition<double> _eastFC;

        public FilterCondition<double> EastFC
        {
            get { return _eastFC; }
            set { _eastFC = value; }
        }
        private FilterCondition<double> _northFC;

        public FilterCondition<double> 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 double _totalEnergy = 0;

        public double TotalEnergy
        {
            get { return _totalEnergy; }
            set
            {
                SetProperty(ref _totalEnergy, value);
            }
        }

        private double _averageEnergy = 0;

        public double AverageEnergy
        {
            get { return _averageEnergy; }
            set
            {
                SetProperty(ref _averageEnergy, value);
            }
        }

        private double _maxEnergy = 0;

        public double MaxEnergy
        {
            get { return _maxEnergy; }
            set
            {
                SetProperty(ref _maxEnergy, value);
            }
        }

        private string _likeCondition;

        public string LikeCondition
        {
            get { return _likeCondition; }
            set
            {
                SetProperty(ref _likeCondition, value);
            }
        }

        private int _sortMode = 1;
        /// <summary>
        ///// 排序模式:-1=降序;1=升序;
        /// </summary>
        public int SortMode
        {
            get { return _sortMode; }
            set
            {
                SetProperty(ref _sortMode, value);
            }
        }
        private List<GridItemEventResult> middleEnergyEvents=new List<GridItemEventResult>();

        public List<GridItemEventResult> MiddleEnergyEvents
        {
            get { return middleEnergyEvents; }
            set 
            {
                SetProperty(ref middleEnergyEvents, value);
            }
        }

        private ObservableCollection<GridItemEventResult> _selectResult;
        public ObservableCollection<GridItemEventResult> SelectResult
        {
            get { return _selectResult; }
            set
            {
                SetProperty(ref _selectResult, value);
            }
        }
        private LightningChart stereoChart;

        public LightningChart StereoChart
        {
            get { return stereoChart; }
            set
            {
                SetProperty(ref stereoChart, value);
            }
        }
        private PlotModel freqChart;

        public PlotModel FreqChart
        {
            get { return freqChart; }
            set
            {
                SetProperty(ref freqChart, value);
            }
        }
        public ICommand SelectEventListCommand
        {
            get => new DelegateCommand<ReportView>((rView) =>
            {
                SelectType = 0;
                DateTime st = TimeFC.Cond1;
                DateTime et = TimeFC.Cond2;
                var results = SearchEvents(st, et);

                if (results != null)
                {
                    SelectResult = new ObservableCollection<GridItemEventResult>(results);
                    //FreqChart = CreateDayFreqImage(results, st, st.ToString("D", culture));
                    //freqBytes = BitmapHelper.ConvertToBytes(ExportToBitmap(FreqChart, dayFreqImageWidth, dayFreqImageHeight));
                    var mes = results.Where(rs => rs.Energy >= MiddleEnergy).ToList();
                    //new ReportPlanImage().DrawPlanClipToFile(mes);
                    MiddleEnergyEvents = mes;
                    MiddleEventCount = mes.Count();
                    if (mes.Count > 0)
                    {
                        ReportPlanImage rpi = new ReportPlanImage();
                        //rpi.DrawPlanClipToDrawVisual(mes, (int)rView.canvasPlan.ActualWidth, (int)rView.canvasPlan.ActualHeight);
                        rpi.Draw(mes, rView.canvasPlan.ActualWidth, rView.canvasPlan.ActualHeight);
                        //rView.canvasPlan = rpi.host;
                        rView.canvasPlan.Children.Clear();
                        rView.canvasPlan.Children.Add(rpi.host);
                        CreateStereoChart(mes);
                    }
                }
            });
        }
        public ICommand SelectDayCommand
        {
            get => new DelegateCommand<ReportView>((rView) =>
            {
                SelectType = 1;
                //日报起始时刻
                DateTime drstarttime = GlobalConfig.DailyReportStartTime;
                Console.WriteLine(GlobalConfig.DailyReportStartTime.ToString());
                DateTime st = new DateTime(TimeFC.Cond1.Year, TimeFC.Cond1.Month, TimeFC.Cond1.Day, 
                    drstarttime.Hour, drstarttime.Minute, drstarttime.Second);

                var results = SearchEvents(st, st.AddSeconds(86399));

                if (results != null)
                {
                    SelectResult = new ObservableCollection<GridItemEventResult>(results);

                    FreqChart = CreateDayFreqImage(results, st, st.ToString("D", culture));
                    //freqBytes = BitmapHelper.ConvertToBytes(ExportToBitmap(FreqChart, dayFreqImageWidth, dayFreqImageHeight));

                    var mes = results.Where(rs => rs.Energy >= MiddleEnergy).ToList();
                    //new ReportPlanImage().DrawPlanClipToFile(mes);
                    MiddleEnergyEvents = mes;
                    MiddleEventCount = mes.Count();
                    if (mes.Count > 0)
                    {
                        ReportPlanImage rpi = new ReportPlanImage();
                        //rpi.DrawPlanClipToDrawVisual(mes, (int)rView.canvasPlan.ActualWidth, (int)rView.canvasPlan.ActualHeight);
                        rpi.Draw(mes, rView.canvasPlan.ActualWidth, rView.canvasPlan.ActualHeight);
                        //rView.canvasPlan = rpi.host;
                        rView.canvasPlan.Children.Clear();
                        rView.canvasPlan.Children.Add(rpi.host);

                        CreateStereoChart(mes);

                    }
                    
                    //rView.canvasPlan.
                    //dayMiddleEventPlanBytes = new ReportPlanImage().DrawPlanClipToFile(mes);


                }
            });
        }

        /// <summary>
        /// 导出事件列表
        /// </summary>
        public ICommand ExportEventListFileExcelCmd
        {
            get => new DelegateCommand<ReportView>((rView) =>
            {
                ExportEventListReport(rView);
            });
        }
        private ObservableCollection<GridItemEventResult> _dataItems = new ObservableCollection<GridItemEventResult>();        

        /// <summary>
        /// 实际到数据源
        /// </summary>
        public ObservableCollection<GridItemEventResult> DataItems
        {
            get { return _dataItems; }
            set
            {
                SetProperty(ref _dataItems, value);
            }
        }

        /// <summary>
        /// 数据列表刷新的请求事件，参数-startIndex,length
        /// </summary>
        public event Action<uint, uint> DataListPagingStartLengthChangeEvent;
        /// <summary>
        /// 用于界面绑定的 页面刷新事件
        /// </summary>
        public ICommand PageRefreshCmd
        {
            get
            {
                return new RelayCommand<Tuple<uint, uint>>(tuple =>
                {
                    if (DataListPagingStartLengthChangeEvent != null)
                    {
                        DataListPagingStartLengthChangeEvent(tuple.Item1,
                                                             tuple.Item2);
                    }
                });
            }
        }

        public ReportViewModel(IEventAggregator ea)
        {
            dayFreqImagePath = AppDomain.CurrentDomain.BaseDirectory + "\\resources\\dayFreqImage.png";
            int yy = DateTime.Now.Year;
            int mm = DateTime.Now.Month;
            int ss = DateTime.Now.Day;
            StartTime = new DateTime(yy, mm, ss,GlobalConfig.DailyReportStartTime.Hour, GlobalConfig.DailyReportStartTime.Minute,GlobalConfig.DailyReportStartTime.Second).AddDays(-1);
            EndTime = new DateTime(yy, mm, ss, GlobalConfig.DailyReportStartTime.Hour, GlobalConfig.DailyReportStartTime.Minute, GlobalConfig.DailyReportStartTime.Second);
            TimeFC = new FilterCondition<DateTime>(true, StartTime, EndTime);
            EastFC = new FilterCondition<double>(false, GlobalConfig.ProjectConfig.WorkArea.EMax, GlobalConfig.ProjectConfig.WorkArea.EMin);
            NorthFC = new FilterCondition<double>(false, GlobalConfig.ProjectConfig.WorkArea.NMax, GlobalConfig.ProjectConfig.WorkArea.NMin);
            DepthFC = new FilterCondition<double>(false, GlobalConfig.ProjectConfig.WorkArea.ZMax, GlobalConfig.ProjectConfig.WorkArea.ZMin);
            MLFC = new FilterCondition<double>(false, 0, -2);
            EnergyFC = new FilterCondition<double>(false, 20000, 0);
            SelectSortMode = SelectSort.Time;

            MiddleEnergy = 200;
            SelectResult = new ObservableCollection<GridItemEventResult>();
           
            this.ea = ea;
            this.ea.GetEvent<UpdateCanvasChildrenMessage>().Publish("updatecanvas");
        }
        
        public void CreateStereoChart(List<GridItemEventResult> events)
        {
            eventSize = new SizeDoubleXYZ(GlobalConfig.eventDSize, GlobalConfig.eventDSize, GlobalConfig.eventDSize);

            _bottomWall = new WallXZ();
            _bottomWall.Material = new Material3D() { DiffuseColor = Color.FromArgb(0, 248, 248, 255) };
            _bottomWall.SetGridStripColor1(Color.FromArgb(0, 248, 248, 255));
            _bottomWall.SetGridStripColor2(Color.FromArgb(0, 248, 248, 255));
            _topWall = new WallXZ();
            _topWall.Material = new Material3D() { DiffuseColor = Color.FromArgb(0, 248, 248, 255) };
            _topWall.SetGridStripColor1(Color.FromArgb(0, 248, 248, 255));
            _topWall.SetGridStripColor2(Color.FromArgb(0, 248, 248, 255));
            _leftWall = new WallYZ();
            _leftWall.Material = new Material3D() { DiffuseColor = Color.FromArgb(0, 248, 248, 255) };
            _leftWall.SetGridStripColor1(Color.FromArgb(0, 248, 248, 255));
            _leftWall.SetGridStripColor2(Color.FromArgb(0, 248, 248, 255));
            _rightWall = new WallYZ();
            _rightWall.Material = new Material3D() { DiffuseColor = Color.FromArgb(0, 248, 248, 255) };
            _rightWall.SetGridStripColor1(Color.FromArgb(0, 248, 248, 255));
            _rightWall.SetGridStripColor2(Color.FromArgb(0, 248, 248, 255));
            _frontWall = new WallXY();
            _frontWall.Material = new Material3D() { DiffuseColor = Color.FromArgb(0, 248, 248, 255) };
            _frontWall.SetGridStripColor1(Color.FromArgb(0, 248, 248, 255));
            _frontWall.SetGridStripColor2(Color.FromArgb(0, 248, 248, 255));
            _backWall = new WallXY();
            _backWall.Material = new Material3D() { DiffuseColor = Color.FromArgb(0, 248, 248, 255) };
            _backWall.SetGridStripColor1(Color.FromArgb(0, 248, 248, 255));
            _backWall.SetGridStripColor2(Color.FromArgb(0, 248, 248, 255));

            _axisXPri3D = new AxisX3D();
            _axisXPri3D.Maximum = GlobalConfig.ProjectConfig.WorkArea.EMax / _scale;
            _axisXPri3D.Minimum = GlobalConfig.ProjectConfig.WorkArea.EMin / _scale;
            _axisXPri3D.Title.Text = "西东";
            _axisXPri3D.LabelsVisible = true;
            _axisXPri3D.LabelsColor = Colors.Black;
            _axisXPri3D.Orientation = PlaneXAxis3D.XZ;
            _axisXPri3D.Location = AxisXLocation3D.BottomFront;
            _axisXPri3D.LabelsNumberFormat = "00000000";
            _axisXPri3D.AutoFormatLabels = false;

            _axisYPri3D = new AxisY3D();
            _axisYPri3D.Title.Text = "海拔";
            _axisYPri3D.Minimum = (GlobalConfig.ProjectConfig.WorkArea.ZMin / _scale);
            _axisYPri3D.Maximum = ((GlobalConfig.ProjectConfig.WorkArea.ZMax + 50) / _scale);
            _axisYPri3D.Reversed = true;
            _axisYPri3D.LabelsColor = Colors.Black;
            //AxisYPri3D.Visible = false;

            _axisZPri3D = new AxisZ3D();
            _axisZPri3D.Maximum = GlobalConfig.ProjectConfig.WorkArea.NMax / _scale;
            _axisZPri3D.Minimum = GlobalConfig.ProjectConfig.WorkArea.NMin / _scale;
            _axisZPri3D.Title.Text = "南北";
            _axisZPri3D.Orientation = PlaneZAxis3D.XZ;
            _axisZPri3D.Location = AxisZLocation3D.BottomRight;
            _axisZPri3D.LabelsColor = Colors.Black;
            _axisZPri3D.LabelsNumberFormat = "0000000";
            _axisZPri3D.AutoFormatLabels = false;

            StereoChart = new LightningChart();
            stereoChart.BeginUpdate();
            StereoChart.View3D.LegendBox.Visible = false;
            stereoChart.ChartBackground = new Fill() { GradientFill = GradientFill.Solid, GradientColor = Colors.White };

            StereoChart.ActiveView = ActiveView.View3D;
            StereoChart.Name = "StereogramImage";
            StereoChart.Title.Text = "三维视图";
            //StereoChart.View3D.ZoomPanOptions.AllowWheelZoom = false;
            //StereoChart.View3D.ZoomPanOptions.AxisWheelAction = AxisWheelAction.None;

            StereoChart.View3D.Lights = (List<Light3D>)View3D.CreateDefaultLights();
            StereoChart.View3D.Dimensions = new SizeDoubleXYZ(_widthRS, _heightRS, _depthRS);
            StereoChart.View3D.Camera = new Camera3D() { RotationX = _verticalRotationRS, RotationY = _horizontalRotationRS, RotationZ = _sideRotationRS };
            StereoChart.View3D.OrientationArrows = new OrientationArrowsOptions3D() { ArrowLength = 50, Visible = true };
            StereoChart.View3D.ClipContents = true;
            //StereoImage.View3D.PointLineSeries3D = ChartPointLineCollection;
            //StereoImage.View3D.Annotations = ChartAnnotationCollection;
            StereoChart.View3D.WallOnBottom = _bottomWall;
            StereoChart.View3D.WallOnTop = _topWall;
            StereoChart.View3D.WallOnLeft = _leftWall;
            StereoChart.View3D.WallOnRight = _rightWall;
            StereoChart.View3D.WallOnFront = _frontWall;
            StereoChart.View3D.WallOnBack = _backWall;
            StereoChart.View3D.XAxisPrimary3D = _axisXPri3D;
            StereoChart.View3D.YAxisPrimary3D = _axisYPri3D;
            StereoChart.View3D.ZAxisPrimary3D = _axisZPri3D;

            PointLineSeries3D plsEvent3d = new PointLineSeries3D(StereoChart.View3D, Axis3DBinding.Primary, Axis3DBinding.Primary, Axis3DBinding.Primary);
            plsEvent3d.Title.Text = "微地震事件";
            plsEvent3d.Tag = "mmevent";
            plsEvent3d.IndividualPointColors = true;
            plsEvent3d.IndividualPointSizes = true;
            plsEvent3d.LineVisible = false;
            plsEvent3d.AllowUserInteraction = true;
            plsEvent3d.PointsVisible = true;
            plsEvent3d.PointStyle.Shape3D = PointShape3D.Sphere;
            plsEvent3d.PointStyle.Size3D = eventSize;

            List<SeriesPoint3D> sp3List = new List<SeriesPoint3D>();
            foreach (var ms in events)
            {
                {
                    float sizeFactor = (float)(((4f + ms.ML) / (4f)) * 4f) + 0.1f;
                    int colorIndex = (int)(((ms.Z - GlobalConfig.ProjectConfig.WorkArea.ZMin)
                        / Math.Abs(GlobalConfig.ProjectConfig.WorkArea.ZMax - GlobalConfig.ProjectConfig.WorkArea.ZMin))
                        * GlobalConfig.ColorCountDefault);
                    Color ec = GlobalConfig.eventDepthColor[colorIndex];

                    sp3List.Add(new SeriesPoint3D((ms.X), (GlobalConfig.BaseZ - ms.Z), (ms.Y), ec, sizeFactor));

                }
            }
            plsEvent3d.Points = sp3List.ToArray();
            StereoChart.View3D.PointLineSeries3D.Add(plsEvent3d);
            stereoChart.EndUpdate();
        }
        public List<GridItemEventResult> SearchEvents(DateTime searchStartTime, DateTime searchEndTime)
        {
            List<GridItemEventResult> results = new List<GridItemEventResult>();
            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<RemoteRealtimeResultEntity>()
                   .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.SetEnergy();
                    results.Add(se);
                }
            }
            SearchCount = results.Count;
            UpdateEnergyStats(results);
            return results;
        }

        private void UpdateEnergyStats(List<GridItemEventResult> results)
        {
            if (results == null || results.Count == 0)
            {
                TotalEnergy = 0;
                AverageEnergy = 0;
                MaxEnergy = 0;
                return;
            }

            TotalEnergy = Math.Round(results.Sum(rs => rs.Energy), 2);
            AverageEnergy = Math.Round(results.Average(rs => rs.Energy), 2);
            MaxEnergy = Math.Round(results.Max(rs => rs.Energy), 2);
        }
        
        public void ExportEventListReport(ReportView rView)
        {
            string fileNmae = "微震事件列表_" + DateTime.Now.ToString("yyyyMMdd");
            switch (SelectType)
            {
                case 1:
                    fileNmae = "微震预警日报表_" + TimeFC.Cond1.ToString("yyyyMMdd");
                    break;
                case 2:
                    fileNmae = "微震预警周报表_" + TimeFC.Cond2.ToString("yyyyMMdd");
                    break;
                case 3:
                    fileNmae = "微震预警月报表_" + TimeFC.Cond2.ToString("yyyyMMdd");
                    break;
            }
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "事件列表|*.xlsx";
            sfd.FileName = fileNmae;
            if (SearchCount == 0)
            {
                HandyControl.Controls.MessageBox.Show("请先选择数据");
                return;
            }
            if (sfd.ShowDialog() == true)
            {
                string outFileName = sfd.FileName;
                switch (SelectType)
                {
                    case 0:
                        ExportEventList(outFileName);
                        break;
                    case 1:
                        legendBytes = BitmapHelper.ElementToBytes(rView.colorMap);
                        freqBytes = BitmapHelper.ElementToBytes(rView.oxyplotDayFreq);
                        middleEventPlanBytes = BitmapHelper.ElementToBytes(rView.canvasMain);
                        middleEventStereoBytes = BitmapHelper.ElementToBytes(StereoChart);
                        ExportDayEventsReport(outFileName, MiddleEnergyEvents);
                        //fileNmae = "微震预警日报表_" + reportStartTime.ToString("yyyyMMdd");
                        break;
                    case 2:
                        //fileNmae = "微震预警周报表_" + reportStartTime.ToString("yyyyMMdd");
                        break;
                    case 3:
                        //fileNmae = "微震预警月报表_" + reportStartTime.ToString("yyyyMMdd");
                        break;
                }
                HandyControl.Controls.MessageBox.Show(outFileName + "导出完成!");
            }
        }
        public void ExportEventList(string fn)
        {
            string tmpPath = Environment.CurrentDirectory + "\\resources\\ReportEventListTemp.xlsx";
            IWorkbook workbook = null;           

            //try
            {
                using (var fs = new FileStream(tmpPath, FileMode.Open, FileAccess.ReadWrite))
                {
                    // 这个对象针对xls   2007版本Office以下版本
                    //workbook = new HSSFWorkbook(fs);
                    //这个对象针对xlsx   2007版本Office以上
                    workbook = new XSSFWorkbook(fs);
                }
                //创建表格
                #region Sheet1-事件列表
                ISheet sheet = workbook.GetSheet("Sheet1");

                //创建样式，垂直居中，边框，自动换行
                ICellStyle style0 = workbook.CreateCellStyle();
                style0.BorderBottom = BorderStyle.Thin;
                style0.BorderTop = BorderStyle.Thin;
                style0.BorderLeft = BorderStyle.Thin;
                style0.BorderRight = BorderStyle.Thin;
                style0.VerticalAlignment = VerticalAlignment.Center;
                style0.WrapText = true;

                // 创建样式，垂直居中，水平居中，边框，自动换行
                ICellStyle style1 = workbook.CreateCellStyle();
                style1.BorderBottom = BorderStyle.Thin;
                style1.BorderTop = BorderStyle.Thin;
                style1.BorderLeft = BorderStyle.Thin;
                style1.BorderRight = BorderStyle.Thin;
                style1.VerticalAlignment = VerticalAlignment.Center;
                style1.Alignment = HorizontalAlignment.Center;
                style1.WrapText = true;

                #region ***设置格式***
               
                #endregion

                #region ***写入数据***
                //标题
                sheet.GetRow(0).Cells[0].SetCellValue(GlobalConfig.WorkAreaName + "工作面地面微震事件列表");
                //报表日期
                sheet.GetRow(1).CreateCell(1).SetCellValue(TimeFC.Cond2.ToString("D", culture));
                //事件数
                sheet.GetRow(1).CreateCell(reportEventListCols).SetCellValue(SelectResult.Count);

                //事件列表
                for (int i = 0; i < SelectResult.Count; i++)
                {
                    GridItemEventResult gr = SelectResult[i];
                    if (gr.IsSelected)
                    {
                        IRow row = sheet.CreateRow(3 + i);
                        row.Height = 20 * 20;
                        row.CreateCell(0).SetCellValue(i + 1);
                        row.CreateCell(1).SetCellValue(gr.EventID);
                        row.CreateCell(2).SetCellValue(gr.EventTime);
                        row.CreateCell(3).SetCellValue(Math.Round(gr.X, 2));
                        row.CreateCell(4).SetCellValue(Math.Round(gr.Y, 2));
                        row.CreateCell(5).SetCellValue(Math.Round(gr.Z, 2));
                        row.CreateCell(6).SetCellValue(Math.Round(gr.ML, 2));
                        row.CreateCell(7).SetCellValue(Math.Round(gr.Energy, 2));
                        row.CreateCell(8).SetCellValue(gr.DominantFreq);
                        row.CreateCell(9).SetCellValue(GlobalData.FocalMechanismIndex2String(gr.SourceChara));
                        string outAngle = gr.Direction < 90 ? "NE" + gr.Direction.ToString() : "NW" + (180 - gr.Direction).ToString();
                        row.CreateCell(10).SetCellValue(outAngle);
                        //row.CreateCell(11);
                        for (int col = 0; col < reportEventListCols + 1; col++)
                        {
                            row.GetCell(col).CellStyle = style1;
                        }
                        //row.GetCell(1).CellStyle = style1;
                        //row.GetCell(8).CellStyle = style1;
                    }
                }
                #endregion
                #endregion


                #region sheet2-事件统计
                ISheet sheet2 = workbook.GetSheet("Sheet2");
                //区域
                sheet2.GetRow(0).CreateCell(1).SetCellValue(GlobalConfig.WorkAreaName);
                //日期
                sheet2.GetRow(1).CreateCell(1).SetCellValue(TimeFC.Cond2.ToString("D", culture));
                //事件数
                sheet2.GetRow(2).CreateCell(1).SetCellValue(SelectResult.Count);

                //≤100J的事件数量
                int less100J = SelectResult.Count(sr => sr.Energy <= 100);
                sheet2.GetRow(5).CreateCell(1).SetCellValue(less100J);
                sheet2.GetRow(5).Cells[1].CellStyle=style1;
                //≤100J的占比
                double less100Jpercent = (double)less100J / (double)SelectResult.Count;
                sheet2.GetRow(6).CreateCell(1).SetCellValue(Math.Round(less100Jpercent*100,2).ToString()+"%");
                sheet2.GetRow(6).Cells[1].CellStyle = style1;

                //＞100J && ≤1000J
                int greater100J = SelectResult.Count(sr => sr.Energy > 100 && sr.Energy<=1000);
                sheet2.GetRow(5).CreateCell(2).SetCellValue(greater100J);
                sheet2.GetRow(5).Cells[2].CellStyle = style1;
                //＞100J && ≤1000J占比
                double greater100Jpercent = (double)greater100J / (double)SelectResult.Count;
                sheet2.GetRow(6).CreateCell(2).SetCellValue(Math.Round(greater100Jpercent*100, 2).ToString() + "%");
                sheet2.GetRow(6).Cells[2].CellStyle = style1;

                //＞1000J && ≤10000J
                int greater1000J = SelectResult.Count(sr => sr.Energy > 1000 && sr.Energy <= 10000);
                sheet2.GetRow(5).CreateCell(3).SetCellValue(greater1000J);
                sheet2.GetRow(5).Cells[3].CellStyle = style1;
                //＞100J && ≤1000J占比
                double greater1000Jpercent = (double)greater1000J / (double)SelectResult.Count;
                sheet2.GetRow(6).CreateCell(3).SetCellValue(Math.Round(greater1000Jpercent*100, 2).ToString() + "%");
                sheet2.GetRow(6).Cells[3].CellStyle = style1;

                //＞10000J
                int greater10000J = SelectResult.Count(sr => sr.Energy > 10000);
                sheet2.GetRow(5).CreateCell(4).SetCellValue(greater10000J);
                sheet2.GetRow(5).Cells[4].CellStyle = style1;
                //＞100J && ≤1000J占比
                double greater10000Jpercent = (double)greater10000J / (double)SelectResult.Count;
                sheet2.GetRow(6).CreateCell(4).SetCellValue(Math.Round(greater10000Jpercent*100, 2).ToString() + "%");
                sheet2.GetRow(6).Cells[4].CellStyle = style1;
                #endregion
                // 3、保存到本地文件              
                using (FileStream fs = new FileStream(fn, FileMode.Create, FileAccess.Write, FileShare.Write))
                {
                    workbook.Write(fs);
                }
                //HandyControl.Controls.MessageBox.Show(fn + "导出完成!");
            }
            //catch (Exception ex)
            //{
            //    MessageBox.Show("导出错误：" + ex.Message);
            //}
        }
        public void ExportDayEventsReport(string fn, List<GridItemEventResult> events)
        {
            string tmpPath = Environment.CurrentDirectory + "\\resources\\ReportDayTemp.xlsx";
            IWorkbook workbook = null;

            //try
            {
                using (var fs = new FileStream(tmpPath, FileMode.Open, FileAccess.ReadWrite))
                {
                    // 这个对象针对xls   2007版本Office以下版本
                    //workbook = new HSSFWorkbook(fs);
                    //这个对象针对xlsx   2007版本Office以上
                    workbook = new XSSFWorkbook(fs);
                }
                //创建表格
                ISheet sheet = workbook.GetSheet("Sheet1");

                //创建样式，垂直居中，边框，自动换行
                ICellStyle style0 = workbook.CreateCellStyle();
                style0.BorderBottom = BorderStyle.Thin;
                style0.BorderTop = BorderStyle.Thin;
                style0.BorderLeft = BorderStyle.Thin;
                style0.BorderRight = BorderStyle.Thin;
                style0.VerticalAlignment = VerticalAlignment.Center;               
                style0.WrapText = true;

                // 创建样式，水平居中，边框，自动换行
                ICellStyle style1 = workbook.CreateCellStyle();
                style1.BorderBottom = BorderStyle.Thin;
                style1.BorderTop = BorderStyle.Thin;
                style1.BorderLeft = BorderStyle.Thin;
                style1.BorderRight = BorderStyle.Thin;
                style1.VerticalAlignment = VerticalAlignment.Center;
                style1.Alignment = HorizontalAlignment.Center;
                style1.WrapText = true;


                #region ***写入数据***
                //日期
                sheet.GetRow(1).Cells[0].SetCellValue(TimeFC.Cond1.ToString("D", culture) + "综合日报表");
                ////数据范围
                //sheet.GetRow(1).Cells[4].SetCellValue("N1100");

                //回风日进尺

                //回风总进尺

                //胶带日进尺

                //胶带总进尺

                //最大震级
                double maxML = SelectResult.Max(sr => sr.ML);
                double maxEnergy = SelectResult.Max(sr => sr.Energy);
                sheet.GetRow(4).Cells[5].SetCellValue(Math.Round(maxML,2));
                //最大能量
                sheet.GetRow(4).Cells[7].SetCellValue(Math.Round(maxEnergy,2));
                #region 插入频度图              
                // 1.确定图片索引
                int pictureIdx = workbook.AddPicture(freqBytes, PictureType.PNG);  // 注意图片格式
                //2.创建画布
                IDrawing patriarch = sheet.CreateDrawingPatriarch();
                //3.设置锚点
                IClientAnchor anchor = patriarch.CreateAnchor(5, 5, 5, 5, 0, 9, 9, 19);
                //4.插入图片
                IPicture pict = patriarch.CreatePicture(anchor, pictureIdx);
                //5.释放对象
                freqBytes = null;
                #endregion

                //平面图
                #region 插入平面图
                //1.确定图片索引
                pictureIdx = workbook.AddPicture(middleEventPlanBytes, PictureType.PNG);  // 注意图片格式
                //2.创建画布
                patriarch = sheet.CreateDrawingPatriarch();
                //3.设置锚点              
                anchor = patriarch.CreateAnchor(5, 5, 5, 5, 0, 21, 3, 34);
                //4.插入图片
                pict = patriarch.CreatePicture(anchor, pictureIdx);
                //5.释放对象
                middleEventPlanBytes = null;
                #endregion

                //三维图
                pictureIdx = workbook.AddPicture(middleEventStereoBytes, PictureType.PNG);  // 注意图片格式
                //2.创建画布
                patriarch = sheet.CreateDrawingPatriarch();
                //3.设置锚点
                //int rowline = 1;
                // 参数说明：（X起始，Y起始，X终止，Y终止，起始单元格列数，行数，终止单元格列数，行数）  
                anchor = patriarch.CreateAnchor(5, 5, 5, 5, 3, 21, 8, 34);
                //4.把图片插到相应的位置
                pict = patriarch.CreatePicture(anchor, pictureIdx);

                //插入色标图
                pictureIdx = workbook.AddPicture(legendBytes, PictureType.PNG);  // 注意图片格式
                //2.创建画布
                patriarch = sheet.CreateDrawingPatriarch();
                //3.设置锚点
                //int rowline = 1;
                // 参数说明：（X起始，Y起始，X终止，Y终止，起始单元格列数，行数，终止单元格列数，行数）  
                anchor = patriarch.CreateAnchor(0, 0, 0, 0, 8, 29, 9, 34);
                //4.插入图片
                pict = patriarch.CreatePicture(anchor, pictureIdx);
                //5.释放对象
                legendBytes = null;

                //事件列表
                for (int i = 0; i < events.Count; i++)
                {
                    GridItemEventResult gr = events[i];
                    string scStr = "未识别";
                    switch (gr.SourceChara)
                    {
                        case 0:
                            scStr = "走滑";
                            break;
                        case 1:
                            scStr = "倾滑";
                            break;
                        case 2:
                            scStr = "张性";
                            break;
                    }
                    if (gr.IsSelected)
                    {
                        IRow row = sheet.CreateRow(reportDayListFirstRow + i);
                        row.Height = 20 * 20;
                        row.CreateCell(0).SetCellValue(i + 1);
                        row.CreateCell(1).SetCellValue(gr.EventTime);
                        row.CreateCell(2).SetCellValue(Math.Round(gr.X, 2));
                        row.CreateCell(3).SetCellValue(Math.Round(gr.Y, 2));
                        row.CreateCell(4).SetCellValue(Math.Round(gr.Z, 2));
                        row.CreateCell(5).SetCellValue(Math.Round(gr.ML, 2));
                        row.CreateCell(6).SetCellValue(Math.Round(gr.Energy, 2));
                        row.CreateCell(7).SetCellValue(scStr);
                        row.CreateCell(8).SetCellValue(gr.DominantFreq);
                        
                        for (int col = 0; col < 9; col++)
                        {
                            row.GetCell(col).CellStyle = style1;
                           
                        }                        
                    }
                }
                ////合并事件列表标题
                //for (int i = 20; i < 21+SearchCount; i++)
                //{
                //    sheet.GetRow(i).GetCell(0).CellStyle = style1;
                //}
                //sheet.GetRow(20).GetCell(0).SetCellValue("事件列表");
                //SetCellRangeAddress(sheet, 20, 20 + SearchCount, 0, 0);

                ////规律标题
                //sheet.CreateRow(20 + SearchCount + 1);
                //sheet.CreateRow(20 + SearchCount + 2);
                //sheet.CreateRow(20 + SearchCount + 3);
                //sheet.CreateRow(20 + SearchCount + 4);
                //sheet.CreateRow(20 + SearchCount + 5);
                //sheet.CreateRow(20 + SearchCount + 6);

                //sheet.GetRow(20 + SearchCount + 1).CreateCell(0).SetCellValue("规律分析及相关说明");                

                //sheet.GetRow(20 + SearchCount + 1).Cells[0].CellStyle = style0;
                //sheet.GetRow(20 + SearchCount + 2).CreateCell(0).CellStyle = style0;
                //sheet.GetRow(20 + SearchCount + 3).CreateCell(0).CellStyle = style0;
                //sheet.GetRow(20 + SearchCount + 4).CreateCell(0).CellStyle = style0;
                //sheet.GetRow(20 + SearchCount + 5).CreateCell(0).CellStyle = style0;
                //sheet.GetRow(20 + SearchCount + 6).CreateCell(0).CellStyle = style0;

                //SetCellRangeAddress(sheet, 20 + SearchCount + 1, 20 + SearchCount + 6, 0, 0);                

                ////规律内容
                //sheet.GetRow(20 + SearchCount + 1).CreateCell(1);

                //for (int i = 21+SearchCount; i < 21 + SearchCount+6; i++)
                //{
                //    for (int j = 1; j < 9; j++)
                //    {
                //        sheet.GetRow(i).CreateCell(j).CellStyle = style0;
                //    }
                //}
                //SetCellRangeAddress(sheet, 20 + SearchCount + 1, 20 + SearchCount + 6, 1, 8);
                #endregion
                // 3、保存到本地文件              
                using (FileStream fs = new FileStream(fn, FileMode.Create, FileAccess.Write, FileShare.Write))
                {
                    workbook.Write(fs);
                }

                //MessageBox.Show(fn + "导出完成!");
            }
            //catch (Exception ex)
            //{
            //    MessageBox.Show("导出错误：" + ex.Message);
            //}
        }
        public PlotModel CreateDayFreqImage(List<GridItemEventResult> events, DateTime statDate, string subTitle = "")
        {
            ReportFreqImage report = new ReportFreqImage();
            var legend1 = new Legend();
            legend1.LegendOrientation = LegendOrientation.Horizontal;
            legend1.LegendPlacement = LegendPlacement.Inside;
            legend1.LegendPosition = LegendPosition.TopRight;
            legend1.LegendPadding = 0;
            legend1.AllowUseFullExtent = true;
            report.PlotLegend = legend1;
            string plotTitle = "频度 - 能量变化趋势图";
            string[] titles = new[] { "<负2级", "负2级至负1级", "负1级至负0.5级", "负0.5级以上" };
            OxyColor strokeColor = OxyColors.Black;
            OxyColor textColor = OxyColors.White;
            LabelPlacement placement = LabelPlacement.Middle;
            report.categoryAxes = new CategoryAxis { Position = AxisPosition.Left };
            string[] categoryColors = new[] { "#052d6e", "#284a7e", "#ffa200", "#a66a00" };
            for (int i = 0; i < 24; i++)
            {
                DateTime showHour = GlobalConfig.DailyReportStartTime.AddHours(i);
                report.categoryAxes.Labels.Add((showHour.Hour).ToString() + "时");
            }
            //Random rnd = new Random((int)DateTime.Now.Ticks);
            for (int i = GlobalData.ReportEventLevelList.Count - 1; i >= 0; i--)
            //for (int i = 0; i < 4; i++)
            {
                ReportEventLevel rel = GlobalData.ReportEventLevelList[i];
                List<double> values = new List<double>();
                for (int j = 0; j < 24; j++)
                {
                    int ec = events.FindAll(es => DateTime.Parse(es.EventTime).Ticks >= statDate.AddHours(j).Ticks &&
                    DateTime.Parse(es.EventTime).Ticks < statDate.AddHours(j + 1).Ticks && es.ML >= rel.lowerbound && es.ML < rel.upperbound).Count;
                    values.Add(ec);
                }
                //report.AddSeries(titles[i], OxyColor.Parse(categoryColors[i]), OxyColor.Parse(categoryColors[i]), textColor, placement, values);
                report.AddSeries(rel.describe, OxyColor.Parse(rel.color), OxyColor.Parse(rel.color), textColor, placement, values);
            }
            report.linearAxis = new LinearAxis
            {
                Position = AxisPosition.Bottom,
                MinimumPadding = 0,
                MaximumPadding = 0.5,
                ExtraGridlines = new[] { 0.0 },
                ExtraGridlineStyle = LineStyle.Solid,
                ExtraGridlineColor = OxyColors.Black,
                ExtraGridlineThickness = 1,
                MajorGridlineStyle = LineStyle.Solid
            };
            report.SubTitle = subTitle;
            report.CreateModeWithValues(plotTitle, OxyColors.White, true);

            return report.plotModel;
            //return report.ExportToBitmap(dayFreqImageHeight, dayFreqImageWidth);
            //byte[] bytes = BitmapHelper.ConvertToBytes(report.ExportToBitmap(dayFreqImageHeight, dayFreqImageWidth));
        }
        
        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.Phases = new Dictionary<string, int>();
                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;
        }
        /// <summary>
        /// 合并单元格
        /// </summary>
        /// <param name="sheet">要合并单元格所在的sheet</param>
        /// <param name="rowstart">开始行的索引</param>
        /// <param name="rowend">结束行的索引</param>
        /// <param name="colstart">开始列的索引</param>
        /// <param name="colend">结束列的索引</param>
        public static void SetCellRangeAddress(ISheet sheet, int rowstart, int rowend, int colstart, int colend)
        {
            CellRangeAddress cellRangeAddress = new CellRangeAddress(rowstart, rowend, colstart, colend);
            sheet.AddMergedRegion(cellRangeAddress);
        }
        private byte[] CreateReportFreqToBytes(List<GridItemEventResult> events, DateTime statDate, string subTitle = "")
        {
            ReportFreqImage report = new ReportFreqImage();
            var legend1 = new Legend();
            legend1.LegendOrientation = LegendOrientation.Horizontal;
            legend1.LegendPlacement = LegendPlacement.Inside;
            legend1.LegendPosition = LegendPosition.TopRight;
            legend1.AllowUseFullExtent = true;
            report.PlotLegend = legend1;
            string plotTitle = "频度 - 能量变化趋势图";
            string[] titles = new[] { "<负2级", "负2级至负1级", "负1级至负0.5级", "负0.5级以上" };
            OxyColor strokeColor = OxyColors.Black;
            OxyColor textColor = OxyColors.White;
            LabelPlacement placement = LabelPlacement.Middle;
            report.categoryAxes = new CategoryAxis { Position = AxisPosition.Left };
            string[] categoryColors = new[] { "#052d6e", "#284a7e", "#ffa200", "#a66a00" };
            for (int i = 0; i < 24; i++)
            {
                DateTime showHour = GlobalConfig.DailyReportStartTime.AddHours(i);
                report.categoryAxes.Labels.Add((showHour.Hour).ToString() + "时");
            }
            Random rnd = new Random((int)DateTime.Now.Ticks);
            for (int i = GlobalData.ReportEventLevelList.Count - 1; i >= 0; i--)
            //for (int i = 0; i < 4; i++)
            {
                ReportEventLevel rel = GlobalData.ReportEventLevelList[i];
                List<double> values = new List<double>();
                for (int j = 0; j < 24; j++)
                {
                    int ec = events.FindAll(es => DateTime.Parse(es.EventTime).Ticks >= statDate.AddHours(j).Ticks &&
                    DateTime.Parse(es.EventTime).Ticks < statDate.AddHours(j + 1).Ticks && es.ML >= rel.lowerbound && es.ML < rel.upperbound).Count;
                    values.Add(ec);
                }
                //report.AddSeries(titles[i], OxyColor.Parse(categoryColors[i]), OxyColor.Parse(categoryColors[i]), textColor, placement, values);
                report.AddSeries(rel.describe, OxyColor.Parse(rel.color), OxyColor.Parse(rel.color), textColor, placement, values);
            }
            report.linearAxis = new LinearAxis
            {
                Position = AxisPosition.Bottom,
                MinimumPadding = 0,
                MaximumPadding = 0.5,
                ExtraGridlines = new[] { 0.0 },
                ExtraGridlineStyle = LineStyle.Solid,
                ExtraGridlineColor = OxyColors.Black,
                ExtraGridlineThickness = 1,
                MajorGridlineStyle = LineStyle.Solid
            };
            report.SubTitle = subTitle;
            report.CreateModeWithValues(plotTitle, OxyColors.White, true);

            byte[] bytes = BitmapHelper.ConvertToBytes(report.ExportToBitmap(dayFreqImageHeight, dayFreqImageWidth));
            if (bytes.Length > 0)
            {
                return bytes;
            }
            else
            {
                return new byte[0];
            }
        }
        private void CreateDayReportToImage(List<GridItemEventResult> events, string fn, DateTime statDate, string subTitle = "")
        {
            ReportFreqImage report = new ReportFreqImage();
            var legend1 = new Legend();
            legend1.LegendOrientation = LegendOrientation.Horizontal;
            legend1.LegendPlacement = LegendPlacement.Inside;
            legend1.LegendPosition = LegendPosition.TopRight;
            legend1.AllowUseFullExtent = true;
            report.PlotLegend = legend1;
            string plotTitle = "频度 - 能量变化趋势图";
            string[] titles = new[] { "<负2级", "负2级至负1级", "负1级至负0.5级", "负0.5级以上" };
            OxyColor strokeColor = OxyColors.Black;
            OxyColor textColor = OxyColors.White;
            LabelPlacement placement = LabelPlacement.Middle;
            report.categoryAxes = new CategoryAxis { Position = AxisPosition.Left };
            string[] categoryColors = new[] { "#052d6e", "#284a7e", "#ffa200", "#a66a00" };
            for (int i = 0; i < 24; i++)
            {
                DateTime showHour = GlobalConfig.DailyReportStartTime.AddHours(i);
                report.categoryAxes.Labels.Add((showHour.Hour).ToString() + "时");
            }
            Random rnd = new Random((int)DateTime.Now.Ticks);
            for (int i = 0; i < 4; i++)
            {
                List<double> values = new List<double>();
                for (int j = 0; j < 24; j++)
                {

                    values.Add(rnd.Next(1, 20));
                }
                report.AddSeries(titles[i], OxyColor.Parse(categoryColors[i]), OxyColor.Parse(categoryColors[i]), textColor, placement, values);
            }
            report.linearAxis = new LinearAxis
            {
                Position = AxisPosition.Bottom,
                MinimumPadding = 0,
                MaximumPadding = 0.05,
                ExtraGridlines = new[] { 0.0 },
                ExtraGridlineStyle = LineStyle.Solid,
                ExtraGridlineColor = OxyColors.Black,
                ExtraGridlineThickness = 1,
                MajorGridlineStyle = LineStyle.Solid
            };
            report.SubTitle = subTitle;
            report.CreateModeWithValues(plotTitle, OxyColors.White, true);
            report.ExportPng(fn, dayFreqImageHeight, dayFreqImageWidth);
            //BitmapSource bitmapSource= report.ExportToBitmap(585, 1485);
            //dayFreqBytes = BitmapHelper.ConvertToBytes(report.ExportToBitmap(585, 1485));
        }
        private void CreateWeekReportImage(string fn, DateTime startDate, string subTitle = "")
        {
            ReportFreqImage report = new ReportFreqImage();
            var legend1 = new Legend();
            legend1.LegendOrientation = LegendOrientation.Horizontal;
            legend1.LegendPlacement = LegendPlacement.Inside;
            legend1.LegendPosition = LegendPosition.TopRight;
            legend1.AllowUseFullExtent = true;
            report.PlotLegend = legend1;
            string plotTitle = "频度 - 能量变化趋势图";
            string[] titles = new[] { "<负2级", "负2级至负1级", "负1级至负0.5级", "负0.5级以上" };
            OxyColor strokeColor = OxyColors.Black;
            OxyColor textColor = OxyColors.White;
            LabelPlacement placement = LabelPlacement.Middle;
            report.categoryAxes = new CategoryAxis { Position = AxisPosition.Left };
            string[] categoryColors = new[] { "#052d6e", "#284a7e", "#ffa200", "#a66a00" };
            for (int i = 0; i < 7; i++)
            {
                report.categoryAxes.Labels.Add(startDate.AddDays(i).ToString("d", culture));

            }
            Random rnd = new Random((int)DateTime.Now.Ticks);
            for (int i = 0; i < 4; i++)
            {
                List<double> values = new List<double>();

                for (int j = 0; j < 7; j++)
                {
                    values.Add(rnd.Next(1, 20));
                }
                report.AddSeries(titles[i], OxyColor.Parse(categoryColors[i]), OxyColor.Parse(categoryColors[i]), textColor, placement, values);
            }
            report.linearAxis = new LinearAxis
            {
                Position = AxisPosition.Bottom,
                MinimumPadding = 0,
                MaximumPadding = 0.05,
                ExtraGridlines = new[] { 0.0 },
                ExtraGridlineStyle = LineStyle.Solid,
                ExtraGridlineColor = OxyColors.Black,
                ExtraGridlineThickness = 1,
                MajorGridlineStyle = LineStyle.Solid
            };
            report.SubTitle = subTitle;
            report.CreateModeWithValues(plotTitle, OxyColors.White, true);
            report.ExportPng(fn);
        }
        private void CreateMonthReportImage(string fn, DateTime startDate, DateTime endDate, string subTitle = "")
        {
            ReportFreqImage report = new ReportFreqImage();
            var legend1 = new Legend();
            legend1.LegendOrientation = LegendOrientation.Horizontal;
            legend1.LegendPlacement = LegendPlacement.Inside;
            legend1.LegendPosition = LegendPosition.TopRight;
            legend1.AllowUseFullExtent = true;
            report.PlotLegend = legend1;
            string plotTitle = "频度 - 能量变化趋势图";
            string[] titles = new[] { "<负2级", "负2级至负1级", "负1级至负0.5级", "负0.5级以上" };
            OxyColor strokeColor = OxyColors.Black;
            OxyColor textColor = OxyColors.White;
            LabelPlacement placement = LabelPlacement.Middle;
            report.categoryAxes = new CategoryAxis { Position = AxisPosition.Left };
            string[] categoryColors = new[] { "#052d6e", "#284a7e", "#ffa200", "#a66a00" };
            int count = (endDate - startDate).Days;
            for (int i = 0; i < count; i++)
            {
                report.categoryAxes.Labels.Add(startDate.AddDays(i).ToString("dd"));

            }
            Random rnd = new Random((int)DateTime.Now.Ticks);
            for (int i = 0; i < 4; i++)
            {
                List<double> values = new List<double>();
                for (int j = 0; j < count; j++)
                {
                    values.Add(rnd.Next(1, 20));
                }
                report.AddSeries(titles[i], OxyColor.Parse(categoryColors[i]), OxyColor.Parse(categoryColors[i]), textColor, placement, values);
            }
            report.linearAxis = new LinearAxis
            {
                Position = AxisPosition.Bottom,
                MinimumPadding = 0,
                MaximumPadding = 0.05,
                ExtraGridlines = new[] { 0.0 },
                ExtraGridlineStyle = LineStyle.Solid,
                ExtraGridlineColor = OxyColors.Black,
                ExtraGridlineThickness = 1,
                MajorGridlineStyle = LineStyle.Solid
            };
            report.SubTitle = subTitle;
            report.CreateModeWithValues(plotTitle, OxyColors.White, true);
            report.ExportPng(fn);
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            //throw new NotImplementedException();
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return false;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            if (StereoChart!=null)
            {
                StereoChart.Dispose();
                StereoChart = null;
            }
            if (FreqChart!=null)
            {
                FreqChart = null;
            }
            GC.Collect();
        }
    }
}
