part of library;

class LibraryController extends GetxController with GetTickerProviderStateMixin{
  
  // 分类数据
  List<CategoryModel> categories = [];
  // 标签数据
  List<LabelModel> labels = [];

  // 广告数组
  List<AdModel> ads = [];
  // 选中标签
  late FilterModel selectedLabel = FilterModel();
  // 选中分类
  late FilterModel selectedCategory = FilterModel();
  // 选中是否收费
  late FilterModel selectedFree = FilterModel();
  late FilterModel selectedDown = FilterModel();

  late TabController tabController = TabController(length:categories.length, vsync: this);

  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishLoad: true,
    controlFinishRefresh: true,
  );

  // 图书列表数据
  List<CourseModel> books = [];

  List<FilterModel> filterCategories = [];
  List<FilterModel> filterLabels = [];
  List<FilterModel> filterFree = [
    FilterModel(id: '0', name: '收费',selected: false),
    FilterModel(id: '1', name: '免费',selected: false)
  ];
  List<FilterModel> filterDown = [
    FilterModel(id: 'read_num', name: '读过'),
    FilterModel(id: 'rating', name: '评分')
  ];


  final int _limit = 20;
  int _page = 1;
  bool _noMore = false;


  late AnimationController _controller;
  bool _show = false;

  bool get show => _show;
  void setShow(bool value) {
    _show = !value;
    if (_show) {
      /// 开启动画
      _controller.forward();
    }
    else {
      /// 收回动画
      _controller.reverse();
    }
    update();
  }


  AnimationController get controller => _controller;

  @override
  void onInit() {
    // 获取分类数据
    _getTabs();

    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 100),
    );
    super.onInit();

  }

  @override
  void onReady() {
    // 获取标签数据
    _getLabels();
    _getAds();
    onRefresh();
    super.onReady();
  }

  @override
  void onClose() {
    tabController.dispose();
    refreshController.dispose();
    super.onClose();
  }

  /// 重置
  void resetFilter() {
    for(FilterModel model in filterCategories){
      model.selected = false;
    }
    filterCategories.first.selected = true;

    for(FilterModel model in filterLabels){
      model.selected = false;
    }
    filterLabels.first.selected = true;

    for(FilterModel model in filterFree){
      model.selected = false;
    }

    for(FilterModel model in filterDown){
      model.selected = false;
    }
    update();

  }

  /// 确定
  void sureFilter(){
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      tabController.animateTo(3); // 你想要的标签索引
    });
     update();
    for(FilterModel model in filterCategories){
      if (model.selected){
        selectedCategory = model;
      }
    }

    for(FilterModel model in filterLabels){
      if(model.selected){
        selectedLabel= model;
      }
    }
    for(FilterModel model in filterFree){
      if(model.selected){
        selectedFree= model;
      }
    }

    for(FilterModel model in filterDown){
      if(model.selected){
        selectedDown= model;
      }
    }

    onRefresh();

  }

  void selectLabel(FilterModel model){
    for (FilterModel m in filterLabels){
      m.selected = false;
    }
    model.selected = true;
    selectedLabel = model;
    onRefresh();
  }

  void selectCategory(FilterModel model){
    for (FilterModel m in filterCategories){
      m.selected = false;
    }
    model.selected = true;
    selectedCategory = model;
    onRefresh();
  }

  /// 获取广告数据
  void _getAds() async {
    ads = await CommonAPI.list(type: '1');
    update();
  }

  /// 获取tab分类数据
  void _getTabs() async {

    Map<String, dynamic> data = {
      'types': 1,
      'book_id': 123,
      'chapter_id': 456,
      // 'is_open': 1,
      // 'color': 'blue',
      // 'content': 'This is a note content',
      // 'del': 0,
      // 'positioning': 'top',
      // 'note': 'This is a note',
    };

    await SqlManager.insertData(data);

    categories = await LibraryAPI.categories();
    tabController.dispose();
    tabController = TabController(length:categories.length, vsync: this);
    categories.first.selected = true;
    filterCategories = categories.map((model) {
      return FilterModel(id: model.categoryId.toString(), name: model.name??'',selected: model.selected);
    }).toList();
    print('===========$filterCategories');
    update();
  }

  /// 获取标签数据
  void _getLabels() async {
    labels = await LibraryAPI.labels();

    filterLabels = labels.map((model) {
      return FilterModel(id: model.labelId.toString(), name: model.name??'',selected: model.selected);
    }).toList();
    selectedLabel = filterLabels.first;
    selectedLabel.selected = true;
    update(['label']);


  }

  /// 收藏 与 取消收藏
  void love({
    required String bookId,
    required num isCollection
  }) async {
    if (isCollection == 0){
      isCollection = 1;
    }
    else{
      isCollection = 0;
    }
    bool result = await CommonAPI.love(bookId: bookId, love: isCollection.toString());
    if (result) {
      onRefresh();
    }
  }


  /// 获取图书列表数据
  Future<void> _getBooks([bool isRefresh = false]) async {
    if (isRefresh) _page = 1;
    // 网路请求
    final result = await LibraryAPI.books(
      page: _page,
      limit: _limit,
      categoryId: selectedCategory.id??'',
      labelId: selectedLabel.id??'',
      isFree: selectedFree.id??'',
      sortField: selectedDown.id??''
    );
    // 如果是刷新 清理数据
    if (isRefresh) books.clear();
    books.addAll(result);
    _page ++;
    _noMore = result.length < _limit;
    update();

  }

  void onRefresh() async {
    try {
      await _getBooks(true);
      refreshController.finishRefresh(IndicatorResult.success);
      refreshController.resetFooter();
    } catch (error) {
      refreshController.finishRefresh(IndicatorResult.fail);
    }
  }

  void onLoading() async {
    if (_noMore) {
      refreshController.finishLoad(IndicatorResult.noMore);
      return;
    }
    try {
      await _getBooks();
      refreshController.finishLoad();
    } catch (error) {
      refreshController.finishLoad(IndicatorResult.fail);
    }
  }



}