using System.Collections;
using System.Collections.ObjectModel;

namespace NavisworksTransport.Core.UIUpdate.Updates
{
    /// <summary>
    /// 集合更新操作类型
    /// </summary>
    public enum CollectionUpdateType
    {
        /// <summary>
        /// 添加项目
        /// </summary>
        Add,

        /// <summary>
        /// 删除项目
        /// </summary>
        Remove,

        /// <summary>
        /// 清空集合
        /// </summary>
        Clear,

        /// <summary>
        /// 替换项目
        /// </summary>
        Replace,

        /// <summary>
        /// 插入项目
        /// </summary>
        Insert,

        /// <summary>
        /// 批量添加
        /// </summary>
        AddRange,

        /// <summary>
        /// 批量删除
        /// </summary>
        RemoveRange
    }

    /// <summary>
    /// 集合更新操作
    /// 支持ObservableCollection、ThreadSafeObservableCollection、ListView等集合的线程安全更新
    /// </summary>
    public class CollectionUpdateOperation : UIUpdateBase
    {
        #region 字段和属性

        /// <summary>
        /// 目标集合
        /// </summary>
        public object TargetCollection { get; }

        /// <summary>
        /// 更新操作类型
        /// </summary>
        public CollectionUpdateType UpdateType { get; }

        /// <summary>
        /// 要操作的项目
        /// </summary>
        public object Item { get; }

        /// <summary>
        /// 要操作的项目集合（用于批量操作）
        /// </summary>
        public IEnumerable<object> Items { get; }

        /// <summary>
        /// 插入位置（用于Insert操作）
        /// </summary>
        public int Index { get; }

        /// <summary>
        /// 原始状态快照（用于回滚）
        /// </summary>
        private List<object> _originalItems;

        /// <summary>
        /// 是否已保存原始状态
        /// </summary>
        private bool _originalStateSaved = false;

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化集合更新操作（单项操作）
        /// </summary>
        /// <param name="targetCollection">目标集合</param>
        /// <param name="updateType">更新类型</param>
        /// <param name="item">要操作的项目</param>
        /// <param name="index">索引位置（可选）</param>
        /// <param name="priority">操作优先级</param>
        public CollectionUpdateOperation(object targetCollection, CollectionUpdateType updateType, object item = null, int index = -1, UIUpdatePriority priority = UIUpdatePriority.Normal)
            : base($"CollectionUpdate_{updateType}", $"集合{updateType}操作", priority)
        {
            TargetCollection = targetCollection ?? throw new ArgumentNullException(nameof(targetCollection));
            UpdateType = updateType;
            Item = item;
            Index = index;

            TargetFramework = DetectTargetFramework(targetCollection);
            SupportsRollback = true;
        }

        /// <summary>
        /// 初始化集合更新操作（批量操作）
        /// </summary>
        /// <param name="targetCollection">目标集合</param>
        /// <param name="updateType">更新类型</param>
        /// <param name="items">要操作的项目集合</param>
        /// <param name="priority">操作优先级</param>
        public CollectionUpdateOperation(object targetCollection, CollectionUpdateType updateType, IEnumerable<object> items, UIUpdatePriority priority = UIUpdatePriority.Normal)
            : base($"CollectionUpdate_{updateType}", $"集合批量{updateType}操作", priority)
        {
            TargetCollection = targetCollection ?? throw new ArgumentNullException(nameof(targetCollection));
            UpdateType = updateType;
            Items = items;
            Index = -1;

            TargetFramework = DetectTargetFramework(targetCollection);
            SupportsRollback = true;
        }

        #endregion

        #region 受保护方法重写

