using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Txgy.EWS.Client.Common.Helpers;
using Txgy.EWS.Client.Common;
using Txgy.EWS.Client.Models;
using System.IO;
using Txgy.EWS.Client.Entity;
using Txgy.EWS.Client.PageModule.Services;
using Txgy.Microseismic.BaseLib.Models;
using Txgy.EWS.Client.PageModule.Common;
using OxyPlot.Axes;
using OxyPlot.Legends;
using OxyPlot.Series;
using OxyPlot;
using Prism.Ioc;

namespace Txgy.EWS.Client.PageModule.Views
{
    /// <summary>
    /// ReportDayListView.xaml 的交互逻辑
    /// </summary>
    public partial class ReportDayListView : UserControl
    {
        IFreeSql fsqlTencent = FreeSqlTencent.tencentRemoteMySQL;
        ReportFreqImage reportImage = new ReportFreqImage();
        CultureInfo culture = new CultureInfo("zh-CN");
        public string dayFreqImagePath;
        public int dayFreqImageWidth = 1485;
        public int dayFreqImageHeight = 585;
        public double MiddleEnergy = 1000;
        public DateTime ReportStartTime;
        public DateTime ReportEndTime;
        public double ReportMinML;
        public double ReportMaxML;
        public int SearchCount;
        public List<GridItemEventResult> SearchEvents;
        IContainerProvider _conprovider;
        public ReportDayListView(IContainerProvider containerProvider)
        {
            _conprovider = containerProvider;
            InitializeComponent();
            InitializePara();
        }
        public void InitializePara()
        {
            int yy = DateTime.Now.Year;
            int mm = DateTime.Now.Month;
            int ss = DateTime.Now.Day;
            ReportStartTime = new DateTime(yy, mm, ss).AddDays(-1);
            ReportMinML = -3.0;
            ReportMaxML = 0;
            dpSearchDate.SelectedDate = ReportStartTime;
            dpSearchDate.DisplayDate = ReportStartTime;
            nudMaxML.Value = ReportMaxML;
            nudMinML.Value = ReportMinML;
            tbMiddleEnergy.Text=MiddleEnergy.ToString();
        }
        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            //_conprovider.Resolve<StereogramView>().chart.SaveToFile("e:\\7.png", (int)gridChart.ActualWidth, (int)gridChart.ActualHeight);
            //rsi.SaveToFile("e:\\7.png", (int)gridChart.ActualWidth, (int)gridChart.ActualHeight);
        }
        ReportStereogramImage rsi = new ReportStereogramImage();
        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            ReportStartTime = (DateTime)dpSearchDate.SelectedDate;
            ReportMaxML=nudMaxML.Value;
            ReportMinML=nudMinML.Value;
            MiddleEnergy=double.Parse(tbMiddleEnergy.Text);
            SearchEvents = SearchDayList();
            if (SearchEvents!=null)
            {
                if (SearchEvents.Count>0)
                {
                    btnExport.IsEnabled = true;
                    tbEventsCount.Text = SearchEvents.Count.ToString();
                    oxyplotDayFreq.Model = CreateDayFreqImage(SearchEvents, ReportStartTime, ReportStartTime.ToString("D", culture));

                    canvasPlan.Children.Clear();
                    ReportPlanImage rpi = new ReportPlanImage();
                    rpi.Draw(SearchEvents,canvasPlan.ActualWidth,canvasPlan.ActualHeight);
                    canvasPlan.Children.Add(rpi.host);

                    rsi=new ReportStereogramImage();
                    rsi.DrawStereoImage(SearchEvents);
                    gridChart.Children.Clear();
                    this.gridChart.Children.Add(rsi.lightChart);
                    //SaveImageToFile(this.gridChart, "e:\\p02.png");
                    

                }
            }
        }
        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 List<GridItemEventResult> SearchDayList()
        {
            List<RemoteRealtimeResultEntity> list = new List<RemoteRealtimeResultEntity>();
            DateTime reportSearchStartDate = new DateTime(ReportStartTime.Year, ReportStartTime.Month, ReportStartTime.Day, 0, 0, 0);
            list = fsqlTencent.Select<RemoteRealtimeResultEntity>()
                    .Where(pp => DateTime.Parse(pp.EventTime).Ticks >= reportSearchStartDate.Ticks &&
                        DateTime.Parse(pp.EventTime).Ticks < reportSearchStartDate.AddHours(24).Ticks && pp.ML >= ReportMinML && pp.ML <= ReportMaxML).ToList();
            if (list != null)
            {
                List<GridItemEventResult> results = new List<GridItemEventResult>();

                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)
                        {
                            EventFunc.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)
                            {
                                EventFunc.ComputeFM(curMmEvent);
                                //目前提取的为半周期
                                curMmEvent.DominantFreq = GlobalData.GetDominFreq(eventTimeStr);
                            }
                        }
                        #endregion
                    }
                    se.DominantFreq = (int)curMmEvent.DominantFreq;
                    se.SourceChara = (int)curMmEvent.FocalType;
                    se.Direction = curMmEvent.Direction;
                    se.SetEnergy();
                    results.Add(se);
                }
                return results;
            }
            return null;
        }
        public void SaveImageToFile(Grid grid,string fileName)
        {
            System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
            RenderTargetBitmap bmp = new RenderTargetBitmap((int)grid.ActualWidth, (int)grid.ActualHeight, 96d, 96d, PixelFormats.Pbgra32);
            bmp.Render(grid);
            BitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bmp));
            encoder.Save(fs);
            fs.Close();
        }
    }
}
