//
//  CommissionRateLogViewModel.swift
//  suixinkan
//

import Foundation

/// 获客员分成比例修改记录 ViewModel，负责刷新、分页与重复项合并。
final class CommissionRateLogViewModel {
    private enum Constants {
        static let pageSize = 10
    }

    private(set) var items: [CommissionRateLogEntity] = []
    private(set) var isRefreshing = false
    private(set) var isLoadingMore = false
    private(set) var initialLoading = true
    private(set) var canLoadMore = false

    var onStateChange: (() -> Void)?
    var onShowMessage: ((String) -> Void)?

    private let saleUserId: Int
    private var total = 0
    private var lastLoadedPage = 0
    private var isLoading = false

    init(saleUserId: Int) {
        self.saleUserId = saleUserId
    }

    /// 重新加载第一页修改记录。
    func refresh(api: OrderAPI) async {
        await load(api: api, page: 1, append: false)
    }

    /// 在存在下一页时加载更多修改记录。
    func loadMore(api: OrderAPI) async {
        guard canLoadMore, !isRefreshing, !isLoadingMore else { return }
        await load(api: api, page: lastLoadedPage + 1, append: true)
    }

    private func load(api: OrderAPI, page: Int, append: Bool) async {
        guard saleUserId > 0 else {
            initialLoading = false
            onShowMessage?("获客员信息无效")
            notifyStateChange()
            return
        }
        guard !isLoading else { return }
        isLoading = true
        if append {
            isLoadingMore = true
        } else {
            isRefreshing = true
        }
        notifyStateChange()

        defer {
            isLoading = false
            initialLoading = false
            if append {
                isLoadingMore = false
            } else {
                isRefreshing = false
            }
            notifyStateChange()
        }

        do {
            let response = try await api.saleUserCommissionRateLogs(
                saleUserId: saleUserId,
                page: page,
                pageSize: Constants.pageSize
            )
            if append {
                let existingIDs = Set(items.map(\.id))
                items.append(contentsOf: response.list.filter { !existingIDs.contains($0.id) })
            } else {
                var seenIDs = Set<Int>()
                items = response.list.filter { seenIDs.insert($0.id).inserted }
            }
            total = max(0, response.total)
            lastLoadedPage = page
            canLoadMore = items.count < total && !response.list.isEmpty
        } catch {
            onShowMessage?(error.localizedDescription)
        }
    }

    private func notifyStateChange() {
        onStateChange?()
    }
}
