import 'package:chat/data/UserData.dart';
import 'package:chat/data/group_data_mgr.dart';
import 'package:chat/models/friends_info.dart';
import 'package:chat/models/group_info_model.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:chat/utils/conversation_table.dart';
import 'package:chat/utils/friend_list_mgr.dart';
import 'package:chat/utils/screen.dart';
import 'package:flutter/material.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:flutter/services.dart';
import 'ProfilePage.dart';
import 'group_item_widget.dart';
import 'package:chat/models/ref_name_provider.dart';
import 'package:provider/provider.dart';

class GlobalSearchPage extends StatefulWidget {
  final int type;
  GlobalSearchPage({Key key, @required this.type}) : super(key: key);
  @override
  _GlobalSearchPageState createState() => _GlobalSearchPageState();
}

class _GlobalSearchPageState extends State<GlobalSearchPage> {
  ScrollController _scrollController = ScrollController();
  TextEditingController _txtCtrl = new TextEditingController();
  bool _hasdeleteIcon = false;
  FocusNode focusNode;
  List searchList = [];
  String searchStr = '';

  @override
  void initState() {
    super.initState();
    _scrollController = new ScrollController();
    focusNode = new FocusNode();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    focusNode.dispose();
    super.dispose();
  }

  //群搜索结果
  Widget _buildSearchGroupBody() {
    return ListView.builder(
      controller: _scrollController,
      itemBuilder: (BuildContext context, int index) {
        GroupInfoModel _contact = searchList[index];

        return GroupItem(Key('Item${_contact.sessionId}'),
            groupInfoModel: _contact);
      },
      itemCount: searchList.length,
    );
  }

  //好友搜索结果
  Widget _buildSearchMyfriendsBody() {
    return ListView.builder(
      controller: _scrollController,
      itemBuilder: (BuildContext context, int index) {
        FriendModel _contact = searchList[index];

        return FriendsInfo(
            userId: _contact.friendId,
            avatar: _contact.avatar,
            title: Provider.of<RefNameProvider>(context)
                .getRefName(_contact.friendId, _contact.name),
            isShowDivder: true,
            groupTitle: null);
      },
      itemCount: searchList.length,
    );
  }

  //通过手机号搜索新用户结果
  Widget _buildSearchNewfriendsBody() {
    if (searchStr == '') return Container();
    return InkWell(
        onTap: () {
          HttpUtil().searchNewFrindsByPhone(searchStr, (int userId) {
            if (userId == null || userId == 0) {
              CustomUI.buildOneConfirm(context, I18n.of(context).not_have_user,
                  I18n.of(context).determine, () {
                Navigator.of(context).pop();
              });
              return;
            }
            if (userId == UserData().basicInfo.userId) {
              CustomUI.buildOneConfirm(context, I18n.of(context).not_add_Myself,
                  I18n.of(context).determine, () {
                Navigator.of(context).pop();
              });
              return;
            }
            Navigator.of(context).push(
              new MaterialPageRoute(
                builder: (context) {
                  return ProfilePage(userId: userId, addMode: 3);
                },
              ),
            );
          });
        },
        child: Container(
            margin: EdgeInsets.only(top: 9),
            height: 55.1,
            width: Screen.width,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              textBaseline: TextBaseline.ideographic,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(left: 20, right: 13),
                  width: Constants.ContactAvatarSize,
                  height: Constants.ContactAvatarSize,
                  decoration: BoxDecoration(
                      gradient: LinearGradient(
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                          colors: <Color>[
                            const Color(0xFF58B7F5),
                            const Color(0xFF1874C9),
                          ]),
                      borderRadius: BorderRadius.circular(6)),
                  child: Icon(
                    IconData(0xe662, fontFamily: Constants.IconFontFamily),
                    color: Colors.white,
                  ),
                ),
                RichText(
                  text: TextSpan(children: [
                    TextSpan(
                        text: '${I18n.of(context).search_phone}: ',
                        style: TextStyle(
                            color: Constants.BlackTextColor, fontSize: 16.23)),
                    TextSpan(
                        text: searchStr,
                        style: TextStyle(
                            color: Color(0xFF008AFF), fontSize: 16.23)),
                  ]),
                ),
              ],
            ),
            color: Colors.white));
  }

  Widget buildBody() {
    Widget result = Container();
    switch (widget.type) {
      case GlobalSearchPageType.SearchGroup:
        result = _buildSearchGroupBody();
        break;
      case GlobalSearchPageType.SearchMyFriends:
        result = _buildSearchMyfriendsBody();
        break;
      case GlobalSearchPageType.SearchNewFriends:
        result = _buildSearchNewfriendsBody();
        break;
      default:
    }
    return result;
  }

  //开始搜索群
  _beginSearchGroup(String str) {
    Map refMap = Provider.of<RefNameProvider>(context).refMap;
    List<GroupInfoModel> groupList = GroupInfoMgr().groupInfoList;
    searchList = CustomUI()
        .getGroupSearchResult(str, groupList == null ? [] : groupList, refMap);
  }

  //开始搜索自己好友
  _beginSearchMyFriends(String str) async {
    List<FriendModel> friendList = [];
    friendList = await FriendListMgr().getFriendList();
    searchList =
        CustomUI().getSearchResult(str, friendList == null ? [] : friendList);
  }

  beginSearch(String str) {
    switch (widget.type) {
      case GlobalSearchPageType.SearchGroup:
        _beginSearchGroup(str);
        break;
      case GlobalSearchPageType.SearchMyFriends:
        _beginSearchMyFriends(str);
        break;
      default:
    }
  }

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

    _body.add(buildBody());

    return Scaffold(
        resizeToAvoidBottomPadding: false,
        appBar: AppBar(
          backgroundColor: AppColors.NewAppbarBgColor,
          title: Text(I18n.of(context).search,
              textScaleFactor: 1.0, style: Constants.MainTitleStyle),
          centerTitle: true,
          elevation: 1,
          leading: CustomUI.buildCustomLeading(context),
          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(
                    keyboardType: TextInputType.text,
                    cursorColor: Constants.BlueTextColor,
                    textInputAction: TextInputAction.search,
                    controller: _txtCtrl,
                    maxLines: 1,
                    focusNode: focusNode,
                    style: TextStyle(
                        textBaseline: TextBaseline.alphabetic, fontSize: 14.5),
                    autofocus: true,
                    inputFormatters:
                        widget.type == GlobalSearchPageType.SearchNewFriends
                            ? [
                                WhitelistingTextInputFormatter.digitsOnly,
                                LengthLimitingTextInputFormatter(15),
                              ]
                            : [
                                LengthLimitingTextInputFormatter(50),
                              ],
                    decoration: InputDecoration(
                      hintText: I18n.of(context).search,
                      hintStyle: TextStyle(
                          fontSize: 14.5,
                          color: Colors.grey,
                          textBaseline: TextBaseline.alphabetic),
                      contentPadding: EdgeInsets.only(
                          left: 20,
                          top: (UserData().language == LanguageType.English ||
                                  UserData().language ==
                                      LanguageType.Vietnamese)
                              ? 3
                              : 10.5,
                          bottom: 10.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('')),
                    ),
                    onChanged: (str) async {
                      setState(() {
                        searchStr = str;
                        if (str.isEmpty) {
                          _hasdeleteIcon = false;
                        } else {
                          _hasdeleteIcon = true;
                          beginSearch(str);
                        }
                      });
                    },
                    onEditingComplete: () {
                      FocusScope.of(context).requestFocus(FocusNode());
                    }),
              )),
        ),
        body: Stack(
          children: _body,
        ));
  }
}
