using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Drawing.Drawing2D;
using SIASUN.Autopilot.View.Helper;
using SIASUN.Autopilot.BLL;
using ProjectBase.Data.BaseDAL;
using SIASUN.Autopilot.Model;
using ProjectBase.Data.Logs;
using DevExpress.Utils;
using System.Data.Common;
using SIASUN.Autopilot.GNSS;
using ProjectBase.Util;

namespace SIASUN.Autopilot.View
{
    public partial class FormRoutePlan : DevExpress.XtraEditors.XtraForm
    {
        #region 私有变量
        /// <summary>
        /// 画线类型
        /// </summary>
        private DrawType type = DrawType.None;       //画线类型
        /// <summary>
        /// ///操作模式
        /// </summary>
        private Mode mode = Mode.None;  //操作模式
        /// <summary>
        /// /在界面上画图的图元
        /// </summary>
        private DShapeList drawingList = new DShapeList();         //在界面上画图的图元
        /// <summary>
        /// /保存标准坐标的图元
        /// </summary>
        private DShapeList standardList = new DShapeList();        //保存标准坐标的图元
        /// <summary>
        /// Undo保存
        /// </summary>
        private DShapeList drawingListUndo = new DShapeList();    //Undo保存
        /// <summary>
        /// Undo保存
        /// </summary>
        private DShapeList standardListUndo = new DShapeList();    //Undo保存
        /// <summary>
        /// 下拉框选择路径的所有点
        /// </summary>
        private List<MoLocationRuleInfo> locationList = new List<MoLocationRuleInfo>();  //下拉框选择路径
        /// <summary>
        /// 自定义路径的所有点 
        /// </summary>
        private BindingList<MoLocationRuleInfo> drawLocationList = new BindingList<MoLocationRuleInfo>();   //自定义路径的所有点 
        /// <summary>
        /// 屏幕点
        /// </summary>
        private List<PointF> pointScreen = new List<PointF>();   //屏幕点
        /// <summary>
        /// 标准坐标
        /// </summary>
        private List<PointF> pointStandard = new List<PointF>();   //标准坐标
        /// <summary>
        /// 线的宽度
        /// </summary>
        private const int lineWidth = 3;    //线的宽度

        /// <summary>
        /// 鼠标位置
        /// </summary>
        private Point mousePoint = new Point();   //鼠标位置

        ///// <summary>
        ///// 图片宽度
        ///// </summary>
        //private int ImageWidth;
        ///// <summary>
        ///// 图片高度
        ///// </summary>
        //private int ImageHeight;
        /// <summary>
        /// 坐标与经纬度转换对象
        /// </summary>
        private CoordinateConversion conversion;

        /// <summary>
        /// 行驶过程中的经纬度
        /// </summary>
        private List<PointF> pointDriving = new List<PointF>();

        /// <summary>
        /// 行驶过程中航向角度
        /// </summary>
        private List<float> angleDriving = new List<float>();

        /// <summary>
        /// 行驶过程中速度
        /// </summary>
        private List<float> speedDriving = new List<float>();

        ///// <summary>
        ///// 画线类型
        ///// </summary>
        private enum DrawType
        {
            Bezier,
            None
        }

        /// <summary>
        /// 操作模式
        /// </summary>
        private enum Mode
        {
            Drive,
            Draw,
            None
        }
        #endregion

        public FormRoutePlan()
        {
            InitializeComponent();
        }

        private void FormRouteManagement_Load(object sender, EventArgs e)
        {
            InitControls();

            //ImageWidth = global::SIASUN.Autopilot.View.Properties.Resources.地图1.Width;
            //ImageHeight = global::SIASUN.Autopilot.View.Properties.Resources.地图1.Height;
            MoLocationMap map = BLLFactory<BlLocationMap>.Instance.FindSingle(string.Format("map_id = '{0}'", System.Configuration.ConfigurationManager.AppSettings["MapId"]));
            WGS84Points point0 = new WGS84Points { x = map.LocationLon1, y = map.LocationLat1, z = 0 };
            WGS84Points point1 = new WGS84Points { x = map.LocationLon2, y = map.LocationLat2, z = 0 };
            PointF imagePoint0 = new PointF { X = map.LocationX1, Y = map.LocationY1 };
            PointF imagePoint1 = new PointF { X = map.LocationX2, Y = map.LocationY2 };
            conversion = new CoordinateConversion(imagePoint0, imagePoint1, point0, point1);
            //BlGNSSPerception.Instance.Init();
            BlGNSSPerception.Instance.GNSSHandler += GetDrivingInfo;
        }

