using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Navisworks.Api;
using NavisworksTransport.Utils;
using NavisworksTransport.PathPlanning;
using NavisworksTransport.Core.Config;

namespace NavisworksTransport
{
    /// <summary>
    /// 类别属性管理器 - 负责为模型元素添加和管理物流相关的自定义属性
    /// </summary>
    public class CategoryAttributeManager
    {
        /// <summary>
        /// 物流类别定义
        /// </summary>
        public static class LogisticsCategories
        {
            public const string LOGISTICS = "物流属性";
            public const string CATEGORY_INTERNAL_NAME = "物流属性_Internal";
        }

        /// <summary>
        /// 物流属性定义
        /// </summary>
        public static class LogisticsProperties
        {
            public const string TYPE = "类型";
            public const string TRAVERSABLE = "可通行";
            public const string PRIORITY = "优先级";
            public const string HEIGHT_LIMIT = "高度限制";
            public const string SPEED_LIMIT = "速度限制";
            public const string WIDTH_LIMIT = "宽度限制";
        }

        /// <summary>
        /// 物流元素类型
        /// </summary>
        public enum LogisticsElementType
        {
            /// <summary>
            /// 空洞 - 没有任何几何覆盖，不可通行（默认值）
            /// </summary>
            空洞 = 0,
            
            /// <summary>
            /// 障碍物 - 墙体、柱子、设备等，不可通行
            /// </summary>
            障碍物 = 1,
            
            /// <summary>
            /// 楼板 - 基础可通行区域，权重1.0
            /// </summary>
            楼板 = 2,
            
            /// <summary>
            /// 门 - 可通行，权重1.2
            /// </summary>
            门 = 3,
            
            /// <summary>
            /// 电梯 - 可通行，权重2.0
            /// </summary>
            电梯 = 4,
            
            /// <summary>
            /// 楼梯 - 可通行，权重3.0
            /// </summary>
            楼梯 = 5,
            
            /// <summary>
            /// 通道 - 可通行，优先路径，权重0.5
            /// </summary>
            通道 = 6,
            
            /// <summary>
            /// 走廊 - 可通行，权重0.6
            /// </summary>
            走廊 = 7,
            
            /// <summary>
            /// 装卸区 - 可通行，权重0.8
            /// </summary>
            装卸区 = 8,
            
            /// <summary>
            /// 停车位 - 可通行，权重0.9
            /// </summary>
            停车位 = 9,

            /// <summary>
            /// 空轨 - 空中运输路径，物体悬挂运行，权重0.7
            /// </summary>
            空轨 = 10,

            /// <summary>
            /// 无关项 - 不参与网格生成的大型构件（如地基、结构基础等）
            /// </summary>
            无关项 = 11
        }

        /// <summary>
        /// 为选定的模型项添加物流属性（使用配置默认值）
        /// </summary>
        /// <param name="items">要处理的模型项集合</param>
        /// <param name="elementType">物流元素类型</param>
        /// <returns>成功处理的项目数量</returns>
        public static int AddLogisticsAttributes(
            ModelItemCollection items,
            LogisticsElementType elementType)
        {
            var logistics = NavisworksTransport.Core.Config.ConfigManager.Instance.Current.Logistics;
            return AddLogisticsAttributes(
                items,
                elementType,
                logistics.Traversable,
                logistics.Priority,
                logistics.HeightLimitMeters,
                logistics.SpeedLimitMetersPerSecond,
                logistics.WidthLimitMeters);
        }

        /// <summary>
        /// 为选定的模型项添加物流属性（指定所有参数）
        /// </summary>
        /// <param name="items">要处理的模型项集合</param>
        /// <param name="elementType">物流元素类型</param>
        /// <param name="isTraversable">是否可通行</param>
        /// <param name="priority">优先级（1-10）</param>
        /// <param name="heightLimit">高度限制（米）</param>
        /// <param name="speedLimit">速度限制（米/秒）</param>
        /// <param name="widthLimit">宽度限制（米）</param>
        /// <returns>成功处理的项目数量</returns>
        public static int AddLogisticsAttributes(
            ModelItemCollection items,
            LogisticsElementType elementType,
            bool isTraversable,
            int priority,
            double heightLimit,
            double speedLimit,
            double widthLimit)
        {
            if (items == null || items.Count == 0)
            {
                return 0;
            }

            // 准备属性字典
            var properties = new Dictionary<string, string>
            {
                { LogisticsProperties.TYPE, elementType.ToString() },
                { LogisticsProperties.TRAVERSABLE, isTraversable ? "是" : "否" },
                { LogisticsProperties.PRIORITY, priority.ToString() },
                { LogisticsProperties.HEIGHT_LIMIT, heightLimit.ToString("F2") + " m" },
                { LogisticsProperties.SPEED_LIMIT, speedLimit.ToString("F2") + " m/s" },
                { LogisticsProperties.WIDTH_LIMIT, widthLimit.ToString("F2") + " m" }
            };

            // 准备内部名称字典
            var propertyInternalNames = new Dictionary<string, string>
            {
                { LogisticsProperties.TYPE, elementType.ToString() + "_Internal" },
                { LogisticsProperties.TRAVERSABLE, "Traversable_Internal" },
                { LogisticsProperties.PRIORITY, "Priority_Internal" },
                { LogisticsProperties.HEIGHT_LIMIT, "HeightLimit_Internal" },
                { LogisticsProperties.SPEED_LIMIT, "SpeedLimit_Internal" },
                { LogisticsProperties.WIDTH_LIMIT, "WidthLimit_Internal" }
            };

            int successCount = NavisworksComPropertyManager.SetUserDefinedProperties(
                items,
                LogisticsCategories.LOGISTICS,
                LogisticsCategories.CATEGORY_INTERNAL_NAME,
                properties,
                propertyInternalNames);

            LogManager.Info($"[属性添加] 添加操作完成，成功添加 {successCount} 个模型的属性");

            // 如果是空轨类型，预计算基准路径
            if (elementType == LogisticsElementType.空轨 && successCount > 0)
            {
                PreCalculateRailBaselinePaths(items);
            }

            return successCount;
        }

