using Arction.Wpf.ChartingMVVM.Axes;
using Arction.Wpf.ChartingMVVM.Views.ViewXY;
using Arction.Wpf.ChartingMVVM;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Threading;
using System.Windows;
using Txgy.EWS.Client.PageModule.Models;
using Txgy.Microseismic.BaseLib.Models;
using Prism.Mvvm;
using Prism.Events;
using Txgy.EWS.Client.IBLL;
using System.Windows.Input;
using Txgy.EWS.Client.Common;
using System.Windows.Media;
using Unity;
using Txgy.EWS.Client.Common.MessageEvents;
using Txgy.EWS.Client.PageModule.Services;
using Newtonsoft.Json.Linq;

namespace Txgy.EWS.Client.PageModule.ViewModels
{
    public class WaveformViewModel : BindableBase
    {
        #region variable
        Dispatcher _dispatcher;
        //private IRemoteDownloadDataBLL remoteDownloadDataBLL;
        private delegate void HandleDataGeneratedDelegate(string eventTime);
        /// <summary>
        /// Delegate for data generation.
        /// </summary>
        private HandleDataGeneratedDelegate _handleDataGenerated;
        /// <summary>
        /// 当前采样数
        /// </summary>
        public int CurPoints;
        private readonly IEventAggregator _ea;
        private readonly ISearchMsEventBLL _searchMsEventBLL;
        private int _selectResult = 0;
        public int SelectResult
        {
            get { return _selectResult; }

            set
            {
                SetProperty(ref _selectResult, value);
            }
        }
        int _channelCount = 60;          // Channel count.
        double _samplingFrequency = 500;  // Sampling frequency (Hz).
        double _previousX = 0;          // Latest X value on axis.
        long _now;                      // Latest time stamp. 
        long _startTicks = 0;           // Controls timing.
        long _samplesOutput;            // Generated samples quantity.

        // Constants
        const double YMin = 30000;       // Minimal y-value.
        const double YMax = 33000;        // Maximal y-value.

        private volatile bool _stop = false; // Stops thread work.
        internal bool IsRunning
        {
            get
            {
                return _thread != null;
            }
        }
        WavesModel _wavesModel;
        #endregion
        /// <summary>
        /// Thread.
        /// </summary>
        private Thread _thread;

        private delegate void ChartUpdateFromThreadHandler(double[][] samples);


        private ChartUpdateFromThreadHandler _chartUpdate;

        private Random _rand = new Random((int)DateTime.Now.Ticks);

        #region "属性"
        private int _lChartCount = 1;
        /// <summary>
        /// 波形控件数量
        /// </summary>
        public int LChartCount
        {
            get { return _lChartCount; }
            set { _lChartCount = value; }
        }
        public List<ShareProperty> WaveComList { get; set; }
        private ShareProperty _wavesCombination;
        /// <summary>
        /// 波形组合
        /// </summary>
        public ShareProperty WavesCombination
        {
            get { return _wavesCombination; }
            set
            {
                _wavesCombination = value;
                SetWavesCombination();
                //Console.WriteLine(_wavesCombination.Name);
            }
        }
        private DataSourcesEnum _dataSources;
        /// <summary>
        /// 数据来源
        /// </summary>
        public DataSourcesEnum DataSources
        {
            get { return _dataSources; }
            set { _dataSources = value; }
        }

        private DataTypeEnum _wavesType;
        /// <summary>
        /// 波形类型
        /// </summary>
        public DataTypeEnum WavesType
        {
            get { return _wavesType; }
            set { _wavesType = value; }
        }

        private DisplayModeEnum _displayMode;
        /// <summary>
        /// 显示模式
        /// </summary>
        public DisplayModeEnum DisplayMode
        {
            get { return _displayMode; }
            set { _displayMode = value; }
        }

        private ScollModeEnum _scollMode;
        /// <summary>
        /// 滚动方式
        /// </summary>
        public ScollModeEnum ScollMode
        {
            get { return _scollMode; }
            set { _scollMode = value; }
        }

        private DateTime _startTime;
        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartTime
        {
            get { return _startTime; }
            set { _startTime = value; }
        }
        private DateTime _endTime;
        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime EndTime
        {
            get { return _endTime; }
            set { _endTime = value; }
        }

        private int _sampling = 500;
        /// <summary>
        /// 采样频率
        /// </summary>
        public int Sampling
        {
            get { return _sampling; }
            set { _sampling = value; }
        }
        /// <summary>
        /// 延时(min)
        /// </summary>
        public int DelayMin { get; set; } = 10;
        /// <summary>
        /// 文件数据位置
        /// </summary>
        public string FileDataPath { get; set; } = @"D:\TaySystemPath\Downloads";
        private int _cacheSize;
        /// <summary>
        /// 缓存大小
        /// </summary>
        public int CacheSize
        {
            get { return _cacheSize; }
            set { _cacheSize = value; }
        }
        private ObservableCollection<int> _stationList;
        /// <summary>
        /// 台站列表
        /// </summary>
        public ObservableCollection<int> StationList
        {
            get { return _stationList; }
            set { _stationList = value; }
        }

