浏览代码

xls:元空间代码逻辑调整1.0,。精简MBICommand文件

xulisong 6 年之前
父节点
当前提交
6075435897

+ 0 - 112
MBI/SAGA.GplotRelationComputerManage/ComputerVerticalPipe.cs

@@ -74,120 +74,8 @@ namespace SAGA.GplotRelationComputerManage
             return result;
         }
 
-        /// <summary>
-        /// 显示主立管数据
-        /// </summary>
-        public void ShowDatas(WinDrawEndPoint win)
-        {
-            var datas = DrawDataServer.GetData<VerticalPipeData>();
-
-           // var win = new WinDrawData();
-
-            win.LoadData = () =>
-            {
-                var canvas = win.GetCanvas;
-                GetBoundary(datas, canvas);
-
-                //坐标的Y轴对应Z坐标,Z坐标按实际尺寸来
-
-                #region 画标高
-
-                var levelLength = canvas.ActualWidth - 200;
-                for (int i = 0; i < datas.Levels.Count; i++)
-
-                {
-                    double y = datas.Levels[i].Elevation;
-                    SgLine line = new SgLine(new System.Windows.Point(100, y),
-                        new System.Windows.Point(levelLength + 100, y));
-                    canvas.Children.Add(line);
-
-                    var txt = new TextBlock()
-                    {
-                        Text = datas.Levels[i].Name,
-                    };
-                    Canvas.SetLeft(txt, levelLength + 100);
-                    Canvas.SetTop(txt, y);
-                    canvas.Children.Add(
-                        txt
-                    );
-                }
-
-
-                #endregion
-
-                #region 画立管
-
-                //根据坐标将立管进行分组
-                //var groupDatas = datas.Datas.GroupBy(t => new {t.DownPoint3D.X, t.DownPoint3D.Y});
-
-
-
-                var groupDatas = datas.Datas.GroupBy(t => new
-                {
-                   X= Math.Round(t.DownPoint3D.X, 1), Y=Math.Round( t.DownPoint3D.Y,1)
-                });
 
-                var index = 0;
-                var seq = 100;
-                foreach (var groupData in groupDatas)
-                {
-                    Logs.Log(groupData.Key.ToString());
-                    var x = 120 + seq * index;
-                    foreach (var data in groupData)
-                    {
-                        var line = new SgLine(new Point(x, data.UpPoint3D.Z), new Point(x, data.DownPoint3D.Z));
-                        canvas.Children.Add(line);
-                    }
 
-                    index++;
-                }
-            };
-            win.ShowDialog();
-
-            #endregion
-        }
-
-        /// <summary>
-        /// 获取数据的边界值
-        /// </summary>
-        void GetBoundary(VerticalPipeData data, Canvas canvas)
-        {
-            //Revit坐标与wpf的Y坐标相反,WPF Y向下
-            var xs = new List<double>();
-
-            data.Levels.ForEach(l =>
-            {
-                xs.Add(-l.Elevation);
-            });
-            data.Datas.ForEach(p =>
-             {
-                 xs.Add(-p.DownPoint3D.Z);
-                 xs.Add(-p.UpPoint3D.Z);
-             });
-
-
-            if (xs.Count == 0) return;
-            var m_maxX = xs.Max();
-            var m_minX = xs.Min();
-
-            var scale = (m_maxX - m_minX) / (canvas.ActualHeight-100);
-
-            //将Z轴所有坐标改为
-
-            data.Levels.ForEach(l =>
-            {
-                Logs.Log($"{l.Elevation}===={(l.Elevation - m_minX) / scale}");
-                l.Elevation = (-l.Elevation - m_minX) / scale;
-            });
-
-            data.Datas.ForEach(p =>
-           {
-               p.DownPoint3D =new Point3D(p.DownPoint3D.X,p.DownPoint3D.Y,
-                   (-p.DownPoint3D.Z - m_minX) / scale);
-               p.UpPoint3D = new Point3D(p.UpPoint3D.X,p.UpPoint3D.Y,
-                   (-p.UpPoint3D.Z - m_minX) / scale);
-           });
-        }
         Point3D Convert3DToWin(XYZ xyz)
         {
             return new Point3D(xyz.X, xyz.Y, xyz.Z);

+ 4 - 227
MBI/SAGA.MBI/Command.cs

@@ -383,7 +383,7 @@ namespace SAGA.MBI
     /// </summary>
     [Transaction(TransactionMode.Manual)]
     [Regeneration(RegenerationOption.Manual)]
-    public class CreateSpaceCommand : ExternalCommand, IExternalCommandAvailability
+    public class CreateSpaceCommand : ExternalCommand
     {
         public override Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
         {
@@ -393,238 +393,15 @@ namespace SAGA.MBI
             return Result.Succeeded;
         }
 
-        /// <summary>
-        /// 创建空间分隔符
-        /// </summary>
-        /// <param name="doc"></param>
-        /// <param name="virLines"></param>
-        /// <param name="deletedPolylines"></param>
-        public void CreateSpaceSeqarate(Document doc, List<PointPair> virLines, List<int> deletedPolylines)
-        {
-            using (Transaction trans = new Transaction(doc, "创建空间分隔符"))
-            {
-                trans.Start();
-                try
-                {
-                    FailureHandlingOptions fho = trans.GetFailureHandlingOptions();
-                    fho.SetFailuresPreprocessor(new FailuresPreprocessor(false));//这里不对冲突进行捕捉,创建空间的时候会重新捕捉
-                    trans.SetFailureHandlingOptions(fho);
-
-                    //读取空间所在视图
-                    var view = doc.GetElements<ViewPlan>().FirstOrDefault(t =>
-                        t.Name?.IndexOf("-saga") > -1 && t.ViewType == ViewType.FloorPlan);
-
-                    if (view == null)
-                    {
-                        MessageBox.Show("无法找到-saga标志的视图");
-                        return;
-                    }
-                    //创建空间分隔符
-                    CreateSpaceSeparationLines(view, doc, virLines);
-
-                    //删除已有的空间分隔符
-
-                    doc.Delete(deletedPolylines.Select(id => new ElementId(id)).ToList());
-
-                    trans.Commit();
-
-                }
-                catch (Exception e)
-                {
-                    trans.RollBack();
-                }
-            }
-        }
-
-        /// <summary>
-        /// 自动创建空间
-        /// </summary>
-        public void AutoCreateSpaces()
-        {
-            string SpaceKey = "UKJ";
-            string ASpaceKey = "UAKJ";
-            IntPtr mainWindowHandle = RevitProcess.GetMainWindowHandle();
-            PressHelper.KeyPress(mainWindowHandle, SpaceKey);
-
-            ////发送自动放置空间
-            PressHelper.KeyPress(mainWindowHandle, ASpaceKey);
-            //ESC
-            PressHelper.KeyPress(mainWindowHandle, (char)27);
-            PressHelper.KeyPress(mainWindowHandle, (char)27);
-            PressHelper.KeyPress(mainWindowHandle, (char)27);
-        }
-
-        /// <summary>
-        /// 创建空间分隔符
-        /// </summary>
-        /// <param name="view"></param>
-        /// <param name="doc"></param>
-        /// <param name="pairs"></param>
-        public static void CreateSpaceSeparationLines(ViewPlan view, Document doc, List<PointPair> pairs)
-        {
-            double z = view.GenLevel.Elevation;
-
-            //创建
-            XYZ axis = XYZ.BasisZ;
-            XYZ vecX = XYZ.BasisX;
-            XYZ normal = vecX.CrossProduct(vecX.VectorRotate(axis, Math.PI / 2));
-            Plane p = new Plane(normal, XYZ.Zero);
-            var sp = SketchPlane.Create(doc, p);
-
-            foreach (var pair in pairs)
-            {
-                var curveArray = new CurveArray();
-                XYZ start = pair.RPoint[0].NewZ(z);
-                XYZ end = pair.RPoint[1].NewZ(z);
-                Line line = null;
-                try
-                {
-                    line = start.NewLine(end);
-                }
-                catch (Exception e)
-                {
-                    Console.WriteLine(e.StackTrace);
-                }
-                if (line != null)
-                {
-                    curveArray.Append(line);
-                    var newLIneId = doc.Create.NewSpaceBoundaryLines(sp, curveArray, view).get_Item(0).Id;
-                    pair.ElementId = newLIneId.IntegerValue;
-                    if (pair.ShowLine != null)
-                        pair.ShowLine.Tag = newLIneId.IntegerValue;
-                }
-            }
-        }
-
-
-
-        public bool IsCommandAvailable(UIApplication applicationData, CategorySet selectedCategories)
+          
+        public override bool IsCommandAvailable(UIApplication applicationData, CategorySet selectedCategories)
         {
             return true;
         }
 
-        /// <summary>
-        /// 手动创建空间
-        /// </summary>
-        /// <param name="doc"></param>
-        public void CreateSpace(Document doc)
-        {
-            using (Transaction trans = new Transaction(doc, "创建空间"))
-            {
-                {
-                    trans.Start();
-                    try
-                    {
-                        //检测是否有空间标记,没有空间标记加载
-                        //doc.LoadFamilySymbolExt(@"C:\ProgramData\Autodesk\RVT 2016\Libraries\China\注释\标记\机械\空间标记.rfa");
-                        doc.LoadFamilySymbolExt(MBIConst.SpaceTagFamilyFilePath);
-
-                        FailureHandlingOptions fho = trans.GetFailureHandlingOptions();
-                        fho.SetFailuresPreprocessor(new FailuresPreprocessor());
-                        trans.SetFailureHandlingOptions(fho);
-
-
-                        var view = doc.GetElements<ViewPlan>().FirstOrDefault(t =>
-                            t.GenLevel?.Name != null && t.Name?.IndexOf("-saga") > -1 &&
-                            t.ViewType == ViewType.FloorPlan);
-
-
-                        if (view != null)
-                        {
-                            Parameter para = view.get_Parameter(Autodesk.Revit.DB.BuiltInParameter.VIEW_PHASE);
-                            Autodesk.Revit.DB.ElementId phaseId = para.AsElementId();
-
-                            var phase = doc.GetElement(phaseId) as Phase;
-                            var level = view.GenLevel;
-                            //如果视图范围不对,也不能很好的创建空间
-
-                            ICollection<ElementId> elements = doc.Create.NewSpaces2(level, phase, view);
-                            //创建20个未放置的空间
-                            //var spaces=   doc.Create.NewSpaces2(phase, 20);
-                            //if (elements == null) MessageBox.Show("无法创建空间,请检查视图范围是否正确!");
-
-                        }
-                        else
-                        {
-                            Autodesk.Revit.UI.TaskDialog.Show("Revit", "没有找到名称以-saga结尾的平面");
-                        }
-
-
-                        doc.Regenerate();
-                        trans.Commit();
-                    }
-                    catch (Exception e)
-                    {
-                        trans.RollBack();
-                        MessageShow.Show(e);
-                    }
-                }
-            }
-        }
-    }
-
-    /// <summary>
-    /// 存储静态冲突数据
-    /// </summary>
-    public class StaticData
-    {
-        public static List<List<ElementId>> FailuresPreprocessorData = new List<List<ElementId>>();
+     
     }
     /// <summary>
-    /// 事务冲突处理
-    /// </summary>
-    public class FailuresPreprocessor : IFailuresPreprocessor
-    {
-        readonly bool m_isAdd;
-        public FailuresPreprocessor(bool isAdd = true)
-        {
-            m_isAdd = isAdd;
-        }
-        public FailureProcessingResult PreprocessFailures(FailuresAccessor failuresAccessor)
-        {
-            IList<FailureMessageAccessor> listFma = failuresAccessor.GetFailureMessages();
-            if (listFma.Count == 0)
-                return FailureProcessingResult.Continue;
-            foreach (FailureMessageAccessor  fma in listFma)
-            {
-                if (fma.GetSeverity() == FailureSeverity.Error)
-                {
-                    if (fma.HasResolutions())
-                        failuresAccessor.ResolveFailure(fma);
-                }
-                if (fma.GetSeverity() == FailureSeverity.Warning)
-                {
-                    if (m_isAdd)
-                    {
-                        var doc = failuresAccessor.GetDocument();
-                        //获取所有的冲突element
-                        var elementIds = fma.GetFailingElementIds();
-                        StaticData.FailuresPreprocessorData.Add(elementIds.ToList());
-                    }
-
-                    failuresAccessor.DeleteWarning(fma);
-                }
-            }
-
-
-            return FailureProcessingResult.ProceedWithCommit;
-        }
-    }
-    /// <summary>
-    /// 输出日志,调试用
-    /// </summary>
-    public class Logs
-    {
-        public static void Log(string msg)
-        {
-            var logs = $"{DateTime.Now}======={msg}";
-            System.Diagnostics.Debug.WriteLine(logs);
-            // WriteLogs(logs);
-
-        }
-    }
-
-    /// <summary>
     /// 同步模型本地名称
     /// </summary>
     [Transaction(TransactionMode.Manual)]

+ 11 - 8
MBI/SAGA.MBI/WinView/Space/FloorSpaceContext.cs

@@ -77,8 +77,9 @@ namespace SAGA.MBI.WinView
         /// <summary>
         /// 创建空间
         /// </summary>
-        public void CreateSpaces()
+        public bool CreateSpaces()
         {
+            bool flag = true;
             #region 描述
 
             /*
@@ -100,34 +101,36 @@ namespace SAGA.MBI.WinView
                     tran.SetFailureHandlingOptions(fho);
 
                     #region 创建空间
-
                     spacePreprocessor.SetOperate(true);
                     tran.Start();
                     SpaceManager.CreateSpace(document);
-
                     tran.Commit(); //提交获取冲突代码
-
                     #endregion
 
                     #region 冲突处理代码
-
                     spacePreprocessor.SetOperate(false);
                     tran.Start();
-
-
+                    SpaceManager.DealSpaceFailuresPreprocessor(document,spacePreprocessor.Items,this);
                     tran.Commit();
 
                     #endregion
                 }
                 catch (Exception ex)
                 {
-
+                    tran.RollBack();
+                    flag = false;
                     MessageShow.Show(ex);
                 }
 
             }
+            return flag;
         }
 
         #endregion
+
+        public void UpdateSpaceSeqaration(List<SpaceSeparation> separations,List<int> deletedIds)
+        {
+            SpaceManager.UpdateSpaceSequaration(Document, separations, deletedIds);
+        }
     }
 }

+ 0 - 2
MBI/SAGA.MBI/WinView/Space/ServerSpace.cs

@@ -7,9 +7,7 @@ namespace SAGA.MBI.WinView.Space {
   
     public class ServerSpace:ModelBase
     {
-
         private string m_Name;
-
         public string Name
         {
             get

+ 170 - 6
MBI/SAGA.MBI/WinView/Space/SpaceManager.cs

@@ -9,12 +9,17 @@ using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
+using System.Text.RegularExpressions;
 using System.Threading.Tasks;
 using Autodesk.Revit.DB;
+using Autodesk.Revit.DB.Architecture;
+using SAGA.DotNetUtils;
 using SAGA.MBI.Common;
 using SAGA.MBI.Model;
+using SAGA.MBI.WinView.Space;
 using SAGA.RevitUtils;
 using SAGA.RevitUtils.Extends;
+using RSpace=Autodesk.Revit.DB.Mechanical.Space;
 
 namespace SAGA.MBI.WinView
 {
@@ -23,7 +28,22 @@ namespace SAGA.MBI.WinView
     /// </summary>
     public class SpaceManager
     {
-      
+        public const string NewCreateSpaceFlag = "不保留已有空间,创建新空间";
+
+        public static bool IsNewSpaceFlag(ServerSpace space)
+        {
+            return space?.Name == NewCreateSpaceFlag;
+        }
+
+        /// <summary>
+        /// 获取元素Id
+        /// </summary>
+        /// <param name="space"></param>
+        /// <returns></returns>
+        public static string GetElementId(MSpace space)
+        {
+            return space.BimID.Split(':')[1];
+        }
 
         /// <summary>
         /// 更新项目中的空间分割
@@ -121,19 +141,163 @@ namespace SAGA.MBI.WinView
         /// 处理冲突信息
         /// </summary>
         /// <param name="doc"></param>
-        /// <param name="failItem"></param>
-        public static void DealSpaceFailuresPreprocessor(Document doc, List<FailItem> failItem)
+        /// <param name="failItems"></param>
+        /// <param name="context">楼层上下文</param>
+        public static void DealSpaceFailuresPreprocessor(Document doc, List<FailItem> failItems,FloorSpaceContext context)
         {
-            //处理错误空间,会出现手动交互的情况
+            #region 处理逻辑
+            /*
+             * 1、根据条件过滤,满足自动处理的自动处理。
+             * 2、不满足自动处理的,手动选择保留项
+             */
+            #endregion
+            List<ServerSpace> serverSpaces = new List<ServerSpace>();
+            Regex regex = new Regex(@"^\d+$");
+
+            var index = 1;
+            foreach (var failItem in failItems)
+            {
+             
+                var spacesServerInfo =context.GetPhysicalSpaces(failItem.Select(id=>id.IntegerValue.ToString()).ToList());
+                if (spacesServerInfo == null || spacesServerInfo.Count == 0)
+                {
+                    #region 冲突对象不包含物理世界空间
+                    var firstElement = doc.GetElement(failItem.FirstOrDefault());
+                    if (firstElement is RSpace first)
+                    {
+                        for (int i = 1; i < failItem.Count; i++)
+                        {
+                            var currentId = failItem[i];
+                            if (first.Id.IsEqual(currentId))
+                                continue;
+                            var curr = doc.GetElement(currentId) as RSpace;
+                            if (!regex.IsMatch(curr.Number))
+                            {
+                                doc.Delete(new List<ElementId>() { currentId });
+                                continue;
+                            }
+                            if (!regex.IsMatch(first.Number))
+                            {
+                                doc.Delete(new List<ElementId>() { first.Id });
+                                first = curr;
+                                continue;
+                            }
+
+                            if (int.Parse(first.Number) > int.Parse(curr.Number))
+                            {
+                                doc.Delete(new List<ElementId>() { first.Id });
+
+                                first = curr;
+                            }
+                            else
+                            {
+                                doc.Delete(new List<ElementId>() { currentId });
+
+                            }
+                        }
+                    } 
+                    #endregion
+                }
+                else if (spacesServerInfo.Count == 1)
+                {
+                    #region 冲突对象包好一个物理世界对象
+                    var serverSpaceId = spacesServerInfo[0].BimID.Split(':')[1];
+                    doc.Delete(failItem.Where(t => t.ToString() != serverSpaceId).ToList()); 
+                    #endregion
+                }
+                else
+                {
+                    #region 冲突对象包含多个物理世界对象,保留物理世界对象手动选择【一般删掉空间分割产生这种情况】
+                    doc.Delete(failItem.Where(t => !spacesServerInfo.Exists(sp => sp.BimID.Split(':')[1] == t.ToString())).ToList());
+                    var groupName = $"待合并元空间组{index}";
+                    foreach (var mRevitEquipBase in spacesServerInfo)
+                    {
+                        if (mRevitEquipBase is MSpace space)
+                        {
+                            serverSpaces.Add(new ServerSpace()
+                            {
+                                Space = space,
+                                GroupName = groupName
+                            });
+                        }
+                    }
+                    serverSpaces.Add(new ServerSpace()
+                    {
+                        Name = NewCreateSpaceFlag,
+                        GroupName = groupName
+                    });
+                    index++; 
+                    #endregion
+                }
+
+            }
+            if (serverSpaces.Count > 0)
+            {
+                var winDeal = new WinSelectSpace(serverSpaces);
+                var result = winDeal.ShowDialog();
+                if (result == true)
+                {              
+                    //在指定位置创建空间,保留任意存在空间的定位点,根据定位点创建空间。
+                   var groups = serverSpaces.GroupBy(t => t.GroupName);
+                    List<string> deletedIds = new List<string>();
+                    List<UV> newSpaceLocations = new List<UV>();
+                    foreach (var groupSpaces in groups)
+                    {
+                        var spaces = groupSpaces.ToList();
+                        foreach (var serverSpace in spaces)
+                        {
+                            if (serverSpace.IsChecked)
+                            {
+                                if (IsNewSpaceFlag(serverSpace))
+                                {
+                                    //新建标志的,利用原始空间坐标创建新空间
+                                    var tempSpace = spaces.FirstOrDefault(c => !IsNewSpaceFlag(c));
+                                    var elementId = GetElementId(tempSpace.Space);
+                                    var useSpace = doc.GetElement(new ElementId(elementId.ToInt())) as RSpace;
+                                    newSpaceLocations.Add(useSpace.GetLocationPoint().ToUv());                             
+                                }
+                            }
+                            else
+                            {
+                                //没选中删除
+                                if (!IsNewSpaceFlag(serverSpace))
+                                {
+                                    deletedIds.Add(GetElementId(serverSpace.Space));
+                                }
+                            }
+                        }
+                    }
+
+                    #region revit 模型处理
+                    //删除
+                    if (deletedIds.Any())
+                    {
+                            doc.Delete(deletedIds.Select(c=>new ElementId(c.ToInt())).ToList()); 
+                    }
+                    //创建新的空间
+                    var view = doc.GetUseView();
+                    Phase phase = view.GetParameterElement(BuiltInParameter.VIEW_PHASE) as Phase;
+                    foreach (var newSpaceLocation in newSpaceLocations)
+                    {
+                        var space = ExternalDataWrapper.Current.DocCreater.NewSpace(view.GenLevel, phase,newSpaceLocation);
+                        ExternalDataWrapper.Current.DocCreater.NewSpaceTag(space, newSpaceLocation, view);
+                    }
+                    #endregion
+                }
+                else
+                {
+                    //没处理会有什么操作
+                }
+            }
         }
 
         /// <summary>
         /// 上传模型
         /// </summary>
         /// <param name="doc"></param>
-        public void UploadModel(Document doc)
+        public static void UploadModel(Document doc)
         {
-            doc.Save();
+            //doc.Save();
             string str = "";
             UploadModeCommand command = new UploadModeCommand();
             command.Execute(null, ref str, null);

+ 0 - 2
MBI/SAGA.MBI/WinView/Space/WinCreateSpace.xaml

@@ -4,8 +4,6 @@
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:converter="clr-namespace:SAGA.DotNetUtils.WPF.Converter;assembly=SAGA.DotNetUtils"
-       
-        xmlns:model="clr-namespace:SAGA.MBI.Model"
         xmlns:windows="clr-namespace:SAGA.RevitUtils.Windows;assembly=SAGA.RevitUtils"
         mc:Ignorable="d"
         Title="空间管理" Height="950" Width="1525">

+ 183 - 381
MBI/SAGA.MBI/WinView/Space/WinCreateSpace.xaml.cs

@@ -28,9 +28,11 @@ using SAGA.MBI.Model;
 using SAGA.MBI.RequestData;
 using SAGA.MBI.Tools;
 using SAGA.MBI.WinView.ModeInfoMaintenance;
+using SAGA.RevitUtils;
 using SAGA.RevitUtils.Windows;
 using Visibility = System.Windows.Visibility;
 using Path = System.IO.Path;
+using System.Threading.Tasks;
 
 //TODO:1.目前存在的问题,如果只选两个已有的端点画线不能实现
 //TODO:2.画图过程中,ESC可取消当前画图
@@ -98,8 +100,6 @@ namespace SAGA.MBI.WinView.Space
             get => new ObservableCollection<TreeNodeItem>(DalModeFileManange.GetMissFileFloors(false));
             set => items = value;
         }
-        //本层空间数据缓存
-        private List<MSpace> m_spacesCache;
         private void MainWindow_Loaded(object sender, RoutedEventArgs e)
         {
             CanvasDefaultTips();
@@ -107,7 +107,7 @@ namespace SAGA.MBI.WinView.Space
         /// <summary>
         /// 初始化画布,并在画图上画出相关数据
         /// </summary>
-        private bool InitData()
+        private void InitData()
         {
             //获取边界值
             GetBoundary();
@@ -127,7 +127,11 @@ namespace SAGA.MBI.WinView.Space
             });
             //画柱
             DrawColumns();
-            return true;
+            var spaces =CurrentContext.Document.GetElements<SpatialElement>().Where(s => s is Autodesk.Revit.DB.Mechanical.Space && s.Area > 0).ToList();
+            //创建空间轮廓,这里必须放在初始化之后创建
+            CreateAllSpaceSeq(spaces);
+            //创建右侧空间树
+            ShowSpacesListFrowServer(spaces);
         }
 
 
