part of web;

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

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

class _ReadPageState extends State<ReadPage> {

  @override
  void initState() {
    super.initState();
  }
  @override
  Widget build(BuildContext context) {

    print('+++++++++++++++++++++++${widget.bookId}');
    return GetBuilder<ReadController>(
      init: ReadController(bookId: widget.bookId, chapterId: widget.chapterId,chapterName: widget.chapterName),
      builder: (readController) => Scaffold(
        appBar: AppBar(
          title: Text(widget.chapterName),
          centerTitle: false,
        ),
        resizeToAvoidBottomInset: false,
        floatingActionButton: readController.show?GestureDetector(
          onTap: (){
            readController.setShowChat(true);
            // FocusScope.of(context).requestFocus(readController.commentFocusNode);
          },
          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://192.168.11.46:9200/read.html'),
               ),
               onWebViewCreated: (InAppWebViewController controller) {

               },
               contextMenu: ContextMenu(
                 options: ContextMenuOptions(hideDefaultSystemContextMenuItems: true),
               ),
               // onLoadStart: (InAppWebViewController controller, Uri? url) async {
               //
               // },
               // onConsoleMessage: (controller, consoleMessage) {
               //   print("Received message from WebView: ${consoleMessage.message}");
               // },
               onLoadStop: (controller, url) {

                 // flutter 主动给 js 传参数
                 Map<String, dynamic> param = {
                   'book_id': 110,
                   'chapter_id': 1,
                   '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){
                   print('----------------------noteCallBack--------------------------$args');
                 });

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

                 // 监听讨论回调
                 controller.addJavaScriptHandler(handlerName: 'discussCallBack', callback: (args){
                   print('----------------------discussCallBack--------------------------$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: 49 + MediaQuery.of(context).viewInsets.bottom,
               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.showChat,
               child: Positioned(
                 left: 0,
                 right: 0,
                 bottom:MediaQuery.of(context).viewInsets.bottom,
                 child: ReadInputDiscuss(controller: readController,)
               ),
             ),
           ],
         ),
       ),
      ),
    );

  }

  /// 目录 笔记 讨论 工具栏
  Widget _createToolBar(ReadController controller){
    return Container(
      child: 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 _showContent(ReadController controller,ToolModel model) {
    print('++++++++++++++++++++++++${model.tag}');
    if (controller.show){
      if (model.tag == 0){
        return model.selected? 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: ReadCategoryPage(controller: controller,onTap: (){
                controller.chooseTool(model);
              },),
            ),
          ),
          // child: ReadCategoryPage(),
        ):const SizedBox();
      }
      else if (model.tag == 1){
        return model.selected? Container(
          color: 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: ReadNotePage(onTap: (){
                controller.chooseTool(model);
              },),
            ),
          ),
          // child: ReadCategoryPage(),
        ):const SizedBox();
      }
      else if (model.tag == 2){
        return model.selected? Container(
          color: 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: ReadDiscussPage(onTap: (){
                controller.chooseTool(model);
              },),
            ),
          ),
          // child: ReadCategoryPage(),
        ):const SizedBox();
      }
    }
    return const SizedBox();
  }

  Widget _discussInput(ReadController controller){
    return Container(
        margin: EdgeInsets.symmetric(horizontal: 15.w),
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.symmetric(vertical: 10.w),
              child: Row(
                children: [
                  Text('话题',style: TextStyle(fontSize: 14.w,color: Colours.c3,height: 1.5,fontWeight: Fonts.medium),),
                  Gaps.hGaps5,
                  Expanded(
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(4),
                      child: TextField(
                        focusNode: controller.discussTitleFocusNode,
                        autofocus: true,
                        decoration: InputDecoration(
                          hintText: '请输入话题名称',
                          hintStyle:TextStyle(fontSize: 12.w,height: 1.5,color: Colours.c9,),
                          filled: true,
                          fillColor: Colours.cF8,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            ClipRRect(
              borderRadius: BorderRadius.circular(4.w),
              child: Container(
                color: Colours.cF8,
                constraints: BoxConstraints(
                  minHeight: 100.w
                ),
                child: Column(
                  children: [
                    TextField(
                      focusNode: controller.discussContentFocusNode,
                      maxLines: null,
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        enabledBorder: InputBorder.none,
                        focusedBorder: InputBorder.none,
                        hintText: '请输入内容',
                        hintStyle:TextStyle(fontSize: 12.w,height: 1.5,color: Colours.c9,),
                        filled: true,
                        fillColor: Colours.cF8,
                      ),
                    ),
                    Column(
                      children: [
                        MediaQuery.removePadding(
                          context: context,
                          removeTop: true,
                          child: GridView.builder(
                          // padding: const EdgeInsets.only(left: 13,top: 10),
                          physics: const NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 6,
                              crossAxisSpacing: 2.w,
                              mainAxisSpacing: 2.w,
                              childAspectRatio: 1
                          ),
                          itemBuilder: (BuildContext context, int index) {
                            return Container(
                              color: Colors.red,
                              child: Center(child: Text('图片')),
                            );
                          },
                          itemCount: 0,
                      ),
                        ),
                        Container(
                          color: Colors.red,
                          child: MediaQuery.removePadding(
                            context: context,
                            removeTop: true,
                            child: ListView.builder(
                              physics: const NeverScrollableScrollPhysics(),
                              shrinkWrap: true,
                              itemBuilder: (BuildContext context, int index){
                                return Container(
                                  height: 20.w,
                                  margin: EdgeInsets.only(right: 130.w),
                                  child: Container(
                                    margin: EdgeInsets.only(top: 5.w),
                                    padding: EdgeInsets.only(right:20.w,left: 10.w),
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(10.w),
                                      color: Colours.cF9,
                                    ),
                                    child: Row(
                                      // mainAxisSize: MainAxisSize.min,
                                      mainAxisAlignment:MainAxisAlignment.spaceBetween,
                                      children: [
                                        Image.asset('assets/images/audio.png'),
                                        Text('0:00/1:52',style: TextStyle(fontSize: 10.w,height: 1.4,color: Colours.c9),)
                                      ],
                                    ),
                                  ),
                                );
                              },
                              itemCount: 0,
                            ),
                          ),
                        )
                      ],
                    )
                  ],
                ),
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Row(
                  children: [
                    Image.asset('assets/images/read_add_img.png'),
                    Gaps.hGaps10,
                    Image.asset('assets/images/read_add_audio.png'),
                  ],
                ),
                GestureDetector(
                  onTap: (){},
                  child: Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(15.w),
                        color: AppTheme.primary,
                        gradient: LinearGradient(
                          colors: [const Color(0xFFD53676).withOpacity(0.9),AppTheme.primary] , // 不可点击时的颜色，透明度为0.7
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                        ),
                    ),
                    padding:  EdgeInsets.symmetric(horizontal:13.5.w,vertical: 4.w),
                    child:  Text('发表',style: TextStyle(fontSize: 14.w,fontWeight: Fonts.medium,color: Colors.white),),
                  ),
                )
              ],
            )
          ],
        )
    );
  }

}


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';
}


// class NoAnimationFabAnimator extends FloatingActionButtonAnimator {
//   // 通过构造函数参数提供动画
//   const NoAnimationFabAnimator();
//
//   @override
//   Animation<double> getRotationAnimation({required Animation<double> parent}) {
//     return AlwaysStoppedAnimation<double>(0);
//   }
//
//   @override
//   Animation<double> getScaleAnimation({required Animation<double> parent}) {
//     return AlwaysStoppedAnimation<double>(1);
//   }
//
//   @override
//   Offset getOffset({required Offset begin, required Offset end, required double progress}) {
//     return begin;
//   }
// }


