import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/material.dart' hide NestedScrollView;
import 'package:sport/bean/notice.dart';
import 'package:sport/pages/social/message_notice_detail_page.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/widgets/appbar.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';

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

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

  @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;
    return DefaultTabController(
      length: 2,
      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),
                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: '通知')],
                                  ),
                                ),
                              ),
                            ),
                            Divider(
                              height: 1,
                              indent: 12.0,
                              endIndent: 12.0,
                            )
                          ],
                        ),
                      )),
                  pinned: true,
                ),
              ];
            },
            body: TabBarView(children: [
              NestedScrollViewInnerScrollPositionKeyWidget(
                  const Key('Tab0'),
                  ListView.separated(
                    padding: EdgeInsets.zero,
                    itemBuilder: (context, index) => index == 0
                        ? InkWell(
                            onTap: () => NavigatorUtil.go(context, "${Routes.socialMessageDetail}?data=comment"),
                            child: Padding(
                              padding: const EdgeInsets.all(12.0),
                              child: Row(children: <Widget>[
                                Image.asset("lib/assets/img/bbsmessage_icon_reply.png"),
                                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.all(12.0),
                                  child: Row(children: <Widget>[
                                    Image.asset("lib/assets/img/bbsmessage_icon_like.png"),
                                    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.zero,
                          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.all(12.0),
                                child: Row(children: <Widget>[
                                  Image.asset(
                                      "lib/assets/img/${(item.type == "rank" || item.type == "receive") ? 'bbsmessage_icon_rank' : 'bbsmessage_icon_notice'}.png"),
                                  SizedBox(
                                    width: 16.0,
                                  ),
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: <Widget>[
                                        Text(
                                          "${item.title}",
                                          style: Theme.of(context).textTheme.subtitle1.copyWith(fontSize: 16),
                                          strutStyle: fixedLine,
                                        ),
                                        SizedBox(
                                          height: 4,
                                        ),
                                        Text(
                                          "${item.content}",
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: Theme.of(context).textTheme.bodyText2,
                                        )
                                      ],
                                    ),
                                  ),
                                  SizedBox(
                                    width: 8.0,
                                  ),
                                  arrowRight()
                                ]),
                              ),
                            );
                          },
                          separatorBuilder: (context, index) => Divider(
                            height: 1,
                          ),
                          itemCount: snapshot.data?.length ?? 0 + 1,
                        );
                      },
                    ),
                  ))
            ])),
      ),
    );
  }
}
