import 'dart:async';

import 'package:app_links/app_links.dart';
import 'package:flutter/material.dart';
import 'package:loopin/IM/im_friend_listeners.dart';

/// 全局监听schem启动参数 wuzhongjie://open?xxx=xxx
class DeepLinkListener extends StatefulWidget {
  final Widget child;

  const DeepLinkListener({required this.child, super.key});

  @override
  State<DeepLinkListener> createState() => _DeepLinkListenerState();
}

class _DeepLinkListenerState extends State<DeepLinkListener> {
  final AppLinks _appLinks = AppLinks();
  StreamSubscription? _sub;

  @override
  void initState() {
    super.initState();
    _handleLinks();
  }

  /// 统一处理冷启动和热启动
  void _handleLinks() {
    _sub = _appLinks.uriLinkStream.listen((Uri? uri) {
      if (uri != null) {
        _parseAppParameter(uri);
      }
    }, onError: (err) {
      logger.e('启动参数监听报错: $err');
    });
  }

  // 小程序返回热启动参数
  void _parseAppParameter(Uri uri) {
    final appParameter = uri.queryParameters['appParameter'];
    if (appParameter != null) {
      logger.e('收到启动参数 appParameter: $appParameter');
    }
  }

  @override
  void dispose() {
    _sub?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}
