part of web;

class ReadPage extends StatefulWidget {
  final String bookId;
  final String chapterId;
  final String chapterName;
  final BookDetailModel bookDetailModel;
  const ReadPage({
    Key? key,
    required this.bookId,
    required this.chapterId,
    required this.chapterName,
    required this.bookDetailModel
  }) : super(key: key);

  @override
  State<ReadPage> createState() => _ReadPageState();
}

class _ReadPageState extends State<ReadPage> {

  @override
  void initState() {
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        context.pop(true);
        return false;
      },
      child: GetBuilder<ReadController>(
        init: ReadController(bookId: widget.bookId, chapterId: widget.chapterId,chapterName: widget.chapterName,bookDetailModel: widget.bookDetailModel),
        builder: (readController) => Scaffold(
          appBar: CustomAppBar(
            titleSpacing: 0,
            title: Align(
              alignment: Alignment.centerLeft,
              child: Text(readController.chapterName),
            ),
            centerTitle: false,
            actions: [
              GestureDetector(
                onTap: () {
                  readController.getBookDown();
                },
                child:  Text(
                  readController.existDownFile == true?'':'离线阅读',
                  style: TextStyle(
                      fontSize: 14.w, color: Colours.c3),
                ))
            ],
          ),
          resizeToAvoidBottomInset: false,
          floatingActionButton: readController.show&& !readController.toolModel.selected?GestureDetector(
            onTap: (){
              readController.setShowChat(true);
              readController.setChatType(0);
            },
            child: Image.asset('assets/images/chat.png'),
          ):null,
          // floatingActionButtonAnimator: const NoAnimationFabAnimator(),
          floatingActionButtonLocation:MyFloatingActionButtonLocation(),
         body: Container(
           color: Colors.white,
           child: Stack(
             children: [
               InAppWebView(
                 initialUrlRequest: URLRequest(
                   url: Uri.parse(kReadBook),
                   // url: Uri.parse("/storage/emulated/0/Android/data/com.zijin.book.flutter_book/files/174/7-325.html"),
                 ),
                 initialOptions: InAppWebViewGroupOptions(
                   crossPlatform: InAppWebViewOptions(
                     clearCache: true
                   )
                 ),
                 contextMenu: ContextMenu(
                   options: ContextMenuOptions(hideDefaultSystemContextMenuItems: true),
                 ),
                 onWebViewCreated: (InAppWebViewController controller){
                   readController.webViewController = controller;
                 },
                  onConsoleMessage: (controller, consoleMessage) {
                   // 接收从 WebView 发送的消息
                    Console.log("Received message from WebView-----------------------------: ${consoleMessage.message}");
                  },
                 onLoadStop: (controller, url) {
                   // flutter 主动给 js 传参数
                   Map<String, dynamic> param = {
                     'book_id': readController.bookId,
                     'chapter_id': readController.chapterId,
                     'token':UserStore.to.token
                   };
                   String str = '$kServerUrl,${readController.bookId},${readController.chapterId},${UserStore.to.token}';
                   Console.log('传给前端的参数--------------------------------$str');
                   controller.evaluateJavascript(source: 'callbackInFlutterComponent("$str");');

                   // 添加单击事件
                   controller.evaluateJavascript(source: '''
                      document.addEventListener('click', function() {
                        window.flutter_inappwebview.callHandler('onTap');
                      });
                    ''');

                   // 监听js单击回调
                   controller.addJavaScriptHandler(handlerName: 'onTap', callback: (args){
                     readController.setShow(readController.show);

                   });

                   // 监听笔记回调
                   controller.addJavaScriptHandler(handlerName: 'noteCallBack', callback: (args){
                     Console.log('监听笔记回调------------------------------------------------$args');
                     readController.noteTitle = args.first;
                     readController.setShowChat(true);
                     readController.setChatType(1);
                     // readController.titleInput.text = args.toString();
                   });

                   // 监听百科回调
                   controller.addJavaScriptHandler(handlerName: 'baikeCallBack', callback: (args){
                     Console.log('监听百科回调------------------------------------------------$args');
                     context.pushNamed(Routes.baiKe,queryParameters: {'keyword':args.first});
                   });

                   // 监听字典回调
                   controller.addJavaScriptHandler(handlerName: 'dictCallBack', callback: (args){
                     Console.log('监听百科回调------------------------------------------------$args');
                     context.pushNamed(Routes.baiDict,queryParameters: {'keyword':args.first});
                   });

                   // 监听朗读回调
                   controller.addJavaScriptHandler(handlerName: 'readCallBack', callback: (args){
                     Console.log('监听朗读回调------------------------------------------------$args');
                     readController.speak(args.first.toString());
                     // readController.speak('中国共产党（英文名：the Communist Party of China，简写CPC），'
                     //     '创建于1921年7月23日，1921年中国共产党成立后，确立了新民主主义革命的正确道路，让灾难深重的中'
                     //     '国人民看到了新的希望、有了新的依靠。我们党探索出农村包围城市、武装夺取政权的正确革命道路，“唤起工'
                     //     '农千百万”“夺过鞭子揍敌人”，经过土地革命战争、抗日战争、解放战争，推翻了压在中国人民头上的帝国主义、'
                     //     '封建主义、官僚资本主义“三座大山”，建立了人民当家作主的中华人民共和国，彻底结束了近代以来中国内忧外患、积贫积弱的悲惨境地，开启了中华民族发展进步的新纪元'
                     // );
                   });

                   // 监听讨论回调
                   controller.addJavaScriptHandler(handlerName: 'discussCallBack', callback: (args){
                     Console.log('监听讨论回调------------------------------------------------$args');
                     readController.setShowChat(true);
                     readController.setChatType(0);
                     readController.titleInput.text = args.first.toString();
                   });

                   controller.addJavaScriptHandler(handlerName: 'answerResultCallBack', callback: (args){
                     Console.log('监听答题回调------------------------------------------------$args');

                     String chapterId = args.first[0].toString();
                     String position = args.first[1].toString();
                     String type = args.first[2].toString();
                     String url = '';
                     // 未答题
                     if(type == '0'){
                       url = kAnswer;
                     }
                     else {
                       url = kAnswerResult;
                     }
                     Map<String,String> params = {
                       'chapter_id':chapterId,
                       'position':position,
                       'url':url,
                       'book_id':readController.bookId,
                       'token':UserStore.to.token
                     };
                     Console.log('监听答题回调---------------给页面传参---------------------------------$params');
                     context.pushNamed(Routes.answer,queryParameters: params);

                     // 跳转知识测评界面

                   });

                   // 监听 上一节 下一节
                   controller.addJavaScriptHandler(handlerName: 'readCallBack', callback: (args){
                     Console.log('监听 上一节 下一节------------------------------------------------$args');
                   });

                 },
               ),
               // AnimatedPositioned(
               //   duration: readController.controller.duration!,
               //   curve: Curves.easeInOut,
               //   top: readController.show ? 0 : -100, // 负值隐藏，0 显示
               //   left: 0,
               //   right: 0,
               //   height: 100,
               //   child: Container(
               //     color: Colors.limeAccent,
               //     alignment: Alignment.center,
               //     child: Text('top View'),
               //   ),
               // ),
               Positioned(
                 left: 0,
                 right: 0,
                 top: 0,
                 bottom: 69,
                 child: _showContent(readController,readController.toolModel)
               ),
               // AnimatedPositioned(
               //   duration: readController.controller.duration!,
               //   curve: Curves.easeInOut,
               //   bottom: readController.show ? 0 : -49 - MediaQuery.of(context).viewInsets.bottom, // 负值隐藏，0 显示
               //   left: 0,
               //   right: 0,
               //   height: 49,
               //   child: Container(
               //     color: Colors.limeAccent,
               //     alignment: Alignment.center,
               //     child: _createToolBar(readController)
               //   ),
               // ),
               /// 底部工具栏布局
               Visibility(
                 visible: readController.show,
                 child:Positioned(
                   left: 0,
                   right: 0,
                   bottom: 0,
                   child: SafeArea(
                     child: Container(
                       height: 69,
                       color: Colors.limeAccent,
                       alignment: Alignment.center,
                       child: _createToolBar(readController)
                     ),
                   ),
                 )
               ),
               /// 悬浮按钮点击发起话题布局
               Visibility(
                 visible: readController.showChat,
                 child: Positioned(
                   left: 0,
                   right: 0,
                   top: 0,
                   bottom:0,
                   child: GestureDetector(
                     onTap: (){
                       readController.setShowChat(false);
                       readController.clearAllDiscussInput();

                     },
                     child: Container(
                       color: const Color(0xFF000000).withOpacity(0.5),
                       child: SingleChildScrollView(
                         reverse: true,
                         child: Container(
                           color: Colors.white,
                           padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
                           // alignment:Alignment.bottomCenter,
                           child: GestureDetector(
                             behavior: HitTestBehavior.opaque,
                             onTap: (){},
                             child: ReadInputDiscuss(controller: readController,)
                           )
                         ),
                       ),
                     ),
                   )
                 ),
               ),
             ],
           ),
         ),
        ),
      ),
    );

  }

  /// 目录 笔记 讨论 工具栏
  Widget _createToolBar(ReadController controller){
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: controller.tools.map((model){
        return Expanded(
          child: GestureDetector(
            onTap: (){
              controller.chooseTool(model);
            },
            child: Container(
              color: Colors.white,
              padding: EdgeInsets.only(bottom: 15.w),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.max,
                children: [
                  SizedBox(
                    width: 25,
                    height: 25,
                    child: Image.asset(model.selected?model.activeIcon:model.icon,fit: BoxFit.cover,)
                  ),
                  SizedBox(height: 2.5.w,),
                  model.selected?Text(model.name,style: TextStyle(fontSize: 12.w,height: 1.4,fontWeight: Fonts.boldSemi,color: AppTheme.primary),)
                      :Text(model.name,style: TextStyle(fontSize: 12.w,height: 1.4,fontWeight: Fonts.medium,color: Colours.c6))
                ],
              ),
            ),
          ),
        );
      }).toList()
    );
  }


  Widget detail(ReadController controller,ToolModel model){
    if(model.tag == 0){
      return ReadCategoryPage(controller: controller,
        // 点 x 事件
        onTap: (){
          controller.chooseTool(model);
        },
        // 点 搜索全部 列表 某一项 事件
        onTapSearchItem: (){
          controller.chooseTool(model);
          // TODO:重新加载阅读界面 参数：chapter_id  text
          Console.log('-----------目录点击搜索条目---------------------');
        },
        onTapChapter: (ChapterModel chapterModel){
          Console.log('-----------选择的章节-------------${chapterModel.name}--------');
          // 配置选择的章节
          controller.selectChapter(chapterModel);
          // 取消选中 tool
          controller.chooseTool(model);
          // 选择了新的章节 刷新 webview
          controller.webViewController.reload();
        },
      );
    }
    else if(model.tag == 1){
      return ReadNotePage(
        // 点 x 事件
        onTap: (){
          controller.chooseTool(model);
        },
        // 点 搜索全部 列表 某一项 事件
        onTapSearchItem: (){
          controller.chooseTool(model);
          // TODO:重新加载阅读界面 参数：chapter_id  text
          Console.log('-----------笔记点击搜索条目---------------------');
        },
        bookDetailModel: controller.bookDetailModel,
        chapterId: controller.chapterId,
      );
    }
    else if(model.tag == 2){
      return ReadDiscussPage(
        // 点 x 事件
        onTap: (){
          controller.chooseTool(model);
        },
        // 点 搜索全部 列表 某一项 事件
        onTapSearchItem: (){
          controller.chooseTool(model);
          // TODO:重新加载阅读界面 参数：chapter_id  text
          Console.log('-----------讨论点击搜索条目---------------------');
        },
        bookDetailModel: controller.bookDetailModel,
        chapterId:controller.chapterId,
      );
    }
    return const SizedBox();
  }
  /// 目录、评论、笔记 背景
  Widget _showContent(ReadController controller,ToolModel model) {
    Console.log('++++++++++++++++++++++++${model.tag}');
    if (controller.show){
      if(model.selected){
        return Container(
          color: const Color(0xFF000000).withOpacity(0.5),
          padding: EdgeInsets.only(top: MediaQuery.of(context).size.height * 0.2),
          child: ClipRRect(
            borderRadius: BorderRadius.only(topRight: Radius.circular(8.w),topLeft: Radius.circular(8.w)),
            child: Container(
              color: Colors.white,
              child: detail(controller, model)
            ),
          ),
          // child: ReadCategoryPage(),
        );
      }
      else{
        return const SizedBox();
      }
    }
    return const SizedBox();
  }


}


/// 定制 悬浮按钮位置
class MyFloatingActionButtonLocation extends FloatingActionButtonLocation {
  @override
  Offset getOffset(ScaffoldPrelayoutGeometry scaffoldGeometry) {
    // You can customize the position of the FloatingActionButton here
    return Offset(scaffoldGeometry.scaffoldSize.width - 15.0.w - 45.w, scaffoldGeometry.scaffoldSize.height - 118.w-49.w);
  }

  @override
  String toString() => 'MyFloatingActionButtonLocation';
}



