//
//  FriendsSearchViewModel.swift

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

import Foundation
import NIMSDK

class FriendsSearchViewModel {
    var searchingStr : String = ""
    
    var searchFrineds: [RelationFriend] = [RelationFriend]()
    var searchConversations: [V2NIMConversation] = [V2NIMConversation]()
    
    // 存储所有好友数据，用于本地搜索
    private var allFriends: [RelationFriend] = []
    // 存储所有会话数据，用于本地搜索
    private var allConversations: [V2NIMConversation] = []

    /// 搜索好友，支持按 nickname 部分匹配
    func searchFriends(page: Int = 1, text: String?, completion: ((_ result: Bool, _ friends: [RelationFriend]) -> Void)?) {
        guard let searchText = text, !searchText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
            searchFrineds = []
            completion?(true, [])
            return
        }
        
        // 如果已有所有好友数据，进行本地搜索
        if !allFriends.isEmpty {
            let filteredFriends = allFriends.filter { friend in
                guard let nickname = friend.nickname else { return false }
                return nickname.lowercased().contains(searchText.lowercased())
            }
            searchFrineds = filteredFriends
            completion?(true, filteredFriends)
        } else {
            // 如果没有本地数据，先加载所有好友再搜索
            loadAllFriends(page: page) { [weak self] result, friends in
                if result {
                    let filteredFriends = friends.filter { friend in
                        guard let nickname = friend.nickname else { return false }
                        return nickname.lowercased().contains(searchText.lowercased())
                    }
                    self?.searchFrineds = filteredFriends
                    completion?(true, filteredFriends)
                } else {
                    completion?(false, [])
                }
            }
        }
    }
    
    /// 搜索会话，支持按会话名称部分匹配
    func searchConversations(text: String?, completion: ((_ result: Bool, _ conversations: [V2NIMConversation]) -> Void)?) {
        guard let searchText = text, !searchText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
            searchConversations = []
            completion?(true, [])
            return
        }
        
        // 如果已有所有会话数据，进行本地搜索
        if !allConversations.isEmpty {
            let filteredConversations = allConversations.filter { conversation in
                guard let name = conversation.name else { return false }
                return name.lowercased().contains(searchText.lowercased())
            }
            searchConversations = filteredConversations
            completion?(true, filteredConversations)
        } else {
            // 如果没有本地数据，先加载所有会话再搜索
            loadAllConversations { [weak self] result, conversations in
                if result {
                    let filteredConversations = conversations.filter { conversation in
                        guard let name = conversation.name else { return false }
                        return name.lowercased().contains(searchText.lowercased())
                    }
                    self?.searchConversations = filteredConversations
                    completion?(true, filteredConversations)
                } else {
                    completion?(false, [])
                }
            }
        }
    }
    
    /// 加载所有好友数据
    private func loadAllFriends(page: Int = 1, completion: ((_ result: Bool, _ friends: [RelationFriend]) -> Void)?) {
        let pageData = RequestPageData()
        pageData.pn = page
        var request = FriendsListRequest()
        request.page = pageData
        let params = request.toNonNilDictionary()

        FriendsProvider.request(.heartbeatRelationList(params: params), modelType: ResponseContentPageData<RelationFriend>.self) { [weak self] result in
            switch result {
            case let .success(model):
                if let validDatas = model?.datas {
                    if pageData.pn == 1 {
                        self?.allFriends = validDatas
                        completion?(true, validDatas)
                    } else {
                        self?.allFriends.append(contentsOf: validDatas)
                        completion?(true, validDatas)
                    }
                } else {
                    completion?(false, [])
                }
            case .failure:
                completion?(false, [])
            }
        }
    }
    
    /// 加载所有会话数据
    private func loadAllConversations(completion: ((_ result: Bool, _ conversations: [V2NIMConversation]) -> Void)?) {
        guard NIMSDK.shared().v2LoginService.getLoginStatus() == .LOGIN_STATUS_LOGINED else {
            completion?(false, [])
            return
        }
        
        NIMSDK.shared().v2ConversationService.getConversationList(0, limit: 1000) { [weak self] result in
            if let conversations = result.conversationList, conversations.count > 0 {
                self?.allConversations = conversations
                completion?(true, conversations)
            } else {
                completion?(false, [])
            }
        } failure: { error in
            dlog("☁️load conversations error: \(error.description)")
            completion?(false, [])
        }
    }
    
    /// 清除搜索数据
    func clearSearch() {
        searchFrineds.removeAll()
        searchConversations.removeAll()
        searchingStr = ""
    }
    
    /// 获取好友搜索结果数量
    var searchResultCount: Int {
        return searchFrineds.count
    }
    
    /// 获取会话搜索结果数量
    var searchConversationResultCount: Int {
        return searchConversations.count
    }
}