@@ -545,7 +549,22 @@ namespace SAGA.MBI.WinView.Space
         {
             return new XYZ(((point.X - 20) / m_scale + m_minX), ((point.Y - 20) / (-m_scale) + (m_maxY)), 0);
         }
-
+        /// <summary>
+        /// 获取上传确认窗口
+        /// </summary>
+        /// <returns></returns>
+        private Window GetUploadConfirm()
+        {
+            WinConfirm confirm = new WinConfirm()
+            {
+                ShowMessage = "空间已发生变化,是否现在就上传模型并计算空间?",
+                TTitle = "空间计算确认",
+                BtnSure = "上传模型并计算空间",
+                BtnCancel = "暂不计算",
+                Owner = this,
+            };
+            return confirm;
+        }
 
         /// <summary>
         /// 保存所画的线
@@ -554,134 +573,11 @@ namespace SAGA.MBI.WinView.Space
         /// <param name="e"></param>
         private void btnSave_Click(object sender, RoutedEventArgs e)
         {
-            m_isAsynFinished = false;
-            //禁用界面,防止重复提交
-            this.IsEnabled = false;
-            m_isDraw = null;
-            //需要保存的分隔符数据
-            List<PointPair> saveDatas = new List<PointPair>();
-            //取出所有的线
-            for (var j = 0; j < this.canvas.Children.Count; j++)
-            {
-                var child = this.canvas.Children[j];
-                if (child is WPolyline line && line.Stroke == Brushes.Red)
-                {
-                    for (int i = 0; i < line.Points.Count - 1; i++)
-                    {
+            SaveFloor();
 
-                        //创建新的虚拟墙
-                        var newLine = new Polyline()
-                        {
-                            Stroke = Brushes.Green,
-                            StrokeThickness = 2,
-
-                        };
-                        newLine.Points.Add(line.Points[i]);
-                        newLine.Points.Add(line.Points[i + 1]);
-
-                        //将现有坐标转化
-                        saveDatas.Add(new PointPair()
-                        {
-                            RPoint = new List<XYZ>() { WpfPointToReivt(line.Points[i]), WpfPointToReivt(line.Points[i + 1]) },
-                            ShowLine = newLine
-                        });
-                        this.canvas.Children.Add(newLine);
-                    }
-                    //删除现有的虚拟墙
-                    this.canvas.Children.Remove(line);
-                    j = -1;
-                }
-            }
-            //保存数据到Revit,创建空间分隔符
-            var doc = m_document;
-            ExecuteCmd.ExecuteCommand(() =>
-            {
-                Logs.Log($"空间分隔符开始");
-                var create = new CreateSpaceCommand();
-                //创建空间分隔符
-                create.CreateSpaceSeqarate(doc, saveDatas, DeletedPolylines);
-                //删除已有的空间分隔符
-                DeletedPolylines.Clear();
-                Logs.Log($"空间分隔符结束");
-                // btnSaveToRevit.IsEnabled = true;
-                return Result.Succeeded;
-            });
-
-
-            //保存后重新创建空间,并加载空间分隔符与空间数据
-
-            CreateSpaceAndReload(doc, () =>
-            {
-                WinConfirm confirm = new WinConfirm()
-                {
-                    ShowMessage = "空间已发生变化,是否现在就上传模型并计算空间?",
-                    TTitle = "空间计算确认",
-                    BtnSure = "上传模型并计算空间",
-                    BtnCancel = "暂不计算",
-                    Owner=this,
-                };
-
-                var result = confirm.ShowDialog();
-                //选择以后界面可用
-                this.IsEnabled = true;
-                if (result == true)
-                {
-                    // 由于上传需要关闭所有模型,所以这里需要对所有数据进行清空
-                    this.canvas.Children.Clear();
-                    //添加默认提示
-                    CanvasDefaultTips();
-                    lbSpaces.ItemsSource = new ObservableCollection<MSpace>();
-                    WinModeInfoMaintenance.GetWindow().Hide();
-                    m_isCreaded = true;
-                    return false;
-                }
-                else
-                {
-                    return true;
-                }
-            });
-
-
-            timer = new DispatcherTimer();
-            timer.Tick += Timer_Elapsed;
-            timer.Interval = TimeSpan.FromMilliseconds(1000);
-            timer.Start();
         }
 
