import 'package:chat/models/im/custom_message_model.dart';
import 'package:chat/models/im/location_model.dart';
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/V2TimConversationListener.dart';
import 'package:tencent_im_sdk_plugin/enum/conversation_type.dart';
import 'package:tencent_im_sdk_plugin/enum/receive_message_opt_enum.dart';
import 'package:tencent_im_sdk_plugin/manager/v2_tim_conversation_manager.dart';
import 'package:tencent_im_sdk_plugin/manager/v2_tim_message_manager.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_callback.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_msg_create_info_result.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

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

  /// 消息管理实例
  V2TIMMessageManager get messageManager =>
      TimService.to.instance.v2TIMMessageManager;

  /// 会话管理
  V2TIMConversationManager get conversationManager =>
      TimService.to.instance.v2ConversationManager;

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

  _addListener() {
    conversationManager.addConversationListener(
        listener: V2TimConversationListener(

            /// 未读消息总数监听
            onTotalUnreadMessageCountChanged: (_) {
      unreadCount.value = _;
    }));
  }

  /// 会话列表
  RxList<V2TimConversation?> conversationList =
      List<V2TimConversation?>.empty(growable: true).obs;

  /// 未读消息总数
  var unreadCount = 0.obs;

  Future<void> fetchList() async {
    var data = await conversationManager.getConversationList(
      count: 100,
      nextSeq: '0',
    );

    if (data.code == 0) {
      conversationList.value = data.data!.conversationList!;
    }
  }

  /// 获取未读消息数
  Future<void> getUnreadCount() async {
    var result = await conversationManager.getTotalUnreadMessageCount();
    unreadCount.value = result.data ?? 0;
  }

  /// 获取会话信息
  Future<V2TimConversation> getById(
    String conversationID,
  ) async {
    var result = await conversationManager.getConversation(
      conversationID: conversationID,
    );
    return result.data!;
  }

  /// 标记会话已读
  Future<void> markAsRead(V2TimConversation conversation) async {
    /// 标记会话内消息已读
    if (conversation.type == ConversationType.V2TIM_GROUP) {
      await messageManager.markGroupMessageAsRead(
        groupID: conversation.groupID!,
      );
    } else {
      await messageManager.markC2CMessageAsRead(
        userID: conversation.userID!,
      );
    }
    fetchList();
  }

  /// 从会话列表移除会话
  Future<void> delete(V2TimConversation conversation) async {
    await deleteById(conversation.conversationID);
    fetchList();
  }

  Future<void> deleteById(String conversationID) async {
    await conversationManager.deleteConversation(
      conversationID: conversationID,
    );
    fetchList();
  }

  /// 清空会话历史消息
  Future<void> clearHistoryMessage(V2TimConversation conversation) async {
    if (conversation.type == ConversationType.V2TIM_GROUP) {
      await messageManager.clearGroupHistoryMessage(
        groupID: conversation.groupID!,
      );
    } else {
      await messageManager.clearC2CHistoryMessage(
        userID: conversation.userID!,
      );
    }
    fetchList();
  }

  /// 设置会话置顶/取消置顶
  Future<bool> setOnTop(V2TimConversation conversation) async {
    var result = await conversationManager.pinConversation(
      conversationID: conversation.conversationID,
      isPinned: !conversation.isPinned!,
    );
    fetchList();

    if (result.code != 0) {
      UiTools.toast(result.desc);
    }

    return result.code == 0;
  }

  /// 开启/关闭消息免打扰
  Future<bool> setReceiveOpt(
    V2TimConversation conversation,
  ) async {
    V2TimCallback result;

    if (conversation.type == ConversationType.V2TIM_GROUP) {
      result = await messageManager.setGroupReceiveMessageOpt(
        groupID: conversation.groupID!,
        opt: (conversation.recvOpt == 0)
            ? ReceiveMsgOptEnum.V2TIM_NOT_RECEIVE_MESSAGE
            : ReceiveMsgOptEnum.V2TIM_RECEIVE_MESSAGE,
      );
    } else {
      result = await messageManager.setC2CReceiveMessageOpt(
        userIDList: [
          conversation.userID!,
        ],
        opt: (conversation.recvOpt == 0)
            ? ReceiveMsgOptEnum.V2TIM_NOT_RECEIVE_MESSAGE
            : ReceiveMsgOptEnum.V2TIM_RECEIVE_MESSAGE,
      );
    }

    fetchList();

    return result.code == 0;
  }

  /// 发送消息
  Future<bool> sendTextMessage(
    V2TimConversation conversation,
    String text,
  ) async {
    var msg = await messageManager.createTextAtMessage(
      text: text,
      atUserList: [],
    );
    if (msg.code == 0) {
      return await _sendMessage(conversation, msg.data!);
    } else {
      UiTools.toast(msg.desc);
      return false;
    }
  }

  /// 发送图片消息
  Future<bool> sendImageMessage(
    V2TimConversation conversation,
    AssetEntity asset,
  ) async {
    var msg = await messageManager.createImageMessage(
      imagePath: (await asset.file)!.path,
    );
    if (msg.code == 0) {
      return await _sendMessage(conversation, msg.data!);
    } else {
      UiTools.toast(msg.desc);
      return false;
    }
  }

  /// 发送语音消息
  Future<bool> sendSoundMessage(
    V2TimConversation conversation,
    String soundPath,
    int duration,
  ) async {
    var msg = await messageManager.createSoundMessage(
        soundPath: soundPath, duration: duration);
    if (msg.code == 0) {
      return await _sendMessage(conversation, msg.data!);
    } else {
      UiTools.toast(msg.desc);
      return false;
    }
  }

  /// 发送视频消息
  Future<bool> sendVideoMessage(
    V2TimConversation conversation,
    AssetEntity asset,
  ) async {
    return false;
    // final originFile = await asset.originFile;
    // var size = await originFile!.length();

    // if (size >= 104857600) {
    //   UiTools.toast('视频文件不能超过100M');
    //   return false;
    // }

    // final duration = asset.videoDuration.inSeconds;

    // String tempPath = (await getTemporaryDirectory()).path;
    // String? thumbnail = await VideoThumbnail.thumbnailFile(
    //   video: originFile.path,
    //   thumbnailPath: tempPath,
    //   imageFormat: ImageFormat.JPEG,
    //   maxWidth: 256,
    //   quality: 25,
    // );

    // var msg = await messageManager.createVideoMessage(
    //   videoFilePath: originFile.path,
    //   type: asset.mimeType!.replaceFirst('video/', ''),
    //   duration: duration,
    //   snapshotPath: thumbnail ?? '',
    // );
    // if (msg.code == 0) {
    //   return await _sendMessage(conversation, msg.data!);
    // } else {
    //   UiTools.toast(msg.desc);
    //   return false;
    // }
  }

  /// 发送文件消息
  Future<bool> sendFileMessage(
    V2TimConversation conversation,
    String fileName,
    String filePath,
  ) async {
    var msg = await messageManager.createFileMessage(
      fileName: fileName,
      filePath: filePath,
    );
    if (msg.code == 0) {
      return await _sendMessage(conversation, msg.data!);
    } else {
      UiTools.toast(msg.desc);
      return false;
    }
  }

  /// 发送位置消息
  Future<bool> sendLocationMessage(
    V2TimConversation conversation,
    LocationModel messageModel,
  ) async {
    var msg = await messageManager.createLocationMessage(
      desc: messageModel.name,
      latitude: messageModel.latitude,
      longitude: messageModel.longitude,
    );
    if (msg.code == 0) {
      return await _sendMessage(conversation, msg.data!);
    } else {
      UiTools.toast(msg.desc);
      return false;
    }
  }

  /// 发送表情消息
  Future<bool> sendFaceMessage(
    V2TimConversation conversation,
  ) async {
    var msg = await messageManager.createFaceMessage(
      data: '',
      index: 0,
    );
    if (msg.code == 0) {
      return await _sendMessage(conversation, msg.data!);
    } else {
      UiTools.toast(msg.desc);
      return false;
    }
  }

  /// 发送聊天记录消息
  Future<bool> sendMergerMessage(
    V2TimConversation conversation,
  ) async {
    var msg = await messageManager.createMergerMessage(
      abstractList: [],
      compatibleText: '',
      msgIDList: [],
      title: '',
    );
    if (msg.code == 0) {
      return await _sendMessage(conversation, msg.data!);
    } else {
      UiTools.toast(msg.desc);
      return false;
    }
  }

  /// 发送自定义消息
  Future<bool> sendCustomMessage(
    V2TimConversation conversation,
    CustomMessageModel customMessageModel,
    String desc,
  ) async {
    var msg = await messageManager.createCustomMessage(
      data: customMessageModel.toJson(),
      desc: desc,
    );
    if (msg.code == 0) {
      return await _sendMessage(conversation, msg.data!);
    } else {
      UiTools.toast(msg.desc);
      return false;
    }
  }

  /// 发送消息
  Future<bool> _sendMessage(
    V2TimConversation conversation,
    V2TimMsgCreateInfoResult result,
  ) async {
    var sendMessageRes = await messageManager.sendMessage(
      id: result.id!,
      receiver: conversation.type == ConversationType.V2TIM_C2C
          ? conversation.userID!
          : '',
      groupID: conversation.type == ConversationType.V2TIM_GROUP
          ? conversation.groupID!
          : '',
      // isExcludedFromUnreadCount: true,
      // isExcludedFromLastMessage: true,
      // needReadReceipt: true,
    );

    if (sendMessageRes.code == 0) {
      // TimMessageService.to
      //     .add(conversation.conversationID, result.messageInfo!);
      fetchList();
      return true;
    } else {
      UiTools.toast(sendMessageRes.desc);
      return false;
    }
  }

  /// 设置会话草稿
  Future<void> draft(
    V2TimConversation conversation, {
    String? draftText = "",
  }) async {
    await conversationManager.setConversationDraft(
      conversationID: conversation.conversationID,
      draftText: draftText,
    );
  }
}
