//
//  YHIMHelper.swift
//  galaxy
//
//  Created by alexzzw on 2024/11/27.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import HyphenateChat
import UIKit

enum YHChatRoomCustomEvent: String {
    // 直播开始
    case liveStart = "chatRoomCustomEventLiveStart"
    // 直播结束
    case liveEnd = "chatRoomCustomEventLiveEnd"
    // 直播暂停
    case livePause = "chatRoomCustomEventLivePause"
    // 直播恢复
    case liveResume = "chatRoomCustomEventLiveResume"
    // 直播商品刷新
    case liveGoodsRefresh = "chatRoomCustomEventLiveGoodsRefresh"
}

struct YHChatRoomCustomLocal {
    static let tipsEvent = "YHLiveRoomTips"
    static let tipsKey = "tips"
    static let userEnterRoomEvent = "userEnterRoomEvent"    //用户进入聊天室 事件
}

class YHIMHelper: NSObject {
    static let didLoginEaseIMSuccess = Notification.Name("com.YHIMHelper.didLoginEaseIMSuccess")
    static let didLogOutEaseIM = Notification.Name("com.YHIMHelper.didLogOutEaseIM")
    static let didChatManagerReceiveMessages = Notification.Name("com.YHIMHelper.didChatManagerReceiveMessages")
    static let didUserEnterRoomMessages = Notification.Name("com.YHIMHelper.didUserEnterRoomMessages")//用户进入直播间
    private let viewModel = YHLiveSalesViewModel()

    var isCurrentUserLogin: Bool {
        guard let userId = YHLoginManager.shared.userModel?.id, userId.count > 0 else {
            return false
        }
        if EMClient.shared().isLoggedIn, EMClient.shared().currentUsername == "\(userId)" {
            return true
        }
        return false
    }
    
    var currentNickname: String {
        return viewModel.huanXinTokenModel?.nickname ?? ""
        //return viewModel.huanXinUserInfoModel?.nickname ?? ""
    }

    static let shared: YHIMHelper = {
        let helper = YHIMHelper()
        return helper
    }()
    
    static func sharedHelper() -> YHIMHelper {
        return shared
    }

    override private init() {
        super.init()
        initHelper()
        setupNotification()
        newRegisterAndLoginCurrentUser { success in
            printLog("registerAndLoginCurrentUser: \(success)")
        }
    }

    deinit {
        EMClient.shared().remove(self)
        EMClient.shared().removeDelegate(self)
        EMClient.shared().roomManager?.remove(self)
        EMClient.shared().chatManager?.remove(self)
        NotificationCenter.default.removeObserver(self)
    }

    private func initHelper() {
        EMClient.shared().addMultiDevices(delegate: self, queue: nil)
        EMClient.shared().add(self, delegateQueue: nil)
        EMClient.shared().roomManager?.add(self, delegateQueue: nil)
        EMClient.shared().chatManager?.add(self, delegateQueue: nil)
    }

    private func setupNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: YhConstant.YhNotification.didLoginSuccessNotifiction, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(logoutSuccess), name: YhConstant.YhNotification.didLogoutSuccessNotifiction, object: nil)
    }

    /*
    func registerAndLoginCurrentUser(completion: @escaping (Bool) -> Void) {
        guard let userId = YHLoginManager.shared.userModel?.id, userId.count > 0 else {
            completion(false)
            return
        }
        viewModel.registerHuanXinUser { [weak self] success, _ in
            guard let self = self else {
                completion(false)
                return
            }
            // 注册成功
            if success {
                viewModel.getHuanXinToken { [weak self] tokenModel, _ in
                    guard let tokenModel = tokenModel else {
                        completion(false)
                        return
                    }
                    guard let self = self else {
                        completion(false)
                        return
                    }
                    let token = tokenModel.accessToken
                    self.loginEaseIM(name: "\(userId)", token: token) { success in
                        completion(success)
                    }
                }
            }
        }
    }
     */
    
    func newRegisterAndLoginCurrentUser(completion: @escaping (Bool) -> Void) {
        guard let userId = YHLoginManager.shared.userModel?.id, userId.count > 0 else {
            completion(false)
            return
        }
        viewModel.getHuanXinToken { [weak self] tokenModel, _ in
            guard let tokenModel = tokenModel else {
                completion(false)
                return
            }
            guard let self = self else {
                completion(false)
                return
            }
            let token = tokenModel.accessToken
            self.loginEaseIM(name: "\(userId)", token: token) { success in
                completion(success)
            }
        }
    }

    @objc private func loginSuccess() {
        newRegisterAndLoginCurrentUser { _ in
            //
        }
    }

    @objc private func logoutSuccess() {
        logoutEaseIM { _ in
            //
        }
    }
}

