part of web;

class ReadController extends FullLifeCycleController with GetSingleTickerProviderStateMixin{

  final String bookId;
  final String chapterId;
  final String chapterName;
  ReadController({required this.bookId, required this.chapterId,required this.chapterName});

  // 目录
  List <ChapterModel> chapters = [];
  List <ToolModel> tools = [
    ToolModel(tag: 0,name: '目录',selected: false,icon: 'assets/images/category_unselect.png',activeIcon: 'assets/images/category_select.png'),
    ToolModel(tag: 1,name: '笔记',selected: false,icon: 'assets/images/note_unselect.png',activeIcon:'assets/images/note_select.png'),
    ToolModel(tag: 2,name: '讨论',selected: false,icon: 'assets/images/discuss_unselect.png',activeIcon:'assets/images/discuss_select.png'),
  ];

  late ToolModel toolModel = tools.first;

  bool  showChat = false;

  final FocusNode discussTitleFocusNode = FocusNode();
  final FocusNode discussContentFocusNode = FocusNode();

  late AnimationController _controller;
  bool _show = true;
  bool get show => _show;

  // 讨论添加的图片数组
  List <String> discussInputImages= [];

  // 讨论话题标题
  final TextEditingController titleInput = TextEditingController();
  // 讨论内容
  final TextEditingController contentInput = TextEditingController();
  //

  ///------------------------------------------ 页面 生命周期--------------------------------------------------------
  @override
  void onInit() {
    // pageController = PageController(initialPage: currentPage);
    discussTitleFocusNode.addListener(_onCommentFocusChanged);
    /// 默认不显示状态栏
    // SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
    /// 初始化
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 100),
    );
    super.onInit();
  }

  @override
  void onReady() {
    // 上报开始阅读时间
    print('000000000000000000000--------------------------------$bookId');
    _addReadTime(type: 'open');
    _getChapters();
    super.onReady();
  }

  @override
  void onClose() {
    // 上报阅读结束时间
    _addReadTime(type: 'close');
    _controller.dispose();
    discussTitleFocusNode.removeListener(_onCommentFocusChanged);
    discussTitleFocusNode.dispose();
    titleInput.dispose();
    contentInput.dispose();
    super.onClose();
  }
  ///------------------------------------------ 页面 生命周期--------------------------------------------------------

  void setShow(bool value) {
    _show = !value;
    if (_show) {
      /// 显示状态栏
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
      /// 开启动画
      _controller.forward();
    }
    else {
      /// 不显示状态栏
      // SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
      /// 收回动画
      _controller.reverse();
    }
    update();
  }

  // 添加讨论图片
  void addDiscussInputImages(String path){
    discussInputImages.add(path);
    print('discussInputImages--------------------------------$path');
    update();
  }
  // 删除讨论图片
  void delDiscussInputImages(String path){
    discussInputImages.remove(path);
    print('delDiscussInputImages--------------------------------$path');
    update();
  }
  // 清空讨论图片
  void clearDiscussInputImages(){
    discussInputImages.clear();
    print('clearDiscussInputImages--------------------------------');
    update();
  }


  // 上传文件
  Future<String> upload({
    required String path
  }) async {
    String result  = await CommonAPI.upload(path:path,fileTypes: 'comment');
    return result;
  }

  // 发表评论
  // {String commentId ='0',String quoteContent ='',String title = ''}
  Future<bool> addDiscuss() async{
    // 音频链接数组
    List<String> audios = [];
    // 图片链接数组
    List<String> images = [];

    // 循环上传图片获取地址
    for(String path in discussInputImages){
      final url = await upload(path: path);
      images.add(url);
    }

    Map<String,dynamic> contentMap = {
      'text':contentInput.text,
      'audio':audios,
      'image':images
    };

    final result = await LibraryAPI.addDiscuss(
        bookId: bookId,
        chapterId: chapterId,
        commentId: '0',
        quoteContent: '',
        title: titleInput.text,
        content: jsonEncode(contentMap)
    );
    if(result){
      Toast.show('话题发表成功');
    }
    else{
      Toast.show('话题发表失败');
    }

    titleInput.text = '';
    contentInput.text = '';
    setShowChat(false);
    return result;

  }



  void chooseTool(ToolModel selectedModel){
    for (var model in tools) {
      // 如果当前遍历到的工具是选中的，并且不是点击的工具，则取消选中
      if (model.selected && model != selectedModel) {
        model.selected = false;
      }
      // 如果当前遍历到的工具是点击的工具，切换选中状态
      else if (model == selectedModel) {
        model.selected = !model.selected;
      }
    }
    toolModel = selectedModel;
    update();
  }


  AnimationController get controller => _controller;

  void _onCommentFocusChanged() {
    if (discussTitleFocusNode.hasFocus || discussContentFocusNode.hasFocus) {
      setShowChat(true);
    } else {
      setShowChat(false);
    }
  }

  void setShowChat(bool value) {
    showChat = value;
    update();
  }



  /// 获取目录信息
  void _getChapters() async {
    chapters = await LibraryAPI.chapters(bookId: bookId);
    update();
  }

  /// 添加阅读时长
  void _addReadTime({required type}) async{
    final result = await LibraryAPI.addReadTime(bookId: bookId, readTypes: type);
  }

  ///------------------------------------------ app 生命周期--------------------------------------------------------

  // 当应用程序从后台切换到前台并变为活动状态时调用。这通常在用户从其他应用程序返回到你的应用程序时发生
  void onResumed(){
    print('onResumed');
    // open
    // 上报开始阅读时间
    _addReadTime(type: 'open');
  }
  // 当应用程序失去焦点并进入非活动状态时调用。这可能是因为用户切换到其他应用程序或将应用程序最小化
  void onPaused(){
    // close
    print('onPaused');
    // 上报阅读结束时间
    _addReadTime(type: 'close');
  }
  // 当应用程序失去焦点但仍然可见时调用。通常，在用户切换到另一个应用程序或显示系统对话框时，应用程序可能会处于非活动状态，但仍然是可见的
  void onInactive(){
    print('onInactive');
    // close
    // 上报阅读结束时间
    _addReadTime(type: 'close');
  }
  // 当应用程序被挂起，可能是由于用户关闭应用程序或系统资源不足时调用。在这个状态下，应用程序的代码将不再运行，并且可能被系统终止
  void onDetached(){
    print('onDetached');
    // close
    // 上报阅读结束时间
    _addReadTime(type: 'close');
  }
  ///------------------------------------------ app 生命周期--------------------------------------------------------

}

class ToolModel {
  ToolModel({required this.tag, required this.selected, required this.name,required this.icon,required this.activeIcon});
  int tag;
  String name;
  bool selected;
  String icon;
  String activeIcon;
}