//
//  MeetViewModel.swift

//
//  Created by Leon on 2025/9/12.
//

import UIKit

class MeetViewModel{
    
    lazy var requestParams = AIRoleListRequest()
    
    /// 可选的筛选参数
    //var filterParams = [String:Any]()
    var filterModel : RolesFilterModel?
    
    // 数据存储
    var cards: [MeetCard] = []
    
    // 回调闭包
    /// 回调所有数据
    var onCardsLoaded: (([MeetCard]) -> Void)?
    /// 仅分页loadMore
    var onCardsMoreLoaded: (([MeetCard]) -> Void)?
    var onLoadError: ((Error) -> Void)?
    
    // 预加载相关
    private var isLoadingMore = false
    
    func loadCards(completion: ((Bool, [MeetCard]) -> Void)? = nil){
        
        var params = requestParams.toNonNilDictionary()
        
        //dicts = dicts.merged(with: filterParams)
        if let filterCondition = filterModel{
            // 筛选条件
            if let sexs = filterCondition.sex, sexs.count > 0, let firstSex = sexs.first{ // 后续可能会改成多选
                params.updateValue(firstSex.rawValue, forKey: "sex")
            }
            
            if let age = filterCondition.age{
                params.updateValue(age.rawValue, forKey: "age")
            }
            
            if let roleCodes = filterCondition.roleCodeList, roleCodes.count > 0{
                params.updateValue(roleCodes, forKey: "roleCodeList")
            }
        }
        
        DiscoverProvider.request(.homeRecommentCardList(params: params), modelType: [MeetCard]?.self) {[weak self] result in
            guard let self = self else{return}
            switch result {
            case .success(let model):
                if let cardsDatas = model {
                    self.cards = cardsDatas ?? []
                    DispatchQueue.main.async {
                        self.onCardsLoaded?(cardsDatas ?? [])
                    }
                    completion?(true, cardsDatas ?? [])
                }
            case .failure(let error):
                DispatchQueue.main.async {
                    self.onLoadError?(error)
                    completion?(false, [])
                }
            }
        }
    }
    
    func loadMoreCards() {
        guard !isLoadingMore else { return }
        isLoadingMore = true
        requestParams.pn += 1
        
        var params = requestParams.toNonNilDictionary()
        if let filterCondition = filterModel{
            // 筛选条件
            if let sexs = filterCondition.sex, sexs.count > 0, let firstSex = sexs.first{ // 后续可能会改成多选
                params.updateValue(firstSex.rawValue, forKey: "sex")
            }
            
            if let age = filterCondition.age{
                params.updateValue(age.rawValue, forKey: "age")
            }
            
            if let roleCodes = filterCondition.roleCodeList, roleCodes.count > 0{
                params.updateValue(roleCodes, forKey: "roleCodeList")
            }
        }
        
        Hud.showIndicator()
        DiscoverProvider.request(.homeRecommentCardList(params: params), modelType: [MeetCard]?.self) {[weak self] result in
            Hud.hideIndicator()
            
            guard let self = self else{return}
            self.isLoadingMore = false
            
            switch result {
            case .success(let model):
                // dlog(model)
                if let cardsDatas = model {
//                    #warning("test")
//                    self.cards.append(contentsOf: [])
//                    DispatchQueue.main.async {
//                        self.onCardsLoaded?(self.cards)
//                        self.onCardsMoreLoaded?([])
//                    }
//                    return
                    // 追加新数据而不是替换
                    
                    self.cards.append(contentsOf: cardsDatas ?? [])
                    DispatchQueue.main.async {
                        self.onCardsLoaded?(self.cards)
                        self.onCardsMoreLoaded?(cardsDatas ?? [])
                    }
                }
            case .failure(let error):
                // 加载失败时回退页码
                self.requestParams.pn -= 1
                DispatchQueue.main.async {
                    self.onLoadError?(error)
                }
            }
        }
    }
    
    func resetAndLoadCards() {
        requestParams.pn = 1
        cards.removeAll()
        isLoadingMore = false
        loadCards()
    }
    
    // 检查是否需要预加载
    func shouldPreload(remainingCount: Int) -> Bool {
        return remainingCount <= 5 && !isLoadingMore
    }
}
