import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:chat/home/global_search.dart';
import 'package:chat/home/new_friends.dart';
import 'package:chat/home/search_newfriend.dart';
import 'package:chat/models/friends_info.dart';
import 'package:flutter/material.dart';
import 'package:chat/data/UserData.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/conversation_table.dart';
import 'package:chat/utils/friend_list_mgr.dart';
import 'package:chat/utils/screen.dart';
import 'package:dio/dio.dart';
import 'package:oktoast/oktoast.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'address_book.dart';

List showUserList = [];

bool isHaveNewFriends() {
  return showUserList.length > 0;
}

class FriendPage extends StatefulWidget {
  @override
  _FriendPageState createState() => _FriendPageState();
}

class _FriendPageState extends State<FriendPage> {
  String _currentLetter = '';
  ScrollController _scrollController;

  List<FriendModel> friendList = [];

  List<Widget> _functionButtons = [];
  final Map _letterPosMap = {INDEX_BAR_WORDS[0]: 0.0};

  Set<String> userIdSet = new Set();

  //var _contactsFuture;
  @override
  void initState() {
    super.initState();

    print('FriendPage initState');
    initNewFriendsList([]);

    getFriendList();
    getNewFriendList(null);
    _scrollController = new ScrollController();
    MessageMgr().on('Add friend', msgAddfrend);
    MessageMgr().on('Delete friend', msgDeletefrend);
    MessageMgr().on('do_friend_apply', messageApply);
    MessageMgr().on('goto_new_friends', messageNew);
  }

  messageApply(data) {
    getNewFriendList(data);
  }

  messageNew(data) {
    gotoNewFriendsPage();
  }

  gotoNewFriendsPage() async {
    Navigator.of(context).push(
      new MaterialPageRoute(
        builder: (context) {
          return NewFriendsPage();
        },
      ),
    );
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setStringList(Constants.NewFriendsList, userIdSet.toList());
    showUserList = [];
    initNewFriendsList([]);
    setState(() {});
  }

