import 'package:chat/data/UserData.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/HttpUtil.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/TokenMgr.dart';
import 'package:chat/utils/UserCard.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class SearchPage extends StatefulWidget {
  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  TextEditingController _txtCtrl = new TextEditingController();
  List list = new List(); //列表要展示的数据
  int _page = 1; //加载的页数
  int rows = 20;
  bool isLoading = false; //是否正在加载数据

  bool _hasdeleteIcon = false;

  @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['UserId'] == data['UserId']) {
        item['Follow'] = data['flag'];
        break;
      }
    }
    setState(() {});
  }

  //获取新的数据
  void getNewData() {
    _page = 1;
    getData((data) {
      list.clear();
      if (data != null) {
        list.addAll(data);
      }
      setState(() {});
    });
  }

  void getMoreData() {
    _page++;
    getData((data) {
      data == null || data.length == 0 ? _page-- : list.addAll(data);
      setState(() {});
    });
  }

  void getData(callback) async {
    var data = {
      "userId": UserData().basicInfo.userId,
      "language": UserData().language,
      "value": _txtCtrl.text,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['lng'] = UserData().longitude;
    data['lat'] = UserData().latitude;
    data['page'] = _page;
    data['rows'] = rows;
    data['sex'] = UserData().basicInfo.sex;
    Response res = await HttpUtil().post('user/search/userList', data: data);
    isLoading = false;
    _refreshController.refreshCompleted();
    var resData = res.data;
    print(resData);
    if (resData['code'] == 0) {
      callback(resData['data']);
    }
  }

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

  searchUser() {}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomPadding: false,
        appBar: AppBar(
          backgroundColor: AppColors.NewAppbarBgColor,
          titleSpacing: 0,
          leading: CustomUI.buildCustomLeading(context),
          title: Container(
            alignment: Alignment.center,
            margin: const EdgeInsets.only(top: 20, bottom: 20, right: 20),
            decoration: BoxDecoration(
                color: Colors.grey[200],
                borderRadius: BorderRadius.all(Radius.circular(10))),
            child: new TextField(
                keyboardAppearance: Brightness.light,
                keyboardType: TextInputType.text,
                textInputAction: TextInputAction.search,
                controller: _txtCtrl,
                maxLines: 1,
                style: TextStyle(
                    textBaseline: TextBaseline.alphabetic,
                    fontSize: 14,
                    color: AppColors.NewAppbarTextColor),
                autofocus: true,
                inputFormatters: [
                  LengthLimitingTextInputFormatter(50),
                ],
                decoration: InputDecoration(
                  hintText: I18n.of(context).search_user,
                  hintStyle: TextStyle(fontSize: 14, color: Colors.grey),
                  suffixIcon: Padding(
                      padding: EdgeInsetsDirectional.only(
                          start: 2.0, end: _hasdeleteIcon ? 20.0 : 0),
                      child: _hasdeleteIcon
                          ? new InkWell(
                              onTap: (() {
                                setState(() {
                                  WidgetsBinding.instance.addPostFrameCallback(
                                      (_) => _txtCtrl.clear());
                                  _hasdeleteIcon = false;
                                });
                              }),
                              child: Icon(
                                Icons.clear,
                                size: 18.0,
                                color: Constants.BlackTextColor,
                              ))
                          : new Text('')),
                  filled: true,
                  contentPadding:
                      EdgeInsets.only(left: 20, top: 14, bottom: 14),
                  fillColor: Colors.transparent,
                  border: InputBorder.none,
                ),
                onChanged: (str) {
                  setState(() {
                    if (str.isEmpty) {
                      _hasdeleteIcon = false;
                    } else {
                      _hasdeleteIcon = true;
                    }
                  });
                },
                onEditingComplete: () {
                  setState(() {
                    isLoading = true;
                    getNewData();
                  });
                }),
          ),
        ),
        body: SafeArea(
            child: Stack(
          children: <Widget>[
            SmartRefresher(
              enablePullDown: !isLoading,
              enablePullUp: !isLoading,
              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,
                        ),
            ),
            isLoading ? CustomUI.buildLoaingAnim(context) : Container(),
          ],
        )));
  }

  Widget _renderRow(BuildContext context, int index) {
    if (index < list.length) {
      var userInfo = list[index];
      var refName = Provider.of<RefNameProvider>(context)
          .getRefName(userInfo['UserId'], userInfo['NickName']);

      return UserCard(
        key: UniqueKey(),
        nameSize: 14,
        userName: refName == userInfo['NickName']
            ? userInfo['NickName']
            : WebData().subUserName(refName, size: 4) +
                '(${WebData().subUserName(userInfo['NickName'], size: 2)})',
        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: userInfo['Age'],
        professional: WebData().getProffesionName(userInfo['Occupation']),
        isOnline: userInfo['OnlineStatus'] == 1
            ? I18n.of(context).online
            : WebData().getLoginTime(context, userInfo['LoginDate']),
        sex: userInfo['Sex'],
        hiddenDistince: userInfo['DistanceStatus'] == 1,
        isLove: userInfo['Follow'] == 0,
        isBalck: userInfo['Follow'] == 1,
        userId: userInfo['UserId'],
        payImg: userInfo['PhotoAut'] == 1,
        isHidden: userInfo['InfoAut'] == 1,
        member: userInfo['IsMember'],
        imgNum: userInfo['PhotoNum'],
      );
    }
    return Container();
  }

  Future<Null> _onRefresh() async {
    getNewData();
  }

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