import 'package:chat/data/WebData.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/models/ref_name_provider.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/UserCard.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.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 FansPage extends StatefulWidget {
  FansPage({Key key}) : super(key: key);

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

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

  @override
  void initState() {
    super.initState();
  }

  Future getData(callback) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['lng'] = UserData().longitude;
    data['lat'] = UserData().latitude;
    data['page'] = _page;
    data['rows'] = rows;
    Response res = await HttpUtil().post('userfollow/fans/list',
        data: data, failback: () => Navigator.of(context).pop());
    _refreshController.refreshCompleted();
    var resData = res.data;
    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).fans_list,
        style: TextStyle(color: AppColors.NewAppbarTextColor),
        textScaleFactor: 1.0,
      ),
      centerTitle: true,
    );

    return Scaffold(
        appBar: appBar,
        body: 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,
                      ),
          ),
        ));
  }

  Widget _renderRow(BuildContext context, int index) {
    if (index < list.length) {
      var userInfo = list[index];
      print(userInfo);
      var whiteItem = UserCard(
        key: UniqueKey(),
        userName: Provider.of<RefNameProvider>(context)
            .getRefName(userInfo['UserId'], userInfo['NickName']),
        city: WebData().getCountry(
            userInfo['Country']), // WebData().getCity(userInfo['City']),
        headUrl: userInfo['Headimgurl'],
        isReal: userInfo['IsAttestation'] == 1,
        constellation:
            WebData().getConstellation(context, userInfo['constellation']),
        distance: userInfo['Distance'].toDouble(),
        age:
            DateTime.now().year - int.parse(userInfo['Birthday'].split('-')[0]),
        professional: WebData().getProffesionName(userInfo['Occupation']),
        isOnline: userInfo['OnlineStatus'] == 1
            ? I18n.of(context).online
            : WebData().getLoginTime(context, userInfo['LoginDate']),
        hiddenDistince: userInfo['DistanceStatus'] == 1,
        sex: userInfo['Sex'],
        isLove: userInfo['Follow'] == 0,
        isBalck: userInfo['Follow'] == 1,
        userId: userInfo['FollowUserId'],
        payImg: userInfo['PhotoAut'] == 1,
        isHidden: userInfo['InfoAut'] == 1,
        member: userInfo['IsMember'],
        imgNum: userInfo['PhotoNum'],
      );

      return (index == 0
          ? Padding(padding: EdgeInsets.only(top: 10), child: whiteItem)
          : whiteItem);
    }
    return Container();
  }

  Future<Null> _onRefresh() async {
    _page = 1;
    getData((data) {
      if (data != null) {
        list.clear();
        list.addAll(data);
        MessageMgr().emit('refresh_fans_num',
            {"UserId": UserData().basicInfo.userId, "nums": list.length});
        setState(() {});
      }
    });
  }

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

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