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() async {
    // 获取标签数据
    _getLabels();
    _getAds();
    onRefresh();

    // Map<String, dynamic> data = {
    //   'types': 1,
    //   'book_id': 175,
    //   'chapter_id': 334,
    //   'is_open': 1,
    //   'color': 'blue',
    //   'content': 'This is a note content',
    //   'upload': 0,
    //   'positioning': 'top',
    //   'note_content': 'This is a note',
    //   'node_id': 0,
    // };
    //
    // await SqlManager.insertData(data);

    final result = await Tools.checkCurrentNetStatus();
    // 有网络 并且是登录状态 的时候上传 笔记
    if (result && UserStore.to.isLogin){
      upload();
    }
    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;
    }
    selectedFree.id = '';

    for(FilterModel model in filterDown){
      model.selected = false;
    }
    selectedDown.id ='';
    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: '3');
    update();
  }

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

    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();
    }
  }

  /// 批量上传离线笔记、高亮、划线的内容
  void upload() async{
    List<Map<String, dynamic>> data = await SqlManager.queryNoUploadData();

    Console.log('查询到的数据----------------------------------------------------$data');
    if(data.isNotEmpty){
      for (Map<String, dynamic> temp in data){

        // 如果是笔记
        if (temp['type'] == '3'){
          // 存储url的数组
          List<String> finalAudios = [];
          // 存储url的数组
          List<String> finalImages = [];

          Map<String,dynamic> contentMap =  jsonDecode(temp['note_content']);
          List<String> audios = contentMap['audio'];
          if(audios.isNotEmpty){
            for(String path in audios){
              final url = await uploadSource(path: path);
              finalAudios.add(url);
            }
          }
          List<String> images = contentMap['image'];
          if(images.isNotEmpty){
            for(String path in images){
              final url = await uploadSource(path: path);
              finalImages.add(url);
            }
          }
          Map<String,dynamic> finalContentMap = {
            'text':contentMap['text'],
            'audio': finalAudios,
            'image': finalImages
          };
          temp['note_content'] = finalContentMap;
        }
      }
      final result = await LibraryAPI.uploadOffline(node: jsonEncode(data));
      // 上传成功后 更新数据库中的字段
      if (result) {
        SqlManager.updateUploadStatus();
      }
    }

  }

  // 上传文件
  Future<String> uploadSource({
    required String path
  }) async {
    // String result  = await CommonAPI.upload(path:path,fileTypes: 'comment');
    // return result;
    OssTool tool = OssTool('zxts-comment-file');
    final response = await tool.putObjectFile(path);
    Console.log('------response--------------------------${response.realUri}');
    return response.realUri.toString();
  }


  /// 获取图书列表数据
  Future<void> _getBooks([bool isRefresh = false]) async {
    _getAds();

    String sort = '';
    if (selectedDown.id !=null){
      if (selectedDown.id!.isNotEmpty){
        if(selectedDown.up){
          sort = 'desc';
        }
        else{
          sort = 'asc';
        }
      }
    }

    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??'',
      sort :sort
      // sort:selectedDown.id!.isEmpty?'':selectedDown.up ==true?'desc':'asc'
    );
    // 如果是刷新 清理数据
    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) {
      Console.log('----------获取图书---------------------------------------$error---------------');
      refreshController.finishRefresh(IndicatorResult.fail);
    }
  }

  void onLoading() async {
    if (_noMore) {
      refreshController.finishLoad(IndicatorResult.noMore);
      return;
    }
    try {
      await _getBooks();
      refreshController.finishLoad();
    } catch (error) {
      Console.log('----------获取图书---------------------------------------$error---------------');
      refreshController.finishLoad(IndicatorResult.fail);
    }
  }



}