extension YHIMHelper {
    /// 登录环信
    func loginEaseIM(name: String, token: String, completion: @escaping (Bool) -> Void) {
        let loginEvent = {
            EMClient.shared().login(withUsername: name.lowercased(), token: token) { _, err in
                DispatchQueue.main.async {
                    guard let err = err else {
                        NotificationCenter.default.post(name: YHIMHelper.didLoginEaseIMSuccess, object: nil)
                        completion(true)
                        return
                    }
                    // 已经登录
                    if err.code == .userAlreadyLoginSame {
                        completion(true)
                        NotificationCenter.default.post(name: YHIMHelper.didLoginEaseIMSuccess, object: nil)
                    } else {
                        completion(false)
                    }
                    printLog("\(err)")
                }
            }
        }

        if EMClient.shared().isLoggedIn {
            logoutEaseIM(unbindDeviceToken: true, completion: { _ in
                loginEvent()
            })
        } else {
            loginEvent()
        }
    }

    /// 登出环信
    func logoutEaseIM(unbindDeviceToken: Bool = true, completion: @escaping (EMError?) -> Void) {
        EMClient.shared().logout(unbindDeviceToken) { err in
            DispatchQueue.main.async {
                completion(err)
                guard let err = err else {
                    NotificationCenter.default.post(name: YHIMHelper.didLogOutEaseIM, object: nil)
                    completion(nil)
                    return
                }
                printLog("\(err)")
            }
        }
    }

    /// 获取聊天室人数
    func fetchRoomMemberList(roomID: String, completion: @escaping (Int?, EMError?) -> Void) {
        EMClient.shared().roomManager?.getChatroomMemberListFromServer(withId: roomID, cursor: nil, pageSize: 20, completion: { result, error in
            DispatchQueue.main.async {
                if let err = error {
                    printLog("\(err)")
                    completion(nil, err)
                } else {
                    var count: Int = 0
                    if let ret = result {
                        count = (ret.list?.count ?? 0) + 1
                        printLog("聊天室人数：\(count)")
                    }
                    completion(count, nil)
                }
            }
        })
    }

    /// 获取聊天室历史消息
    func fetchHistoryMessage(roomID: String, completion: @escaping ([EMChatMessage]?, EMError?) -> Void) {
        let option = EMFetchServerMessagesOption()
        option.direction = .up // 时间戳逆序的消息因为要倒置表格
        EMClient.shared().chatManager?.fetchMessagesFromServer(by: roomID, conversationType: .chatRoom, cursor: nil, pageSize: 10, option: option, completion: { result, err in
            DispatchQueue.main.async {
                if let err = err {
                    // 获取失败
                    printLog("获取历史消息--失败")
                    printLog(err)
                    completion(nil, err)
                } else {
                    // 获取成功
                    printLog(result)
                    if let ret = result, let arr = ret.list, arr.count > 0 {
                        printLog("获取历史消息 \(arr.count) 条")
                    } else {
                        printLog("获取历史消息 (0) 条")
                    }
                    completion(result?.list as? [EMChatMessage], err)
                }
            }
        })
    }

    /// 加入聊天室
    func joinChatRoom(roomID: String, leaveOtherRooms: Bool, completion: @escaping (EMError?) -> Void) {
        printLog("joinChatRoom: \(currentNickname)")
        let jsonString = ["fromNickName":currentNickname].jsonString()
        EMClient.shared().roomManager?.joinChatroom(roomID, ext: jsonString, leaveOtherRooms: leaveOtherRooms, completion: { _, err in
            DispatchQueue.main.async {
                if let err = err {
                    printLog(err.errorDescription)
                } else {
                    printLog("加入聊天室-成功")
                }
                completion(err)
            }

        })
    }

