//
//  SessionListController.swift

//
//  Created by Leon on 2025/8/13.
//

import JXSegmentedView
import UIKit
class SessionListController: CLViewController<SessionListView> {
    
    var sessions = [V2NIMConversation]()
    var lastedResult: V2NIMConversationResult?
    
    var msgStat: MessageStat?

    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        setupViews()
        setupDatas()
        setupEvents()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if sessions.count == 0{
            
        }
        loadMessageStat()
    }

    private func setupViews() {
        navigationView.isHidden = true
        view.backgroundColor = .clear

        addRefreshHeader()
        addRefreshFooter()
        container.delegate = self
    }

    func addRefreshHeader() {
        RefreshHeaderAnimator { [weak self] in
            self?.loadMessageStat()
            self?.loadData()
        }.link(to: container.tableView)
    }

    func addRefreshFooter() {
        RefreshFooterAnimator { [weak self] in
            self?.loadData(more: true)
        }.link(to: container.tableView)
    }

    private func setupDatas() {
        setupSessions()
    }

    private func setupSessions() {
        container.tableView.mj_footer?.endRefreshing()
        sessions.removeAll()
        refreshTable()

        if sessions.count == 0 {
            loadData()
        }
    }

    private func setupEvents() {
        NIMSDK.shared().v2ConversationService.add(self)
        
        NotificationCenter.default.addObserver(self, selector: #selector(notifiyRelationHiddenUpdate), name: AppNotificationName.heartbeatRelationHiddenUpdate.notificationName, object: nil)
    }

    func loadData(more:Bool = false) {
        guard NIMSDK.shared().v2LoginService.getLoginStatus() == .LOGIN_STATUS_LOGINED else {
            container.tableView.mj_footer?.endRefreshing()
            return
        }
        var offset:Int64 = 0
        if(more){
            offset = lastedResult?.offset ?? 0
        }
        

        NIMSDK.shared().v2ConversationService.getConversationList(offset, limit: 20) { [weak self] result in
            self?.container.tableView.mj_header?.endRefreshing()
            
            self?.lastedResult = result
            
            if let conversations = result.conversationList, conversations.count > 0 {

                if more{
                    self?.sessions.append(contentsOf: conversations)
                }else{
                    self?.sessions = conversations
                    self?.container.tableView.mj_footer?.resetNoMoreData()
                    // dlog("☁️conversations:\(conversations)")
                }
                self?.refreshTable()
                
                var accountIds = [String]()
                for per in conversations {
                    if let accountId = V2NIMConversationIdUtil.conversationTargetId(per.conversationId){
                        accountIds.append(accountId)
                    }
                }
                self?.loadUserInfos(ids: accountIds)
            }
            
            if result.finished{
                self?.container.tableView.mj_footer?.endRefreshingWithNoMoreData()
            }else{
                self?.container.tableView.mj_footer?.endRefreshing()
            }
        } failure: { error in
            dlog("☁️load conversations error: \(error.description)")
        }
    }
    
    func loadMessageStat(){
        IMManager.shared.regetNoticeUnread()
    }
    
    func loadUserInfos(ids: [String]){
        guard ids.count > 0 else {return}
        
        NIMSDK.shared().v2UserService.getUserList(ids) { users in
            dlog("☁️getUserList✅")
        }
    }
    
    func deleteAllConversations(){
        var conversations = [String]()
        
        var aiIds = [Int]()
        for per in sessions {
            let conversationId = per.conversationId
            if !conversations.contains(where: { str in
                str == conversationId
            }){
                conversations.append(conversationId)
                if let aiId = IMHelperUtil.getAIIdByConversationId(conversationId){
                    aiIds.append(aiId)
                }
            }
        }
        
        if conversations.count > 0{
            NIMSDK.shared().v2ConversationService.deleteConversationList(byIds: conversations, clearMessage: true) { resultList in
                dlog("☁️删除所有会话结果，成功结果：\(resultList)")
                
                if resultList.count > 0{
                    aiIds.removeAll()
                    for per in resultList {
                        let conversationId = per.conversationId
                        if let aiId = IMHelperUtil.getAIIdByConversationId(conversationId){
                            aiIds.append(aiId)
                        }
                    }
                }
                
                if aiIds.count > 0{
                    let params = ["aiIdList":aiIds]
                    AICowProvider.request(.aiMessageDel(params: params), modelType: EmptyModel.self) { result in
                        switch result {
                        case .success:
                            break
                        case .failure:
                            break
                        }
                    }
                }
            }failure: { error in
                dlog("❌💬 deleteConversationList error: \(error)")
            }
            
            
        }
    }
    
    // MARK: - Helper

    func refreshTable() {
        
        sortSessions()
        
        container.cellModels = sessions
        container.tableView.reloadData()
        if sessions.count > 0 {
            container.removeEmpty()
        } else {
            container.showEmpty(text: "No Data~")
        }
    }
    
    func sortSessions() {
        sessions.sort { recent1, recent2 in
            let time1: Double = recent1.lastMessage?.messageRefer.createTime ?? 0
            let time2: Double = recent2.lastMessage?.messageRefer.createTime ?? 0
            return time1 > time2
        }
    }
}

