import 'package:cached_network_image/cached_network_image.dart';
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/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';
import 'ProfilePage.dart';

class WhiteAndBlackPage extends StatefulWidget {
  final bool isWhite;
  WhiteAndBlackPage({Key key, this.isWhite = true}) : super(key: key);

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

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

  @override
  void initState() {
    super.initState();
    MessageMgr().on('refresh_love_list', msgRefreshLoveList);
  }

  msgRefreshLoveList(data) {
    for (int i = 0; i < list.length; i++) {
      var item = list[i];
      if (item['FollowUserId'] == data['UserId'] && data['flag'] != 0) {
        list.removeAt(i);
        break;
      }
    }
    setState(() {});
  }

  Future getData(type, callback) async {
    var data = {
      "userid": UserData().basicInfo.userId,
      "type": type,
    };
    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/follow/user',
        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,
      title: new Text(
        widget.isWhite ? I18n.of(context).i_like : I18n.of(context).blacklist2,
        textScaleFactor: 1.0,
        style: TextStyle(color: AppColors.NewAppbarTextColor),
      ),
      centerTitle: true,
      leading: CustomUI.buildCustomLeading(context),
    );

    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: true,
        isBalck: false,
        userId: userInfo['FollowUserId'],
        payImg: userInfo['PhotoAut'] == 1,
        isHidden: userInfo['InfoAut'] == 1,
        member: userInfo['IsMember'],
        imgNum: userInfo['PhotoNum'],
      );
      var blackItem = Container(
        padding: EdgeInsets.all(10),
        margin: EdgeInsets.symmetric(horizontal: 10, vertical: 4),
        decoration: BoxDecoration(
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: Color.fromRGBO(0, 0, 0, 248),
                offset: Offset(0, 6),
                blurRadius: 6,
              )
            ],
            borderRadius: BorderRadius.all(Radius.circular(10))),
        child: Row(
          children: <Widget>[
            _buildImg(userInfo['FollowUserId'], userInfo['Headimgurl']),
            Padding(
                padding: EdgeInsets.only(left: 10),
                child: Text(
                  WebData().subUserName(Provider.of<RefNameProvider>(context)
                      .getRefName(
                          userInfo['FollowUserId'], userInfo['NickName'])),
                  textScaleFactor: 1.0,
                  style:
                      TextStyle(fontSize: 15, color: Constants.BlackTextColor),
                )),
            Expanded(child: Container()),
            InkWell(
              onTap: () async {
                HttpUtil().cancleBlackUser(userInfo['FollowUserId'], () {
                  for (int i = 0; i < list.length; i++) {
                    if (list[i]['FollowUserId'] == userInfo['FollowUserId']) {
                      setState(() {
                        list.removeAt(i);
                        if (list.length == 0) {
                          _refreshController.refreshCompleted();
                        }
                      });
                      break;
                    }
                  }
                });
              },
              child: Container(
                  padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10.5),
                  decoration: BoxDecoration(
                      color: Constants.ConfrimButtonColor,
                      borderRadius: BorderRadius.all(Radius.circular(5))),
                  alignment: Alignment.center,
                  child: Text(
                    I18n.of(context).cancel_shield,
                    textScaleFactor: 1.0,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 13.5,
                    ),
                  )),
            )
          ],
        ),
      );
      return widget.isWhite
          ? (index == 0
              ? Padding(padding: EdgeInsets.only(top: 10), child: whiteItem)
              : whiteItem)
          : blackItem;
    }
    return Container();
  }

  Widget _buildImg(userId, url) {
    return InkWell(
        onTap: () {
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (context) {
                return ProfilePage(
                  userId: userId,
                );
              },
            ),
          );
        },
        child: Container(
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(2.0)),
            width: 70.6,
            height: 70.6,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: url == '' || url == null
                  ? Image.asset(
                      Constants.DefaultHeadImgUrl,
                    )
                  : CachedNetworkImage(
                      imageUrl: url,
                      placeholder: (context, url) => Image.asset(
                        Constants.DefaultHeadImgUrl,
                        width: 55,
                        height: 55,
                      ),
                      fit: BoxFit.cover,
                    ),
            )));
  }

  Future<Null> _onRefresh() async {
    _page = 1;
    getData(widget.isWhite == true ? 0 : 1, (data) {
      if (data != null) {
        list.clear();
        list.addAll(data);
        setState(() {});
      }
    });
  }

  Future _onLoading() async {
    _page++;
    getData(widget.isWhite == true ? 0 : 1, (data) {
      if (data == null || data.length == 0) {
        _page--;
        _refreshController.loadNoData();
      } else {
        list.addAll(data);
        _refreshController.loadComplete();
      }
      setState(() {});
    });
  }

  @override
  void dispose() {
    _refreshController.dispose();
    MessageMgr().off('refresh_love_list', msgRefreshLoveList);
    super.dispose();
  }
}
