//
//  SessionController+NIM.swift
//  LegendTeam
//
//  Created by 梁博 on 20/12/21.
//

import Foundation
import NIMSDK

extension SessionController {
    func setupNIM() {
        NIMSDK.shared().v2MessageService.add(self)
    }
    
    func loadMessages(completion: @escaping (( _ messageDatas: [V2NIMMessage]?, _ error: V2NIMError?) -> Void)){
        util.loadMessages {[weak self] firstPage, messageDatas, error in
                
            self?.tableView.mj_header?.endRefreshing()
            self?.tableView.reloadData()
            completion(messageDatas, error)
            
            // Log
            self?.util.logAllCellModels()
            
            if error == nil {
                if let nimMsgs = messageDatas {
                    if nimMsgs.count < 50 && nimMsgs.count >= 0{ // 说明加载完毕
                        self?.dealFirstMessage()
                    }
                    
                    if firstPage == true, nimMsgs.count == 0{
                        self?.letAISendPrologue()
                    }
                }
                
                
            }
        }
    }
    
    /// 清理未读
    func markReadAll() {

        IMManager.shared.clearUnreadCountBy(ids: [conversationId])
    }
    
    // MARK: - Functions
    
    /// 处理收到的消息, 处理一些特殊业务逻辑。主要考扩展字段带来的类型
    private func dealRecvMessagesEvents(messages: [V2NIMMessage]) {
        // dlog("☁️SessionController+NIM dealRecvMessages: \(messages)")
        
        var createAILoadingModelFlag = false
        
        // 🚩处理
        for message in messages {
            if dealEveryMessage(message){
                createAILoadingModelFlag = true
            }
            
        } //  end circle messages
        
        
        // 🚩音频自动播放数据处理
        if self.isDisplaying && (aiInfo?.isAutoPlayVoice ?? 0 == 1){
            for per in messages.reversed(){
                if let model = util.findCellModel(message: per){
                    if let info = model.baseRemoteInfo, let _ = info.customAttachment?.type{
                        // 有类型的消息
                    }else{
                        model.autoPlayAudioOnce = true
                        break
                    }
                }else{
                    dlog("⚠️Not found cellModel by message")
                }
            }
        }
        
        
        if createAILoadingModelFlag{
            util.createAnAILoadingModel()
            tableView.reloadData()
        }
        
    }
    
    private func dealEveryMessage(_ message: V2NIMMessage) -> Bool{
        var createAILoadingModelFlag = false
        // 一些事件是在Attachment
        let info = IMRemoteUtil.dealRemoteInfo(message: message)
        
        if message.isSelf{
            createAILoadingModelFlag = true
            dlog("☁️[onReceive] 收到一条自己的消息（服务端代发）")
            // State Set
            textSuggestionsView.requestNewDatasNextTime = true
        }
        
        // 带心动分数反馈
        if let heartbeatVal = info.score, heartbeatVal != 0{
            if let aiInfo = aiInfo, let currentBeatVal = aiInfo.aiUserHeartbeatRelation?.heartbeatVal {
                let total = currentBeatVal + heartbeatVal
                dlog("💓heartbeatVal 新val: \(total), 本次变化: \(heartbeatVal)")
                
                IMAIViewModel.shared.updateHeartbeatVal(total)
                sessionNavigationView.configOnlyHeartbeatVal(value: total)
            }
        }
        
        // 滑动底部
        var scrollBottom = true
        if message.messageType == .MESSAGE_TYPE_CUSTOM{
            if let attachment = info.customAttachment{
                dealCustomAttachment(attachment: attachment)
                
                if attachment.type == .IM_SEND_GIFT{
                    createAILoadingModelFlag = true
                }
                scrollBottom = attachment.type?.needInstantScrollDisplay ?? false
            }
        }
        
        if scrollBottom {
            scrollToBottom(tableView, delay: 0.35, animated: true)
        }
        
        return createAILoadingModelFlag
    }
    