        private LightningChart _lChartAll;
        /// <summary>
        /// 所有波形
        /// </summary>
        public LightningChart LChartALL
        {
            get { return _lChartAll; }
            set { _lChartAll = value; }
        }
        private LightningChart _lChartZ;
        /// <summary>
        /// Z通道波形
        /// </summary>
        public LightningChart LChartZ
        {
            get { return _lChartZ; }
            set { _lChartZ = value; }
        }
        private LightningChart _lChartE;
        /// <summary>
        /// E通道波形
        /// </summary>
        public LightningChart LChartE
        {
            get { return _lChartE; }
            set { _lChartE = value; }
        }
        private LightningChart _lChartN;
        /// <summary>
        /// N通道波形
        /// </summary>
        public LightningChart LChartN
        {
            get { return _lChartN; }
            set { _lChartN = value; }
        }

        private FrameworkElement childContent;
        public FrameworkElement ChildContent
        {
            get { return childContent; }
            set { childContent = value; }
        }

        private Grid gridChart;

        public Grid GridChart
        {
            get { return gridChart; }
            set { gridChart = value; }
        }
        private string _btnContrlContent = "开始";

        public string BtnContrlContent
        {
            get { return _btnContrlContent; }
            set { _btnContrlContent = value; }
        }
        private ObservableCollection<MmEvent> _showEvents;
        public ObservableCollection<MmEvent> ShowEvents
        {
            get { return _showEvents; }
            set
            {
                SetProperty(ref _showEvents, value);
            }
        }
        StationWorkModel _stationWorker = null;

        public List<StationModel> smList;
        //public static readonly DependencyProperty XAxesProperty =
        //DependencyProperty.Register(
        //    "xAxes",
        //    typeof(AxisXCollection),
        //    typeof(WavesViewModel)
        //);
        //public AxisXCollection xAxes
        //{
        //    get { return GetValue(XAxesProperty) as AxisXCollection; }
        //    set { SetValue(XAxesProperty, value); }
        //}
        #endregion
        #region "Command"

        #endregion
        public WaveformViewModel(IUnityContainer unityContainer, IEventAggregator ea, ISearchMsEventBLL searchMsEventBLL)
        {
            this._ea = ea;
            this._searchMsEventBLL = searchMsEventBLL;
            _dispatcher = unityContainer.Resolve<Dispatcher>();
            //this.remoteDownloadDataBLL = remoteDownloadDataBLL;
            SelectResult = 10;
            //this.SelectCommand = new CommandBase();
            //this.SelectCommand.ExcuteAction = new Action<object>(SelectEvent);
            //this.SelectCommand.CanExecuteFunc = new Func<bool>(() => true);

            var wcList = (WavesCombinationEnum[])Enum.GetValues(typeof(WavesCombinationEnum));
            WaveComList = wcList.Select(value => new ShareProperty((int)value, value.ToString())).ToList();
            WavesCombination = WaveComList.SingleOrDefault(wc => wc.ID == 0);

            _chartUpdate = new ChartUpdateFromThreadHandler(FeedNewDataToChartPingPu);


            _wavesModel = new WavesModel();
            //_checkBoxWaveformScrollStabilizing = new DelegateCommand(WaveformScrollStabilizing);
            //_checkBoxPaletteColoring = new DelegateCommand(PaletteColoring);
            LChartALL.ViewXY.XAxes = new AxisXCollection();
            LChartALL.ViewXY.XAxes.Add(_wavesModel.GetAxisX(10));
            InitData();
            //(Application.Current.w as UserControl).Loaded += ViewModel_Loaded;
            (Application.Current.MainWindow as System.Windows.Window).Closing += ApplicationClosingDispose;
            _handleDataGenerated = new HandleDataGeneratedDelegate(ShowWave);
            this._ea.GetEvent<ShowWavesEvent>().Subscribe(i =>
            {
                _dispatcher.Invoke(_handleDataGenerated, i);
            });

        }

