namespace NavisworksTransport.Core
{
    /// <summary>
    /// 路径规划服务 - 为UI层提供统一的业务逻辑访问接口
    /// 这是一个Facade模式的实现，封装了PathPlanningManager和Command Pattern的复杂性
    /// </summary>
    public class PathPlanningService : IDisposable
    {
        #region 私有字段

        private readonly PathPlanningManager _pathManager;
        private readonly CommandExecutor _commandExecutor;
        private readonly UIStateManager _uiStateManager;
        private readonly string _serviceId;
        private bool _isDisposed = false;

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化路径规划服务
        /// </summary>
        /// <param name="pathManager">路径规划管理器</param>
        /// <param name="commandExecutor">命令执行器，为null时使用默认实例</param>
        /// <param name="uiStateManager">UI状态管理器，为null时使用默认实例</param>
        public PathPlanningService(PathPlanningManager pathManager, CommandExecutor commandExecutor = null, UIStateManager uiStateManager = null)
        {
            _pathManager = pathManager ?? throw new ArgumentNullException(nameof(pathManager));
            _commandExecutor = commandExecutor ?? CommandExecutor.Instance;
            _uiStateManager = uiStateManager ?? UIStateManager.Instance;
            _serviceId = Guid.NewGuid().ToString("N").Substring(0, 8);

            LogManager.Info($"PathPlanningService初始化完成，ServiceId: {_serviceId}");
        }

        #endregion

        #region 公共属性

        /// <summary>
        /// 服务ID
        /// </summary>
        public string ServiceId => _serviceId;

        /// <summary>
        /// 获取路径管理器（只读访问）
        /// </summary>
        public IPathPlanningManager PathManager => _pathManager;

        /// <summary>
        /// 当前编辑状态
        /// </summary>
        public PathEditState CurrentEditState => _pathManager.PathEditState;

        /// <summary>
        /// 当前路径
        /// </summary>
        public PathRoute CurrentRoute => _pathManager.CurrentRoute;

        /// <summary>
        /// 所有路径（只读）
        /// </summary>
        public IReadOnlyList<PathRoute> AllRoutes => _pathManager.Routes;

        /// <summary>
        /// 选择的通道（只读）
        /// </summary>
        public IReadOnlyList<ModelItem> SelectedChannels => _pathManager.SelectedChannels;

        /// <summary>
        /// 是否在编辑状态
        /// </summary>
        public bool IsInEditableState => _pathManager.IsInEditableState;

        /// <summary>
        /// 路径统计信息
        /// </summary>
        public string Statistics => _pathManager.GetStatistics();

        #endregion

        #region 事件转发

        /// <summary>
        /// 路径规划状态变更事件
        /// </summary>
        public event EventHandler<PathPlanningStatusChangedEventArgs> StatusChanged
        {
            add { _pathManager.StatusChanged += value; }
            remove { _pathManager.StatusChanged -= value; }
        }

        /// <summary>
        /// 路径规划错误事件
        /// </summary>
        public event EventHandler<PathPlanningErrorOccurredEventArgs> ErrorOccurred
        {
            add { _pathManager.ErrorOccurred += value; }
            remove { _pathManager.ErrorOccurred -= value; }
        }

        /// <summary>
        /// 编辑状态变更事件
        /// </summary>
        public event EventHandler<PathEditStateChangedEventArgs> EditStateChanged
        {
            add { _pathManager.EditStateChanged += value; }
            remove { _pathManager.EditStateChanged -= value; }
        }

        /// <summary>
        /// 通道选择变更事件
        /// </summary>
        public event EventHandler<ChannelSelectionChangedEventArgs> ChannelSelectionChanged
        {
            add { _pathManager.ChannelSelectionChanged += value; }
            remove { _pathManager.ChannelSelectionChanged -= value; }
        }

        /// <summary>
        /// 路径点操作事件
        /// </summary>
        public event EventHandler<PathPointOperationEventArgs> PathPointOperation
        {
            add { _pathManager.PathPointOperation += value; }
            remove { _pathManager.PathPointOperation -= value; }
        }

        /// <summary>
        /// 路径生成事件
        /// </summary>
        public event EventHandler<RouteGeneratedEventArgs> RouteGenerated
        {
            add { _pathManager.RouteGenerated += value; }
            remove { _pathManager.RouteGenerated -= value; }
        }

        /// <summary>
        /// 当前路径变更事件
        /// </summary>
        public event EventHandler<CurrentRouteChangedEventArgs> CurrentRouteChanged
        {
            add { _pathManager.CurrentRouteChanged += value; }
            remove { _pathManager.CurrentRouteChanged -= value; }
        }

        /// <summary>
        /// 路径点列表更新事件
        /// </summary>
        public event EventHandler<PathPointsListUpdatedEventArgs> PathPointsListUpdated
        {
            add { _pathManager.PathPointsListUpdated += value; }
            remove { _pathManager.PathPointsListUpdated -= value; }
        }