extension SessionListController{
    @objc private func notifiyRelationHiddenUpdate(){
        loadData()
    }
}

// MARK: - SessionListViewDelegate
extension SessionListController: SessionListViewDelegate{
    func selectRow(indexPath: IndexPath) {
        if (indexPath.section == 0){
            AppRouter.goNoticeCenter()
            return
        }
        
        let conversation = sessions[indexPath.row]
        let conversationId = conversation.conversationId
        AppRouter.goChatVC(conversationId: conversationId, complete: nil)
        
//        #warning("test")
//        let sessionId = "439217670979585@r@t"
//        AppRouter.goChatVC(accId: sessionId, complete: nil)
    }
    
    // Delete single conversation
    func deleteRow(indexPath: IndexPath) {
        let conversation = sessions[indexPath.row]
        let conversationId = conversation.conversationId
        
        //dlog("conversationId: \(conversationId)")
        let aiId = IMHelperUtil.getAIIdByConversationId(conversationId)
        //dlog("aiId : \(String(describing: aiId))")
        NIMSDK.shared().v2ConversationService.deleteConversation(conversationId, clearMessage: true) {
            dlog("☁️delete conversation ok✅")
            guard let theAIId = aiId else{return}
            let params = ["aiIdList":[theAIId]]
            AICowProvider.request(.aiMessageDel(params: params), modelType: EmptyModel.self) { result in
                switch result {
                case .success:
                    break
                case .failure:
                    break
                }
            }
        } failure: { error in
            dlog("☁️delete conversation failed, error:\(error.description)")
        }

    }
}

// MARK: NIMConversationManagerDelegate

extension SessionListController: V2NIMConversationListener {
    func onSyncStarted() {
        //dlog("☁️[Conversation]onSyncStarted")
    }

    func onSyncFinished() {
        //dlog("☁️[Conversation]onSyncFinished")
        // let totalUnreadCount = NIMSDK.shared().v2ConversationService.getTotalUnreadCount()
        setupSessions()
        refreshTable()
    }

    func onSyncFailed(_ error: V2NIMError) {
        dlog("☁️[Conversation]onSyncFailed:\(error)")
    }

    func onConversationCreated(_ conversation: V2NIMConversation) {
        sessions.insert(conversation, at: 0)
        refreshTable()
    }

    /// 会话变更回调
    func onConversationChanged(_ conversations: [V2NIMConversation]) {
        dlog("☁️[Conversation]Changed")
        // 1. 把更新的会话转成字典，方便快速查找
        let updateMap = Dictionary(uniqueKeysWithValues: conversations.map { ($0.conversationId, $0) })
        
        // 2. 遍历 sessions，如果有对应更新就替换
        for (index, session) in sessions.enumerated() {
            if let updated = updateMap[session.conversationId] {
                sessions[index] = updated
            }
        }
        refreshTable()
        
        // conversation中可能有新消息，重新获取未读数量
        IMManager.shared.regetConversationAllUnreadCount()
    }

    func onConversationDeleted(_ conversationIds: [String]) {
        sessions.removeAll { per in
            for perId in conversationIds {
                if per.conversationId == perId {
                    return true
                }
            }
            return false
        }
        refreshTable()
    }

//    func onTotalUnreadCountChanged(_ unreadCount: Int) {
//        // See more in IMManager
//    }

    // 账号多端登录会话已读时间戳标记通知回调
    func onConversationReadTimeUpdated(_ conversationId: String, readTime: TimeInterval) {
    }
}

// MARK: - Noti

extension SessionListController {
    @objc func logout() {
    }
}

extension SessionListController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
