using Prism.Events;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Txgy.EWS.Client.Common;
using Txgy.EWS.Client.Common.MessageEvents;
using Txgy.EWS.Client.FocalMechanism.Core;
using Txgy.EWS.Client.FocalMechanism.Model;
using Txgy.EWS.Client.PageModule.Models;
using Txgy.Microseismic.BaseLib.Models;
using Unity;
using static WW.Cad.Model.Entities.DxfHatch.BoundaryPath;
using WW.Cad.Model.Entities;
using WW.Cad.Model;
using Color = System.Windows.Media.Color;
using WW.Cad.IO;
using System.Diagnostics;
using Txgy.EWS.Client.Common.Helpers;
using Txgy.EWS.Client.Models;
using Txgy.EWS.Client.Entity;
using System.Threading.Tasks;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Txgy.EWS.Client.PageModule.Views
{
    /// <summary>
    /// EarlyWarningView.xaml 的交互逻辑
    /// </summary>
    public partial class EarlyWarningViewBak : UserControl
    {
        Dispatcher _dispatcher;
        private readonly IEventAggregator _ea;
        private VisualHost host;
        public TransformGroup transGroup;
        private delegate void HandleDataGeneratedDelegate(List<GridItemEventResult> results, double dw, double dh,int ts,DateTime inTime);
        /// <summary>
        /// Delegate for data generation.
        /// </summary>
        private HandleDataGeneratedDelegate _handleDataGenerated;

        int EventShowTotalSeconds = 86400;
        double width = 700;
        double height = 700;
        double canvasLeft = 80;
        double canvasTop = 50;
        double canvasRight = 50;
        double canvasBottom = 50;
        double canvasWidthRange = 2000;
        double canvasHeightRange = 2000;
        double gridTextSpacing = 500;
        public double unit = 100;

        public double fontSize = 12;
        public double stationSize = 20;
        public double stationFontSize = 10;
        double baseX = 39701000;
        double baseY = 4352000;
        double xDrawUnit = 1;
        double yDrawUnit = 1;
        double drawUnit = 1;
        Point _downPoint = new Point(0, 0);
        bool _isMoving = false;
        public bool IsShowGridText = true;
        public bool IsShowGrid = true;
        public System.Windows.Media.Color BackGroundColor = System.Windows.Media.Colors.White;
        public Brush GridLineBrush = Brushes.Gray;
        public double GridLineWidth = 0.2;

        public Brush BrushStrikeSlip = Brushes.Black;
        public Brush BrushDipSlip = Brushes.Blue;
        public Brush BrushTensile = Brushes.Red;
        public Brush BrushEvent = Brushes.Green;

        public double EventSize = 3;
        public ProcessCore pCore { get; set; }
        public Factory factory { get; set; }
        public FMMap fmMap { get; set; }
        public MmEvent curMmEvent { get; set; }
        public bool IsShowEvent = true;

        private double _scale = 1;
        public double Scale
        {
            get { return _scale; }
            set
            {
                _scale = value;
            }
        }
        public List<CadLayer> CadLayers { get; set; }
        ReportPlanImage rpi = new ReportPlanImage();
        public EarlyWarningViewBak(IUnityContainer unityContainer, IEventAggregator ea)
        {
            InitializeComponent();
            _ea = ea;
            _dispatcher = unityContainer.Resolve<Dispatcher>();
           
            //rpi.DrawPlanClipToDrawVisual(mes, (int)rView.canvasPlan.ActualWidth, (int)rView.canvasPlan.ActualHeight);
            rpi.Draw(null, canvas.Width, canvas.Height);
            //host = new VisualHost();
            host = rpi.host;
            canvas.Children.Add(host);

            baseX = GlobalConfig.ProjectConfig.WorkArea.EMin;
            baseY = GlobalConfig.ProjectConfig.WorkArea.NMin;

            canvasWidthRange = Math.Ceiling((GlobalConfig.ProjectConfig.WorkArea.EMax - GlobalConfig.ProjectConfig.WorkArea.EMin) / 100) * 100;
            canvasHeightRange = Math.Ceiling((GlobalConfig.ProjectConfig.WorkArea.NMax - GlobalConfig.ProjectConfig.WorkArea.NMin) / 100) * 100;

            gridTextSpacing = 500;

            width = canvas.Width;
            height = canvas.Height;

            xDrawUnit = (width - canvasLeft - canvasRight) / (double)canvasWidthRange;
            yDrawUnit = (height - canvasTop - canvasBottom) / (double)canvasHeightRange;

            drawUnit = xDrawUnit < yDrawUnit ? xDrawUnit : yDrawUnit;

            //if (xUnit < yUnit) drawUnit = yUnit;
            CadLayers = new List<CadLayer>();
            CreateBackgroudByDwg();

            this.SizeChanged += SystemMonitor_SizeChanged;
            transGroup = new TransformGroup();
            transGroup.Children.Add(new ScaleTransform(1.2, 1.2));
            transGroup.Children.Add(new TranslateTransform(-380, -150));
            canvas.RenderTransform = transGroup;
            //事件时限秒数
            EventShowTotalSeconds = BusinessConfigManager.Current.Runtime.EventShowTotalSeconds;
            this._ea.GetEvent<BusinessConfigChangedEvent>().Subscribe(config =>
            {
                EventShowTotalSeconds = config.Runtime.EventShowTotalSeconds;
                RedrawReceivedEvents();
            }, ThreadOption.UIThread);
            this._ea.GetEvent<ClearWarningDataEvent>().Subscribe(RedrawReceivedEvents, ThreadOption.UIThread);

            _handleDataGenerated = new HandleDataGeneratedDelegate(rpi.DrawGierInTime);

            //this._ea.GetEvent<UpdateReceivedEventMessage>().Subscribe(u =>
            //{
            //    _dispatcher.Invoke(_handleDataGenerated,GlobalData.ReceivedEvents,canvas.ActualWidth,canvas.ActualHeight, EventShowTotalSeconds,DateTime.Now);
            //});

            this._ea.GetEvent<StartRunMonitorMessage>().Subscribe(() =>
            {
                //_dispatcher.Invoke(_handleDataGenerated, GlobalData.ReceivedEvents, canvas.ActualWidth, canvas.ActualHeight, EventShowTotalSeconds, DateTime.Now);
            });



            Task.Delay(TimeSpan.FromSeconds(3)).ContinueWith(t =>
            {
                CreateStoryBoard();
            }, TaskScheduler.FromCurrentSynchronizationContext());
            //this._ea.GetEvent<UpdateEventsMessage>().Subscribe(u =>
            //{
            //    Draw();
            //});
            //Draw();

            //this._ea.GetEvent<UpdateEventsMessage>().Subscribe(u =>
            //{
            //    //_dispatcher.Invoke(_handleDataGenerated);
            //});
        }
        private void RedrawReceivedEvents()
        {
            if (_handleDataGenerated == null)
            {
                return;
            }

            _dispatcher.Invoke(_handleDataGenerated, GlobalData.ReceivedEvents, canvas.ActualWidth, canvas.ActualHeight, EventShowTotalSeconds, DateTime.Now);
        }
        public void CreateStoryBoard()
        {
            var myCircle = new Ellipse();
            myCircle.Width = 50;
            myCircle.Height = 50;
            myCircle.Fill = Brushes.Blue;
            myCircle.Stroke = new SolidColorBrush(System.Windows.Media.Colors.Red);
            myCircle.StrokeThickness = 2;
            TranslateTransform ttf = new TranslateTransform(100, 100);//定位到城市所在的点
            myCircle.RenderTransform = ttf;
            myCircle.ToolTip = string.Format("{0} {1}", 1, 2);
            myCircle.Opacity = 0;
            this.canvas.Children.Add(myCircle);
            var sb = new Storyboard();

            sb.Completed += OnStoryboardCompleted;
            this.canvas.RegisterName("ell", myCircle);
            DoubleAnimation ellda = new DoubleAnimation();
            ellda.From = 0.2;//此处值设置0-1会有不同的呈现效果
            ellda.To = 1;
            ellda.Duration = new Duration(TimeSpan.FromSeconds(2));
            ellda.BeginTime = TimeSpan.FromSeconds(0);//推迟动画开始时间 等轨迹连接到圆时 开始播放圆的呈现动画
            ellda.FillBehavior = FillBehavior.HoldEnd;
            Storyboard.SetTargetName(ellda, "ell");
            Storyboard.SetTargetProperty(ellda, new PropertyPath(Ellipse.OpacityProperty));
            sb.Children.Add(ellda);
            //圆呈放射状
            RadialGradientBrush rgBrush = new RadialGradientBrush();
            GradientStop gStop0 = new GradientStop(Color.FromArgb(255, 0, 0, 0), 0);
            //此为控制点 color的a值设为0 off值走0-1 透明部分向外放射 初始设为255是为了初始化效果 开始不呈放射状 等跑动的点运动到城市的圆后 color的a值才设为0开始呈现放射动画
            GradientStop gStopT = new GradientStop(Color.FromArgb(255, 0, 0, 0), 0);
            GradientStop gStop1 = new GradientStop(Color.FromArgb(255, 0, 0, 0), 1);
            rgBrush.GradientStops.Add(gStop0);
            rgBrush.GradientStops.Add(gStopT);
            rgBrush.GradientStops.Add(gStop1);
            myCircle.OpacityMask = rgBrush;
            this.canvas.RegisterName("e", gStopT);

            //跑动的点达到城市的圆时 控制点由不透明变为透明 color的a值设为0 动画时间为0
            ColorAnimation ca = new ColorAnimation();
            ca.To = Color.FromArgb(0, 0, 0, 0);
            ca.Duration = new Duration(TimeSpan.FromSeconds(0));
            ca.BeginTime = TimeSpan.FromSeconds(0);
            ca.FillBehavior = FillBehavior.HoldEnd;
            Storyboard.SetTargetName(ca, "e");
            Storyboard.SetTargetProperty(ca, new PropertyPath(GradientStop.ColorProperty));
            sb.Children.Add(ca);

            //点达到城市的圆时 呈现放射状动画 控制点的off值走0-1 透明部分向外放射
            DoubleAnimation eda = new DoubleAnimation();
            eda.To = 1;
            eda.Duration = new Duration(TimeSpan.FromSeconds(2));
            //eda.RepeatBehavior = RepeatBehavior.Forever;
            eda.RepeatBehavior = new RepeatBehavior(2);
            eda.BeginTime = TimeSpan.FromSeconds(0);

            Storyboard.SetTargetName(eda, "e");
            Storyboard.SetTargetProperty(eda, new PropertyPath(GradientStop.OffsetProperty));
            sb.Children.Add(eda);

            sb.Begin(canvas);
        }
        private void OnStoryboardCompleted(object sender, EventArgs e)
        {
            var ellipse = this.canvas.FindName("ell") as Ellipse;
            this.canvas.Children.Remove(ellipse);
        }
        public void HostDraw()
        {
            rpi.Draw(null, canvas.Width, canvas.Height);
        }

        public void Draw()
        {
            if (host.visuals.Count > 0)
            {
                host.RemoveVisual(host.visuals[0]);
            }

            DrawingVisual visual = new DrawingVisual();
            //Application.Current.Dispatcher.Invoke(() =>
            //{
            using (DrawingContext dc = visual.RenderOpen())
            {
                //绘制背景色
                Pen pen = new Pen(Brushes.White, 0);
                //pen.Freeze();
                dc.DrawRectangle(new SolidColorBrush(BackGroundColor), pen,
                    new Rect(canvasLeft, canvasTop, width - canvasLeft - canvasRight, height - canvasTop - canvasBottom));

                int xAxisCount = (int)Math.Ceiling(canvasHeightRange / unit);
                int yAxisCount = (int)Math.Ceiling(canvasWidthRange / unit);
                DrawGrid(dc, xAxisCount, yAxisCount, unit);
                DrawDwg(dc);
                if (IsShowEvent)
                {
                    if (GlobalData.AlarmEvents != null)
                    {
                        if (GlobalData.AlarmEvents.Count > 0)
                        {
                            foreach (var item in GlobalData.AlarmEvents)
                            {
                                //如果事件时间在24小时内显示
                                if ((DateTime.Now - DateTime.Parse(item.EventTime)).TotalSeconds <= EventShowTotalSeconds)
                                {
                                    float sizeFactor = (float)(((4f + item.ML) / (4f)) * 2f) + 0.1f;
                                    int colorIndex = (int)(((item.Z - GlobalConfig.ProjectConfig.WorkArea.ZMin)
                                    / Math.Abs(GlobalConfig.ProjectConfig.WorkArea.ZMax - GlobalConfig.ProjectConfig.WorkArea.ZMin))
                                    * GlobalConfig.ColorCountDefault);
                                    Color ec = GlobalConfig.eventDepthColor[colorIndex];
                                    BrushEvent = new SolidColorBrush(ec);
                                    Pen eventPen = new Pen(BrushEvent, 0);
                                    //eventPen.Freeze();
                                    dc.DrawEllipse(BrushEvent, eventPen,
                                        new Point(canvasLeft + (item.X - baseX) * drawUnit, canvasTop + (canvasHeightRange - (item.Y - baseY)) * drawUnit),
                                        EventSize * sizeFactor, EventSize * sizeFactor);
                                }

                            }
                        }
                    }
                }
            }
            host.AddVisual(visual);
            //});
        }

        public void CreateBackgroudByDwg()
        {
            string CadFilePath = GlobalConfig.ProjectConfig.CadFileName;
            DxfModel model = DwgReader.Read(CadFilePath);
            List<string> entityTpyeList = new List<string>();
            Typeface typeface = new Typeface(new FontFamily("Arial"),
                           FontStyles.Normal,
                           FontWeights.Normal,
                           FontStretches.Normal);
            //try
            {

                foreach (var clc in GlobalConfig.CadLayerConfigs)
                {
                    if (clc.isShow)
                    {
                        var ents = model.Entities.FindAll(et => et.Layer.Name == clc.name);
                        CadLayer cadLayer = new CadLayer(clc.name, clc.lineColor, clc.linewidth);
                        foreach (var ent in ents)
                        {
                            List<Point> points = new List<Point>();
                            //if (!entityTpyeList.Contains(ent.EntityType))
                            //{
                            //    entityTpyeList.Add(ent.EntityType);
                            //    Console.WriteLine(ent.EntityType);
                            //}
                            switch (ent.EntityType)
                            {
                                case "POLYLINE":
                                    foreach (var point in ((DxfPolyline3D)ent).Vertices)
                                    {
                                        if (point.X >= GlobalConfig.ProjectConfig.WorkArea.EMin &&
                                            point.X <= GlobalConfig.ProjectConfig.WorkArea.EMax &&
                                            point.Y >= GlobalConfig.ProjectConfig.WorkArea.NMin &&
                                            point.Y <= GlobalConfig.ProjectConfig.WorkArea.EMax)
                                        {
                                            double x = canvasLeft + (point.X - baseX) * drawUnit;
                                            double y = canvasTop + (canvasHeightRange - (point.Y - baseY)) * drawUnit;
                                            points.Add(new Point(x, y));
                                        }
                                    }
                                    if (points.Count > 0)
                                    {
                                        //bool isFile = clc.name.Contains("台站") ? true : false;
                                        //cadLayer.GeometryCollection.Add(CreateCadGeometry(points, clc.lineClose, clc.isFill));
                                    }
                                    break;
                                case "LWPOLYLINE":
                                    foreach (var point in ((DxfLwPolyline)ent).Vertices)
                                    {
                                        if (point.X >= GlobalConfig.ProjectConfig.WorkArea.EMin &&
                                            point.X <= GlobalConfig.ProjectConfig.WorkArea.EMax &&
                                            point.Y >= GlobalConfig.ProjectConfig.WorkArea.NMin &&
                                            point.Y <= GlobalConfig.ProjectConfig.WorkArea.EMax)
                                        {
                                            double x = canvasLeft + (point.X - baseX) * drawUnit;
                                            double y = canvasTop + (canvasHeightRange - (point.Y - baseY)) * drawUnit;
                                            points.Add(new Point(x, y));
                                        }
                                    }
                                    if (points.Count > 0)
                                    {
                                        //cadLayer.GeometryCollection.Add(CreateCadGeometry(points, clc.lineClose, clc.isFill));
                                    }
                                    break;
                                case "MTEXT":
                                    DxfMText met = (DxfMText)ent;
                                    if (met.Text.Contains("16") && clc.name.Contains("台站"))
                                    {
                                        //Console.WriteLine(1);
                                    }
                                    if (met.InsertionPoint.X >= GlobalConfig.ProjectConfig.WorkArea.EMin &&
                                                                met.InsertionPoint.X <= GlobalConfig.ProjectConfig.WorkArea.EMax &&
                                                                met.InsertionPoint.Y >= GlobalConfig.ProjectConfig.WorkArea.NMin &&
                                                                met.InsertionPoint.Y <= GlobalConfig.ProjectConfig.WorkArea.EMax)
                                    {
                                        string text = met.Text;
                                        FormattedText formattedText = new FormattedText(text,
                                            new System.Globalization.CultureInfo("zh-CN"),
                                            FlowDirection.RightToLeft,
                                            typeface,
                                            clc.fontSize, new SolidColorBrush(clc.lineColor), 1
                                            );
                                        formattedText.TextAlignment = TextAlignment.Right;
                                        double x = canvasLeft + (met.InsertionPoint.X - baseX) * drawUnit;
                                        double y = canvasTop + (canvasHeightRange - (met.InsertionPoint.Y - baseY)) * drawUnit;
                                        Point origin = new Point(x, y);
                                        cadLayer.TextCollection.Add(new CadText(formattedText, origin));
                                    }

                                    break;
                                case "TEXT":
                                    DxfText et = (DxfText)ent;
                                    if (et.Text.Contains("16") && clc.name.Contains("台站"))
                                    {
                                        //Console.WriteLine(1);
                                    }
                                    if (et.AlignmentPoint1.X >= GlobalConfig.ProjectConfig.WorkArea.EMin &&
                                                                et.AlignmentPoint1.X <= GlobalConfig.ProjectConfig.WorkArea.EMax &&
                                                                et.AlignmentPoint1.Y >= GlobalConfig.ProjectConfig.WorkArea.NMin &&
                                                                et.AlignmentPoint1.Y <= GlobalConfig.ProjectConfig.WorkArea.EMax)
                                    {
                                        string text = et.Text;
                                        FormattedText formattedText = new FormattedText(text,
                                            new System.Globalization.CultureInfo("zh-CN"),
                                            FlowDirection.RightToLeft,
                                            typeface,
                                            clc.fontSize, new SolidColorBrush(clc.lineColor), 1
                                            );
                                        formattedText.TextAlignment = TextAlignment.Right;
                                        double x = canvasLeft + (et.AlignmentPoint1.X - baseX) * drawUnit;
                                        double y = canvasTop + (canvasHeightRange - (et.AlignmentPoint1.Y - baseY)) * drawUnit;
                                        Point origin = new Point(x, y);
                                        cadLayer.TextCollection.Add(new CadText(formattedText, origin));
                                    }
                                    break;
                                case "CIRCLE":
                                    DxfCircle dxfCircle = (DxfCircle)ent;
                                    //Console.WriteLine(1);
                                    break;
                                case "HATCH":
                                    DxfHatch dxfHatch = (DxfHatch)ent;
                                    foreach (var point in dxfHatch.BoundaryPaths[0].Edges)
                                    {
                                        LineEdge lineEdge = (LineEdge)point;
                                        //if (lineEdge.st. >= GlobalConfig.ProjectConfig.WorkArea.EMin &&
                                        //    point.X <= GlobalConfig.ProjectConfig.WorkArea.EMax &&
                                        //    point.Y >= GlobalConfig.ProjectConfig.WorkArea.NMin &&
                                        //    point.Y <= GlobalConfig.ProjectConfig.WorkArea.EMax)
                                        {
                                            double x = canvasLeft + (lineEdge.Start.X - baseX) * drawUnit;
                                            double y = canvasTop + (canvasHeightRange - (lineEdge.Start.Y - baseY)) * drawUnit;
                                            points.Add(new Point(x, y));
                                            x = canvasLeft + (lineEdge.End.X - baseX) * drawUnit;
                                            y = canvasTop + (canvasHeightRange - (lineEdge.End.Y - baseY)) * drawUnit;
                                            points.Add(new Point(x, y));
                                        }
                                    }
                                    if (points.Count > 0)
                                    {
                                        //cadLayer.GeometryCollection.Add(CreateCadGeometry(points, clc.lineClose, clc.isFill));
                                    }
                                    break;
                            }
                        }
                        CadLayers.Add(cadLayer);
                    }
                }
            }
            //catch (Exception ex)
            //{
            //    Console.WriteLine(ex.Message);
            //}
        }
        public PathGeometry CreateCadGeometry(List<Point> points, bool isClose, bool isFill)
        {
            PolyLineSegment lineSegment = new PolyLineSegment();

            foreach (var item in points)
            {
                lineSegment.Points.Add(item);
            }
            PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();
            myPathSegmentCollection.Add(lineSegment);

            PathFigure pathFigure = new PathFigure();
            pathFigure.IsClosed = isClose;
            pathFigure.IsFilled = isFill;
            pathFigure.StartPoint = points[0];
            pathFigure.Segments = myPathSegmentCollection;

            PathFigureCollection pthFigureCollection = new PathFigureCollection();
            pthFigureCollection.Add(pathFigure);

            PathGeometry pthGeometry = new PathGeometry();
            pthGeometry.Figures = pthFigureCollection;
            return pthGeometry;
        }
        private void DrawDwg(DrawingContext dc)
        {
            if (CadLayers != null)
            {
                foreach (var layer in CadLayers)
                {
                    Pen layerPen = new Pen(new SolidColorBrush(layer.Color), layer.LineWidth);
                    layerPen.Freeze();
                    foreach (var geo in layer.GeometryCollection)
                    {
                        //dc.DrawGeometry(new SolidColorBrush(layer.Color), layerPen, geo.DrawGeometry);
                    }
                    foreach (var text in layer.TextCollection)
                    {
                        dc.DrawText(text.formattedText, text.drawPoint);
                    }
                    foreach (var line in layer.LineCollection)
                    {
                        dc.DrawLine(layerPen, line.drawPoint0, line.drawPoint1);
                    }
                }
            }
        }
        private void Canvas_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            width = this.mainView.ActualWidth + e.Delta;
            height = this.mainView.ActualHeight + e.Delta;
            if (height < 400) height = 400;
            if (width < 400) width = 400;

            this.mainView.Width = width;
            this.mainView.Height = height;
            //xDrawUnit = (width - canvasLeft - canvasRight) / (double)canvasWidthRange;
            //yDrawUnit = (height - canvasTop - canvasBottom) / (double)canvasHeightRange;
            //drawUnit = xDrawUnit < yDrawUnit ? xDrawUnit : yDrawUnit;

            //this.mainView.SetValue(Canvas.LeftProperty, (this.RenderSize.Width - this.mainView.Width) / 2);
            Control ctl = sender as Control;
            System.Windows.Point point = e.GetPosition(ctl);
            //滚轮滚动时控制 放大的倍数,没有固定的值，可以根据需要修改。
            double scale = e.Delta * 0.001;

            ZoomImage(transGroup, point, scale);

            e.Handled = true;
        }
        //对控件进行缩放。
        private void ZoomImage(TransformGroup group, Point point, double scale)
        {
            Point pointToContent = group.Inverse.Transform(point);

            ScaleTransform scaleT = group.Children[0] as ScaleTransform;

            if (scaleT.ScaleX + scale < 1) return;

            scaleT.ScaleX += scale;

            scaleT.ScaleY += scale;

            TranslateTransform translateT = group.Children[1] as TranslateTransform;

            translateT.X = -1 * ((pointToContent.X * scaleT.ScaleX) - point.X);

            translateT.Y = -1 * ((pointToContent.Y * scaleT.ScaleY) - point.Y);

        }

        /// <summary>
        /// 绘制张性
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="center"></param>
        /// <param name="angle"></param>
        private void DrawTensile(DrawingContext dc, Point center, double angle, Brush brush)
        {
            Point drawCenter = new Point(center.X + canvasLeft, center.Y + canvasTop);
            RotateTransform _rotateTrans = new RotateTransform();
            _rotateTrans.Angle = angle;
            _rotateTrans.CenterX = drawCenter.X;
            _rotateTrans.CenterY = drawCenter.Y;
            double LRadis = 10;
            double WRadis = 5;
            EllipseGeometry ellipseGeometry = new EllipseGeometry(new Point(drawCenter.X, canvasTop + center.Y), LRadis, WRadis);
            LineGeometry line = new LineGeometry(new Point(drawCenter.X - LRadis, drawCenter.Y), new Point(drawCenter.X + LRadis, drawCenter.Y));

            ellipseGeometry.Transform = _rotateTrans;
            line.Transform = _rotateTrans;
            Pen pen = new Pen(brush, 1.5);
            pen.Freeze();
            dc.DrawGeometry(Brushes.Transparent, pen, ellipseGeometry);
            dc.DrawGeometry(Brushes.Transparent, pen, line);

        }
        /// <summary>
        /// 绘制倾滑
        /// </summary>
        private void DrawDipSlip(DrawingContext dc, Point center, double angle, Brush brush)
        {
            Point drawCenter = new Point(center.X + canvasLeft, center.Y + canvasTop);
            RotateTransform _rotateTrans = new RotateTransform();
            _rotateTrans.Angle = angle;
            _rotateTrans.CenterX = drawCenter.X;
            _rotateTrans.CenterY = drawCenter.Y;
            double len = 10;

            Point p1 = new Point(drawCenter.X - len, drawCenter.Y);
            Point p2 = new Point(drawCenter.X - len, drawCenter.Y - 4);
            Point p3 = new Point(drawCenter.X + len, drawCenter.Y - 4);
            Point p4 = new Point(drawCenter.X + len, drawCenter.Y);
            Point p5 = new Point(drawCenter.X + 2, drawCenter.Y);
            Point p6 = new Point(drawCenter.X + 2, drawCenter.Y + len);
            Point p7 = new Point(drawCenter.X - 4, drawCenter.Y + 4.5);
            Point p8 = new Point(drawCenter.X - 2, drawCenter.Y + 4.5);
            Point p9 = new Point(drawCenter.X - 2, drawCenter.Y);
            PolyLineSegment lineSegment = new PolyLineSegment();
            lineSegment.Points.Add(p1);
            lineSegment.Points.Add(p2);
            lineSegment.Points.Add(p3);
            lineSegment.Points.Add(p4);
            lineSegment.Points.Add(p5);
            lineSegment.Points.Add(p6);
            lineSegment.Points.Add(p7);
            lineSegment.Points.Add(p8);
            lineSegment.Points.Add(p9);
            PathFigure pathFigure = new PathFigure();
            pathFigure.IsClosed = true;
            pathFigure.IsFilled = true;
            pathFigure.StartPoint = p1;

            PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();
            myPathSegmentCollection.Add(lineSegment);
            pathFigure.Segments = myPathSegmentCollection;
            PathFigureCollection pthFigureCollection = new PathFigureCollection();

            pthFigureCollection.Add(pathFigure);

            PathGeometry pthGeometry = new PathGeometry();
            pthGeometry.Figures = pthFigureCollection;
            pthGeometry.Transform = _rotateTrans;
            Pen pen = new Pen(Brushes.White, 0);
            pen.Freeze();
            dc.DrawGeometry(brush, pen, pthGeometry);
            //PolyLineSegment polyLineSegment= new PolyLineSegment() 
        }
        /// <summary>
        /// 绘制走滑
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="center"></param>
        /// <param name="angle"></param>
        /// <param name="brush"></param>
        private void DrawStrikeSlip(DrawingContext dc, Point center, double angle, Brush brush)
        {
            Point drawCenter = new Point(center.X + canvasLeft, center.Y + canvasTop);
            RotateTransform _rotateTrans = new RotateTransform();
            _rotateTrans.Angle = angle;
            _rotateTrans.CenterX = canvasLeft + center.X;
            _rotateTrans.CenterY = canvasTop + center.Y;

            //上箭头
            Point p1 = new Point(drawCenter.X - 9, drawCenter.Y - 2);
            Point p2 = new Point(drawCenter.X - 9, drawCenter.Y - 5);
            Point p3 = new Point(drawCenter.X + 3, drawCenter.Y - 5);
            Point p4 = new Point(drawCenter.X + 3, drawCenter.Y - 9);
            Point p5 = new Point(drawCenter.X + 9, drawCenter.Y - 2);
            PolyLineSegment lineSegment = new PolyLineSegment();
            lineSegment.Points.Add(p1);
            lineSegment.Points.Add(p2);
            lineSegment.Points.Add(p3);
            lineSegment.Points.Add(p4);
            lineSegment.Points.Add(p5);
            PathFigure pathFigure = new PathFigure();
            pathFigure.IsClosed = true;
            pathFigure.IsFilled = true;
            pathFigure.StartPoint = p1;


            PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();
            myPathSegmentCollection.Add(lineSegment);
            pathFigure.Segments = myPathSegmentCollection;

            PathFigureCollection pthFigureCollection = new PathFigureCollection();
            pthFigureCollection.Add(pathFigure);

            PathGeometry pthGeometry = new PathGeometry();
            pthGeometry.Figures = pthFigureCollection;
            pthGeometry.Transform = _rotateTrans;
            Pen pen = new Pen(Brushes.White, 0);
            pen.Freeze();
            dc.DrawGeometry(brush, pen, pthGeometry);


            //下箭头
            Point xp1 = new Point(drawCenter.X - 9, drawCenter.Y + 2);
            Point xp2 = new Point(drawCenter.X + 9, drawCenter.Y + 2);
            Point xp3 = new Point(drawCenter.X + 9, drawCenter.Y + 5);
            Point xp4 = new Point(drawCenter.X - 3, drawCenter.Y + 5);
            Point xp5 = new Point(drawCenter.X - 3, drawCenter.Y + 9);
            PolyLineSegment lineSegment2 = new PolyLineSegment();
            lineSegment2.Points.Add(xp1);
            lineSegment2.Points.Add(xp2);
            lineSegment2.Points.Add(xp3);
            lineSegment2.Points.Add(xp4);
            lineSegment2.Points.Add(xp5);
            PathFigure pathFigure2 = new PathFigure();
            pathFigure2.IsClosed = true;
            pathFigure2.IsFilled = true;
            pathFigure2.StartPoint = xp1;

            PathSegmentCollection myPathSegmentCollection2 = new PathSegmentCollection();
            pathFigure2.Segments = myPathSegmentCollection2;
            myPathSegmentCollection2.Add(lineSegment2);

            PathFigureCollection pthFigureCollection2 = new PathFigureCollection();
            pthFigureCollection2.Add(pathFigure2);

            PathGeometry pthGeometry2 = new PathGeometry();
            pthGeometry2.Figures = pthFigureCollection2;
            pthGeometry2.Transform = _rotateTrans;

            dc.DrawGeometry(brush, pen, pthGeometry2);


        }
        /// <summary>
        /// 绘制台站
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="center"></param>
        /// <param name="text"></param>
        /// <param name="size"></param>
        /// <param name="brush"></param>
        /// <exception cref="InvalidOperationException"></exception>
        private void DrawStation(DrawingContext dc, Point center, string text, double size, Brush brush)
        {
            Point drawCenter = new Point(center.X + canvasLeft, center.Y + canvasTop);
            Rect rect = new Rect(drawCenter.X - size / 2.0, drawCenter.Y - size / 2.0, size, size);
            Pen stationPen = new Pen(brush, 1);
            stationPen.Freeze();
            dc.DrawRectangle(Brushes.Transparent, stationPen, rect);
            FormattedText formattedText = new FormattedText(text,
                new System.Globalization.CultureInfo("zh-CN"),
                FlowDirection.LeftToRight,
                new Typeface("Arail"),
                stationFontSize, brush, 1
                );
            dc.DrawText(formattedText, new Point(drawCenter.X - size / 2.0 + 1, drawCenter.Y - size / 2.0 + 5));
        }
        /// <summary>
        /// 绘制网格
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="xLines"></param>
        /// <param name="yLines"></param>
        /// <param name="unit"></param>
        /// <param name="pen"></param>
        /// <exception cref="InvalidOperationException"></exception>
        private void DrawGrid(DrawingContext dc, int xLines, int yLines, double unit)
        {
            Point drawPoint = new Point(canvasLeft, canvasTop);
            int xWidth = (int)(drawUnit * canvasWidthRange);
            int ylength = (int)(drawUnit * canvasHeightRange);
            //int canLen=
            if (IsShowGrid)
            {
                System.Windows.Media.Pen normalPen = new System.Windows.Media.Pen(GridLineBrush, GridLineWidth);
                Pen drawPen = normalPen;
                Pen stressPen = new Pen(GridLineBrush, 0.5);
                //绘制X轴
                for (int i = 0; i < xLines + 1; i++)
                {
                    if ((i % (gridTextSpacing / unit)) == 0)
                    {
                        drawPen = stressPen;
                    }
                    else
                    {
                        drawPen = normalPen;
                    }
                    drawPen.Freeze();
                    dc.DrawLine(drawPen, new Point(drawPoint.X + 0, drawPoint.Y + i * drawUnit * unit),
                        new Point(drawPoint.X + xWidth, drawPoint.Y + i * drawUnit * unit));
                }
                //绘制Y轴
                for (int i = 0; i < yLines + 1; i++)
                {
                    if ((i % (gridTextSpacing / unit)) == 0)
                    {
                        drawPen = stressPen;
                    }
                    else
                    {
                        drawPen = normalPen;
                    }
                    dc.DrawLine(drawPen, new Point(drawPoint.X + i * drawUnit * unit, drawPoint.Y + 0),
                       new Point(drawPoint.X + i * drawUnit * unit, drawPoint.Y + ylength));
                }
            }
            //绘制网格文字
            if (IsShowGridText)
            {
                string txtTmp = (baseX + unit).ToString("F0");
                Typeface typeface = new Typeface(new FontFamily("Arial"),
                           FontStyles.Normal,
                           FontWeights.Normal,
                           FontStretches.Normal);
                GlyphTypeface glyphTypeface;
                if (!typeface.TryGetGlyphTypeface(out glyphTypeface))
                    throw new InvalidOperationException("No glyphtypeface found");

                ushort[] glyphIndexes = new ushort[txtTmp.Length];
                double[] advanceWidths = new double[txtTmp.Length];
                double totalWidth = 0;
                for (int n = 0; n < txtTmp.Length; n++)
                {
                    ushort glyphIndex = glyphTypeface.CharacterToGlyphMap[txtTmp[n]];
                    glyphIndexes[n] = glyphIndex;
                    double twidth = glyphTypeface.AdvanceWidths[glyphIndex] * fontSize;
                    advanceWidths[n] = twidth;
                    totalWidth += twidth;
                }

                for (int i = 0; i < xLines + 1; i++)
                {
                    if (((i * unit) % gridTextSpacing) == 0)
                    {
                        string text = (baseY + i * unit).ToString("F0");
                        FormattedText formattedText = new FormattedText(text,
                            new System.Globalization.CultureInfo("zh-CN"),
                            FlowDirection.RightToLeft,
                            typeface,
                            fontSize, Brushes.Black, 1
                            );
                        dc.DrawText(formattedText, new Point(drawPoint.X - 10, drawPoint.Y + (xLines - i) * drawUnit * unit - 6));
                    } //dc.DrawLine(pen, new Point(drawPoint.X + 0, drawPoint.Y + i * drawUnit * unit), new Point(drawPoint.X + xWidth, drawPoint.Y + i * drawUnit * unit));
                }

                for (int i = 0; i < yLines + 1; i++)
                {
                    if (((i * unit) % gridTextSpacing) == 0)
                    {
                        string text = (baseX + i * unit).ToString("F0");
                        FormattedText formattedText = new FormattedText(text,
                            new System.Globalization.CultureInfo("zh-CN"),
                            FlowDirection.RightToLeft,
                            typeface,
                            fontSize, Brushes.Black, 1
                            );
                        dc.DrawText(formattedText, new Point(drawPoint.X + i * drawUnit * unit + totalWidth / 2.0, height - canvasBottom + 5));
                    }//dc.DrawLine(pen, new Point(drawPoint.X + i * drawUnit * unit, height - canvasBottom + 10), new Point(drawPoint.X + i * drawUnit * unit, height - canvasBottom + 10));
                }
            }
        }
        private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _downPoint = e.GetPosition(sender as Canvas);
            this.previousMousePoint = _downPoint;
            //left = double.Parse(this.mainView.GetValue(Canvas.LeftProperty).ToString());
            //top = double.Parse(this.mainView.GetValue(Canvas.TopProperty).ToString());
            _isMoving = true;
            (sender as Canvas).CaptureMouse();
            e.Handled = true;
        }
        private void Canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _isMoving = false;
            (sender as Canvas).ReleaseMouseCapture();
            //
            e.Handled = true;
        }
        private void Canvas_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isMoving)
            {
                Point currentPoint = e.GetPosition(sender as Canvas);
                //this.mainView.SetValue(Canvas.LeftProperty, left + (currentPoint.X - _downPoint.X));
                //this.mainView.SetValue(Canvas.TopProperty, top + (currentPoint.Y - _downPoint.Y));
                //Canvas image = sender as Canvas;
                TranslateTransform tt = transGroup.Children[1] as TranslateTransform;
                this.DoImageMove(tt, currentPoint);
                e.Handled = true;
            }
        }
        Point previousMousePoint;
        private void DoImageMove(TranslateTransform transform, Point position)
        {
            //trgroup = group.Children[1] as TransformGroup;

            //Debug.Assert(group != null, "Can't find transform group from image compare panel resource");

            //TranslateTransform transform = group.Children[1] as TranslateTransform;

            transform.X += position.X - this.previousMousePoint.X;

            transform.Y += position.Y - this.previousMousePoint.Y;

            this.previousMousePoint = position;

        }
        private void SystemMonitor_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            this.mainView.SetValue(Canvas.LeftProperty, (this.RenderSize.Width - this.mainView.ActualWidth) / 2);
            width = canvas.Width;
            height = canvas.Height;
            //xDrawUnit = (width - canvasLeft - canvasRight) / (double)canvasWidthRange;
            //yDrawUnit = (height - canvasTop - canvasBottom) / (double)canvasHeightRange;
            //drawUnit = xDrawUnit < yDrawUnit ? xDrawUnit : yDrawUnit;
        }
        #region bak_20230228
        //private IEventAggregator _ea;
        //Dispatcher _dispatcher;
        //// Delegates
        //private delegate void HandleDataGeneratedDelegate();
        ///// <summary>
        ///// Delegate for data generation.
        ///// </summary>
        //private HandleDataGeneratedDelegate _handleDataGenerated;
        //public SizeDoubleXYZ EventSize;
        //public EarlyWarningView(IUnityContainer unityContainer, IEventAggregator ea)
        //{
        //    InitializeComponent();
        //    _ea = ea;
        //    _dispatcher = unityContainer.Resolve<Dispatcher>();
        //    _handleDataGenerated = new HandleDataGeneratedDelegate(PutSamplesToChart);
        //    EventSize = new SizeDoubleXYZ(GlobalConfig.eventDSize * 10, GlobalConfig.eventDSize * 10, GlobalConfig.eventDSize * 10);
        //    this._ea.GetEvent<UpdateEventsMessage>().Subscribe(u =>
        //    {
        //        _dispatcher.Invoke(_handleDataGenerated);
        //    });
        //}

        //private void PutSamplesToChart()
        //{
        //    //(Application.Current. as EarlyWarningView).chart.Add(item);
        //    //Type type = Type.GetType("Txgy.EWS.Client.PageModule.Views.EarlyWarningView");
        //    //LightningChart lChart = (Activator.CreateInstance(type) as EarlyWarningView).chart;

        //    this.chart.BeginUpdate();

        //    List<SeriesPoint3D> sp3List = new List<SeriesPoint3D>();
        //    foreach (var ms in GlobalData.AlarmEvents)
        //    {
        //        {
        //            float sizeFactor = (float)(((4f + ms.ML) / (4f)) * 6f) + 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), 20, (ms.Y) , ec, sizeFactor));

        //        }
        //    }

        //    PointLineSeries3D plsEvent3d = new PointLineSeries3D();
        //    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;
        //    plsEvent3d.AddPoints(sp3List.ToArray(), false);
        //    //ChartPointLineCollection.Add(plsEvent3d);
        //    //Console.WriteLine(ChartPointLineCollection.Count);
        //    this.chart.View3D.PointLineSeries3D.Add(plsEvent3d);
        //    this.chart.EndUpdate();

        //}
        //IFreeSql fsqlTencent = FreeSqlTencent.tencentRemoteMySQL;
        //int tmp = 0;
        //DateTime timeTemp = new DateTime(2023, 2, 1, 0, 0, 0);
        //private void Button_Click(object sender, RoutedEventArgs e)
        //{
        //    DateTime dateTime = timeTemp.AddHours(tmp);
        //    Stopwatch watch = new Stopwatch();
        //    watch.Start();

        //    //MmEventEntity mmEvent= searchMsEventBLL.GetLastEvent();
        //    var mme = fsqlTencent.Select<RemoteRealtimeResultEntity>()
        //    .Where(re => DateTime.Parse(re.EventTime).Ticks <= dateTime.Ticks)
        //    .OrderByDescending(re => re.RTEventID).First();

        //    watch.Stop();
        //    TimeSpan timespan = watch.Elapsed;

        //    Console.WriteLine("FreeSql:" + mme.RTEventID + " ++++++++++++++++时长：" + timespan.TotalMilliseconds);

        //    GlobalData.AlarmEvents.Add(mme);
        //    //AlarmEventPayload aep = new AlarmEventPayload(mme);
        //    //Application.Current.Dispatcher.Invoke(_handleDataGenerated, aep);
        //    tmp++;
        //}
        #endregion
    }
}