        #endregion

        #region 主要业务方法

        /// <summary>
        /// 选择通道模型
        /// </summary>
        /// <param name="useCurrentSelection">是否使用当前选择的模型</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>选择的通道数量</returns>
        public async Task<PathPlanningResult<int>> SelectChannelsAsync(bool useCurrentSelection = true, CancellationToken cancellationToken = default)
        {
            try
            {
                var command = new SelectChannelsCommand(_pathManager, useCurrentSelection);
                var result = await _commandExecutor.ExecuteAsync(command, cancellationToken);
                
                if (result.IsSuccess)
                {
                    var channelCount = _pathManager.SelectedChannels.Count;
                    return PathPlanningResult<int>.Success(channelCount, result.Message);
                }
                
                return PathPlanningResult<int>.Failure(result.ErrorMessage, result.Exception);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[PathPlanningService] 选择通道异常", ex);
                return PathPlanningResult<int>.Failure($"选择通道时发生异常: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 开始创建新路径
        /// </summary>
        /// <param name="routeName">路径名称</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>创建的新路径</returns>
        public async Task<PathPlanningResult<PathRoute>> StartCreatingRouteAsync(string routeName = null, CancellationToken cancellationToken = default)
        {
            try
            {
                var command = new StartCreatingRouteCommand(_pathManager, routeName);
                var result = await _commandExecutor.ExecuteAsync(command, cancellationToken);
                
                if (result.IsSuccess && result is PathPlanningResult<PathRoute> typedResult)
                {
                    return typedResult;
                }
                
                // 如果是普通结果，尝试获取当前路径作为返回值
                if (result.IsSuccess)
                {
                    return PathPlanningResult<PathRoute>.Success(_pathManager.CurrentRoute, result.Message);
                }
                
                return PathPlanningResult<PathRoute>.Failure(result.ErrorMessage, result.Exception);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[PathPlanningService] 开始创建新路径异常", ex);
                return PathPlanningResult<PathRoute>.Failure($"开始创建新路径时发生异常: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 完成当前编辑
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<PathPlanningResult> FinishEditingAsync(CancellationToken cancellationToken = default)
        {
            try
            {
                var command = new FinishEditingCommand(_pathManager);
                return await _commandExecutor.ExecuteAsync(command, cancellationToken);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[PathPlanningService] 完成编辑异常", ex);
                return PathPlanningResult.Failure($"完成编辑时发生异常: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 取消当前编辑
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<PathPlanningResult> CancelEditingAsync(CancellationToken cancellationToken = default)
        {
            try
            {
                var command = new CancelEditingCommand(_pathManager);
                return await _commandExecutor.ExecuteAsync(command, cancellationToken);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[PathPlanningService] 取消编辑异常", ex);
                return PathPlanningResult.Failure($"取消编辑时发生异常: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 在3D视图中添加路径点
        /// </summary>
        /// <param name="worldPoint">3D坐标</param>
        /// <param name="pointType">路径点类型</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>添加的路径点</returns>
        public async Task<PathPlanningResult<PathPoint>> AddPathPointAsync(Point3D worldPoint, PathPointType? pointType = null, CancellationToken cancellationToken = default)
        {
            try
            {
                var command = new AddPathPointCommand(_pathManager, worldPoint, pointType);
                var result = await _commandExecutor.ExecuteAsync(command, cancellationToken);
                
                if (result.IsSuccess && result is PathPlanningResult<PathPoint> typedResult)
                {
                    return typedResult;
                }
                
                return PathPlanningResult<PathPoint>.Failure(result.ErrorMessage, result.Exception);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[PathPlanningService] 添加路径点异常", ex);
                return PathPlanningResult<PathPoint>.Failure($"添加路径点时发生异常: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 生成路径
        /// </summary>
        /// <param name="route">要生成的路径，为null时使用当前路径</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>生成的路径</returns>
        public async Task<PathPlanningResult<PathRoute>> GeneratePathAsync(PathRoute route = null, CancellationToken cancellationToken = default)
        {
            try
            {
                var command = new GeneratePathCommand(_pathManager, route);
                var result = await _commandExecutor.ExecuteAsync(command, cancellationToken);
                
                if (result.IsSuccess && result is PathPlanningResult<PathRoute> typedResult)
                {
                    return typedResult;
                }
                
                // 如果是普通结果，使用当前路径或指定路径作为返回值
                if (result.IsSuccess)
                {
                    var targetRoute = route ?? _pathManager.CurrentRoute;
                    return PathPlanningResult<PathRoute>.Success(targetRoute, result.Message);
                }
                
                return PathPlanningResult<PathRoute>.Failure(result.ErrorMessage, result.Exception);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[PathPlanningService] 生成路径异常", ex);
                return PathPlanningResult<PathRoute>.Failure($"生成路径时发生异常: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 删除指定路径
        /// </summary>
        /// <param name="route">要删除的路径</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<PathPlanningResult> DeleteRouteAsync(PathRoute route, CancellationToken cancellationToken = default)
        {
            try
            {
                var command = new DeleteRouteCommand(_pathManager, route);
                return await _commandExecutor.ExecuteAsync(command, cancellationToken);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[PathPlanningService] 删除路径异常", ex);
                return PathPlanningResult.Failure($"删除路径时发生异常: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 切换到编辑状态
        /// </summary>
        /// <param name="route">要编辑的路径</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<PathPlanningResult> SwitchToEditingStateAsync(PathRoute route, CancellationToken cancellationToken = default)
        {
            try
            {
                var command = new SwitchToEditingStateCommand(_pathManager, route);
                return await _commandExecutor.ExecuteAsync(command, cancellationToken);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[PathPlanningService] 切换到编辑状态异常", ex);
                return PathPlanningResult.Failure($"切换到编辑状态时发生异常: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 切换到查看状态
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<PathPlanningResult> SwitchToViewingStateAsync(CancellationToken cancellationToken = default)
        {
            try
            {
                var command = new SwitchToViewingStateCommand(_pathManager);
                return await _commandExecutor.ExecuteAsync(command, cancellationToken);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[PathPlanningService] 切换到查看状态异常", ex);
                return PathPlanningResult.Failure($"切换到查看状态时发生异常: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 设置当前路径
        /// </summary>
        /// <param name="route">要设置的路径</param>
        public void SetCurrentRoute(PathRoute route)
        {
            try
            {
                _pathManager.SetCurrentRoute(route);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[PathPlanningService] 设置当前路径异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 添加路径到管理器
        /// </summary>
        /// <param name="route">要添加的路径</param>
        /// <returns>是否成功添加</returns>
        public bool AddRoute(PathRoute route)
        {
            try
            {
                return _pathManager.AddRoute(route);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[PathPlanningService] 添加路径异常", ex);
                return false;
            }
        }

        #endregion

        #region 同步方法（兼容性）

        /// <summary>
        /// 选择通道模型（同步版本）
        /// </summary>
        /// <param name="useCurrentSelection">是否使用当前选择的模型</param>
        /// <returns>选择的通道数量</returns>
        public int SelectChannels(bool useCurrentSelection = true)
        {
            try
            {
                return _pathManager.SelectChannels(useCurrentSelection);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[PathPlanningService] 同步选择通道异常", ex);
                return 0;
            }
        }

        /// <summary>
        /// 在3D视图中添加路径点（同步版本）
        /// </summary>
        /// <param name="worldPoint">3D坐标</param>
        /// <param name="pointType">路径点类型</param>
        /// <returns>添加的路径点</returns>
        public PathPoint AddPathPoint(Point3D worldPoint, PathPointType? pointType = null)
        {
            try
            {
                return _pathManager.AddPathPointIn3D(worldPoint, pointType);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[PathPlanningService] 同步添加路径点异常", ex);
                return null;
            }
        }

        #endregion

        #region 辅助方法

        /// <summary>
        /// 验证路径有效性
        /// </summary>
        /// <param name="route">要验证的路径</param>
        /// <returns>验证结果</returns>
        public PathPlanningResult ValidateRoute(PathRoute route)
        {
            if (route == null)
            {
                return PathPlanningResult.ValidationFailure("路径不能为空");
            }

            if (route.Points.Count < 2)
            {
                return PathPlanningResult.ValidationFailure("路径至少需要包含2个点");
            }

            var hasStartPoint = route.Points.Any(p => p.Type == PathPointType.StartPoint);
            var hasEndPoint = route.Points.Any(p => p.Type == PathPointType.EndPoint);

            if (!hasStartPoint)
            {
                return PathPlanningResult.ValidationFailure("路径必须包含至少一个起点");
            }

            if (!hasEndPoint)
            {
                return PathPlanningResult.ValidationFailure("路径必须包含至少一个终点");
            }

            return PathPlanningResult.Success("路径验证通过");
        }

        /// <summary>
        /// 获取路径摘要信息
        /// </summary>
        /// <param name="route">路径</param>
        /// <returns>摘要信息</returns>
        public string GetRouteSummary(PathRoute route)
        {
            if (route == null)
            {
                return "路径为空";
            }

            return $"路径: {route.Name}, 点数: {route.Points.Count}, 长度: {route.TotalLength:F2}米, 预估时间: {route.EstimatedTime:F1}秒";
        }

        #endregion

        #region IDisposable实现

        public void Dispose()
        {
            if (_isDisposed)
            {
                return;
            }

            try
            {
                LogManager.Info($"PathPlanningService正在释放，ServiceId: {_serviceId}");
                
                // 清理事件订阅
                // 注意：事件订阅会在remove时自动清理
                
                _isDisposed = true;
                LogManager.Info($"PathPlanningService已释放，ServiceId: {_serviceId}");
            }
            catch (Exception ex)
            {
                LogManager.Error($"PathPlanningService释放时发生错误", ex);
            }
        }

        #endregion
    }
}