using System;
using System.Collections.Generic;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using KGIS.Framework.AE;
using KGIS.Framework.EngineEditor;
using KGIS.Framework.Maps;
using KGIS.Framework.Platform;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.Helper;
using Kingo.Plugin.EngineEditor.Common;
using Kingo.PluginServiceInterface;
using UIShell.OSGi;
namespace Kingo.Plugin.EngineEditor.Commands.Tools
{
    /// 
    /// 绘制零星面
    /// 
    public class DrawPolygonLXCommandForKDB : BaseToolCmd
    {
        public VerificationOfFeatureNodeDensity density
        {
            get;
            set;
        }
        public override void OnCreate(object hook)
        {
            base.OnCreate(hook);
        }
        private void ActiveViewEvents_Event_ItemDeleted(object Item)
        {
            if (EditorSettingClass.Instance.IsTraceing)
            {
                this.EndTraceFeedback();
            }
        }
        private void ActiveViewEvents_Event_ItemAdded(object Item)
        {
            if (EditorSettingClass.Instance.IsTraceing)
            {
                this.EndTraceFeedback();
            }
        }
        private void ActiveViewEvents_Event_ContentsChanged()
        {
        }
        //在范围更新时
        private void M_pAxMapControl_OnExtentUpdated(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnExtentUpdatedEvent e)
        {
            if (EditorSettingClass.Instance.IsTraceing && this.m_pTraceFeedback != null)
            {
                try
                {
                    this.FillFeatureCache(this.m_pPointCatched);
                }
                catch (Exception) { }
                this.GetBeTracedPolyline();
                //this.m_pTraceFeedback.SetSplitPolyline(m_pListBeTracePolyline);
                this.m_pTraceFeedback.ListBeTracePolyline = this.m_pListBeTracePolyline;
            }
        }
        //停用/取消激活
        public override bool Deactivate()
        {
            base.Deactivate();
            MapsManager.Instance.MapService.getAxMapControl().OnExtentUpdated -= M_pAxMapControl_OnExtentUpdated;
            IActiveViewEvents_Event activeViewEvents_Event = base.m_pMapControl.ActiveView as IActiveViewEvents_Event;
            activeViewEvents_Event.ContentsChanged -= ActiveViewEvents_Event_ContentsChanged;
            activeViewEvents_Event.ItemAdded -= ActiveViewEvents_Event_ItemAdded;
            activeViewEvents_Event.ItemDeleted -= ActiveViewEvents_Event_ItemDeleted;
            this.m_deactivate = true;
            return this.m_deactivate;
        }
        public override void OnClick()
        {
            base.OnClick();
            MapsManager.Instance.MapService.getAxMapControl().OnExtentUpdated += M_pAxMapControl_OnExtentUpdated;
            IActiveViewEvents_Event activeViewEvents_Event = base.m_pMapControl.ActiveView as IActiveViewEvents_Event;
            activeViewEvents_Event.ContentsChanged += ActiveViewEvents_Event_ContentsChanged;
            activeViewEvents_Event.ItemAdded += ActiveViewEvents_Event_ItemAdded;
            activeViewEvents_Event.ItemDeleted += ActiveViewEvents_Event_ItemDeleted;
        }
        public override bool Enabled
        {
            get
            {
                try
                {
                    if (MapsManager.Instance == null) return false;
                    object pTemp = (MapsManager.Instance.CurrProjectInfo as ProjectInfo);
                    if (pTemp == null)
                    {
                        return false;
                    }
                    else
                    {
                        //if (string.IsNullOrWhiteSpace(pTemp.GetProjDBPath()))
                        //{
                        //    return false;
                        //}
                        //else
                        //{
                        if (m_pEditor == null)
                        {
                            return false;
                        }
                        //替换Env改动
                        IFeatureLayer layer = (m_pEditor as EngineEditorClass).TargetLayer as IFeatureLayer;// Env.Instance.KMap.EngEditor.TargetLayer as IFeatureLayer;
                        if ((m_pEditor as EngineEditorClass).EditState == esriEngineEditState.esriEngineStateEditing && layer != null)
                        {
                            if ((m_pEditor as EngineEditorClass).GeometryType == esriGeometryType.esriGeometryPolygon)
                            {
                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        }
                        return false;
                        //}
                    }
                }
                catch (Exception ex)
                {
                    LogAPI.Debug("整形要素Enabled异常:" + ex.Message);
                    return false;
                }
            }
        }
        //新增面-鼠标点击
        public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            if (Button == 1)
            {
                DisplayFeedbackMethod pDisplayFeedbackMethod = this.m_pDisplayFeedbackMethod;
                if (this.m_pGeometry == null)
                {
                    switch (pDisplayFeedbackMethod)
                    {
                        case DisplayFeedbackMethod.Line:
                            this.NewPolyline();
                            break;
                        case DisplayFeedbackMethod.Polygon:
                            this.NewPolygon();
                            break;
                        default:
                            break;
                    }
                }
                if (pDisplayFeedbackMethod != DisplayFeedbackMethod.Arc)
                {
                    if (EditorSettingClass.Instance.IsTraceing && (this.m_pDisplayFeedbackMethod == DisplayFeedbackMethod.Polygon || this.m_pDisplayFeedbackMethod == DisplayFeedbackMethod.Line))
                    {
                        IPoint p = this.m_pMapControl.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
                        ISnappingResult snappingResult = null;
                        if (this.m_pSnappingEnv != null && this.m_pSnappingEnv.Enabled)
                        {
                            snappingResult = this.m_pPntSnapper.Snap(p);
                        }
                        if (snappingResult == null && m_pTraceFeedback == null)
                        {
                            m_pTraceFeedback = null;
                            switch (pDisplayFeedbackMethod)
                            {
                                case DisplayFeedbackMethod.Polygon:
                                    this.AddToFeedback(this.m_pPointCatched);
                                    this.AddPointToPolygon(this.m_pPointCatched);
                                    break;
                                case DisplayFeedbackMethod.Line:
                                    //this.StartFeedback(this.m_pPointCatched);
                                    this.AddToFeedback(this.m_pPointCatched);
                                    this.AddPointToPolyline(this.m_pPointCatched);
                                    break;
                            }
                        }
                        else if (snappingResult == null && m_pTraceFeedback != null)
                        {
                            IPolyline polyline = this.AddToTraceFeedBack(this.m_pPointCatched);
                            if (polyline != null && !polyline.IsEmpty)
                            {
                                if (pDisplayFeedbackMethod == DisplayFeedbackMethod.Polygon)
                                {
                                    this.AddPolylineToPolygon(polyline);
                                    this.AddToFeedback(polyline);
                                }
                                else if (pDisplayFeedbackMethod == DisplayFeedbackMethod.Line)
                                {
                                    this.AddPolylineToPolyline(polyline);
                                    this.AddToFeedback(polyline);
                                    //this.StartFeedback(polyline.ToPoint);
                                }
                            }
                        }
                        else
                        {
                            base.ListSelectableLayer = MapsManager.Instance.MapService.GetAllVisibleLayerInMap();
                            try
                            {
                                this.FillFeatureCache(this.m_pPointCatched);
                            }
                            catch (Exception)
                            { }
                            this.GetBeTracedPolyline();
                            IPolyline polyline = this.AddToTraceFeedBack(this.m_pPointCatched);
                            if (polyline != null && !polyline.IsEmpty)
                            {
                                if (pDisplayFeedbackMethod == DisplayFeedbackMethod.Polygon)
                                {
                                    this.AddPolylineToPolygon(polyline);
                                    this.AddToFeedback(polyline);
                                }
                                else if (pDisplayFeedbackMethod == DisplayFeedbackMethod.Line)
                                {
                                    this.AddPolylineToPolyline(polyline);
                                    this.AddToFeedback(polyline);
                                    //this.StartFeedback(polyline.ToPoint);
                                }
                            }
                        }
                    }
                    else
                    {
                        m_pTraceFeedback = null;
                        switch (pDisplayFeedbackMethod)
                        {
                            case DisplayFeedbackMethod.Polygon:
                                this.AddToFeedback(this.m_pPointCatched);
                                this.AddPointToPolygon(this.m_pPointCatched);
                                break;
                            case DisplayFeedbackMethod.Line:
                                //this.StartFeedback(this.m_pPointCatched);
                                this.AddToFeedback(this.m_pPointCatched);
                                this.AddPointToPolyline(this.m_pPointCatched);
                                break;
                        }
                    }
                }
                else if (this.m_nArcPointCount == 0)
                {
                    IPointCollection pointCollection = this.m_pGeometry as IPointCollection;
                    int pointCount = pointCollection.PointCount;
                    if (pointCount >= 1)
                    {
                        IPoint pPoint = pointCollection.get_Point(pointCount - 1);
                        this.AddToArcFeedback(pPoint);
                        this.AddToArcFeedback(this.m_pPointCatched);
                    }
                    else
                    {
                        this.AddToArcFeedback(this.m_pPointCatched);
                    }
                }
                else if (this.m_nArcPointCount != 1)
                {
                    if (this.m_nArcPointCount == 2)
                    {
                        ICircularArc circularArc = this.AddToArcFeedback(this.m_pPointCatched);
                        if (circularArc != null)
                        {
                            this.AddSegmentToPolygon(circularArc as ISegment);
                            this.AddToFeedback((circularArc as ISegment).ToPoint);
                        }
                    }
                }
                else
                {
                    this.AddToArcFeedback(this.m_pPointCatched);
                }
                if (this.m_pPointCatched != null)
                {
                    this.SketchGeometry.Update();
                }
                this.RefreshForeground(null);
            }
        }
        public override void OnMouseMove(int Button, int Shift, int X, int Y)
        {
            if (Button == 4) return;
            this.m_pPointCatched = this.m_pMapControl.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.RefreshForeground(null);
                //获取绘制点-线
                point = base.SnappingSketch(this.m_pPointCatched, ref strDescription);
                if (point != null)
                {
                    this.m_pPointCatched = point;
                }
            }
            try
            {
                DisplayFeedbackMethod pDisplayFeedbackMethod = this.m_pDisplayFeedbackMethod;
                if (pDisplayFeedbackMethod == DisplayFeedbackMethod.Arc)
                {
                    if (this.m_pNewArcFeedback == null && this.m_pDisplayFeedback != null)
                    {
                        this.m_pDisplayFeedback.MoveTo(this.m_pPointCatched);
                    }
                    if (this.m_pNewArcFeedback != null)
                    {
                        if (this.m_nArcPointCount == 2)
                        {
                            (this.m_pNewArcFeedback as IDisplayFeedback).MoveTo(this.m_pPointCatched);
                        }
                    }
                }
                else
                {
                    if (EditorSettingClass.Instance.IsTraceing && (this.m_pDisplayFeedbackMethod == DisplayFeedbackMethod.Polygon || this.m_pDisplayFeedbackMethod == DisplayFeedbackMethod.Line))
                    {
                        if (this.m_pTraceFeedback == null && this.m_pDisplayFeedback != null)
                        {
                            this.m_pDisplayFeedback.MoveTo(this.m_pPointCatched);
                        }
                        if (this.m_pTraceFeedback != null)
                        {
                            try
                            {
                                this.m_pTraceFeedback.MoveTo(this.m_pPointCatched);
                            }
                            catch (Exception) { }
                            this.RefreshForeground(null);
                        }
                    }
                    else
                    {
                        switch (pDisplayFeedbackMethod)
                        {
                            case DisplayFeedbackMethod.Polygon:
                                this.m_pDisplayFeedback?.MoveTo(this.m_pPointCatched);
                                break;
                            case DisplayFeedbackMethod.Line:
                                this.m_pDisplayFeedback?.MoveTo(this.m_pPointCatched);
                                break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //FormReportException.Report(ex);
                LogAPI.Debug("新增面绘制草图失败:" + ex.Message);
            }
            if (point != null)
            {
                this.m_pSnappingSketchFeedback.Update(point, strDescription);
            }
        }
        public override void Refresh(int hDC)
        {
            this.m_pSnappingFeedback?.Refresh(hDC);
            this.m_pDisplayFeedback?.Refresh(hDC);
            if (EditorSettingClass.Instance.IsTraceing && this.m_pTraceFeedback != null)
            {
                this.m_pTraceFeedback.Refresh(hDC);
            }
        }
        public override void ReStartFeedback()
        {
            IPointCollection pointCollection = null;
            int num = 0;
            if (this.m_pGeometry != null || !this.m_pGeometry.IsEmpty)
            {
                IGeometryCollection geometryCollection = this.m_pGeometry as IGeometryCollection;
                int geometryCount = geometryCollection.GeometryCount;
                if (geometryCount > 0)
                {
                    this.m_pRing = geometryCollection.get_Geometry(geometryCollection.GeometryCount - 1) as IRing;
                    pointCollection = (this.m_pRing as IPointCollection);
                    num = pointCollection.PointCount;
                }
                else
                {
                    this.m_pRing = null;
                }
            }
            this.EndFeedback();
            this.EndArcFeedback();
            this.EndTraceFeedback();
            if (pointCollection != null)
            {
                for (int i = 0; i < num; i++)
                {
                    this.AddToFeedback(pointCollection.get_Point(i));
                }
            }
            this.RefreshForeground(null);
        }
        public override void OnMouseUp(int Button, int Shift, int X, int Y)
        {
            base.OnMouseUp(Button, Shift, X, Y);
        }
        public override void OnKeyDown(int keyCode, int Shift)
        {
            base.OnKeyDown(keyCode, Shift);
        }
        public override void OnKeyUp(int keyCode, int Shift)
        {
            base.OnKeyUp(keyCode, Shift);
        }
        public override void OnDblClick()
        {
            try
            {
                int selectIdZYQ = 1;
                IUcZYQMagrHelper ucZYQMagrHelper = null;
                if (MapsManager.Instance.MapService.GetProjectInfo() is ProjectInfo ProInfo && ProInfo.ProjType == EnumProjType.BHTBTQ && Platform.Instance.SystemType == SystemTypeEnum.BGFWCG)
                {
                    ucZYQMagrHelper = BundleRuntime.Instance.GetFirstOrDefaultService();
                    if (ucZYQMagrHelper != null)
                    {
                        selectIdZYQ = ucZYQMagrHelper.GetCheckedID();
                    }
                }
                FinishSketch();
                if (ucZYQMagrHelper != null)
                {
                    ucZYQMagrHelper.AddMask(selectIdZYQ);
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("新增面‘OnDblClick’操作异常:" + ex.Message);
                MessageHelper.ShowError("新增面‘OnDblClick’操作异常:" + ex);
            }
        }
        public void FinishSketch()
        {
            this.EndFeedback();
            this.EndArcFeedback();
            this.EndTraceFeedback();
            if (m_pGeometry is IPolygon)
            {
                if (!(m_pGeometry as IPolygon).IsClosed)
                {
                    (m_pGeometry as IPolygon).Close();
                }
                (this.m_pGeometry as IPolygon).SimplifyPreserveFromTo();
                if (!this.m_pGeometry.IsEmpty)
                {
                    DrawGeometry();
                }
            }
            else if (m_pGeometry is IPolyline)
            {
                if (!this.m_pGeometry.IsEmpty)
                {
                    IPolyline polyline = this.m_pGeometry as IPolyline;
                    polyline.SimplifyNetwork();
                    DrawGeometry();
                }
            }
            if (EditorSettingClass.Instance.OnDrawEnd != null)
            {
                EditorSettingClass.Instance.OnDrawEnd(this, this.m_pGeometry);
            }
            if (this.m_pGeometry != null)
                System.Runtime.InteropServices.Marshal.ReleaseComObject(this.m_pGeometry);
            if (m_pPath != null)
                System.Runtime.InteropServices.Marshal.ReleaseComObject(this.m_pPath);
            if (m_pRing != null)
                System.Runtime.InteropServices.Marshal.ReleaseComObject(this.m_pRing);
            this.m_pGeometry = null;
            if (this.m_pRing != null)
                System.Runtime.InteropServices.Marshal.ReleaseComObject(this.m_pRing);
            this.m_pRing = null;
            if (this.m_pPath != null)
                System.Runtime.InteropServices.Marshal.ReleaseComObject(this.m_pPath);
            this.m_pPath = null;
            if (this.SketchGeometry != null)
            {
                this.SketchGeometry.Deactivate();
                this.SketchGeometry = null;
            }
            this.RefreshForeground(null);
        }
        public void DrawGeometry()
        {
            try
            {
                if (!((m_pEditor as EngineEditorClass).TargetLayer is IFeatureLayer featureLayer) || featureLayer.FeatureClass == null)
                {
                    return;
                }
                IEngineEditSketch editSketch = m_pEditor as IEngineEditSketch;
                //IGeometry geometry = m_pGeometry;
                //geometry.SpatialReference = m_pHookHelper.FocusMap.SpatialReference;
                //if (RegionAuthorize == null)
                //{
                //    RegionAuthorize = new RegionAuthorize();
                //}
                if (density == null)
                {
                    density = new VerificationOfFeatureNodeDensity(m_pHookHelper);
                }
                //验证区域授权
                //if (!RegionAuthorize.ValidateAuthorize(geometry))
                //{
                //    MessageHelper.ShowError("绘制图形不在授权区域范围内!");
                //    //模拟点击Backspace按键,目的清除当前绘制对象
                //    OnKeyDown((int)ConsoleKey.Backspace, 0);
                //    //editSketch.FinishSketch();
                //    //ControlsEditingClearCommandClass pControlsEditingClearCommandClass = new ControlsEditingClearCommandClass();
                //    //pControlsEditingClearCommandClass.OnCreate(m_pHookHelper.Hook);
                //    //pControlsEditingClearCommandClass.OnClick();
                //    return;
                //}
                m_pGeometry = density.Verification(m_pGeometry);
                //判断绘制的图形是否在目标图层数据范围内
                double xmin = 0;
                double xmax = 0;
                double ymin = 0;
                double ymax = 0;
                //判断绘制的图形是否在目标图层数据范围内
                if ((featureLayer.FeatureClass as IGeoDataset) != null && (featureLayer.FeatureClass as IGeoDataset).SpatialReference != null)
                {
                    (featureLayer.FeatureClass as IGeoDataset).SpatialReference.GetDomain(out xmin, out xmax, out ymin, out ymax);
                    IEnvelope enveloe = new Envelope() as IEnvelope;
                    enveloe.XMin = xmin;
                    enveloe.XMax = xmax;
                    enveloe.YMin = ymin;
                    enveloe.YMax = ymax;
                    if (!FeatureAPI.IsContains(enveloe, m_pGeometry))
                    {
                        MessageHelper.ShowTips("绘制图形超出目标图层范围!");
                        editSketch.Geometry = null;
                        editSketch.RefreshSketch();
                        this.m_pHookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewBackground, null, this.m_pHookHelper.ActiveView.Extent);
                        return;
                    }
                }
                //if ((featureLayer.FeatureClass as IGeoDataset) != null && !KGIS.Framework.AE.FeatureAPI.IsContains((featureLayer.FeatureClass as IGeoDataset).Extent, geometry))
                //{
                //    System.Windows.Forms.MessageBox.Show("绘制图形超出目标图层范围!", "系统提示:", System.Windows.Forms.MessageBoxButtons.OK);
                //    editSketch.Geometry = null;
                //    editSketch.RefreshSketch();
                //    this.m_pHookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewBackground, null, this.m_pHookHelper.ActiveView.Extent);
                //    return;
                //}
                //editSketch.FinishSketch();
                //ControlsUndoCommand undo = new ControlsUndoCommand();
                //undo.OnCreate(m_pHookHelper.Hook);
                //undo.OnClick();
                //开始记录操作
                m_pEditor.StartOperation();
                #region
                //IIdentify identify = featureLayer as IIdentify;
                //IArray iarray = identify.Identify(geometry);
                //for (int i = 0; i < iarray.Count; i++)
                //{
                //    IFeatureIdentifyObj pFeatIdObj = iarray.get_Element(i) as IFeatureIdentifyObj;
                //    IRowIdentifyObject pRowObj = pFeatIdObj as IRowIdentifyObject;
                //    IFeature newFeature = pRowObj.Row as IFeature;
                //    ITopologicalOperator topOper = newFeature.ShapeCopy as ITopologicalOperator;
                //    IGeometry geometryNew = topOper.Difference(geometry);
                //    newFeature.Shape = geometryNew;
                //    newFeature.Store();
                //}
                //IFeature featureNew = featureLayer.FeatureClass.CreateFeature();
                //if (selectPointLayer != null)
                //{
                //    ISpatialFilter filter = new SpatialFilterClass();
                //    filter.Geometry = geometry;
                //    IFeatureCursor featureCursor = selectPointLayer.FeatureClass.Search(filter, false);
                //    IFeature lxdw = featureCursor.NextFeature();
                //    for (int i = 0; i < lxdw.Fields.FieldCount; i++)
                //    {
                //        string fieldName = lxdw.Fields.Field[i].Name;
                //        if (fieldName.ToUpper() == "OBJECTID" || fieldName.ToUpper() == "FID" || fieldName.ToUpper() == "SHAPE")
                //        {
                //            continue;
                //        }
                //        int fieldIndex = featureNew.Fields.FindField(fieldName);
                //        if (fieldIndex < 0) continue;
                //        featureNew.Value[fieldIndex] = lxdw.Value[i];
                //    }
                //}
                //featureNew.Shape = geometry;
                //featureNew.Store();
                #endregion
                IFeatureSelection featureSelection = featureLayer as IFeatureSelection;
                featureSelection.Clear();
                //IFeatureLayer selectFeatureLayer = Env.Instance.KMap.GetFeatureLayerByName(this.m_pHookHelper.ActiveView.FocusMap, Env.Instance.DefaultValue.ED_DLTB_TableName) as IFeatureLayer;
                //IFeatureLayer selectFeatureLayer = Env.Instance.KMap.GetFeatureLayerByName(this.m_pHookHelper.ActiveView.FocusMap, "LXDW") as IFeatureLayer;
                //if (selectFeatureLayer == null || selectFeatureLayer.FeatureClass == null)
                //{
                //    selectFeatureLayer = Env.Instance.KMap.GetFeatureLayerByName(this.m_pHookHelper.ActiveView.FocusMap, Env.Instance.DefaultValue.DLTB_TableName) as IFeatureLayer;
                //}
                //替换Env改动
                //IFeatureLayer selectFeatureLayer = Env.Instance.KMap.GetFeatureLayerByName(Env.Instance.DefaultValue.DLTB_TableName);
                IFeatureLayer selectFeatureLayer = (m_pEditor as EngineEditorClass).TargetLayer as IFeatureLayer;// _MapService.GetFeatureLayerByName(//Env.Instance.DefaultValue.DLTB_TableName);
                if (selectFeatureLayer != null && selectFeatureLayer.FeatureClass != null)
                {
                    #region
                    //GenerateNewFeature(geometry, selectFeatureLayer.FeatureClass)为geometry裁剪后的图形,不符合 需求
                    //按权属分割、合并图斑
                    //List GeoList = FeatureAPI.GenerateNewFeature(geometry, selectFeatureLayer.FeatureClass);
                    //if (GeoList == null || GeoList.Count <= 0)
                    //{
                    //    GeoList.Add(geometry);
                    //    //DrawFeature(featureLayer.FeatureClass, geometry, featureSelection);
                    //}
                    #endregion
                    List GeoList = new List();
                    GeoList.Add(m_pGeometry);
                    //------------------
                    IIdentify identify = featureLayer as IIdentify;
                    List featureList = new List();
                    bool isSplit;
                    int splitIndex, segIndex;
                    for (int k = 0; k < GeoList.Count; k++)
                    {
                        IGeometry item = GeoList[k];
                        if (item.IsEmpty)
                            continue;
                        ITopologicalOperator2 topologicalOperator2 = item as ITopologicalOperator2;
                        //调用Simplify()方法使IsSimple和IsKnownSimple属性都为true
                        topologicalOperator2.Simplify();
                        IPolyline pPolyline = topologicalOperator2.Boundary as IPolyline;
                        item.SpatialReference = this.m_pHookHelper.FocusMap.SpatialReference;
                        if (identify != null)
                        {
                            IArray iarray = identify.Identify(item);
                            if (iarray != null)
                            {
                                for (int i = 0; i < iarray.Count; i++)
                                {
                                    IFeatureIdentifyObj pFeatIdObj = iarray.get_Element(i) as IFeatureIdentifyObj;
                                    IRowIdentifyObject pRowObj = pFeatIdObj as IRowIdentifyObject;
                                    IFeature newFeature = pRowObj.Row as IFeature;
                                    newFeature.Shape.SpatialReference = this.m_pHookHelper.FocusMap.SpatialReference;
                                    ITopologicalOperator topOper = newFeature.ShapeCopy as ITopologicalOperator;
                                    topOper.Simplify();
                                    IGeometry geometryNew = topOper.Difference(item);
                                    if (geometryNew.IsEmpty)
                                    {
                                        continue;
                                    }
                                    newFeature.Shape = geometryNew;
                                    newFeature.Store();
                                    SplitMultipartFeature(new List() { newFeature }, item, featureSelection);
                                    IPointCollection pointCollection = geometryNew as IPointCollection;
                                    for (int j = 0; j < pointCollection.PointCount; j++)
                                    {
                                        //if (KGIS.Framework.AE.FeatureAPI.IsInterSect(pointCollection.get_Point(j) as IGeometry, item))
                                        //{
                                        //    pPolyline.SplitAtPoint(pointCollection.get_Point(j), false, false, out isSplit, out splitIndex, out segIndex);
                                        //}
                                    }
                                    item = FeatureAPI.ConstructPolygonFromPolyline(pPolyline);
                                }
                            }
                        }
                        ////白明雅 2020-04-01
                        //if (dataCheckService != null)
                        //{
                        //    dataCheckService.GeometryCheck(item, featureLayer);
                        //}
                        DrawFeature(featureLayer.FeatureClass, item, featureSelection);
                    }
                    #region 打开数据检查助手
                    //替换Env改动
                    //if (Env.Instance.Platfrom.WinFeatureCheck != null)
                    //{
                    //    (Env.Instance.Platfrom.WinFeatureCheck as CheckAssistant).InitData(featureList);
                    //}
                    #endregion
                }
                else
                {
                    //if (dataCheckService != null)
                    //{
                    //    dataCheckService.GeometryCheck(m_pGeometry, featureLayer);
                    //}
                    DrawFeature(featureLayer.FeatureClass, m_pGeometry, featureSelection);
                }
                //结束记录操作
                m_pEditor.StopOperation("DRAWLX");
                //模拟点击Backspace按键,目的清除当前绘制对象
                OnKeyDown((int)ConsoleKey.Backspace, 0);
                //**************************************************************************
                //增加通知要素属性窗体刷新功能
                //**************************************************************************
                //Env.Instance.Platfrom.NotifyMsg.SetNotifyMsg(new Common.Interface.NotifyMsgPackage() { MsgType = "RefreshFeatureAttribute" });//暂时注销,待改回
                this.m_pHookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewBackground | esriViewDrawPhase.esriViewGeoSelection, null, this.m_pHookHelper.ActiveView.Extent);
                //KGIS.Common.Utility.CustomLogAPI.WriteSystemOperationLog("数据增加", "画零星面");
            }
            catch (Exception ex)
            {
                LogAPI.Debug("画零星面 期间 鼠标双击 时异常,异常信息如下:");
                LogAPI.Debug(ex);
                LogAPI.Debug("画零星面 期间 鼠标双击 时异常信息结束");
                MessageHelper.ShowError("绘制失败:" + ex.Message);
            }
        }
        private void DrawFeature(IFeatureClass pFeatureClass, IGeometry geometry, IFeatureSelection featureSelection)
        {
            /*
             * 修改bug:画零星面,出现多条只有属性、没有图形数据
             */
            if (geometry == null || geometry.IsEmpty)
            {
                return;
            }
            IFeature feature = pFeatureClass.CreateFeature();
            //IPointCollection ps = geometry as IPointCollection;
            //List pList = new List();
            //for (int i = 0; i < ps.PointCount; i++)
            //{
            //    pList.Add(ps.Point[i]);
            //}
            //IPoint p = GetGravityPoint(pList);
            //ps.AddPoint(p);
            feature.Shape = geometry;
            feature.Shape.SpatialReference = m_pHookHelper.FocusMap.SpatialReference;
            feature.Store();
            SplitMultipartFeature(new List() { feature }, geometry, featureSelection);
        }
        public void SplitMultipartFeature(List SelectedFeature, IGeometry drawGeometry, IFeatureSelection featureSelection)
        {
            try
            {
                foreach (IFeature item in SelectedFeature)
                {
                    IGeometry geo = item.ShapeCopy;
                    ITopologicalOperator topologicalOperator = geo as ITopologicalOperator;
                    if (topologicalOperator == null) continue;
                    topologicalOperator.Simplify();
                    if (item.ShapeCopy.GeometryType == esriGeometryType.esriGeometryPolygon)
                    {
                        if ((topologicalOperator as IPolygon4) == null || (topologicalOperator as IPolygon4).ExteriorRingCount <= 0)
                        {
                            continue;
                        }
                        //外环图形
                        if (!((topologicalOperator as IPolygon4).ExteriorRingBag is GeometryBag ExterGeometryBag)) continue;
                        //IGeometry firstGeo = null;
                        IGeometryCollection ExterRingGeometryCollection = ExterGeometryBag as IGeometryCollection;
                        for (int i = 0; i < ExterRingGeometryCollection.GeometryCount; i++)
                        {
                            IGeometryCollection geometry = new PolygonClass() as IGeometryCollection;
                            IGeometry ExterGeometry = ExterRingGeometryCollection.get_Geometry(i);
                            if (ExterGeometry != null && !ExterGeometry.IsEmpty)
                            {
                                geometry.AddGeometry(ExterGeometry);
                            }
                            else
                            {
                                continue;
                            }
                            //内环图形
                            IGeometryBag InteriorBag = (topologicalOperator as IPolygon4).get_InteriorRingBag(ExterGeometry as IRing);
                            if (InteriorBag != null)
                            {
                                IGeometryCollection InteriorRingGeometryCollection = InteriorBag as IGeometryCollection;
                                if (InteriorRingGeometryCollection == null) continue;
                                for (int IG = 0; IG < InteriorRingGeometryCollection.GeometryCount; IG++)
                                {
                                    IGeometry interiorGeo = InteriorRingGeometryCollection.get_Geometry(IG);
                                    if (interiorGeo != null && !interiorGeo.IsEmpty)
                                    {
                                        geometry.AddGeometry(interiorGeo);
                                    }
                                }
                            }
                            if (i == 0)
                            {
                                item.Shape = geometry as IGeometry;
                                item.Store();
                                if (FeatureAPI.IsContains(drawGeometry, item.ShapeCopy))
                                {
                                    //ISpatialReference s = item.ShapeCopy.SpatialReference;
                                    //var n = s.Name;
                                    //属性继承
                                    //KGIS.Tools.Utility.FeatureHelper.SetFeatureAttributeNew(item);//以后待改回
                                    featureSelection.Add(item);
                                }
                            }
                            else
                            {
                                IFeature newFeaturte = (item.Class as IFeatureClass).CreateFeature();
                                IFeatureEdit pFeatureEdit = item as IFeatureEdit;
                                pFeatureEdit.SplitAttributes(newFeaturte);
                                (geometry as IGeometry).SpatialReference = item.ShapeCopy.SpatialReference;
                                newFeaturte.Shape = geometry as IGeometry;
                                newFeaturte.Store();
                                if (KGIS.Framework.AE.FeatureAPI.IsContains(drawGeometry, newFeaturte.ShapeCopy))
                                {
                                    //属性继承
                                    //KGIS.Tools.Utility.FeatureHelper.SetFeatureAttributeNew(newFeaturte);//以后待改回
                                    featureSelection.Add(newFeaturte);
                                }
                            }
                        }
                        //if (firstGeo != null)
                        //{
                        //    firstGeo.SpatialReference = item.ShapeCopy.SpatialReference;
                        //    item.Shape = firstGeo;
                        //    item.Store();
                        //}
                    }
                    else if (item.ShapeCopy.GeometryType == esriGeometryType.esriGeometryPolyline)
                    {
                        IGeometryCollection pGeocoll = geo as IGeometryCollection;
                        int geomcount = pGeocoll.GeometryCount;
                        if (geomcount > 1)
                        {
                            for (int k = 1; k < geomcount; k++)
                            {
                                IFeature newFeaturte = (item.Class as IFeatureClass).CreateFeature();
                                IFeatureEdit pFeatureEdit = item as IFeatureEdit;
                                pFeatureEdit.SplitAttributes(newFeaturte);
                                IGeometry newGeom = pGeocoll.get_Geometry(k);
                                IPointCollection points = newGeom as IPointCollection;
                                IPointCollection line = new PolylineClass();
                                for (int i = 0; i < points.PointCount; i++)
                                {
                                    line.AddPoint(points.get_Point(i));
                                }
                                newGeom = line as IGeometry;
                                newGeom.SpatialReference = item.ShapeCopy.SpatialReference;
                                newFeaturte.Shape = newGeom;
                                newFeaturte.Store();
                            }
                            IGeometry newGeom2 = pGeocoll.get_Geometry(0);
                            IPointCollection points2 = newGeom2 as IPointCollection;
                            IPointCollection line2 = new PolylineClass();
                            for (int i = 0; i < points2.PointCount; i++)
                            {
                                line2.AddPoint(points2.get_Point(i));
                            }
                            newGeom2 = line2 as IGeometry;
                            newGeom2.SpatialReference = item.ShapeCopy.SpatialReference;
                            item.Shape = newGeom2;
                            item.Store();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("画零星面 期间 拆分多部件要素 时异常,异常信息如下:");
                LogAPI.Debug(ex);
                LogAPI.Debug("画零星面 期间 拆分多部件要素 时异常信息结束");
                throw ex;
            }
        }
        private IPoint GetGravityPoint(List lstPol)
        {
            double n, i;
            double x1, y1, x2, y2, x3, y3;
            double sum_x = 0, sum_y = 0, sum_s = 0;
            //n = int.Parse(Console.ReadLine());
            //x1 = int.Parse(Console.ReadLine());
            //y1 = int.Parse(Console.ReadLine());
            //x2 = int.Parse(Console.ReadLine());
            //y2 = int.Parse(Console.ReadLine());
            x1 = lstPol[0].X;
            y1 = lstPol[0].Y;
            x2 = lstPol[1].X;
            y2 = lstPol[1].Y;
            n = lstPol.Count;
            int k = 2;
            for (i = 1; i <= n - 2; i++)
            {
                //x3 = int.Parse(Console.ReadLine());
                //y3 = int.Parse(Console.ReadLine());
                x3 = lstPol[k].X;
                y3 = lstPol[k].Y;
                double s = ((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) / 2.0;
                sum_x += (x1 + x2 + x3) * s;
                sum_y += (y1 + y2 + y3) * s;
                sum_s += s;
                x2 = x3;
                y2 = y3;
                k++;
            }
            Console.WriteLine("重心为:%.2lf , %.2lf\n", sum_x / sum_s / 3.0, sum_y / sum_s / 3.0);
            IPoint result = new PointClass() { X = sum_x / sum_s / 3.0, Y = sum_y / sum_s / 3.0 };
            return result;
        }
    }
}