        /// <summary>
        /// 初始化控件
        /// </summary>
        private void InitControls()
        {
            //地图控件
            this.picExControl1.SetImage(global::SIASUN.Autopilot.View.Properties.Resources.地图1, true);
            this.picExControl1.DrawOriginalPathEvent += new PicExControl.DrawPath(DrawOriginalPath);
            this.picExControl1.DrawDrivingPathEvent += new PicExControl.DrawPath(DrawDrivingPath);
            this.picExControl1.MouseMoveTooltipEvent += new SIASUN.Autopilot.View.PicExControl.MouseMoveTooltip(picExControl1_MouseMove);

            this.btn_SavePath.Enabled = false;
            //this.layoutControl_DrawLine.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            this.layoutControl_DrawBezier.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            this.layoutControl_Udo.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            this.layoutControl_Rdo.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            this.layoutControl_Cancel.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            this.layoutControl_Ok.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            this.layoutControl_Name.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            this.layoutControl_Stop.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            this.label_PathName.Text = null;

            //下拉框
            this.lookUp_Path.Properties.DataSource = BLLFactory<BlLocationRuleInfo>.Instance.SqlTable("SELECT rule_name FROM location_rule_info GROUP BY rule_name");
            this.lookUp_Path.Properties.ValueMember = "RULE_NAME";
            this.lookUp_Path.Properties.DisplayMember = "RULE_NAME";
            this.lookUp_Path.Properties.NullText = null;
        }

        /// <summary>
        /// 自定义路径按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_DrawPath_Click(object sender, EventArgs e)
        {
            this.btn_DrivePath.Enabled = false;
            this.btn_SavePath.Enabled = true;
            //this.layoutControl_DrawLine.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            this.layoutControl_DrawBezier.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            this.layoutControl_Udo.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            this.layoutControl_Rdo.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            this.layoutControl_Cancel.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            this.layoutControl_Ok.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            this.layoutControl_Name.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            this.lookUp_Path.Enabled = false;
            this.lookUp_Path.EditValue = null;
            this.label_PathName.Text = null;
            mode = Mode.Draw;
        }

