
import 'dart:io';

import 'package:get/get.dart';

import '../models/index.dart';
import '../utils/index.dart';
import '../values/index.dart';

///
/// 消息服务
/// 
class MessageCommunicationService extends GetxService {
  
  static MessageCommunicationService get to => Get.find();

  String baseUrl() {
    return O2ApiManager.instance.getModuleBaseUrl(
        O2DistributeModuleEnum.x_message_assemble_communicate) ?? '';
  }

  /// 
  /// 图片地址
  String getIMMsgImageUrl(String fileId, {int width = 144, int height = 192}) {
     return '${baseUrl()}jaxrs/im/msg/download/$fileId/image/width/$width/height/$height';
  }

  ///
  /// 文件、图片、音频文件等下载地址
  /// 
  String getIMMsgDownloadFileUrl(String fileId) {
    return '${baseUrl()}jaxrs/im/msg/download/$fileId';
  }


  ///
  /// 获取ImConfig
  /// 
  Future<IMConfigData?> getImConfig() async {
    try {
      ApiResponse response = await O2HttpClient.instance.get('${baseUrl()}jaxrs/im/manager/config');
      IMConfigData mode = IMConfigData.fromJson(response.data);
      return mode;
    } catch (err, stackTrace) {
      OLogger.e('获取ImConfig失败', err, stackTrace);
    }
    return null;
  }


  ///
  /// 创建会话
  ///
  Future<IMConversationInfo?> createConversation(String type, List<String> personList) async {
    try {
      ApiResponse response = await O2HttpClient.instance
          .post('${baseUrl()}jaxrs/im/conversation', {'type': type, 'personList': personList});
      IMConversationInfo info = IMConversationInfo.fromJson(response.data);
      return info;
    } catch (err, stackTrace) {
      OLogger.e('创建会话失败', err, stackTrace);
    }
    return null;
  }

  ///
  /// 更新会话
  ///
  Future<IMConversationInfo?> updateConversation(IMConversationInfo form) async {
    try {
      ApiResponse response = await O2HttpClient.instance
          .put('${baseUrl()}jaxrs/im/conversation', form.toJson());
      IMConversationInfo info = IMConversationInfo.fromJson(response.data);
      return info;
    } catch (err, stackTrace) {
      OLogger.e('更新会话失败', err, stackTrace);
    }
    return null;
  }

  ///
  /// 获取会话
  ///
  Future<IMConversationInfo?> getConversation(String id) async {
    try {
      ApiResponse response = await O2HttpClient.instance.get('${baseUrl()}jaxrs/im/conversation/$id');
      IMConversationInfo info = IMConversationInfo.fromJson(response.data);
      return info;
    } catch (err, stackTrace) {
      OLogger.e('获取会话失败', err, stackTrace);
    }
    return null;
  }

  /// 删除会话
  /// 单聊会话是虚拟删除
  Future<ValueBoolData?> deleteSingleConversation(String id) async {
    try {
      ApiResponse response = await O2HttpClient.instance.delete('${baseUrl()}jaxrs/im/conversation/$id/single');
      return ValueBoolData.fromJson(response.data);
    } catch (err, stackTrace) {
      OLogger.e('删除会话失败', err, stackTrace);
    }
    return null;
  }
  /// 删除会话
  /// 群聊会话是真实删除 需要管理员
  Future<ValueBoolData?> deleteGroupConversation(String id) async {
    try {
      ApiResponse response = await O2HttpClient.instance.delete('${baseUrl()}jaxrs/im/conversation/$id/group');
      return ValueBoolData.fromJson(response.data);
    } catch (err, stackTrace) {
      OLogger.e('删除会话失败', err, stackTrace);
    }
    return null;
  }


  /// 系统消息
  ///
  /// 直接查询 instant 对象 不正确 没有配置消息通道也会有消息
  /// 改成查 pmsinner  通道的消息列表
  Future<List<InstantMsg>?> myInstantMsgList(int count) async {
    try {
      final map = {
        "person": O2ApiManager.instance.o2User?.distinguishedName,
        "consume": "pmsinner"
      };
      // ApiResponse response = await O2HttpClient.instance.get('${baseUrl()}jaxrs/instant/list/currentperson/noim/count/$count/desc');
      ApiResponse response = await O2HttpClient.instance.post('${baseUrl()}jaxrs/message/list/paging/1/size/100', map); // 不需要全部数据
      var list = response.data == null ? [] : response.data as List;
      return list.map((e) => InstantMsg.fromJson(e)).toList();
    } catch (err, stackTrace) {
      OLogger.e('获取我的系统消息列表失败', err, stackTrace);
    }
    return null;
  }