    // MARK: - Helper methods
    private func dealCustomAttachment(attachment: IMCustomAttachment){
        guard let type = attachment.type else {return}
        if type == .HEARTBEAT_LEVEL_UP{
            // sessionNavigationView.upDownNoticeView.showUnlocked(string: attachment.title ?? "-")
            // sessionNavigationView.playUpgradeAnimationOnce()
            IMAIViewModel.shared.heartbeatLevelUpString = attachment.title
            requestUserInfo(userId: aiId)
        }else if type == .HEARTBEAT_LEVEL_DOWN{
            // sessionNavigationView.upDownNoticeView.showLose(string: attachment.title ?? "-")
            IMAIViewModel.shared.heartbeatLevelDownString = attachment.title
            requestUserInfo(userId: aiId)
        }else if type == .INSUFFICIENT_BALANCE{
            IMAIViewModel.shared.showChatModelInsufficentCoinSheet()
        }
    }
    
    public func dealFirstMessage() {
        if let model = self.util.cellModels.first, model.cellType == .tips {
            return
        }
        insertFirstTipsMessage(text: "Content generated by AI");
    }
    
    private func insertFirstTipsMessage(text: String) {
        let tipMessage = IMMessageMaker.msgWithTips(text)
        util.inserMessageWith(message: tipMessage, atIndex: 0)
        tableView.reloadData()
    }
    
}

// MARK: - NIMChatManagerDelegate

extension SessionController: V2NIMMessageListener {
    /// 收到一条新消息（被动发送 + 收到的消息
    func onReceive(_ messages: [V2NIMMessage]) {
        dlog("☁️SessionNIN V2NIMMessageListener 收到消息:\(messages.count)条")
        guard let message = messages.first else{
            return
        }
        guard let messageConversationId = message.conversationId, messageConversationId == conversationId else{
            return
        }
    
        
        util.clearAILoadingModel()
        _ = util.appendWith(messages: messages)
        tableView.reloadData()
        
        // 处理一些业务逻辑
        dealRecvMessagesEvents(messages: messages)
        
        markReadAll()
    }

    
    
    /// 本端发送消息状态回调(主动发送）
    func onSend(_ message: V2NIMMessage) {
        dlog("☁️本端发送消息状态回调.\(message.text ?? "-"), serverExtension: \(message.serverExtension ?? "-"), raw:\(message.attachment?.raw ?? "-")")
        if let model = util.findCellModel(message: message){ // 更新
            model.v2msg = message
            tableView.reloadData()
        }else{
            util.appendWith(messages: [message])
            tableView.reloadData()
            scrollToBottom(tableView, delay: 0, animated: true)
        }
        
        // 发送成功✅，需要做的：
        if message.sendingState == .MESSAGE_SENDING_STATE_SUCCEEDED{
            if let model = util.findCellModel(message: message){
                if let type =  model.baseRemoteInfo?.customAttachment?.type{
                    if type == .CALL{
                        return
                    }
                }
                util.createAnAILoadingModel()
                tableView.reloadData()
                scrollToBottom(tableView, delay: 0, animated: true)
            }
            
            textSuggestionsView.requestNewDatasNextTime = true
        }
    }
    
    /**
     * 更新消息在线同步通知
     * 更新消息多端同步通知
     * 更新消息漫游通知
     */
    func onReceiveMessagesModified(_ messages: [V2NIMMessage]) {
        dlog("☁️消息被修改.\(messages)")
        for per in util.cellModels {
            for updatePer in messages {
                if let updateMsgId = updatePer.messageServerId, let nowMsgId = per.v2msg?.messageServerId, nowMsgId == updateMsgId{
                    per.v2msg = updatePer
                    per.baseRemoteInfo = IMRemoteUtil.dealRemoteInfo(message: updatePer)
                    dlog("☁️消息更新ed，\(updatePer.text ?? "")")
                    break
                }
            }
        }
        tableView.reloadData()
    }
    
    
}