        /// <summary>
        /// 内部验证逻辑
        /// </summary>
        /// <param name="context">更新上下文</param>
        /// <returns>验证结果</returns>
        protected override UIUpdateValidationResult ValidateInternal(UIUpdateContext context)
        {
            try
            {
                // 检查目标集合
                if (TargetCollection == null)
                {
                    return UIUpdateValidationResult.Failure("目标集合不能为空");
                }

                // 检查集合类型是否支持
                if (!IsSupportedCollectionType(TargetCollection))
                {
                    return UIUpdateValidationResult.Failure($"不支持的集合类型: {TargetCollection.GetType().Name}");
                }

                // 根据操作类型验证参数
                switch (UpdateType)
                {
                    case CollectionUpdateType.Add:
                        if (Item == null)
                        {
                            return UIUpdateValidationResult.Failure("Add操作需要指定Item参数");
                        }
                        break;

                    case CollectionUpdateType.Remove:
                        if (Item == null)
                        {
                            return UIUpdateValidationResult.Failure("Remove操作需要指定Item参数");
                        }
                        break;

                    case CollectionUpdateType.Insert:
                        if (Item == null)
                        {
                            return UIUpdateValidationResult.Failure("Insert操作需要指定Item参数");
                        }
                        if (Index < 0)
                        {
                            return UIUpdateValidationResult.Failure("Insert操作需要指定有效的Index参数");
                        }
                        break;

                    case CollectionUpdateType.Replace:
                        if (Item == null)
                        {
                            return UIUpdateValidationResult.Failure("Replace操作需要指定Item参数");
                        }
                        if (Index < 0)
                        {
                            return UIUpdateValidationResult.Failure("Replace操作需要指定有效的Index参数");
                        }
                        break;

                    case CollectionUpdateType.AddRange:
                    case CollectionUpdateType.RemoveRange:
                        if (Items == null || !Items.Any())
                        {
                            return UIUpdateValidationResult.Failure($"{UpdateType}操作需要指定Items参数");
                        }
                        break;

                    case CollectionUpdateType.Clear:
                        // Clear操作不需要额外参数
                        break;
                }

                return UIUpdateValidationResult.Success();
            }
            catch (Exception ex)
            {
                return UIUpdateValidationResult.Failure($"验证集合更新操作时发生异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 执行前置处理
        /// </summary>
        /// <param name="context">更新上下文</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        protected override async Task<UIUpdateResult> PreExecuteAsync(UIUpdateContext context, CancellationToken cancellationToken)
        {
            try
            {
                // 保存原始状态用于回滚
                if (!_originalStateSaved && SupportsRollback)
                {
                    _originalItems = CreateSnapshot(TargetCollection);
                    _originalStateSaved = true;
                    LogInfo($"已保存集合原始状态，共{_originalItems.Count}项");
                }

                return await Task.FromResult(UIUpdateResult.Success("前置处理完成", Id));
            }
            catch (Exception ex)
            {
                return UIUpdateResult.Failure($"前置处理失败: {ex.Message}", ex, Id);
            }
        }

        /// <summary>
        /// 执行主要逻辑
        /// </summary>
        /// <param name="context">更新上下文</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>执行结果</returns>
        protected override async Task<UIUpdateResult> ExecuteInternalAsync(UIUpdateContext context, CancellationToken cancellationToken)
        {
            try
            {
                LogInfo($"执行集合{UpdateType}操作");

                // 根据集合类型选择更新方式
                if (TargetCollection is ThreadSafeObservableCollection<object> threadSafeCollection)
                {
                    return await UpdateThreadSafeObservableCollectionAsync(threadSafeCollection, cancellationToken);
                }
                else if (TargetCollection is IList list)
                {
                    return await UpdateListAsync(list, cancellationToken);
                }
                else if (TargetCollection is ListView listView)
                {
                    return await UpdateListViewAsync(listView, cancellationToken);
                }
                else
                {
                    return UIUpdateResult.Failure($"不支持的集合类型: {TargetCollection.GetType().Name}", null, Id);
                }
            }
            catch (Exception ex)
            {
                LogError($"执行集合{UpdateType}操作失败", ex);
                return UIUpdateResult.Failure($"集合更新失败: {ex.Message}", ex, Id);
            }
        }

        /// <summary>
        /// 内部回滚逻辑
        /// </summary>
        /// <param name="context">更新上下文</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>回滚结果</returns>
        protected override async Task<UIUpdateResult> RollbackInternalAsync(UIUpdateContext context, CancellationToken cancellationToken)
        {
            try
            {
                if (!_originalStateSaved || _originalItems == null)
                {
                    return UIUpdateResult.Failure("无法回滚，原始状态未保存", null, Id);
                }

                LogInfo($"回滚集合状态，恢复到{_originalItems.Count}项");

                // 清空当前集合并恢复原始项目
                var clearOperation = new CollectionUpdateOperation(TargetCollection, CollectionUpdateType.Clear);
                var clearResult = await clearOperation.ExecuteInternalAsync(context, cancellationToken);
                
                if (!clearResult.IsSuccess)
                {
                    return UIUpdateResult.Failure($"回滚清空集合失败: {clearResult.Message}", null, Id);
                }

                // 恢复原始项目
                if (_originalItems.Count > 0)
                {
                    var restoreOperation = new CollectionUpdateOperation(TargetCollection, CollectionUpdateType.AddRange, _originalItems);
                    var restoreResult = await restoreOperation.ExecuteInternalAsync(context, cancellationToken);
                    
                    if (!restoreResult.IsSuccess)
                    {
                        return UIUpdateResult.Failure($"回滚恢复项目失败: {restoreResult.Message}", null, Id);
                    }
                }

                return UIUpdateResult.Success($"成功回滚集合状态", Id);
            }
            catch (Exception ex)
            {
                LogError($"回滚集合状态时发生异常", ex);
                return UIUpdateResult.Failure($"回滚失败: {ex.Message}", ex, Id);
            }
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 检测目标框架类型
        /// </summary>
        /// <param name="collection">目标集合</param>
        /// <returns>框架类型</returns>
        private UIFrameworkType DetectTargetFramework(object collection)
        {
            if (collection is DependencyObject || collection is ObservableCollection<object>)
            {
                return UIFrameworkType.WPF;
            }

            if (collection is Control || collection is ListView)
            {
                return UIFrameworkType.WinForms;
            }

            return UIFrameworkType.Auto;
        }

        /// <summary>
        /// 检查是否为支持的集合类型
        /// </summary>
        /// <param name="collection">集合对象</param>
        /// <returns>是否支持</returns>
        private bool IsSupportedCollectionType(object collection)
        {
            return collection is IList ||
                   collection is ICollection ||
                   collection is ListView ||
                   collection is ThreadSafeObservableCollection<object>;
        }

        /// <summary>
        /// 创建集合状态快照
        /// </summary>
        /// <param name="collection">目标集合</param>
        /// <returns>状态快照</returns>
        private List<object> CreateSnapshot(object collection)
        {
            var snapshot = new List<object>();

            if (collection is IEnumerable enumerable)
            {
                foreach (var item in enumerable)
                {
                    snapshot.Add(item);
                }
            }
            else if (collection is ListView listView)
            {
                foreach (ListViewItem item in listView.Items)
                {
                    snapshot.Add(item);
                }
            }

            return snapshot;
        }

        /// <summary>
        /// 更新ThreadSafeObservableCollection
        /// </summary>
        /// <param name="collection">目标集合</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>更新结果</returns>
        private async Task<UIUpdateResult> UpdateThreadSafeObservableCollectionAsync(ThreadSafeObservableCollection<object> collection, CancellationToken cancellationToken)
        {
            try
            {
                switch (UpdateType)
                {
                    case CollectionUpdateType.Add:
                        collection.Add(Item);
                        break;

                    case CollectionUpdateType.Remove:
                        collection.Remove(Item);
                        break;

                    case CollectionUpdateType.Clear:
                        collection.Clear();
                        break;

                    case CollectionUpdateType.Insert:
                        collection.Insert(Index, Item);
                        break;

                    case CollectionUpdateType.Replace:
                        if (Index < collection.Count)
                        {
                            collection[Index] = Item;
                        }
                        else
                        {
                            return UIUpdateResult.Failure($"索引{Index}超出集合范围", null, Id);
                        }
                        break;

                    case CollectionUpdateType.AddRange:
                        foreach (var item in Items)
                        {
                            collection.Add(item);
                        }
                        break;

                    case CollectionUpdateType.RemoveRange:
                        foreach (var item in Items.ToList()) // 创建副本避免枚举修改问题
                        {
                            collection.Remove(item);
                        }
                        break;

                    default:
                        return UIUpdateResult.Failure($"不支持的更新类型: {UpdateType}", null, Id);
                }

                return await Task.FromResult(UIUpdateResult.Success($"ThreadSafeObservableCollection {UpdateType}操作成功", Id));
            }
            catch (Exception ex)
            {
                return UIUpdateResult.Failure($"ThreadSafeObservableCollection操作失败: {ex.Message}", ex, Id);
            }
        }

        /// <summary>
        /// 更新普通List集合
        /// </summary>
        /// <param name="list">目标列表</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>更新结果</returns>
        private async Task<UIUpdateResult> UpdateListAsync(IList list, CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource<UIUpdateResult>();

            try
            {
                // 检查是否需要UI线程调度
                if (RequiresUIThread && TargetFramework == UIFrameworkType.WPF && Application.Current != null)
                {
                    Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        try
                        {
                            var result = ExecuteListOperation(list);
                            tcs.SetResult(result);
                        }
                        catch (Exception ex)
                        {
                            tcs.SetResult(UIUpdateResult.Failure($"WPF List操作失败: {ex.Message}", ex, Id));
                        }
                    }));
                }
                else if (RequiresUIThread && TargetFramework == UIFrameworkType.WinForms && list is Control control)
                {
                    if (control.InvokeRequired)
                    {
                        control.BeginInvoke(new Action(() =>
                        {
                            try
                            {
                                var result = ExecuteListOperation(list);
                                tcs.SetResult(result);
                            }
                            catch (Exception ex)
                            {
                                tcs.SetResult(UIUpdateResult.Failure($"WinForms List操作失败: {ex.Message}", ex, Id));
                            }
                        }));
                    }
                    else
                    {
                        var result = ExecuteListOperation(list);
                        tcs.SetResult(result);
                    }
                }
                else
                {
                    var result = ExecuteListOperation(list);
                    tcs.SetResult(result);
                }

                return await tcs.Task;
            }
            catch (Exception ex)
            {
                return UIUpdateResult.Failure($"List操作异常: {ex.Message}", ex, Id);
            }
        }

        /// <summary>
        /// 执行List操作
        /// </summary>
        /// <param name="list">目标列表</param>
        /// <returns>操作结果</returns>
        private UIUpdateResult ExecuteListOperation(IList list)
        {
            try
            {
                switch (UpdateType)
                {
                    case CollectionUpdateType.Add:
                        list.Add(Item);
                        break;

                    case CollectionUpdateType.Remove:
                        list.Remove(Item);
                        break;

                    case CollectionUpdateType.Clear:
                        list.Clear();
                        break;

                    case CollectionUpdateType.Insert:
                        list.Insert(Index, Item);
                        break;

                    case CollectionUpdateType.Replace:
                        if (Index < list.Count)
                        {
                            list[Index] = Item;
                        }
                        else
                        {
                            return UIUpdateResult.Failure($"索引{Index}超出集合范围", null, Id);
                        }
                        break;

                    case CollectionUpdateType.AddRange:
                        foreach (var item in Items)
                        {
                            list.Add(item);
                        }
                        break;

                    case CollectionUpdateType.RemoveRange:
                        foreach (var item in Items.ToList())
                        {
                            list.Remove(item);
                        }
                        break;

                    default:
                        return UIUpdateResult.Failure($"不支持的更新类型: {UpdateType}", null, Id);
                }

                return UIUpdateResult.Success($"List {UpdateType}操作成功", Id);
            }
            catch (Exception ex)
            {
                return UIUpdateResult.Failure($"List操作失败: {ex.Message}", ex, Id);
            }
        }

        /// <summary>
        /// 更新ListView控件
        /// </summary>
        /// <param name="listView">目标ListView</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>更新结果</returns>
        private async Task<UIUpdateResult> UpdateListViewAsync(ListView listView, CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource<UIUpdateResult>();

            try
            {
                if (listView.InvokeRequired)
                {
                    listView.BeginInvoke(new Action(() =>
                    {
                        try
                        {
                            var result = ExecuteListViewOperation(listView);
                            tcs.SetResult(result);
                        }
                        catch (Exception ex)
                        {
                            tcs.SetResult(UIUpdateResult.Failure($"ListView操作失败: {ex.Message}", ex, Id));
                        }
                    }));
                }
                else
                {
                    var result = ExecuteListViewOperation(listView);
                    tcs.SetResult(result);
                }

                return await tcs.Task;
            }
            catch (Exception ex)
            {
                return UIUpdateResult.Failure($"ListView操作异常: {ex.Message}", ex, Id);
            }
        }

        /// <summary>
        /// 执行ListView操作
        /// </summary>
        /// <param name="listView">目标ListView</param>
        /// <returns>操作结果</returns>
        private UIUpdateResult ExecuteListViewOperation(ListView listView)
        {
            try
            {
                switch (UpdateType)
                {
                    case CollectionUpdateType.Add:
                        if (Item is ListViewItem item)
                        {
                            listView.Items.Add(item);
                        }
                        else
                        {
                            listView.Items.Add(Item?.ToString() ?? "");
                        }
                        break;

                    case CollectionUpdateType.Remove:
                        if (Item is ListViewItem removeItem)
                        {
                            listView.Items.Remove(removeItem);
                        }
                        else if (Item is int removeIndex)
                        {
                            if (removeIndex >= 0 && removeIndex < listView.Items.Count)
                            {
                                listView.Items.RemoveAt(removeIndex);
                            }
                        }
                        else
                        {
                            // 根据文本查找并删除
                            var itemToRemove = listView.Items.Cast<ListViewItem>()
                                .FirstOrDefault(x => x.Text == Item?.ToString());
                            if (itemToRemove != null)
                            {
                                listView.Items.Remove(itemToRemove);
                            }
                        }
                        break;

                    case CollectionUpdateType.Clear:
                        listView.Items.Clear();
                        break;

                    case CollectionUpdateType.Insert:
                        if (Item is ListViewItem insertItem)
                        {
                            listView.Items.Insert(Index, insertItem);
                        }
                        else
                        {
                            listView.Items.Insert(Index, Item?.ToString() ?? "");
                        }
                        break;

                    case CollectionUpdateType.AddRange:
                        foreach (var addItem in Items)
                        {
                            if (addItem is ListViewItem listViewItem)
                            {
                                listView.Items.Add(listViewItem);
                            }
                            else
                            {
                                listView.Items.Add(addItem?.ToString() ?? "");
                            }
                        }
                        break;

                    case CollectionUpdateType.RemoveRange:
                        var itemsToRemove = Items.ToList();
                        foreach (var removeItem in itemsToRemove)
                        {
                            if (removeItem is ListViewItem listViewRemoveItem)
                            {
                                listView.Items.Remove(listViewRemoveItem);
                            }
                            else
                            {
                                var foundItem = listView.Items.Cast<ListViewItem>()
                                    .FirstOrDefault(x => x.Text == removeItem?.ToString());
                                if (foundItem != null)
                                {
                                    listView.Items.Remove(foundItem);
                                }
                            }
                        }
                        break;

                    default:
                        return UIUpdateResult.Failure($"不支持的更新类型: {UpdateType}", null, Id);
                }

                return UIUpdateResult.Success($"ListView {UpdateType}操作成功", Id);
            }
            catch (Exception ex)
            {
                return UIUpdateResult.Failure($"ListView操作失败: {ex.Message}", ex, Id);
            }
        }

        #endregion
    }
}