using Autodesk.Navisworks.Api;
using System;
using System.Collections.Generic;
using System.Linq;

namespace NavisworksTransport
{
    /// <summary>
    /// 楼层检测器 - 负责从模型中识别和提取楼层信息
    /// </summary>
    public class FloorDetector
    {
        // 常见的楼层属性名称
        private readonly string[] COMMON_FLOOR_ATTRIBUTES = {
            "Level", "Floor", "Storey", "楼层", "层", "Level Name", "Story",
            "Building Level", "Floor Level", "Elevation", "Z", "Height"
        };

        #region 公共方法

        /// <summary>
        /// 检测模型中的楼层信息
        /// </summary>
        /// <param name="items">要检测的模型元素集合</param>
        /// <param name="attributeName">指定的楼层属性名称，为空时自动检测</param>
        /// <param name="maxDepth">最大遍历深度，1=仅第一级，2=到第二级，3=到第三级，4=到第四级，5=到第五级，0=所有级别</param>
        /// <returns>检测到的楼层信息列表</returns>
        public List<FloorInfo> DetectFloors(ModelItemCollection items, string attributeName = null, int maxDepth = 1)
        {
            try
            {
                LogManager.Info($"[FloorDetector] ========== DetectFloors开始 ==========");
                LogManager.Info($"[FloorDetector] 输入参数: items.Count={items?.Count ?? -1}, attributeName='{attributeName ?? "null"}', maxDepth={maxDepth}");
                LogManager.Info($"[FloorDetector] 当前线程ID: {System.Threading.Thread.CurrentThread.ManagedThreadId}");
                
                if (items == null || items.Count == 0)
                {
                    LogManager.Warning("[FloorDetector] 输入的模型元素集合为空");
                    return new List<FloorInfo>();
                }

                LogManager.Info($"[FloorDetector] 开始检测楼层，元素数量: {items.Count}，遍历深度: {maxDepth}");

                // 根据深度限制获取要分析的项目
                var itemsToAnalyze = GetItemsByDepth(items, maxDepth);
                LogManager.Info($"[FloorDetector] 按深度筛选后的元素数量: {itemsToAnalyze.Count}");

                List<FloorInfo> floors;

                if (!string.IsNullOrEmpty(attributeName))
                {
                    LogManager.Info($"[FloorDetector] 使用指定属性检测楼层: {attributeName}");
                    // 使用指定属性检测楼层
                    floors = DetectFloorsByAttribute(itemsToAnalyze, attributeName);
                    LogManager.Info($"[FloorDetector] 使用属性 '{attributeName}' 检测到 {floors.Count} 个楼层");
                }
                else
                {
                    LogManager.Info($"[FloorDetector] 开始自动检测最佳楼层属性");
                    // 自动检测最佳楼层属性
                    string bestAttribute = FindBestFloorAttribute(itemsToAnalyze);
                    LogManager.Info($"[FloorDetector] FindBestFloorAttribute返回: '{bestAttribute ?? "null"}'");
                    
                    if (!string.IsNullOrEmpty(bestAttribute))
                    {
                        LogManager.Info($"[FloorDetector] 使用自动选择的属性: {bestAttribute}");
                        floors = DetectFloorsByAttribute(itemsToAnalyze, bestAttribute);
                        LogManager.Info($"[FloorDetector] 自动选择属性 '{bestAttribute}' 检测到 {floors.Count} 个楼层");
                    }
                    else
                    {
                        LogManager.Info($"[FloorDetector] 未找到合适的楼层属性，无法进行楼层检测");
                        LogManager.Info($"[FloorDetector] 建议：请确保模型包含标准的楼层属性（如Level、Floor、楼层等）");
                        // 不再使用高程检测，直接返回空结果
                        floors = new List<FloorInfo>();
                    }
                }

                LogManager.Info($"[FloorDetector] 开始验证和优化楼层结果");
                // 验证和优化检测结果
                floors = ValidateAndOptimizeFloors(floors);
                LogManager.Info($"[FloorDetector] 验证优化完成，最终楼层数: {floors?.Count ?? -1}");

                LogManager.Info($"[FloorDetector] ========== DetectFloors完成 ========== 最终识别 {floors.Count} 个楼层");
                return floors;
            }
            catch (Exception ex)
            {
                LogManager.Error($"[FloorDetector] ========== DetectFloors异常 ==========");
                LogManager.Error($"[FloorDetector] 楼层检测失败: {ex.Message}");
                LogManager.Error($"[FloorDetector] 异常堆栈: {ex.StackTrace}");
                throw;
            }
        }

