import 'package:chat/services/tim_service.dart';
import 'package:chat/utils/ui_tools.dart';
import 'package:get/get.dart';
import 'package:tencent_im_sdk_plugin/enum/friend_application_type_enum.dart';
import 'package:tencent_im_sdk_plugin/enum/friend_response_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_application.dart';

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

  /// 好友申请
  RxList<V2TimFriendApplication?> applies =
      List<V2TimFriendApplication?>.empty(growable: true).obs;

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

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

  /// 获取申请列表
  Future<void> fetchList() async {
    var applyList = await friendshipManager.getFriendApplicationList();
    if (applyList.code == 0) {
      applies.value = applyList.data!.friendApplicationList!;
    }
  }

  /// 接受好友请求
  Future<bool> accept(String userID) async {
    var result = await friendshipManager.acceptFriendApplication(
      responseType: FriendResponseTypeEnum.V2TIM_FRIEND_ACCEPT_AGREE_AND_ADD,
      type: FriendApplicationTypeEnum.V2TIM_FRIEND_APPLICATION_COME_IN,
      userID: userID,
    );

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