-        private bool m_isCreaded = false;//是否上传数据的标志,用于定时器
-        private bool m_isAsynFinished = false;
-        private void Timer_Elapsed(object sender, EventArgs e)
-        {
-
-            if (m_isAsynFinished)
-            {
-                //所有的操作只在这里进行保存
-                m_document.Save();
-                Logs.Log($"{DateTime.Now}被保存!!!!!!!!!!!!!!!!!!");
-                if (m_isCreaded)
-                {
-                    //放在命令里面
-                    //ExecuteCmd.ExecuteCommand(() =>
-                    //{
-                        try
-                        {
-                            string str = "";
-                            UploadModeCommand command = new UploadModeCommand();
-                            command.Execute(null, ref str, null);
-                        }
-                        catch (Exception exception)
-                        {
-                            Console.WriteLine(exception);
-                            MessageBox.Show(exception.Message);
-                        }
-                    //    return Result.Succeeded;
-                    //});            
-                    m_isCreaded = false;
-                }
-                timer.Stop();
-                m_isAsynFinished = false;
-            }
-        }
+   
 
         /// <summary>
         /// 离开画布,改变鼠标样式
@@ -786,9 +682,7 @@ namespace SAGA.MBI.WinView.Space
 
             MoveElement(val, center);
         }
-
-        private string m_curFloorId = "";//当前选择项楼层Id
-        private Document m_document;//当前操作的模型
+        public FloorSpaceContext CurrentContext;
         /// <summary>
         /// 楼层切换
         /// </summary>
