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

704 lines
35 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")
}
private enum BlindBoxAnimationPhase {
case loading
case ready
case opening
case none
}
extension Notification.Name {
static let navigateToMediaViewer = Notification.Name("navigateToMediaViewer")
}
// MARK: -
struct VisualEffectView: UIViewRepresentable {
var effect: UIVisualEffect?
func makeUIView(context: Context) -> UIVisualEffectView {
let view = UIVisualEffectView(effect: nil)
// Use a simpler approach without animator
let blurEffect = UIBlurEffect(style: .systemUltraThinMaterialLight)
// Create a custom blur effect with reduced intensity
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.alpha = 0.3 // Reduce intensity
// Add a white background with low opacity for better frosted effect
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.white.withAlphaComponent(0.1)
backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.contentView.addSubview(backgroundView)
view.contentView.addSubview(blurView)
blurView.frame = view.bounds
blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return view
}
func updateUIView(_ uiView: UIVisualEffectView, context: Context) {
// No need to update the effect
}
}
struct AVPlayerController: UIViewControllerRepresentable {
@Binding var player: AVPlayer?
func makeUIViewController(context: Context) -> AVPlayerViewController {
let controller = AVPlayerViewController()
controller.player = player
controller.showsPlaybackControls = false
controller.videoGravity = .resizeAspect
controller.view.backgroundColor = .clear
return controller
}
func updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) {
uiViewController.player = player
}
}
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
@State private var showControls = false
@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))
}
// ViewModel
// ViewModel
// ViewModel
// ViewModel
// ViewModel
// ViewModel.prepareMedia()
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
}
}
// MARK: - Computed Properties
private var scaledWidth: CGFloat {
if viewModel.isPortrait {
return UIScreen.main.bounds.height * scale * 1/viewModel.aspectRatio
} else {
return UIScreen.main.bounds.width * scale
}
}
private var scaledHeight: CGFloat {
if viewModel.isPortrait {
return UIScreen.main.bounds.height * scale
} else {
return UIScreen.main.bounds.width * scale * 1/viewModel.aspectRatio
}
}
var body: some View {
ZStack {
Color.themeTextWhiteSecondary.ignoresSafeArea()
.onAppear {
Perf.event("BlindBox_Appear")
print("🎯 BlindBoxView appeared with mediaType: \(mediaType)")
print("🎯 Current thread: \(Thread.current)")
//
// if mediaType == .all, let firstItem = blindList.first {
// displayData = BlindBoxData(from: firstItem)
// } else {
// displayData = blindGenerate
// }
//
// NotificationCenter.default.addObserver(
// forName: .blindBoxStatusChanged,
// object: nil,
// queue: .main
// ) { notification in
// if let status = notification.userInfo?["status"] as? String {
// switch status {
// case "Preparing":
// withAnimation {
// self.animationPhase = .loading
// }
// case "Unopened":
// withAnimation {
// self.animationPhase = .ready
// }
// default:
// //
// withAnimation {
// self.animationPhase = .ready
// }
// break
// }
// }
// }
//
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 {
ZStack {
VisualEffectView(effect: UIBlurEffect(style: .systemUltraThinMaterialLight))
.opacity(0.3)
.edgesIgnoringSafeArea(.all)
Group {
if mediaType == .all, viewModel.player != nil {
// Video Player
AVPlayerController(player: .init(get: { viewModel.player }, set: { viewModel.player = $0 }))
.frame(width: scaledWidth, height: scaledHeight)
.opacity(scale == 1 ? 1 : 0.7)
.onAppear { viewModel.player?.play() }
} else if mediaType == .image, let image = viewModel.displayImage {
// Image View
Image(uiImage: image)
.resizable()
.scaledToFit()
.frame(width: scaledWidth, height: scaledHeight)
.opacity(scale == 1 ? 1 : 0.7)
}
}
.onTapGesture {
withAnimation(.easeInOut(duration: 0.1)) {
showControls.toggle()
}
}
//
if showControls {
VStack {
HStack {
Button(action: {
// BlindOutcomeView
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))
}
}) {
Image(systemName: "chevron.left")
.font(.system(size: 24))
.foregroundColor(.black)
}
Spacer()
}
Spacer()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.padding(.top, 50)
.padding(.leading, 20)
.zIndex(1000)
.transition(.opacity)
.onAppear {
// 2
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
withAnimation(.easeInOut(duration: 0.3)) {
showControls = true
}
}
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.animation(.easeInOut(duration: 1.0), value: scale)
.ignoresSafeArea()
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
withAnimation(.spring(response: 2.5, dampingFraction: 0.6, blendDuration: 1.0)) {
self.scale = 1.0
}
}
}
} else {
// Original content
VStack {
VStack(spacing: 20) {
if mediaType == .all {
//
HStack {
//
Button(action: showUserProfile) {
SVGImage(svgName: "User")
.frame(width: 24, height: 24)
.padding(13) // Increases tap area while keeping visual size
.contentShape(Rectangle()) // Makes the padded area tappable
}
.buttonStyle(PlainButtonStyle()) // Prevents the button from affecting the layout
Spacer()
// //
// NavigationLink(destination: TestView()) {
// Text("TestView")
// .font(.subheadline)
// .padding(.horizontal, 12)
// .padding(.vertical, 6)
// .background(Color.brown)
// .foregroundColor(.white)
// .cornerRadius(8)
// }
// //
// NavigationLink(destination: SubscribeView()) {
// Text("Subscribe")
// .font(.subheadline)
// .padding(.horizontal, 12)
// .padding(.vertical, 6)
// .background(Color.orange)
// .foregroundColor(.white)
// .cornerRadius(8)
// }
// .padding(.trailing)
// .fullScreenCover(isPresented: $showLogin) {
// LoginView()
// }
NavigationLink(destination: SubscribeView()) {
Text("\(viewModel.memberProfile?.remainPoints ?? 0)")
.font(Typography.font(for: .subtitle))
.fontWeight(.bold)
.padding(.horizontal, 12)
.padding(.vertical, 6)
.background(Color.black)
.foregroundColor(.white)
.cornerRadius(16)
}
.padding(.trailing)
.fullScreenCover(isPresented: $showLogin) {
LoginView()
}
}
.padding(.horizontal)
.padding(.top, 20)
}
//
VStack(alignment: .leading, spacing: 4) {
Text("Hi! Click And")
Text("Open Your Box~")
}
.font(Typography.font(for: .smallLargeTitle))
.fontWeight(.bold)
.foregroundColor(Color.themeTextMessageMain)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal)
.opacity(showScalingOverlay ? 0 : 1)
.offset(y: showScalingOverlay ? -UIScreen.main.bounds.height * 0.2 : 0)
.animation(.easeInOut(duration: 0.5), value: showScalingOverlay)
//
ZStack {
// 1. SVG
if !showScalingOverlay {
SVGImage(svgName: "BlindBg", contentMode: .fit)
// .position(x: UIScreen.main.bounds.width / 2,
// y: UIScreen.main.bounds.height * 0.325)
.opacity(showScalingOverlay ? 0 : 1)
.animation(.easeOut(duration: 1.5), value: showScalingOverlay)
}
if mediaType == .all && !showScalingOverlay {
ZStack {
SVGImage(svgName: "BlindCount")
.frame(width: 100, height: 60)
Text("\(viewModel.blindCount?.availableQuantity ?? 0) Boxes")
.font(Typography.font(for: .body, family: .quicksandBold))
.foregroundColor(.white)
.offset(x: 6, y: -18)
}
.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: "loading", isPlaying: animationPhase == .loading && !showScalingOverlay)
.frame(width: 300, height: 300)
// .onAppear {
// DispatchQueue.main.asyncAfter(deadline: .now() + 6) {
// withAnimation {
// animationPhase = .ready
// }
// }
// }
case .ready:
ZStack {
LottieView(name: "data", 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: "open", 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:
//
Color.clear
.frame(width: 300, height: 300)
// SVGImage(svgName: "BlindNone")
// .frame(width: 300, height: 300)
}
}
.offset(y: -50)
.compositingGroup()
.padding()
}
//
if !showScalingOverlay && !showMedia {
VStack(alignment: .leading, spacing: 8) {
// blindGeneratedescription
Text(viewModel.blindGenerate?.name ?? "Some box")
.font(Typography.font(for: .body, family: .quicksandBold))
.foregroundColor(Color.themeTextMessageMain)
Text(viewModel.blindGenerate?.description ?? "")
.font(.system(size: 14))
.foregroundColor(Color.themeTextMessageMain)
}
.frame(width: UIScreen.main.bounds.width * 0.70, alignment: .leading)
.padding()
.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 {
Button(action: {
if animationPhase == .ready {
//
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
}
} else if animationPhase == .none {
Router.shared.navigate(to: .mediaUpload)
}
}) {
if animationPhase == .loading {
Text("Next: \(viewModel.countdownText)")
.font(Typography.font(for: .body))
.fontWeight(.bold)
.frame(maxWidth: .infinity)
.padding()
.background(Color.white)
.foregroundColor(.black)
.cornerRadius(32)
} else if animationPhase == .ready {
Text("Ready")
.font(Typography.font(for: .body))
.fontWeight(.bold)
.frame(maxWidth: .infinity)
.padding()
.background(Color.themePrimary)
.foregroundColor(Color.themeTextMessageMain)
.cornerRadius(32)
} else {
Text("Go to Buy")
.font(Typography.font(for: .body))
.fontWeight(.bold)
.frame(maxWidth: .infinity)
.padding()
.background(Color.themePrimary)
.foregroundColor(Color.themeTextMessageMain)
.cornerRadius(32)
}
}
.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
}
}
// struct TransparentVideoPlayer: UIViewRepresentable {
// func makeUIView(context: Context) -> UIView {
// let view = UIView()
// view.backgroundColor = .clear
// view.isOpaque = false
// return view
// }
// func updateUIView(_ uiView: UIView, context: Context) {}
// }