import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sport/bean/message.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/provider/message_model.dart';
import 'package:sport/router/navigator_util.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/popupmenu.dart' as menu;
import 'package:sport/widgets/error.dart';
import 'package:sport/widgets/image.dart';
import 'package:sport/widgets/loading.dart';

class MessageListSubPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _MessageListSubPageState();
  }
}

class _MessageListSubPageState extends State<MessageListSubPage>
    with InjectApi, UserId, AutomaticKeepAliveClientMixin {
  List<MessageItem> messageList;
  StreamSubscription _streamSubscription;
  bool isLoading = true;
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getChatIndex().then((value) {
      setState(() {
        isLoading = false;
        messageList = value;
      });
    });
    initListen();
  }

  // MessageInstance 类型是 服务器请求回来的类型 MessageItem 是本地 存储后的类型...
  Future<List<MessageItem>> 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'];
            item.isTop = unReadList[i]['isTop'];
          }
        }
        messageList.add(item);
      }
    }
    return messageList;
  }

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

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

  Widget messageWidget(
      BuildContext context, api, id, online, avatar, name, messageList, index) {
    GlobalKey messageKey = new GlobalKey();
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      key: messageKey,
      onTap: () async {
        UserInfo info = (await api.getUserInfo("$id")).data;
        await NavigatorUtil.goPage(context, (context) => ChatPage(info));
        getChatIndex().then((value) {
          setState(() {
            isLoading = false;
            messageList = messageList;
          });
        }); // 原来是为了更新那个红点的...
      },
      onLongPressStart: (e) async {
        RenderBox renderBox = messageKey.currentContext.findRenderObject();
        var offset =
            renderBox.localToGlobal(Offset(0.0, renderBox.size.height));
        final RelativeRect position = RelativeRect.fromLTRB(
            e.globalPosition.dx, //取点击位置坐弹出x坐标
            offset.dy, //取text高度做弹出y坐标（这样弹出就不会遮挡文本）
            e.globalPosition.dx,
            offset.dy);

        PopupMenuEntry menuItem(
                {String imgUrl, String text, dynamic callBack}) =>
            menu.PopupMenuItem(
              value: callBack,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  if (imgUrl != null)
                    Image.asset(
                      "lib/assets/img/$imgUrl",
                      width: 24,
                    ),
                  SizedBox(
                    width: 4,
                  ),
                  Text(
                    text,
                  )
                ],
              ),
            );

        var d = await showMenu(
          context: context,
          position: position,
          items: <PopupMenuEntry>[
            PopupMenuItem(
                child: Container(
              child: Column(
                children: <Widget>[
                  menuItem(
                      text: messageList[index].isTop == 1 ? "取消置顶" : "置顶",
                      callBack: 1),
                  menuItem(text: "删除聊天", callBack: 2)
                ],
              ),
            ))
          ],
        );
        if (d == 1) {
//        Navigator.of(context).pop(1);
          await MessageDB()
              .updateIsTop(id, messageList[index].isTop == 1 ? 0 : 1);
          ToastUtil.show("${messageList[index].isTop}");
        } else if (d == 2) {
          bool flag = await showDialog(
              context: context,
              builder: (context) => CustomAlertDialog(
                  title: '是否删除聊天记录',
                  ok: () => Navigator.of(context).pop(true)));

          if (flag) {
            await MessageDB().deleteUserIdMessage(id);
            getChatIndex();
            ToastUtil.show("删除成功");
          }
        }
      },
      child: Column(
        children: <Widget>[
          Padding(
              padding: const EdgeInsets.only(top: 12.0, bottom: 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,
                      mainAxisAlignment:MainAxisAlignment.center,
                      children: <Widget>[
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            Flexible(
                              child: Text(
                                "$name",
                                style: Theme.of(context)
                                    .textTheme
                                    .headline3
                                    .copyWith(fontWeight: FontWeight.normal),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                strutStyle: StrutStyle(forceStrutHeight: true),
                              ),
                            ),
                            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),fontSize: 11.0),
//                                    ))
                            Image.asset("lib/assets/img/untrace.png",width: 44.0,height: 22.0,)
                                : 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,
                          ),
                        if (messageList[index].message.type == "image")
                          Text(
                            "分享图片",
                            style: Theme.of(context).textTheme.bodyText1,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        if (messageList[index].message.type == "share")
                          Text(
                            "分享链接",
                            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),
                              ),
                            ),
                          ))
                      ],
                    ),
                  )
                ],
              )),
          Divider(height: 1,)
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    if (isLoading)
      return LoadingWidget(
        child: Text("loading"),
      );
    // TODO: implement build
    return messageList.length <= 0
        ? Center(
            child: RequestErrorWidget(
              null,
              msg: "暂无消息",
              assets: RequestErrorWidget.ASSETS_NO_COMMENT,
            ),
          )
        : ListView.builder(
            padding: EdgeInsets.symmetric(horizontal: 12.0),
//            separatorBuilder: (context, index) => Divider(
//                  height: 1,
//                ),
            itemCount: messageList?.length ?? 0,
            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 messageWidget(
                  context, api, id, online, avatar, name, messageList, index);
            });
  }
}
