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 GetBuilder<ReadController>(
      init: ReadController(bookId: widget.bookId, chapterId: widget.chapterId,chapterName: widget.chapterName,bookDetailModel: widget.bookDetailModel),
      builder: (readController) => Scaffold(
        appBar: CustomAppBar(
          title: Text(readController.chapterName),
          centerTitle: false,
          actions: [
            GestureDetector(
              onTap: () {
                readController.getBookDown();
              },
              child:  Text(
                '离线阅读',
                style: TextStyle(
                    fontSize: 14.w, color: Colours.c3),
              ))
          ],
        ),
        resizeToAvoidBottomInset: false,
        floatingActionButton: readController.show&& !readController.toolModel.selected?GestureDetector(
          onTap: (){
            readController.setShowChat(true);
            readController.noteTitle = '你好你问你你等您第五年对哦in我ID呢哦win地哦为内地那打卡你打困哪';
            readController.setChatType(1);
          },
          child: Image.asset('assets/images/chat.png'),
        ):null,
        // floatingActionButtonAnimator: const NoAnimationFabAnimator(),
        floatingActionButtonLocation:MyFloatingActionButtonLocation(),
       body: Container(
         color: Colors.white,
         child: Stack(
           children: [
             // Container(
             //   height: 40,
             //   width: double.infinity,
             //   color: Colors.lightBlue,
             // ),
             InAppWebView(
               initialUrlRequest: URLRequest(
                 url: Uri.parse('http://150.158.138.40:9200/read.html'),
               ),
               contextMenu: ContextMenu(
                 options: ContextMenuOptions(hideDefaultSystemContextMenuItems: true),
               ),
               onWebViewCreated: (InAppWebViewController controller){
                 readController.webViewController = controller;
               },
               onLoadStop: (controller, url) {
                 // flutter 主动给 js 传参数
                 Map<String, dynamic> param = {
                   'book_id': readController.bookId,
                   'chapter_id': readController.chapterId,
                   'token':UserStore.to.token
                 };
                 controller.evaluateJavascript(source: 'callbackInFlutterComponent("$param");');

                 // 添加单击事件
                 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){
                 });

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

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

               },
             ),
             // 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: 49,
               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: 49,
                     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,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.max,
                children: [
                  SizedBox(
                    width: 17,
                    height: 17,
                    child: Image.asset(model.selected?model.activeIcon:model.icon)
                  ),
                  // SizedBox(height: 2.5.w,),
                  model.selected?Text(model.name,style: TextStyle(fontSize: 10.w,height: 1.4,fontWeight: Fonts.medium,color: AppTheme.primary),)
                      :Text(model.name,style: TextStyle(fontSize: 10.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,
        onTap: (){
          controller.chooseTool(model);
        },
        onTapChapter: (ChapterModel chapterModel){
          print('-----------选择的章节-------------${chapterModel.name}--------');
          // 配置选择的章节
          controller.selectChapter(chapterModel);
          // 取消选中 tool
          controller.chooseTool(model);
          // 选择了新的章节 刷新 webview
          controller.webViewController.reload();
        },
      );
    }
    else if(model.tag == 1){
      return ReadNotePage(onTap: (){
        controller.chooseTool(model);
      },bookDetailModel: controller.bookDetailModel,chapterId: controller.chapterId,);
    }
    else if(model.tag == 2){
      return ReadDiscussPage(onTap: (){
        controller.chooseTool(model);
      },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';
}



