import 'package:chat/data/UserData.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/home/add_friend.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/conversation_table.dart';
import 'package:dio/dio.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'ProfilePage.dart';

class _ContactItem extends StatelessWidget {
  _ContactItem(
      {@required this.avatar,
      @required this.title,
      @required this.userId,
      this.groupTitle,
      this.onPressed,
      this.gradient,
      this.iconCode,
      this.isShowDivder: true,
      this.state});
  final int userId;
  final int iconCode;
  final String avatar;
  final String title;
  final String groupTitle;
  final VoidCallback onPressed;
  final Gradient gradient;
  final bool isShowDivder;
  final int state;

  static const double MARGIN_VERTICAL = 10.0;
  static const double GROUP_TITLE_HEIGHT = 24.0;

  @override
  Widget build(BuildContext context) {
    Widget _avatarIcon;
    if (iconCode == null) {
      _avatarIcon = ClipRRect(
          borderRadius: BorderRadius.circular(6),
          child: CachedNetworkImage(
            imageUrl: this.avatar,
            width: Constants.ContactAvatarSize,
            height: Constants.ContactAvatarSize,
          ));
    } else {
      _avatarIcon = Container(
        width: Constants.ContactAvatarSize,
        height: Constants.ContactAvatarSize,
        decoration: BoxDecoration(
            gradient: gradient, borderRadius: BorderRadius.circular(6)),
        child: Icon(
          IconData(this.iconCode, fontFamily: Constants.IconFontFamily),
          color: Colors.white,
        ),
      );
    }

    Widget _button = Container(
      padding: const EdgeInsets.symmetric(
          vertical: MARGIN_VERTICAL, horizontal: 16.0),
      decoration: BoxDecoration(color: Colors.white),
      child: Row(
        children: <Widget>[
          _avatarIcon,
          SizedBox(width: 10.0),
          Expanded(child: Text(title, textScaleFactor: 1.0)),
          state == 1
              ? InkWell(
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 21, vertical: 7),
                    child: Text(
                      I18n.of(context).added,
                      textScaleFactor: 1.0,
                      style: TextStyle(color: const Color(0xFF8A8B8B)),
                    ),
                  ),
                )
              : (state == 0
                  ? InkWell(
                      child: Container(
                        padding:
                            EdgeInsets.symmetric(horizontal: 21, vertical: 7),
                        child: Text(
                          I18n.of(context).already_applied,
                          textScaleFactor: 1.0,
                          style: TextStyle(color: const Color(0xFF8A8B8B)),
                        ),
                      ),
                    )
                  : InkWell(
                      onTap: () {
                        Navigator.of(context).push(
                          new MaterialPageRoute(
                            builder: (context) {
                              return AddFriendPage(
                                userId: this.userId,
                                pageType: SendMessagePageType.AddFriends,
                                originalName: I18n.of(context)
                                    .i_am
                                    .replaceFirst(
                                        '/s1', UserData().basicInfo.nickName),
                              );
                            },
                          ),
                        );
                      },
                      child: Container(
                        padding:
                            EdgeInsets.symmetric(horizontal: 21, vertical: 7),
                        decoration: BoxDecoration(
                            color: const Color(0xFF3875E9),
                            borderRadius: BorderRadius.circular(5)),
                        child: Text(
                          I18n.of(context).add,
                          textScaleFactor: 1.0,
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    )),
        ],
      ),
    );

    //分组标签
    Widget _itemBody;
    if (this.groupTitle != null) {
      _itemBody = Column(
        children: <Widget>[
          Container(
            height: GROUP_TITLE_HEIGHT,
            padding: EdgeInsets.only(left: 16.0, right: 16.0),
            color: const Color(AppColors.ContactGroupTitleBgColor),
            alignment: Alignment.centerLeft,
            child: Text(this.groupTitle,
                textScaleFactor: 1.0, style: AppStyles.GroupTitleItemTextStyle),
          ),
          _button,
        ],
      );
    } else {
      _itemBody = _button;
    }

    return InkWell(
        onTap: () {
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (context) {
                return ProfilePage(
                  userId: userId,
                );
              },
            ),
          );
        },
        child: Container(
            color: Colors.white,
            child: Column(
              children: <Widget>[
                _itemBody,
                isShowDivder
                    ? Container(
                        height: 1,
                        color: const Color(0xFFF3F3F3),
                        margin: EdgeInsets.only(
                            left: 26 + Constants.ContactAvatarSize),
                      )
                    : Container()
              ],
            )));
  }
}

class ContactsPage extends StatefulWidget {
  @override
  _ContactsPageState createState() => _ContactsPageState();
}

class _ContactsPageState extends State<ContactsPage> {
  String _currentLetter = '';
  ScrollController _scrollController;
  TextEditingController _txtCtrl = new TextEditingController();
  FocusNode editFocus = FocusNode();
  bool _hasdeleteIcon = false;
  bool isLoadingFinish = false;

  List<FriendModel> searchList = [];

  List<FriendModel> friendList = [];

