import SwiftUI import Combine // MARK: - MomentDetailViewModel @MainActor final class MomentDetailViewModel: ObservableObject { // MARK: - Published Properties @Published var moment: MomentsInfo @Published var isLikeLoading = false @Published var localIsLike: Bool @Published var localLikeCount: Int @Published var showImagePreview = false @Published var images: [String] = [] @Published var currentIndex: Int = 0 // MARK: - Private Properties private var cancellables = Set() // MARK: - Initialization init(moment: MomentsInfo) { self.moment = moment self.localIsLike = moment.isLike self.localLikeCount = moment.likeCount self.images = moment.dynamicResList?.compactMap { $0.resUrl } ?? [] debugInfoSync("📱 MomentDetailViewModel: 初始化") debugInfoSync(" 动态ID: \(moment.dynamicId)") debugInfoSync(" 用户: \(moment.nick)") debugInfoSync(" 图片数量: \(images.count)") } // MARK: - Public Methods func onImageTap(_ index: Int) { currentIndex = index showImagePreview = true debugInfoSync("📸 MomentDetailViewModel: 图片被点击,索引: \(index)") } func like() { guard !isLikeLoading, moment.status != 0 else { debugInfoSync("⏸️ MomentDetailViewModel: 跳过点赞 - 正在加载: \(isLikeLoading), 审核中: \(moment.status == 0)") return } isLikeLoading = true debugInfoSync("📡 MomentDetailViewModel: 开始点赞操作") Task { do { // 获取当前用户ID guard let uidStr = await UserInfoManager.getCurrentUserId(), let uid = Int(uidStr) else { await MainActor.run { isLikeLoading = false } setAPILoadingErrorSync(UUID(), errorMessage: "无法获取用户信息,请重新登录") return } // 确定请求参数 let status = localIsLike ? 0 : 1 // 0: 取消点赞, 1: 点赞 // 创建 API 服务实例 let api = LiveAPIService() // 创建请求 let request = LikeDynamicRequest( dynamicId: moment.dynamicId, uid: uid, status: status, likedUid: moment.uid, worldId: moment.worldId ) debugInfoSync("📡 MomentDetailViewModel: 发送点赞请求") debugInfoSync(" 动态ID: \(moment.dynamicId)") debugInfoSync(" 当前状态: \(localIsLike)") debugInfoSync(" 请求状态: \(status)") // 发起请求 let response: LikeDynamicResponse = try await api.request(request) await MainActor.run { isLikeLoading = false // 处理响应 if response.code == 200 { localIsLike.toggle() localLikeCount += localIsLike ? 1 : -1 debugInfoSync("✅ MomentDetailViewModel: 点赞操作成功") debugInfoSync(" 动态ID: \(moment.dynamicId)") debugInfoSync(" 新状态: \(localIsLike)") debugInfoSync(" 新数量: \(localLikeCount)") } else { let errorMessage = response.message.isEmpty ? "点赞失败,请重试" : response.message setAPILoadingErrorSync(UUID(), errorMessage: errorMessage) debugErrorSync("❌ MomentDetailViewModel: 点赞操作失败") debugErrorSync(" 动态ID: \(moment.dynamicId)") debugErrorSync(" 错误: \(errorMessage)") } } } catch { await MainActor.run { isLikeLoading = false } setAPILoadingErrorSync(UUID(), errorMessage: error.localizedDescription) debugErrorSync("❌ MomentDetailViewModel: 点赞请求异常") debugErrorSync(" 动态ID: \(moment.dynamicId)") debugErrorSync(" 错误: \(error.localizedDescription)") } } } }