import 'package:flutter/foundation.dart';
import '../models/element.dart';
import '../services/mock_data_service.dart';

/// 要素状态管理
class ElementProvider with ChangeNotifier {
  List<DocumentElement> _elements = [];
  List<DocumentElement> _selectedElements = [];
  String? _searchQuery;
  ElementType? _filterType;
  bool _loading = false;

  List<DocumentElement> get elements => _elements;
  List<DocumentElement> get selectedElements => _selectedElements;
  String? get searchQuery => _searchQuery;
  ElementType? get filterType => _filterType;
  bool get loading => _loading;

  /// 过滤后的要素列表
  List<DocumentElement> get filteredElements {
    var filtered = _elements;

    // 搜索过滤
    if (_searchQuery != null && _searchQuery!.isNotEmpty) {
      filtered = filtered.where((e) {
        return e.label.toLowerCase().contains(_searchQuery!.toLowerCase()) ||
            e.value.toLowerCase().contains(_searchQuery!.toLowerCase());
      }).toList();
    }

    // 类型过滤
    if (_filterType != null) {
      filtered = filtered.where((e) => e.type == _filterType).toList();
    }

    return filtered;
  }

  ElementProvider() {
    loadElements();
  }

  /// 加载要素列表
  Future<void> loadElements({String? documentId}) async {
    _loading = true;
    notifyListeners();

    // 模拟网络请求
    await Future.delayed(const Duration(milliseconds: 300));

    _elements = MockDataService.getMockElements();
    if (documentId != null) {
      _elements = _elements.where((e) => e.documentId == documentId).toList();
    }
    _loading = false;
    notifyListeners();
  }

  /// 设置搜索查询
  void setSearchQuery(String? query) {
    _searchQuery = query;
    notifyListeners();
  }

  /// 设置类型过滤
  void setFilterType(ElementType? type) {
    _filterType = type;
    notifyListeners();
  }

  /// 添加要素
  void addElement(DocumentElement element) {
    _elements.add(element);
    notifyListeners();
  }

  /// 批量替换要素
  void setElements(List<DocumentElement> elements) {
    _elements = List<DocumentElement>.from(elements);
    _selectedElements.clear();
    notifyListeners();
  }

  /// 删除要素
  void removeElement(String id) {
    _elements.removeWhere((e) => e.id == id);
    _selectedElements.removeWhere((e) => e.id == id);
    notifyListeners();
  }

  /// 选择要素
  void selectElement(DocumentElement element) {
    if (!_selectedElements.contains(element)) {
      _selectedElements.add(element);
      notifyListeners();
    }
  }

  /// 取消选择要素
  void deselectElement(DocumentElement element) {
    _selectedElements.remove(element);
    notifyListeners();
  }

  /// 清空选择
  void clearSelection() {
    _selectedElements.clear();
    notifyListeners();
  }
}
