part of book_detail;

class BookDetailController extends GetxController with GetSingleTickerProviderStateMixin{

  final String bookId;
  BookDetailController(this.bookId);

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

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


  @override
  void onInit() {
    tabController = TabController(length: tabs.length, vsync: this);
    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 getChapters() async {


    chapters = await LibraryAPI.chapters(bookId: bookId);

    // chapters = [
    //   ChapterModel(name: '第一章',selected: false, children: [
    //     ChapterModel(name: '第一节',children: [
    //       ChapterModel(name: '第一小节',children: []),
    //     ]),
    //     ChapterModel(name: '第二节',children: [
    //       ChapterModel(name: '第二小节',children: []),
    //     ])
    //   ]),
    //   ChapterModel(name: '第二章',children: [
    //     ChapterModel(name: '第一节',children: [
    //       ChapterModel(name: '第1小节',children: []),
    //     ]),
    //     ChapterModel(name: '第一节',children: [
    //       ChapterModel(name: '第1小节',children: []),
    //     ])
    //   ]),
    // ];
    update();
  }

  /// 获取图书详细信息
  void getBookDetails() async {
    bookDetails = await LibraryAPI.details(bookId:bookId);
    // 将阅读最后章节写入到数据库
    SqlManager.updateReadHistoryByBookId(int.parse(bookId), bookDetails.chapterId!.toInt());
    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());
    Console.log('================================$result');
    if (result) {
      getBookDetails();
    }
  }






}