import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gmalpha_flutter/NewMessageModel/page/messagePage/MessageModel.dart';
import 'package:gmalpha_flutter/NewMessageModel/page/messagePage/common.dart';
import 'package:gmalpha_flutter/NewMessageModel/service/remote/entity/LatestMessageEntity.dart';
import 'package:gmalpha_flutter/NewMessageModel/service/remote/entity/MyMessageEntity.dart';
import 'package:gmalpha_flutter/NewMessageModel/service/remote/entity/UnreadMessageEntity.dart';
import 'package:gmalpha_flutter/NewMessageModel/util/Jump.dart';
import 'package:gmalpha_flutter/commonModel/GMBase.dart';
import 'package:gmalpha_flutter/commonModel/eventbus/GlobalEventBus.dart';
import 'package:gmalpha_flutter/commonModel/eventbus/event/LoginEvent.dart';
import 'package:gmalpha_flutter/commonModel/eventbus/event/SyncMessageEvent.dart';
import 'package:gmalpha_flutter/res/value/ALColors.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MessagePage extends StatefulWidget {
  MessageModel _messageModel;
  final String fromPage;

  MessagePage(this.fromPage) {
    _messageModel = new MessageModel(1, 10);
  }

  @override
  _MessagePageState createState() => _MessagePageState(_messageModel);
}

class _MessagePageState extends BasePage<MessagePage> {
  MessageModel _messageModel;
  static int pageCount = 10;
  static int pageNo = 2;
  StreamSubscription<LoginEvent> eventBusListener;
  StreamSubscription<SyncMessageEvent> eventBusListenerSync;
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  _MessagePageState(this._messageModel);

  @override
  void initState() {
    super.initState();
    _messageModel.init(context);
    eventBusListener = GlobalEventBus().event.on<LoginEvent>().listen((event) {
      print("flutter EVENT BUS LoginEvent ${event}");
      _messageModel.init(context);
    });
    eventBusListenerSync =
        GlobalEventBus().event.on<SyncMessageEvent>().listen((event) {
      print("flutter EVENT BUS SyncMessageEvent ${event}");
      _messageModel.init(context);
    });
  }

  void _onLoading(BuildContext context) async {
    await _messageModel.getMyMessage(context, pageNo, pageCount, (data) {
      if (data.data?.length == 0) {
        _refreshController.loadNoData();
      } else {
        pageNo++;
        _refreshController.loadComplete();
      }
    });
  }

