wake-ios/wake/Features/BlindBox/View/BlindBoxView.swift

426 lines
22 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import SwiftUI
import SwiftData
import AVKit
import Foundation
//
extension Notification.Name {
static let blindBoxStatusChanged = Notification.Name("blindBoxStatusChanged")
}
internal enum BlindBoxAnimationPhase {
case loading
case ready
case opening
case none
}
extension Notification.Name {
static let navigateToMediaViewer = Notification.Name("navigateToMediaViewer")
}
// MARK: -
struct BlindBoxView: View {
let mediaType: BlindBoxMediaType
let currentBoxId: String?
@StateObject private var viewModel: BlindBoxViewModel
@State private var showModal = false //
@State private var showSettings = false //
@State private var showLogin = false
// ViewModel countdownText
//
@State private var showScalingOverlay = false
@State private var animationPhase: BlindBoxAnimationPhase = .none
@State private var scale: CGFloat = 0.1
// showControls BlindBoxMediaOverlay
@State private var isAnimating = true
@State private var showMedia = false
// -
@Query private var login: [Login]
init(mediaType: BlindBoxMediaType, blindBoxId: String? = nil) {
self.mediaType = mediaType
self.currentBoxId = blindBoxId
_viewModel = StateObject(wrappedValue: BlindBoxViewModel(mediaType: mediaType, currentBoxId: blindBoxId))
}
private func startScalingAnimation() {
self.scale = 0.1
self.showScalingOverlay = true
withAnimation(.spring(response: 2.0, dampingFraction: 0.5, blendDuration: 0.8)) {
self.scale = 1.0
}
}
// BlindBoxMediaOverlay
var body: some View {
ZStack {
Color.themeTextWhiteSecondary.ignoresSafeArea()
.onAppear {
Perf.event("BlindBox_Appear")
print("🎯 BlindBoxView appeared with mediaType: \(mediaType)")
print("🎯 Current thread: \(Thread.current)")
//
Task {
await viewModel.load()
}
}
.onDisappear {
viewModel.stopPolling()
viewModel.stopCountdown()
// Clean up video player
viewModel.player?.pause()
viewModel.player?.replaceCurrentItem(with: nil)
viewModel.player = nil
NotificationCenter.default.removeObserver(
self,
name: .blindBoxStatusChanged,
object: nil
)
}
.onChange(of: viewModel.blindGenerate?.status) { _, status in
guard let status = status?.lowercased() else { return }
if status == "unopened" {
Perf.event("BlindBox_Status_Unopened")
withAnimation { self.animationPhase = .ready }
} else if status == "preparing" {
Perf.event("BlindBox_Status_Preparing")
withAnimation { self.animationPhase = .loading }
}
}
.onChange(of: animationPhase) { _, phase in
if phase != .loading {
// VM
}
}
.onChange(of: viewModel.videoURL) { _, url in
if !url.isEmpty {
withAnimation { self.animationPhase = .ready }
}
}
.onChange(of: viewModel.imageURL) { _, url in
if !url.isEmpty {
withAnimation { self.animationPhase = .ready }
}
}
.onChange(of: viewModel.didBootstrap) { _, done in
guard done else { return }
// loading ready
let initialStatus = viewModel.blindGenerate?.status.lowercased() ?? ""
if initialStatus == "unopened" {
withAnimation { self.animationPhase = .ready }
} else if initialStatus == "preparing" {
withAnimation { self.animationPhase = .loading }
} else {
// none onChange
self.animationPhase = .none
}
}
if showScalingOverlay {
BlindBoxMediaOverlay(
mediaType: mediaType,
player: .init(get: { viewModel.player }, set: { viewModel.player = $0 }),
displayImage: viewModel.displayImage,
isPortrait: viewModel.isPortrait,
aspectRatio: viewModel.aspectRatio,
scale: $scale,
onBack: {
if mediaType == .all, !viewModel.videoURL.isEmpty, let url = URL(string: viewModel.videoURL) {
Router.shared.navigate(to: .blindOutcome(media: .video(url, nil), time: viewModel.blindGenerate?.name ?? "Your box", description: viewModel.blindGenerate?.description ?? "", isMember: viewModel.isMember))
} else if mediaType == .image, let image = viewModel.displayImage {
Router.shared.navigate(to: .blindOutcome(media: .image(image), time: viewModel.blindGenerate?.name ?? "Your box", description: viewModel.blindGenerate?.description ?? "", isMember: viewModel.isMember))
}
}
)
} else {
// Original content
VStack {
VStack(spacing: 20) {
if mediaType == .all {
BlindBoxHeaderBar(
onMenuTap: showUserProfile,
remainPoints: viewModel.memberProfile?.remainPoints ?? 0,
showLogin: $showLogin
)
}
//
BlindBoxTitleView()
.opacity(showScalingOverlay ? 0 : 1)
.offset(y: showScalingOverlay ? -UIScreen.main.bounds.height * 0.2 : 0)
.animation(.easeInOut(duration: 0.5), value: showScalingOverlay)
//
ZStack {
// 1. Card
if !showScalingOverlay {
CardBlindBackground()
}
if mediaType == .all && !showScalingOverlay {
BlindCountBadge(text: "\(viewModel.blindCount?.availableQuantity ?? 0) Boxes")
.position(x: UIScreen.main.bounds.width * 0.7,
y: UIScreen.main.bounds.height * 0.18)
.opacity(showScalingOverlay ? 0 : 1)
.animation(.easeOut(duration: 1.5), value: showScalingOverlay)
}
if !showScalingOverlay {
VStack(spacing: 20) {
switch animationPhase {
case .loading:
LottieView(name: "ready", isPlaying: animationPhase == .loading && !showScalingOverlay)
.frame(width: 300, height: 300)
// .onAppear {
// DispatchQueue.main.asyncAfter(deadline: .now() + 6) {
// withAnimation {
// animationPhase = .ready
// }
// }
// }
case .ready:
ZStack {
LottieView(name: "ready", isPlaying: animationPhase == .ready && !showScalingOverlay)
.frame(width: 300, height: 300)
// Add a transparent overlay to capture taps
Color.clear
.contentShape(Rectangle()) // Make the entire area tappable
.frame(width: 300, height: 300)
.onTapGesture {
Perf.event("BlindBox_Open_Tapped")
print("点击了盲盒")
let boxIdToOpen = self.currentBoxId ?? self.viewModel.blindGenerate?.id
if let boxId = boxIdToOpen {
Task {
do {
try await viewModel.openBlindBox(for: boxId)
print("✅ 盲盒开启成功")
} catch {
print("❌ 开启盲盒失败: \(error)")
}
}
}
withAnimation {
animationPhase = .opening
}
}
}
.frame(width: 300, height: 300)
case .opening:
ZStack {
if !showMedia {
LottieView(name: "ready", loopMode: .playOnce, isPlaying: !showMedia)
.frame(width: 300, height: 300)
.scaleEffect(scale)
}
// GIFView
Color.clear
.onAppear {
Perf.event("BlindBox_Opening_Begin")
print("开始播放开启动画")
// 1
self.scale = 1.0
// 1
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
withAnimation(.spring(response: 1.0, dampingFraction: 0.7)) {
//
self.scale = max(
UIScreen.main.bounds.width / 300,
UIScreen.main.bounds.height / 300
) * 1.2
//
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
withAnimation(.spring(response: 0.8, dampingFraction: 0.7)) {
self.scale = 1.0
//
Perf.event("BlindBox_Opening_ShowMedia")
self.showScalingOverlay = true
Task { await viewModel.prepareMedia() }
// GIF
self.showMedia = true
}
}
}
}
}
}
.frame(width: 300, height: 300)
case .none:
//
LottieView(name: "ready", loopMode: .loop, isPlaying: true)
.frame(width: 300, height: 300)
.scaleEffect(scale)
// Color.clear
// .frame(width: 300, height: 300)
// SVGImage(svgName: "BlindNone")
// .frame(width: 300, height: 300)
}
}
.offset(y: -50)
.compositingGroup()
.padding()
}
//
if !showScalingOverlay && !showMedia {
BlindBoxDescriptionView(
name: viewModel.blindGenerate?.name ?? "Some box",
description: viewModel.blindGenerate?.description ?? ""
)
.offset(x: -10, y: UIScreen.main.bounds.height * 0.2)
}
}
.padding()
.frame(
maxWidth: .infinity,
maxHeight: UIScreen.main.bounds.height * 0.65
)
.opacity(showScalingOverlay ? 0 : 1)
.animation(.easeOut(duration: 1.5), value: showScalingOverlay)
.offset(y: showScalingOverlay ? -100 : 0)
.animation(.easeInOut(duration: 1.5), value: showScalingOverlay)
// TODO
if mediaType == .all, viewModel.didBootstrap {
BlindBoxActionButton(
phase: animationPhase,
countdownText: viewModel.countdownText,
onOpen: {
let boxIdToOpen = self.currentBoxId ?? self.viewModel.blindGenerate?.id
if let boxId = boxIdToOpen {
Task {
do {
try await viewModel.openBlindBox(for: boxId)
print("✅ 盲盒开启成功")
} catch {
print("❌ 开启盲盒失败: \(error)")
}
}
}
withAnimation {
animationPhase = .opening
}
},
onGoToBuy: {
Router.shared.navigate(to: .mediaUpload)
}
)
.padding(.horizontal)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.themeTextWhiteSecondary)
.offset(x: showModal ? UIScreen.main.bounds.width * 0.8 : 0)
.animation(.spring(response: 0.6, dampingFraction: 0.8), value: showModal)
.edgesIgnoringSafeArea(.all)
}
//
SlideInModal(
isPresented: $showModal,
onDismiss: hideUserProfile
) {
UserProfileModal(
showModal: $showModal,
showSettings: $showSettings,
isMember: .init(get: { viewModel.isMember }, set: { viewModel.isMember = $0 }),
memberDate: .init(get: { viewModel.memberDate }, set: { viewModel.memberDate = $0 })
)
}
.offset(x: showSettings ? UIScreen.main.bounds.width : 0)
.animation(.spring(response: 0.6, dampingFraction: 0.8), value: showSettings)
//
ZStack {
if showSettings {
Color.black.opacity(0.3)
.edgesIgnoringSafeArea(.all)
.onTapGesture(perform: hideSettings)
.transition(.opacity)
}
if showSettings {
SettingsView(isPresented: $showSettings)
.transition(.move(edge: .leading))
.zIndex(1)
}
}
.animation(.spring(response: 0.6, dampingFraction: 0.8), value: showSettings)
}
}
.navigationBarBackButtonHidden(true)
}
///
private func showUserProfile() {
withAnimation(.spring(response: 0.6, dampingFraction: 0.8)) {
// print(": \(login.count)")
// for (index, item) in login.enumerated() {
// print(" \(index + 1): =\(item.email), =\(item.name)")
// }
print("当前登录记录:")
for (index, item) in login.enumerated() {
print("记录 \(index + 1): 邮箱=\(item.email), 姓名=\(item.name)")
}
showModal.toggle()
}
}
///
private func hideUserProfile() {
withAnimation(.spring(response: 0.6, dampingFraction: 0.8)) {
showModal = false
}
}
///
private func hideSettings() {
withAnimation(.spring(response: 0.6, dampingFraction: 0.8)) {
showSettings = false
}
}
}
// MARK: -
#Preview {
BlindBoxView(mediaType: .all)
.onAppear {
// Preview使
#if DEBUG
if ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" {
// Preview
let previewToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJFZERTQSJ9.eyJqdGkiOjczNzAwMTY5NzMzODE1NzA1NjAsImlkZW50aXR5IjoiNzM1MDQzOTY2MzExNjYxOTc3NyIsImV4cCI6MTc1Nzc1Mzc3NH0.tZ8p5sW4KX6HFoJpJN0e4VmJOAGhTrYD2yTwQwilKpufzqOAfXX4vpGYBurgBIcHj2KmXKX2PQMOeeAtvAypDA"
let _ = KeychainHelper.saveAccessToken(previewToken)
print("🔑 Preview token set for testing")
}
#endif
}
}
//
#Preview("First Blind Box") {
BlindBoxView(mediaType: .image, blindBoxId: "7370140297747107840")
.onAppear {
// Preview使
#if DEBUG
if ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" {
// Preview
let previewToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJFZERTQSJ9.eyJqdGkiOjczNzAwMTY5NzMzODE1NzA1NjAsImlkZW50aXR5IjoiNzM1MDQzOTY2MzExNjYxOTc3NyIsImV4cCI6MTc1Nzc1Mzc3NH0.tZ8p5sW4KX6HFoJpJN0e4VmJOAGhTrYD2yTwQwilKpufzqOAfXX4vpGYBurgBIcHj2KmXKX2PQMOeeAtvAypDA"
let _ = KeychainHelper.saveAccessToken(previewToken)
print("🔑 Preview token set for testing")
}
#endif
}
}