    /// 退出聊天室
    func quitChatRoom(roomID: String, completion: @escaping (EMError?) -> Void) {
        EMClient.shared().roomManager?.leaveChatroom(roomID, completion: { err in
            DispatchQueue.main.async {
                if let error = err {
                    printLog(error.errorDescription)
                } else {
                    printLog("退出聊天室-成功")
                }
                completion(err)
            }
        })
    }

    /// 发送消息
    func sendMessage(roomID: String, sendText: String, completion: @escaping (EMChatMessage?, EMError?) -> Void) {
        let textMessageBody = EMTextMessageBody(text: sendText)
        // 消息接收方，单聊为对端用户的 ID，群聊为群组 ID，聊天室为聊天室 ID。
        let message = EMChatMessage(conversationID: roomID, body: textMessageBody, ext: ["fromNickName": currentNickname])
        // 会话类型，单聊为 `EMChatTypeChat`，群聊为 `EMChatTypeGroupChat`，聊天室为 `EMChatTypeChatRoom`，默认为单聊。
        message.chatType = .chatRoom
        EMClient.shared().chatManager?.send(message, progress: nil, completion: { message, error in
            DispatchQueue.main.async {
                if let err = error {
                    printLog(err.errorDescription)
                    completion(nil, err)
                } else if let message = message {
                    printLog("消息发送-成功")
                    completion(message, nil)
                } else {
                    completion(nil, EMError.init(description: "发送失败", code: .noError))
                }
            }
        })
    }
}

extension YHIMHelper: EMChatroomManagerDelegate {
    func userDidJoin(_ aChatroom: EMChatroom, user aUsername: String, ext: String?) {
        printLog("\(aChatroom) 加入聊天室了1   ext = \(ext ?? "")")
        if let jsonString = ext {
            let dic = jsonString.toDictionary()
            if let fromNickName = dic["fromNickName"] {
                printLog(fromNickName)
                
                NotificationCenter.default.post(name: YHIMHelper.didUserEnterRoomMessages, object: fromNickName)
                return
            }
        }
    }
    
    func userDidLeave(_ aChatroom: EMChatroom, user aUsername: String) {
        let memberCount = aChatroom.occupantsCount
        printLog(memberCount)
        printLog("\(aUsername) 离开 聊天室了1111")
    }
    
    func userDidLeave(_ aChatroom: EMChatroom, user aUsername: String,ext: String?) {
        let memberCount = aChatroom.occupantsCount
        printLog(memberCount)
        printLog("\(aUsername) 离开 聊天室了2222")
    }
}

extension YHIMHelper: EMChatManagerDelegate {
    // 收到消息
    func messagesDidReceive(_ aMessages: [EMChatMessage]) {
        /*
         for (i, t) in aMessages.enumerated() {
             printLog(t.ext)
             var nickName: String = ""
             if let ext = t.ext {
                 nickName = ext["fromNickName"] as? String ?? "YinHe"
             }
             if let body = t.body as? EMTextMessageBody, body.type == .text {
                 printLog(body.text)
                 printLog("\(nickName) : \(body.text)")
             }
         }
         */
        NotificationCenter.default.post(name: YHIMHelper.didChatManagerReceiveMessages, object: aMessages)
    }
}

extension YHIMHelper: EMClientDelegate {
    /// 自动登录
    func autoLoginDidCompleteWithError(_ aError: EMError?) {
        guard aError == nil else {
            return
        }
        // 自动登录也发送提醒
        NotificationCenter.default.post(name: YHIMHelper.didLoginEaseIMSuccess, object: nil)
    }

    /// 被强制登出
    func userAccountDidForced(toLogout aError: EMError?) {
        guard aError == nil else {
            return
        }
        NotificationCenter.default.post(name: YHIMHelper.didLogOutEaseIM, object: nil)
    }
}

extension YHIMHelper: EMMultiDevicesDelegate {
    func multiDevicesContactEventDidReceive(_ aEvent: EMMultiDevicesEvent, username aUsername: String, ext aExt: String?) {
        //
    }

    func multiDevicesGroupEventDidReceive(_ aEvent: EMMultiDevicesEvent, groupId aGroupId: String, ext aExt: Any?) {
        //
    }
}
