//
//  YHContactViewModel.swift
//  galaxy
//
//  Created by Dufet on 2025/9/28.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHContactViewModel: YHBaseViewModel {
    var curPageIndex: Int = 1
    var pageSize = 10
    var totalCount: Int = 0
    var contacts: [YHContact] = []
    var hasMore: Bool = true

    // super-app/business-card/list

    // 最近浏览
    func getList(_ firstFlag: Bool, callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        var params: [String: Any] = ["page": curPageIndex,
                                     "page_size": pageSize]
        if firstFlag {
            curPageIndex = 1
            params = ["page": curPageIndex,
                      "page_size": pageSize]

        } else {
            params = ["page": curPageIndex + 1,
                      "page_size": pageSize]
        }

        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Contact.contactList
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, _ in
            guard let self = self else { return }
            // 1. json字符串 转 对象
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHContactListModel.deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }

                if firstFlag {
                    self.totalCount = result.total
                    self.contacts.removeAll()
                    self.contacts = result.list

                } else {
                    self.contacts.append(contentsOf: result.list)
                    curPageIndex += 1
                }

                if self.contacts.count >= self.totalCount {
                    self.hasMore = false
                } else {
                    self.hasMore = true
                }

                callBackBlock(true, nil)

            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
}
