import 'dart:async'; import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:webview_flutter/webview_flutter.dart'; import 'package:yumi/app/routes/sc_fluro_navigator.dart'; import 'package:yumi/modules/room_game/bridge/hotgame_js_bridge.dart'; import 'package:yumi/modules/room_game/data/models/room_game_models.dart'; import 'package:yumi/modules/room_game/data/room_game_repository.dart'; import 'package:yumi/modules/room_game/utils/room_game_viewport.dart'; import 'package:yumi/modules/room_game/views/baishun_loading_view.dart'; import 'package:yumi/modules/wallet/wallet_route.dart'; import 'package:yumi/shared/tools/sc_h5_url_utils.dart'; import 'package:yumi/ui_kit/components/sc_tts.dart'; class HotgameGamePage extends StatefulWidget { const HotgameGamePage({ super.key, required this.roomId, required this.game, required this.launchModel, }); final String roomId; final RoomGameListItemModel game; final BaishunLaunchModel launchModel; @override State createState() => _HotgameGamePageState(); } class _HotgameGamePageState extends State { static const double _sevenScreenRatio = 0.72; final RoomGameRepository _repository = RoomGameRepository(); final Set> _webGestureRecognizers = >{ Factory(() => EagerGestureRecognizer()), }; late final WebViewController _controller; Timer? _bridgeBootstrapTimer; Timer? _loadingFallbackTimer; bool _isLoading = true; bool _isClosing = false; bool _didReceiveBridgeMessage = false; bool _didFinishPageLoad = false; bool _didInjectProgressBridge = false; int _bridgeInjectCount = 0; String? _errorMessage; @override void initState() { super.initState(); _controller = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setBackgroundColor(Colors.black) ..addJavaScriptChannel( HotgameJsBridge.channelName, onMessageReceived: _handleBridgeMessage, ) ..addJavaScriptChannel( HotgameBridgeActions.recharge, onMessageReceived: (JavaScriptMessage message) => _handleNamedChannelMessage( HotgameBridgeActions.recharge, message, ), ) ..addJavaScriptChannel( HotgameBridgeActions.quit, onMessageReceived: (JavaScriptMessage message) => _handleNamedChannelMessage( HotgameBridgeActions.quit, message, ), ) ..addJavaScriptChannel( HotgameBridgeActions.loadComplete, onMessageReceived: (JavaScriptMessage message) => _handleNamedChannelMessage( HotgameBridgeActions.loadComplete, message, ), ) ..setNavigationDelegate( NavigationDelegate( onPageStarted: (String url) { _log('page_started url=${_clip(url, 240)}'); _prepareForPageLoad(); }, onPageFinished: (String url) async { _didFinishPageLoad = true; _log('page_finished url=${_clip(url, 240)}'); await _injectBridge(reason: 'page_finished'); if (!mounted || _errorMessage != null) { return; } setState(() { _isLoading = false; }); }, onProgress: (int progress) { if (_didInjectProgressBridge || progress < 10 || _errorMessage != null) { return; } _didInjectProgressBridge = true; unawaited(_injectBridge(reason: 'progress_$progress')); }, onWebResourceError: (WebResourceError error) { _log( 'web_resource_error code=${error.errorCode} ' 'type=${error.errorType} desc=${_clip(error.description, 300)}', ); _stopBridgeBootstrap(reason: 'web_resource_error'); if (!mounted) { return; } setState(() { _errorMessage = error.description; _isLoading = false; }); }, ), ); _log('init launch=${_stringifyForLog(_buildLaunchSummary())}'); unawaited(_loadGameEntry()); } @override void dispose() { _stopBridgeBootstrap(reason: 'dispose'); super.dispose(); } void _prepareForPageLoad() { _didReceiveBridgeMessage = false; _didFinishPageLoad = false; _didInjectProgressBridge = false; _bridgeInjectCount = 0; _stopBridgeBootstrap(reason: 'prepare_page_load'); _bridgeBootstrapTimer = Timer.periodic(const Duration(milliseconds: 250), ( Timer timer, ) { if (!mounted || _didReceiveBridgeMessage || _errorMessage != null) { timer.cancel(); return; } unawaited(_injectBridge(reason: 'bootstrap')); if (_didFinishPageLoad && timer.tick >= 12) { timer.cancel(); } }); _loadingFallbackTimer = Timer(const Duration(seconds: 6), () { if (!mounted || _didReceiveBridgeMessage || _errorMessage != null) { return; } setState(() { _isLoading = false; }); }); if (!mounted) { return; } setState(() { _isLoading = true; _errorMessage = null; }); } void _stopBridgeBootstrap({String reason = 'manual'}) { if (_bridgeBootstrapTimer != null || _loadingFallbackTimer != null) { _log('stop_bootstrap reason=$reason'); } _bridgeBootstrapTimer?.cancel(); _bridgeBootstrapTimer = null; _loadingFallbackTimer?.cancel(); _loadingFallbackTimer = null; } Future _loadGameEntry() async { try { _prepareForPageLoad(); final entryUrl = widget.launchModel.entry.entryUrl.trim(); _log( 'load_entry launchMode=${widget.launchModel.entry.launchMode} ' 'entryUrl=${_clip(entryUrl, 240)}', ); if (entryUrl.isEmpty || entryUrl.startsWith('mock://')) { await _controller.loadHtmlString(_buildMockHtml()); return; } final h5Url = SCH5UrlUtils.appendToken(entryUrl); final uri = Uri.tryParse(h5Url); if (uri == null) { throw Exception('Invalid hotgame entry url: $entryUrl'); } await _controller.loadRequest(uri); } catch (error) { _log('load_entry_error error=${_clip(error.toString(), 400)}'); if (!mounted) { return; } setState(() { _errorMessage = error.toString(); _isLoading = false; }); } } Future _injectBridge({String reason = 'manual'}) async { _bridgeInjectCount += 1; if (reason != 'bootstrap' || _bridgeInjectCount <= 3 || _bridgeInjectCount % 5 == 0) { _log('inject_bridge reason=$reason count=$_bridgeInjectCount'); } try { await _controller.runJavaScript( HotgameJsBridge.bootstrapScript(launchPayload: _buildLaunchPayload()), ); } catch (error) { _log( 'inject_bridge_error reason=$reason error=${_clip(error.toString(), 300)}', ); } } Future _handleBridgeMessage(JavaScriptMessage message) async { _log('channel_message raw=${_clip(message.message, 600)}'); final bridgeMessage = HotgameBridgeMessage.parse(message.message); await _dispatchBridgeMessage(bridgeMessage); } Future _handleNamedChannelMessage( String action, JavaScriptMessage message, ) async { final bridgeMessage = HotgameBridgeMessage.fromAction( action, message.message, ); _log('named_channel action=$action raw=${_clip(message.message, 600)}'); await _dispatchBridgeMessage(bridgeMessage); } Future _dispatchBridgeMessage( HotgameBridgeMessage bridgeMessage, ) async { if (bridgeMessage.action == HotgameBridgeActions.debugLog) { final tag = bridgeMessage.payload['tag']?.toString().trim(); final message = bridgeMessage.payload['message']?.toString() ?? ''; _log('h5_debug tag=${tag ?? 'unknown'} message=${_clip(message, 800)}'); return; } _didReceiveBridgeMessage = true; _stopBridgeBootstrap(reason: 'bridge_message_${bridgeMessage.action}'); _log( 'bridge_action action=${bridgeMessage.action} ' 'payload=${_stringifyForLog(_sanitizeForLog(bridgeMessage.payload))}', ); switch (bridgeMessage.action) { case HotgameBridgeActions.recharge: await _openRechargeAndNotifyGame(); break; case HotgameBridgeActions.quit: await _closeAndExit(reason: 'h5_quit'); break; case HotgameBridgeActions.loadComplete: if (!mounted) { return; } setState(() { _isLoading = false; _errorMessage = null; }); break; default: _log('bridge_action_unhandled action=${bridgeMessage.action}'); break; } } Future _openRechargeAndNotifyGame() async { _log('hotgame_recharge open_wallet'); await SCNavigatorUtils.push(context, WalletRoute.recharge); try { await _controller.runJavaScript( HotgameJsBridge.buildRechargeSuccessScript(), ); } catch (error) { _log( 'recharge_success_notify_error error=${_clip(error.toString(), 300)}', ); } } Future _reload() async { if (!mounted) { return; } setState(() { _errorMessage = null; _isLoading = true; }); await _loadGameEntry(); } Future _closeAndExit({String reason = 'user_exit'}) async { if (_isClosing) { return; } _isClosing = true; try { final sessionId = widget.launchModel.gameSessionId.trim(); if (sessionId.isNotEmpty && !sessionId.startsWith('mock')) { await _repository.closeGame( provider: widget.game.provider, roomId: widget.roomId, gameSessionId: sessionId, reason: reason, params: const {}, ); } } catch (error) { _log('close_error error=${_clip(error.toString(), 300)}'); } if (mounted) { Navigator.of(context).pop(); } } String _resolveScreenMode() { return resolveRoomGameScreenMode( widget.game.launchParams, fullScreen: widget.game.fullScreen, ); } int _resolveSafeHeight() { if (widget.launchModel.entry.safeHeight > 0) { return widget.launchModel.entry.safeHeight; } if (widget.game.safeHeight > 0) { return widget.game.safeHeight; } return 0; } double _calculateBodyHeight(BuildContext context) { final screenMode = _resolveScreenMode(); final maxDialogHeight = resolveRoomGameAvailableHeight( context, reservedTop: 12.w, ); if (maxDialogHeight <= 0) { return 0; } if (screenMode == 'full') { return maxDialogHeight; } if (screenMode == 'seven') { return maxDialogHeight * _sevenScreenRatio; } return clampRoomGameHeight( _calculatePreferredBodyHeight(context), maxDialogHeight, ); } double _calculatePreferredBodyHeight(BuildContext context) { final mediaQuery = MediaQuery.maybeOf(context); final screenSize = mediaQuery?.size ?? Size.zero; final safeHeight = _resolveSafeHeight(); final fallback = screenSize.width; if (safeHeight > 0 && screenSize.width > 0) { final ratio = roomGameDesignWidth / safeHeight; return screenSize.width / ratio; } return fallback; } void _log(String message) {} String _maskValue(String value, {int keepStart = 6, int keepEnd = 4}) { final trimmed = value.trim(); if (trimmed.isEmpty) { return ''; } if (trimmed.length <= keepStart + keepEnd) { return trimmed; } return '${trimmed.substring(0, keepStart)}***${trimmed.substring(trimmed.length - keepEnd)}'; } Object? _sanitizeForLog(Object? value, {String key = ''}) { final lowerKey = key.toLowerCase(); final shouldMask = lowerKey.contains('code') || lowerKey.contains('token') || lowerKey.contains('authorization'); if (value is Map) { final result = {}; for (final MapEntry entry in value.entries) { result[entry.key.toString()] = _sanitizeForLog( entry.value, key: entry.key.toString(), ); } return result; } if (value is List) { return value.map((Object? item) => _sanitizeForLog(item)).toList(); } if (value is String) { final normalized = shouldMask ? _maskValue(value) : value; return _clip(normalized, 600); } return value; } String _clip(String value, [int limit = 600]) { final trimmed = value.trim(); if (trimmed.length <= limit) { return trimmed; } return '${trimmed.substring(0, limit)}...'; } String _stringifyForLog(Object? value) { if (value == null) { return ''; } try { return _clip(jsonEncode(value), 800); } catch (_) { return _clip(value.toString(), 800); } } Map _buildLaunchPayload() { return { 'provider': widget.launchModel.provider, 'gameId': widget.launchModel.gameId, 'providerGameId': widget.launchModel.providerGameId, 'gameSessionId': widget.launchModel.gameSessionId, 'entry': widget.launchModel.entry.toJson(), 'launchConfig': widget.launchModel.launchConfig.toJson(), 'roomState': widget.launchModel.roomState.toJson(), 'game': { 'gameId': widget.game.gameId, 'provider': widget.game.provider, 'gameType': widget.game.gameType, 'name': widget.game.name, 'launchMode': widget.game.launchMode, 'launchParams': widget.game.launchParams, }, }; } Map _buildLaunchSummary() { final payload = _buildLaunchPayload(); return { 'roomId': widget.roomId, 'provider': widget.game.provider, 'gameId': widget.game.gameId, 'providerGameId': widget.launchModel.providerGameId, 'gameSessionId': widget.launchModel.gameSessionId, 'entry': _sanitizeForLog(payload['entry']), 'launchConfig': _sanitizeForLog(payload['launchConfig']), 'roomState': _sanitizeForLog(payload['roomState']), }; } String _buildMockHtml() { return '''