  Widget _buildNewFriends(list) {
    if (list.length == 0) {
      return FriendsInfo(
          avatar: '',
          userId: 0,
          iconCode: 0xe66c,
          title: I18n.of(Constants.getCurrentContext()).new_friends,
          gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: <Color>[
                const Color(0xFF58B7F5),
                const Color(0xFF1874C9),
              ]),
          onPressed: gotoNewFriendsPage);
    } else {
      return _buildFriendsItem(list);
    }
  }

  Widget _buildAvatar(url) {
    return ClipRRect(
        borderRadius: BorderRadius.circular(6),
        child: CachedNetworkImage(
          imageUrl: url,
          placeholder: (context, url) => Image.asset(
            Constants.DefaultHeadImgUrl,
            width: Constants.ContactAvatarSize,
            height: Constants.ContactAvatarSize,
          ),
          width: Constants.ContactAvatarSize,
          height: Constants.ContactAvatarSize,
        ));
  }

  Widget _buildFriendsItem(list) {
    Widget unreadRedDot = Container(
      margin: EdgeInsets.only(right: 15),
      width: Constants.UnReadMsgNotifyDotSize,
      height: Constants.UnReadMsgNotifyDotSize,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius:
            BorderRadius.circular(Constants.UnReadMsgNotifyDotSize / 2.0),
        color: Color(0xFFFF5454),
      ),
      child: Text(list.length > 99 ? "99+" : list.length.toString(),
          textScaleFactor: 1.0, style: AppStyles.UnreadMsgCountDotStyle),
    );

    var left;
    if (list.length == 1) {
      left = Row(
        children: <Widget>[
          _buildAvatar(list[0]['ApplyUrl']),
          SizedBox(width: 10.0),
          Expanded(
              child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(list[0]['ApplyName'],
                  textScaleFactor: 1.0, style: TextStyle(fontSize: 12.66)),
              SizedBox(
                height: 5,
              ),
              Text(I18n.of(context).apply_fro_friends,
                  textScaleFactor: 1.0,
                  style:
                      TextStyle(fontSize: 10, color: const Color(0xFF6A6A6A))),
            ],
          )),
          unreadRedDot,
        ],
      );
    } else {
      left = Row(
        children: <Widget>[
          Expanded(
              child: Container(
                  height: Constants.ContactAvatarSize,
                  constraints: BoxConstraints(maxWidth: Screen.width - 100),
                  child: ListView(
                    scrollDirection: Axis.horizontal,
                    children: list
                        .map<Widget>((f) => Container(
                              child: _buildAvatar(f['ApplyUrl']),
                              margin: EdgeInsets.only(right: 5),
                            ))
                        .toList(),
                  ))),
          unreadRedDot,
        ],
      );
    }

    return InkWell(
        onTap: gotoNewFriendsPage,
        child: Container(
          padding: const EdgeInsets.symmetric(
              vertical: MARGIN_VERTICAL, horizontal: 16.0),
          decoration: BoxDecoration(color: Colors.white),
          child: left,
        ));
  }

  showPermission() async {
    if (await CustomUI.showPermissionSetting(
        Constants.getCurrentContext(),
        PermissionGroup.contacts,
        I18n.of(Constants.getCurrentContext()).contact_permission)) {
      MessageMgr().emit('PostContact');
      Navigator.push(Constants.getCurrentContext(),
          MaterialPageRoute<void>(builder: (BuildContext context) {
        return ContactsPage();
      }));
    }
  }

  getFriendList() async {
    friendList = await FriendListMgr().getFriendList();

    if (mounted) {
      setState(() {});
    }
  }

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

    Response res =
        await HttpUtil().post('friendship/newFriends/record', data: data);

    if (res == null) {
      return;
    }
    var resData = res.data;
    if (resData['code'] == 0) {
      if (resData['data'] != null) {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        List<String> list = prefs.getStringList(Constants.NewFriendsList);
        if (list != null) {
          userIdSet = new Set.from(list);
        } else {
          userIdSet = new Set();
        }

        if (userdata != null && userIdSet.contains(userdata['userId'])) {
          userIdSet.remove(userdata['userId']);
        }
        showUserList = [];

        for (int i = 0; i < resData['data'].length; i++) {
          if (!userIdSet
              .contains(resData['data'][i]['ApplyUserId'].toString())) {
            showUserList.add(resData['data'][i]);
            userIdSet.add(resData['data'][i]['ApplyUserId'].toString());
          }
        }

        initNewFriendsList(showUserList);
        if (mounted) {
          setState(() {});
        }
      }
    } else {
      showToast(resData['msg']);
    }
  }

  initNewFriendsList(showUserList) {
    _functionButtons = [
      FriendsInfo(
          avatar: '',
          userId: 0,
          iconCode: 0xe659,
          title: I18n.of(Constants.getCurrentContext()).scan,
          gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: <Color>[
                const Color(0xFF6171F1),
                const Color(0xFF3441C1),
              ]),
          onPressed: () {
            CustomUI().goScanPage(Constants.getCurrentContext());
          }),
      FriendsInfo(
          avatar: '',
          userId: 0,
          iconCode: 0xe67a,
          isShowDivder: true,
          title: I18n.of(Constants.getCurrentContext()).contact_add,
          gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: <Color>[
                const Color(0xFF1AC59E),
                const Color(0xFF088E76),
              ]),
          onPressed: () async {
            final PermissionStatus addStatus = await PermissionHandler()
                .checkPermissionStatus(PermissionGroup.contacts);
            if ((addStatus == PermissionStatus.unknown ||
                    addStatus == PermissionStatus.denied) &&
                Platform.isIOS) {
              CustomUI.buildContacts(context, I18n.of(context).privacyAgreement,
                  I18n.of(context).determine, () {
                Navigator.of(context).pop();
                showPermission();
              }, title: I18n.of(context).tip);
            } else {
              showPermission();
            }
          }),
      FriendsInfo(
          avatar: '',
          userId: 0,
          iconCode: 0xe662,
          isShowDivder: true,
          title: I18n.of(Constants.getCurrentContext()).add_friends,
          gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: <Color>[
                const Color(0xFF9E58E5),
                const Color(0xFF6118A6),
              ]),
          onPressed: () async {
            Navigator.push(Constants.getCurrentContext(),
                MaterialPageRoute<void>(builder: (BuildContext context) {
              return SearchNewFriendsPage();
            }));
          }),
    ];
    _functionButtons.insert(0, _buildNewFriends(showUserList));
  }

  msgAddfrend(data) {
    // setState(() {
    //   _contactsFuture = FriendListMgr().getFriendList();
    // });
    getFriendList();
  }

  msgDeletefrend(data) {
    // setState(() {
    //   _contactsFuture = FriendListMgr().getFriendList();
    // });
    getFriendList();
  }

  updateIndexPos(List<FriendModel> friendList) {
    //计算用于 IndexBar 进行定位的关键通讯录列表项的位置
    var _totalPos = _functionButtons.length * FriendsInfo.height(false);
    for (var i = 0; i < friendList.length; i++) {
      bool _hasGroupTitle = true;
      if (i > 0 &&
          friendList[i].nameTag.compareTo(friendList[i - 1].nameTag) == 0) {
        _hasGroupTitle = false;
      }

      if (_hasGroupTitle) {
        _letterPosMap[friendList[i].nameTag] = _totalPos;
      }
      _totalPos += FriendsInfo.height(_hasGroupTitle);
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();

    print('FriendPage dispose');

    MessageMgr().off('Add friend', msgAddfrend);
    MessageMgr().off('Delete friend', msgDeletefrend);
    MessageMgr().off('do_friend_apply', messageApply);
    MessageMgr().off('goto_new_friends', messageNew);
    super.dispose();
  }

  String getLetter(BuildContext context, double tileHeight, Offset globalPos) {
    RenderBox _box = context.findRenderObject();
    var local = _box.globalToLocal(globalPos);
    int index = (local.dy ~/ tileHeight).clamp(0, INDEX_BAR_WORDS.length - 1);
    return INDEX_BAR_WORDS[index];
  }

  void _jumpToIndex(String letter) {
    if (_letterPosMap.isNotEmpty) {
      final _pos = _letterPosMap[letter];
      if (_pos != null) {
        _scrollController.animateTo(_letterPosMap[letter],
            curve: Curves.easeInOut, duration: Duration(microseconds: 200));
      }
    }
  }

  Widget _buildIndexBar(BuildContext context, BoxConstraints constraints) {
    final List<Widget> _letters = INDEX_BAR_WORDS.map((String word) {
      return Expanded(
          child: Container(
              margin: EdgeInsets.only(right: 5),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color:
                    _currentLetter == word ? Colors.blue : Colors.transparent,
              ),
              alignment: Alignment.center,
              padding: EdgeInsets.all(2),
              width: 20,
              child: Text(
                word,
                textScaleFactor: 1.0,
                style: TextStyle(
                    fontSize: 10,
                    color:
                        _currentLetter == word ? Colors.white : Colors.black),
              )));
    }).toList();

    final _totalHeight = constraints.biggest.height;
    final _tileHeight = _totalHeight / _letters.length;
    return GestureDetector(
      onVerticalDragDown: (DragDownDetails details) {
        setState(() {
          _currentLetter =
              getLetter(context, _tileHeight, details.globalPosition);
          _jumpToIndex(_currentLetter);
        });
      },
      onVerticalDragEnd: (DragEndDetails details) {
        setState(() {
          //_indexBarBgColor = Colors.transparent;
          _currentLetter = null;
        });
      },
      onVerticalDragCancel: () {
        setState(() {
          //_indexBarBgColor = Colors.transparent;
          _currentLetter = null;
        });
      },
      onVerticalDragUpdate: (DragUpdateDetails details) {
        setState(() {
          //var _letter = getLetter(context, _tileHeight, details.globalPosition);
          _currentLetter =
              getLetter(context, _tileHeight, details.globalPosition);
          _jumpToIndex(_currentLetter);
        });
      },
      child: Column(
        children: _letters,
      ),
    );
  }

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

    friendList.sort((a, b) => a.nameTag.compareTo(b.nameTag));
    updateIndexPos(friendList);
    _body.addAll([
      ListView.builder(
        controller: _scrollController,
        itemBuilder: (BuildContext context, int index) {
          if (index < _functionButtons.length) {
            if (index == 0) {
              return Padding(
                padding: EdgeInsets.only(top: 7),
                child: _functionButtons[index],
              );
            } else {
              return _functionButtons[index];
            }
          }
          var result;
          int _contactIndex = index - _functionButtons.length;
          bool _isGroupTitle = true;
          FriendModel _contact = friendList[_contactIndex];

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

          result = FriendsInfo(
              userId: _contact.friendId,
              avatar: _contact.avatar,
              title: Provider.of<RefNameProvider>(context)
                  .getRefName(_contact.friendId, _contact.name),
              isShowDivder: true,
              groupTitle: _isGroupTitle ? _contact.nameTag : null);

          if (index == (friendList.length + _functionButtons.length - 1)) {
            return result = Column(
              children: <Widget>[
                result,
                Container(
                  height: 50,
                  color: Colors.white,
                  child: Text(I18n.of(context)
                      .total_friends_nus
                      .replaceFirst('/s1', friendList.length.toString())),
                  alignment: Alignment.center,
                  width: Screen.width,
                ),
              ],
            );
          }
          return result;
        },
        itemCount: friendList.length + _functionButtons.length,
      ),
      Positioned(
        width: Constants.IndexBarWidth,
        right: 0.0,
        top: 0.0,
        bottom: 0.0,
        child: Container(
          //color: _indexBarBgColor,
          child: LayoutBuilder(
            builder: _buildIndexBar,
          ),
        ),
      )
    ]);

    if (_currentLetter != null && _currentLetter.isNotEmpty) {
      _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,
                textScaleFactor: 1.0, style: Constants.MainTitleStyle),
            centerTitle: false,
            elevation: 1,
            bottom: CustomUI.buildSearchButton(context, () {
              Navigator.of(context).push(
                new MaterialPageRoute(
                  builder: (context) {
                    return GlobalSearchPage(
                      type: GlobalSearchPageType.SearchMyFriends,
                    );
                  },
                ),
              );
            })),
        body: Stack(
          children: _body,
        ));
  }
}
