using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
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.Shapes;

namespace WpfApp1.CharttoImage
{
    /// <summary>
    /// ChartToImageSample.xaml 的交互逻辑
    /// </summary>
    public partial class ChartToImageSample2 : Window
    {
        ScanGraphVm scanGraphVm;
        Viewbox viewbox;
        ScanGraph scanGraph;
        public ChartToImageSample2()
        {
            InitializeComponent();
            scanGraphVm = new ScanGraphVm();
            
            viewbox = new Viewbox();
            scanGraph = new ScanGraph
            {
                Width = 1024,
                Height = 300
            };
            scanGraph.DataContext = scanGraphVm;
            viewbox.Child = scanGraph;

            viewbox.Measure(scanGraph.RenderSize);
            viewbox.Arrange(new System.Windows.Rect(new System.Windows.Point(0, 0), scanGraph.RenderSize));
            scanGraph.chart.Update(true, true);//强制使 livechart 刷新
            viewbox.UpdateLayout();
        }



        private void btnOutput2Click(object sender, RoutedEventArgs e)
        {
            string strDesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.InitialDirectory = strDesktopPath;
            sfd.Filter = "jpg|*.jpg";
            sfd.FileName = System.IO.Path.ChangeExtension(System.IO.Path.GetRandomFileName(), ".jpg");
            if (sfd.ShowDialog() == true)
            {
                SavePic2(sfd.FileName);
            }
        }

        async void SavePic(string path)
        {

            //一定要把 scangraph 放入容器， 且scangraph  Left,Top 对齐，margin=0
            //不然有黑框
            //整个scangraph 的尺寸是 Margin+(Width,Height)
            //Margin 是透明，也就是黑色
            var viewbox = new Viewbox();

            ScanGraph scanGraph = new ScanGraph
            {
                Width = 1024,
                Height = 300,
                //HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
                //VerticalAlignment = System.Windows.VerticalAlignment.Top,
                //Margin = new System.Windows.Thickness()
            };
            scanGraph.DataContext = scanGraphVm;
            scanGraph.chart.AxisX[0].SetBinding(LiveCharts.Wpf.Axis.MinValueProperty, new Binding(nameof(scanGraphVm.XMin)) { Source = scanGraphVm });
            scanGraph.chart.AxisX[0].SetBinding(LiveCharts.Wpf.Axis.MaxValueProperty, new Binding(nameof(scanGraphVm.XMax)) { Source = scanGraphVm });
            scanGraph.chart.AxisY[0].SetBinding(LiveCharts.Wpf.Axis.MinValueProperty, new Binding(nameof(scanGraphVm.YMin)) { Source = scanGraphVm });
            scanGraph.chart.AxisY[0].SetBinding(LiveCharts.Wpf.Axis.MaxValueProperty, new Binding(nameof(scanGraphVm.YMax)) { Source = scanGraphVm });
            (scanGraph.chart.Series[0] as LiveCharts.Wpf.LineSeries)
                .SetBinding(LiveCharts.Wpf.LineSeries.ValuesProperty, new Binding(nameof(scanGraphVm.Values)) { Source = scanGraphVm });


            viewbox.Child = scanGraph;

            viewbox.Measure(scanGraph.RenderSize);
            viewbox.Arrange(new System.Windows.Rect(new System.Windows.Point(0, 0), scanGraph.RenderSize));

            scanGraph.chart.Update(true,true);//强制使 livechart 刷新

            viewbox.UpdateLayout();
            //scanGraph.chart.Update(true, true);//强制使 livechart 刷新
            
            //等会再导出
            //await Task.Delay(2000);
            //scanGraph.chart.Update(true, true);//强制使 livechart 刷新

            SaveToJpeg(scanGraph, path);
        }

        async void SavePic2(string path)
        {
            scanGraph.chart.Update(true, true);//强制使 livechart 刷新
            SaveToJpeg(scanGraph, path);
        }
        void SaveToJpeg(FrameworkElement visual, string fileName)
        {
            var encoder = new JpegBitmapEncoder();
            EncodeVisual(visual, fileName, encoder);
        }

        void EncodeVisual(FrameworkElement visual, string fileName, BitmapEncoder encoder)
        {
            var bitmap = new RenderTargetBitmap((int)visual.ActualWidth, (int)visual.ActualHeight, 96, 96, PixelFormats.Pbgra32);
            bitmap.Render(visual);
            var frame = BitmapFrame.Create(bitmap);

            encoder.Frames.Add(frame);
            using (var stream = File.Create(fileName)) encoder.Save(stream);
        }
    }
}
