import 'dart:async';

import 'package:autosos_flutter/config/getui_constant.dart';
import 'package:autosos_flutter/util/sp_util.dart';
import 'package:flutter/foundation.dart';
import 'package:getuiflut/getuiflut.dart';

/// 推送服务（对应 Android 个推封装）
/// 使用 getuiflut 0.2.x 实际 API（addEventHandler 需要全部回调）
class PushService {
  static final PushService instance = PushService._();
  PushService._();

  String? _clientId;
  String? get clientId => _clientId;

  final _payloadController = StreamController<Map<String, dynamic>>.broadcast();
  Stream<Map<String, dynamic>> get payloadStream => _payloadController.stream;

  final _notificationController = StreamController<Map<String, dynamic>>.broadcast();
  Stream<Map<String, dynamic>> get notificationStream => _notificationController.stream;

  bool _started = false;

  /// 启动个推 SDK
  void init() {
    try {
      if (_started) return;

      // Android 通过 initGetuiSdk 启动（自动）
      // iOS 通过 startSdk 启动
      if (defaultTargetPlatform == TargetPlatform.iOS) {
        Getuiflut().startSdk(
          appId: GetuiConstant.appId,
          appKey: GetuiConstant.appKey,
          appSecret: GetuiConstant.appSecret,
        );
      } else {
        Getuiflut().initGetuiSdk;
      }

      // 注册事件回调（addEventHandler 全部为 required）
      Getuiflut().addEventHandler(
        onReceiveClientId: (String message) async {
          _clientId = message;
          SPUtil().setString('clientId', message);
          debugPrint('Getui ClientId: $message');
        },

        onRegisterDeviceToken: (String token) async {
          debugPrint('Getui device token: $token');
        },
        onNotificationMessageArrived: (Map<String, dynamic> msg) async {
          debugPrint('Getui notification arrived: $msg');
          _notificationController.add(msg);
        },
        onNotificationMessageClicked: (Map<String, dynamic> msg) async {
          debugPrint('Getui notification clicked: $msg');
          _notificationController.add({...msg, '_clicked': true});
        },
        onTransmitUserMessageReceive: (Map<String, dynamic> msg) async {
          debugPrint('Getui transmit msg: $msg');
        },
        onReceiveOnlineState: (String state) async {
          debugPrint('Getui online state: $state');
        },
        onReceivePayload: (Map<String, dynamic> message) async {
          debugPrint('Getui receive payload: $message');
          _payloadController.add(message);
        },
        onReceiveNotificationResponse: (Map<String, dynamic> message) async {
          debugPrint('Getui receive notification response: $message');
        },
        onAppLinkPayload: (String message) async {
          debugPrint('Getui app link: $message');
        },
        onPushModeResult: (Map<String, dynamic> message) async {
          debugPrint('Getui push mode: $message');
        },
        onSetTagResult: (Map<String, dynamic> message) async {
          debugPrint('Getui set tag result: $message');
        },
        onAliasResult: (Map<String, dynamic> message) async {
          debugPrint('Getui alias result: $message');
        },
        onQueryTagResult: (Map<String, dynamic> message) async {
          debugPrint('Getui query tag result: $message');
        },
        onWillPresentNotification: (Map<String, dynamic> message) async {
          debugPrint('Getui will present: $message');
        },
        onOpenSettingsForNotification: (Map<String, dynamic> message) async {
          debugPrint('Getui open settings: $message');
        },
        onGrantAuthorization: (String granted) async {
          debugPrint('Getui grant auth: $granted');
        },
        onLiveActivityResult: (Map<String, dynamic> message) async {
          debugPrint('Getui live activity: $message');
        },
        onRegisterPushToStartTokenResult: (Map<String, dynamic> message) async {
          debugPrint('Getui push to start: $message');
        },
      );

      _started = true;
    } catch (e) {
      debugPrint('PushService init failed: $e');
    }
  }

  /// 关闭推送通道（用户退出登录后）
  void turnOff() {
    try {
      Getuiflut().turnOffPush();
    } catch (e) {
      debugPrint('turnOff push failed: $e');
    }
  }

  /// 开启推送
  void turnOn() {
    try {
      Getuiflut().turnOnPush();
    } catch (e) {
      debugPrint('turnOn push failed: $e');
    }
  }

  /// 获取 clientId（异步）
  Future<String?> fetchClientId() async {
    try {
      final id = await Getuiflut().getClientId;
      _clientId = id;
      if (id.isNotEmpty) {
        SPUtil().setString('clientId', id);
      }
      return id;
    } catch (e) {
      debugPrint('fetchClientId failed: $e');
      return null;
    }
  }

  /// 绑定用户别名（手机号 + sn 时间戳）
  void bindAlias(String alias, String sn) {
    try {
      Getuiflut().bindAlias(alias, sn);
    } catch (e) {
      debugPrint('bindAlias failed: $e');
    }
  }

  /// 解绑别名
  void unbindAlias(String alias, String sn, {bool isSelf = true}) {
    try {
      Getuiflut().unbindAlias(alias, sn, isSelf);
    } catch (e) {
      debugPrint('unbindAlias failed: $e');
    }
  }

  /// 设置标签
  void setTags(List<String> tags, String sn) {
    try {
      Getuiflut().setTag(tags, sn);
    } catch (e) {
      debugPrint('setTags failed: $e');
    }
  }

  /// 静默时间（夜间免打扰）—— 实际 API 仅接受 beginHour + durationHours
  void setSilentTime(int beginHour, int durationHours) {
    try {
      Getuiflut().setSilentTime(beginHour, durationHours);
    } catch (e) {
      debugPrint('setSilentTime failed: $e');
    }
  }

  /// 角标清零
  void resetBadge() {
    try {
      Getuiflut().resetBadge();
    } catch (e) {
      debugPrint('resetBadge failed: $e');
    }
  }

  void dispose() {
    _payloadController.close();
    _notificationController.close();
  }
}
