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/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/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/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';

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

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

  StreamSubscription _streamSubscription;
  List<MessageItem> messageList;
  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();
    getChatIndex(); // 初始化chat...
    initListen();
  }

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

  // MessageInstance 类型是 服务器请求回来的类型 MessageItem 是本地 存储后的类型...
  void getChatIndex() async {
    //    List<ChatMessageInstance> list = (await api.getChatIndex()).results;
//    var list = await MessageDB().getMessageList();
    messageList = [];
    var unReadList = await MessageDB().getMessageUnRead();

//    print("[unReadList]:$unReadList---------------------------------------");

    if (unReadList != null && unReadList.length > 0) {
      List<int> ids = [];
      for (var item in unReadList) {
        ids.add(MessageItem.fromJson(item).userId);
      }

      List<ChatOnlineInfo> chatInfo = (await api.getChatUserInfo(ids)).results;

      // 这不是是个骚的?
      for (int i = 0; i < unReadList.length; i++) {
        MessageItem item = MessageItem.fromJson(unReadList[i]);
        for (int j = 0; j < chatInfo.length; j++) {
          if (item.userId == chatInfo[j].userId) {
            if (item.message.fromUser.id == int.parse(selfId)) {
              item.message.toUser.online = chatInfo[i].online;
            } else {
              item.message.fromUser.online = chatInfo[i].online;
            }
//            print("[online:]${chatInfo[i].online}------------------------");
            item.message.relate = chatInfo[i].relate;
            item.unReadCount = unReadList[i]['cout'];
          }
        }
        messageList.add(item);
      }
    }
    setState(() {
      messageList = messageList;
    });
//    return messageList;
  }

  // 在本页中如果收到了就 ...
  initListen() {
    Stream<List<MessageInstance>> queryStream =
        Provider.of<MessageModel>(context, listen: false).queryStream;
    _streamSubscription = queryStream.listen((List<MessageInstance> list) {
//      for (MessageInstance item in list) {
//        addMessageToPage(item);
//      }
      print("[receive:message]:$list-----------------------------");
      getChatIndex();
    });
  }

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

  @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),
                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'),
                  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: messageList == null
                          ? RequestLoadingWidget()
                          : messageList.length == 0
                              ? Center(
                                  child: RequestErrorWidget(
                                    null,
                                    msg: "暂无消息",
                                    assets:
                                        RequestErrorWidget.ASSETS_NO_COMMENT,
                                  ),
                                )
                              : ListView.separated(
                                  padding: EdgeInsets.zero,
                                  separatorBuilder: (context, index) => Divider(
                                        height: 1,
                                      ),
                                  itemCount: messageList?.length ?? 0 + 1,
                                  itemBuilder: (context, index) {
                                    // 这里可能有得后续看看怎么写比较好 ... 判断是否是自己 ...
                                    // 这里拿的时候得判断一手 是自己还是别人发的...
                                    int id;
                                    String name;
                                    String avatar;
                                    bool online;
                                    if (messageList[index]
                                            .message
                                            .fromUser
                                            .id ==
                                        int.parse(selfId)) {
                                      id = messageList[index].message.toUser.id;
                                      name = messageList[index]
                                          .message
                                          .toUser
                                          .name;
                                      avatar = messageList[index]
                                          .message
                                          .toUser
                                          .avatar;
                                      online = messageList[index]
                                          .message
                                          .toUser
                                          .online;
                                    } else {
                                      id = messageList[index]
                                          .message
                                          .fromUser
                                          .id;
                                      name = messageList[index]
                                          .message
                                          .fromUser
                                          .name;
                                      avatar = messageList[index]
                                          .message
                                          .fromUser
                                          .avatar;
                                      online = messageList[index]
                                          .message
                                          .fromUser
                                          .online;
                                    }

                                    return InkWell(
                                      onTap: () async {
                                        await NavigatorUtil.goPage(context,
                                            (context) => ChatPage(name, id));
                                        getChatIndex();
                                      },
                                      child: Padding(
                                        padding: const EdgeInsets.all(12.0),
                                        child: Column(
                                          children: <Widget>[
                                            Padding(
                                                padding:
                                                    const EdgeInsets.all(12.0),
                                                child: Row(
                                                  children: <Widget>[
                                                    !online
                                                        ? ColorFiltered(
                                                            colorFilter:
                                                                ColorFilter.mode(
                                                                    Colors
                                                                        .white,
                                                                    BlendMode
                                                                        .color),
                                                            child: CircleAvatar(
                                                              backgroundImage:
                                                                  userAvatarProvider(
                                                                      avatar),
                                                              radius: 22,
                                                            ),
                                                          )
                                                        : CircleAvatar(
                                                            backgroundImage:
                                                                userAvatarProvider(
                                                                    avatar),
                                                            radius: 22,
                                                          ),
                                                    SizedBox(
                                                      width: 8,
                                                    ),
                                                    Expanded(
                                                      flex: 3,
                                                      child: Column(
                                                        crossAxisAlignment:
                                                            CrossAxisAlignment
                                                                .start,
                                                        children: <Widget>[
                                                          Row(
                                                            children: <Widget>[
                                                              Expanded(
                                                                child: Text(
                                                                  "$name",
                                                                  style: Theme.of(
                                                                          context)
                                                                      .textTheme
                                                                      .headline3,
                                                                  maxLines: 1,
                                                                  overflow:
                                                                      TextOverflow
                                                                          .ellipsis,
                                                                ),
                                                              ),
                                                              SizedBox(
                                                                width: 4.0,
                                                              ),
                                                              messageList[index]
                                                                          .message
                                                                          .relate !=
                                                                      'friends'
                                                                  ? Container(
                                                                      padding: EdgeInsets.symmetric(
                                                                          horizontal:
                                                                              5.0),
                                                                      decoration: BoxDecoration(
                                                                          border: Border.all(
                                                                              color: Color(
                                                                                  0xffffc400)),
                                                                          borderRadius: BorderRadius.all(Radius.circular(
                                                                              8.0))),
                                                                      child:
                                                                          Text(
                                                                        "未关注",
                                                                        style: Theme.of(context)
                                                                            .textTheme
                                                                            .bodyText1
                                                                            .copyWith(color: Color(0xffffc400)),
                                                                      ))
                                                                  : Container()
                                                            ],
                                                          ),
                                                          SizedBox(
                                                            height: 4,
                                                          ),
                                                          if (messageList[index]
                                                                  .message
                                                                  .type ==
                                                              "text")
                                                            Text(
                                                              "${messageList[index].message.data.text}",
                                                              style: Theme.of(
                                                                      context)
                                                                  .textTheme
                                                                  .bodyText1,
                                                              maxLines: 1,
                                                              overflow:
                                                                  TextOverflow
                                                                      .ellipsis,
                                                            ),
                                                          if (messageList[index]
                                                                  .message
                                                                  .type ==
                                                              "forum-forward")
                                                            Text(
                                                              "${messageList[index].message.data.subject.content}",
                                                              style: Theme.of(
                                                                      context)
                                                                  .textTheme
                                                                  .bodyText1,
                                                              maxLines: 1,
                                                              overflow:
                                                                  TextOverflow
                                                                      .ellipsis,
                                                            ),
                                                        ],
                                                      ),
                                                    ),
                                                    SizedBox(
                                                      width: 8,
                                                    ),
                                                    Expanded(
                                                      flex: 1,
                                                      child: Column(
                                                        crossAxisAlignment:
                                                            CrossAxisAlignment
                                                                .end,
                                                        mainAxisAlignment:
                                                            MainAxisAlignment
                                                                .center,
                                                        children: <Widget>[
                                                          Text(
                                                            "${DateFormat.format(DateTime.parse(messageList[index].message.createdAt))}",
                                                            style: Theme.of(
                                                                    context)
                                                                .textTheme
                                                                .bodyText1,
                                                          ),
                                                          SizedBox(
                                                            height: 3,
                                                          ),
                                                          if (messageList[index]
                                                                  .unReadCount >
                                                              0)
                                                            ClipOval(
                                                                child:
                                                                    Container(
                                                              width: 21.0,
                                                              height: 21.0,
                                                              color: Color(
                                                                  0xffff5B1D),
                                                              child: Center(
                                                                child: Text(
                                                                  '${messageList[index].unReadCount}',
                                                                  style: TextStyle(
                                                                      color: Colors
                                                                          .white,
                                                                      fontSize:
                                                                          12.0),
                                                                ),
                                                              ),
                                                            ))
                                                        ],
                                                      ),
                                                    )
                                                  ],
                                                )),
                                          ],
                                        ),
                                      ),
                                    );
                                  }))),
              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,
                        );
                      },
                    ),
                  ))
            ])),
      ),
    );
  }
}