@@ -805,12 +699,14 @@ namespace SAGA.MBI.WinView.Space
                     ShowMessage = "尚未保存空间变化,确认放弃修改?",
                     TTitle = "空间修改确认",
                     BtnSure = "保存并更改模型",
-                    BtnCancel = "放弃修改"
+                    BtnCancel = "放弃修改",
+                    Owner=this
+                    
                 };
                 var result = confirm.ShowDialog();
                 if (result == true)
                 {
-                    btnSave_Click(null, null);
+                    SaveFloor();
                     return;
                 }
                 DeletedPolylines.Clear();
@@ -819,127 +715,181 @@ namespace SAGA.MBI.WinView.Space
 
             if (tv.SelectedItem is TreeNodeItem item && item.Item is MFloor floor)
             {
-                try
+                InitFloor(floor);
+            }
+        }
+
+        public void InitFloor(MFloor floor)
+        {
+            try
+            {
+                //关闭空间属性窗
+                WinModeInfoMaintenance.GetWindow().Hide();
+                this.canvas.Children.Clear();
+                this.canvas.IsEnabled = false;
+                this.lbSpaces.ItemsSource = null;
+
+                #region 数据整理
+
+                FloorSpaceContext context = new FloorSpaceContext(floor);
+                CurrentContext = context;
+                var doc = context.Document;
+                var view = doc.GetUseView();
+                if (view == null)
                 {
-                    //关闭空间属性窗
-                    WinModeInfoMaintenance.GetWindow().Hide();
-                    m_curFloorId = floor.Id;
-                    this.canvas.Children.Clear();
+                    MessageBox.Show("无法找到名称以-saga结尾的视图!");
+                    return;
+                }
 
-                    this.canvas.IsEnabled = false;
+                bool result = LoadData();
+                if (!result)
+                {
+                    MessageBox.Show("模型文件没有找到相关数据!");
+                    return;
+                }
 
-                    this.lbSpaces.ItemsSource = null;
-                    //模型文件路径
-                    var filePath = floor.FullPath;
+                ExecuteCmd.ExecuteCommand(() =>
+                {
+                    context.CreateSpaces();
 
-                    //检测文件是否存在
-                    if (!File.Exists(filePath))
+                    #region 初始化界面
+                    this.canvas.IsEnabled = true;
+                    btnOrigin_Click(null, null);
+                    InitData(); 
+                    #endregion
+                    return Result.Succeeded;
+                });
+
+                #endregion           
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show(ex.Message);
+            }
+        }
+
+        private List<PointPair> GetPoints()
+        {
+            List<PointPair> saveDatas = new List<PointPair>();
+            for (var j = 0; j < this.canvas.Children.Count; j++)
+            {
+                var child = this.canvas.Children[j];
+                if (child is WPolyline line && line.Stroke == Brushes.Red)
+                {
+                    for (int i = 0; i < line.Points.Count - 1; i++)
                     {
-                        MessageBox.Show("无法找到相关模型文件!");
-                        return;
-                    }
-                    //加载模型文件并激活
-                    //  var uiDoc = ExternalDataWrapper.Current.App.OpenDocumentFile(filePath);
-                    Logs.Log("加载模型开始");
-                    var uiDoc = ExternalDataWrapper.Current.UiApp.OpenAndActivateDocument(filePath);
-                    Logs.Log("加载模型结束");
 
-                    var doc = uiDoc.Document;
-                    m_document = doc;
+                        //创建新的虚拟墙
+                        var newLine = new Polyline()
+                        {
+                            Stroke = Brushes.Green,
+                            StrokeThickness = 2,
 
+                        };
+                        newLine.Points.Add(line.Points[i]);
+                        newLine.Points.Add(line.Points[i + 1]);
 
-                    var view = doc.GetElements<ViewPlan>().FirstOrDefault(t => t.GenLevel?.Name != null && t.Name?.IndexOf("-saga") > -1 && t.ViewType == ViewType.FloorPlan);
-                    if (view == null)
-                    {
-                        MessageBox.Show("无法找到名称以-saga结尾的视图!");
-                        return;
-                    }
-                    bool result = LoadData();
-                    if (!result)
-                    {
-                        MessageBox.Show("模型文件没有找到相关数据!");
-                        return;
+                        //将现有坐标转化
+                        saveDatas.Add(new PointPair()
+                        {
+                            RPoint = new List<XYZ>() { WpfPointToReivt(line.Points[i]), WpfPointToReivt(line.Points[i + 1]) },
+                            ShowLine = newLine
+                        });
+                        this.canvas.Children.Add(newLine);
                     }
-                    this.canvas.IsEnabled = true;
-
-                    //重置画布
-                    btnOrigin_Click(null, null);
-                    //缓存所有空间数据
-                    m_spacesCache = SpaceConvert.GetFloorSpaceInfos(m_curFloorId).OfType<MSpace>().ToList();
-                    //创建空间
-                    //检测日志,是否有墙,虚拟墙,柱子数据的改变
-                    CreateSpaceAndReload(doc, InitData);
-                }
-                catch (Exception ex)
-                {
-                    MessageBox.Show(ex.Message);
+                    //删除现有的虚拟墙
+                    this.canvas.Children.Remove(line);
+                    j = -1;
                 }
             }
+
+            return saveDatas;
         }
 