        /// <summary>
        /// 保存路径按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SavePath_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txt_PathName.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请输入路径名称。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (drawLocationList.Count == 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请至少绘制一条路径。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            bool bOK = true;
            DbTransaction trans = null;
            try
            {
                trans = BLLFactory<BlLocationRuleInfo>.Instance.CreateTransaction();
                foreach (MoLocationRuleInfo item in drawLocationList)
                {
                    if (bOK)
                    {
                        item.RuleName = this.txt_PathName.Text.Trim();
                        bOK = BLLFactory<BlLocationRuleInfo>.Instance.Insert(item,trans);
                    }
                }
                bOK = SaveDirective(bOK,drawLocationList,trans);
                if (!bOK)
                {
                    trans.Rollback();
                    DevExpress.XtraEditors.XtraMessageBox.Show("保存路径失败。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    trans.Commit();
                    DevExpress.XtraEditors.XtraMessageBox.Show("保存路径成功。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //this.btn_DrawPath.Enabled = true;
                    //this.btn_SavePath.Enabled = false;
                    //this.btn_DrivePath.Enabled = true;
                    ////this.layoutControl_DrawLine.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    //this.layoutControl_DrawBezier.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    //this.layoutControl_Udo.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    //this.layoutControl_Rdo.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    //this.layoutControl_Cancel.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    //this.layoutControl_Ok.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    //this.layoutControl_Name.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    this.lookUp_Path.Properties.DataSource = BLLFactory<BlLocationRuleInfo>.Instance.SqlTable("SELECT rule_name FROM location_rule_info GROUP BY rule_name");
                    //this.txt_PathName.Text = null;
                    //this.lookUp_Path.Enabled = true;
                    btn_Cancel_Click_1( sender, e);
                    //mode = Mode.None;
                    //type = DrawType.None;
                    //drawingList.Clear();
                    //standardList.Clear();
                    //drawingListUndo.Clear();
                    //standardListUndo.Clear();
                    //drawLocationList.Clear();
                    this.picExControl1.Invalidate();
                }

            }
            catch (Exception ex)
            {
                trans.Rollback();
                DevExpress.XtraEditors.XtraMessageBox.Show("保存路径失败。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LogHelper.log.Error(string.Format("插入数据库location_rule_info出现错误：{0}", ex));
            }
            finally
            {
                trans.Dispose();
            }

        }

        /// <summary>
        /// 保存动作指令集
        /// </summary>
        /// <param name="bOk"></param>
        /// <param name="trans"></param>
        /// <returns></returns>
        private bool SaveDirective(bool bOk , BindingList<MoLocationRuleInfo> list, DbTransaction trans)
        {
            if (!bOk)
            {
                return false;
            }
            MoActionDirective mo = new MoActionDirective();
            mo.RuleName = list[0].RuleName;
            for (int i = 1; i < list.Count; i++)
            {
                if (bOk)
                {
                    mo.DirectiveId = i;
                    if (i == 1)
                    {
                        mo.DirectiveInfo = string.Format("动作{0}:起步请加速到{1}KPH", i, list[i].LocationSpeed);
                    }
                    else
                    {
                        if (list[i].LocationSpeed > list[i-1].LocationSpeed)
                        {
                            mo.DirectiveInfo = string.Format("动作{0}:点{1}加速到{2}KPH", i,i, list[i].LocationSpeed);
                        }
                        else if (list[i].LocationSpeed < list[i - 1].LocationSpeed)
                        {
                            mo.DirectiveInfo = string.Format("动作{0}:点{1}制动至{2}KPH", i, i, list[i].LocationSpeed);
                        }
                        else if (list[i].LocationSpeed == list[i - 1].LocationSpeed)
                        {
                            mo.DirectiveInfo = string.Format("动作{0}:点{1}保持{2}KPH", i, i, list[i].LocationSpeed);
                        }
                    }
                    mo.DirectiveResult = 2;
                    bOk = BLLFactory<BlActionDirective>.Instance.Insert(mo, trans);
                }
            }
            return bOk;
        }

        /// <summary>
        /// 画直线按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void btn_DrawLine_Click(object sender, EventArgs e)
        //{
        //    this.btn_DrawBezier.Enabled = false;
        //    this.btn_Udo.Enabled = false;
        //    this.btn_Rdo.Enabled = false;
        //    this.layoutControl_Draw.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
        //    this.picExControl1.AllawDraw = true;
        //    this.label_Message.Text = "请在地图上单击鼠标左键选择两个点";
        //}

        /// <summary>
        /// 画曲线按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_DrawBezier_Click(object sender, EventArgs e)
        {
            //this.btn_DrawLine.Enabled = false;
            if (type == DrawType.Bezier)
            {
                return;
            }
            this.btn_Udo.Enabled = false;
            this.btn_Rdo.Enabled = false;
            this.layoutControl_Draw.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            this.picExControl1.AllawDraw = true;
            this.label_Message.Text = "请在地图上单击鼠标左键选择点";
            type = DrawType.Bezier;
        }

        /// <summary>
        /// 第二行取消按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            //this.btn_DrawLine.Enabled = true;
            this.btn_Udo.Enabled = true;
            this.btn_Rdo.Enabled = true;
            this.btn_DrawBezier.Enabled = true;
            this.layoutControl_Draw.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            this.label_Message.Text = null;
            type = DrawType.None;
            this.picExControl1.AllawDraw = false;
            pointScreen.Clear();
            pointStandard.Clear();
            this.picExControl1.Invalidate();
        }

        /// <summary>
        /// 驾驶车画路径按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_DrivePath_Click(object sender, EventArgs e)
        {
            this.btn_DrawPath.Enabled = false;
            this.btn_SavePath.Enabled = false;
            this.lookUp_Path.Enabled = false;
            this.lookUp_Path.EditValue = null;
            this.label_PathName.Text = null;
            this.btn_SavePath.Enabled = true;
            this.layoutControl_Name.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            this.layoutControl_Stop.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            mode = Mode.Drive;

            BlGNSSPerception.Instance.Init();
        }

        /// <summary>
        /// 第一行取消按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Cancel_Click_1(object sender, EventArgs e)
        {
            if (mode == Mode.Draw)    //自定义路径模式
            {
                this.btn_DrivePath.Enabled = true;
                //this.btn_SavePath.Enabled = false;
                //this.layoutControl_DrawLine.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                this.layoutControl_DrawBezier.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                this.layoutControl_Udo.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                this.layoutControl_Rdo.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                this.layoutControl_Cancel.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                this.layoutControl_Ok.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                this.layoutControl_Draw.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                //this.layoutControl_Name.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                btn_Cancel_Click(sender, e);
            }
            else if (mode == Mode.Drive)  //驾驶车户路径模式
            {
                //DevExpress.XtraEditors.XtraMessageBox.Show("正在进行自定义路径操作，请取消后再操作！。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.btn_DrawPath.Enabled = true;
                this.layoutControl_Stop.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                pointDriving.Clear();
                angleDriving.Clear();
                BlGNSSPerception.Instance.Close();
            }
            this.btn_SavePath.Enabled = false;
            this.layoutControl_Name.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            this.txt_PathName.Text = null;
            drawingList.Clear();
            standardList.Clear();
            drawingListUndo.Clear();
            standardListUndo.Clear();
            drawLocationList.Clear();
            this.lookUp_Path.Enabled = true;
            mode = Mode.None;
        }

        /// <summary>
        /// 确定按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Ok_Click(object sender, EventArgs e)
        {
            //保存画的线
            if (pointStandard.Count < 2)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请最少选择两个点。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            drawingList.Add(new DCurve(pointStandard.ToArray(), Color.Red, lineWidth));
            standardList.Add(new DCurve(pointStandard.ToArray(), Color.Red, lineWidth));
            //刷新控件状态
            //this.btn_DrawLine.Enabled = true;
            this.btn_Udo.Enabled = true;
            this.btn_Rdo.Enabled = true;
            this.btn_DrawBezier.Enabled = true;
            this.layoutControl_Draw.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            this.label_Message.Text = null;
            type = DrawType.None;
            pointScreen.Clear();
            pointStandard.Clear();
            this.picExControl1.AllawDraw = false;
            this.picExControl1.Invalidate();
        }

        /// <summary>
        /// 画原始路径
        /// </summary>
        /// <param name="g"></param>
        private void DrawOriginalPath(Graphics g)
        {
            try
            {
                if (mode == Mode.None)   //下拉框选择路径时
                {
                    if (locationList.Count <= 0)
                    {
                        return;
                    }
                    List<PointF> list = new List<PointF>();
                    double x;
                    double y;
                    foreach (MoLocationRuleInfo item in locationList)
                    {
                        conversion.GetWGS84ToGauss(item.LocationLon, item.LocationLat,out x, out y);
                        list.Add(new PointF((float)(x * this.picExControl1.Wrate) + this.picExControl1.StartPoint.X, (float)(y * this.picExControl1.Hrate) + this.picExControl1.StartPoint.Y));
                    }
                    g.DrawCurve(new Pen(Color.Red, lineWidth), list.ToArray());
                }
                else if (mode == Mode.Draw)  //自定义路径时
                {
                    if (type == DrawType.Bezier)
                    {
                        //在地图上选点时，显示点
                        foreach (PointF p in pointScreen)
                        {
                            Region newRegion = new Region(new RectangleF(p, new Size(2 * 2, 2 * 2)));
                            g.FillRegion(new SolidBrush(Color.Red), newRegion);
                        }
                    }
                    //绘制自定义路径
                    for (int i = 0; i < drawingList.Count; i++)
                    {
                        for (int j = 0; j < drawingList[i].pointlist.Length; j++)
                        {
                            drawingList[i].pointlist[j].X = (standardList[i].pointlist[j].X * this.picExControl1.Wrate) + this.picExControl1.StartPoint.X;
                            drawingList[i].pointlist[j].Y = (standardList[i].pointlist[j].Y * this.picExControl1.Hrate) + this.picExControl1.StartPoint.Y;
                        }
                        drawingList[i].pointchange(drawingList[i].pointlist);
                    }
                    drawingList.DrawList(g);
                    RefreshGrid();
                }
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("绘制路径失败。" + ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LogHelper.log.Error(string.Format("绘制路径失败：{0}", ex.ToString()));
            }

        }

        /// <summary>
        /// 绘制线后将点显示在表格中
        /// </summary>
        private void RefreshGrid()
        {
            drawLocationList.Clear();
            if (mode == Mode.Draw)
            {
                double lon;
                double lat;
                for (int i = 0; i < standardList.Count; i++)
                {
                    for (int j = 0; j < standardList[i].pointlist.Length; j++)
                    {
                        conversion.GetGaussToWGS84(standardList[i].pointlist[j].X, standardList[i].pointlist[j].Y, out lon, out lat);
                        MoLocationRuleInfo mo = new MoLocationRuleInfo
                        {
                            RuleName = this.txt_PathName.Text,
                            LocatonId = drawLocationList.Count + 1,
                            LocationLon = lon,
                            LocationLat = lat
                            //LocationHeight = 11,
                            //LocationSpeed =11
                        };
                        drawLocationList.Add(mo);
                    }
                }
            }
            else if (mode == Mode.Drive)
            {
                for (int i = 0; i < pointDriving.Count; i++)
                {
                    MoLocationRuleInfo mo = new MoLocationRuleInfo
                    {
                        RuleName = this.txt_PathName.Text,
                        LocatonId = drawLocationList.Count + 1,
                        LocationLon = pointDriving[i].X,
                        LocationLat = pointDriving[i].Y,
                        //LocationHeight = 11,
                        LocationSpeed = speedDriving[i]
                    };
                    drawLocationList.Add(mo);
                }

            }

            this.gridControl_Path.DataSource = drawLocationList;
            this.gridControl_Path.RefreshDataSource();
        }

        /// <summary>
        /// 画行驶路径
        /// </summary>
        /// <param name="g"></param>
        private void DrawDrivingPath(Graphics g)
        {
            if (mode == Mode.Drive)
            {
                if (pointDriving.Count < 1 || angleDriving.Count < 1)
                {
                    return;
                }
                double x;
                double y;
                if (pointDriving.Count < 2)
                {
                    conversion.GetWGS84ToGauss(pointDriving[0].X, pointDriving[0].Y, out x, out y);
                    g.TranslateTransform((float)x, (float)y);
                    g.RotateTransform(angleDriving[0]);
                    g.DrawImage(global::SIASUN.Autopilot.View.Properties.Resources.汽车2, -7, -15, 14, 30);
                }
                else
                {
                    List<PointF> list = new List<PointF>();
                    for (int i = 0; i < pointDriving.Count; i++)
                    {
                        conversion.GetWGS84ToGauss(pointDriving[i].X, pointDriving[i].Y, out x, out y);
                        list.Add(new PointF((float)(x * this.picExControl1.Wrate) + this.picExControl1.StartPoint.X, (float)(y * this.picExControl1.Hrate) + this.picExControl1.StartPoint.Y));
                    }

                    //foreach (PointF item in pointDriving)
                    //{
                    //    conversion.GetWGS84ToGauss(item.X, item.Y, out x, out y);
                    //    list.Add(new PointF((float)(x * this.picExControl1.Wrate) + this.picExControl1.StartPoint.X, (float)(y * this.picExControl1.Hrate) + this.picExControl1.StartPoint.Y));
                    //}
                    g.DrawCurve(new Pen(Color.Red, lineWidth), list.ToArray());

                    g.TranslateTransform(list[list.Count-1].X, list[list.Count-1].Y);
                    g.RotateTransform(angleDriving[angleDriving.Count-1]);
                    g.DrawImage(global::SIASUN.Autopilot.View.Properties.Resources.汽车2, -7, -15, 14, 30);
                }
                RefreshGrid();
            }

        }
        /// <summary>
        /// 获取行驶中经纬度和角度值
        /// </summary>
        private void GetDrivingInfo(object sender, GNSSInfoEventArgs gnss)
        {
            pointDriving.Add(new PointF { X= (float)gnss.Nmea.gprmc.Longitude,Y = (float)gnss.Nmea.gprmc.Latitude});
            angleDriving.Add((float)gnss.Nmea.gprmc.Deviated);
            speedDriving.Add((float)gnss.Nmea.gprmc.Speed);
            this.picExControl1.Invalidate();

        }

        /// <summary>
        /// 下拉框按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lookUp_Path_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Delete)
            {
                LookUpEdit lookUp = sender as LookUpEdit;
                lookUp.EditValue = null;

            }
        }

        /// <summary>
        /// 下拉框选中项改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lookUp_Path_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.lookUp_Path.EditValue == null)
                {
                    this.label_PathName.Text = null;
                    locationList = new List<MoLocationRuleInfo>();
                }
                else
                {
                    this.label_PathName.Text = this.lookUp_Path.EditValue.ToString();
                    SysEnvironment.CurrentRuleName = this.label_PathName.Text.Trim();
                    string condition = string.Format("rule_name = '{0}'", this.lookUp_Path.EditValue.ToString());
                    locationList = BLLFactory<BlLocationRuleInfo>.Instance.Find(condition);

                }
                this.gridControl_Path.DataSource = locationList;
                this.gridControl_Path.RefreshDataSource();
                this.picExControl1.Invalidate();
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("获取路径失败。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LogHelper.log.Error(string.Format("获取路径失败：{0}", ex.ToString()));
            }

        }

