using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Autodesk.Navisworks.Api;

namespace NavisworksTransport.Commands
{
    /// <summary>
    /// 选择通道命令
    /// 支持通过当前选择或类别筛选来选择可通行的物流通道
    /// </summary>
    public class SelectChannelsCommand : CommandBase
    {
        private readonly bool _useCurrentSelection;
        private readonly PathPlanningManager _pathManager;

        public SelectChannelsCommand(PathPlanningManager pathManager, bool useCurrentSelection = true)
            : base("SelectChannels", "选择通道", "选择可通行的物流通道模型")
        {
            _pathManager = pathManager ?? throw new ArgumentNullException(nameof(pathManager));
            _useCurrentSelection = useCurrentSelection;
        }

        protected override PathPlanningResult ValidateParameters()
        {
            if (_pathManager == null)
                return PathPlanningResult.ValidationFailure("路径管理器未初始化");

            var document = Application.ActiveDocument;
            if (document?.Models == null)
                return PathPlanningResult.ValidationFailure("当前没有加载的Navisworks模型");

            if (_useCurrentSelection)
            {
                var selection = document.CurrentSelection.SelectedItems;
                if (selection.Count == 0)
                    return PathPlanningResult.ValidationFailure("请先选择通道模型，或使用类别筛选模式");
            }

            return PathPlanningResult.Success("参数验证通过");
        }

        protected override async Task<PathPlanningResult> ExecuteInternalAsync(CancellationToken cancellationToken)
        {
            UpdateProgress(10, "开始选择通道...");
            
            try
            {
                var selectedCount = _pathManager.SelectChannels(_useCurrentSelection);
                
                UpdateProgress(100, $"通道选择完成，共选择 {selectedCount} 个通道");
                
                if (selectedCount == 0)
                {
                    return PathPlanningResult.Failure("未找到任何符合条件的通道模型");
                }

                return PathPlanningResult.Success($"成功选择了 {selectedCount} 个通道模型");
            }
            catch (Exception ex)
            {
                LogError("选择通道时发生错误", ex);
                return PathPlanningResult.Failure($"选择通道失败: {ex.Message}", ex);
            }
            finally
            {
                await Task.CompletedTask; // 确保方法是真正的异步方法
            }
        }
    }

    /// <summary>
    /// 开始新建路径命令
    /// </summary>
    public class StartCreatingRouteCommand : CommandBase
    {
        private readonly string _routeName;
        private readonly PathPlanningManager _pathManager;

        public StartCreatingRouteCommand(PathPlanningManager pathManager, string routeName = null)
            : base("StartCreatingRoute", "开始新建路径", "开始创建新的运输路径")
        {
            _pathManager = pathManager ?? throw new ArgumentNullException(nameof(pathManager));
            _routeName = routeName;
        }

        protected override PathPlanningResult ValidateParameters()
        {
            if (_pathManager == null)
                return PathPlanningResult.ValidationFailure("路径管理器未初始化");

            if (_pathManager.IsInEditableState)
                return PathPlanningResult.ValidationFailure("当前已在编辑状态，请先完成或取消当前编辑");

            return PathPlanningResult.Success("参数验证通过");
        }

        protected override async Task<PathPlanningResult> ExecuteInternalAsync(CancellationToken cancellationToken)
        {
            UpdateProgress(20, "准备创建新路径...");
            
            try
            {
                var newRoute = _pathManager.StartCreatingNewRoute(_routeName);
                
                if (newRoute == null)
                {
                    return PathPlanningResult.Failure("创建新路径失败，可能是缺少可通行的物流模型");
                }

                UpdateProgress(100, $"新路径创建成功: {newRoute.Name}");
                
                return PathPlanningResult<PathRoute>.Success(newRoute, $"新路径 '{newRoute.Name}' 创建成功，请在3D视图中点击设置路径点");
            }
            catch (Exception ex)
            {
                LogError("创建新路径时发生错误", ex);
                return PathPlanningResult.Failure($"创建新路径失败: {ex.Message}", ex);
            }
            finally
            {
                await Task.CompletedTask; // 确保方法是真正的异步方法
            }
        }
    }

