part of book_detail;

class BookDetailController extends GetxController with GetSingleTickerProviderStateMixin{

  final String bookId;
  BookDetailController(this.bookId);


  final PageController pageController = PageController(initialPage: 0);
  List <Widget>tabs = [
    const Tab(text: '目录',),
    const Tab(text: '编辑推荐',),
    const Tab(text: '简介',),
    const Tab(text: '本书信息',),
  ];
  late TabController tabController = TabController(length: tabs.length, vsync: this);

  num currentChapterId = 0;

  // 目录
  List <ChapterModel> chapters = [];
  // 图书
  BookDetailModel bookDetails = BookDetailModel();


  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    getBookDetails();
    getChapters();
    super.onReady();
  }

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

  /// 加入书架
  void addCart(String bookId) async {
    final result = await ShopAPI.addCart(bookId: bookId);
    if(result){
      Toast.show('加入书架成功');
    }
  }

  void writeCurrentReadChapterIdToData(List<ChapterModel> data) {
    for(ChapterModel cModel in data){
      cModel.currentRead = false;
      if(cModel.id == currentChapterId){
        cModel.currentRead = true;
        cModel.selected = true;
      }
      else{
        writeCurrentReadChapterIdToData(cModel.children!);
      }
    }

    ChapterModel? tModel = findChapterById(chapters, currentChapterId);
    if(tModel != null){
      updateParentsStatus(chapters, tModel!);
    }

  }

  ChapterModel? findChapterById(List<ChapterModel> data,num id){
    for (ChapterModel cModel in data){
      if(cModel.id == id){
        return cModel;
      }
      ChapterModel? tModel = findChapterById(cModel.children!, id);
      if(tModel !=null){
        return tModel;
      }
    }
    return null;
  }

  void updateParentsStatus(List<ChapterModel> data, ChapterModel model) {
    ChapterModel? parentNode = findParentChapter(data, model);
    while (parentNode != null) {
      parentNode.selected = true;
      parentNode = findParentChapter(data, parentNode);
    }
  }

  ChapterModel? findParentChapter(List<ChapterModel> data, ChapterModel model){
    for (ChapterModel tModel in data){
      if(tModel.id == model.pid){
        return tModel;
      }
      ChapterModel? cModel = findParentChapter(tModel.children!, model);
      if(cModel != null) {
        return cModel;
      }
    }
    return null;
  }



  /// 写入特定数据

  void writeData(List<ChapterModel> listA, List<ChapterModel> listB){
    for(int i = 0; i < listA.length;i++){
      ChapterModel aModel = listA[i];
      ChapterModel bModel = listB[i];
      if(aModel.id == bModel.id){
        // aModel.seen = bModel.seen;
        bModel.selected = aModel.selected;
      }
      writeData(aModel.children!, bModel.children!);
    }
  }
  /// 获取目录信息
  void getChapters() async {
    final result = await LibraryAPI.chapters(bookId: bookId);
    writeData(chapters, result);

    chapters = result;
    writeCurrentReadChapterIdToData(chapters);
    update();
  }

  /// 获取图书详细信息
  void getBookDetails() async {
    bookDetails = await LibraryAPI.details(bookId:bookId);
    // 将阅读最后章节写入到数据库
    bool netStatus = await Tools.checkCurrentNetStatus();
    // 有网络的时候才会 存储 其余不存储
    if (netStatus){
      try {
        final result = await SqlManager.updateReadHistoryByBookId(int.parse(bookId), bookDetails.chapterId!.toInt());
        Console.log('Sql-------存入数据库读到的章节----------------book_id:$bookId-----chapterId:${bookDetails.chapterId!.toInt()}---------result:$result--');
      }
      catch(err){
        Console.log('Sql--------------err------------------$err');
      }
    }

    update();
  }
  /// 收藏 与 取消收藏
  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) {
      getBookDetails();
    }
  }

  // 获取当前的章节id
  Future<String> getCurrentChapterId() async{
    String chapterId = '';
    bool netStatus = await Tools.checkCurrentNetStatus();
    final exist = await _isExistFile(bookId);
    if (!netStatus && exist){
      chapterId = await SqlManager.queryReadHistoryByBookId(int.parse(bookId));
    }
    else{
      chapterId = bookDetails.chapterId.toString();
    }
    return chapterId;
  }
  // 获取当前的章节名称
  Future<String> getCurrentChapterName() async{
    String chapterName = '';
    bool netStatus = await Tools.checkCurrentNetStatus();
    final exist = await _isExistFile(bookId);
    if (!netStatus && exist){
      String chapterId = await SqlManager.queryReadHistoryByBookId(int.parse(bookId));
      chapterName = _getChapterName(chapterId);
    }
    else{
      chapterName = bookDetails.chapterName.toString();
    }

    Console.log('getCurrentChapterName-------------------------------$chapterName-');
    return chapterName;
  }


  // 判断是否存在离线文件
  Future<bool> _isExistFile(String bookId) async {
    bool existDownFile= false;
    String directoryPath = await Tools.getDirectory();
    Directory directory = Directory(directoryPath);
    bool directoryExists = await directory.exists();
    if (directoryExists) {
      Console.log('存在名为 "$bookId" 的文件夹');
      existDownFile =  await Directory('${directory.path}/$bookId').exists();

    }
    else {
      Console.log('不存在名为 "$bookId" 的文件夹');
      existDownFile = false;
    }
    return existDownFile;
  }

  String _getChapterName(String chapterId){
    for (ChapterModel model in chapters){
      if ('${model.id}' == chapterId){
        return model.name??'';
      }
      if (model.children !=null){
        for (ChapterModel subModel in model.children!){
          if ('${subModel.id}' == chapterId){
            return subModel.name??'';
          }
        }
      }

    }
    return '';
  }




}