  Widget _pad(Widget widget, {l, t, r, b}) {
    return new Padding(
        padding:
            EdgeInsets.fromLTRB(l ??= 0.0, t ??= 0.0, r ??= 0.0, b ??= 0.0),
        child: widget);
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 375, height: 667)..init(context);
    return Scaffold(
        appBar: AppBar(
          leading: baseText(
              "消息", ScreenUtil.instance.setSp(20.0), ALColors.Color323232),
        ),
        body: SmartRefresher(
            enablePullDown: false,
            enablePullUp: true,
            footer: CustomFooter(
              builder: (BuildContext context, LoadStatus mode) {
                String body;
                var loadingTS = TextStyle(
                    color: ALColors.Color999999,
                    fontSize: ScreenUtil().setSp(16));
                if (mode == LoadStatus.idle) {
                  body = '上拉加载';
                } else if (mode == LoadStatus.loading ||
                    mode == LoadStatus.canLoading) {
                  body = '加载中...';
                } else if (mode == LoadStatus.failed) {
                  body = '加载失败！点击重试！';
                } else {
                  body = '暂时无更多数据';
                }
                var loadingIndicator = Visibility(
                    visible: (mode == LoadStatus.loading ||
                            mode == LoadStatus.canLoading)
                        ? true
                        : false,
                    child: SizedBox(
                        child: CircularProgressIndicator(
                            valueColor:
                                AlwaysStoppedAnimation(ALColors.Color999999),
                            strokeWidth: 2),
                        width: ScreenUtil().setWidth(16),
                        height: ScreenUtil().setHeight(16)));
                return _pad(
                    Row(
                      children: <Widget>[
                        loadingIndicator,
                        _pad(Text(body, style: loadingTS),
                            l: ScreenUtil().setWidth(10))
                      ],
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.center,
                    ),
                    t: 20.0,
                    b: 20.0);
              },
            ),
            controller: _refreshController,
            onLoading: () => _onLoading(context),
            child: Container(
                color: ALColors.ColorFFFFFF,
                child: SingleChildScrollView(
                    child: Column(
                        children: <Widget>[topCard(), getListView()])))));
  }

  Widget getListView() {
    return StreamBuilder<MyMessageEntity>(
        stream: _messageModel.myMessageLive.stream,
        initialData: _messageModel.myMessageLive.data,
        builder: (BuildContext context, data) {
          var dataList = data?.data?.data;
          if (dataList == null) {
            return noData();
          }
          return ListView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemBuilder: (c, i) => messageList(dataList[i]),
            itemCount: dataList.length,
          );
        });
  }

  Widget noData() {
    return Container();
  }

  Widget topCard() {
    return Container(
      color: ALColors.ColorFFFFFF,
      child: Column(
        children: <Widget>[
          StreamBuilder<LatestMessageEntity>(
            stream: _messageModel.latestMessageLive.stream,
            initialData: _messageModel.latestMessageLive.data,
            builder: (BuildContext context, data) {
              if (data?.data == null) {
                return noData();
              }
              var content = data.data?.data?.content ?? '没有新的通知';
              return GestureDetector(
                  onTap: () {
                    super.pageStop();
                    onClickButton('notice');
                    jumpToAttentionPage(context)
                        .then((value) {})
                        .whenComplete(() {
                      startTime = DateTime.now().millisecondsSinceEpoch;
                    });
                  },
                  child: messageTop('images/icon_notice.svg', '通知',
                      content == '' ? '没有新的通知' : content, 0));
            },
          ),
          StreamBuilder<UnreadMessageEntity>(
            stream: _messageModel.likeUnreadMessageLive.stream,
            initialData: _messageModel.likeUnreadMessageLive.data,
            builder: (BuildContext context, data) {
              if (data?.data == null) {
                return noData();
              }
              var voteCount = data.data?.data?.voteCount ?? 0;
              return GestureDetector(
                  onTap: () {
                    onClickButton('like');
                    jumpToLikePage(context);
                  },
                  child: messageTop(
                      'images/icon_like.svg',
                      'Like!',
                      voteCount == 0 ? '还没有人给你Like!哦~' : '有$voteCount个人Like!了你',
                      voteCount));
            },
          ),
          StreamBuilder<UnreadMessageEntity>(
            stream: _messageModel.followUnreadMessageLive.stream,
            initialData: _messageModel.followUnreadMessageLive.data,
            builder: (BuildContext context, data) {
              if (data?.data == null) {
                return noData();
              }
              var count = data.data?.data?.count ?? 0;
              return GestureDetector(
                  onTap: () {
                    onClickButton('attention');
                    jumpToFocusPage(context);
                  },
                  child: messageTop('images/icon_follow.svg', '关注',
                      count == 0 ? '还没有人给你关注哦~' : '有$count个人关注了你', count));
            },
          ),
          Container(
              margin: EdgeInsets.only(
                  left: ScreenUtil.instance.setWidth(16),
                  right: ScreenUtil.instance.setWidth(16),
                  bottom: ScreenUtil().setHeight(24)),
              height: ScreenUtil.instance.setHeight(12),
              decoration: BoxDecoration(
                  color: ALColors.ColorFFFFFF,
                  border: Border(
                      bottom: BorderSide(
                          color: Color(0xfffE4E4E4),
                          width: ScreenUtil.instance.setWidth(1),
                          style: BorderStyle.solid))))
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _refreshController.dispose();
    eventBusListener?.cancel();
    eventBusListenerSync?.cancel();
    pageNo = 2;
  }

  @override
  String pageName() {
    return 'message_home';
  }

  @override
  String referrer() {
    return widget.fromPage;
  }
}
