import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sport/bean/comment.dart';
import 'package:sport/pages/social/notification.dart';
import 'package:sport/services/api/inject_api.dart';
import 'package:sport/services/userid.dart';
import 'package:sport/utils/DateFormat.dart';
import 'package:sport/utils/toast.dart';
import 'package:sport/widgets/dialog/alert_dialog.dart';
import 'package:sport/widgets/dialog/comment_dialog.dart';
import 'package:sport/widgets/dialog/modal_bottom_action.dart';
import 'package:sport/widgets/dialog/request_dialog.dart';
import 'package:sport/widgets/image.dart';
import 'package:sport/widgets/misc.dart';
import 'package:sport/widgets/space.dart';

class PostCommentWidget extends StatefulWidget {
  final Comment comment;
  final int avatarWidth;

  PostCommentWidget(this.comment, {this.avatarWidth = 30});

  @override
  State<StatefulWidget> createState() => _PostCommentState();
}

class _PostCommentState extends State<PostCommentWidget> with InjectApi, UserId {
  var _padding = Space(
    width: 4,
  );

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

  @override
  Widget build(BuildContext context) {
    Comment item = widget.comment;
    return Column(
      children: <Widget>[
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                buildSocialUserWidget(context, item?.socialInfo, item.createTime, widget.avatarWidth),
                Padding(
                  padding: const EdgeInsets.only(right: 12.0),
                  child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () async {
                      await (item.isLiked ?? false ? api.postForumUnLike(item.id, "comment_id") : api.postForumLike(item.id, "comment_id"));
                      setState(() {
                        item.toggleLike();
                      });
                    },
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: <Widget>[
                        Image.asset("lib/assets/img/bbslist_icon_like${item.isLiked ?? false ? 'd' : ''}.png"),
                        _padding,
                        Text(item.likeCount == 0 ? "" : "${item.likeCount}", style: Theme.of(context).textTheme.bodyText1),
                      ],
                    ),
                  ),
                ),
              ],
            ),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                CommentInputNotification(item).dispatch(context);
              },
              onLongPress: () async {
                await showActionDialog(context, {
                  if (item.userId != selfId)
                    "举报评论": () {
                      request(context, () async {
                        await api.postForumReport(commentId: item.id).catchError((onError) {});
                        ToastUtil.show("举报成功");
                      });
                    },
                  if (item.userId != selfId)
                    "屏蔽此条": () {
                      request(context, () async {
                        await api.postForumBlockObject(item.id, "comment").catchError((onError) {});
                        ToastUtil.show("屏蔽成功");
                        CommentNotification(item, CommentNotification.TYPE_DEL).dispatch(context);
                      });
                    },
                  if (item.userId == selfId)
                    "删除此条": () async {
                      if (await showDialog(
                            context: context,
                            builder: (context) => CustomAlertDialog(title: '确定删除此条？', ok: () => Navigator.of(context).pop(true)),
                          ) ==
                          true) {
                        request(context, () async {
                          await api.postDelComment(item.id);
                          ToastUtil.show("删除成功");
                          CommentNotification(item, CommentNotification.TYPE_DEL).dispatch(context);
                        });
                      }
                    },
                  "复制文字": () {
                    Clipboard.setData(ClipboardData(text: item.content));
                    ToastUtil.show("已复制到粘贴板");
                  }
                });
              },
              child: Padding(
                padding: EdgeInsets.fromLTRB(widget.avatarWidth + 8.0 + 12.0, 6.0, 12.0, 20.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Padding(
                        padding: const EdgeInsets.only(bottom: 8.0),
                        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
                          item.isExpansion ?? false == false
                              ? RichText(
                                  maxLines: 5,
                                  text: TextSpan(style: Theme.of(context).textTheme.subtitle1.copyWith(fontSize: 15.0), children: <InlineSpan>[
                                    if (item.toUserName != null && item.toUserName.isNotEmpty)
                                      TextSpan(
                                        text: '@${item.toUserName} ',
                                        style: Theme.of(context).textTheme.subtitle1.copyWith(color: Theme.of(context).accentColor),
                                      ),
                                    TextSpan(text: item.content),
                                  ]),
                                )
                              : RichText(
                                  text: TextSpan(style: Theme.of(context).textTheme.subtitle1.copyWith(fontSize: 15.0), children: <InlineSpan>[
                                    if (item.toUserName != null && item.toUserName.isNotEmpty)
                                      TextSpan(
                                        text: '@${item.toUserName} ',
                                        style: Theme.of(context).textTheme.subtitle1.copyWith(color: Theme.of(context).accentColor),
                                      ),
                                    TextSpan(text: item.content),
                                  ]),
                                ),
                          if (isExpansion(item.content))
                            GestureDetector(
                                onTap: () {
                                  item.isExpansion = !(item.isExpansion ?? true);
                                  setState(() {});
                                },
                                child: Padding(
                                  padding: const EdgeInsets.only(top: 5.0),
                                  child: Row(
                                    children: <Widget>[
                                      Text(
                                        item.isExpansion ?? false == false ? "全部" : "收起",
                                        style: Theme.of(context).textTheme.bodyText1,
                                        strutStyle: fixedLine,
                                      ),
                                      SizedBox(
                                        width: 4,
                                      ),
                                      item.isExpansion ?? false == false ? arrowBottom() : arrowTop()
                                    ],
                                  ),
                                )),
                        ])),
                    Row(
                      children: <Widget>[
                        Text(DateFormat.formatTime(item.createTime), style: Theme.of(context).textTheme.bodyText1, strutStyle: fixedLine),
                        dot,
                        InkWell(
                          onTap: () {
                            _showCommentList(context, item);
                          },
                          child: Text("${item.commentCount > 0 ? "${item.commentCount}条" : ""}回复",
                              style: Theme.of(context).textTheme.subtitle1.copyWith(fontSize: 12.0), strutStyle: fixedLine),
                        )
                      ],
                    )
                  ],
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  bool isExpansion(String text) {
    TextPainter _textPainter = TextPainter(maxLines: 5, text: TextSpan(text: text, style: TextStyle(fontSize: 16.0)), textDirection: TextDirection.ltr)
      ..layout(maxWidth: MediaQuery.of(context).size.width - 24);
    if (_textPainter.didExceedMaxLines) {
      return true;
    } else {
      return false;
    }
  }

  void _showCommentList(BuildContext context, Comment currentItem, {bool comment = false}) async {
    await showCommentList(context, currentItem, comment: comment);
    setState(() {});
  }
}