        private void CheckEvent(object obj)
        {
            //if (ShowEvents != null)
            //{
            //    int eventIndex = (int)obj;
            //    if (ShowEvents[eventIndex] != null)
            //    {
            //        CheckEventShowWave(ShowEvents[eventIndex].EventTimeStr);
            //    }
            //}
            //CheckEventShowWave()
        }
        //string str = "2022-04-10T04:00:52.488";
        private void ShowWave(string obj)
        {
            //System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            //sw.Start();
            string EventTimeStr = obj;
            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 mseedStr = ".mseed";
            string asciiSavePath = GlobalConfig.ProjectConfig.TxtFilePath + "\\" + datePath + "\\" + dataFileName + ".txt";
            if (!Directory.Exists(dataFilePath))
            {
                Directory.CreateDirectory(dataFilePath);
            }
            if (!Directory.Exists(Path.GetDirectoryName(asciiSavePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(asciiSavePath));
            }
            if (!File.Exists(dataFilePath + dataFileName + mseedStr))
            {

                TaskData taskData = new TaskData();
                taskData.EventTimeStr = EventTimeStr;
                taskData.Tasks = new Task(() =>
                {
                    int res = new DownloadWavedata().Download(EventTimeStr, dataFilePath, dataFileName + mseedStr, GlobalConfig.UseWaveDataTable);
                    if (res > -1)
                    {
                        MSeed2Asc(dataFilePath + dataFileName + mseedStr, asciiSavePath);
                    }
                    //Console.WriteLine(taskData.IsComplete);
                });
                taskData.CallBack = (string res) =>
                {
                    _dispatcher.Invoke(() =>
                    {
                        UpdateWavesFromTxt(asciiSavePath);
                        _channelCount = smList.Count * 3;
                        UpdateChart();
                        UpdateChartData();
                    });


                };
                TaskQueue.Instance.AddTaskAndRuning(taskData);
                //_searchMsEventBLL.DownLoadWavedata(downLoadStr, mseedPath, mseedStr, GlobalConfig.UseWaveDataTable);
                //if (!File.Exists(savePath))
                //{
                //    if (!Directory.Exists(Path.GetDirectoryName(savePath)))
                //    {
                //        Directory.CreateDirectory(Path.GetDirectoryName(savePath));
                //    }
                //    MSeed2Asc(mseedPath + mseedStr + ".mseed", savePath);
                //}
                //Dialog.Show(new TextDialog() { ShowText = mseedPath + mseedStr + ".mseed" + "下载完成!" });
            }
            else
            {
                if (!File.Exists(asciiSavePath))
                {
                    MSeed2Asc(dataFilePath + dataFileName + mseedStr, asciiSavePath);
                }
                _dispatcher.Invoke(() =>
                {
                    UpdateWavesFromTxt(asciiSavePath);
                    _channelCount = smList.Count * 3;
                    UpdateChart();
                    UpdateChartData();
                });
                //Dialog.Show(new TextDialog() { ShowText = mseedPath + mseedStr + ".mseed" + "已存在!" });
            }



        }

        private void UpdateChart()
        {
            //线程问题
            LChartALL.ViewXY.YAxes = new AxisYCollection();
            LChartALL.ViewXY.YAxes.Clear();
            LChartALL.ViewXY.YAxes.AddRange(_wavesModel.CreateYAxisPingPu(smList, LChartALL));
            for (int i = 0; i < LChartALL.ViewXY.YAxes.Count; i++)
            {
                LChartALL.ViewXY.YAxes[i].LabelsColor = Colors.Black;
                LChartALL.ViewXY.YAxes[i].AxisColor = Colors.Black;
                LChartALL.ViewXY.YAxes[i].GridStripColor = Colors.Black;
                LChartALL.ViewXY.YAxes[i].Title.Color = Colors.Black;
                LChartALL.ViewXY.YAxes[i].Title.Shadow.DropColor = Colors.Transparent;
                LChartALL.ViewXY.YAxes[i].Title.Shadow.ContrastColor = Colors.Transparent;
            }
            LChartALL.ViewXY.XAxes = new AxisXCollection();
            LChartALL.ViewXY.XAxes.Add(_wavesModel.GetAxisX(CurPoints / Sampling));
            LChartALL.ViewXY.XAxes[0].LabelsColor = Colors.Black;
            //LChartALL.ViewXY.XAxes[0].Title.Fill.Color = Colors.Black;

            //LChartALL.ViewXY.XAxes = new AxisXCollection();
            //LChartALL.ViewXY.XAxes.Add(_wavesModel.GetAxisX(CurPoints / Sampling));
            //LChartALL.ViewXY.XAxes[0].LabelsColor = Colors.Black;

            LChartALL.ViewXY.SampleDataSeries = new SampleDataSeriesCollection();
            LChartALL.ViewXY.SampleDataSeries.AddRange(
                _wavesModel.GetSampleDataSeriesPingPu(smList, LChartALL, LChartALL.ViewXY.XAxes[0],
                LChartALL.ViewXY.YAxes, _samplingFrequency));
        }
        private void UpdateChartData()
        {
            double[][] multiChannelData = new double[smList.Count * 3][];
            try
            {
                for (int channelIndex = 0; channelIndex < smList.Count; channelIndex++)
                {
                    multiChannelData[channelIndex * 3] = smList[channelIndex].dz.ToArray();
                    multiChannelData[channelIndex * 3 + 1] = smList[channelIndex].dn.ToArray();
                    multiChannelData[channelIndex * 3 + 2] = smList[channelIndex].de.ToArray();
                }
                // Invoke FeedNewDataToChart.
                _dispatcher.Invoke(_chartUpdate, System.Windows.Threading.DispatcherPriority.ContextIdle,
                    multiChannelData as object);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        public void UpdateWavesFromTxt(string fn)
        {
            string allStr;

            smList = new List<StationModel>();
            using (StreamReader streamReader = new StreamReader(fn))
            {
                allStr = streamReader.ReadToEnd();
            }
            if (allStr.Length > 0)
            {
                string[] strLines = allStr.Trim().Split(new char[] { '\n' });
                List<string> strList = strLines.ToList();
                int cnt = strList.Count;
                string[] snStr = strLines[0].Trim().Split(',');
                string tmpName = snStr[0].Substring(14, 3);
                CurPoints = int.Parse(snStr[1].Trim().Split(' ')[0]);
                StationModel station = new StationModel();
                station.Name = tmpName;
                station.dz = new List<double>();
                station.dn = new List<double>();
                station.de = new List<double>();

                int channelFlag = 0;

                for (int i = 1; i < strLines.Length; i++)
                {
                    string row = strLines[i].Trim();
                    if (strLines[i].Contains("HA"))
                    {
                        string[] rowStr = strLines[i].Split(',');
                        string chnStr1 = rowStr[0].Substring(21, 3);
                        if (chnStr1 == "SHZ")
                        {
                            //Console.WriteLine($"台站：{station.Name}\tZ:{station.dz.Count}" +
                            //    $"\tN:{station.dn.Count}\tE:{station.de.Count}");
                            smList.Add(station);
                            station = new StationModel();
                            station.Name = rowStr[0].Substring(14, 3);
                            channelFlag = 0;//Z
                        }
                        else if (chnStr1 == "SHN")
                        {
                            channelFlag = 1;//N
                        }
                        else
                        {
                            channelFlag = 2;//E
                        }
                    }
                    else
                    {
                        switch (channelFlag)
                        {
                            case 0://Z
                                station.dz.Add(double.Parse(row));
                                break;
                            case 1://N
                                station.dn.Add(double.Parse(row));
                                break;
                            case 2://E
                                station.de.Add(double.Parse(row));
                                break;
                        }
                    }
                }
                smList.Add(station);
                smList.Reverse();
            }

            //while (num<cnt)
            //{
            //    string str = strList[num];
            //    if (str.Contains("HA"))
            //    {
            //        string[] snStr = str.Trim().Split(',');
            //        station = new StationModel();
            //        station.Name = snStr[1];
            //        newStation = true;
            //    }
            //    else
            //    {
            //        if (true)
            //        {

            //        }
            //    }

            //    num++;
            //}
            //Console.WriteLine(Path.GetFileNameWithoutExtension(fn)+":"+strs.Length);
            //for (int i = 0; i < datas.Length; i++)
            //{
            //    datas[i] = double.Parse(strs[channelIndex * 30001 + i + 1]);
            //}

        }
        public void MSeed2Asc(string filePath, string savePath)
        {
            using (Process compiler = new Process())
            {
                compiler.StartInfo.FileName = "mseed2ascii.exe";
                compiler.StartInfo.Arguments = filePath + " -o " + savePath;
                compiler.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                compiler.Start();
                compiler.WaitForExit();
            }
        }
        private void SelectEvent(object obj)
        {
            //List<MmEvent> events = remoteSQL.GetDateEvent(StartTime, EndTime);
            //if (events != null)
            //{
            //    ShowEvents = new ObservableCollection<MmEvent>();
            //    foreach (MmEvent e in events)
            //        ShowEvents.Add(e);
            //    SelectResult = ShowEvents.Count;
            //    //UpdateEventOfDayPlot(events);
            //    //UpdateEventOfML(events);
            //    //CreateEventOfGrade(events);
            //}
        }
        private void ApplicationClosingDispose(object sender, CancelEventArgs e)
        {
            if (IsRunning == true)
            {
                // The thread is currently running so signal it to stop. 
                // Dispose method will be called again after the thread stops.
                Stop();
            }
            else
            {
                if (LChartALL != null)
                {
                    LChartALL.Dispose();
                    LChartALL = null;
                }

            }
        }
        public void Dispose()
        {
            gridChart.Children.Clear();

            if (LChartALL != null)
            {
                LChartALL.Dispose();
                LChartALL = null;
            }
            //if (IsRunning == true)
            //{
            //    // The thread is currently running so signal it to stop. 
            //    // Dispose method will be called again after the thread stops.
            //    Stop();
            //}
        }
        public void SetWavesCombination()
        {
            switch (WavesCombination.Name)
            {
                case "平铺":
                    LChartCount = 1;
                    CreateGridChartPingPu();
                    break;
                case "叠加":
                    LChartCount = 1;
                    CreateGridChartDieJia();
                    break;
                case "分类":
                    LChartCount = 3;
                    CreateGridChartFenLei();
                    break;
            }
        }
        public void CreateGridChartPingPu()
        {
            if (LChartALL != null)
            {
                LChartALL = null;
            }

            LChartALL = new LightningChart();
            LChartALL.Title.Visible = false;
            //LChartALL.Title.Text = "事件波形";
            //LChartALL.Title.Color = Colors.Black;
            //LChartALL.Title.Shadow.DropColor = Colors.Transparent;
            //LChartALL.Title.Shadow.ContrastColor = Colors.Transparent;
            //LChartALL.Title.Font = new WpfFont("等线", 20);

            LChartALL.ViewXY.AxisLayout.YAxesLayout = YAxesLayout.Stacked;

            LChartALL.ViewXY.AxisLayout.SegmentsGap = 0;
            LChartALL.ViewXY.ZoomPanOptions.PanDirection = PanDirection.Horizontal;
            LChartALL.ViewXY.ZoomPanOptions.WheelZooming = WheelZooming.Horizontal;

            //背景颜色
            LChartALL.ViewXY.GraphBackground.Color = Colors.White;
            LChartALL.ViewXY.GraphBackground.GradientFill = GradientFill.Solid;
            LChartALL.ViewXY.GraphBackground.GradientColor = Colors.White;
            LChartALL.ChartBackground.GradientFill = GradientFill.Solid;
            LChartALL.ChartBackground.Color = Color.FromArgb(0, 0, 0, 0);

            GridChart = new Grid();
            GridChart.ColumnDefinitions.Add(new ColumnDefinition());
            GridChart.Name = "chartGrid";
            GridChart.Children.Add(LChartALL);

            this.ChildContent = GridChart;
        }
        public void CreateGridChartDieJia()
        {
            if (LChartALL != null)
            {
                LChartALL = null;
            }
            LChartALL = new LightningChart();
            LChartALL.Title.Text = "叠加";

            GridChart = new Grid();
            GridChart.ColumnDefinitions.Add(new ColumnDefinition());
            GridChart.Name = "chartGrid";
            GridChart.Children.Add(LChartALL);

            this.ChildContent = GridChart;
        }
        public void CreateGridChartFenLei()
        {
            LChartZ = new LightningChart();
            LChartALL.Title.Text = "Z";
            LChartZ.SetValue(Grid.ColumnProperty, 0);

            LChartE = new LightningChart();
            LChartALL.Title.Text = "E";
            LChartE.SetValue(Grid.ColumnProperty, 1);

            LChartN = new LightningChart();
            LChartALL.Title.Text = "N";
            LChartN.SetValue(Grid.ColumnProperty, 2);

            GridChart = new Grid();
            GridChart.ColumnDefinitions.Add(new ColumnDefinition());
            GridChart.ColumnDefinitions.Add(new ColumnDefinition());
            GridChart.ColumnDefinitions.Add(new ColumnDefinition());

            GridChart.Name = "chartGrid";
            GridChart.Children.Add(LChartZ);
            GridChart.Children.Add(LChartE);
            GridChart.Children.Add(LChartN);
            this.ChildContent = GridChart;
        }
        private void InitData()
        {
            LChartALL.ViewXY.YAxes = new AxisYCollection();
            LChartALL.ViewXY.YAxes.Clear();
            LChartALL.ViewXY.YAxes.AddRange(_wavesModel.CreateYAxisPingPu(GlobalConfig.ProjectConfig.StationDic, LChartALL));
            for (int i = 0; i < LChartALL.ViewXY.YAxes.Count; i++)
            {
                LChartALL.ViewXY.YAxes[i].LabelsColor = Colors.Black;
                LChartALL.ViewXY.YAxes[i].AxisColor = Colors.Black;
                LChartALL.ViewXY.YAxes[i].GridStripColor = Colors.Black;
                LChartALL.ViewXY.YAxes[i].Title.Color = Colors.Black;
                LChartALL.ViewXY.YAxes[i].Title.Shadow.DropColor = Colors.Transparent;
                LChartALL.ViewXY.YAxes[i].Title.Shadow.ContrastColor = Colors.Transparent;
                LChartALL.ViewXY.YAxes[i].Title.Font = new WpfFont("Calibri", 12);
            }
            LChartALL.ViewXY.XAxes = new AxisXCollection();
            LChartALL.ViewXY.XAxes.Add(_wavesModel.GetAxisX(CurPoints / Sampling));
            LChartALL.ViewXY.XAxes[0].LabelsColor = Colors.Black;

            LChartALL.ViewXY.SampleDataSeries = new SampleDataSeriesCollection();
            LChartALL.ViewXY.SampleDataSeries.AddRange(
                _wavesModel.GetSampleDataSeriesPingPu(GlobalConfig.ProjectConfig.StationDic, LChartALL, LChartALL.ViewXY.XAxes[0],
                LChartALL.ViewXY.YAxes, _samplingFrequency));
            //string mseedPath = FileDataPath + "\\" + StartTime.Year.ToString("D2");
            //Console.WriteLine(mseedPath);
            //Start();
        }
        private void FeedNewDataToChartPingPu(double[][] data)
        {
            LChartALL.BeginUpdate();

            for (int channelIndex = 0; channelIndex < _channelCount; channelIndex++)
            {
                LChartALL.ViewXY.SampleDataSeries[channelIndex].AddSamples(data[channelIndex], true);
                //LChartALL.ViewXY.YAxes[channelIndex].Minimum = data[channelIndex].Min();
                //LChartALL.ViewXY.YAxes[channelIndex].Maximum = data[channelIndex].Max();
            }

            _previousX = (double)_samplesOutput / _samplingFrequency;

            LChartALL.ViewXY.XAxes[0].ScrollPosition = _previousX;
            LChartALL.EndUpdate();

        }
        private void ButtonStartStopMethod(object obj)
        {
            //if (_thread == null)
            //{
            //    //Start 
            //    BtnContrlContent = "Stop";
            //    //isEnableSampFreq = false;
            //    //isEnableChannelCount = false;
            //    //bool bWaveformScrollStabilizing = CheckBoxWaveformScrollStabilizing == true;

            //    _previousX = 0;

            //    //Read channel count
            //    try
            //    {
            //        //_channelCount = int.Parse((Application.Current.MainWindow as View).ChannelCount.Text.ToString());
            //    }
            //    catch
            //    {
            //        Dialog.Show("Invalid channel count text input");
            //        return;
            //    }

            //    //Read sampling frequency
            //    try
            //    {
            //        //_samplingFrequency = double.Parse((Application.Current.MainWindow as View).SamplingFrequency.Text.ToString());
            //    }
            //    catch
            //    {
            //        Dialog.Show("Invalid sampling frequency text input");
            //        return;
            //    }

            //    //Read X axis length
            //    try
            //    {
            //        //_xLength = double.Parse((Application.Current.MainWindow as View).XLen.Text.ToString());
            //    }
            //    catch
            //    {
            //        Dialog.Show("Invalid X-Axis length text input");
            //        return;
            //    }

            //    int newPointsCount = _channelCount * (int)_samplingFrequency; //Amount of new generated points per second

            //    LChartALL.Title.Text = "Real-time data feeding from a thread, " + _channelCount.ToString() + " * " + _samplingFrequency.ToString("0")
            //        + " Hz = " + newPointsCount.ToString() + " new data points per sec";

            //    //LChartALL.ViewXY.YAxes.Clear();                 //Remove existing y-axes
            //    //LChartALL.ViewXY.SampleDataSeries.Clear();      //Remove existing SampleDataSeries

            //    ////Add Y axis and SampleDataSeries for each channel 

            //    //LChartALL.ViewXY.YAxes.AddRange(_wavesModel.CreateYAxisPingPu(PublicConfig.StationCount, LChartALL));
            //    //LChartALL.ViewXY.SampleDataSeries.AddRange(_wavesModel.GetSampleDataSeriesPingPu(PublicConfig.StationCount,
            //    //    LChartALL, LChartALL.ViewXY.XAxes[0]
            //    //    , LChartALL.ViewXY.YAxes, _samplingFrequency));


            //    //初始化数据读取
            //    _stationWorker = new StationWorkModel();
            //    //_stationWorker.Stations
            //    _stationWorker.files = Directory.GetFiles(@"D:\datatmp", "*.txt");
            //    _stationWorker.InitWork();

            //    //ScrollMode();

            //    LChartALL.ViewXY.XAxes[0].SetRange(0, _xLength);

            //    _samplesOutput = 0;
            //    _startTicks = DateTime.Now.Ticks;

            //    _stop = false;

            //    _threadWrite = new Thread(new ThreadStart(
            //        () =>
            //        {
            //            while (_stop == false)
            //            {
            //                if (_stationWorker.Stations[0].cz.Count < 500)
            //                {

            //                    _stationWorker.StartWriter();
            //                    // Get the elapsed time as a TimeSpan value.

            //                }
            //                //_stationWorker.StartWriter();
            //                Thread.Sleep(100);
            //            }

            //        }));
            //    _threadWrite.Start();

            //    //_fitYTimer = new DispatcherTimer(DispatcherPriority.Background);
            //    //_fitYTimer.Interval = TimeSpan.FromMilliseconds(500);
            //    //_fitYTimer.Tick += _fitYTimer_Tick;
            //    //_fitYTimer.Start();
            //    Thread.Sleep(500);
            //    //Thread.Sleep(5000);
            //    _thread = new Thread(new ThreadStart(ThreadLoop));
            //    _thread.Start();
            //}
            //else
            //{
            //    // Stop.
            //    BtnContrlContent = "Start";
            //    //isEnableSampFreq = true;
            //    //isEnableChannelCount = true;
            //    //_fitYTimer.Stop();
            //    _stop = true;
            //}
        }

        private void _fitYTimer_Tick(object sender, EventArgs e)
        {
            FitY(null);
        }

        public void Start()
        {
            if (IsRunning == false)
            {
                //ButtonStartStopMethod(null);
            }
        }
        public void Stop()
        {
            if (IsRunning == true)
            {
                //ButtonStartStopMethod(null);

            }
        }
        private void ThreadLoop()
        {
            while (_stop == false)
            {

                // Generate data for each channel. Use StopWatch to 
                // investigate how many samples must be generated.
                //Stopwatch stopWatch = new Stopwatch();
                //stopWatch.Start();
                //if (_stationWorker.Stations[0].cz.Count < 500)
                //{

                //    _stationWorker.StartWriter();
                //    // Get the elapsed time as a TimeSpan value.

                //}

                _now = DateTime.Now.Ticks; //Get current time stamp.

                long currentSampleIndex =
                    (long)(TimeSpan.FromTicks(_now - _startTicks).TotalSeconds * _samplingFrequency);

                int sampleBundleToGenerate = (int)(currentSampleIndex - _samplesOutput);
                //Console.WriteLine("currentSampleIndex:{0}\tsampleBundle:{1}", currentSampleIndex, sampleBundleToGenerate);
                _channelCount = _stationWorker.StationCnt;
                if (sampleBundleToGenerate > 0)
                {
                    //YMax = tmps.Max();
                    double[][] multiChannelData = new double[_channelCount][];

                    for (int channelIndex = 0; channelIndex < _channelCount; channelIndex++)
                    {
                        multiChannelData[channelIndex] = new double[sampleBundleToGenerate];
                        double[] tmps = _stationWorker.Reader(_stationWorker.Stations[channelIndex], sampleBundleToGenerate);
                        //if (tmps.Min()<30000)
                        //{
                        //    Console.WriteLine($"{_stationWorker.Stations[channelIndex].Name}\t{tmps.Min()}");
                        //}
                        //Console.WriteLine(tmps.Average());
                        //Generate random data
                        for (int sampleIndex = 0; sampleIndex < sampleBundleToGenerate; sampleIndex++)
                        {
                            multiChannelData[channelIndex][sampleIndex] = tmps[sampleIndex];
                        }
                    }

                    _samplesOutput += sampleBundleToGenerate;

                    // Invoke FeedNewDataToChart.
                    _dispatcher.Invoke(_chartUpdate, System.Windows.Threading.DispatcherPriority.ContextIdle,
                        multiChannelData as object);

                }

                // Sleep a little while so that UI stays responsive.
                Thread.Sleep(500);

                //stopWatch.Stop();//停止测量某个时间间隔的运行时间。
                //TimeSpan ts = stopWatch.Elapsed; //获取当前实例测量得出的总运行时间。
                //Console.WriteLine(ts.TotalMilliseconds);
            }

            _thread = null;
            #region "原程序"
            //while (_stop == false)
            //{
            //    // Generate data for each channel. Use StopWatch to 
            //    // investigate how many samples must be generated.

            //    _now = DateTime.Now.Ticks; //Get current time stamp.

            //    long currentSampleIndex =
            //        (long)(TimeSpan.FromTicks(_now - _startTicks).TotalSeconds * _samplingFrequency);

            //    int sampleBundleToGenerate = (int)(currentSampleIndex - _samplesOutput);
            //    Console.WriteLine("currentSampleIndex:{0}\tsampleBundle:{1}", currentSampleIndex, sampleBundleToGenerate);
            //    if (sampleBundleToGenerate > 0)
            //    {
            //        double yRange = YMax - YMin;

            //        double[][] multiChannelData = new double[_channelCount][];

            //        for (int channelIndex = 0; channelIndex < _channelCount; channelIndex++)
            //        {
            //            multiChannelData[channelIndex] = new double[sampleBundleToGenerate];

            //            //Generate random data
            //            for (int sampleIndex = 0; sampleIndex < sampleBundleToGenerate; sampleIndex++)
            //            {
            //                multiChannelData[channelIndex][sampleIndex] = YMin + _rand.NextDouble() * yRange;
            //            }
            //        }

            //        _samplesOutput += sampleBundleToGenerate;

            //        // Invoke FeedNewDataToChart.
            //        Application.Current.Dispatcher.Invoke(_chartUpdate, System.Windows.Threading.DispatcherPriority.ContextIdle, 
            //            multiChannelData as object);
            //    }

            //    // Sleep a little while so that UI stays responsive.
            //    Thread.Sleep(1);
            //}

            //_thread = null;
            #endregion
        }

        //private void FitY(object o)
        //{
        //    FitY();
        //}
        private void FitY(object o)
        {
            if (LChartALL != null)
            {
                //Disable rendering, strongly recommended before updating chart properties
                LChartALL.BeginUpdate();

                foreach (AxisY axisY in LChartALL.ViewXY.YAxes)
                {
                    //Console.WriteLine($"min:{axisY.Minimum}\tmax:{axisY.Maximum}");
                    if (axisY.Minimum < 30000)
                    {
                        axisY.Minimum = 30000;
                    }
                    if (axisY.Maximum < 35000)
                    {
                        axisY.Maximum = 35000;
                    }
                    bool changed = false;
                    axisY.Fit(0.0, out changed, true, false, 30000, 35000);
                }

                //Allow chart rendering
                LChartALL.EndUpdate();
            }
        }

        public void ConvertWaves(object o)
        {
            Stopwatch sw = new Stopwatch();
            string[] files = Directory.GetFiles(@"D:\BaiduNetdiskDownload\03\08\00", "*.mseed", SearchOption.AllDirectories);
            int taskNum = 0;
            bool isAllCompleted = false;
            int taskCnt = files.Length;
            Task[] tasks = new Task[taskCnt];
            sw.Start();

            foreach (var item in files)
            {
                tasks[taskNum] = Task.Factory.StartNew(() =>
                {
                    using (Process compiler = new Process())
                    {
                        string sn = Path.GetFileNameWithoutExtension(item);
                        compiler.StartInfo.FileName = "mseed2ascii.exe";
                        compiler.StartInfo.Arguments = item + " -o " + GlobalConfig.ProjectConfig.TxtFilePath + "\\" + sn + ".txt";
                        compiler.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        compiler.Start();
                        //compiler.WaitForExit();
                        //Console.WriteLine(taskNum);
                        //string fileName = Path.GetFileNameWithoutExtension(item.filePath);
                        //MoveFile(System.Environment.CurrentDirectory, fileName, "*" + item.txtTimeStr + "*.txt", movePath);
                        //this.Dispatcher.BeginInvoke(new Action(() => listBoxConverts.Items.Add(item.filePath)));
                    }
                });
                taskNum++;
            }
            var moniCom = Task.Factory.StartNew(() =>
            {
                while (!isAllCompleted)
                {
                    int comTask = 0;
                    foreach (var item in tasks)
                    {
                        //Console.WriteLine($"ID:{item.Id}\tCompleted:{item.Status.ToString()}");
                        if (item.IsCompleted)
                        {
                            comTask++;
                        }
                    }
                    if (comTask >= taskCnt)
                    {
                        isAllCompleted = true;
                        sw.Stop();
                        TimeSpan ts2 = sw.Elapsed;
                        // Console.WriteLine("总共花费{0}ms.", ts2.TotalMilliseconds);
                        //MessageBox.Show($"完成,共花费:{tsts2.TotalMilliseconds}ms!");
                    }
                    Thread.Sleep(1);
                }
            });

            // System.Diagnostics.Process.Start(@"D:\mseed2ascii.exe", @"d:\HA.N02-202203080000.mseed -o "+CachePath+"\\3.txt");
            ////var tc = Task.Factory.StartNew(() =>
            //{
            //    using (Process compiler = new Process())
            //    {
            //        //ProcessStartInfo info = new ProcessStartInfo("mseed2ascii.exe");
            //        //info.WindowStyle = ProcessWindowStyle.Hidden;
            //        //info.Arguments = "HA.20211023T044938.04.mseed";
            //        compiler.StartInfo.FileName = "mseed2ascii.exe";
            //        compiler.StartInfo.Arguments = "HA.N02-202203080000.mseed";
            //        //compiler.StartInfo.FileName = System.Environment.CurrentDirectory+"\\m2a\\mseed2ascii.exe";
            //        //compiler.StartInfo.Arguments = System.Environment.CurrentDirectory + "\\m2a\\HA.N02-202203080000.mseed";
            //        //compiler.StartInfo.UseShellExecute = false;
            //        // compiler.StartInfo.RedirectStandardOutput = true;
            //        compiler.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
            //        compiler.Start();

            //        //Console.WriteLine(compiler.StandardOutput.ReadToEnd());

            //        compiler.WaitForExit();
            //        Console.WriteLine();
            //        //Application.Current.Dispatcher.BeginInvoke(new Action(() => listBoxConverts.Items.Add("mseed2ascii.exe")));
            //    }
            //}

            //sw.Stop();
            //TimeSpan ts2 = sw.Elapsed;
            //Console.WriteLine("sw总共花费{0}ms.", ts2.TotalMilliseconds);
        }

        public void ReadTxtData(object o)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();

            ChannelModel cmZ = new ChannelModel();
            cmZ.Name = "Z";
            cmZ.ReadDataFromTxt(GlobalConfig.ProjectConfig.TxtFilePath + "\\HA.N02-202203080000.txt", 0);

            ChannelModel cmE = new ChannelModel();
            cmE.Name = "E";
            cmE.ReadDataFromTxt(GlobalConfig.ProjectConfig.TxtFilePath + "\\HA.N02-202203080000.txt", 1);

            ChannelModel cmN = new ChannelModel();
            cmN.Name = "N";
            cmN.ReadDataFromTxt(GlobalConfig.ProjectConfig.TxtFilePath + "\\HA.N02-202203080000.txt", 2);

            sw.Stop();
            TimeSpan ts2 = sw.Elapsed;
            //Dialog.Show("总共花费" + ts2.TotalMilliseconds + "ms.");
            // Console.WriteLine("总共花费{0}ms.", ts2.TotalMilliseconds);
        }


    }
    /// <summary>
    /// 波形组合
    /// </summary>
    public enum WavesCombinationEnum
    {
        平铺 = 0,
        叠加,
        分类
    }
    /// <summary>
    /// 波形类型
    /// </summary>
    public enum DataTypeEnum
    {
        原始数据 = 0,
        事件数据
    }
    /// <summary>
    /// 数据来源
    /// </summary>
    public enum DataSourcesEnum
    {
        文件 = 0,
        数据库
    }
    /// <summary>
    /// 显示模式
    /// </summary>
    public enum DisplayModeEnum
    {
        自动 = 0,
        手动
    }
    public enum ScollModeEnum
    {
        Scrolling = 0,
        Stepping
    }
}
