//
//  StoreAdminOrderListViewModel.swift
//  suixinkan
//
//  Created by Codex on 2026/6/29.
//

import Foundation
import Combine

@MainActor
/// 店长订单 Tab ViewModel，对齐 Android DepositOrderListViewModel。
final class StoreAdminOrderListViewModel: ObservableObject {
    @Published var searchPhone = ""
    @Published var selectedStatus = 0
    @Published var filterStartDate: Date?
    @Published var filterEndDate: Date?
    @Published private(set) var orders: [StoreOrderListItem] = []
    @Published private(set) var loading = false
    @Published private(set) var loadingMore = false
    @Published private(set) var total = 0
    @Published private(set) var page = 1
    @Published private(set) var hasMore = false

    private let pageSize = 20

    /// 返回去除首尾空白后的手机号搜索值。
    var normalizedPhone: String? {
        let text = searchPhone.trimmingCharacters(in: .whitespacesAndNewlines)
        return text.isEmpty ? nil : text
    }

    /// 当前筛选标题。
    var currentFilterTitle: String {
        OrderFilters.storeAdminStatusFilters.first(where: { $0.id == selectedStatus })?.title ?? "全部"
    }

    /// 刷新店长订单列表。
    func reload(api: OrderServing, storeId: Int?, showLoading: Bool = true) async throws {
        guard let storeId, storeId > 0 else {
            orders = []
            total = 0
            page = 1
            hasMore = false
            return
        }

        if showLoading { loading = true }
        defer { if showLoading { loading = false } }

        let result = try await api.storeOrderList(
            storeId: storeId,
            page: 1,
            pageSize: pageSize,
            userPhone: normalizedPhone,
            orderStatus: orderStatusQuery,
            orderType: nil,
            startTime: OrderDateRangeFormatter.queryValue(from: filterStartDate),
            endTime: OrderDateRangeFormatter.queryValue(from: filterEndDate)
        )
        orders = result.list
        total = result.total
        page = 1
        hasMore = orders.count < result.total && !result.list.isEmpty
    }

    /// 加载下一页。
    func loadMore(api: OrderServing, storeId: Int?) async throws {
        guard !loadingMore, hasMore, let storeId, storeId > 0 else { return }
        loadingMore = true
        defer { loadingMore = false }

        let nextPage = page + 1
        let result = try await api.storeOrderList(
            storeId: storeId,
            page: nextPage,
            pageSize: pageSize,
            userPhone: normalizedPhone,
            orderStatus: orderStatusQuery,
            orderType: nil,
            startTime: OrderDateRangeFormatter.queryValue(from: filterStartDate),
            endTime: OrderDateRangeFormatter.queryValue(from: filterEndDate)
        )
        orders.append(contentsOf: result.list)
        total = result.total
        page = nextPage
        hasMore = orders.count < result.total && !result.list.isEmpty
    }

    /// 提交店长订单退款。
    func refund(
        api: OrderServing,
        storeId: Int?,
        orderNumber: String,
        mode: OrderRefundMode,
        amount: String,
        reason: String
    ) async throws {
        guard let storeId, storeId > 0 else { return }
        try await api.storeOrderRefund(
            storeId: storeId,
            orderNumber: orderNumber,
            refundType: mode,
            refundAmount: amount,
            refundReason: reason
        )
    }

    private var orderStatusQuery: Int? {
        selectedStatus > 0 ? selectedStatus : nil
    }
}
