using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.SystemUI;
using KGIS.Framework.EngineEditor;
using KGIS.Framework.Maps;
using KGIS.Framework.Platform;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.Interface;
using Kingo.Plugin.EngineEditor.Views;
using Kingo.PluginServiceInterface;
namespace Kingo.Plugin.EngineEditor.Commands.Tools
{
    public class ControlsEditingEditTool : BaseToolCmd
    {
        #region 私有变量
        //private string m_strMsg;
        //private string m_caption = "";
        //private string m_category = "";
        //private string m_name = "";
        //private string m_tooltip = "";
        //private int m_iBitmap;
        private bool m_checked;
        private IToolbarMenu m_toolbarMenuVertex;//绘图时右键弹出的鼠标点在编辑要素的顶点或边缘上,弹出的右键菜单
        private IToolbarMenu m_toolbarMenuEdit;//编辑工具弹出的右键菜单
        private IEngineEditSketch editSketch;
        private ControlsEditingEditToolClass editorTool = new ControlsEditingEditToolClass();
        private ICommand currentCmd = null;
        private System.Windows.Forms.Cursor m_InsertVertexCursor;
        private System.Windows.Forms.Cursor m_DeleteVertexCursor;
        private bool _IsEditVertex;
        /// 
        /// 是否编辑节点
        /// 
        private bool isEditVertex
        {
            get
            {
                return _IsEditVertex;
            }
            set
            {
                if (value)
                {
                    //增加打开节点编辑面板功能
                    //Platform.Instance.SendMsg(new NotifyMsgPackage() { MsgType = "OpenEditVerticesToolbox" });
                }
                else
                {
                    this.currentCmd = null;
                    //增加通知功能(用于要素节点编辑)
                    Platform.Instance.SendMsg(new NotifyMsgPackage() { MsgType = "ResultEditVertexCommand", Content = currentCmd });//暂时注销,待改回
                    //Platform.Instance.SendMsg(new NotifyMsgPackage() { MsgType = "CloseEditVerticesToolbox" });
                }
                _IsEditVertex = value;
            }
        }
        private IPoint MouseDownPoint = new PointClass() { X = 0, Y = 0 };
        private IPoint MouseUpPoint = new PointClass() { X = 0, Y = 0 };
        private System.Drawing.Point downPoint = new System.Drawing.Point();
        private bool isReleaseAddOrDeletePoint = false;
        #endregion
        /// 
        /// 构造函数
        /// 
        public ControlsEditingEditTool()
        {
        }
        #region Override ICommand Members
        /// 
        /// 该命令关联的图片
        /// 
        public override int Bitmap
        {
            get
            {
                return editorTool.Bitmap;
            }
        }
        /// 
        /// 该命令的标题
        /// 
        public override string Caption
        {
            get
            {
                return editorTool.Caption;
            }
        }
        /// 
        /// 该命令的分组
        /// 
        public override string Category
        {
            get
            {
                return editorTool.Category;
            }
        }
        /// 
        /// 该命令的勾选状态
        /// 
        public override bool Checked
        {
            get
            {
                return m_checked;
            }
        }
        public override bool Enabled
        {
            get
            {
                if (MapsManager.Instance == null)
                    return false;
                object pTemp = (MapsManager.Instance.CurrProjectInfo as ProjectInfo);
                if (pTemp == null)
                {
                    return false;
                }
                else
                {
                    //if (string.IsNullOrWhiteSpace(pTemp.ListTaskPackage==null))//pTemp.GetProjDBPath()
                    //{
                    //    return false;
                    //}
                    //else
                    //{
                    IMapControlDefault pMapControlDefault = m_pHookHelper.Hook as IMapControlDefault;
                    if (!editorTool.Enabled && pMapControlDefault != null && pMapControlDefault.CurrentTool == this)
                    {
                        pMapControlDefault.CurrentTool = null;
                    }
                    return editorTool.Enabled;
                    //}
                }
            }
        }
        /// 
        /// 命令帮助内容ID
        /// 
        public override int HelpContextID
        {
            get
            {
                return editorTool.HelpContextID;
            }
        }
        /// 
        /// 命令帮助文件
        /// 
        public override string HelpFile
        {
            get
            {
                return editorTool.HelpFile;
            }
        }
        /// 
        /// 状态栏信息
        /// 
        public override string Message
        {
            get
            {
                return editorTool.Message;
            }
        }
        /// 
        /// 命令的名称
        /// 
        public override string Name
        {
            get
            {
                return editorTool.Name;//base.Name;
            }
        }
        private IMapService _MapService;
        private IEngineSnapEnvironment snapEnv = null;
        /// 
        /// 点击命令时处理逻辑
        /// 
        //[LogWrite(Description = "")]
        public override void OnClick()
        {
            try
            {
                isReleaseAddOrDeletePoint = false;
                _MapService = MapsManager.Instance.MapService;
                editorTool.OnClick();//调用基类的OnClick方法
                //添加右键菜单
                if (m_toolbarMenuVertex == null)
                {
                    m_toolbarMenuVertex = CreateVertexContextMenu();
                    m_toolbarMenuVertex.SetHook(m_pHookHelper.Hook);
                }
                if (m_toolbarMenuEdit == null)
                {
                    m_toolbarMenuEdit = CreateEditContextMenu();
                    m_toolbarMenuEdit.SetHook(m_pHookHelper.Hook);
                }
                if (m_pEditor == null)
                {
                    m_pEditor = new EngineEditorClass();
                }
                editSketch = m_pEditor as IEngineEditSketch;
                snapEnv = (IEngineSnapEnvironment)m_pEditor;
                List layers = MapsManager.Instance.MapService.GetAllVisibleLayerInMap();
                if (layers != null)
                {
                    foreach (IFeatureLayer item in layers)
                    {
                        IEngineFeatureSnapAgent featureSnapAgent = new EngineFeatureSnap();
                        featureSnapAgent.FeatureClass = item.FeatureClass;
                        featureSnapAgent.HitType = esriGeometryHitPartType.esriGeometryPartBoundary | esriGeometryHitPartType.esriGeometryPartVertex;
                        snapEnv.AddSnapAgent(featureSnapAgent);
                    }
                }
                m_checked = true;
            }
            catch (Exception ex)
            {
                LogAPI.Debug("点击 编辑工具 时异常,异常信息如下:");
                LogAPI.Debug(ex);
                LogAPI.Debug("点击 编辑工具 时异常信息结束");
            }
        }
        /// 
        /// 将命令与MapControl等ToolBuddy控件绑定
        /// 
        /// 
        //[LogWrite(Description = "")]
        public override void OnCreate(object hook)
        {
            try
            {
                base.OnCreate(hook);
                editorTool.OnCreate(hook);//调用基类的OnCreate方法
                //                          //初始化m_pHookHelper,并给Hook对象赋值
                //if (m_pHookHelper == null)
                //{
                //    //替换Env改动
                //    //m_pHookHelper = Env.Instance.KMap.HookHelper;
                //    ////m_pHookHelper.Hook = hook;
                //    m_pHookHelper = new HookHelperClass();
                //    m_pHookHelper.Hook = hook;
                //}
                //IHookHelper2 hookHelper2 = m_pHookHelper as IHookHelper2;
                //if (hookHelper2 != null)
                //{
                //    IExtensionManager extensionManager = hookHelper2.ExtensionManager;
                //    if (extensionManager != null)
                //    {
                //        IExtension extension = extensionManager.FindExtension(new UIDClass
                //        {
                //            Value = "{E07B4C52-C894-4558-B8D4-D4050018D1DA}"//捕捉
                //        });
                //        if (extension != null)
                //        {
                //            this.m_pSnappingEnv = (extension as ISnappingEnvironment);
                //            this.m_pPntSnapper = this.m_pSnappingEnv.PointSnapper;
                //            this.m_pSnappingFeedback = new SnappingFeedbackClass();
                //            this.m_pSnappingFeedback.Initialize(hook, this.m_pSnappingEnv, true);
                //        }
                //    }
                //}
                //订阅消息通知事件
                Platform.Instance.NotifyMsgEven2 += NotifyMsg_NotifyMsgEven;//暂时注销,待改回
                System.IO.Stream insertVerStream = GetType().Assembly.GetManifestResourceStream("Kingo.Plugin.EngineEditor.Resources.Tool.InsertVertexCursor.cur");
                if (insertVerStream != null)
                    m_InsertVertexCursor = new System.Windows.Forms.Cursor(insertVerStream);
                System.IO.Stream delVerStream = GetType().Assembly.GetManifestResourceStream("Kingo.Plugin.EngineEditor.Resources.Tool.DeleteVertexCursor.cur");
                if (delVerStream != null)
                    m_DeleteVertexCursor = new System.Windows.Forms.Cursor(delVerStream);
            }
            catch (Exception ex)
            {
                LogAPI.Debug("初始化 编辑工具 命令时异常,异常信息如下:");
                LogAPI.Debug(ex);
                LogAPI.Debug("初始化 编辑工具 命令时异常信息结束");
            }
        }
        #region 增加接收消息通知函数
        void NotifyMsg_NotifyMsgEven(NotifyMsgPackage obj)
        {
            if (obj.MsgType == "EditVertexCommand")
            {
                currentCmd = obj.Content as ICommand;
                Platform.Instance.SendMsg(new NotifyMsgPackage() { MsgType = "ResultEditVertexCommand", Content = currentCmd });//暂时注销,待改回
            }
            else if (obj.MsgType == "ExitVertexCommand")
            {
                isReleaseAddOrDeletePoint = true;
                currentCmd = null;
                Deactivate();
                MapsManager.Instance.MapService.getAxMapControl().CurrentTool = null;
            }
        }
        #endregion
        /// 
        /// 命题提示
        /// 
        public override string Tooltip
        {
            get
            {
                return editorTool.Tooltip;
            }
        }
        #endregion
        #region Override ITool Members
        private int _Cursor;
        /// 
        /// 该工具在图上漫游时的鼠标样式
        /// 
        public override int Cursor
        {
            get
            {
                if (_Cursor == 0 && editorTool.Enabled)
                    return editorTool.Cursor;
                else
                    return _Cursor;
            }
        }
        /// 
        /// 该工具不再为当前工具,释放资源时使用
        /// 
        /// 
        //[LogWrite(Description = "")]
        public override bool Deactivate()
        {
            try
            {
                snapEnv?.ClearSnapAgents();
                if (editSketch != null && editSketch.Geometry != null && isEditVertex)
                {
                    editSketch.FinishSketchPart();
                    editSketch.FinishSketch();
                }
                isEditVertex = false;
                m_checked = false;
                CloseFrm();//释放要素编辑器
                           //切换工具同时,切换任务
                IEngineEditTask pEngineEditTask = m_pEditor as IEngineEditTask;
                pEngineEditTask = m_pEditor.GetTaskByUniqueName("ControlToolsEditing_CreateNewFeatureTask");
                //为空不赋值
                if (pEngineEditTask != null)
                {
                    m_pEditor.CurrentTask = pEngineEditTask;
                }
                //return editorTool.Deactivate();
            }
            catch (Exception ex)
            {
                LogAPI.Debug(ex);
            }
            return editorTool.Deactivate(); ;
        }
        /// 
        /// 右键菜单
        /// 
        /// X坐标
        /// Y坐标
        /// 若有右键菜单返回True
        public override bool OnContextMenu(int x, int y)
        {
            return editorTool.OnContextMenu(x, y);
        }
        /// 
        /// 双击事件逻辑
        /// 
        //[LogWrite(Description = "")]
        public override void OnDblClick()
        {
            editorTool.OnDblClick();//调用基类OnDblClick
            if (editSketch.Geometry == null)
                return;
            this.SketchGeometry = new SketchGeometry(this.editSketch.Geometry, null, true);
            isEditVertex = true;
        }
        /// 
        /// Key Down逻辑
        /// 
        /// 
        /// 
        //[LogWrite(Description = "")]
        public override void OnKeyDown(int keyCode, int shift)
        {
            if (editorTool.Enabled)
                editorTool.OnKeyDown(keyCode, shift);
        }
        /// 
        /// Key up逻辑
        /// 
        /// 
        /// 
        //[LogWrite(Description = "")]
        public override void OnKeyUp(int keyCode, int shift)
        {
            if (editorTool.Enabled)
                editorTool.OnKeyUp(keyCode, shift);
        }
        private bool IsMouseDown = false;
        /// 
        /// Mouse Down逻辑
        /// 
        /// 
        /// 
        /// 
        /// 
        //[LogWrite(Description = "")]
        public override void OnMouseDown(int button, int shift, int x, int y)
        {
            try
            {
                if (button == 1)
                {
                    IsMouseDown = true;
                    //替换Env改动
                    MouseDownPoint = m_pHookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y);
                    //MouseDownPoint = m_pPointCatched;// m_pHookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y);
                    ((IEngineEditSketch)m_pEditor).SetEditLocation(x, y);
                    #region 增加判断当前点击是否符合节点编辑条件功能
                    IPoint clickedPt = m_pHookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y);
                    if (m_pPointCatched == null)
                        m_pPointCatched = clickedPt;
                    IGeometry editShape = editSketch.Geometry;
                    //增加判断当前是否编辑节点状态代码
                    if (editShape == null)
                    {
                        editorTool.OnMouseDown(button, shift, x, y);
                        isEditVertex = false;
                        ClearSel();
                        return;
                    }
                    if (isReleaseAddOrDeletePoint && currentCmd == null)
                    {
                        return;
                    }
                    IHitTest hitShape = editShape as IHitTest;
                    #region 注释代码
                    //未选择操作图层时
                    //if (hitShape == null)
                    //{
                    //    return;
                    //}
                    #endregion
                    IPoint hitPoint = new PointClass();
                    IPoint hitPointBoundary = new PointClass();
                    double hitDistance = 0;
                    int hitPartIndex = 0;
                    int hitSegmentIndex = 0;
                    bool bRightSide = false;
                    esriGeometryHitPartType hitPartType = esriGeometryHitPartType.esriGeometryPartNone;
                    //the searchRadius is the maximum distance away, in map units, from the shape that will be used
                    //for the test - change to an appropriate value.
                    double searchRadius = this.ConvertPixelsToMapUnits(0.0); ;
                    if (currentCmd is CustomVertexDeleteCommandChinese)
                    {
                        hitPartType = esriGeometryHitPartType.esriGeometryPartVertex;
                    }
                    else if (currentCmd is CustomVertexInsertCommandChinese)
                    {
                        hitPartType = esriGeometryHitPartType.esriGeometryPartBoundary;
                    }
                    ClearSel();
                    hitShape.HitTest(m_pPointCatched, searchRadius, hitPartType, hitPoint, ref hitDistance, ref hitPartIndex, ref hitSegmentIndex, ref bRightSide);
                    #endregion
                    if (hitPoint.IsEmpty)
                    {
                        if (currentCmd != null)
                        {
                            currentCmd = null;
                            Platform.Instance.SendMsg(new NotifyMsgPackage() { MsgType = "ResultEditVertexCommand", Content = currentCmd });//暂时注销,待改回
                            return;
                        }
                        //判断当前是否点击的要素节点,如果是非节点处,则改变当前任务为新建要素任务
                        hitShape.HitTest(m_pPointCatched, searchRadius, esriGeometryHitPartType.esriGeometryPartVertex, hitPoint, ref hitDistance, ref hitPartIndex, ref hitSegmentIndex, ref bRightSide);
                        //判断是否点击边界,若是允许右键添加节点,否则重置任务
                        hitShape.HitTest(m_pPointCatched, searchRadius, esriGeometryHitPartType.esriGeometryPartBoundary, hitPointBoundary, ref hitDistance, ref hitPartIndex, ref hitSegmentIndex, ref bRightSide);
                        if (hitPoint.IsEmpty && button == 2)
                        {
                            if (hitPointBoundary.IsEmpty)
                            {
                                //重置任务
                                IEngineEditTask pEngineEditTask = m_pEditor as IEngineEditTask;
                                pEngineEditTask = m_pEditor.GetTaskByUniqueName("ControlToolsEditing_CreateNewFeatureTask");
                                if (pEngineEditTask != null)
                                {
                                    m_pEditor.CurrentTask = pEngineEditTask;
                                }
                            }
                            if (editorTool.Enabled && hitPointBoundary.IsEmpty)
                                editorTool.OnMouseDown(button, shift, x, y);//调用基类的OnMouseDown事件
                        }
                        else
                        {
                            if (editorTool.Enabled)
                                editorTool.OnMouseDown(button, shift, x, y);//调用基类的OnMouseDown事件
                        }
                        //isEditVertex = false;
                    }
                    else
                    {
                        if (hitPartType == esriGeometryHitPartType.esriGeometryPartVertex)
                        {
                            SketchGeometry.EditVertexInfo.SetEditVertexInfo(m_pPointCatched, true, hitPartIndex, hitSegmentIndex);
                        }
                        else if (hitPartType == esriGeometryHitPartType.esriGeometryPartBoundary)
                        {
                            SketchGeometry.EditVertexInfo.SetEditVertexInfo(m_pPointCatched, false, hitPartIndex, hitSegmentIndex);
                        }
                    }
                }
                //点击右键时,弹出编辑菜单
                if (button == 2)
                {
                    //((IEngineEditSketch)m_pEditor).SetEditLocation(x, y);
                    if (m_pEditor.CurrentTask != null && m_pEditor.CurrentTask.UniqueName == "ControlToolsEditing_ModifyFeatureTask")
                        m_toolbarMenuVertex.PopupMenu(x, y, m_pHookHelper.ActiveView.ScreenDisplay.hWnd);
                    else
                        m_toolbarMenuEdit.PopupMenu(x, y, m_pHookHelper.ActiveView.ScreenDisplay.hWnd);
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("ControlsEditingEditTool > OnMouseDown异常:" + ex);
            }
        }
        /// 
        /// Mouse Move逻辑
        /// 
        /// 
        /// 
        /// 
        /// 
        public override void OnMouseMove(int button, int shift, int x, int y)
        {
            downPoint = new System.Drawing.Point();
            downPoint.X = x;
            downPoint.Y = y;
            if (isEditVertex)
            {
                if (editSketch.Geometry == null)
                {
                    isEditVertex = false;
                    return;
                }
                //进入编辑节点状态并且编辑任务是编辑节点(鼠标在节点上)时,允许拖动,测绘大队20180905优化选择移动功能需求
                if (m_pEditor.CurrentTask != null && m_pEditor.CurrentTask.UniqueName == "ControlToolsEditing_ModifyFeatureTask")
                {
                    if (editorTool.Enabled)
                        editorTool.OnMouseMove(button, shift, x, y);
                }
                #region
                if (isReleaseAddOrDeletePoint && currentCmd == null)
                {
                    return;
                }
                IPoint clickedPt = m_pHookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y);
                IGeometry editShape = editSketch.Geometry;
                IHitTest hitShape = editShape as IHitTest;
                IPoint hitPoint = new PointClass();
                double hitDistance = 0;
                int hitPartIndex = 0;
                int hitSegmentIndex = 0;
                bool bRightSide = false;
                esriGeometryHitPartType hitPartType = esriGeometryHitPartType.esriGeometryPartNone;
                //the searchRadius is the maximum distance away, in map units, from the shape that will be used
                //for the test - change to an appropriate value.
                double searchRadius = this.ConvertPixelsToMapUnits(0.0);
                if (currentCmd is CustomVertexDeleteCommandChinese)
                {
                    #region 捕捉
                    this.m_pPointCatched = this.m_pHookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y);
                    if (this.m_pSnappingEnv != null && this.m_pSnappingEnv.Enabled)
                    {
                        ISnappingResult snappingResult = this.m_pPntSnapper.Snap(this.m_pPointCatched);
                        this.m_pSnappingFeedback.Update(snappingResult, 0);
                        if (snappingResult != null)
                        {
                            this.m_pPointCatched = snappingResult.Location;
                        }
                    }
                    string strDescription = "";
                    IPoint point = null;
                    if (this.m_pSnappingEnv != null && this.m_pSnappingEnv.Enabled && SnappingSketchFeedback.Enabled)
                    {
                        this.m_pHookHelper.ActiveView.PartialRefresh(ESRI.ArcGIS.Carto.esriViewDrawPhase.esriViewForeground, null, null);
                        //this.RefreshForeground(null);
                        point = SnappingSketch(this.m_pPointCatched, ref strDescription);
                        if (point != null)
                        {
                            this.m_pPointCatched = point;
                        }
                    }
                    #endregion
                    hitPartType = esriGeometryHitPartType.esriGeometryPartVertex;
                }
                else if (currentCmd is CustomVertexInsertCommandChinese)
                {
                    #region 捕捉
                    this.m_pPointCatched = this.m_pHookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y);
                    if (this.m_pSnappingEnv != null && this.m_pSnappingEnv.Enabled)
                    {
                        ISnappingResult snappingResult = this.m_pPntSnapper.Snap(this.m_pPointCatched);
                        this.m_pSnappingFeedback.Update(snappingResult, 0);
                        if (snappingResult != null)
                        {
                            this.m_pPointCatched = snappingResult.Location;
                        }
                    }
                    string strDescription = "";
                    IPoint point = null;
                    if (this.m_pSnappingEnv != null && this.m_pSnappingEnv.Enabled && SnappingSketchFeedback.Enabled)
                    {
                        this.m_pHookHelper.ActiveView.PartialRefresh(ESRI.ArcGIS.Carto.esriViewDrawPhase.esriViewForeground, null, null);
                        //this.RefreshForeground(null);
                        point = SnappingSketch(this.m_pPointCatched, ref strDescription);
                        if (point != null)
                        {
                            this.m_pPointCatched = point;
                        }
                    }
                    #endregion
                    hitPartType = esriGeometryHitPartType.esriGeometryPartBoundary;
                }
                else
                {
                    hitPartType = esriGeometryHitPartType.esriGeometryPartNone;
                }
                hitShape.HitTest(clickedPt, searchRadius, hitPartType, hitPoint, ref hitDistance, ref hitPartIndex, ref hitSegmentIndex, ref bRightSide);
                #endregion
                if (hitPoint.IsEmpty)
                {
                    _Cursor = editorTool.Cursor;
                }
                else
                {
                    if (hitPartType == esriGeometryHitPartType.esriGeometryPartVertex && m_DeleteVertexCursor != null)
                    {
                        _Cursor = m_DeleteVertexCursor.Handle.ToInt32();
                    }
                    else if (hitPartType == esriGeometryHitPartType.esriGeometryPartBoundary && m_InsertVertexCursor != null)
                    {
                        _Cursor = m_InsertVertexCursor.Handle.ToInt32();
                    }
                }
            }
            //不在编辑节点状态下(要素只是高亮显示)允许拖动要素
            else
            {
                if (IsMouseDown && !isEditVertex) return;
                //if (downPoint.X == x || downPoint.Y == y)
                //{
                //}
                ((IEngineEditSketch)m_pEditor).SetEditLocation(x, y);
                if (editorTool.Enabled)
                    editorTool.OnMouseMove(button, shift, x, y);
            }
        }
        /// 
        /// Mouse up逻辑
        /// 
        /// 
        /// 
        /// 
        /// 
        //[LogWrite(Description = "")]
        public override void OnMouseUp(int button, int shift, int x, int y)
        {
            try
            {
                if (button == 1)
                {
                    IsMouseDown = false;
                    //如果窗体显示就关闭
                    PointToScreen(x, y);
                    CloseFrm();
                    if (isReleaseAddOrDeletePoint && currentCmd == null)
                    {
                        return;
                    }
                    //-------------
                    //替换Env改动
                    MouseUpPoint = m_pHookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y);
                    //框选单个要素进入节点编辑问题处理
                    if ((!MouseUpPoint.X.Equals(MouseDownPoint.X) || !MouseUpPoint.Y.Equals(MouseDownPoint.Y)) && isEditVertex && currentCmd != null)
                    {
                        IEngineEditTask pEngineEditTask = m_pEditor as IEngineEditTask;
                        pEngineEditTask = m_pEditor.GetTaskByUniqueName("ControlToolsEditing_ModifyFeatureTask");
                        if (pEngineEditTask != null)
                        {
                            m_pEditor.CurrentTask = pEngineEditTask;
                        }
                    }
                    if (editorTool.Enabled)
                        editorTool.OnMouseUp(button, shift, x, y);
                    if (m_pEditor.CurrentTask != null && m_pEditor.CurrentTask.UniqueName != "ControlToolsEditing_ModifyFeatureTask")
                    {
                        isEditVertex = false;
                    }
                    else
                    {
                        //增加调用新增节点/删除节点命令
                        if (currentCmd is CustomVertexDeleteCommandChinese)
                        {
                            SketchGeometry.DeleteVertexEdit();
                            editSketch.Geometry = SketchGeometry.Geometry;
                            editSketch.ModifySketch();
                        }
                        else if (currentCmd is CustomVertexInsertCommandChinese)
                        {
                            SketchGeometry.InsertVertexEdit();
                            editSketch.Geometry = SketchGeometry.Geometry;
                            editSketch.ModifySketch();
                        }
                    }
                    ISelection pSelection = m_pHookHelper.FocusMap.FeatureSelection;
                    IEnumFeatureSetup iEnumFeatureSetup = (IEnumFeatureSetup)pSelection;
                    iEnumFeatureSetup.AllFields = true;
                    IEnumFeature enumFeature = (IEnumFeature)iEnumFeatureSetup;
                    enumFeature.Reset();
                    IFeature feature = enumFeature.Next();
                    if (feature == null)
                    {
                        return;
                    }
                    //20230927 方法调用会影响其他功能 暂时注释
                    //Platform.Instance.SendMsg(new KGIS.Framework.Utils.Interface.NotifyMsgPackage() { MsgType = "Positioning", Content = feature.OID });
                    Platform.Instance.SendMsg(new NotifyMsgPackage() { MsgType = "Positioning", Content = feature });
                    //判断点MouseDownPoint上是否有多个要数,没有return ,有弹出选择框
                    if (isEditVertex == false)
                    {
                        SelectFeatureCount(MouseDownPoint, true);
                    }
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("ControlsEditingEditTool > OnMouseUp异常:" + ex);
            }
        }
        private void ClearSel()
        {
            ISelection pSelection = m_pHookHelper.FocusMap.FeatureSelection;
            IEnumFeatureSetup iEnumFeatureSetup = (IEnumFeatureSetup)pSelection;
            iEnumFeatureSetup.AllFields = true;
            IEnumFeature enumFeature = (IEnumFeature)iEnumFeatureSetup;
            enumFeature.Reset();
            IFeature feature = enumFeature.Next();
            if (feature == null)
            {
                return;
            }
            IList list = MapsManager.Instance.MapService.GetAllVisibleLayerInMap();// LayerHelper.GetAllLayerInMap(m_pHookHelper.FocusMap, true);
            ////矢量化工程:编辑模式下,先勾选权属层数据,双击地图,再取消勾选权属数据,再次双击地图,之前的权属层数据还在
            //替换Env改动
            //IFeatureLayer m_featurelayer = Env.Instance.KMap.GetFeatureLayerByName((feature.Class as FeatureClass).BrowseName);
            IFeatureLayer m_featurelayer = _MapService.GetFeatureLayerByName((feature.Class as FeatureClass).BrowseName);
            if (m_featurelayer == null)
            {
                m_pHookHelper.FocusMap.ClearSelection();
            }
            else if (!list.Contains(m_featurelayer))
            {
                m_pHookHelper.FocusMap.ClearSelection();
            }
        }
        /// 
        /// 刷新
        /// 
        /// 
        public override void Refresh(int hdc)
        {
            if (editorTool.Enabled)
                editorTool.Refresh(hdc);
            IsExistSelect();//添加是否有要素被选中判断
        }
        #endregion
        /// 
        /// 右键弹出时的鼠标点在编辑要素的顶点或边缘上时弹出的右键菜单
        /// 
        /// 顶点会边缘上时弹出的右键菜单
        public static IToolbarMenu CreateVertexContextMenu()
        {
            IToolbarMenu pToolbarMenuVertex = new ToolbarMenuClass();
            pToolbarMenuVertex.AddItem(new ControlsEditingVertexInsertCommandChinese(), -1, 0, false, esriCommandStyles.esriCommandStyleTextOnly);
            pToolbarMenuVertex.AddItem(new ControlsEditingVertexDeleteCommandChinese(), -1, 1, false, esriCommandStyles.esriCommandStyleTextOnly);
            pToolbarMenuVertex.AddItem(new ControlsEditingVertexMoveCommandChinese(), -1, 2, false, esriCommandStyles.esriCommandStyleTextOnly);
            pToolbarMenuVertex.AddItem(new ControlsEditingVertexMoveToCommandChinese(), -1, 3, false, esriCommandStyles.esriCommandStyleTextOnly);
            pToolbarMenuVertex.AddItem(new ControlsEditingSketchDeleteCommandChinese(), -1, 4, true, esriCommandStyles.esriCommandStyleTextOnly);
            pToolbarMenuVertex.AddItem(new ControlsEditingSketchFinishCommandChinese(), -1, 5, false, esriCommandStyles.esriCommandStyleTextOnly);
            pToolbarMenuVertex.AddItem(new ControlsEditingSketchFinishPartCommandChinese(), -1, 6, false, esriCommandStyles.esriCommandStyleIconAndText);
            pToolbarMenuVertex.AddItem(new ControlsEditingSketchPropertiesCommandChinese(), -1, 7, true, esriCommandStyles.esriCommandStyleIconAndText);
            return pToolbarMenuVertex;
        }
        /// 
        /// Edit Tool右击时弹出的右键菜单
        /// 
        /// Edit Tool右击时弹出的右键菜单
        public static IToolbarMenu CreateEditContextMenu()
        {
            IToolbarMenu pToolbarMenuEdit = new ToolbarMenuClass();
            pToolbarMenuEdit.AddItem(new ControlsEditingCopyCommandChinese(), -1, 0, false, esriCommandStyles.esriCommandStyleIconAndText);
            pToolbarMenuEdit.AddItem(new ControlsEditingPasteCommandChinese(), -1, 1, false, esriCommandStyles.esriCommandStyleIconAndText);
            pToolbarMenuEdit.AddItem(new ControlsEditingClearCommandChinese(), -1, 2, true, esriCommandStyles.esriCommandStyleIconAndText);
            pToolbarMenuEdit.AddItem(new ControlsMapIdentifyToolClassChinese(), -1, 3, true, esriCommandStyles.esriCommandStyleIconAndText);
            pToolbarMenuEdit.AddItem(new ControlsZoomToSelectedCommandClassChinese(), -1, 4, true, esriCommandStyles.esriCommandStyleIconAndText);
            pToolbarMenuEdit.AddItem(new ControlsClearSelectionCommandChinese(), -1, 5, false, esriCommandStyles.esriCommandStyleIconAndText);
            pToolbarMenuEdit.AddItem(new ControlsEditingAttributeCommandChinese(), -1, 6, true, esriCommandStyles.esriCommandStyleIconAndText);
            return pToolbarMenuEdit;
        }
        #region 添加要素转换器
        System.Drawing.Point pointnew = new System.Drawing.Point();
        public FrmFeatureSelected frmFeaSelect = null;
        ILayer layer = null;
        IFeatureLayer pFeatureLayer = null;
        ISelectionSet pSelectionSet = null;
        public void SelectFeatureCount(IPoint point, bool IsTest)
        {
            try
            {
                layer = (m_pEditor as EngineEditorClass).TargetLayer;
                if (layer == null)
                    return;//判断当前是否存在编辑图层
                List layers = MapsManager.Instance.MapService.GetAllVisibleLayerInMap();
                Dictionary> keyValuePairs = new Dictionary>();
                foreach (IFeatureLayer layeritem in layers)
                {
                    IIdentify pIdentify = layeritem as IIdentify;
                    if (layeritem.FeatureClass == null || layeritem.FeatureClass.FeatureCount(null) == 0) continue;
                    IArray pIDs = pIdentify.Identify((IGeometry)point);
                    if (pIDs == null) continue;
                    keyValuePairs[((IDataset)layeritem.FeatureClass).Name] = new List();
                    for (int i = 0; i < pIDs.Count; i++)
                    {
                        IRowIdentifyObject row = (IRowIdentifyObject)pIDs.get_Element(i);
                        if (row == null)
                            continue;
                        IFeature f = row.Row as IFeature;
                        if (f.HasOID)
                            keyValuePairs[((IDataset)layeritem.FeatureClass).Name].Add(f.OID);
                        Marshal.FinalReleaseComObject(f);//释放要素
                    }
                }
                if (keyValuePairs.Count > 1)
                {
                    if (frmFeaSelect == null || frmFeaSelect.bReturn == false)
                    {
                        frmFeaSelect = new FrmFeatureSelected(m_pHookHelper, keyValuePairs)
                        {
                            Left = pointnew.X + 50,
                            Top = pointnew.Y + 50,
                            ShowInTaskbar = true
                        };
                        frmFeaSelect.ShowInMainForm();
                    }
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("Edit Tool左键点击选择图斑异常:" + ex);
            }
        }
        /// 
        /// 给MouseXY赋值屏幕XY
        /// 
        /// 
        /// 
        /// 转换后的点的坐标(没有用到)
        public System.Drawing.Point PointToScreen(int x, int y)
        {
            //替换Env改动
            //pointnew = Env.Instance.KMap.AxMapControl.PointToScreen(new System.Drawing.Point(x, y));
            pointnew = _MapService.PointToScreen(new System.Drawing.Point(x, y));
            return pointnew;
        }
        /// 
        /// 关闭要素编辑器
        /// 
        /// frmFeaSelect为要素编辑器
        public void CloseFrm()
        {
            //如果窗体显示就关闭
            if (frmFeaSelect != null && frmFeaSelect.bReturn == true)
            {
                frmFeaSelect.Close();
                frmFeaSelect = null;
            }
        }
        /// 
        /// 判断当前是否有选中要素,没有则关闭弹窗
        /// 
        public void IsExistSelect()
        {
            try
            {
                if (layer == null)
                {
                    layer = (m_pEditor as EngineEditorClass).TargetLayer;
                    if (layer == null)
                    {
                        return;
                    }
                    pFeatureLayer = layer as IFeatureLayer;
                }
                if (pFeatureLayer == null) return;
                pSelectionSet = (pFeatureLayer as IFeatureSelection).SelectionSet;
                IEnumIDs enumIDs = pSelectionSet.IDs;
                enumIDs.Reset();
                int objectid = 0;
                while ((objectid = enumIDs.Next()) >= 0)
                {
                    return;
                }
                CloseFrm();
            }
            catch (Exception ex)
            {
                LogAPI.Debug("要素是否被选中判断异常:" + ex);
            }
        }
        #endregion
    }
}