import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/MessageBox.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../utils/HttpUtil.dart';
import 'package:dio/dio.dart';
import "../data/UserData.dart";
import '../utils/TokenMgr.dart';

class FollowUserPage extends StatefulWidget {
  FollowUserPage({Key key}) : super(key: key);

  @override
  _FollowUserPageState createState() => new _FollowUserPageState();
}

class _FollowUserPageState extends State<FollowUserPage> {
  List list = new List(); //列表要展示的数据
  RefreshController _refreshController =
      RefreshController(initialRefresh: true);
  int _page = 1; //加载的页数
  int rows = 20;

  @override
  void initState() {
    super.initState();
    MessageMgr().on('love_program', msgListLove);
    MessageMgr().on('refresh_list', msgRefreshList);
    MessageMgr().on('refresh_list_when_no_data', msgRefreshListWhenNoData);
    MessageMgr().on('join_program', msgJoinList);
  }

  msgJoinList(data) {
    for (int i = 0; i < list.length; i++) {
      if (list[i]['Id'] == data) {
        list[i]['EnrollNum']++;
        list[i]['IsEnroll']++;
        setState(() {});
        break;
      }
    }
  }

  msgRefreshListWhenNoData(data) {
    if (list.length == 0) _onRefresh();
  }

  msgRefreshList(data) {
    _onRefresh();
  }

  msgListLove(data) {
    print('msgListLove $data');
    for (int i = 0; i < list.length; i++) {
      if (list[i]['Id'] == data) {
        list[i]['FabulousNum']++;
        list[i]['IsFabulous']++;
        setState(() {});
        break;
      }
    }
  }

  Future getData(callback) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['page'] = _page;
    data['rows'] = rows;
    Response res = await HttpUtil().post('userfollow/dynamic/follow',
        data: data, failback: () => Navigator.of(context).pop());
    var resData = res.data;
    _refreshController.refreshCompleted();
    print(resData);
    if (resData['code'] == 0) {
      callback(resData['data']);
    } else {
      showToast(resData['msg']);
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget appBar = new AppBar(
      backgroundColor: AppColors.NewAppbarBgColor,
      leading: CustomUI.buildCustomLeading(context),
      title: new Text(
        I18n.of(context).i_like,
        textScaleFactor: 1.0,
        style: Constants.MainTitleStyle,
      ),
      centerTitle: true,
      elevation: 1,
    );

    Widget content = Scaffold(
        appBar: appBar,
        body: SafeArea(
            child: SafeArea(
          child: SmartRefresher(
            enablePullDown: true,
            enablePullUp: true,
            header: MaterialClassicHeader(),
            footer: CustomUI.buildLoadingFooter(),
            controller: _refreshController,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child:
                (_refreshController.headerStatus == RefreshStatus.completed &&
                        list.length == 0)
                    ? CustomUI.buildNoData(context)
                    : ListView.builder(
                        itemBuilder: _renderRow,
                        itemCount: list.length,
                      ),
          ),
        )));
    return content;
  }

  Future _onLoading() async {
    _page++;
    getData((data) {
      if (data == null || data.length == 0) {
        _page--;
        _refreshController.loadNoData();
      } else {
        list.addAll(data);
        _refreshController.loadComplete();
      }
      setState(() {});
    });
  }

  Widget _renderRow(BuildContext context, int index) {
    if (index < list.length) {
      var userInfo = list[index];
      return MessageBox(programInfo: userInfo);
    }
    return Container();
  }

  Future<Null> _onRefresh() async {
    _page = 1;
    getData((data) {
      list.clear();
      list.addAll(data == null ? [] : data);
      setState(() {});
    });
  }

  @override
  void dispose() {
    _refreshController.dispose();
    MessageMgr().off('love_program', msgListLove);
    MessageMgr().off('refresh_list', msgRefreshList);
    MessageMgr().off('join_program', msgJoinList);
    MessageMgr().off('refresh_list_when_no_data', msgRefreshListWhenNoData);
    super.dispose();
  }
}