    /// <summary>
    /// 完成编辑命令
    /// </summary>
    public class FinishEditingCommand : CommandBase
    {
        private readonly PathPlanningManager _pathManager;

        public FinishEditingCommand(PathPlanningManager pathManager)
            : base("FinishEditing", "完成编辑", "完成当前路径编辑并保存")
        {
            _pathManager = pathManager ?? throw new ArgumentNullException(nameof(pathManager));
        }

        protected override PathPlanningResult ValidateParameters()
        {
            if (_pathManager == null)
                return PathPlanningResult.ValidationFailure("路径管理器未初始化");

            if (!_pathManager.IsInEditableState)
                return PathPlanningResult.ValidationFailure("当前不在编辑状态");

            if (_pathManager.CurrentRoute == null || _pathManager.CurrentRoute.Points.Count < 2)
                return PathPlanningResult.ValidationFailure("路径至少需要包含2个点（起点和终点）");

            return PathPlanningResult.Success("参数验证通过");
        }

        protected override async Task<PathPlanningResult> ExecuteInternalAsync(CancellationToken cancellationToken)
        {
            UpdateProgress(30, "正在完成编辑...");
            
            try
            {
                bool success = _pathManager.FinishEditing();
                
                if (!success)
                {
                    return PathPlanningResult.Failure("完成编辑失败");
                }

                UpdateProgress(100, "编辑完成");
                
                return PathPlanningResult.Success("路径编辑已成功完成");
            }
            catch (Exception ex)
            {
                LogError("完成编辑时发生错误", ex);
                return PathPlanningResult.Failure($"完成编辑失败: {ex.Message}", ex);
            }
            finally
            {
                await Task.CompletedTask; // 确保方法是真正的异步方法
            }
#pragma warning restore CS1998
        }
    }

    /// <summary>
    /// 取消编辑命令
    /// </summary>
    public class CancelEditingCommand : CommandBase
    {
        private readonly PathPlanningManager _pathManager;

        public CancelEditingCommand(PathPlanningManager pathManager)
            : base("CancelEditing", "取消编辑", "取消当前路径编辑")
        {
            _pathManager = pathManager ?? throw new ArgumentNullException(nameof(pathManager));
        }

        protected override PathPlanningResult ValidateParameters()
        {
            if (_pathManager == null)
                return PathPlanningResult.ValidationFailure("路径管理器未初始化");

            if (!_pathManager.IsInEditableState)
                return PathPlanningResult.ValidationFailure("当前不在编辑状态");

            return PathPlanningResult.Success("参数验证通过");
        }

        protected override async Task<PathPlanningResult> ExecuteInternalAsync(CancellationToken cancellationToken)
        {
            UpdateProgress(50, "正在取消编辑...");
            
            try
            {
                bool success = _pathManager.CancelEditing();
                
                if (!success)
                {
                    return PathPlanningResult.Failure("取消编辑失败");
                }

                UpdateProgress(100, "编辑已取消");
                
                return PathPlanningResult.Success("路径编辑已取消");
            }
            catch (Exception ex)
            {
                LogError("取消编辑时发生错误", ex);
                return PathPlanningResult.Failure($"取消编辑失败: {ex.Message}", ex);
            }
            finally
            {
                await Task.CompletedTask; // 确保方法是真正的异步方法
            }
        }
    }

    /// <summary>
    /// 添加路径点命令
    /// </summary>
    public class AddPathPointCommand : CommandBase
    {
        private readonly Point3D _worldPoint;
        private readonly PathPointType? _pointType;
        private readonly PathPlanningManager _pathManager;

        public AddPathPointCommand(PathPlanningManager pathManager, Point3D worldPoint, PathPointType? pointType = null)
            : base("AddPathPoint", "添加路径点", "在3D视图中添加路径点")
        {
            _pathManager = pathManager ?? throw new ArgumentNullException(nameof(pathManager));
            _worldPoint = worldPoint;
            _pointType = pointType;
        }

        protected override PathPlanningResult ValidateParameters()
        {
            if (_pathManager == null)
                return PathPlanningResult.ValidationFailure("路径管理器未初始化");

            if (!_pathManager.IsInEditableState)
                return PathPlanningResult.ValidationFailure("当前不在编辑状态，无法添加路径点");

            if (_worldPoint == null)
                return PathPlanningResult.ValidationFailure("3D点坐标无效");

            return PathPlanningResult.Success("参数验证通过");
        }

