import 'dart:async';
import 'dart:convert';

import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/material.dart' hide NestedScrollView;
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sport/bean/message.dart';
import 'package:sport/bean/notice.dart';
import 'package:sport/bean/post_user.dart';
import 'package:sport/bean/user_friend.dart';
import 'package:sport/bean/user_info.dart';
import 'package:sport/db/message_db.dart';
import 'package:sport/pages/social/chat_page.dart';
import 'package:sport/pages/social/message_notice_detail_page.dart';
import 'package:sport/pages/social/user_detail_page.dart';
import 'package:sport/pages/social/user_friend_page.dart';
import 'package:sport/provider/message_model.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/router/routes.dart';
import 'package:sport/services/api/inject_api.dart';
import 'package:sport/services/api/resp.dart';
import 'package:sport/services/userid.dart';
import 'package:sport/utils/DateFormat.dart';
import 'package:sport/utils/toast.dart';
import 'package:sport/widgets/appbar.dart';
import 'package:sport/widgets/dialog/alert_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/persistent_header.dart';
import 'package:sport/widgets/dialog/popupmenu.dart' as menu;
import 'package:sport/pages/social/message_list_subpage.dart';

class MessagePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _PageState();
}

class _PageState extends State<MessagePage>
    with TickerProviderStateMixin, InjectApi, UserId {
  TabController _controller;
  Future<List<Notice>> _future;

  final List<String> avatarList = [
    "https://wx3.sinaimg.cn/mw1024/a6bdcd78gy1gfna8yznv5j20m90m9tbz.jpg",
    "https://wx2.sinaimg.cn/mw1024/a6bdcd78gy1gfna8x3nbzj20m90m943a.jpg",
    "https://wx3.sinaimg.cn/mw1024/a6bdcd78gy1gfnaavrha3j20m90m9dkj.jpg",
    "https://wx4.sinaimg.cn/mw1024/a6bdcd78gy1gfna8znb76j20m90m978t.jpg",
    "https://wx4.sinaimg.cn/mw1024/a6bdcd78gy1gfna8wnwquj20lr0lradp.jpg",
    "https://wx4.sinaimg.cn/mw1024/a6bdcd78gy1gfna90vpgkj20lr0lrtby.jpg",
    "https://wx1.sinaimg.cn/mw1024/a6bdcd78gy1gfna8y4jb6j20m90m9tcj.jpg",
    "https://wx3.sinaimg.cn/mw1024/a6bdcd78gy1gfnaawemhtj20m90m9q7n.jpg",
    "https://wx4.sinaimg.cn/mw1024/a6bdcd78gy1gfnaaveqmwj20ls0lsn07.jpg",
    "https://wxt.sinaimg.cn/mw1024/a6bdcd78gy1gfnaat7uw5j20ls0lr0w0.jpg",
    "https://wx2.sinaimg.cn/mw1024/a6bdcd78gy1gfnaaubdhhj20m90m9786.jpg",
    "https://wx2.sinaimg.cn/mw1024/a6bdcd78gy1gfna8ylkkaj20m90m9aea.jpg",
    "https://wx1.sinaimg.cn/mw1024/a6bdcd78gy1gcj8j7qwapj20dx0dxdgv.jpg",
  ];
  @override
  void initState() {
    super.initState();
    _controller = TabController(length: 2, vsync: this);
    _future = _getNotice();
  }

  Future<List<Notice>> _getNotice() async {
    List<Notice> items = [];
    var resp = await api.getInformList().catchError((onError) {});
    items.addAll(resp?.pageResult?.results ?? []);
    resp = await api.getNoticeList(isMsg: "0", markread: null);
    items.addAll(resp?.pageResult?.results ?? []);
    return items;
  }

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

  @override
  Widget build(BuildContext context) {
    final double tabHeader = 50;
    final double statusBarHeight = MediaQuery.of(context).padding.top;
    final double pinnedHeaderHeight =
        //statusBar height
        statusBarHeight +
            //pinned SliverAppBar height in header
            kToolbarHeight +
            tabHeader;

    Widget _buildChat(UserFriend user, List<UserFriend> list) {
      Widget child = Row(
        children: <Widget>[
          CircleAvatar(
            backgroundImage: userAvatarProvider(user?.socialInfo?.avatar),
            radius: 22,
          ),
          SizedBox(
            width: 8,
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  "${user?.socialInfo?.name}",
                  style: Theme.of(context).textTheme.headline3,
                ),
                SizedBox(
                  height: 5,
                ),
                Text(
                  "${DateFormat.formatCreateAt(user?.updatedAt)}在线",
                  style: Theme.of(context).textTheme.bodyText1,
                ),
              ],
            ),
          ),
        ],
      );

      return Column(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(12.0),
            child: InkWell(
                onTap: () async {
                  await NavigatorUtil.goPage(
                      context,
                      (context) => UserDetailPage(
                          PostUser(
                              id: "${user?.socialInfo?.id}",
                              name: user?.socialInfo?.name,
                              avatar: user?.socialInfo?.avatar),
                          userFriends: list));
                  setState(() {});
                },
                child: child),
          ),
          Divider(
            height: 1,
          )
        ],
      );
    }

    return DefaultTabController(
      length: 3,
      child: Scaffold(
        backgroundColor: Colors.white,
        body: NestedScrollView(
            pinnedHeaderSliverHeightBuilder: () {
              return pinnedHeaderHeight;
            },
            innerScrollPositionKeyBuilder: () {
              TabController tabController = DefaultTabController.of(context);
              String index = 'Tab${tabController.index}';
              return Key(index);
            },
            headerSliverBuilder: (context, innerBoxIsScrolled) {
              return <Widget>[
                buildSliverAppBar(context, "社区消息",
                    innerBoxIsScrolled: innerBoxIsScrolled,
                  actions: [
                    IconButton(
                      icon: Image.asset("lib/assets/img/topbar_friendslist.png"),
                      onPressed: () {
                        NavigatorUtil.goPage(context, (context) => UserFriendPage());
                      },
                    ),
                  ]
                ),
                SliverPersistentHeader(
                  delegate: PersistentHeader(
                      min: tabHeader,
                      max: tabHeader,
                      child: Container(
                        color: Colors.white,
                        child: Column(
                          children: <Widget>[
                            Expanded(
                              child: Center(
                                child: Container(
                                  height: 30,
                                  child: TabBar(
                                    isScrollable: true,
                                    labelPadding:
                                        EdgeInsets.symmetric(horizontal: 32),
                                    indicatorWeight: 3,
                                    indicatorPadding:
                                        EdgeInsets.symmetric(horizontal: 6),
                                    tabs: <Widget>[
                                      Tab(
                                        text: '聊天',
                                      ),
                                      Tab(text: '消息'),
                                      Tab(text: '通知')
                                    ],
                                  ),
                                ),
                              ),
                            ),
                            Divider(
                              height: 1,
                              indent: 12.0,
                              endIndent: 12.0,
                            )
                          ],
                        ),
                      )),
                  pinned: true,
                ),
              ];
            },
            body: TabBarView(children: [
              NestedScrollViewInnerScrollPositionKeyWidget(
                  const Key('Tab0'), Container(child: MessageListSubPage())),
              NestedScrollViewInnerScrollPositionKeyWidget(
                  const Key('Tab0'),
                  ListView.separated(
                    padding: EdgeInsets.symmetric(horizontal: 12.0),
                    itemBuilder: (context, index) => index == 0
                        ? InkWell(
                            onTap: () => NavigatorUtil.go(context,
                                "${Routes.socialMessageDetail}?data=comment"),
                            child: Padding(
                              padding: const EdgeInsets.symmetric(vertical: 12.0),
                              child: Row(children: <Widget>[
                                Image.asset(
                                    "lib/assets/img/bbsmessage_icon_color_reply.png",width: 44.0,height: 44.0,),
                                SizedBox(
                                  width: 16.0,
                                ),
                                Expanded(
                                  child: Text(
                                    "回复我的",
                                    style: Theme.of(context)
                                        .textTheme
                                        .subtitle1
                                        .copyWith(fontSize: 16),
                                    strutStyle: fixedLine,
                                  ),
                                ),
                                FutureBuilder(
                                    future: api.getNoticeCount("comment", "0"),
                                    builder: (BuildContext context,
                                            AsyncSnapshot<RespData<int>>
                                                snapshot) =>
                                        snapshot.data == null
                                            ? Container()
                                            : snapshot.data.data == 0
                                                ? Container()
                                                : Container(
                                                    width: 20,
                                                    height: 20,
                                                    decoration: BoxDecoration(
                                                        shape: BoxShape.circle,
                                                        color: Theme.of(context)
                                                            .accentColor),
                                                    child: Center(
                                                      child: Text(
                                                        snapshot.data.data > 99
                                                            ? "99+"
                                                            : "${snapshot.data.data}",
                                                        maxLines: 1,
                                                        style: TextStyle(
                                                            fontSize: 10,
                                                            color:
                                                                Colors.white),
                                                      ),
                                                    ),
                                                  )),
                                SizedBox(
                                  width: 8.0,
                                ),
                                arrowRight()
                              ]),
                            ))
                        : index == 1
                            ? InkWell(
                                onTap: () => NavigatorUtil.go(context,
                                    "${Routes.socialMessageDetail}?data=like"),
                                child: Padding(
                                  padding: const EdgeInsets.symmetric(vertical: 12.0),
                                  child: Row(children: <Widget>[
                                    Image.asset(
                                        "lib/assets/img/bbsmessage_icon_color_like.png",width: 44.0,height: 44.0,),
                                    SizedBox(
                                      width: 16.0,
                                    ),
                                    Expanded(
                                      child: Text(
                                        "点赞",
                                        style: Theme.of(context)
                                            .textTheme
                                            .subtitle1
                                            .copyWith(fontSize: 16),
                                        strutStyle: fixedLine,
                                      ),
                                    ),
                                    FutureBuilder(
                                        future: api.getNoticeCount("like", "0"),
                                        builder: (BuildContext context,
                                                AsyncSnapshot<RespData<int>>
                                                    snapshot) =>
                                            snapshot.data == null
                                                ? Container()
                                                : snapshot.data.data == 0
                                                    ? Container()
                                                    : Container(
                                                        width: 20,
                                                        height: 20,
                                                        decoration: BoxDecoration(
                                                            shape:
                                                                BoxShape.circle,
                                                            color: Theme.of(
                                                                    context)
                                                                .accentColor),
                                                        child: Center(
                                                          child: Text(
                                                            snapshot.data.data >
                                                                    99
                                                                ? "99+"
                                                                : "${snapshot.data.data}",
                                                            maxLines: 1,
                                                            style: TextStyle(
                                                                fontSize: 10,
                                                                color: Colors
                                                                    .white),
                                                          ),
                                                        ),
                                                      )),
                                    SizedBox(
                                      width: 8.0,
                                    ),
                                    arrowRight()
                                  ]),
                                ))
                            : Container(),
                    separatorBuilder: (context, index) => Divider(
                      height: 1,
                    ),
                    itemCount: 3,
                  )),
              NestedScrollViewInnerScrollPositionKeyWidget(
                  const Key('Tab0'),
                  Container(
                    child: FutureBuilder(
                      future: _future,
                      builder: (_, AsyncSnapshot<List<Notice>> snapshot) {
                        if (snapshot == null || snapshot.data == null)
                          return RequestLoadingWidget();
                        return ListView.separated(
                          padding: EdgeInsets.symmetric(horizontal: 12.0),
                          itemBuilder: (context, index) {
                            if (index >= snapshot.data.length)
                              return Container();
                            var item = snapshot.data[index];
                            return InkWell(
                              onTap: () async {
                                bool result = await NavigatorUtil.goPage(
                                    context,
                                    (context) => MessageNoticeDetailPage(item));
                                if (result == true) {
                                  item.isRead = 1;
                                }
                              },
                              child: Padding(
                                padding: const EdgeInsets.symmetric(vertical: 12.0),
                                child: Row(children: <Widget>[
                                  Image.asset(
                                      "lib/assets/img/bbsmessage_icon_color_${(item.type == "rank" || item.type == "receive") ? 'rank' : 'notice'}.png",width: 44.0,height: 44.0,),
                                  SizedBox(
                                    width: 8.0,
                                  ),
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: <Widget>[
                                        Container(
                                          height:18.0,
                                          child: Text(
                                            "${item.title}",
                                            style: Theme.of(context)
                                                .textTheme
                                                .subtitle1
                                                .copyWith(fontSize: 16),
                                            strutStyle: fixedLine,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ),
                                        SizedBox(
                                          height: 4,
                                        ),
                                        Text(
                                          "${item.content}",
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: Theme.of(context)
                                              .textTheme
                                              .bodyText1,
                                        )
                                      ],
                                    ),
                                  ),
                                  SizedBox(
                                    width: 8.0,
                                  ),
                                  arrowRight()
                                ]),
                              ),
                            );
                          },
                          separatorBuilder: (context, index) => Divider(
                            height: 1,
                          ),
                          itemCount: snapshot.data?.length ?? 0 + 1,
                        );
                      },
                    ),
                  ))
            ])),
      ),
    );
  }
}