  ///
  /// 我的会话列表
  ///
  Future<List<IMConversationInfo>?> myConversationList() async {
    try {
      ApiResponse response = await O2HttpClient.instance.get('${baseUrl()}jaxrs/im/conversation/list/my');
      var list = response.data == null ? [] : response.data as List;
      return list.map((e) => IMConversationInfo.fromJson(e)).toList();
    } catch (err, stackTrace) {
      OLogger.e('获取我的会话列表失败', err, stackTrace);
    }
    return null;
  }

  ///
  /// 阅读会话消息
  ///
  Future<IdData?> readConversation(String id) async {
    try {
      ApiResponse response = await O2HttpClient.instance
          .put('${baseUrl()}jaxrs/im/conversation/$id/read', {});
      IdData info = IdData.fromJson(response.data);
      return info;
    } catch (err, stackTrace) {
      OLogger.e('阅读会话消息失败', err, stackTrace);
    }
    return null;
  }

  ///
  /// 发送消息
  ///
  Future<IdData?> sendMessage(IMMessage message) async {
    try {
      ApiResponse response = await O2HttpClient.instance
          .post('${baseUrl()}jaxrs/im/msg', message.toJson());
      IdData info = IdData.fromJson(response.data);
      return info;
    } catch (err, stackTrace) {
      OLogger.e('发送消息失败', err, stackTrace);
    }
    return null;
  }

  ///
  /// 我的会话列表
  ///
  Future<IMMessagePageData?> conversationMessageByPage(String conversationId, int page, {int limit = O2.o2DefaultPageSize}) async {
    try {
      ApiResponse response = await O2HttpClient.instance.post('${baseUrl()}jaxrs/im/msg/list/$page/size/$limit', {"conversationId": conversationId});
      var list = response.data == null ? [] : response.data as List;
      List<IMMessage> msgList = list.map((e) => IMMessage.fromJson(e)).toList();
      // // 根据消息时间 倒转顺序
      // msgList.sort(((a, b) => a.createTime!.compareTo(b.createTime!)));
      int total = response.count ?? 1;
      var totalPage = (total % limit != 0) ? total ~/ limit + 1 : total ~/ limit;
      return IMMessagePageData(page: page, totalPage: totalPage, list: msgList);
    } catch (err, stackTrace) {
      OLogger.e('获取我的会话列表失败', err, stackTrace);
    }
    return null;
  }

  ///
  /// 上传文件到im
  /// 
  Future<IMMessageFileResponse?> uploadFileToIM(String conversationId, String type, File file) async {
    try {
      ApiResponse response = await O2HttpClient.instance.postUploadFile('${baseUrl()}jaxrs/im/msg/upload/$conversationId/type/$type', file);
      return IMMessageFileResponse.fromJson(response.data);
    } catch (err, stackTrace) {
      OLogger.e('上传文件失败', err, stackTrace);
    }
    return null;
  }

  ///
  /// 清空会话内的消息
  ///
  Future<ValueBoolData?> deleteAllChatMsg(String conversationId) async {
    try {
      ApiResponse response = await O2HttpClient.instance
          .delete('${baseUrl()}jaxrs/im/conversation/$conversationId/clear/all/msg');
      return ValueBoolData.fromJson(response.data);
    } catch (err, stackTrace) {
      OLogger.e('清空会话内的消息失败', err, stackTrace);
    }
    return null;
  }

  ///
  /// 撤回消息
  ///
  Future<IdData?> revokeMessage(String msgId) async {
    try {
      ApiResponse response = await O2HttpClient.instance
          .get('${baseUrl()}jaxrs/im/msg/revoke/$msgId' );
      return IdData.fromJson(response.data);
    } catch (err, stackTrace) {
      OLogger.e('撤回失败', err, stackTrace);
    }
    return null;
  }


}