using System;
using System.Runtime.InteropServices;
using ComApi = Autodesk.Navisworks.Api.Interop.ComApi;
using ComApiBridge = Autodesk.Navisworks.Api.ComApi.ComApiBridge;

namespace NavisworksTransport
{
    /// <summary>
    /// Navisworks COM API 属性管理器 - 静态工具类
    /// </summary>
    public static class NavisworksComPropertyManager
    {
        /// <summary>
        /// COM状态对象 - 使用单例模式的ComStateManager
        /// </summary>
        private static ComApi.InwOpState10 ComState => ComStateManager.GetState();

        /// <summary>
        /// 添加或更新用户定义的属性类别
        /// </summary>
        /// <param name="items">要处理的模型项集合</param>
        /// <param name="categoryDisplayName">类别显示名称</param>
        /// <param name="categoryInternalName">类别内部名称</param>
        /// <param name="properties">属性字典（属性名称->属性值）</param>
        /// <param name="propertyInternalNames">属性内部名称字典（属性名称->内部名称）</param>
        /// <param name="overwriteExisting">是否覆盖已存在的属性</param>
        /// <returns>成功处理的项目数量</returns>
        public static int SetUserDefinedProperties(
            Autodesk.Navisworks.Api.ModelItemCollection items,
            string categoryDisplayName,
            string categoryInternalName,
            System.Collections.Generic.Dictionary<string, string> properties,
            System.Collections.Generic.Dictionary<string, string> propertyInternalNames,
            bool overwriteExisting = true)
        {
            if (items == null || items.Count == 0)
            {
                return 0;
            }

            int successCount = 0;
            ComApi.InwOpSelection comSelection = null;

            try
            {
                // 转换选择集合为COM对象
                comSelection = ComApiBridge.ToInwOpSelection(items);

                // 遍历每个路径对象
                foreach (ComApi.InwOaPath3 path in comSelection.Paths())
                {
                    ComApi.InwGUIPropertyNode2 propertyNode = null;
                    ComApi.InwOaPropertyVec propertyCategory = null;

                    try
                    {
                        // 获取属性节点
                        propertyNode = (ComApi.InwGUIPropertyNode2)ComState.GetGUIPropertyNode(path, false);

                        // 🔍 关键修复：动态查找现有属性的索引
                        int existingIndex = GetUserDefinedCategoryIndex(propertyNode, categoryDisplayName);
                        
                        // 创建新的属性类别
                        propertyCategory = (ComApi.InwOaPropertyVec)ComState.ObjectFactory(
                            ComApi.nwEObjectType.eObjectType_nwOaPropertyVec, null, null);

                        // 添加所有属性
                        foreach (var kvp in properties)
                        {
                            string internalName = propertyInternalNames.ContainsKey(kvp.Key) 
                                ? propertyInternalNames[kvp.Key] 
                                : kvp.Key.Replace(" ", "_") + "_Internal";
                            
                            AddPropertyToCategory(propertyCategory, kvp.Key, kvp.Value, internalName);
                        }

                        if (existingIndex >= 0)
                        {
                            // 🎯 存在属性时：使用正确的索引进行更新
                            // 注意：SetUserDefined的索引是从1开始的
                            int updateIndex = existingIndex + 1;
                            LogManager.Debug($"[COM属性管理] 发现现有属性类别在索引 {existingIndex}，将使用索引 {updateIndex} 进行更新");
                            
                            try
                            {
                                // 使用正确的索引覆盖现有PropertyCategory
                                propertyNode.SetUserDefined(updateIndex, categoryDisplayName, 
                                                          categoryInternalName, propertyCategory);
                                LogManager.Info($"[COM属性管理] ✅ 成功覆盖现有属性类别 (index={updateIndex})");
                            }
                            catch (Exception setEx)
                            {
                                LogManager.Error($"[COM属性管理] ❌ 覆盖属性失败，错误: {setEx.Message}");
                                throw;
                            }
                        }
                        else
                        {
                            // 🆕 不存在属性时：使用索引0创建新属性
                            LogManager.Debug("[COM属性管理] 未发现现有属性类别，将创建新的属性类别");
                            
                            try
                            {
                                // 使用参数0表示创建新的PropertyCategory
                                propertyNode.SetUserDefined(0, categoryDisplayName, 
                                                          categoryInternalName, propertyCategory);
                                LogManager.Info("[COM属性管理] ✅ 成功创建新的属性类别 (index=0)");
                            }
                            catch (Exception setEx)
                            {
                                LogManager.Error($"[COM属性管理] ❌ 创建属性失败，错误: {setEx.Message}");
                                throw;
                            }
                        }

                        successCount++;
                    }
                    catch (Exception ex)
                    {
                        LogManager.Error($"[COM属性管理] 处理单个模型项时发生错误: {ex.Message}");
                    }
                    finally
                    {
                        // 释放COM对象
                        if (propertyCategory != null)
                        {
                            Marshal.ReleaseComObject(propertyCategory);
                            propertyCategory = null;
                        }
                        if (propertyNode != null)
                        {
                            Marshal.ReleaseComObject(propertyNode);
                            propertyNode = null;
                        }
                        if (path != null)
                        {
                            Marshal.ReleaseComObject(path);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[COM属性管理] 设置属性时发生错误: {ex.Message}");
            }
            finally
            {
                // 释放选择集合COM对象
                if (comSelection != null)
                {
                    Marshal.ReleaseComObject(comSelection);
                }
            }

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

        /// <summary>
        /// 删除用户定义的属性类别
        /// </summary>
        /// <param name="items">要处理的模型项集合</param>
        /// <param name="categoryDisplayName">要删除的类别显示名称</param>
        /// <returns>成功删除的项目数量</returns>
        public static int RemoveUserDefinedCategory(
            Autodesk.Navisworks.Api.ModelItemCollection items,
            string categoryDisplayName)
        {
            if (items == null || items.Count == 0)
            {
                return 0;
            }

            int successCount = 0;
            ComApi.InwOpSelection comSelection = null;

            LogManager.Info($"[COM属性管理] 开始删除 {items.Count} 个模型的属性类别: {categoryDisplayName}");

            try
            {
                // 转换选择集合为COM对象
                comSelection = ComApiBridge.ToInwOpSelection(items);

                // 遍历每个路径对象
                foreach (ComApi.InwOaPath3 path in comSelection.Paths())
                {
                    ComApi.InwGUIPropertyNode2 propertyNode = null;

                    try
                    {
                        // 获取属性节点
                        propertyNode = (ComApi.InwGUIPropertyNode2)ComState.GetGUIPropertyNode(path, false);

                        // 查找物流属性的相对索引（只查找一次）
                        int relativeIndex = GetUserDefinedCategoryIndex(propertyNode, categoryDisplayName);
                        
                        if (relativeIndex < 0)
                        {
                            LogManager.Debug($"[COM属性管理] 该模型没有属性类别 '{categoryDisplayName}'，跳过");
                            continue;
                        }

                        // 执行删除操作
                        // 用户定义属性索引从1开始，所以需要+1
                        int userDefinedIndex = relativeIndex + 1;
                        propertyNode.RemoveUserDefined(userDefinedIndex);
                        
                        successCount++;
                        LogManager.Info($"[COM属性管理] ✅ 成功删除属性类别 (索引={userDefinedIndex})");
                    }
                    catch (Exception ex)
                    {
                        LogManager.Error($"[COM属性管理] ❌ 删除单个模型项属性时发生错误: {ex.Message}");
                    }
                    finally
                    {
                        // 释放COM对象
                        if (propertyNode != null)
                        {
                            Marshal.ReleaseComObject(propertyNode);
                            propertyNode = null;
                        }
                        if (path != null)
                        {
                            Marshal.ReleaseComObject(path);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[COM属性管理] ❌ 删除属性时发生错误: {ex.Message}");
            }
            finally
            {
                // 释放选择集合COM对象
                if (comSelection != null)
                {
                    Marshal.ReleaseComObject(comSelection);
                }
            }

            LogManager.Info($"[COM属性管理] 删除操作完成，成功删除 {successCount} 个模型的属性");
            return successCount;
        }

        /// <summary>
        /// 获取属性值（通过COM API）
        /// </summary>
        /// <param name="item">模型项</param>
        /// <param name="categoryDisplayName">类别显示名称</param>
        /// <param name="propertyName">属性名称</param>
        /// <returns>属性值，如果不存在返回空字符串</returns>
        public static string GetPropertyValue(
            Autodesk.Navisworks.Api.ModelItem item,
            string categoryDisplayName,
            string propertyName)
        {
            ComApi.InwOaPath comPath = null;
            ComApi.InwGUIPropertyNode2 propertyNode = null;

            try
            {
                // 转换ModelItem为COM路径
                comPath = ComApiBridge.ToInwOaPath(item);
                
                // 获取属性节点
                propertyNode = (ComApi.InwGUIPropertyNode2)ComState.GetGUIPropertyNode(comPath, false);

                // 遍历所有属性类别
                foreach (ComApi.InwGUIAttribute2 attribute in propertyNode.GUIAttributes())
                {
                    try
                    {
                        if (attribute.UserDefined && attribute.ClassUserName == categoryDisplayName)
                        {
                            // 获取属性集合
                            ComApi.InwOaPropertyColl propertyColl = attribute.Properties();
                            
                            try
                            {
                                // 遍历属性
                                foreach (ComApi.InwOaProperty property in propertyColl)
                                {
                                    try
                                    {
                                        if (property.UserName == propertyName)
                                        {
                                            string value = property.value.ToString();
                                            return value;
                                        }
                                    }
                                    finally
                                    {
                                        if (property != null)
                                        {
                                            Marshal.ReleaseComObject(property);
                                        }
                                    }
                                }
                            }
                            finally
                            {
                                if (propertyColl != null)
                                {
                                    Marshal.ReleaseComObject(propertyColl);
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (attribute != null)
                        {
                            Marshal.ReleaseComObject(attribute);
                        }
                    }
                }
                
                LogManager.Debug($"[COM API读取] 模型: {item.DisplayName}, 属性: {propertyName} - 未找到");
            }
            catch (Exception ex)
            {
                LogManager.Error($"通过COM API获取属性值时发生错误: {ex.Message}");
            }
            finally
            {
                // 释放COM对象
                if (propertyNode != null)
                {
                    Marshal.ReleaseComObject(propertyNode);
                }
                if (comPath != null)
                {
                    Marshal.ReleaseComObject(comPath);
                }
            }

            return string.Empty;
        }

        /// <summary>
        /// 更新单个属性值
        /// </summary>
        /// <param name="item">模型项</param>
        /// <param name="categoryDisplayName">类别显示名称</param>
        /// <param name="categoryInternalName">类别内部名称</param>
        /// <param name="propertyName">要更新的属性名称</param>
        /// <param name="propertyValue">新的属性值</param>
        /// <returns>操作是否成功</returns>
        public static bool UpdatePropertyValue(
            Autodesk.Navisworks.Api.ModelItem item,
            string categoryDisplayName,
            string categoryInternalName,
            string propertyName,
            string propertyValue)
        {
            ComApi.InwOaPath comPath = null;
            ComApi.InwGUIPropertyNode2 propertyNode = null;

            try
            {
                LogManager.Debug($"[COM属性管理] 开始更新模型 {item.DisplayName} 的属性 {propertyName} = {propertyValue}");
                
                // 转换ModelItem为COM路径
                comPath = ComApiBridge.ToInwOaPath(item);
                
                // 获取属性节点
                propertyNode = (ComApi.InwGUIPropertyNode2)ComState.GetGUIPropertyNode(comPath, false);

                // 🔍 关键修复：使用正确的相对索引查找
                int existingIndex = GetUserDefinedCategoryIndex(propertyNode, categoryDisplayName);
                
                if (existingIndex < 0)
                {
                    LogManager.Warning($"[COM属性管理] 模型没有属性类别 '{categoryDisplayName}'，无法更新属性");
                    return false;
                }

                // 获取现有的属性类别
                ComApi.InwGUIAttribute2 existingAttribute = null;
                int userDefinedIndex = 0;
                foreach (ComApi.InwGUIAttribute2 attribute in propertyNode.GUIAttributes())
                {
                    try
                    {
                        if (attribute.UserDefined)
                        {
                            if (userDefinedIndex == existingIndex)
                            {
                                existingAttribute = attribute;
                                break;
                            }
                            userDefinedIndex++;
                        }
                    }
                    finally
                    {
                        if (attribute != existingAttribute && attribute != null)
                        {
                            Marshal.ReleaseComObject(attribute);
                        }
                    }
                }

                if (existingAttribute == null)
                {
                    LogManager.Warning($"[COM属性管理] 无法获取现有的属性类别 '{categoryDisplayName}'");
                    return false;
                }

                ComApi.InwOaPropertyVec newPropertyCategory = null;

                try
                {
                    // 创建新的属性类别，保留其他属性，只修改指定属性
                    newPropertyCategory = (ComApi.InwOaPropertyVec)ComState.ObjectFactory(
                        ComApi.nwEObjectType.eObjectType_nwOaPropertyVec, null, null);

                    // 复制现有属性，修改指定属性
                    foreach (ComApi.InwOaProperty existingProp in existingAttribute.Properties())
                    {
                        try
                        {
                            if (existingProp.UserName == propertyName)
                            {
                                // 更新指定属性
                                AddPropertyToCategory(newPropertyCategory, propertyName, 
                                          propertyValue, existingProp.name);
                            }
                            else
                            {
                                // 保留其他属性
                                AddPropertyToCategory(newPropertyCategory, existingProp.UserName, 
                                          existingProp.value.ToString(), existingProp.name);
                            }
                        }
                        finally
                        {
                            if (existingProp != null)
                            {
                                Marshal.ReleaseComObject(existingProp);
                            }
                        }
                    }

                    // 🎯 使用正确的索引进行覆盖更新
                    int updateIndex = existingIndex + 1;
                    propertyNode.SetUserDefined(updateIndex, categoryDisplayName, 
                                              categoryInternalName, newPropertyCategory);
                    
                    LogManager.Info($"[COM属性管理] ✅ 成功更新属性 {propertyName} = {propertyValue} (index={updateIndex})");
                    return true;
                }
                finally
                {
                    if (newPropertyCategory != null)
                    {
                        Marshal.ReleaseComObject(newPropertyCategory);
                    }
                    if (existingAttribute != null)
                    {
                        Marshal.ReleaseComObject(existingAttribute);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[COM属性管理] ❌ 更新属性失败，错误: {ex.Message}");
                return false;
            }
            finally
            {
                // 释放COM对象
                if (propertyNode != null)
                {
                    Marshal.ReleaseComObject(propertyNode);
                }
                if (comPath != null)
                {
                    Marshal.ReleaseComObject(comPath);
                }
            }
        }

        #region 私有辅助方法

        /// <summary>
        /// 创建并添加单个属性到属性类别
        /// </summary>
        private static void AddPropertyToCategory(ComApi.InwOaPropertyVec propertyCategory, 
            string displayName, string value, string internalName)
        {
            ComApi.InwOaProperty property = null;

            try
            {
                // 创建新属性
                property = (ComApi.InwOaProperty)ComState.ObjectFactory(
                    ComApi.nwEObjectType.eObjectType_nwOaProperty, null, null);

                // 设置属性信息
                property.name = internalName;      // 内部名称
                property.UserName = displayName;   // 显示名称
                property.value = value;            // 属性值

                // 添加到属性类别
                propertyCategory.Properties().Add(property);
            }
            finally
            {
                if (property != null)
                {
                    Marshal.ReleaseComObject(property);
                }
            }
        }

        /// <summary>
        /// 查找现有用户定义属性类别的相对索引（在用户定义属性中的位置）
        /// </summary>
        /// <summary>
        /// 查找现有用户定义属性类别的相对索引（在用户定义属性中的位置）
        /// </summary>
        private static int GetUserDefinedCategoryIndex(ComApi.InwGUIPropertyNode2 propertyNode, string categoryDisplayName)
        {
            try
            {
                int userDefinedIndex = 0; // 用户定义属性的索引计数器
                LogManager.Debug($"[相对索引查找] 开始查找属性分类 '{categoryDisplayName}' 的相对索引");

                foreach (ComApi.InwGUIAttribute2 attribute in propertyNode.GUIAttributes())
                {
                    try
                    {
                        LogManager.Debug($"[相对索引查找] 检查属性: UserDefined={attribute.UserDefined}, ClassUserName='{attribute.ClassUserName ?? "无名称"}'");
                        
                        if (attribute.UserDefined)
                        {
                            // ⚠️ 关键修复：只匹配ClassUserName，不匹配ClassName
                            // ClassName是系统生成的（如"LcOaPropOverrideCat"），我们无法控制
                            if (attribute.ClassUserName == categoryDisplayName)
                            {
                                LogManager.Debug($"[相对索引查找] ✅ 找到属性分类，相对索引为: {userDefinedIndex}, ClassUserName='{attribute.ClassUserName}'");
                                return userDefinedIndex; // 返回在用户定义属性中的索引位置
                            }
                            // 只有用户定义的属性才计入索引
                            userDefinedIndex++;
                            LogManager.Debug($"[相对索引查找] 发现其他用户定义属性 '{attribute.ClassUserName}'，当前索引计数: {userDefinedIndex}");
                        }
                    }
                    finally
                    {
                        if (attribute != null)
                        {
                            Marshal.ReleaseComObject(attribute);
                        }
                    }
                }
                
                LogManager.Debug($"[相对索引查找] ❌ 未找到属性分类 '{categoryDisplayName}'，总共检查了 {userDefinedIndex} 个用户定义属性");
                return -1; // 未找到返回-1
            }
            catch (Exception ex)
            {
                LogManager.Error($"[相对索引查找] 查找属性相对索引时发生错误: {ex.Message}");
                return -1;
            }
        }

        #endregion

        /// <summary>
        /// 设置楼层属性
        /// </summary>
        /// <param name="item">目标模型项</param>
        /// <param name="floorLevel">楼层标识</param>
        /// <param name="zone">区域标识（可选）</param>
        /// <param name="subSystem">子系统标识（可选）</param>
        /// <param name="categoryDisplayName">类别显示名称</param>
        /// <param name="categoryInternalName">类别内部名称</param>
        /// <param name="floorPropertyName">楼层属性名称</param>
        /// <param name="zonePropertyName">区域属性名称</param>
        /// <param name="subSystemPropertyName">子系统属性名称</param>
        /// <returns>操作是否成功</returns>
        public static bool SetFloorProperties(
            Autodesk.Navisworks.Api.ModelItem item,
            string floorLevel,
            string zone,
            string subSystem,
            string categoryDisplayName,
            string categoryInternalName,
            string floorPropertyName,
            string zonePropertyName,
            string subSystemPropertyName)
        {
            ComApi.InwOaPath comPath = null;
            ComApi.InwGUIPropertyNode2 propertyNode = null;

            try
            {
                LogManager.Debug($"[COM楼层管理] 开始设置模型 {item.DisplayName} 的楼层属性");
                
                // 转换ModelItem为COM路径
                comPath = ComApiBridge.ToInwOaPath(item);
                
                // 获取属性节点
                propertyNode = (ComApi.InwGUIPropertyNode2)ComState.GetGUIPropertyNode(comPath, false);

                // 🔍 使用正确的相对索引查找
                int existingIndex = GetUserDefinedCategoryIndex(propertyNode, categoryDisplayName);
                
                // 创建新的属性类别
                ComApi.InwOaPropertyVec propertyCategory = null;

                try
                {
                    propertyCategory = (ComApi.InwOaPropertyVec)ComState.ObjectFactory(
                        ComApi.nwEObjectType.eObjectType_nwOaPropertyVec, null, null);

                    // 添加楼层属性
                    if (!string.IsNullOrEmpty(floorLevel))
                    {
                        AddPropertyToCategory(propertyCategory, "楼层", floorLevel, floorPropertyName);
                    }

                    // 添加区域属性（如果有值）
                    if (!string.IsNullOrEmpty(zone))
                    {
                        AddPropertyToCategory(propertyCategory, "区域", zone, zonePropertyName);
                    }

                    // 添加子系统属性（如果有值）
                    if (!string.IsNullOrEmpty(subSystem))
                    {
                        AddPropertyToCategory(propertyCategory, "子系统", subSystem, subSystemPropertyName);
                    }

                    if (existingIndex >= 0)
                    {
                        // 🎯 存在属性时：使用正确的索引进行更新
                        int updateIndex = existingIndex + 1;
                        LogManager.Debug($"[COM楼层管理] 发现现有楼层属性在索引 {existingIndex}，将使用索引 {updateIndex} 进行更新");
                        
                        try
                        {
                            propertyNode.SetUserDefined(updateIndex, categoryDisplayName, 
                                                      categoryInternalName, propertyCategory);
                            LogManager.Info($"[COM楼层管理] ✅ 成功覆盖现有楼层属性类别 (index={updateIndex})");
                        }
                        catch (Exception setEx)
                        {
                            LogManager.Error($"[COM楼层管理] ❌ 覆盖楼层属性失败，错误: {setEx.Message}");
                            throw;
                        }
                    }
                    else
                    {
                        // 🆕 不存在属性时：使用索引0创建新属性
                        LogManager.Debug("[COM楼层管理] 未发现现有楼层属性，将创建新的属性类别");
                        
                        try
                        {
                            propertyNode.SetUserDefined(0, categoryDisplayName, 
                                                      categoryInternalName, propertyCategory);
                            LogManager.Info("[COM楼层管理] ✅ 成功创建新的楼层属性类别 (index=0)");
                        }
                        catch (Exception setEx)
                        {
                            LogManager.Error($"[COM楼层管理] ❌ 创建楼层属性失败，错误: {setEx.Message}");
                            throw;
                        }
                    }

                    LogManager.Info($"[COM楼层管理] ✅ 成功设置楼层属性");
                    return true;
                }
                finally
                {
                    if (propertyCategory != null)
                    {
                        Marshal.ReleaseComObject(propertyCategory);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[COM楼层管理] ❌ 设置楼层属性失败，错误: {ex.Message}");
                return false;
            }
            finally
            {
                // 释放COM对象
                if (propertyNode != null)
                {
                    Marshal.ReleaseComObject(propertyNode);
                }
                if (comPath != null)
                {
                    Marshal.ReleaseComObject(comPath);
                }
            }
        }

        /// <summary>
        /// 获取楼层属性值
        /// </summary>
        /// <param name="item">模型项</param>
        /// <param name="categoryDisplayName">类别显示名称</param>
        /// <param name="propertyInternalName">属性内部名称</param>
        /// <returns>属性值，如果不存在返回null</returns>
        /// <summary>
        /// 获取楼层属性值
        /// </summary>
        /// <param name="item">模型项</param>
        /// <param name="categoryDisplayName">类别显示名称</param>
        /// <param name="propertyInternalName">属性内部名称</param>
        /// <returns>属性值，如果不存在返回null</returns>
        public static string GetFloorPropertyValue(
            Autodesk.Navisworks.Api.ModelItem item,
            string categoryDisplayName,
            string propertyInternalName)
        {
            ComApi.InwOaPath comPath = null;
            ComApi.InwGUIPropertyNode2 propertyNode = null;

            try
            {
                // 转换ModelItem为COM路径
                comPath = ComApiBridge.ToInwOaPath(item);
                
                // 获取属性节点
                propertyNode = (ComApi.InwGUIPropertyNode2)ComState.GetGUIPropertyNode(comPath, false);

                // 遍历所有属性类别
                foreach (ComApi.InwGUIAttribute2 attribute in propertyNode.GUIAttributes())
                {
                    try
                    {
                        if (attribute.UserDefined && attribute.ClassUserName == categoryDisplayName)
                        {
                            // 获取属性集合
                            ComApi.InwOaPropertyColl propertyColl = attribute.Properties();
                            
                            try
                            {
                                // 遍历属性
                                foreach (ComApi.InwOaProperty property in propertyColl)
                                {
                                    try
                                    {
                                        if (property.name == propertyInternalName)
                                        {
                                            string value = property.value?.ToString();
                                            LogManager.Debug($"[COM楼层读取] 模型: {item.DisplayName}, 属性: {propertyInternalName}, 值: {value}");
                                            return value;
                                        }
                                    }
                                    finally
                                    {
                                        if (property != null)
                                        {
                                            Marshal.ReleaseComObject(property);
                                        }
                                    }
                                }
                            }
                            finally
                            {
                                if (propertyColl != null)
                                {
                                    Marshal.ReleaseComObject(propertyColl);
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (attribute != null)
                        {
                            Marshal.ReleaseComObject(attribute);
                        }
                    }
                }
                
                return null;
            }
            catch (Exception ex)
            {
                LogManager.Error($"通过COM API获取楼层属性值时发生错误: {ex.Message}");
                return null;
            }
            finally
            {
                // 释放COM对象
                if (propertyNode != null)
                {
                    Marshal.ReleaseComObject(propertyNode);
                }
                if (comPath != null)
                {
                    Marshal.ReleaseComObject(comPath);
                }
            }
        }

    }
}