  @override
  void initState() {
    print('ContactsPage initState');
    super.initState();
    getFriendList();
    _scrollController = new ScrollController();
    MessageMgr().on('post_add_friend', msgAddFriend);
  }

  msgAddFriend(data) {
    for (int i = 0; i < friendList.length; i++) {
      if (friendList[i].friendId == data) {
        setState(() {
          friendList[i].state = 0;
        });
        break;
      }
    }
  }

  getFriendList() async {
    Map data = {
      "userId": UserData().basicInfo.userId,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil().post('maillist/user/get', data: data);
    Map resData = res.data;
    isLoadingFinish = true;
    print(resData['data']);
    if (resData['code'] == 0 && resData['data'] != null) {
      resData['data'].forEach((f) {
        var friend = FriendModel.fromServerJson(f);
        if (friend.friendId != UserData().basicInfo.userId)
          friendList.add(friend);
      });
      setState(() {});
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    editFocus.dispose();
    MessageMgr().off('post_add_friend', msgAddFriend);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final List<Widget> _body = [];

    if (!_hasdeleteIcon) {
      friendList.sort((a, b) => a.nameTag.compareTo(b.nameTag));
      _body.add((friendList == null || friendList.length == 0)
          ? CustomUI.buildNoData(context)
          : ListView.builder(
              controller: _scrollController,
              itemBuilder: (BuildContext context, int index) {
                int _contactIndex = index;
                bool _isGroupTitle = true;
                FriendModel _contact = friendList[_contactIndex];

                if (_contactIndex >= 1 &&
                    _contact.nameTag == friendList[_contactIndex - 1].nameTag) {
                  _isGroupTitle = false;
                }

                return _ContactItem(
                    userId: _contact.friendId,
                    avatar: _contact.avatar,
                    title: _contact.name,
                    state: _contact.state,
                    isShowDivder: _isGroupTitle,
                    groupTitle: _isGroupTitle ? _contact.nameTag : null);
              },
              itemCount: friendList.length,
            ));
    } else {
      _body.add(ListView.builder(
        controller: _scrollController,
        itemBuilder: (BuildContext context, int index) {
          FriendModel _contact = searchList[index];

          return _ContactItem(
              userId: _contact.friendId,
              avatar: _contact.avatar,
              title: _contact.name,
              state: _contact.state,
              isShowDivder: true,
              groupTitle: null);
        },
        itemCount: searchList.length,
      ));
    }

    if (_currentLetter != null &&
        _currentLetter.isNotEmpty &&
        !_hasdeleteIcon) {
      _body.add(Center(
        child: Container(
          width: Constants.IndexLetterBoxSize,
          height: Constants.IndexLetterBoxSize,
          decoration: BoxDecoration(
            color: AppColors.IndexLetterBoxBgColor,
            borderRadius: BorderRadius.all(
                Radius.circular(Constants.IndexLetterBoxRadius)),
          ),
          child: Center(
            child: Text(_currentLetter,
                textScaleFactor: 1.0, style: AppStyles.IndexLetterBoxTextStyle),
          ),
        ),
      ));
    }

    return Scaffold(
        resizeToAvoidBottomPadding: false,
        appBar: AppBar(
          backgroundColor: AppColors.NewAppbarBgColor,
          title: Text(
            I18n.of(context).contact_add,
            textScaleFactor: 1.0,
            style: TextStyle(color: AppColors.NewAppbarTextColor),
          ),
          centerTitle: true,
          leading: CustomUI.buildCustomLeading(context),
          elevation: 1,
          bottom: PreferredSize(
              preferredSize: Size.fromHeight(49),
              child: Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(bottom: 14, left: 12.5, right: 12.5),
                height: 35,
                decoration: BoxDecoration(
                    color: const Color(0xFFEEEEEE),
                    borderRadius: BorderRadius.all(Radius.circular(8))),
                child: TextField(
                    keyboardAppearance: Brightness.light,
                    keyboardType: TextInputType.text,
                    textInputAction: TextInputAction.search,
                    controller: _txtCtrl,
                    focusNode: editFocus,
                    maxLines: 1,
                    style: TextStyle(
                        textBaseline: TextBaseline.alphabetic, fontSize: 14.5),
                    autofocus: false,
                    inputFormatters: [
                      LengthLimitingTextInputFormatter(50),
                    ],
                    decoration: InputDecoration(
                      hintText: I18n.of(context).search,
                      hintStyle: TextStyle(fontSize: 14.5),
                      prefixIcon: Icon(
                        IconData(
                          0xe664,
                          fontFamily: Constants.IconFontFamily,
                        ),
                        color: const Color(0xFFA0A0A0),
                        size: 18,
                      ),
                      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,
                      fillColor: Colors.transparent,
                      border: InputBorder.none,
                    ),
                    onChanged: (str) async {
                      setState(() {
                        if (str.isEmpty) {
                          _hasdeleteIcon = false;
                        } else {
                          _hasdeleteIcon = true;
                          searchList = CustomUI().getSearchResult(
                              str, friendList == null ? [] : friendList);
                        }
                      });
                    },
                    onEditingComplete: () {}),
              )),
        ),
        body: Stack(
          children: _body,
        ));
  }
}
