import 'package:azlistview/azlistview.dart';
import 'package:chat/models/im/contact_info_model.dart';
import 'package:chat/routes/contact_routes.dart';
import 'package:chat/services/tim_service.dart';
import 'package:chat/utils/im_tools.dart';
import 'package:chat/utils/ui_tools.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:tencent_im_sdk_plugin/enum/friend_type_enum.dart';
import 'package:tencent_im_sdk_plugin/manager/v2_tim_friendship_manager.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_check_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info_result.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';

class TimFriendService extends GetxService {
  static TimFriendService get to => Get.find<TimFriendService>();

  /// 好友关系
  V2TIMFriendshipManager get friendshipManager =>
      TimService.to.instance.v2TIMFriendshipManager;

  /// 好友列表
  var friends = List<V2TimFriendInfo>.empty(growable: true).obs;

  /// 格式化后的联系人信息
  var contacts = List<ContactInfoModel>.empty(growable: true).obs;

  final List<ContactInfoModel> _topList = [
    ContactInfoModel(
      name: '新的朋友',
      userID: '',
      tagIndex: '@',
      icon: Icons.person_add_alt,
      color: Colors.amber,
      route: ContactRoutes.friendRequest,
    ),
    ContactInfoModel(
      name: '群聊',
      userID: '',
      tagIndex: '@',
      icon: Icons.group,
      color: Colors.green,
      route: ContactRoutes.group,
    ),
    ContactInfoModel(
      name: '订阅消息',
      userID: '',
      tagIndex: '@',
      icon: Icons.mark_email_read,
      color: Colors.blue,
    ),
  ];

  @override
  void onInit() async {
    super.onInit();
    await fetchList();
  }

  Future<void> fetchList() async {
    var result = await friendshipManager.getFriendList();
    if (result.code == 0) {
      friends.value = result.data!;
      contacts.clear();
      for (var element in result.data!) {
        String name = ImTools.parseNicknameFromInfo(element);
        String pinyin = PinyinHelper.getPinyinE(name);
        String tag = pinyin.substring(0, 1).toUpperCase();

        if (!RegExp('[A-Z]').hasMatch(tag)) {
          tag = '#';
        }

        contacts.add(ContactInfoModel(
          name: name,
          userID: element.userID,
          tagIndex: tag,
          namePinyin: pinyin,
          friendInfo: element,
        ));
      }

      SuspensionUtil.sortListBySuspensionTag(contacts);
      SuspensionUtil.setShowSuspensionStatus(contacts);
      contacts.insertAll(0, _topList);
    }
  }

  /// 添加好友
  Future<bool> add(
    String userID, {
    String? remark,
    String? addWording,
    String? addSource,
  }) async {
    var result = await friendshipManager.addFriend(
      userID: userID,
      remark: remark,
      addWording: addWording,
      addSource: addSource,
      addType: FriendTypeEnum.V2TIM_FRIEND_TYPE_BOTH,
    );
    if (result.code == 0) {
      if (result.data!.resultCode == 0) {
        fetchList();
        return true;
      } else if (result.data!.resultCode == 30539) {
        return true;
      } else if (result.data!.resultCode == 30010) {
        UiTools.toast('好友数量已达上限');
        return false;
      } else {
        UiTools.toast(
            result.data!.resultInfo! + result.data!.resultCode.toString());
        return false;
      }
    }
    UiTools.toast(result.desc);
    return false;
  }

  /// 删除双向好友
  Future<bool> delete(String userID) async {
    var result = await friendshipManager.deleteFromFriendList(
      deleteType: FriendTypeEnum.V2TIM_FRIEND_TYPE_BOTH,
      userIDList: [userID],
    );

    if (result.code == 0) {
      fetchList();
      return result.data!.first.resultCode == 0;
    } else {
      UiTools.toast(result.desc);
      return false;
    }
  }

  /// 检测好友是否有双向（单向）好友关系。
  Future<V2TimFriendCheckResult?> check(String userID) async {
    var result = await friendshipManager.checkFriend(
      checkType: FriendTypeEnum.V2TIM_FRIEND_TYPE_BOTH,
      userIDList: [userID],
    );

    if (result.code == 0) {
      return result.data!.first;
    } else {
      UiTools.toast(result.desc);
      return null;
    }
  }

  /// 获取用户资料
  Future<V2TimUserFullInfo?> userInfo(String userID) async {
    var result = await TimService.to.instance.getUsersInfo(
      userIDList: [userID],
    );

    if (result.code == 0) {
      return result.data!.first;
    }

    UiTools.toast(result.desc);
    return null;
  }

  /// 获取好友资料
  Future<V2TimFriendInfoResult?> friendInfo(String userID) async {
    var result = await friendshipManager.getFriendsInfo(userIDList: [userID]);

    if (result.code == 0) {
      if (result.data!.isNotEmpty) {
        return result.data!.first;
      } else {
        return null;
      }
    }

    UiTools.toast(result.desc);
    return null;
  }

  /// 修改个人资料
  Future<bool> setSelfInfo({
    String? nickname,
    String? avatar,
  }) async {
    var result = await TimService.to.instance.setSelfInfo(
      userFullInfo: V2TimUserFullInfo(
        nickName: nickname,
        faceUrl: avatar,
      ),
    );

    if (result.code == 0) {
      //   TimService.to.fetchSelfInfo();
      return true;
    }
    UiTools.toast(result.desc);
    return false;
  }

  /// 设置是否允许陌生人消息
  Future<bool> allowStrangerMessage() async {
    var result = await TimService.to.instance.setSelfInfo(
      userFullInfo: V2TimUserFullInfo(
        customInfo: {
          'Stranger': 'TRUE',
        },
      ),
    );

    if (result.code == 0) {
      return true;
    }
    UiTools.toast(result.desc);
    return false;
  }

  /// 禁止陌生人消息
  Future<bool> forbidStrangerMessage() async {
    var result = await TimService.to.instance.setSelfInfo(
      userFullInfo: V2TimUserFullInfo(
        customInfo: {
          'Stranger': '',
        },
      ),
    );
    if (result.code == 0) {
      return true;
    }
    return false;
  }

  /// 修改好友备注信息
  Future<bool> setFriendRemark(
    String userID,
    String friendRemark,
  ) async {
    var result = await friendshipManager.setFriendInfo(
      userID: userID,
      friendRemark: friendRemark,
    );

    if (result.code == 0) {
      return true;
    }
    UiTools.toast(result.desc);
    return false;
  }
}
