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/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/commonModel/ui/ALColors.dart';
import 'common.dart';

//刷新状态枚举
enum LoadingStatus {
  //正在加载中
  STATUS_LOADING,
  //数据加载完毕
  STATUS_COMPLETED,
  //空闲状态
  STATUS_IDEL
}

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 var loadStatus = LoadingStatus.STATUS_IDEL;
  static int pageCount = 10;

  //定义整个页面的数据源 list
  static List list = new List();

  //定义加载中默认文字
  String loadText = "加载中...";

  //定义 ListView 的监听， ScrollController ScrollController 能够添加对ListView的滑动监听
  ScrollController _scrollController = new ScrollController();

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

//  加载中的布局
  Widget _loadingView() {
    var loadingTS = TextStyle(color: ALColors.Color999999, fontSize: 16);
//    var loadingText=new Opacity(opacity: loadStatus==LoadingStatus.STATUS_LOADING?1.0:0,child:_pad(Text(loadText,style: loadingTS),l:20.0));
    var loadingText = _pad(Text(loadText, style: loadingTS), l: 20.0);
//    var loadingIndicator=new Opacity(opacity: loadStatus==LoadingStatus.STATUS_LOADING?1.0:0,child:SizedBox(child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation(Colors.blue)),width: 20.0,height: 20.0,));
    var loadingIndicator = new Visibility(
        visible: loadStatus == LoadingStatus.STATUS_LOADING ? true : false,
        child: SizedBox(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation(ALColors.Color999999),
            strokeWidth: 2.0,
          ),
          width: 16.0,
          height: 16.0,
        ));

    return _pad(
        Row(
          children: <Widget>[loadingIndicator, loadingText],
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
        ),
        t: 20.0,
        b: 20.0);
  }

  _MessagePageState(this._messageModel);
  @override
  void initState() {
    super.initState();
    _messageModel.init(context);
    //在初始化状态的方法里 设置ListView的监听
    _scrollController.addListener(() {
      //判断 当滑动到最底部的时候，去加载更多的数据
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        //此时加载下一页数据
        _getMoreData();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 375, height: 667)..init(context);
    return Scaffold(
      appBar: AppBar(
        centerTitle: false,
        title: messageTitle('消息'),
        elevation: 0,
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Column(
            children: <Widget>[
              topCard(),
              StreamBuilder<MyMessageEntity>(
                stream: _messageModel.myMessageLive.stream,
                initialData: _messageModel.myMessageLive.data ,
                builder: (BuildContext context, data){
                  var dataList = data.data?.data;
                  if(dataList == null) {
                    return Container(
                      color: ALColors.ColorFFFFFF,
                      height: ScreenUtil().setHeight(430),
                      child: Center(child: Text('暂无相关内容', style: TextStyle(color: ALColors.Color999999, fontSize: ScreenUtil().setSp(16))))
                    );
                  }
                  print('++++++====================${dataList.length}=================');
                  return ListView.builder(
                    itemCount: dataList.length + 1,
                    itemBuilder: (BuildContext context, int index) {
                      if (index == dataList.length) {
                        return _loadingView();
                      } else {
                        return Container(
                          color: ALColors.ColorFFFFFF,
                          child: Column(
                            children: <Widget>[
                              messageList(dataList[index])
                            ],
                          ),
                        );
                      }
                    },
                    controller: _scrollController,
                  );
                },
              )
            ]
          ),
        ),
      )
    );
  }


  topCard(){
    return Container(
      color: ALColors.ColorFFFFFF,
      child: Column(
        children: <Widget>[
          StreamBuilder<LatestMessageEntity>(
            stream: _messageModel.latestMessageLive.stream,
            initialData: _messageModel.latestMessageLive.data ,
            builder: (BuildContext context, data){
              var content = data.data?.data?.content ?? '没有新的通知';
              print('-====================${data.data.data.content}=================');
              return messageTop('images/message_noti.png', '通知', content == '' ? '没有新的通知' : content, 0);
            },
          ),
          StreamBuilder<UnreadMessageEntity>(
            stream: _messageModel.likeUnreadMessageLive.stream,
            initialData: _messageModel.likeUnreadMessageLive.data ,
            builder: (BuildContext context, data){
              var voteCount = data.data?.data?.voteCount ?? 0;
              print('-====================${voteCount}=================');
              return 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){
              var count = data.data?.data?.count ?? 0;
              print('-====================${count}=================');
              return 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
                )
              )
            )
          )
        ],
      ),
    );
  }

  //获取完更多数据，然后给控件setState 让控件进行数据更新
  Future _getMoreData() async {
    if (loadStatus == LoadingStatus.STATUS_IDEL)
      //先设置状态，防止往下拉就直接加载数据
      setState(() {
        loadStatus = LoadingStatus.STATUS_LOADING;
      });
    List moreList = [1,2];
    await _messageModel.getMyMessage(2, 2);
    //准备完数据后，在设置状态

    setState(() {
      if (moreList.length > 0) {
        list.addAll(moreList);
        loadStatus = LoadingStatus.STATUS_IDEL;
        loadText = '加载中...';
      } else {
        //加载完毕
        loadText = '暂时无更多数据';
        loadStatus = LoadingStatus.STATUS_COMPLETED;
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }
  
}