//
//  WithdrawalAuditViewModel.swift
//  suixinkan
//
//  Created by Codex on 2026/6/25.
//

import Foundation
import Combine

/// 提现审核筛选项，按提现记录的状态文案聚合审核视角。
enum WithdrawalAuditFilter: String, CaseIterable, Identifiable {
    case all
    case processing
    case completed

    var id: String { rawValue }

    /// 筛选项展示标题。
    var title: String {
        switch self {
        case .all: "全部"
        case .processing: "处理中"
        case .completed: "已完成"
        }
    }
}

@MainActor
/// 提现审核 ViewModel，负责提现记录分页、状态筛选和失败状态清理。
final class WithdrawalAuditViewModel: ObservableObject {
    @Published var records: [WalletWithdrawRecord] = []
    @Published var selectedFilter: WithdrawalAuditFilter = .all
    @Published var isLoading = false
    @Published var isLoadingMore = false
    @Published var loadFailed = false
    @Published var loadFailureReason: String?
    @Published var errorMessage: String?

    private let pageSize = 10
    @Published private var page = 1
    @Published private var total = 0

    /// 当前筛选下的提现记录。
    var filteredRecords: [WalletWithdrawRecord] {
        filteredRecords(for: selectedFilter)
    }

    /// 是否还有下一页。
    var hasMore: Bool {
        records.count < total
    }

    /// 记录总数，优先使用服务端 total。
    var totalCount: Int {
        max(total, records.count)
    }

    /// 处理中数量。
    var processingCount: Int {
        filteredRecords(for: .processing).count
    }

    /// 已完成数量。
    var completedCount: Int {
        filteredRecords(for: .completed).count
    }

    /// 按指定筛选返回提现记录。
    func filteredRecords(for filter: WithdrawalAuditFilter) -> [WalletWithdrawRecord] {
        switch filter {
        case .all:
            return records
        case .processing:
            return records.filter { record in
                let status = record.statusLabel
                return status.contains("中") || status.contains("待")
            }
        case .completed:
            return records.filter { record in
                let status = record.statusLabel
                return status.contains("完成") || status.contains("到账") || status.contains("通过")
            }
        }
    }

    /// 切换筛选项，仅影响本地展示。
    func selectFilter(_ filter: WithdrawalAuditFilter) {
        selectedFilter = filter
    }

    /// 重新加载第一页提现审核记录。
    func reload(api: WalletServing) async {
        isLoading = true
        loadFailed = false
        loadFailureReason = nil
        errorMessage = nil
        defer { isLoading = false }

        do {
            let response = try await api.walletWithdrawList(page: 1, pageSize: pageSize)
            records = response.item
            total = response.total
            page = 1
        } catch {
            clearRecords()
            loadFailed = true
            loadFailureReason = error.localizedDescription
            errorMessage = error.localizedDescription
        }
    }

    /// 加载下一页提现审核记录。
    func loadMore(api: WalletServing) async {
        guard hasMore, !isLoadingMore, !isLoading else { return }
        isLoadingMore = true
        errorMessage = nil
        defer { isLoadingMore = false }

        let nextPage = page + 1
        do {
            let response = try await api.walletWithdrawList(page: nextPage, pageSize: pageSize)
            records += response.item
            total = response.total
            page = nextPage
        } catch {
            errorMessage = error.localizedDescription
        }
    }

    /// 清空旧提现审核数据，避免失败后残留上一账号或上一状态记录。
    private func clearRecords() {
        records = []
        page = 1
        total = 0
        isLoadingMore = false
    }
}
