import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gmalpha_flutter/NewMessageModel/page/MessageModel.dart';
import 'package:gmalpha_flutter/NewMessageModel/page/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/res/value/ALColors.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MessagePage extends StatefulWidget {
  MessageModel _messageModel;

  MessagePage(String fromPage) {
    _messageModel = new MessageModel(1, 10);
  }
  @override
  _MessagePageState createState() => _MessagePageState(_messageModel);
}

class _MessagePageState extends State<MessagePage> {
  MessageModel _messageModel;
  static int pageCount = 10;
  static int pageNo = 2;
  RefreshController _refreshController = RefreshController(initialRefresh: false);

  _MessagePageState(this._messageModel);
  @override
  void initState() {
    super.initState();
    _messageModel.init(context);
  }

  void _onLoading() async {
    await _messageModel.getMyMessage(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(
        centerTitle: false,
        title: messageTitle('消息'),
        elevation: 0,
        backgroundColor: ALColors.ColorFFFFFF,
      ),
      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,
        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: (){
                  onClickButton('notice');
                  jumpToAttentionPage(context);
                },
                child: messageTop('images/message_noti.png', '通知', 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');
                  jumpToAttentionPage(context);
                },
                child: messageTop('images/message_like.png', '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');
                  jumpToAttentionPage(context);
                },
                child: messageTop('images/message_att.png', '关注', count == 0 ? '还没有人给你关注哦~' : '有$count个人关注了你', count)
              );
            },
          ),
          Container(
            margin: EdgeInsets.only(left: ScreenUtil().setWidth(16), right: ScreenUtil().setWidth(16), bottom: ScreenUtil().setHeight(24)),
            height: ScreenUtil().setHeight(12),
            decoration: BoxDecoration(
              color: ALColors.ColorFFFFFF,
              border: Border(
                bottom: BorderSide(
                  color: Color(0xfffE4E4E4),
                  width: ScreenUtil().setWidth(1),
                  style: BorderStyle.solid
                )
              )
            )
          )
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _refreshController.dispose();
    pageNo = 2;
  }
  
}