        protected override async Task<PathPlanningResult> ExecuteInternalAsync(CancellationToken cancellationToken)
        {
            UpdateProgress(30, "正在添加路径点...");
            
            try
            {
                var pathPoint = _pathManager.AddPathPointIn3D(_worldPoint, _pointType);
                
                if (pathPoint == null)
                {
                    return PathPlanningResult.Failure("添加路径点失败");
                }

                UpdateProgress(100, $"路径点已添加: {pathPoint.Name}");
                
                return PathPlanningResult<PathPoint>.Success(pathPoint, $"路径点 '{pathPoint.Name}' 添加成功");
            }
            catch (Exception ex)
            {
                LogError("添加路径点时发生错误", ex);
                return PathPlanningResult.Failure($"添加路径点失败: {ex.Message}", ex);
            }
            finally
            {
                await Task.CompletedTask; // 确保方法是真正的异步方法
            }
        }
    }

    /// <summary>
    /// 生成路径命令
    /// </summary>
    public class GeneratePathCommand : CommandBase
    {
        private readonly PathRoute _route;
        private readonly PathPlanningManager _pathManager;

        public GeneratePathCommand(PathPlanningManager pathManager, PathRoute route = null)
            : base("GeneratePath", "生成路径", "生成或重新计算路径")
        {
            _pathManager = pathManager ?? throw new ArgumentNullException(nameof(pathManager));
            _route = route;
        }

        protected override PathPlanningResult ValidateParameters()
        {
            if (_pathManager == null)
                return PathPlanningResult.ValidationFailure("路径管理器未初始化");

            var targetRoute = _route ?? _pathManager.CurrentRoute;
            if (targetRoute == null)
                return PathPlanningResult.ValidationFailure("没有指定要生成的路径");

            if (!targetRoute.IsValid())
                return PathPlanningResult.ValidationFailure("路径无效：必须包含至少一个起点和一个终点");

            return PathPlanningResult.Success("参数验证通过");
        }

        protected override async Task<PathPlanningResult> ExecuteInternalAsync(CancellationToken cancellationToken)
        {
            var targetRoute = _route ?? _pathManager.CurrentRoute;
            
            UpdateProgress(20, $"正在生成路径: {targetRoute.Name}");
            
            try
            {
                bool success = _pathManager.GeneratePath(targetRoute);
                
                if (!success)
                {
                    return PathPlanningResult.Failure("路径生成失败");
                }

                UpdateProgress(100, "路径生成完成");
                
                return PathPlanningResult<PathRoute>.Success(
                    targetRoute, 
                    $"路径 '{targetRoute.Name}' 生成成功，长度: {targetRoute.TotalLength:F2}米，预估时间: {targetRoute.EstimatedTime:F1}秒"
                );
            }
            catch (Exception ex)
            {
                LogError("生成路径时发生错误", ex);
                return PathPlanningResult.Failure($"生成路径失败: {ex.Message}", ex);
            }
            finally
            {
                await Task.CompletedTask; // 确保方法是真正的异步方法
            }
        }
    }

    /// <summary>
    /// 删除路径命令
    /// </summary>
    public class DeleteRouteCommand : CommandBase
    {
        private readonly PathRoute _route;
        private readonly PathPlanningManager _pathManager;

        public DeleteRouteCommand(PathPlanningManager pathManager, PathRoute route)
            : base("DeleteRoute", "删除路径", "删除指定的路径")
        {
            _pathManager = pathManager ?? throw new ArgumentNullException(nameof(pathManager));
            _route = route ?? throw new ArgumentNullException(nameof(route));
        }

        protected override PathPlanningResult ValidateParameters()
        {
            if (_pathManager == null)
                return PathPlanningResult.ValidationFailure("路径管理器未初始化");

            if (_route == null)
                return PathPlanningResult.ValidationFailure("没有指定要删除的路径");

            if (!_pathManager.Routes.Contains(_route))
                return PathPlanningResult.ValidationFailure("指定的路径不存在于管理器中");

            return PathPlanningResult.Success("参数验证通过");
        }

