import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:sport/bean/comment.dart';
import 'package:sport/bean/notice.dart';
import 'package:sport/bean/post.dart';
import 'package:sport/bean/post_user.dart';
import 'package:sport/provider/lib/provider_widget.dart';
import 'package:sport/provider/lib/view_state_lifecycle.dart';
import 'package:sport/provider/message_detail_model.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/services/api/resp.dart';
import 'package:sport/utils/DateFormat.dart';
import 'package:sport/utils/toast.dart';
import 'package:sport/widgets/appbar.dart';
import 'package:sport/widgets/dialog/comment_dialog.dart';
import 'package:sport/widgets/dialog/request_dialog.dart';
import 'package:sport/widgets/error.dart';
import 'package:sport/widgets/image.dart';
import 'package:sport/widgets/loading.dart';
import 'package:sport/widgets/misc.dart';
import 'package:sport/widgets/space.dart';

class MessageDetailPage extends StatefulWidget {
  final String type;

  MessageDetailPage(this.type);

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

class _PageState extends ViewStateLifecycle<MessageDetailPage, MessageDetailModel> {
  String _title;

  @override
  MessageDetailModel createModel() => MessageDetailModel(widget.type);

  @override
  void initState() {
    super.initState();
    if (widget.type == "comment") {
      _title = "回复我的";
    } else if (widget.type == "like") {
      _title = "点赞我的";
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        body: ProviderWidget<MessageDetailModel>(
          model: model,
          onModelReady: (model) => model.initData(),
          builder: (_, model, __) {
            return EasyRefresh.custom(
              controller: model.refreshController,
              enableControlFinishRefresh: true,
              enableControlFinishLoad: true,
              onRefresh: () => model.refresh(),
              onLoad: model.isIdle ? () => model.loadMore() : null,
              header: buildClassicalHeader(
                extent: 100.0 + MediaQuery.of(context).padding.top,
                triggerDistance: 120.0 + MediaQuery.of(context).padding.top,
              ),
              footer: buildClassicalFooter(),
              slivers: <Widget>[
                buildSliverAppBar(context, _title),
                if (model.isBusy)
                  SliverToBoxAdapter(
                    child: RequestLoadingWidget(),
                  ),
                if (model.isIdle)
                  SliverList(
                    delegate: SliverChildBuilderDelegate(
                      (context, index) {
                        if (index.isOdd) {
                          return Divider();
                        }
                        return _buildDetailWidget(context, model.list[index ~/ 2]);
                      },
                      childCount: model.list.length * 2 - 1,
                    ),
                  ),
                if (model.isEmpty)
                  SliverFillRemaining(
                    child: Center(
                      child: RequestErrorWidget(
                        // ()=>model.readAll(),
                        // action: widget.type == "comment" ? "查看所有回复" : "查看所有点赞",
                        null,
                        msg: widget.type == "comment" ? "暂无回复~" : "暂无点赞~",
                        assets: RequestErrorWidget.ASSETS_NO_COMMENT,
                      ),
                    ),
                  )
              ],
            );
          },
        ));
  }

  Widget _buildDetailWidget(BuildContext context, Notice item) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 6.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          if (item.fromUserInfo != null)
            GestureDetector(
              onTap: () => NavigatorUtil.goSocialUserDetail(context, item.fromUserInfo),
              child: Row(
                children: <Widget>[
                  CircleAvatar(backgroundImage: userAvatarProvider(item.fromUserInfo.avatar), radius: 18),
                  Space(
                    width: 8,
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        item.fromUserInfo.name,
                        style: Theme.of(context).textTheme.subtitle1.copyWith(fontWeight: FontWeight.w600),
                      ),Space(
                        height: 4,
                      ),
                      Text(DateFormat.formatTime(item.createTime), style: Theme.of(context).textTheme.bodyText1)
                    ],
                  )
                ],
              ),
            ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 12.0),
            child: widget.type == "like"
                ? Row(
                    children: <Widget>[
                      Image.asset("lib/assets/img/bbs_icon_like_complete.png"),
                      SizedBox(
                        width: 8,
                      ),
                      Text(
                        "赞了我的${item.commentDetail == null ? '帖子' : '评论'}",
                        style: Theme.of(context).textTheme.subtitle1.copyWith(fontSize: 16),
                      )
                    ],
                  )
                : RichText(
                    maxLines: 3,
                    text: TextSpan(children: <InlineSpan>[
                      TextSpan(text: '回复：', style: TextStyle(color: Theme.of(context).accentColor, fontSize: 16)),
                      TextSpan(text: item.content, style: Theme.of(context).textTheme.subtitle1.copyWith(fontSize: 16)),
                    ]),
                  ),
          ),
          item.subjectDetail == null
              ? Container()
              : item.commentDetail == null ? _buildPostWidget(item.subjectDetail) : _buildCommentWidget(item.commentDetail, item.subjectDetail)
        ],
      ),
    );
  }

  Widget _buildCommentWidget(Comment item, Post post) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        Comment current = Comment.fromJson(item.toJson());
        current.socialInfo = PostUser(id: item.userId, name: item.userName, avatar: item.userAvatar);
        showCommentList(context, current);
      },
      child: Container(
        padding: EdgeInsets.all(12.0),
        decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(10)), color: Color(0xfff1f1f1)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            RichText(
              maxLines: 3,
              text: TextSpan(children: <InlineSpan>[
                TextSpan(text: '我的评论：', style: TextStyle(color: Theme.of(context).accentColor)),
                if (item.toUserName != null && item.toUserName.isNotEmpty)
                  TextSpan(
                    text: '@${item.toUserName} ',
                    style: Theme.of(context).textTheme.subtitle1.copyWith(fontSize: 16, color: Theme.of(context).accentColor),
                  ),
                TextSpan(text: item.content, style: TextStyle(color: Color(0xff666666))),
              ]),
            ),
            if (post != null)
              Container(
                  margin: EdgeInsets.symmetric(vertical: 12),
                  padding: const EdgeInsets.symmetric(vertical: 7.0, horizontal: 8.0),
                  decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(10)), color: Colors.white),
                  child: _postWidget(post)),
          ],
        ),
      ),
    );
  }

  Widget _buildPostWidget(Post post) {
    return Container(
        padding: const EdgeInsets.symmetric(vertical: 7.0, horizontal: 8.0),
        decoration: new BoxDecoration(
          color: Color(0xfff1f1f1), // 底色
          borderRadius: new BorderRadius.all(Radius.circular(10.0)),
        ),
        child: _postWidget(post));
  }

  _postWidget(Post post) {
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () async {
          Post netPost = await request(context, () async {
            RespData<Post> data = await model.api.getPostDetail(post.id).catchError((onError) {});
            if(data.code ==0){
              return data.data;
            }else {
              ToastUtil.show(data.msg);
              return null;
            }
          });
          if (netPost != null) NavigatorUtil.goSocialPostDetail(context, netPost);
        },
        child: Row(
          children: <Widget>[
            if (post.images != null && post.images.isNotEmpty)
              ClipRRect(
                child: CachedNetworkImage(
                  imageUrl: post.images[0].src,
                  fit: BoxFit.cover,
                  width: 50,
                  height: 50,
                ),
                // 也可控件一边圆角大小
                borderRadius: new BorderRadius.all(Radius.circular(6.0)),
              ),
            Expanded(
              child: Container(
                margin: const EdgeInsets.all(5.0),
                child: Text(post.content, maxLines: 1, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.subtitle1),
              ),
            )
          ],
        ));
  }
}