        /// <summary>
        /// 地图控件鼠标点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void picExControl1_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Left)
                {
                    if (type == DrawType.Bezier)
                    {
                        pointScreen.Add(new PointF(e.X, e.Y));
                        pointStandard.Add(new PointF((e.X - this.picExControl1.StartPoint.X) / this.picExControl1.Wrate,
                                                  (e.Y - this.picExControl1.StartPoint.Y) / this.picExControl1.Hrate));
                        this.label_Message.Text = string.Format("已选择{0}个点", pointScreen.Count);
                    }
                    this.picExControl1.Invalidate();
                }
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("在地图上选点失败。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LogHelper.log.Error(string.Format("在地图上选点失败：{0}", ex.ToString()));
            }

        }

        /// <summary>
        /// 描点结束按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Draw_Click(object sender, EventArgs e)
        {
            try
            {
                using (Graphics g = this.picExControl1.CreateGraphics())
                {
                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    if (pointScreen.Count < 2)
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("请最少选择两个点。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    g.DrawCurve(new Pen(Color.Red, lineWidth), pointScreen.ToArray());
                }
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("绘制路线失败。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LogHelper.log.Error(string.Format("绘制路线失败：{0}", ex.ToString()));
            }

        }

        /// <summary>
        /// 撤销按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Udo_Click(object sender, EventArgs e)
        {
            if (standardList.Count == 0)
            {
                return;
            }
            drawingListUndo.Add(drawingList[drawingList.Count - 1]);
            standardListUndo.Add(standardList[standardList.Count - 1]);
            drawingList.RemoveAt(drawingList.Count - 1);
            standardList.RemoveAt(standardList.Count - 1);
            this.picExControl1.Invalidate();
        }

        /// <summary>
        /// 重做按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Rdo_Click(object sender, EventArgs e)
        {
            if (drawingListUndo.Count == 0)
                return;
            drawingList.Add(drawingListUndo[drawingListUndo.Count - 1]);
            standardList.Add(standardListUndo[standardListUndo.Count - 1]);
            drawingListUndo.RemoveAt(drawingListUndo.Count - 1);
            standardListUndo.RemoveAt(standardListUndo.Count - 1);
            this.picExControl1.Invalidate();
        }

        /// <summary>
        /// /输入自定义名称后触发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txt_PathName_TextChanged(object sender, EventArgs e)
        {
            this.label_PathName.Text = this.txt_PathName.Text;
        }

        /// <summary>
        /// 鼠标移动显示经纬度
        /// </summary>
        /// <param name="e"></param>
        private void picExControl1_MouseMove(MouseEventArgs e)
        {
            if (mousePoint.X != e.X || mousePoint.Y != e.Y)
            {
                ToolTipControllerShowEventArgs args = this.toolTip_Message.CreateShowArgs();
                //this.toolTip_Message.SetToolTip(this.picExControl1, string.Format("横坐标:{0}\n纵坐标:{1}", e.X.ToString(), e.Y.ToString()));
                //this.toolTip_Message.SetTitle(this.picExControl1,"提示");
                //this.toolTip_Message.SetToolTipIconType(this.picExControl1,ToolTipIconType.Exclamation);
                double lon;
                double lat;
                conversion.GetGaussToWGS84((e.X - this.picExControl1.StartPoint.X) / this.picExControl1.Wrate, (e.Y - this.picExControl1.StartPoint.Y) / this.picExControl1.Hrate, out lon, out lat);
                args.ToolTip = string.Format("经度:{0}\n纬度:{1}", lon.ToString(), lat.ToString());
                args.SelectedControl = this.picExControl1;
                //args.Title = "提示";
                this.toolTip_Message.ShowHint(args, System.Windows.Forms.Control.MousePosition);
                mousePoint.X = e.X;
                mousePoint.Y = e.Y;
            }
            else
            {
                mousePoint.X = e.X;
                mousePoint.Y = e.Y;
            }
        }

        private void picExControl1_MouseLeave(object sender, EventArgs e)
        {
            this.toolTip_Message.HideHint();
        }

        /// <summary>
        /// 窗口关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormRouteManagement_FormClosing(object sender, FormClosingEventArgs e)
        {
            //BlGNSSPerception.Instance.Close();
        }

        /// <summary>
        /// 停止按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Stop_Click(object sender, EventArgs e)
        {
            BlGNSSPerception.Instance.Close();
        }

        /// <summary>
        /// 放大按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Big_Click(object sender, EventArgs e)
        {
            float rate = 1;
            if (Math.Max(this.picExControl1.Wrate, this.picExControl1.Hrate) <= 10)
            {
                rate = 1.15F;
            }
            Zoom(rate);
        }

        /// <summary>
        /// 缩小按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Small_Click(object sender, EventArgs e)
        {
            float rate = 1;
            if (Math.Min(this.picExControl1.Wrate, this.picExControl1.Hrate) > Math.Max(0.75687, 0.75687))
            {
                rate = 0.85F;
            }
            Zoom(rate);
        }

        /// <summary>
        /// 地图缩放
        /// </summary>
        /// <param name="rate"></param>
        private void Zoom(float rate)
        {
            if (rate == 1) return;
            float imageX = (356F - this.picExControl1.StartPoint.X) / this.picExControl1.Wrate;
            float imageY = (279F - this.picExControl1.StartPoint.Y) / this.picExControl1.Hrate;

            this.picExControl1.Hrate *= rate;
            this.picExControl1.Wrate *= rate;

            this.picExControl1.StartPoint = new PointF(356F - imageX * this.picExControl1.Wrate, 279F - imageY * this.picExControl1.Hrate);
            this.picExControl1.Invalidate();
        }
    }
}