        /// <summary>
        /// 获取可用的楼层属性列表
        /// </summary>
        /// <param name="items">要分析的模型元素集合</param>
        /// <param name="maxDepth">最大遍历深度，1=仅第一级，2=到第二级，3=到第三级，4=到第四级，5=到第五级，0=所有级别</param>
        /// <returns>可用的楼层属性列表</returns>
        public List<string> GetAvailableFloorAttributes(ModelItemCollection items, int maxDepth = 1)
        {
            try
            {
                LogManager.Info($"[FloorDetector] ===== GetAvailableFloorAttributes开始 =====");
                LogManager.Info($"[FloorDetector] 输入items.Count: {items?.Count ?? -1}, maxDepth: {maxDepth}");
                LogManager.Info($"[FloorDetector] 当前线程ID: {System.Threading.Thread.CurrentThread.ManagedThreadId}");
                
                // 根据深度限制获取要分析的项目
                var itemsToAnalyze = GetItemsByDepth(items, maxDepth);
                LogManager.Info($"[FloorDetector] 按深度筛选后的元素数量: {itemsToAnalyze.Count}");
                
                var availableAttributes = new HashSet<string>();
                int sampleSize = Math.Min(100, itemsToAnalyze.Count); // 采样前100个元素
                LogManager.Info($"[FloorDetector] 采样大小: {sampleSize}");
                
                var sampleItems = itemsToAnalyze.Take(sampleSize);
                LogManager.Info($"[FloorDetector] 开始枚举采样的模型项");
                
                int processedCount = 0;
                foreach (ModelItem item in sampleItems)
                {
                    try
                    {
                        processedCount++;
                        //LogManager.Info($"[FloorDetector] 正在处理第 {processedCount} 个采样项");
                        
                        var categories = item.PropertyCategories;
                        //LogManager.Info($"[FloorDetector] 第 {processedCount} 个项有 {(categories != null ? categories.Count() : 0)} 个属性类别");
                        
                        foreach (PropertyCategory category in categories)
                        {
                            try
                            {
                                var properties = category.Properties;
                                //LogManager.Info($"[FloorDetector] 类别 '{category.DisplayName}' 有 {(properties != null ? properties.Count() : 0)} 个属性");
                                
                                foreach (DataProperty property in properties)
                                {
                                    try
                                    {
                                        string propName = property.DisplayName;

                                        // 检查是否为楼层相关属性
                                        if (IsFloorRelatedAttribute(propName))
                                        {
                                            //LogManager.Info($"[FloorDetector] 发现楼层相关属性: {propName}");
                                            availableAttributes.Add(propName);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        LogManager.Warning($"[FloorDetector] 处理属性时出错: {ex.Message}");
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                LogManager.Warning($"[FloorDetector] 处理属性类别时出错: {ex.Message}");
                            }
                        }
                        //LogManager.Info($"[FloorDetector] 完成处理第 {processedCount} 个采样项");
                    }
                    catch (Exception ex)
                    {
                        LogManager.Warning($"[FloorDetector] 处理模型项时出错: {ex.Message}");
                        LogManager.Warning($"[FloorDetector] 异常堆栈: {ex.StackTrace}");
                    }
                }

                var result = availableAttributes.OrderBy(attr => attr).ToList();
                LogManager.Info($"[FloorDetector] ===== GetAvailableFloorAttributes完成 ===== 找到 {result.Count} 个可用的楼层属性，共处理 {processedCount} 个模型项");

                return result;
            }
            catch (Exception ex)
            {
                LogManager.Error($"[FloorDetector] ===== GetAvailableFloorAttributes异常 =====");
                LogManager.Error($"[FloorDetector] 获取楼层属性失败: {ex.Message}");
                LogManager.Error($"[FloorDetector] 异常堆栈: {ex.StackTrace}");
                return new List<string>();
            }
        }

        /// <summary>
        /// 从给定的模型项集合中检测楼层信息 - 不进行深度遍历
        /// </summary>
        /// <param name="items">预先过滤的模型项集合</param>
        /// <param name="attributeName">指定的楼层属性名称，为空时自动检测</param>
        /// <returns>检测到的楼层信息列表</returns>
        public List<FloorInfo> DetectFloorsFromGivenItems(ModelItemCollection items, string attributeName = null)
        {
            try
            {
                LogManager.Info($"[FloorDetector] ===== DetectFloorsFromGivenItems开始 =====");
                LogManager.Info($"[FloorDetector] 输入参数: items.Count={items?.Count ?? -1}, attributeName='{attributeName ?? "null"}'");
                
                if (items == null || items.Count == 0)
                {
                    LogManager.Warning("[FloorDetector] 输入的模型元素集合为空");
                    return new List<FloorInfo>();
                }

                LogManager.Info($"[FloorDetector] 直接使用传入的模型项集合进行楼层检测，元素数量: {items.Count}");

                List<FloorInfo> floors;

                if (!string.IsNullOrEmpty(attributeName))
                {
                    LogManager.Info($"[FloorDetector] 使用指定属性检测楼层: {attributeName}");
                    // 使用指定属性检测楼层
                    floors = DetectFloorsByAttribute(items, attributeName);
                    LogManager.Info($"[FloorDetector] 使用属性 '{attributeName}' 检测到 {floors.Count} 个楼层");
                }
                else
                {
                    LogManager.Info($"[FloorDetector] 开始自动检测最佳楼层属性");
                    // 自动检测最佳楼层属性
                    string bestAttribute = FindBestFloorAttribute(items);
                    LogManager.Info($"[FloorDetector] FindBestFloorAttribute返回: '{bestAttribute ?? "null"}'");
                    
                    if (!string.IsNullOrEmpty(bestAttribute))
                    {
                        LogManager.Info($"[FloorDetector] 使用自动选择的属性: {bestAttribute}");
                        floors = DetectFloorsByAttribute(items, bestAttribute);
                        LogManager.Info($"[FloorDetector] 自动选择属性 '{bestAttribute}' 检测到 {floors.Count} 个楼层");
                    }
                    else
                    {
                        LogManager.Info($"[FloorDetector] 未找到合适的楼层属性，无法进行楼层检测");
                        LogManager.Info($"[FloorDetector] 建议：请确保模型包含标准的楼层属性（如Level、Floor、楼层等）");
                        // 不再使用高程检测，直接返回空结果
                        floors = new List<FloorInfo>();
                    }
                }

                LogManager.Info($"[FloorDetector] 开始验证和优化楼层结果");
                // 验证和优化检测结果
                floors = ValidateAndOptimizeFloors(floors);
                LogManager.Info($"[FloorDetector] 验证优化完成，最终楼层数: {floors?.Count ?? -1}");

                LogManager.Info($"[FloorDetector] ===== DetectFloorsFromGivenItems完成 ===== 最终识别 {floors.Count} 个楼层");
                return floors;
            }
            catch (Exception ex)
            {
                LogManager.Error($"[FloorDetector] ===== DetectFloorsFromGivenItems异常 =====");
                LogManager.Error($"[FloorDetector] 楼层检测失败: {ex.Message}");
                LogManager.Error($"[FloorDetector] 异常堆栈: {ex.StackTrace}");
                throw;
            }
        }

        #endregion

        #region 私有方法 - 深度控制和基于属性的检测

        /// <summary>
        /// 根据指定深度获取模型项
        /// </summary>
        /// <param name="items">输入的模型项集合</param>
        /// <param name="maxDepth">最大深度，1=仅第一级，2=到第二级，3=到第三级，4=到第四级，5=到第五级，0=所有级别</param>
        /// <returns>筛选后的模型项集合</returns>
        public ModelItemCollection GetItemsByDepth(ModelItemCollection items, int maxDepth)
        {
            try
            {
                LogManager.Info($"[FloorDetector] GetItemsByDepth 开始，maxDepth={maxDepth}, 输入项数={items?.Count ?? 0}");
                
                var result = new ModelItemCollection();

                if (maxDepth <= 0)
                {
                    // 深度为0表示包含所有级别
                    LogManager.Info("[FloorDetector] maxDepth=0，返回所有级别的项");
                    if (items != null)
                    {
                        result.AddRange(items);
                    }
                    return result;
                }

                // 使用文档的根项目开始深度遍历
                var document = Autodesk.Navisworks.Api.Application.ActiveDocument;
                if (document?.Models?.Count > 0)
                {
                    var rootItems = new ModelItemCollection();
                    rootItems.AddRange(document.Models.RootItems);
                    AddItemsToDepth(rootItems, result, 1, maxDepth);
                }

                LogManager.Info($"[FloorDetector] GetItemsByDepth 完成，返回项数={result.Count}");
                return result;
            }
            catch (Exception ex)
            {
                LogManager.Error($"[FloorDetector] GetItemsByDepth 异常: {ex.Message}", ex);
                // 出错时返回空集合（因为当maxDepth>0时，items参数本来就会被忽略）
                return new ModelItemCollection();
            }
        }

        /// <summary>
        /// 递归添加指定深度的模型项
        /// </summary>
        /// <param name="currentItems">当前层级的项目</param>
        /// <param name="result">结果集合</param>
        /// <param name="currentDepth">当前深度</param>
        /// <param name="maxDepth">最大深度</param>
        private void AddItemsToDepth(ModelItemCollection currentItems, ModelItemCollection result, int currentDepth, int maxDepth)
        {
            if (currentDepth > maxDepth || currentItems == null || currentItems.Count == 0)
                return;

            // 添加当前层级的项目
            foreach (ModelItem item in currentItems)
            {
                result.Add(item);
                
                // 如果还没有达到最大深度，继续遍历子项
                if (currentDepth < maxDepth && item.Children != null && item.Children.Count() > 0)
                {
                    var childItems = new ModelItemCollection();
                    childItems.AddRange(item.Children);
                    AddItemsToDepth(childItems, result, currentDepth + 1, maxDepth);
                }
            }
        }

        private List<FloorInfo> DetectFloorsByAttribute(ModelItemCollection items, string attributeName)
        {
            var floorGroups = new Dictionary<string, List<ModelItem>>();

            foreach (ModelItem item in items)
            {
                try
                {
                    string floorValue = CategoryAttributeManager.GetGeneralPropertyValueSafe(item, attributeName);
                    if (!string.IsNullOrEmpty(floorValue))
                    {
                        if (!floorGroups.ContainsKey(floorValue))
                        {
                            floorGroups[floorValue] = new List<ModelItem>();
                        }
                        floorGroups[floorValue].Add(item);
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Warning($"[FloorDetector] 处理模型项楼层属性时出错: {ex.Message}");
                }
            }

            var floors = new List<FloorInfo>();
            foreach (var kvp in floorGroups)
            {
                var floorItems = new ModelItemCollection();
                floorItems.AddRange(kvp.Value);

                var floorInfo = new FloorInfo
                {
                    FloorName = SanitizeFloorName(kvp.Key),
                    Items = floorItems,
                    Elevation = CalculateAverageElevation(floorItems),
                    Bounds = CalculateBounds(floorItems),
                    Properties = new Dictionary<string, object>
                    {
                        ["OriginalAttributeValue"] = kvp.Key,
                        ["AttributeName"] = attributeName,
                        ["DetectionMethod"] = "Attribute"
                    }
                };

                floors.Add(floorInfo);
            }

            return floors.OrderBy(f => f.Elevation).ToList();
        }


        #endregion

        // 高程检测方法已删除 - 性能优化：避免高耗时的高程遍历算法

        #region 私有方法 - 属性检测和验证

        private string FindBestFloorAttribute(ModelItemCollection items)
        {
            LogManager.Info($"[FloorDetector] ===== FindBestFloorAttribute开始 =====");
            LogManager.Info($"[FloorDetector] 输入items.Count: {items?.Count ?? -1}");
            
            var attributeScores = new Dictionary<string, int>();
            int sampleSize = Math.Min(50, items.Count); // 减少采样数量以提高稳定性
            int processedCount = 0;
            
            LogManager.Info($"[FloorDetector] 采样大小: {sampleSize}，开始枚举ModelItem");

            foreach (ModelItem item in items)
            {
                if (processedCount >= sampleSize) 
                {
                    LogManager.Info($"[FloorDetector] 达到采样限制，停止处理");
                    break; // 限制处理数量
                }
                
                try
                {
                    //LogManager.Info($"[FloorDetector] 正在处理第 {processedCount + 1} 个模型项");
                    
                    var categories = item.PropertyCategories;
                    //LogManager.Info($"[FloorDetector] 模型项 {processedCount + 1} 有 {(categories != null ? categories.Count() : 0)} 个属性类别");
                    
                    foreach (PropertyCategory category in categories)
                    {
                        try
                        {
                            var properties = category.Properties;
                            //LogManager.Info($"[FloorDetector] 类别 '{category.DisplayName}' 有 {(properties != null ? properties.Count() : 0)} 个属性");
                            
                            foreach (DataProperty property in properties)
                            {
                                try
                                {
                                    string propName = property.DisplayName;

                                    if (IsFloorRelatedAttribute(propName))
                                    {
                                        //LogManager.Info($"[FloorDetector] 找到楼层相关属性: {propName}");
                                        string value = CategoryAttributeManager.GetSafePropertyValue(property);
                                        //LogManager.Info($"[FloorDetector] 属性值: {value ?? "null"}");
                                        
                                        if (!string.IsNullOrEmpty(value) && IsValidFloorValue(value))
                                        {
                                            // 根据属性名称的匹配度给分
                                            int score = CalculateAttributeScore(propName);
                                            if (attributeScores.ContainsKey(propName))
                                                attributeScores[propName] = attributeScores[propName] + score;
                                            else
                                                attributeScores[propName] = score;
                                            
                                            //LogManager.Info($"[FloorDetector] 属性 '{propName}' 累计得分: {attributeScores[propName]}");
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogManager.Warning($"[FloorDetector] 处理属性时出错: {ex.Message}");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogManager.Warning($"[FloorDetector] 处理属性类别时出错: {ex.Message}");
                        }
                    }
                    processedCount++;
                    //LogManager.Info($"[FloorDetector] 完成处理第 {processedCount} 个模型项");
                }
                catch (Exception ex)
                {
                    LogManager.Warning($"[FloorDetector] 处理模型项时出错: {ex.Message}");
                    LogManager.Warning($"[FloorDetector] 异常堆栈: {ex.StackTrace}");
                }
            }

            LogManager.Info($"[FloorDetector] 枚举完成，总共处理了 {processedCount} 个模型项");
            LogManager.Info($"[FloorDetector] 找到属性候选: {attributeScores.Count} 个");
            
            // 返回得分最高的属性
            var bestAttribute = attributeScores.OrderByDescending(kvp => kvp.Value).FirstOrDefault();

            if (bestAttribute.Value > 0)
            {
                LogManager.Info($"[FloorDetector] ===== FindBestFloorAttribute完成 ===== 选择最佳楼层属性: {bestAttribute.Key} (得分: {bestAttribute.Value})");
                return bestAttribute.Key;
            }

            LogManager.Info($"[FloorDetector] ===== FindBestFloorAttribute完成 ===== 未找到合适的楼层属性");
            return null;
        }

        private bool IsFloorRelatedAttribute(string attributeName)
        {
            if (string.IsNullOrEmpty(attributeName))
                return false;

            return COMMON_FLOOR_ATTRIBUTES.Any(attr =>
                attributeName.IndexOf(attr, StringComparison.OrdinalIgnoreCase) >= 0);
        }

        private int CalculateAttributeScore(string attributeName)
        {
            // 根据属性名称的匹配度计算分数
            string lowerName = attributeName.ToLower();

            // 最高优先级：完全匹配的标准楼层属性
            if (lowerName == "level" || lowerName == "floor" || lowerName == "楼层" || lowerName == "层")
                return 10;
            // 高优先级：包含标准楼层关键词
            if (lowerName.Contains("level") || lowerName.Contains("floor") || lowerName.Contains("层"))
                return 8;
            // 中高优先级：其他英文楼层词汇
            if (lowerName.Contains("storey") || lowerName.Contains("story"))
                return 6;
            // 中低优先级：高程相关（数值型，不够直观）
            if (lowerName.Contains("elevation"))
                return 4;

            return 3; // 默认分数
        }

        private bool IsValidFloorValue(string value)
        {
            if (string.IsNullOrEmpty(value))
                return false;

            // 检查是否为有效的楼层值
            // 数字楼层（如 "1", "2", "B1"）
            if (System.Text.RegularExpressions.Regex.IsMatch(value, @"^[B]?\d+[F]?$",
                System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                return true;

            // 文字楼层（如 "Ground Floor", "First Floor"）
            if (value.ToLower().Contains("floor") || value.ToLower().Contains("level"))
                return true;

            // 中文楼层（如 "一层", "地下一层"）
            if (value.Contains("层"))
                return true;

            return false;
        }

        #endregion

        #region 私有方法 - 结果验证和优化

        private List<FloorInfo> ValidateAndOptimizeFloors(List<FloorInfo> floors)
        {
            if (floors == null || floors.Count == 0)
                return floors;

            var validatedFloors = new List<FloorInfo>();

            foreach (var floor in floors)
            {
                // 验证楼层是否有效
                if (IsValidFloor(floor))
                {
                    // 优化楼层名称
                    floor.FloorName = OptimizeFloorName(floor.FloorName);
                    validatedFloors.Add(floor);
                }
                else
                {
                    LogManager.Warning($"[FloorDetector] 跳过无效楼层: {floor.FloorName}");
                }
            }

            // 按高程排序
            validatedFloors = validatedFloors.OrderBy(f => f.Elevation).ToList();

            // 重新编号（如果需要）
            RenumberFloorsIfNeeded(validatedFloors);

            return validatedFloors;
        }

        private bool IsValidFloor(FloorInfo floor)
        {
            // 检查楼层是否包含模型元素
            if (floor.Items == null || floor.Items.Count == 0)
                return false;

            // 检查楼层名称是否有效
            if (string.IsNullOrEmpty(floor.FloorName))
                return false;

            // 检查边界框是否有效 - 简化检查
            // BoundingBox3D是结构体，总是有值

            return true;
        }

        private string OptimizeFloorName(string originalName)
        {
            if (string.IsNullOrEmpty(originalName))
                return "Unknown_Floor";

            // 移除特殊字符，保留字母数字和下划线
            string optimized = System.Text.RegularExpressions.Regex.Replace(originalName, @"[^\w\u4e00-\u9fa5]", "_");

            // 移除多余的下划线
            optimized = System.Text.RegularExpressions.Regex.Replace(optimized, @"_+", "_");

            // 移除首尾下划线
            optimized = optimized.Trim('_');

            return string.IsNullOrEmpty(optimized) ? "Unknown_Floor" : optimized;
        }

        private void RenumberFloorsIfNeeded(List<FloorInfo> floors)
        {
            // 如果楼层名称都是自动生成的数字格式，重新编号
            bool needsRenumbering = floors.All(f =>
                System.Text.RegularExpressions.Regex.IsMatch(f.FloorName, @"^Floor_\d+$"));

            if (needsRenumbering)
            {
                for (int i = 0; i < floors.Count; i++)
                {
                    floors[i].FloorName = $"Floor_{i + 1:D2}";
                    floors[i].Properties["RenumberedIndex"] = i + 1;
                }
            }
        }

        #endregion

        #region 私有方法 - 辅助计算

        private double CalculateAverageElevation(ModelItemCollection items)
        {
            if (items == null || items.Count == 0)
                return 0.0;

            double totalElevation = 0.0;
            int validCount = 0;

            foreach (ModelItem item in items)
            {
                try
                {
                    var bounds = item.BoundingBox();
                    if (bounds.HasVolume)
                    {
                        totalElevation += bounds.Min.Z;
                        validCount++;
                    }
                }
                catch
                {
                    // 忽略无法获取边界框的元素
                }
            }

            return validCount > 0 ? totalElevation / validCount : 0.0;
        }

        private BoundingBox3D CalculateBounds(ModelItemCollection items)
        {
            if (items == null || items.Count == 0)
                return new BoundingBox3D();

            BoundingBox3D combinedBounds = null;

            foreach (ModelItem item in items)
            {
                try
                {
                    var itemBounds = item.BoundingBox();
                    if (itemBounds != null && itemBounds.HasVolume)
                    {
                        if (combinedBounds == null)
                        {
                            combinedBounds = itemBounds;
                        }
                        else
                        {
                            combinedBounds = combinedBounds.Extend(itemBounds);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // 记录错误但继续处理其他元素
                    LogManager.Warning($"[FloorDetector] 计算边界框时出错: {ex.Message}");
                }
            }

            return combinedBounds ?? new BoundingBox3D();
        }

        private string SanitizeFloorName(string floorName)
        {
            if (string.IsNullOrEmpty(floorName))
                return "Unknown_Floor";

            // 替换空格和特殊字符为下划线
            string sanitized = System.Text.RegularExpressions.Regex.Replace(floorName.Trim(), @"\s+", "_");

            // 移除或替换其他特殊字符
            sanitized = System.Text.RegularExpressions.Regex.Replace(sanitized, @"[^\w\u4e00-\u9fa5]", "_");

            // 移除多余的下划线
            sanitized = System.Text.RegularExpressions.Regex.Replace(sanitized, @"_+", "_");

            // 移除首尾下划线
            sanitized = sanitized.Trim('_');

            return string.IsNullOrEmpty(sanitized) ? "Unknown_Floor" : sanitized;
        }

        // GenerateFloorName方法已删除 - 随高程检测算法一起移除

        #endregion
    }

    /// <summary>
    /// 楼层信息类
    /// 独立的数据结构，用于表示楼层检测结果
    /// </summary>
    public class FloorInfo
    {
        /// <summary>
        /// 楼层名称
        /// </summary>
        public string FloorName { get; set; }

        /// <summary>
        /// 楼层标高
        /// </summary>
        public double Elevation { get; set; }

        /// <summary>
        /// 楼层边界框
        /// </summary>
        public BoundingBox3D Bounds { get; set; }

        /// <summary>
        /// 楼层包含的模型元素
        /// </summary>
        public ModelItemCollection Items { get; set; }

        /// <summary>
        /// 楼层元素数量
        /// </summary>
        public int ItemCount => Items?.Count ?? 0;

        /// <summary>
        /// 楼层附加属性
        /// </summary>
        public System.Collections.Generic.Dictionary<string, object> Properties { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public FloorInfo()
        {
            Items = new ModelItemCollection();
            Properties = new System.Collections.Generic.Dictionary<string, object>();
        }
    }
}