import 'dart:ui';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:huixiang/community/photo_view_gallery_screen.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/data/article.dart';
import 'package:huixiang/data/base_data.dart';
import 'package:huixiang/data/member_comment.dart';
import 'package:huixiang/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:huixiang/view_widget/round_button.dart';
import 'package:huixiang/view_widget/tips_dialog.dart';
import 'package:huixiang/web/web_view/comment_list.dart';
import 'package:huixiang/web/web_view/input_comment.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'community_view/class_details_video.dart';

class NewCommunityDetails extends StatefulWidget {
  final Map<String, dynamic>? arguments;

  NewCommunityDetails({this.arguments});

  @override
  State<StatefulWidget> createState() {
    return _NewCommunityDetails();
  }
}

class _NewCommunityDetails extends State<NewCommunityDetails> with WidgetsBindingObserver {
  ApiService? apiService;
  final GlobalKey commentKey = GlobalKey();
  final GlobalKey videoKey = GlobalKey();
  double height = 0;
  final ScrollController scrollController = ScrollController();
  bool isKeyBoardShow = false;
  double commentHeight = 60.h;
  var commentFocus = FocusNode();
  String parenId = "0";
  String hintText = S.current.liuxianinjingcaidepinglunba;
  final GlobalKey inputKey = GlobalKey();
  final TextEditingController commentTextController = TextEditingController();
  int commentTotal = 0;
  List<MemberComment> memberList = [];
  bool isShowImg = true;
  Article? article;
  String? commentsId;
  String? userId;
  bool emojiShowing =false;
  double keyboard = -1;
  bool needShowSmiley = false;
  bool needHideSmiley = false;

  @override
  void initState() {
    super.initState();
    commentsId = widget.arguments?["commentsId"];
    userId = widget.arguments?["userId"];
    WidgetsBinding.instance.addObserver(this);
    commentFocus.addListener(_focusNodeListener);
    queryDetails(commentsId);
  }

  ///详情接口
  queryDetails(id) async {
    SharedPreferences value = await SharedPreferences.getInstance();
    BaseData<Article>? baseData = await apiService?.informationInfo(id)
        .catchError((onError) {
      debugPrint(onError.toString());
    });
    if (baseData?.isSuccess ?? false) {
      setState(() {
        article = baseData!.data;
      });
    }
  }

  ///关注/取关会员
  _vipFollow(followId, isFollow) async {
    BaseData? baseData = await apiService?.follow(followId);
    if (baseData?.isSuccess ?? false) {
      SmartDialog.showToast(isFollow ? "关注成功" : "取关成功",
          alignment: Alignment.center);
      setState(() {});
    } else {
      // SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
    }
  }

