import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:huixiang/retrofit/data/activity.dart';
import 'package:huixiang/retrofit/data/article.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/member_comment_list.dart';
import 'package:huixiang/retrofit/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/view_widget/comment_menu.dart';
import 'package:huixiang/view_widget/custom_image.dart';
import 'package:huixiang/view_widget/login_tips_dialog.dart';
import 'package:like_button/like_button.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CommentList extends StatefulWidget {

  final bool isKeyBoardShow;
  final Function reply;
  final Function delCommentTips;
  final double fontSize;
  final String relationalId;
  final int relationalType;
  final int like;
  final Function requestApiFinish;

  CommentList(Key key, this.like, this.relationalId,this.relationalType,
      this.isKeyBoardShow, this.reply, this.delCommentTips, this.fontSize,{this.requestApiFinish})
      : super(key: key);

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

class CommentListState extends State<CommentList> {
  int commentTotal = 0;
  List<MemberCommentList> memberList = [];
  ApiService apiService;

  //评论点赞
  queryCommentLike(String id) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String token = sharedPreferences.getString("token");
    if (token == null || token == "") {
      LoginTipsDialog().show(context);
      return;
    }
    BaseData baseData = await apiService.commentLike(id).catchError((error) {});
    if (baseData != null && baseData.isSuccess) {
      memberList.forEach((element) {
        if (element.id == id) {
          if (element.liked) {
            element.likes -= 1;
            element.liked = false;
          } else {
            element.likes += 1;
            element.liked = true;

          }
        }
      });
    }
  }

  @override
  void initState() {
    super.initState();
    queryMemberCommentList();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          decoration: BoxDecoration(
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withAlpha(12),
                offset: Offset(0, 2),
                blurRadius: 14,
                spreadRadius: 0,
              ),
            ],
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                padding: EdgeInsets.all(16),
                child: Row(
                  children: [
                    Text(
                      S.of(context).pinglun_(commentTotal.toString()),
                      style: TextStyle(
                        fontSize: widget.fontSize + 4,
                        fontWeight: FontWeight.bold,
                        color: Color(0xff1A1A1A),
                      ),
                    ),
                    SizedBox(
                      width: 16.w,
                    ),
                    Text(
                      S.of(context).xihuan_("${widget.like ?? "0"}"),
                      style: TextStyle(
                        fontSize: widget.fontSize + 4,
                        fontWeight: FontWeight.bold,
                        color: Color(0xff1A1A1A),
                      ),
                    ),
                  ],
                ),
              ),
              if (memberList != null && memberList.length > 0)
                ListView.builder(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  itemCount: memberList != null ? memberList.length : 0,
                  scrollDirection: Axis.vertical,
                  itemBuilder: (context, position) {
                    return Material(
                      color: Colors.white,
                      child: InkWell(
                        onTap: () {
                          showPressMenu(memberList[position].createUser,
                              memberList[position]);
                        },
                        child: commentItem(memberList[position]),
                      ),
                    );
                  },
                ),
              if (memberList != null && memberList.length > 0)
                Container(
                  decoration: BoxDecoration(
                    color: Color(0xFFF2F2F2),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withAlpha(12),
                        offset: Offset(0, 2),
                        blurRadius: 14,
                        spreadRadius: 0,
                      ),
                    ],
                  ),
                  alignment: Alignment.topCenter,
                  padding: EdgeInsets.only(top: 22.h, bottom: 22.h),
                  child: Text(
                    S.of(context).yixiansquanbupinglun,
                    style: TextStyle(
                      fontSize: widget.fontSize + 2,
                      color: Color(0xff353535),
                    ),
                  ),
                ),
              // if (memberList == null || memberList.length == 0)
              //   Container(
              //     width: double.infinity,
              //     height: MediaQuery.of(context).size.height - kToolbarHeight
              //         - MediaQuery.of(context).padding.top - 160.h,
              //     alignment: Alignment.topCenter,
              //     color: Color(0xFFF2F2F2),
              //     padding: EdgeInsets.only(top: 22.h),
              //     child: Text(
              //       S.of(context).zanwupinglun,
              //       style: TextStyle(
              //         fontSize: widget.fontSize + 2,
              //         fontWeight: FontWeight.bold,
              //         color: Color(0xFFA0A0A0),
              //       ),
              //     ),
              //   ),
            ],
          ),
        ),
      ],
    );
  }

  double commentHeight = 60.h;

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

  //评论列表
  queryMemberCommentList() async {
    if(widget?.relationalId == null || widget.relationalId.isEmpty)
      return;
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    if (apiService == null)
      apiService = ApiService(
        Dio(),
        context: context,
        token: sharedPreferences.getString("token"),
        showLoading: false,
      );
    BaseData<PageInfo<MemberCommentList>> baseData =
        await apiService.memberCommentList({
      "pageNum": 1,
      "pageSize": 100,
      "relationalId": widget.relationalId,
      "relationalType": widget.relationalType,
    }).catchError((error) {});
    if (baseData != null && baseData.isSuccess) {
      setState(() {
        memberList.clear();
        commentTotal = baseData.data.size;
        widget.requestApiFinish(commentTotal);
        memberList.addAll(baseData.data.list);
        contentHeight();
        setState(() {});
      });
    }
  }

  showPressMenu(String userId, memberComment) {
    if (widget.isKeyBoardShow) {
      FocusScope.of(context).requestFocus(FocusNode());
      return;
    }
    SharedPreferences.getInstance().then((value) {
      SmartDialog.show(
        widget: CommentMenu(
          (type) {
            SmartDialog.dismiss();
            if (type == "huifu") {
              widget.reply(memberComment);
            } else if (type == "shanchu") {
              widget.delCommentTips(memberComment);
            }
          },
          isSelf: userId == value.getString("userId"),
        ),
        alignmentTemp: Alignment.bottomCenter,
        isUseAnimationTemp: true,
        animationDurationTemp: Duration(milliseconds: 300),
      );
    });
  }

  Widget commentItem(MemberCommentList memberList) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 8.w),
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                MImage(
                  memberList.userAvatarUrl ?? "",
                  fit: BoxFit.cover,
                  isCircle: true,
                  width: 40,
                  height: 40,
                  fadeSrc: "assets/image/default_user.webp",
                  errorSrc: "assets/image/default_user.webp",
                ),
                SizedBox(
                  width: 12.w,
                ),
                Expanded(
                  child: Container(
                    // height: 60.h,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text.rich(
                          TextSpan(
                            children: [
                              TextSpan(
                                text: memberList.username,
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: widget.fontSize + 2,
                                  color: Colors.black,
                                ),
                              ),
                            ],
                          ),
                          textDirection: TextDirection.ltr,
                        ),
                        SizedBox(
                          height: 3.h,
                        ),
                        Text(
                          memberList.createTime,
                          overflow: TextOverflow.ellipsis,
                          maxLines: 2,
                          style: TextStyle(
                            fontSize: widget.fontSize,
                            color: Color(0xff808080),
                          ),
                        ),
                      ],
                    ),
                  ),
                  flex: 1,
                ),
                Tooltip(
                  message: S.of(context).dianzanxihuan_(S.of(context).pinglun),
                  child: Container(
                    alignment: Alignment.topRight,
                    child: LikeButton(
                      padding: EdgeInsets.all(10),
                      circleSize: 16,
                      circleColor: CircleColor(
                        start: Color(0xff00ddff),
                        end: Color(0xff0099cc),
                      ),
                      bubblesColor: BubblesColor(
                        dotPrimaryColor: Color(0xff33b5e5),
                        dotSecondaryColor: Color(0xff0099cc),
                      ),
                      bubblesSize: 15,
                      likeBuilder: (bool isLiked) {
                        return isLiked
                            ? Image.asset(
                                "assets/image/icon_like.webp",
                                width: 16,
                                height: 16,
                              )
                            : Image.asset(
                                "assets/image/icon_like_h.webp",
                                width: 16,
                                height: 16,
                              );
                      },
                      isLiked: memberList.liked ?? false,
                      onTap: (isLiked) async {
                        await queryCommentLike(memberList.id);
                        return (memberList == null || memberList.liked == null)
                            ? false
                            : memberList.liked;
                      },
                      likeCount: memberList.likes,
                      countBuilder: (int count, bool isLiked, String text) {
                        return Text(
                          text,
                          style: TextStyle(
                            color: Color(0xFF1A1A1A),
                            fontSize: widget.fontSize,
                          ),
                        );
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            padding: EdgeInsets.only(
              left: 68.w,
              right: 16.w,
              top: 16.h,
              bottom: 16.h,
            ),
            child: Align(
              alignment: Alignment.centerLeft,
              child: Text(
                memberList.content,
                style: TextStyle(
                  fontSize: widget.fontSize + 2,
                  color: Color(0xff1A1A1A),
                ),
              ),
            ),
          ),
          SizedBox(
            height: 12.h,
          ),
          if (memberList.parentContent != null)
            Container(
              margin: EdgeInsets.only(left: 68.w, right: 16.w),
              decoration: BoxDecoration(
                color: Color(0xffF2F2F2),
                borderRadius: BorderRadius.circular(2.0),
              ),
              child: Padding(
                padding: EdgeInsets.only(left: 4.w, top: 4.h, bottom: 4.h),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "${memberList.parentUserName}:" ?? "",
                      style: TextStyle(
                        fontSize: widget.fontSize,
                        color: Color(0xff808080),
                      ),
                    ),
                    Expanded(
                      flex: 1,
                      child: Text(
                        memberList.parentContent ?? "",
                        style: TextStyle(
                          fontSize: widget.fontSize,
                          color: Color(0xff808080),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
        ],
      ),
    );
  }
}