Hotgame Mock

'''; } @override Widget build(BuildContext context) { final bodyHeight = _calculateBodyHeight(context); final bottomFrameHeight = resolveRoomGameCompatibilityBottomHeight(context); return PopScope( canPop: false, onPopInvokedWithResult: (bool didPop, Object? result) async { if (didPop) { return; } await _closeAndExit(); }, child: Material( color: Colors.transparent, child: Align( alignment: Alignment.bottomCenter, child: ClipRRect( borderRadius: BorderRadius.only( topLeft: Radius.circular(24.w), topRight: Radius.circular(24.w), ), child: Container( width: ScreenUtil().screenWidth, height: bodyHeight + bottomFrameHeight, color: const Color(0xFF081915), child: Stack( children: [ Positioned( left: 0, right: 0, top: 0, bottom: bottomFrameHeight, child: WebViewWidget( controller: _controller, gestureRecognizers: _webGestureRecognizers, ), ), if (bottomFrameHeight > 0) Positioned( left: 0, right: 0, bottom: 0, height: bottomFrameHeight, child: RoomGameCompatibilityBottomFrame( height: bottomFrameHeight, ), ), if (_errorMessage != null) _buildErrorState(), if (_isLoading && _errorMessage == null) const IgnorePointer( ignoring: true, child: BaishunLoadingView( message: 'Waiting for Hotgame...', ), ), ], ), ), ), ), ), ); } Widget _buildErrorState() { return Positioned.fill( child: Container( color: Colors.black.withValues(alpha: 0.88), padding: EdgeInsets.symmetric(horizontal: 28.w), alignment: Alignment.center, child: Column( mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.error_outline, color: Colors.white70, size: 34.w), SizedBox(height: 12.w), Text( 'Hotgame failed to load', style: TextStyle( color: Colors.white, fontSize: 16.sp, fontWeight: FontWeight.w700, ), ), SizedBox(height: 8.w), Text( _errorMessage ?? '', textAlign: TextAlign.center, style: TextStyle(color: Colors.white70, fontSize: 12.sp), ), SizedBox(height: 16.w), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ TextButton(onPressed: _reload, child: const Text('Retry')), SizedBox(width: 10.w), TextButton( onPressed: () { SCTts.show('Please verify the Hotgame entry url'); }, child: const Text('Tips'), ), ], ), ], ), ), ); } }