  @override
  void didChangeMetrics() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted) return;
      if (MediaQuery.of(context).viewInsets.bottom == 0) {
        if (isKeyBoardShow) {
          FocusScope.of(context).requestFocus(FocusNode());
          if (mounted)
            if(!emojiShowing)
            setState(() {
              hintText = S.current.liuxianinjingcaidepinglunba;
              isKeyBoardShow = false;
            });
        }
      } else {
        if (mounted)
          setState(() {
            isKeyBoardShow = true;
          });
      }
    });
    if (needShowSmiley && window.viewInsets.bottom <= 0.1) {
      needShowSmiley = false;
      setState(() {
        emojiShowing = true;
      });
    }
    if(needHideSmiley && window.viewInsets.bottom > 0.1) {
      needHideSmiley = false;
      setState(() {
        emojiShowing = false;
      });
    }
  }

  void _focusNodeListener() {
    /*if (_focusNode.hasFocus || _focusNode.consumeKeyboardToken()){
			setState(() {
				smileyPadGone = true;
			});
		}*/
  }

  _onTextFieldTap() {
    if(emojiShowing) {
      needHideSmiley = true;
    }
  }

  _onSmileyTap() {
    if(!emojiShowing && commentFocus.hasFocus && isKeyBoardShow) {
      needShowSmiley = true;
      commentFocus.unfocus();
    } else {
      setState(() {
        emojiShowing = !emojiShowing;
        isKeyBoardShow = emojiShowing;
      });
    }
  }

  @override
  void dispose(){
    WidgetsBinding.instance.removeObserver(this);
    commentFocus.removeListener(_focusNodeListener);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double h = MediaQuery.of(context).viewInsets.bottom;
    if(h > 0 && keyboard <h) {
      setState(() {
        keyboard = h;
      });
    }
    return WillPopScope(
        onWillPop: () async {
          Navigator.of(context).pop(true);
      return false;
    },
    child:AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light,
        child: Material(child: Scaffold(
          appBar: MyAppBar(
            title: S.of(context).dongtaixiangqing,
            titleColor: Colors.black,
            titleSize: 18.sp,
            background: Colors.white,
            leading: true,
            leadingColor: Colors.black,
          ),
          body: Container(
            margin: EdgeInsets.only(top:2.h),
            child: Column(
              children: [
                Expanded(
                  child: SingleChildScrollView(
                    physics: BouncingScrollPhysics(),
                    child: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.all(16),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Container(
                                    height: 44,
                                    child: Row(
                                      children: [
                                        GestureDetector(
                                          onTap: () {
                                            Navigator.push(
                                                context,
                                                MaterialPageRoute(
                                                  builder: (context) => PhotoViewGalleryScreen(
                                                    images: [
                                                      (article?.authorHeadImg?.isEmpty ?? true)
                                                          ? "https://lmg.jj20.com/up/allimg/tx30/09041130358711081.jpg"
                                                          : article!.authorHeadImg
                                                    ], //传入图片list
                                                    index: 0, //传入当前点击的图片的index
                                                  ),
                                                ),
                                            );
                                          },
                                          child: MImage(
                                            (article?.authorHeadImg ?? ""),
                                            width: 44,
                                            height: 44,
                                            isCircle: true,
                                            fit: BoxFit.cover,
                                            errorSrc: "assets/image/default_1.webp",
                                            fadeSrc: "assets/image/default_1.webp",
                                          ),
                                        ),
                                        SizedBox(
                                          width: 8,
                                        ),
                                        Column(
                                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              article?.authorName ?? "",
                                              style: TextStyle(
                                                fontSize: 15.sp,
                                                fontWeight: MyFontWeight.semi_bold,
                                                color: Color(0xFF1A1A1A),
                                              ),
                                            ),
                                            Text(
                                              article?.createTime ?? "",
                                              style: TextStyle(
                                                fontSize: 13.sp,
                                                fontWeight: MyFontWeight.regular,
                                                color: Color(0xFF808080),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                  if (article?.author != userId)
                                  GestureDetector(
                                      onTap: () {
                                        setState(() {
                                            article?.liked =
                                            !(article?.liked ?? false);
                                            _vipFollow(article?.author,
                                                article?.liked ?? false);
                                        });
                                      },
                                      child:
                                      Container(
                                          width: 56.w,
                                          height: 25.h,
                                          alignment: Alignment.center,
                                          child: RoundButton(
                                            height: 25.h,
                                            backgroup: (article?.liked ?? false)
                                                ? Color(0xFFE6E6E6)
                                                : Color(0xFF32A060),
                                            textColor: (article?.liked ?? false)
                                                ? Color(0xFF808080)
                                                : Colors.white,
                                            text: (article?.liked ?? false)
                                                ? S.of(context).yiguanzhu
                                                : S.of(context).guanzhu,
                                            radius: 20,
                                            icons: Icon(
                                              (article?.liked ?? false)
                                                  ? Icons.check
                                                  : Icons.add,
                                              color: (article?.liked ?? false)
                                                  ? Color(0xFF808080)
                                                  : Colors.white,
                                              size: 15,
                                            ),
                                          ))
                                  ),
                                ],
                              ),
                              SizedBox(
                                height: 12.h,
                              ),
                              Text(
                                article?.mainTitle ?? "",
                                maxLines: 5,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                  color: Color(0xFF1A1A1A),
                                  fontWeight: MyFontWeight.regular,
                                  fontSize: 15.sp,
                                ),
                              ),
                              buildMedia(article?.content),
                            ],
                          ),
                        ),
                        CommentList(
                          commentKey,
                          article?.likes ?? 0,
                          commentsId,
                          4,
                          isKeyBoardShow,
                          _reply,
                          _delCommentTips,
                          12.sp,
                          requestApiFinish: (total){setState(() {
                            commentTotal = total;
                          });},
                        ),
                        if (memberList.length == 0)
                          Container(
                            width: double.infinity,
                            alignment: Alignment.topCenter,
                            margin: EdgeInsets.only(top: 40),
                            padding: EdgeInsets.all(22.h),
                            child: Text(
                              S.of(context)
                                  .zanwupinglun,
                              style: TextStyle(
                                fontSize: 12,
                                fontWeight: FontWeight.bold,
                                color: Color(0xFFA0A0A0),
                              ),
                            ),
                          ),
                      ],
                    ),
                  ),
                  flex: 1,
                ),
                /// 富文本评论的输入框
                InputComment(
                  inputKey,
                  hintText,
                  isKeyBoardShow,
                  keyboard,
                  emojiShowing,
                  commentFocus,
                  commentTextController,
                  _toComment,
                  _onSmileyTap,
                  _onTextFieldTap,
                  _queryMemberComment,
                  _queryInformationLikes,
                  isLike: article?.liked ?? false,
                ),
              ],
            ),
          ),
        ),)
    ));
  }

  ///动态内容
  Widget buildMedia(String? subjectInfo) {
    if (!(subjectInfo?.startsWith("{") ?? false)) {
      return Container();
    }
    var cnt = jsonDecode(subjectInfo!);
    Widget itemWidget = Container();
    if (cnt["type"] == "image" &&
        cnt["images"] != null &&
        cnt["images"].length > 0) {
      if (cnt["images"].length == 1) {
        itemWidget = Container(
          child: InkWell(
              onTap: () {
                // ImagePickers.previewImages(subjectInfo.images,0);
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => PhotoViewGalleryScreen(
                      images: cnt["images"], //传入图片list
                      index: 0, //传入当前点击的图片的index
                    ),
                  ),
                );
              },
              child: MImage(
                cnt["images"][0],
                radius: BorderRadius.circular(2),
                fit: BoxFit.contain,
                width: MediaQuery.of(context).size.width / 1.5,
                height: MediaQuery.of(context).size.width,
                errorSrc: "assets/image/default_2_1.webp",
                fadeSrc: "assets/image/default_2_1.webp",
              )),
        );
      } else {
        itemWidget = GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount:
            (cnt["images"].length == 2 || cnt["images"].length == 4)
                ? 2
                : 3,
            crossAxisSpacing: 12.w,
            mainAxisSpacing: 12.w,
            childAspectRatio: 1,
          ),
          padding: EdgeInsets.zero,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemBuilder: (context, position) {
            return Container(
              child: InkWell(
                onTap: () {
                  // ImagePickers.previewImages(subjectInfo.images, position);
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => PhotoViewGalleryScreen(
                        images: cnt["images"], //传入图片list
                        index: position, //传入当前点击的图片的index
                      ),
                    ),
                  );
                },
                child: MImage(
                  cnt["images"][position],
                  fit: BoxFit.cover,
                  aspectRatio: 1,
                  radius: BorderRadius.circular(1),
                  errorSrc: "assets/image/default_2_1.webp",
                  fadeSrc: "assets/image/default_2_1.webp",
                ),
              ),
            );
          },
          itemCount: cnt["images"].length,
        );
      }
    } else if (cnt["type"] == "video" &&
        cnt["video"] != null &&
        cnt["video"].isNotEmpty) {
      itemWidget = Container(
        child:ClassDetailsVideo(key:videoKey,exitFull: (){setState(() {});},
          coverImg: cnt["video"].toString().replaceAll(".mp4", "_poster.jpg"),isShowImg: this.isShowImg,
          changeShowImg: (isShowImg){setState(() {
            this.isShowImg = isShowImg;
          });},videoUrl: cnt["video"],
          heightFun: (height) {
            this.height =
                height +
                    MediaQuery
                        .of(context)
                        .padding
                        .top +
                    kToolbarHeight +
                    24;
            if (mounted) setState(() {});
          },)
      );
    }
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(
          height: 16.h,
        ),
        itemWidget,
      ],
    );
  }

  ///给文章/活动点赞
  _queryInformationLikes() async {
    BaseData? baseData = await apiService?.informationLikes("${commentsId}").catchError((onError) {});
    if (baseData?.isSuccess ?? false) {
      commentKey.currentState?.setState(() {});
      setState(() {
        int likes = article?.likes ?? 0;
        if (article?.liked ?? false)
          article?.likes = likes - 1;
        else
          article?.likes = likes + 1;
        article?.liked = !(article?.liked ?? false);
      });
    } else {
      SmartDialog.showToast("${baseData?.msg}", alignment: Alignment.center);
    }
  }

  ///动态发布评论
  _queryMemberComment(String content) async {
    BaseData? baseData = await apiService?.memberComment({
      "content": content,
      "parentId": parenId,
      "relationalId": commentsId,
      "relationalType":4
    }).catchError((error) {});
    if (baseData?.isSuccess ?? false) {
      CommentListState? state = commentKey.currentState as CommentListState?;
      state?.queryMemberCommentList();
      commentTextController.text = "";
      FocusScope.of(context).unfocus();
      _queryMemberCommentList();
    }
  }

  ///滑动到评论列表
  _toComment() {
    if (commentKey.currentContext == null) return;
    RenderBox? firstRenderBox = commentKey.currentContext!.findRenderObject() as RenderBox?;
    Offset? first = firstRenderBox?.localToGlobal(Offset.zero);
    scrollController.animateTo(
      (first?.dy ?? 0) +
          scrollController.offset -
          (kToolbarHeight + MediaQuery
              .of(context)
              .padding
              .top),
      duration: Duration(milliseconds: 300),
      curve: Curves.easeIn,
    );
  }

  contentHeight() {
    double contentHeight = MediaQuery
        .of(context)
        .size
        .height -
        kToolbarHeight -
        MediaQuery
            .of(context)
            .padding
            .top -
        160.h;
    if ((contentHeight - 60.h) > (128.h * memberList.length)) {
      commentHeight = contentHeight - (128.h * memberList.length);
    }
  }

  ///删除评论的提示
  _delCommentTips(memberComment) {
    SmartDialog.show(widget: Tips(() {
      delComment(memberComment);
    }));
  }

  ///删除评论
  delComment(memberComment) async {
    BaseData? baseData = await apiService?.delComment(memberComment.id);
    if (baseData?.isSuccess ?? false) {
      CommentListState? state = commentKey.currentState as CommentListState?;
      state?.queryMemberCommentList();
    }
  }

  ///评论 回复
  _reply(memberComment) {
    FocusScope.of(context).requestFocus(commentFocus);
    parenId = memberComment.id;
    hintText = S.of(context).huifu_("${memberComment.username}");
  }

  ///评论列表
  _queryMemberCommentList() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    BaseData<PageInfo<MemberComment>>? baseData = await apiService?.memberCommentList({
      "pageNum": 1,
      "pageSize": 100,
      "relationalId": commentsId,
      "relationalType":4,
    }).catchError((error) {});
    if (baseData?.isSuccess ?? false) {
      commentTotal = baseData?.data?.size;
      memberList = baseData?.data?.list ?? [];
      contentHeight();
      if (mounted) setState(() {});
    }
  }
}