        protected override async Task<PathPlanningResult> ExecuteInternalAsync(CancellationToken cancellationToken)
        {
            UpdateProgress(30, $"正在删除路径: {_route.Name}");
            
            try
            {
                string routeName = _route.Name;
                bool success = _pathManager.DeleteRoute(_route);
                
                if (!success)
                {
                    return PathPlanningResult.Failure("删除路径失败");
                }

                UpdateProgress(100, "路径删除完成");
                
                return PathPlanningResult.Success($"路径 '{routeName}' 已成功删除");
            }
            catch (Exception ex)
            {
                LogError("删除路径时发生错误", ex);
                return PathPlanningResult.Failure($"删除路径失败: {ex.Message}", ex);
            }
            finally
            {
                await Task.CompletedTask; // 确保方法是真正的异步方法
            }
        }
    }

    /// <summary>
    /// 切换到编辑状态命令
    /// </summary>
    public class SwitchToEditingStateCommand : CommandBase
    {
        private readonly PathRoute _route;
        private readonly PathPlanningManager _pathManager;

        public SwitchToEditingStateCommand(PathPlanningManager pathManager, PathRoute route)
            : base("SwitchToEditingState", "切换到编辑状态", "切换到路径编辑状态")
        {
            _pathManager = pathManager ?? throw new ArgumentNullException(nameof(pathManager));
            _route = route ?? throw new ArgumentNullException(nameof(route));
        }

        protected override PathPlanningResult ValidateParameters()
        {
            if (_pathManager == null)
                return PathPlanningResult.ValidationFailure("路径管理器未初始化");

            if (_route == null)
                return PathPlanningResult.ValidationFailure("没有指定要编辑的路径");

            if (_pathManager.IsInEditableState)
                return PathPlanningResult.ValidationFailure("当前已在编辑状态，请先完成或取消当前编辑");

            return PathPlanningResult.Success("参数验证通过");
        }

        protected override async Task<PathPlanningResult> ExecuteInternalAsync(CancellationToken cancellationToken)
        {
            UpdateProgress(40, $"正在切换到编辑状态: {_route.Name}");
            
            try
            {
                _pathManager.SwitchToEditingState(_route);
                
                UpdateProgress(100, "已切换到编辑状态");
                
                return PathPlanningResult.Success($"已切换到编辑状态，正在编辑路径: {_route.Name}");
            }
            catch (Exception ex)
            {
                LogError("切换到编辑状态时发生错误", ex);
                return PathPlanningResult.Failure($"切换到编辑状态失败: {ex.Message}", ex);
            }
            finally
            {
                await Task.CompletedTask; // 确保方法是真正的异步方法
            }
        }
    }

    /// <summary>
    /// 切换到查看状态命令
    /// </summary>
    public class SwitchToViewingStateCommand : CommandBase
    {
        private readonly PathPlanningManager _pathManager;

        public SwitchToViewingStateCommand(PathPlanningManager pathManager)
            : base("SwitchToViewingState", "切换到查看状态", "切换到路径查看状态")
        {
            _pathManager = pathManager ?? throw new ArgumentNullException(nameof(pathManager));
        }

        protected override PathPlanningResult ValidateParameters()
        {
            if (_pathManager == null)
                return PathPlanningResult.ValidationFailure("路径管理器未初始化");

            return PathPlanningResult.Success("参数验证通过");
        }

        protected override async Task<PathPlanningResult> ExecuteInternalAsync(CancellationToken cancellationToken)
        {
            UpdateProgress(40, "正在切换到查看状态...");
            
            try
            {
                _pathManager.SwitchToViewingState();
                
                UpdateProgress(100, "已切换到查看状态");
                
                return PathPlanningResult.Success("已切换到查看状态");
            }
            catch (Exception ex)
            {
                LogError("切换到查看状态时发生错误", ex);
                return PathPlanningResult.Failure($"切换到查看状态失败: {ex.Message}", ex);
            }
            finally
            {
                await Task.CompletedTask; // 确保方法是真正的异步方法
            }
        }
    }
}