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;
using Txgy.Controls;

namespace Txgy.EWS.Client.PageModule.Views
{
    /// <summary>
    /// EarlyWarningView.xaml 的交互逻辑
    /// </summary>
    public partial class EarlyWarningView : 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;
        public List<EventAinimationElement> eventAinimationElements = new List<EventAinimationElement>();
        double eaiRadis = 10;
        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 EarlyWarningView(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, 1));
            transGroup.Children.Add(new TranslateTransform(-380, 0));
            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 =>
            {
                RedrawReceivedEvents();
            });
            //开始监控
            //this._ea.GetEvent<StartRunMonitorMessage>().Subscribe(() =>
            //{
            //    _dispatcher.Invoke(_handleDataGenerated, GlobalData.ReceivedEvents, canvas.ActualWidth, canvas.ActualHeight, EventShowTotalSeconds, DateTime.Now);
            //});

            //触发事件闪动动画
            this._ea.GetEvent<SelectAlarmEventMessage>().Subscribe(aem =>
            {
                ClickEventInListStoryBoard(aem, 3);
            });
            //GridItemEventResult gier = new GridItemEventResult();
            //gier.EventID = 53459;
            //gier.EventTime = "2023-04-23T00:14:16.037";
            //gier.X = 38398017;
            //gier.Y = 4030418;
            //gier.Z = 709.6;
            //gier.ML = -1.66;
            //gier.Energy = 1500;

            //Task.Delay(TimeSpan.FromSeconds(3)).ContinueWith(t =>
            //{
            //    CreateStoryBoard(gier, 5);
            //}, 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 ClickEventInListStoryBoard(GridItemEventResult gier, int Repeat)
        {
            EventAinimationItem eai = rpi.ConvertGierToEai(gier);
            EventAinimationElement eae = new EventAinimationElement();
            eae.EllName = "ell" + gier.EventID.ToString();
            eae.GStopName = "gstop" + gier.EventID.ToString();

            var haveElement = this.canvas.FindName(eae.EllName);
            if (haveElement == null)
            {
                if (eventAinimationElements.Count > 20)
                {
                    eventAinimationElements.RemoveAt(0);
                }
                eventAinimationElements.Add(eae);
                var myCircle = new Ellipse();
                myCircle.Name = eae.EllName;
                myCircle.Width = eaiRadis * 2;
                myCircle.Height = eaiRadis * 2;
                myCircle.Fill = Brushes.Blue;
                myCircle.Stroke = new SolidColorBrush(System.Windows.Media.Colors.Red);
                myCircle.StrokeThickness = 2;
                TranslateTransform ttf = new TranslateTransform(eai.OffsetX - eaiRadis, eai.OffsetY - eaiRadis);//事件位置
                myCircle.RenderTransform = ttf;
                //myCircle.ToolTip = string.Format("发震时刻：{0}\n东：{1}，北：{2}，深度：{3}\n震级：{4}ml，能量：{5}J",
                //    gier.EventTime, Math.Round(gier.X, 2), Math.Round(gier.Y, 2), Math.Round(gier.Z, 2), Math.Round(gier.ML, 2), gier.Energy);
                myCircle.Opacity = 0;
                this.canvas.Children.Add(myCircle);
                var sb = new Storyboard();
                sb.Name = eae.EllName;
                sb.Completed += ((s, e) =>
                {
                    var ellipse = this.canvas.FindName(eae.EllName) as Ellipse;
                    this.canvas.Children.Remove(ellipse);
                    this.canvas.UnregisterName(eae.EllName);
                    this.canvas.UnregisterName(eae.GStopName);
                });
                //sb.Completed += OnStoryboardCompleted;

                this.canvas.RegisterName(eae.EllName, 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, eae.EllName);
                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(eae.GStopName, 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, eae.GStopName);
                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(Repeat);
                eda.BeginTime = TimeSpan.FromSeconds(0);

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

                sb.Begin(canvas);
            }
        }
        public void ClickEventInPlanStoryBoard(GridItemEventResult gier, int Repeat)
        {
            EventAinimationItem eai = rpi.ConvertGierToEai(gier);
            EventAinimationElement eae = new EventAinimationElement();
            eae.EllName = "ell" + gier.EventID.ToString();
            eae.GStopName = "gstop" + gier.EventID.ToString();

            var haveElement = this.canvas.FindName(eae.EllName);
            if (haveElement == null)
            {
                if (eventAinimationElements.Count > 20)
                {
                    eventAinimationElements.RemoveAt(0);
                }
                eventAinimationElements.Add(eae);
                var myCircle = new Ellipse();
                myCircle.Name = eae.EllName;
                //大小
                myCircle.Width = eaiRadis * 1.2;
                myCircle.Height = eaiRadis * 1.2;
                myCircle.Fill = Brushes.Blue;
                myCircle.Stroke = new SolidColorBrush(System.Windows.Media.Colors.Red);
                myCircle.StrokeThickness = 2;
                //事件位置
                TranslateTransform ttf = new TranslateTransform(eai.OffsetX - eaiRadis*0.6, eai.OffsetY - eaiRadis*0.6);
                myCircle.RenderTransform = ttf;
                //myCircle.ToolTip = string.Format("发震时刻：{0}\n东：{1}，北：{2}，深度：{3}\n震级：{4}ml，能量：{5}J",
                //    gier.EventTime, Math.Round(gier.X, 2), Math.Round(gier.Y, 2), Math.Round(gier.Z, 2), Math.Round(gier.ML, 2), gier.Energy);
                myCircle.Opacity = 0;
                this.canvas.Children.Add(myCircle);
                var sb = new Storyboard();
                sb.Name = eae.EllName;
                sb.Completed += ((s, e) =>
                {
                    var ellipse = this.canvas.FindName(eae.EllName) as Ellipse;
                    this.canvas.Children.Remove(ellipse);
                    this.canvas.UnregisterName(eae.EllName);
                    this.canvas.UnregisterName(eae.GStopName);
                });
                //sb.Completed += OnStoryboardCompleted;

                this.canvas.RegisterName(eae.EllName, 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, eae.EllName);
                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(eae.GStopName, 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, eae.GStopName);
                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(Repeat);
                eda.BeginTime = TimeSpan.FromSeconds(0);

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

                sb.Begin(canvas);
            }

        }
        private void OnStoryboardCompleted(object sender, EventArgs e)
        {
            //var sb = sender as Storyboard;
            //this.canvas.FindName
            var ellipse = this.canvas.FindName("ell") as Ellipse;
            //this.canvas.UnregisterName("ell");
            //this.canvas.UnregisterName("e");
            this.canvas.Children.Remove(ellipse);
        }
        private void RemoveAinimationElement(EventAinimationElement eae)
        {
            var ellipse = this.canvas.FindName(eae.EllName) as Ellipse;
            this.canvas.UnregisterName(eae.EllName);
            this.canvas.UnregisterName(eae.GStopName);
            this.canvas.Children.Remove(ellipse);
        }

        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);
                                    //}

                                    //不显示工区号，如N1103
                                    //if (met.Text.Contains("N"))
                                    //{
                                    //    break;
                                    //}
                                    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("N") && clc.name.Contains("台站"))
                                    //{
                                    //不显示工区号，如N1103   
                                    //}
                                    //if (et.Text.Contains("N"))
                                    //{
                                    //    break;
                                    //}
                                    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));
                }
            }
        }

        bool isSelectEvent = false;
        private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            tip.IsOpen = false;
            if (!isSelectEvent)
            {
                isSelectEvent = true;
            }
            e.Handled = true;
        }

        private void Canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (isSelectEvent)
            {
                // 获取鼠标点击的位置
                Point point = e.GetPosition(canvas);
                //Debug.WriteLine(point.ToString());
                // 使用GetVisual方法获取点击的DrawingVisual
                DrawingVisual visual = rpi.host.GetVisual(point);

                if (visual != null)
                {                    
                    GridItemEventResult gier = (GridItemEventResult)TaggedVisual.GetTag(visual);
                    ClickEventInPlanStoryBoard(gier, 1);
                    tip.Placement = System.Windows.Controls.Primitives.PlacementMode.MousePoint;

                    tip.Content = string.Format("发震时刻：{0}\n东：{1}，北：{2}，海拔：{3}m\n震级：{4}ml，能量：{5}J",
                    gier.EventTime, Math.Round(gier.X, 2), Math.Round(gier.Y, 2), Math.Round(gier.Z, 2), Math.Round(gier.ML, 2), gier.Energy);
                    // logic for Show/Hide:
                    tip.Visibility = isSelectEvent ? Visibility.Visible : Visibility.Collapsed;

                    // Be open constantly while mouse-moving:
                    tip.IsOpen = true;

                }
                else
                {
                    isSelectEvent = false;
                    tip.Visibility = isSelectEvent ? Visibility.Visible : Visibility.Collapsed;
                    tip.IsOpen = isSelectEvent;
                }
            }
            // 防止事件进一步冒泡
            e.Handled = true;
        }
        private void Canvas_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isMoving)
            {
                Point currentPoint = e.GetPosition(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)
        {
            transform.X += position.X - this.previousMousePoint.X;
            transform.Y += position.Y - this.previousMousePoint.Y;
            this.previousMousePoint = position;
        }
        private void myListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //if (ReceivedEventListBox.SelectedItem == null && _lastSelectedItem != null)
            //{
            //    // Restore the last selected item if nothing is selected
            //    _lastSelectedItem.IsSelected = true;
            //}
            //else
            //{
            //    // Update the last selected item
            //    _lastSelectedItem = ReceivedEventListBox.SelectedItem as ListBoxItem;
            //}
        }

        private void right_MouseRightButtonDown(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 right_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            _isMoving = false;
            (sender as Canvas).ReleaseMouseCapture();
            //
            e.Handled = true;
        }

        private void right_MouseLeave(object sender, MouseEventArgs e)
        {
            if (isSelectEvent)
            {
                tip.Visibility = Visibility.Collapsed;
                isSelectEvent = false;
                e.Handled = true;
            }
        }

        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;
        }

    }
    public struct EventAinimationElement
    {
        public string EllName { get; set; }
        public string GStopName { get; set; }

    }
}