-        /// <summary>
-        /// 创建空间并重新加载到列表
-        /// </summary>
-        /// <param name="doc"></param>
-        /// <param name="callback">异步回调函数</param>
-        private void CreateSpaceAndReload(Document doc, Func<bool> callback)
+        private void SaveFloor()
         {
-            ExecuteCmd.ExecuteCommand(() =>
+            //禁用界面,防止重复提交
+            this.IsEnabled = false;
+            m_isDraw = null;
+            //需要保存的分隔符数据
+            List<PointPair> saveDatas = GetPoints();
+            bool flagExecuteSuccess = true;//本应在回调函数里传值,目前代码不支持
+            ExecuteCmd.ExecuteCommandOnce(() =>
             {
-                Logs.Log($"创建空间开始");
-                //生成空间
-                CreateSpaceCommand cmd = new CreateSpaceCommand();
+                #region 创建空间
+                CurrentContext.UpdateSpaceSeqaration(saveDatas
+                                .Select(points => new SpaceSeparation(points.RPoint[0], points.RPoint[1])).ToList(),
+                            DeletedPolylines);
+                DeletedPolylines.Clear();
+                var createSuccess=CurrentContext.CreateSpaces();
+                if (!createSuccess)
+                {
+                    flagExecuteSuccess = false;
+                    MessageShow.Infomation("保存楼层空间失败");
+                    return Result.Succeeded;
+                }
 
-                cmd.CreateSpace(doc);
-                // doc.Regenerate();
-                Logs.Log($"创建空间结束");
-                return Result.Succeeded;
-            });
+                #endregion
 
-            //因为异步执行,获取空间不能直接放到下面
+                #region 初始化界面
+                this.canvas.IsEnabled = true;
+                btnOrigin_Click(null, null);
+                InitData();
 
-            //删除冲突的空间
-            ExecuteCmd.ExecuteCommand(() =>
-            {
-                Logs.Log($"删除空间开始");
-                //     DeleteFailuresPreprocessorData(doc);
-                DeleteFailuresPreprocessorDataByManual(doc);
-                //保存数据
-                //    doc.Save();
-
-                bool? isReload = callback?.Invoke();
-                if (isReload == true)
-                {
-                    try
-                    {
-                        //加载空间
-                        var spaces = doc.GetElements<SpatialElement>().Where(s => s is Autodesk.Revit.DB.Mechanical.Space && s.Area > 0).ToList();
+                #endregion
 
-                        //创建空间轮廓,这里必须放在初始化之后创建
-                        CreateAllSpaceSeq(spaces);
-                        //创建右侧空间树
-                        ShowSpacesListFrowServer(spaces);
-                    }
-                    catch (Exception e)
-                    {
-                        MessageBox.Show(e.Message);
-                    }
+                #region 上传模型选择
+                Window confirm = GetUploadConfirm();
+                var result = confirm.ShowDialog();
+                //选择以后界面可用
+                this.IsEnabled = true;
+                if (result == true)
+                {
+                    // 由于上传需要关闭所有模型,所以这里需要对所有数据进行清空
+                    this.canvas.Children.Clear();
+                    //添加默认提示
+                    CanvasDefaultTips();
+                    lbSpaces.ItemsSource = new ObservableCollection<MSpace>();
+                    WinModeInfoMaintenance.GetWindow().Hide();
 
+                    #region 错误尝试
+                    //上传中的一些操作,不能发生在idling中
+
+                    //    Action<FloorSpaceContext> action = new Action<FloorSpaceContext>((context) =>
+                    //    {
+                    //        try
+                    //        {
+                    //             CurrentContext.Document.Save();
+                    //            SpaceManager.UploadModel(context.Document);
+                    //        }
+                    //        catch (Exception ex)
+                    //        {
+                    //            MessageShow.Show(ex);
+                    //        }
+                    //    });
+                    //    action.BeginInvoke(CurrentContext, null, null); 
+                    #endregion
+                }
+                #endregion
+                return Result.Succeeded;
+            }, () =>
+            {
+                if (!flagExecuteSuccess)
+                {
+                    return Result.Succeeded;
                 }
-                m_isAsynFinished = true;
-                //btnSaveToRevit.IsEnabled = true;
                 try
                 {
-                    Logs.Log($"删除空间结束");
-                    doc.Save();
-                    DocumentChangedLog.RemoveInvalidLogs();
+                    var document = CurrentContext.Document;
+                    document.Save();
+                   
+                    SpaceManager.UploadModel(document);
                 }
-                catch (Exception e)
+                catch (Exception ex)
                 {
-                    MessageBox.Show(e.Message);
+                    MessageShow.Show(ex);
                 }
-
-                return Result.Succeeded;
+                 return Result.Succeeded;
             });
         }
 
@@ -968,9 +918,7 @@ namespace SAGA.MBI.WinView.Space
         /// <param name="spaces"></param>
         private void ShowSpacesListFrowServer(List<SpatialElement> spaces)
         {
-            // var infosjobj = ConvertElementsToJArray(spaces);
-            //var datas = CommonConvert.QueryObjectInfoByIds(m_curFloorId, infosjobj).OfType<MSpace>().ToList();
-            var datas = GetSpaceFromCacheByIds(spaces.Select(t => t.Id).ToList());
+            var datas = CurrentContext.GetPhysicalSpaces(spaces.Select(t => t.Id.IntegerValue.ToString()).ToList());
 
             var localSpace = spaces.Where(t => !datas.Any(s => s.BimID.Split(':')[1] == t.Id.ToString()))
                 .Select(t => new MSpace("", $"{Guid.NewGuid()}:{t.Id.ToString()}") { Name = t.Name });
@@ -981,148 +929,16 @@ namespace SAGA.MBI.WinView.Space
         }
 
         
-        /// <summary>
-        /// 手动删除冲突的空间
-        /// </summary>
-        /// <param name="doc"></param>
-        private void DeleteFailuresPreprocessorDataByManual(Document doc)
-        {
-            bool isReCreate = false;
-            using (Transaction trans = new Transaction(doc, "删除多余的空间"))
-            {
-                trans.Start();
-                try
-                {
-                    //处理异常显示
-                    FailureHandlingOptions fho = trans.GetFailureHandlingOptions();
-                    fho.SetFailuresPreprocessor(new FailuresPreprocessor(false));
-                    trans.SetFailureHandlingOptions(fho);
-
-                    List<ServerSpace> serverSpaces = new List<ServerSpace>();
-                    Regex regex = new Regex("^\\d+$");
-
-                    var index = 1;
-                    //对冲突的空间进行删除
-                    foreach (List<ElementId> elementIds in StaticData.FailuresPreprocessorData)
-                    {
-                        Logs.Log(string.Join("-", elementIds));
-                        //取出空间的服务器信息
-                    
-                        var spacesServerInfo = GetSpaceFromCacheByIds(elementIds);
-                        //如果返回值小于等于1,自动处理
-                        //如果返回值大于1,则在界面处理
-                        if (spacesServerInfo == null || spacesServerInfo.Count == 0)
-                        {
-
-
-                            var firstElement = doc.GetElement(elementIds.FirstOrDefault());
-
-                            //对所有冲突的空间编号进行比较,保留较小编号的空间
-                            if (firstElement is Autodesk.Revit.DB.Mechanical.Space first)
-                            {
-                                foreach (var id in elementIds)
-                                {
-                                    if (first.Id.IsEqual(id))
-                                        continue;
-                                    var curr = doc.GetElement(id) as Autodesk.Revit.DB.Mechanical.Space;
-                                    Logs.Log("=============");
-                                    Logs.Log($"当前空间Id:{id},Num:{curr.Number}");
-                                    //如果编号非数字,删其中一个
-                                    if (!regex.IsMatch(first.Number))
-                                    {
-                                        doc.Delete(new List<ElementId>() { first.Id });
-
-                                        first = curr;
-                                        continue;
-                                    }
-                                    if (!regex.IsMatch(curr.Number))
-                                    {
-                                        doc.Delete(new List<ElementId>() { id });
-                                        continue;
-                                    }
-                                    if (int.Parse(first.Number) > int.Parse(curr.Number))
-                                    {
-                                        Logs.Log($"1.被删除的空间Id:{id},Num:{first.Number}");
-                                        doc.Delete(new List<ElementId>() { first.Id });
-
-                                        first = curr;
-                                    }
-                                    else
-                                    {
-                                        Logs.Log($"2.被删除的空间Id:{id},Num:{curr.Number}");
-                                        doc.Delete(new List<ElementId>() { id });
-
-                                    }
-                                    Logs.Log("=============");
-                                }
-                            }
-                        }
-                        else if (spacesServerInfo.Count == 1)
-                        {
-                            var serverSpaceId = spacesServerInfo[0].BimID.Split(':')[1];
-                            doc.Delete(elementIds.Where(t => t.ToString() != serverSpaceId).ToList());
-                        }
-                        else
-                        {
-                            doc.Delete(elementIds.Where(t => !spacesServerInfo.Exists(sp => sp.BimID.Split(':')[1] == t.ToString())).ToList());
-                            var groupName = $"待合并元空间组{index}";
-                            foreach (var mRevitEquipBase in spacesServerInfo)
-                            {
-                                if (mRevitEquipBase is MSpace space)
-                                {
-                                    serverSpaces.Add(new ServerSpace()
-                                    {
-                                        Space = space,
-                                        GroupName = groupName
-                                    });
-                                }
-                            }
-                            serverSpaces.Add(new ServerSpace()
-                            {
-                                Name = "不保留已有空间,创建新空间",
-                                GroupName = groupName
-                            });
-                            index++;
-                        }
-
-                    }
-                    if (serverSpaces.Count > 0)
-                    {
-                        var winDeal = new WinSelectSpace(serverSpaces);
-                        var result = winDeal.ShowDialog();
-                        if (result == true)
-                        {
-                            var ids = winDeal.DeleteElementIds.Select(t => new ElementId(int.Parse(t))).ToList();
-                            doc.Delete(ids);
-                            isReCreate = winDeal.IsReCreate;
-                        }
-                    }
-
-                    //提交事务
-                    trans.Commit();
-                }
-                catch (Exception e)
-                {
-                    //回滚事务
-                    trans.RollBack();
-                }
-
-            }
-            StaticData.FailuresPreprocessorData.Clear();
-            if (isReCreate) CreateSpaceAndReload(doc, null);
-        }
-
-       
+        
         /// <summary>
         /// 加载模型数据
         /// </summary>
         private bool LoadData()
         {
-            var doc = m_document;
+            var doc = CurrentContext.Document;
             //读取墙数据
             List<Wall> walls = doc.FilterElements<Wall>().ToList();
             if (walls.Count == 0) return false;
-            //   List<List<XYZ>> wallData = GroupWallByParallel(walls);//太慢改为直接获取墙线
 
             //获取虚拟墙(空间分隔符或者房间分隔符)
             var wallData = walls.Select(t => t.GetCurve().Tessellate().ToList()).ToList();
@@ -1137,7 +953,6 @@ namespace SAGA.MBI.WinView.Space
                 var ml = line as ModelLine;
 
                 var mlLine = ml.Location.GetLine();
-                //return new SgLine(mlLine.StartPoint().ToW2DPoint(), mlLine.EndPoint().ToW2DPoint());                        //return new SgLine(mlLine.StartPoint().ToW2DPoint(), mlLine.EndPoint().ToW2DPoint());
                 return
                     new PointPair(ml.Id.IntegerValue, new List<System.Windows.Point>()
                     {
@@ -1226,17 +1041,6 @@ namespace SAGA.MBI.WinView.Space
         }
 
         /// <summary>
-        /// 从缓存获取空间信息
-        /// </summary>
-        /// <param name="ids"></param>
-        /// <returns></returns>
-        private List<MSpace> GetSpaceFromCacheByIds(List<ElementId> ids)
-        {
-            if (m_spacesCache != null)
-                return m_spacesCache.Where(s => ids.Exists(id => id.ToString() == s.BimID.Split(':')[1])).ToList();
-            return new List<MSpace>();
-        }
-        /// <summary>
         /// 创建空间边缘轮廓
         /// </summary>
         /// <param name="space"></param>
@@ -1327,8 +1131,6 @@ namespace SAGA.MBI.WinView.Space
         private DispatcherTimer timer;
 
        
-
-
         private void CanvasDefaultTips()
         {
             string tips = "请选择一个需要进行空间管理的楼层";

+ 0 - 6
MBI/SAGA.MBI/WinView/Space/WinSelectSpace.xaml

@@ -38,10 +38,6 @@
                                
                             </RadioButton>
                             <TextBlock Text="{Binding Name}" Width="420" />
-                            <!--<TextBlock Text="{Binding AuthorName}"
-                           Width="100" />
-                <TextBlock Text="{Binding UpTime}"
-                           Width="100" />-->
                         </StackPanel>
                     </DataTemplate>
                 </ListBox.ItemTemplate>
@@ -61,8 +57,6 @@
                                                         <TextBlock Text="{Binding Path=ItemCount, StringFormat=数量:{0},Converter={StaticResource converter}}"
                                                        VerticalAlignment="Center"
                                                        Margin="5,0,0,0" />
-                                                        <!--<Button Content="Sale"
-                                                    Margin="5,0,0,0" />-->
                                                     </StackPanel>
                                                 </Expander.Header>
                                                 <ItemsPresenter />

+ 47 - 65
MBI/SAGA.MBI/WinView/Space/WinSelectSpace.xaml.cs

@@ -1,12 +1,10 @@
 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
-using System.Diagnostics;
 using System.Globalization;
 using System.Linq;
 using System.Windows;
 using System.Windows.Data;
-using SAGA.MBI.Model;
 
 namespace SAGA.MBI.WinView.Space
 {
@@ -15,6 +13,7 @@ namespace SAGA.MBI.WinView.Space
     /// </summary>
     public partial class WinSelectSpace
     {
+        #region 事件相关处理
         public WinSelectSpace()
         {
             InitializeComponent();
@@ -22,104 +21,87 @@ namespace SAGA.MBI.WinView.Space
             rbtnManual.Checked += RbtnManual_Checked;
             rbtnAuto.Checked += RbtnManual_Checked;
         }
+        public WinSelectSpace(List<ServerSpace> data) : this()
+        {
+            m_Data = data;
+            lbMain.ItemsSource = data;
+        }
+        private void WinSelectSpace_Loaded(object sender, RoutedEventArgs e)
+        {
 
+            ICollectionView cv = CollectionViewSource.GetDefaultView(lbMain.ItemsSource);
+            cv.GroupDescriptions.Add(new PropertyGroupDescription("GroupName"));
+        }
         private void RbtnManual_Checked(object sender, RoutedEventArgs e)
         {
-            Debug.Assert(rbtnManual.IsChecked != null, "rbtnManual.IsChecked != null");
-            m_isManual = rbtnManual.IsChecked.Value;
             if (rbtnManual.IsChecked != true)
             {
-                lbMain.ItemsSource = new List<ServerSpace>() { new ServerSpace() { Name = "根据算法自动合并", GroupName = "自动合并" } };
+                lbMain.ItemsSource = new List<ServerSpace>() { new ServerSpace() { Name = "根据算法自动合并", GroupName = "自动合并" ,IsChecked=true} };
             }
             else
             {
-                lbMain.ItemsSource = m_data;
+                lbMain.ItemsSource = m_Data;
             }
 
         }
 
-        private List<ServerSpace> m_data;
-        public bool IsReCreate { get; set; }
-        public List<string> DeleteElementIds { get; set; } = new List<string>();
+        #endregion
+        private List<ServerSpace> m_Data;
 
-        private bool m_isManual = true;
-        public WinSelectSpace(List<ServerSpace> data) : this()
+        public bool IsManual
         {
-            m_data = data;
-            lbMain.ItemsSource = data;
+            get { return rbtnManual.IsChecked.Value; }
         }
-        private void WinSelectSpace_Loaded(object sender, RoutedEventArgs e)
+        private void btnSure_Click(object sender, RoutedEventArgs e)
         {
-
-            ICollectionView cv = CollectionViewSource.GetDefaultView(lbMain.ItemsSource);
-            cv.GroupDescriptions.Add(new PropertyGroupDescription("GroupName"));
+            if (DealServerSpace())
+            {
+                  DialogResult = true;
+            }          
         }
 
-        private void btnSure_Click(object sender, RoutedEventArgs e)
+        private void btnCancel_Click(object sender, RoutedEventArgs e)
         {
-            DeleteElementIds.Clear();
-            var data = m_data.GroupBy(t => t.GroupName);
+            DialogResult = false;
+        }
 
-            if (m_isManual)
+        #region 私有方法
+        private bool DealServerSpace()
+        {
+            var groups = m_Data.GroupBy(t => t.GroupName);
+            if (IsManual)
             {
-                foreach (IGrouping<string, ServerSpace> modelFiles in data)
+                foreach (IGrouping<string, ServerSpace> group in groups)
                 {
-                    var curDeleteElementId = new List<string>();
-                    bool anyCheck = false;
-                    foreach (var modelFile in modelFiles)
-                    {
-                        if (modelFile.IsChecked)
-                        {
-                            anyCheck = true;
-                            if (modelFile.Name.IndexOf("不保留已有空间") > -1)
-                            {
-                                curDeleteElementId = modelFiles.Where(t => t.Space != null).Select(t => GetElementId(t.Space))
-                                    .ToList();
-                                IsReCreate = true;
-                                break;
-                            }
-
-                        }
-                        else
-                        {
-                            if (modelFile.Space != null)
-                                curDeleteElementId.Add(GetElementId(modelFile.Space));
-                        }
-                    }
-                    //必须所有的项目被处理
+                    bool anyCheck = group.Any(sp => sp.IsChecked);
+                    //每个分组必须要,存在一个被选中
                     if (!anyCheck)
                     {
                         MessageBox.Show("您还有冲突空间没有处理!");
-                        return;
+                        return false;
                     }
-                    DeleteElementIds.AddRange(curDeleteElementId);
                 }
             }
             else
             {
-                foreach (IGrouping<string, ServerSpace> modelFiles in data)
+                foreach (IGrouping<string, ServerSpace> group in groups)
                 {
-                    var curDeleteElementId = modelFiles.Where(m => m.Name.IndexOf("不保留已有空间") == -1).ToList();
-                    curDeleteElementId.RemoveAt(0);
-
-                    DeleteElementIds.AddRange(curDeleteElementId.Select(t => GetElementId(t.Space)));
+                    bool useFlag = false;
+                    foreach (var space in group)
+                    {
+                        space.IsChecked = false;
+                        if (!useFlag && !SpaceManager.IsNewSpaceFlag(space))
+                        {
+                            useFlag = true;
+                            space.IsChecked = true;
+                        }
+                    }
                 }
 
             }
-
-
-            // MessageBox.Show(string.Join(",", DeleteElementIds));
-            DialogResult = true;
-        }
-
-        public string GetElementId(MSpace space)
-        {
-            return space.BimID.Split(':')[1];
-        }
-        private void btnCancel_Click(object sender, RoutedEventArgs e)
-        {
-            DialogResult = false;
+            return true;
         }
+        #endregion
     }
     /// <summary>
     /// 转换分组后的空间数量,去掉自动

+ 4 - 0
MBI/Test/Test.csproj

@@ -105,6 +105,10 @@
     <None Include="App.config" />
   </ItemGroup>
   <ItemGroup>
+    <ProjectReference Include="..\CEFSharpWPF\CEFSharpWPF.csproj">
+      <Project>{6449f956-11a3-4207-ae0f-9ab8563dfdce}</Project>
+      <Name>CEFSharpWPF</Name>
+    </ProjectReference>
     <ProjectReference Include="..\FirmLib\Com.FirmLib.UI\Com.FirmLib.UI.csproj">
       <Project>{1a6202ba-6646-48d1-8f93-f55ed4cff075}</Project>
       <Name>Com.FirmLib.UI</Name>