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

import Foundation
import Combine

/// 绑定获客员 ViewModel，负责邀请信息加载与接受绑定。
@MainActor
final class BindAcquirerViewModel: ObservableObject {
    @Published var inviteInfo: SaleUserInviteInfo?
    @Published var isLoading = false
    @Published var isAlreadyBound = false
    @Published var errorMessage: String?

    private var saleUserId = 0

    /// 加载获客员邀请信息。
    func load(api: CooperationOrderServing, saleUserId: Int) async {
        guard saleUserId > 0 else {
            errorMessage = "获客员信息无效"
            return
        }
        if self.saleUserId == saleUserId && (inviteInfo != nil || isAlreadyBound) { return }
        self.saleUserId = saleUserId
        isAlreadyBound = false
        isLoading = true
        errorMessage = nil
        defer { isLoading = false }
        do {
            var info = try await api.saleUserInviteInfo(saleUserId: saleUserId)
            if info.saleUserId <= 0 {
                info = SaleUserInviteInfo(
                    saleUserId: saleUserId,
                    isBound: info.isBound,
                    photographerName: info.photographerName,
                    photographerPhone: info.photographerPhone,
                    salerName: info.salerName,
                    salerPhone: info.salerPhone,
                    shareCode: info.shareCode,
                    subtitle: info.subtitle,
                    title: info.title
                )
            }
            if info.isBound {
                isAlreadyBound = true
            }
            inviteInfo = info
        } catch {
            handleBindError(error.localizedDescription.isEmpty ? "获取邀请信息失败" : error.localizedDescription)
        }
    }

    /// 提交接受绑定。
    func acceptBind(api: CooperationOrderServing) async throws {
        guard saleUserId > 0, !isAlreadyBound else { return }
        try await api.saleUserAcceptBind(saleUserId: saleUserId)
    }

    /// 处理绑定错误，识别已绑定状态。
    func handleBindError(_ message: String) {
        errorMessage = message
        if message.contains("已绑定") {
            isAlreadyBound = true
        }
    }
}
