import 'package:get/get.dart';

import '../../../common/api/index.dart';
import '../../../common/models/index.dart';
import '../../../common/utils/index.dart';
import '../../../common/values/index.dart';
import '../contact/contact_picker/index.dart';
import 'im_chat/index.dart';
import 'index.dart';
import 'instant_chat/index.dart';
import 'speech_assistant_chat/index.dart';

class ImController extends GetxController {
  ImController();

  final state = ImState();
  Map<String, String> headers = {};
  EventBus eventBus = EventBus();
  final eventId = 'IM';
  List<InstantMsg> instantMsgList = [];
  InstantMsg? instantMsg;

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
     //监听websocket消息
    eventBus.on(EventBus.websocketCreateImMsg, eventId, (arg) {
      OLogger.d("收到websocket im 新消息！刷新会话列表");
      if (arg is IMMessage) {
        loadConversationList();
      }
    });
    eventBus.on(EventBus.websocketImConversationDeleteMsg, eventId, (arg) {
      OLogger.d("收到websocket 删除会话消息！刷新会话列表");
      loadConversationList();
    });
    eventBus.on(EventBus.websocketImConversationUpdateMsg, eventId, (arg) {
      OLogger.d("收到websocket 更新会话消息！刷新会话列表");
      loadConversationList();
    });
    headers[O2ApiManager.instance.tokenName] =
        O2ApiManager.instance.o2User?.token ?? '';
    final extend = ProgramCenterService.to.extendParam();
    final isShow = extend['showIMSpeechButton'] ?? false;
    state.showSpeechAssistant =  isShow;
    loadConversationList();
    super.onReady();
  }


  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    eventBus.off(EventBus.websocketCreateImMsg, eventId);
    eventBus.off(EventBus.websocketImConversationDeleteMsg, eventId);
    eventBus.off(EventBus.websocketImConversationUpdateMsg, eventId);
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  // 语音助手
  void startSpeechAssistant() {
    SpeechAssistantChatPage.open();
  }

  Future<void> startSingleChat() async {
    var result = await ContactPickerPage.startPicker([ContactPickMode.personPicker]);
    if (result is ContactPickerResult) {
      if (result.users != null && result.users!.isNotEmpty) {
        if (result.users![0].distinguishedName! == O2ApiManager.instance.o2User?.distinguishedName) {
          Loading.toast('im_msg_create_conversation_not_with_self'.tr);
          return;
        }
        createConversation(O2.imConversationTypeSingle, [result.users![0].distinguishedName!]);
      }
    }
  }

  Future<void> startGroupChat() async {
    var result = await ContactPickerPage.startPicker([ContactPickMode.personPicker], multiple: true);
    if (result is ContactPickerResult) {
      List<String> personList = [];
      result.users?.forEach((element) {
        personList.add(element.distinguishedName!);
      });
      createConversation(O2.imConversationTypeGroup, personList);
    }
  }

  Future<void> createConversation(String type, List<String> personList) async {
    if (type.isEmpty || personList.isEmpty) {
      return;
    }
    final conv = await MessageCommunicationService.to.createConversation(type, personList);
    if (conv != null) {
      tapOpenConversation(conv);
    }
  }


  /// 获取会话列表
  Future<void> loadConversationList() async {
    if (ProgramCenterService.to.isShowSystemMessage()) {
      loadInstantMsgList();
    } else {
      state.showInstantMsg = false;
    }

    var list = await MessageCommunicationService.to.myConversationList();
    if (list != null && list.isNotEmpty) {
      state.conversationList.clear();
      state.conversationList.addAll(list);
    }
    int unReadNumber = 0;
    for (var element in state.conversationList) {
      unReadNumber += element.unreadNumber??0;
    }
    eventBus.emit(EventBus.imUnReadNumberMsg, unReadNumber);
  }

  Future<void> loadInstantMsgList() async {
    final list = await MessageCommunicationService.to.myInstantMsgList(15);
    if (list == null || list.isEmpty) {
      state.showInstantMsg = false;
      return;
    }
    final newList = list.where((element) => element.type?.startsWith('im_') == false).toList(); // im 消息不显示
    instantMsgList.clear();
    instantMsgList.addAll(newList);
    instantMsg = instantMsgList.first;
    state.showInstantMsg = true;
  }

  /// 单聊 人员头像
  String? personIconUrl(IMConversationInfo info) {
    // 单聊
    if (info.type == O2.imConversationTypeSingle) {
      var otherParty = info.personList?.firstWhereOrNull((element) => element != O2ApiManager.instance.o2User?.distinguishedName);
      if (otherParty != null && otherParty.isNotEmpty) {
        return OrganizationControlService.to.iconUrl(otherParty);
      }
    }
    return null;
  }

  /// 聊天会话
  Future<void> tapOpenConversation(IMConversationInfo info) async {
    OLogger.d("点击会话。。。。");
    await ImChatPage.open(info.id!);
    loadConversationList();
  }
  /// 系统消息
  Future<void> clickInstant() async {
    OLogger.d('点击了 系统消息');
    await InstantChatPage.open();
    loadConversationList();
  }


}