        /// <summary>
        /// 检查模型项是否已有物流属性
        /// </summary>
        /// <param name="item">要检查的模型项</param>
        /// <returns>如果已有物流属性返回true</returns>
        public static bool HasLogisticsAttributes(ModelItem item)
        {
            try
            {
                // 检查自定义属性
                foreach (PropertyCategory category in item.PropertyCategories)
                {
                    if (category.DisplayName == LogisticsCategories.LOGISTICS)
                    {
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"检查物流属性时发生错误: {ex.Message}");
            }

            return false;
        }

        /// <summary>
        /// 获取模型项的物流属性值
        /// </summary>
        /// <param name="item">模型项</param>
        /// <param name="propertyName">属性名称</param>
        /// <returns>属性值，如果不存在返回空字符串</returns>
        public static string GetLogisticsPropertyValue(ModelItem item, string propertyName)
        {
            try
            {
                foreach (PropertyCategory category in item.PropertyCategories)
                {
                    if (category.DisplayName == LogisticsCategories.LOGISTICS)
                    {
                        foreach (DataProperty property in category.Properties)
                        {
                            if (property.DisplayName == propertyName)
                            {
                                return property.Value.ToDisplayString();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取物流属性值时发生错误: {ex.Message}");
            }

            return string.Empty;
        }

        /// <summary>
        /// 获取指定类型的物流项目
        /// </summary>
        /// <param name="elementType">物流元素类型</param>
        /// <param name="document">文档，如果为null则使用ActiveDocument</param>
        /// <returns>指定类型的物流项目列表</returns>
        public static List<ModelItem> GetLogisticsItemsByType(LogisticsElementType elementType)
        {
            try
            {
                // 使用 Search API 搜索当前活动文档
                using (var search = new Search())
                {
                    // 搜索整个文档的根项及其所有后代
                    search.Selection.SelectAll();
                    search.Locations = SearchLocations.DescendantsAndSelf;
                    
                    var searchConditions = search.SearchConditions;
                    searchConditions.Clear();
                    
                    // 搜索条件：必须有物流分类
                    searchConditions.Add(SearchCondition.HasCategoryByDisplayName(LogisticsCategories.LOGISTICS));
                    
                    // 搜索条件：类型属性等于指定值
                    searchConditions.Add(
                        SearchCondition.HasPropertyByDisplayName(LogisticsCategories.LOGISTICS, LogisticsProperties.TYPE)
                        .EqualValue(VariantData.FromDisplayString(elementType.ToString())));
                    
                    // 执行搜索并返回列表
                    return search.FindAll(Application.ActiveDocument, false).ToList();
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[CategoryAttributeManager] 获取物流项目失败: {ex.Message}");
                return new List<ModelItem>();
            }
        }

        /// <summary>
        /// 获取指定物流元素类型的所有模型项（字符串版本，支持自定义类别）
        /// </summary>
        /// <param name="typeId">类型ID（内置类别名称或自定义类别ID）</param>
        /// <returns>符合条件的模型项列表</returns>
        public static List<ModelItem> GetLogisticsItemsByType(string typeId)
        {
            try
            {
                // 使用 Search API 搜索当前活动文档
                using (var search = new Search())
                {
                    // 搜索整个文档的根项及其所有后代
                    search.Selection.SelectAll();
                    search.Locations = SearchLocations.DescendantsAndSelf;
                    
                    var searchConditions = search.SearchConditions;
                    searchConditions.Clear();
                    
                    // 搜索条件：必须有物流分类
                    searchConditions.Add(SearchCondition.HasCategoryByDisplayName(LogisticsCategories.LOGISTICS));
                    
                    // 搜索条件：类型属性等于指定值
                    searchConditions.Add(
                        SearchCondition.HasPropertyByDisplayName(LogisticsCategories.LOGISTICS, LogisticsProperties.TYPE)
                        .EqualValue(VariantData.FromDisplayString(typeId)));
                    
                    // 执行搜索并返回列表
                    return search.FindAll(Application.ActiveDocument, false).ToList();
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[CategoryAttributeManager] 获取物流项目失败: {ex.Message}");
                return new List<ModelItem>();
            }
        }

        /// <summary>
        /// 根据物流属性筛选模型项
        /// </summary>
        /// <param name="items">要筛选的模型项集合</param>
        /// <param name="elementType">要筛选的元素类型</param>
        /// <returns>匹配条件的模型项集合</returns>
        public static ModelItemCollection FilterByLogisticsType(ModelItemCollection items, LogisticsElementType elementType)
        {
            try
            {
                // 使用SearchAPI优化：直接搜索具有指定类型值的物流项目
                using (var search = new Search())
                {
                    // 将输入的ModelItemCollection转换为搜索选择
                    search.Selection.CopyFrom(items);
                    search.Locations = SearchLocations.DescendantsAndSelf;
                    
                    var searchConditions = search.SearchConditions;
                    searchConditions.Clear();
                    
                    // 搜索条件：必须有物流分类
                    searchConditions.Add(SearchCondition.HasCategoryByDisplayName(LogisticsCategories.LOGISTICS));
                    
                    // 搜索条件：类型属性等于指定值
                    searchConditions.Add(
                        SearchCondition.HasPropertyByDisplayName(LogisticsCategories.LOGISTICS, LogisticsProperties.TYPE)
                        .EqualValue(VariantData.FromDisplayString(elementType.ToString())));
                    
                    return search.FindAll(Application.ActiveDocument, false);
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"按物流类型过滤失败: {ex.Message}");
                
                // 如果SearchAPI失败，回退到原始实现
                ModelItemCollection filteredItems = new ModelItemCollection();
                foreach (ModelItem item in items)
                {
                    string typeValue = GetLogisticsPropertyValue(item, LogisticsProperties.TYPE);
                    if (typeValue == elementType.ToString())
                    {
                        filteredItems.Add(item);
                    }
                }
                return filteredItems;
            }
        }

        /// <summary>
        /// 按物流元素类型筛选模型项（字符串版本，支持自定义类别）
        /// </summary>
        /// <param name="items">要筛选的模型项集合</param>
        /// <param name="typeId">类型ID（内置类别名称或自定义类别ID）</param>
        /// <returns>符合条件的模型项集合</returns>
        public static ModelItemCollection FilterByLogisticsType(ModelItemCollection items, string typeId)
        {
            try
            {
                // 使用SearchAPI优化：直接搜索具有指定类型值的物流项目
                using (var search = new Search())
                {
                    // 将输入的ModelItemCollection转换为搜索选择
                    search.Selection.CopyFrom(items);
                    search.Locations = SearchLocations.DescendantsAndSelf;
                    
                    var searchConditions = search.SearchConditions;
                    searchConditions.Clear();
                    
                    // 搜索条件：必须有物流分类
                    searchConditions.Add(SearchCondition.HasCategoryByDisplayName(LogisticsCategories.LOGISTICS));
                    
                    // 搜索条件：类型属性等于指定值
                    searchConditions.Add(
                        SearchCondition.HasPropertyByDisplayName(LogisticsCategories.LOGISTICS, LogisticsProperties.TYPE)
                        .EqualValue(VariantData.FromDisplayString(typeId)));
                    
                    return search.FindAll(Application.ActiveDocument, false);
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"按物流类型过滤失败: {ex.Message}");
                
                // 如果SearchAPI失败，回退到原始实现
                ModelItemCollection filteredItems = new ModelItemCollection();
                foreach (ModelItem item in items)
                {
                    string typeValue = GetLogisticsPropertyValue(item, LogisticsProperties.TYPE);
                    if (typeValue == typeId)
                    {
                        filteredItems.Add(item);
                    }
                }
                return filteredItems;
            }
        }

        /// <summary>
        /// 筛选可通行的模型项
        /// </summary>
        /// <param name="items">要筛选的模型项集合</param>
        /// <returns>可通行的模型项集合</returns>
        public static ModelItemCollection FilterTraversableItems(ModelItemCollection items)
        {
            try
            {
                // 使用SearchAPI优化：直接搜索可通行的物流项目
                using (var search = new Search())
                {
                    // 将输入的ModelItemCollection转换为搜索选择
                    search.Selection.CopyFrom(items);
                    search.Locations = SearchLocations.DescendantsAndSelf;
                    
                    var searchConditions = search.SearchConditions;
                    searchConditions.Clear();
                    
                    // 搜索条件：必须有物流分类
                    searchConditions.Add(SearchCondition.HasCategoryByDisplayName(LogisticsCategories.LOGISTICS));
                    
                    // 搜索条件：可通行属性等于"是"
                    searchConditions.Add(
                        SearchCondition.HasPropertyByDisplayName(LogisticsCategories.LOGISTICS, LogisticsProperties.TRAVERSABLE)
                        .EqualValue(VariantData.FromDisplayString("是")));
                    
                    return search.FindAll(Application.ActiveDocument, false);
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"过滤可通行物流项目失败: {ex.Message}");
                
                // 如果SearchAPI失败，回退到原始实现
                ModelItemCollection filteredItems = new ModelItemCollection();
                foreach (ModelItem item in items)
                {
                    string traversableValue = GetLogisticsPropertyValue(item, LogisticsProperties.TRAVERSABLE);
                    if (traversableValue == "是")
                    {
                        filteredItems.Add(item);
                    }
                }
                return filteredItems;
            }
        }

        /// <summary>
        /// 获取文档中所有具有物流属性的模型项
        /// </summary>
        /// <param name="document">Navisworks文档</param>
        /// <returns>具有物流属性的模型项集合</returns>
        public static ModelItemCollection GetAllLogisticsItems()
        {
            try
            {
                using (var search = new Search())
                {
                    search.Selection.SelectAll();
                    var searchConditions = search.SearchConditions;
                    searchConditions.Clear();
                    var hasLogisticsCondition = SearchCondition.HasCategoryByDisplayName(LogisticsCategories.LOGISTICS);
                    searchConditions.Add(hasLogisticsCondition);
                    return search.FindAll(Application.ActiveDocument, false);
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"获取物流属性模型项失败: {ex.Message}");
                return new ModelItemCollection();
            }
        }

        /// <summary>
        /// 获取文档中所有可通行的物流模型项（具有物流属性且通行性为"是"）
        /// </summary>
        /// <param name="document">Navisworks文档</param>
        /// <returns>可通行的物流模型项集合</returns>
        public static ModelItemCollection GetAllTraversableLogisticsItems()
        {
            var allLogisticsItems = GetAllLogisticsItems();
            return FilterTraversableItems(allLogisticsItems);
        }

        /// <summary>
        /// 根据高度限制筛选适用的通道
        /// </summary>
        /// <param name="items">要筛选的模型项集合</param>
        /// <param name="heightLimit">高度限制（米）</param>
        /// <returns>适用的通道集合</returns>
        public static ModelItemCollection FilterByHeightLimit(ModelItemCollection items, double heightLimit)
        {
            try
            {
                // 对于高度限制过滤，采用混合方式：
                // 1. 使用SearchAPI快速获取有物流属性的项目
                // 2. 再进行高度限制过滤
                
                ModelItemCollection logisticsItems;
                
                using (var search = new Search())
                {
                    // 将输入的ModelItemCollection转换为搜索选择
                    search.Selection.CopyFrom(items);
                    search.Locations = SearchLocations.DescendantsAndSelf;
                    
                    var searchConditions = search.SearchConditions;
                    searchConditions.Clear();
                    
                    // 搜索条件：必须有物流分类
                    searchConditions.Add(SearchCondition.HasCategoryByDisplayName(LogisticsCategories.LOGISTICS));
                    
                    logisticsItems = search.FindAll(Application.ActiveDocument, false);
                }
                
                // 对获取到的物流项目进行高度限制过滤
                ModelItemCollection filteredItems = new ModelItemCollection();
                foreach (ModelItem item in logisticsItems)
                {
                    string heightValue = GetLogisticsPropertyValue(item, LogisticsProperties.HEIGHT_LIMIT);
                    if (string.IsNullOrEmpty(heightValue))
                    {
                        // 如果没有设置高度限制，使用默认值3.0米，符合条件则添加
                        if (heightLimit <= 3.0)
                        {
                            filteredItems.Add(item);
                        }
                    }
                    else
                    {
                        // 解析高度限制值
                        string numericValue = heightValue.Replace("m", "").Replace("米", "").Trim();
                        if (double.TryParse(numericValue, out double itemHeightLimit))
                        {
                            if (heightLimit <= itemHeightLimit)
                            {
                                filteredItems.Add(item);
                            }
                        }
                    }
                }
                
                return filteredItems;
            }
            catch (Exception ex)
            {
                LogManager.Error($"按高度限制过滤失败: {ex.Message}");
                
                // 如果SearchAPI失败，回退到完全原始实现
                ModelItemCollection filteredItems = new ModelItemCollection();
                foreach (ModelItem item in items)
                {
                    string heightValue = GetLogisticsPropertyValue(item, LogisticsProperties.HEIGHT_LIMIT);
                    if (string.IsNullOrEmpty(heightValue))
                    {
                        if (heightLimit <= 3.0)
                        {
                            filteredItems.Add(item);
                        }
                    }
                    else
                    {
                        string numericValue = heightValue.Replace("m", "").Replace("米", "").Trim();
                        if (double.TryParse(numericValue, out double itemHeightLimit))
                        {
                            if (heightLimit <= itemHeightLimit)
                            {
                                filteredItems.Add(item);
                            }
                        }
                    }
                }
                return filteredItems;
            }
        }

        /// <summary>
        /// 获取模型项的物流元素类型
        /// </summary>
        /// <param name="item">模型项</param>
        /// <returns>物流元素类型，如果没有设置则返回障碍物</returns>
        public static LogisticsElementType GetLogisticsElementType(ModelItem item)
        {
            try
            {
                string typeValue = GetLogisticsPropertyValue(item, LogisticsProperties.TYPE);
                if (!string.IsNullOrEmpty(typeValue))
                {
                    if (Enum.TryParse<LogisticsElementType>(typeValue, out LogisticsElementType result))
                    {
                        return result;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取物流元素类型时发生错误: {ex.Message}");
            }

            // 默认返回障碍物类型
            return LogisticsElementType.障碍物;
        }

        /// <summary>
        /// 预计算空轨基准路径
        /// </summary>
        /// <param name="items">已设置为空轨的模型项集合</param>
        private static void PreCalculateRailBaselinePaths(ModelItemCollection items)
        {
            if (items == null || items.Count == 0)
                return;

            // 确保在主线程上执行（Navisworks COM API 要求）
            if (!NavisworksApiHelper.IsOnUIThread())
            {
                NavisworksApiHelper.ExecuteOnUIThread(() => PreCalculateRailBaselinePaths(items));
                return;
            }

            LogManager.Debug($"[空轨] 开始预计算 {items.Count} 个空轨模型的基准路径");

            int successCount = 0;
            int failCount = 0;

            foreach (ModelItem item in items)
            {
                try
                {
                    // 调用RailGeometryHelper提取基准路径
                    var baselinePath = RailGeometryHelper.ExtractRailBaselinePath(item);

                    if (baselinePath != null && baselinePath.PathPoints != null && baselinePath.PathPoints.Count > 0)
                    {
                        successCount++;
                        LogManager.Debug($"[空轨] 成功提取模型 {item.DisplayName} 的基准路径，共 {baselinePath.PathPoints.Count} 个点，总长度 {baselinePath.TotalLength:F2} 模型单位");

                        // 自动可视化基准路径
                        var railModelId = $"{item.DisplayName}_{item.GetHashCode()}";
                        PathPointRenderPlugin.Instance.RenderRailBaseline(railModelId, baselinePath.PathPoints);
                    }
                    else
                    {
                        failCount++;
                        LogManager.Warning($"[空轨] 模型 {item.DisplayName} 的基准路径提取失败或路径为空");
                    }
                }
                catch (Exception ex)
                {
                    failCount++;
                    LogManager.Error($"[空轨] 预计算模型 {item.DisplayName} 的基准路径时发生错误: {ex.Message}");
                }
            }

            LogManager.Info($"[空轨] 基准路径预计算完成，成功 {successCount} 个，失败 {failCount} 个");
        }

        /// <summary>
        /// 删除选定模型项的物流属性
        /// </summary>
        /// <param name="items">要删除属性的模型项集合</param>
        /// <returns>成功删除属性的项目数量</returns>
        public static int RemoveLogisticsAttributes(ModelItemCollection items)
        {
            if (items == null || items.Count == 0)
            {
                return 0;
            }

            int successCount = NavisworksComPropertyManager.RemoveUserDefinedCategory(
                items, 
                LogisticsCategories.LOGISTICS);

            // 轻量级缓存刷新：触发Navisworks内部状态更新
            if (successCount > 0)
            {
                NavisworksApiHelper.SafeCacheRefresh("属性删除");
            }

            return successCount;
        }


        /// <summary>
        /// 更新选定模型项的物流属性
        /// </summary>
        /// <param name="items">要更新属性的模型项集合</param>
        /// <param name="elementType">新的物流元素类型</param>
        /// <param name="isTraversable">是否可通行</param>
        /// <param name="priority">优先级（1-10）</param>
        /// <param name="heightLimit">高度限制（米）</param>
        /// <param name="speedLimit">速度限制（米/秒）</param>
        /// <param name="widthLimit">宽度限制（米）</param>
        /// <returns>成功更新的项目数量</returns>
        public static int UpdateLogisticsAttributes(
            ModelItemCollection items,
            LogisticsElementType elementType,
            bool isTraversable,
            int priority,
            double heightLimit,
            double speedLimit,
            double widthLimit)
        {
            if (items == null || items.Count == 0)
            {
                return 0;
            }

            // 准备属性字典
            var properties = new Dictionary<string, string>
            {
                { LogisticsProperties.TYPE, elementType.ToString() },
                { LogisticsProperties.TRAVERSABLE, isTraversable ? "是" : "否" },
                { LogisticsProperties.PRIORITY, priority.ToString() },
                { LogisticsProperties.HEIGHT_LIMIT, heightLimit.ToString("F2") + " m" },
                { LogisticsProperties.SPEED_LIMIT, speedLimit.ToString("F2") + " m/s" },
                { LogisticsProperties.WIDTH_LIMIT, widthLimit.ToString("F2") + " m" }
            };

            // 准备内部名称字典
            var propertyInternalNames = new Dictionary<string, string>
            {
                { LogisticsProperties.TYPE, elementType.ToString() + "_Internal" },
                { LogisticsProperties.TRAVERSABLE, "Traversable_Internal" },
                { LogisticsProperties.PRIORITY, "Priority_Internal" },
                { LogisticsProperties.HEIGHT_LIMIT, "HeightLimit_Internal" },
                { LogisticsProperties.SPEED_LIMIT, "SpeedLimit_Internal" },
                { LogisticsProperties.WIDTH_LIMIT, "WidthLimit_Internal" }
            };

            int successCount = NavisworksComPropertyManager.SetUserDefinedProperties(
                items, 
                LogisticsCategories.LOGISTICS, 
                LogisticsCategories.CATEGORY_INTERNAL_NAME,
                properties,
                propertyInternalNames,
                overwriteExisting: true);

            LogManager.Info($"[属性更新] 更新操作完成，成功更新 {successCount} 个模型的属性");
            return successCount;
        }

        /// <summary>
        /// 通过COM API获取物流属性值（解决缓存同步问题）
        /// </summary>
        /// <param name="item">模型项</param>
        /// <param name="propertyName">属性名称</param>
        /// <returns>属性值，如果不存在返回空字符串</returns>
        public static string GetLogisticsPropertyValueViaCom(ModelItem item, string propertyName)
        {
            return NavisworksComPropertyManager.GetPropertyValue(
                item,
                LogisticsCategories.LOGISTICS,
                propertyName);
        }

        /// <summary>
        /// 获取模型项的速度限制
        /// </summary>
        /// <param name="item">模型项</param>
        /// <returns>速度限制（米/秒），如果未设置返回0</returns>
        public static double GetSpeedLimit(ModelItem item)
        {
            try
            {
                string speedStr = GetLogisticsPropertyValueViaCom(item, LogisticsProperties.SPEED_LIMIT);

                if (string.IsNullOrEmpty(speedStr))
                    return 0;

                // 使用统一的解析方法处理限速值
                double parsedValue = ParseLogisticsLimitValue(speedStr, "限速");

                // ParseLogisticsLimitValue返回-1表示解析失败，我们转换为0
                return parsedValue > 0 ? parsedValue : 0;
            }
            catch (Exception ex)
            {
                LogManager.Warning($"获取速度限制失败: {ex.Message}");
                return 0;
            }
        }

        /// <summary>
        /// 通用方法：获取模型项的指定属性值（不限于物流属性）
        /// </summary>
        /// <param name="item">模型项</param>
        /// <param name="propertyName">属性名称</param>
        /// <returns>属性值，如果不存在返回null</returns>
        public static string GetGeneralPropertyValue(ModelItem item, string propertyName)
        {
            try
            {
                foreach (PropertyCategory category in item.PropertyCategories)
                {
                    foreach (DataProperty property in category.Properties)
                    {
                        if (string.Equals(property.DisplayName, propertyName, StringComparison.OrdinalIgnoreCase))
                        {
                            return property.Value?.ToDisplayString();
                        }
                    }
                }
                return null;
            }
            catch (Exception ex)
            {
                LogManager.Error($"获取通用属性值时发生错误: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"获取通用属性值时发生错误: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 通用方法：获取模型项的指定属性值并进行字符串修剪（用于AttributeGrouper等场景）
        /// </summary>
        /// <param name="item">模型项</param>
        /// <param name="propertyName">属性名称</param>
        /// <returns>修剪后的属性值，如果不存在返回null</returns>
        public static string GetGeneralPropertyValueTrimmed(ModelItem item, string propertyName)
        {
            try
            {
                foreach (PropertyCategory category in item.PropertyCategories)
                {
                    foreach (DataProperty property in category.Properties)
                    {
                        if (string.Equals(property.DisplayName, propertyName, StringComparison.OrdinalIgnoreCase))
                        {
                            return property.Value?.ToString()?.Trim();
                        }
                    }
                }
                return null;
            }
            catch (Exception ex)
            {
                LogManager.Error($"获取修剪后的通用属性值时发生错误: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"获取修剪后的通用属性值时发生错误: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 安全获取属性值的通用方法，会根据数据类型选择合适的转换方式
        /// </summary>
        /// <param name="property">数据属性</param>
        /// <returns>安全转换后的属性值字符串</returns>
        public static string GetSafePropertyValue(DataProperty property)
        {
            try
            {
                if (property?.Value == null)
                    return null;

                // 检查是否为DisplayString类型
                if (property.Value.IsDisplayString)
                {
                    return property.Value.ToDisplayString()?.Trim();
                }
                else
                {
                    // 对于非DisplayString类型，使用ToString()
                    return property.Value.ToString()?.Trim();
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"安全获取属性值时发生错误: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"安全获取属性值时发生错误: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 通用方法：使用安全方式获取模型项的指定属性值
        /// </summary>
        /// <param name="item">模型项</param>
        /// <param name="propertyName">属性名称</param>
        /// <returns>安全获取的属性值，如果不存在返回null</returns>
        public static string GetGeneralPropertyValueSafe(ModelItem item, string propertyName)
        {
            try
            {
                foreach (PropertyCategory category in item.PropertyCategories)
                {
                    foreach (DataProperty property in category.Properties)
                    {
                        if (string.Equals(property.DisplayName, propertyName, StringComparison.OrdinalIgnoreCase))
                        {
                            return GetSafePropertyValue(property);
                        }
                    }
                }
                return null;
            }
            catch (Exception ex)
            {
                LogManager.Error($"安全获取通用属性值时发生错误: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"安全获取通用属性值时发生错误: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 获取模型项的完整物流属性信息
        /// </summary>
        /// <param name="item">模型项</param>
        /// <returns>物流属性信息，如果不存在返回null</returns>
        public static LogisticsAttributeInfo GetLogisticsAttributeInfo(ModelItem item)
        {
            if (!HasLogisticsAttributes(item))
            {
                return null;
            }

            try
            {
                var info = new LogisticsAttributeInfo
                {
                    // 使用COM API获取各个属性值以确保数据一致性
                    ElementType = GetLogisticsPropertyValueViaCom(item, LogisticsProperties.TYPE),
                    IsTraversable = GetLogisticsPropertyValueViaCom(item, LogisticsProperties.TRAVERSABLE) == "是"
                };

                string priorityStr = GetLogisticsPropertyValueViaCom(item, LogisticsProperties.PRIORITY);
                if (int.TryParse(priorityStr, out int priority))
                {
                    info.Priority = priority;
                }
                
                string heightStr = GetLogisticsPropertyValueViaCom(item, LogisticsProperties.HEIGHT_LIMIT);
                if (heightStr.Contains("m") || heightStr.Contains("米"))
                {
                    heightStr = heightStr.Replace("m", "").Replace("米", "").Trim();
                    if (double.TryParse(heightStr, out double height))
                    {
                        info.HeightLimit = height;
                    }
                }
                else if (double.TryParse(heightStr, out double heightValue))
                {
                    info.HeightLimit = heightValue;
                }
                
                string speedStr = GetLogisticsPropertyValueViaCom(item, LogisticsProperties.SPEED_LIMIT);
                if (speedStr.Contains("m/s"))
                {
                    speedStr = speedStr.Replace("m/s", "").Trim();
                    if (double.TryParse(speedStr, out double speed))
                    {
                        info.SpeedLimit = speed;
                    }
                }
                else if (double.TryParse(speedStr, out double speedValue))
                {
                    info.SpeedLimit = speedValue;
                }

                string widthStr = GetLogisticsPropertyValueViaCom(item, LogisticsProperties.WIDTH_LIMIT);
                if (widthStr.Contains("m") || widthStr.Contains("米"))
                {
                    widthStr = widthStr.Replace("m", "").Replace("米", "").Trim();
                    if (double.TryParse(widthStr, out double width))
                    {
                        info.WidthLimit = width;
                    }
                }
                else if (double.TryParse(widthStr, out double widthValue))
                {
                    info.WidthLimit = widthValue;
                }

                return info;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取物流属性信息时发生错误: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 设置模型项的可通行性属性
        /// </summary>
        /// <param name="item">模型项</param>
        /// <param name="isTraversable">是否可通行</param>
        /// <returns>操作是否成功</returns>
        public bool SetTraversable(ModelItem item, bool isTraversable)
        {
            return NavisworksComPropertyManager.UpdatePropertyValue(
                item,
                LogisticsCategories.LOGISTICS,
                LogisticsCategories.CATEGORY_INTERNAL_NAME,
                LogisticsProperties.TRAVERSABLE,
                isTraversable ? "是" : "否");
        }

        /// <summary>
        /// 设置模型项的自定义属性
        /// </summary>
        /// <param name="item">模型项</param>
        /// <param name="propertyName">属性名称</param>
        /// <param name="propertyValue">属性值</param>
        /// <param name="overwriteExisting">是否覆盖现有属性</param>
        /// <returns>操作是否成功</returns>
        public bool SetCustomAttribute(ModelItem item, string propertyName, string propertyValue, bool overwriteExisting = true)
        {
            return NavisworksComPropertyManager.UpdatePropertyValue(
                item,
                LogisticsCategories.LOGISTICS,
                LogisticsCategories.CATEGORY_INTERNAL_NAME,
                propertyName,
                propertyValue);
        }

        /// <summary>
        /// 解析物流属性限值字符串，支持带单位的格式（如 "3.00 m"）
        /// 这是一个通用方法，用于解析限宽、限高等属性值
        /// </summary>
        /// <param name="limitValueStr">限值属性字符串</param>
        /// <param name="propertyName">属性名称（用于日志记录）</param>
        /// <returns>解析出的数值（米），-1表示解析失败</returns>
        public static double ParseLogisticsLimitValue(string limitValueStr, string propertyName = "限值")
        {
            if (string.IsNullOrEmpty(limitValueStr))
                return -1;
                
            try
            {
                // 移除单位后缀和多余空格（按从复杂到简单的顺序处理）
                string cleanValue = limitValueStr.Trim()
                    .Replace(" m/s", "")   // 先移除 " m/s"
                    .Replace("m/s", "")    // 再移除 "m/s"
                    .Replace(" m", "")     // 然后移除 " m"
                    .Replace("m", "")      // 移除单独的 "m"
                    .Replace(" ", "");     // 最后移除所有空格

                if (double.TryParse(cleanValue, out double value) && value > 0)
                {
                    return value;
                }

                LogManager.Debug($"【{propertyName}解析】无法解析数值: '{limitValueStr}' -> '{cleanValue}'");
                return -1;
            }
            catch (Exception ex)
            {
                LogManager.Debug($"【{propertyName}解析】解析异常: '{limitValueStr}', 错误: {ex.Message}");
                return -1;
            }
        }
        #region 自定义类别支持

        private static Core.Config.CustomCategoryConfig _customCategoryConfig;
        private static readonly object _customCategoryLock = new object();

        /// <summary>
        /// 自定义类别配置（懒加载）
        /// </summary>
        public static Core.Config.CustomCategoryConfig CustomCategories
        {
            get
            {
                if (_customCategoryConfig == null)
                {
                    lock (_customCategoryLock)
                    {
                        if (_customCategoryConfig == null)
                        {
                            _customCategoryConfig = new Core.Config.CustomCategoryConfig();
                        }
                    }
                }
                return _customCategoryConfig;
            }
        }

        /// <summary>
        /// 重新加载自定义类别配置
        /// </summary>
        public static void ReloadCustomCategories()
        {
            lock (_customCategoryLock)
            {
                // 重新创建实例，从 ConfigManager 获取最新数据
                _customCategoryConfig = new Core.Config.CustomCategoryConfig();
                LogManager.Info("[CategoryAttributeManager] 自定义类别配置已重新加载");
            }
        }

        /// <summary>
        /// 获取模型项的物流元素类型（字符串形式，支持自定义类别）
        /// </summary>
        /// <param name="item">模型项</param>
        /// <returns>类别ID字符串，如果没有设置则返回"障碍物"</returns>
        public static string GetCategoryId(ModelItem item)
        {
            try
            {
                string typeValue = GetLogisticsPropertyValue(item, LogisticsProperties.TYPE);
                if (!string.IsNullOrEmpty(typeValue))
                {
                    // 先检查是否为内置类别
                    if (Enum.TryParse<LogisticsElementType>(typeValue, out _))
                    {
                        return typeValue;
                    }

                    // 再检查是否为自定义类别
                    if (CustomCategories.CategoryExists(typeValue))
                    {
                        return typeValue;
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[CategoryAttributeManager] 获取类别ID失败: {ex.Message}");
            }

            // 默认返回障碍物
            return LogisticsElementType.障碍物.ToString();
        }

        /// <summary>
        /// 获取类别定义（内置或自定义）
        /// </summary>
        /// <param name="categoryId">类别ID</param>
        /// <returns>类别定义，如果不存在返回null</returns>
        public static Core.Config.CategoryDefinition GetCategoryDefinition(string categoryId)
        {
            if (string.IsNullOrEmpty(categoryId))
                return null;

            // 先查内置
            if (Enum.TryParse<LogisticsElementType>(categoryId, out var builtInType))
            {
                return Core.Config.BuiltInCategories.GetByType(builtInType);
            }

            // 再查自定义
            return CustomCategories.GetCategory(categoryId);
        }

        /// <summary>
        /// 获取类别的寻路权重
        /// </summary>
        /// <param name="categoryId">类别ID</param>
        /// <returns>权重值，未知类别返回1.0</returns>
        public static double GetCategoryWeight(string categoryId)
        {
            // 简化为返回默认值，后续可根据需要扩展
            // 障碍物类别返回最大权重
            if (categoryId?.Equals("障碍物", StringComparison.OrdinalIgnoreCase) == true ||
                categoryId?.Equals("空洞", StringComparison.OrdinalIgnoreCase) == true)
            {
                return double.MaxValue;
            }
            return 1.0;
        }

        /// <summary>
        /// 检查类别是否可通行
        /// </summary>
        /// <param name="categoryId">类别ID</param>
        /// <returns>是否可通行</returns>
        public static bool IsCategoryTraversable(string categoryId)
        {
            // 简化为根据类别名称判断
            if (categoryId?.Equals("障碍物", StringComparison.OrdinalIgnoreCase) == true ||
                categoryId?.Equals("空洞", StringComparison.OrdinalIgnoreCase) == true ||
                categoryId?.Equals("无关项", StringComparison.OrdinalIgnoreCase) == true)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 获取所有可用类别（内置 + 自定义）
        /// </summary>
        public static IEnumerable<Core.Config.CategoryDefinition> GetAllAvailableCategories()
        {
            return CustomCategories.GetAllCategories();
        }

        /// <summary>
        /// 检查是否为自定义类别
        /// </summary>
        public static bool IsCustomCategory(string categoryId)
        {
            return !string.IsNullOrEmpty(categoryId) && 
                   !Enum.TryParse<LogisticsElementType>(categoryId, out _);
        }

        /// <summary>
        /// 为选中的模型项添加物流属性（支持自定义类别）
        /// </summary>
        public static int AddLogisticsAttributes(
            ModelItemCollection items,
            string categoryId,
            bool isTraversable,
            int priority,
            double heightLimit,
            double speedLimit,
            double widthLimit)
        {
            if (items == null || items.Count == 0)
                return 0;

            if (string.IsNullOrEmpty(categoryId))
            {
                LogManager.Warning("[CategoryAttributeManager] 类别ID为空，无法设置属性");
                return 0;
            }

            // 准备属性字典
            var properties = new Dictionary<string, string>
            {
                { LogisticsProperties.TYPE, categoryId },
                { LogisticsProperties.TRAVERSABLE, isTraversable ? "是" : "否" },
                { LogisticsProperties.PRIORITY, priority.ToString() },
                { LogisticsProperties.HEIGHT_LIMIT, heightLimit.ToString("F2") + " m" },
                { LogisticsProperties.SPEED_LIMIT, speedLimit.ToString("F2") + " m/s" },
                { LogisticsProperties.WIDTH_LIMIT, widthLimit.ToString("F2") + " m" }
            };

            // 准备内部名称字典
            var propertyInternalNames = new Dictionary<string, string>
            {
                { LogisticsProperties.TYPE, categoryId + "_Internal" },
                { LogisticsProperties.TRAVERSABLE, "Traversable_Internal" },
                { LogisticsProperties.PRIORITY, "Priority_Internal" },
                { LogisticsProperties.HEIGHT_LIMIT, "HeightLimit_Internal" },
                { LogisticsProperties.SPEED_LIMIT, "SpeedLimit_Internal" },
                { LogisticsProperties.WIDTH_LIMIT, "WidthLimit_Internal" }
            };

            int successCount = NavisworksComPropertyManager.SetUserDefinedProperties(
                items,
                LogisticsCategories.LOGISTICS,
                LogisticsCategories.CATEGORY_INTERNAL_NAME,
                properties,
                propertyInternalNames);

            LogManager.Info($"[属性添加] 添加操作完成，类别: {categoryId}, 成功添加 {successCount} 个模型的属性");

            // 如果是空轨类型，预计算基准路径
            if (categoryId == "空轨" && successCount > 0)
            {
                PreCalculateRailBaselinePaths(items);
            }

            return successCount;
        }

        #endregion
    }

    /// <summary>
    /// 物流属性信息类
    /// </summary>
    public class LogisticsAttributeInfo
    {
        /// <summary>
        /// 元素类型
        /// </summary>
        public string ElementType { get; set; } = "";

        /// <summary>
        /// 是否可通行
        /// </summary>
        public bool IsTraversable { get; set; } = true;

        /// <summary>
        /// 优先级
        /// </summary>
        public int Priority { get; set; } = 5;

        /// <summary>
        /// 高度限制（米）
        /// </summary>
        public double HeightLimit { get; set; } = 3.0;

        /// <summary>
        /// 速度限制
        /// </summary>
        public double SpeedLimit { get; set; } = 10.0;

        /// <summary>
        /// 宽度限制（米）
        /// </summary>
        public double WidthLimit { get; set; } = 3.0;

        /// <summary>
        /// 尝试解析元素类型为枚举
        /// </summary>
        /// <returns>解析成功的枚举值，失败返回通道</returns>
        public CategoryAttributeManager.LogisticsElementType GetElementTypeEnum()
        {
            if (Enum.TryParse<CategoryAttributeManager.LogisticsElementType>(ElementType, out var result))
            {
                return result;
            }
            return CategoryAttributeManager.LogisticsElementType.通道;
        }
    }

    /// <summary>
    /// 自动路径规划专用的障碍物识别工具类
    /// </summary>
    public static class AutoPathObstacleDetector
    {
        /// <summary>
        /// 检查模型项是否为障碍物（用于自动路径规划）
        /// </summary>
        /// <param name="item">要检查的模型项</param>
        /// <returns>如果是障碍物返回true</returns>
        public static bool IsObstacle(ModelItem item)
        {
            // 首先检查是否有物流属性
            if (CategoryAttributeManager.HasLogisticsAttributes(item))
            {
                var categoryId = CategoryAttributeManager.GetCategoryId(item);
                var isTraversable = CategoryAttributeManager.GetLogisticsPropertyValue(item, CategoryAttributeManager.LogisticsProperties.TRAVERSABLE);
                
                // 如果明确标记为不可通行，则为障碍物
                if (isTraversable == "否")
                {
                    return true;
                }
                
                // 使用类别定义检查是否为障碍物（支持自定义类别）
                if (!CategoryAttributeManager.IsCategoryTraversable(categoryId))
                {
                    return true;
                }
                                
                // 如果有物流属性且可通行，则不是障碍物
                if (isTraversable == "是")
                {
                    return false;
                }
            }
            
            // 如果没有物流属性，则使用简单的几何和名称识别
            return IsObstacleByNameAndGeometry(item);
        }
        
        /// <summary>
        /// 通过名称和几何特征识别障碍物
        /// </summary>
        /// <param name="item">模型项</param>
        /// <returns>如果判断为障碍物返回true</returns>
        private static bool IsObstacleByNameAndGeometry(ModelItem item)
        {
            string displayName = item.DisplayName?.ToLower() ?? "";
            
            // 通过名称关键词识别障碍物
            string[] obstacleKeywords = {
                "墙", "wall", "柱", "column", "梁", "beam", "板", "slab",
                "栏杆", "railing", "护栏", "guard", "围栏", "fence",
                "设备", "equipment", "机器", "machine", "管道", "pipe",
                "线缆", "cable", "风管", "duct", "障碍", "obstacle"
            };
            
            foreach (string keyword in obstacleKeywords)
            {
                if (displayName.Contains(keyword))
                {
                    return true;
                }
            }
            
            // 通过几何特征识别（检查是否有实体几何）
            try
            {
                if (item.HasGeometry)
                {
                    var bbox = item.BoundingBox();
                    if (bbox != null)
                    {
                        // 计算体积，小体积的可能是装饰性元素，不算障碍物
                        double volume = (bbox.Max.X - bbox.Min.X) * 
                                       (bbox.Max.Y - bbox.Min.Y) * 
                                       (bbox.Max.Z - bbox.Min.Z);
                        
                        // 体积小于1立方米的忽略
                        if (volume < 1.0)
                        {
                            return false;
                        }
                        
                        // 有一定体积的实体几何认为是潜在障碍物
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"检查几何特征时发生错误: {ex.Message}");
            }
            
            // 默认不认为是障碍物
            return false;
        }
        
        /// <summary>
        /// 检查模型项是否为通道（可通行区域）
        /// </summary>
        /// <param name="item">要检查的模型项</param>
        /// <returns>如果是通道返回true</returns>
        public static bool IsPassable(ModelItem item)
        {
            // 首先检查是否有物流属性
            if (CategoryAttributeManager.HasLogisticsAttributes(item))
            {
                var categoryId = CategoryAttributeManager.GetCategoryId(item);
                var isTraversable = CategoryAttributeManager.GetLogisticsPropertyValue(item, CategoryAttributeManager.LogisticsProperties.TRAVERSABLE);
                
                // 如果明确标记为可通行，则为通道
                if (isTraversable == "是")
                {
                    return true;
                }
                
                // 使用类别定义检查是否可通行（支持自定义类别）
                if (CategoryAttributeManager.IsCategoryTraversable(categoryId))
                {
                    return true;
                }
            }
            
            // 如果没有物流属性，通过名称识别通道
            return IsPassableByName(item);
        }
        
        /// <summary>
        /// 通过名称识别通道
        /// </summary>
        /// <param name="item">模型项</param>
        /// <returns>如果判断为通道返回true</returns>
        private static bool IsPassableByName(ModelItem item)
        {
            string displayName = item.DisplayName?.ToLower() ?? "";
            
            // 通过名称关键词识别通道
            string[] passableKeywords = {
                "通道", "corridor", "走廊", "hall", "过道", "aisle",
                "门", "door", "入口", "entrance", "出口", "exit",
                "电梯", "elevator", "lift", "楼梯", "stair", "step",
                "坡道", "ramp", "路径", "path", "道路", "road"
            };
            
            foreach (string keyword in passableKeywords)
            {
                if (displayName.Contains(keyword))
                {
                    return true;
                }
            }
            
            return false;
        }
        
        /// <summary>
        /// 获取模型项的通行成本（用于A*算法）
        /// </summary>
        /// <param name="item">模型项</param>
        /// <returns>通行成本，值越大表示越难通行</returns>
        public static double GetTraversalCost(ModelItem item)
        {
            // 如果是障碍物，返回无穷大成本
            if (IsObstacle(item))
            {
                return double.MaxValue;
            }
            
            // 检查物流属性中的优先级
            if (CategoryAttributeManager.HasLogisticsAttributes(item))
            {
                string priorityStr = CategoryAttributeManager.GetLogisticsPropertyValue(item, CategoryAttributeManager.LogisticsProperties.PRIORITY);
                if (int.TryParse(priorityStr, out int priority))
                {
                    // 优先级越高（数值越大）成本越低
                    return Math.Max(1.0, 11.0 - priority); // 1-10的优先级转换为1-10的成本
                }
                
                // 检查速度限制
                string speedStr = CategoryAttributeManager.GetLogisticsPropertyValue(item, CategoryAttributeManager.LogisticsProperties.SPEED_LIMIT);
                if (speedStr.Contains("m/s"))
                {
                    speedStr = speedStr.Replace("m/s", "").Trim();
                    if (double.TryParse(speedStr, out double speed) && speed > 0)
                    {
                        // 速度越高成本越低
                        return Math.Max(1.0, 50.0 / speed);
                    }
                }
                else if (double.TryParse(speedStr, out double speedValue) && speedValue > 0)
                {
                    // 速度越高成本越低
                    return Math.Max(1.0, 50.0 / speedValue);
                }
            }
            
            // 根据类型设置默认成本
            if (IsPassable(item))
            {
                return 1.0; // 明确的通道成本最低
            }
            
            // 默认成本
            return 2.0;
        }
        
        /// <summary>
        /// 批量筛选障碍物
        /// </summary>
        /// <param name="items">要筛选的模型项集合</param>
        /// <returns>障碍物集合</returns>
        public static ModelItemCollection FilterObstacles(ModelItemCollection items)
        {
            ModelItemCollection obstacles = new ModelItemCollection();
            
            foreach (ModelItem item in items)
            {
                if (IsObstacle(item))
                {
                    obstacles.Add(item);
                }
            }
            
            return obstacles;
        }
        
        /// <summary>
        /// 批量筛选可通行区域
        /// </summary>
        /// <param name="items">要筛选的模型项集合</param>
        /// <returns>可通行区域集合</returns>
        public static ModelItemCollection FilterPassableAreas(ModelItemCollection items)
        {
            ModelItemCollection passableAreas = new ModelItemCollection();
            
            foreach (ModelItem item in items)
            {
                if (IsPassable(item))
                {
                    passableAreas.Add(item);
                }
            }
            
            return passableAreas;
        }

    }
} 
