import 'dart:io';
import 'package:get/get.dart';
import 'package:flutter/services.dart';
import 'package:injectable/injectable.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:jpush_flutter/jpush_interface.dart';
import 'package:keyboard/module/store/new_discount/new_discount_page.dart';
import 'package:keyboard/utils/atmob_log.dart';

import '../../data/consts/build_config.dart';
import '../../data/consts/constants.dart';
import '../../di/get_it.dart';
import '../../module/main/main_controller.dart';
import '../../router/app_pages.dart';

@singleton
class JpushHelper {
  static const String tag = "qqq JpushHelper";
  static String registrationId = "";

  static final JPushFlutterInterface _jpush = JPush.newJPush();

  JpushHelper();

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> init() async {
    String? platformVersion;
    AtmobLog.d(tag, "flutter init JPushHelper");
    print("qqq flutter init JPushHelper");
    try {
      _jpush.addEventHandler(
        onReceiveNotification: (Map<String, dynamic> message) async {
          AtmobLog.d(tag, "flutter onReceiveNotification: $message");


        },
        onOpenNotification: (Map<String, dynamic> message) async {
          AtmobLog.d(tag, "flutter onOpenNotification: $message");
          if (Get.isRegistered<MainController>() &&
              Get.currentRoute != RoutePath.newDiscount) {
            NewDiscountPage.start();
          }
          //清除应用图标角标数量
          _jpush.setBadge(-1);
        },
        onReceiveMessage: (Map<String, dynamic> message) async {
          AtmobLog.d(tag, "flutter onReceiveMessage: $message");
        },
        onReceiveNotificationAuthorization: (
          Map<String, dynamic> message,
        ) async {
          AtmobLog.d(
            tag,
            "flutter onReceiveNotificationAuthorization: $message",
          );
        },
        onNotifyMessageUnShow: (Map<String, dynamic> message) async {
          AtmobLog.d(tag, "flutter onNotifyMessageUnShow: $message");
        },
        onInAppMessageShow: (Map<String, dynamic> message) async {
          AtmobLog.d(tag, "flutter onInAppMessageShow: $message");
        },
        onCommandResult: (Map<String, dynamic> message) async {
          AtmobLog.d(tag, "flutter onCommandResult: $message");
        },
        onInAppMessageClick: (Map<String, dynamic> message) async {
          AtmobLog.d(tag, "flutter onInAppMessageClick: $message");
        },
        onConnected: (Map<String, dynamic> message) async {
          AtmobLog.d(tag, "flutter onConnected: $message");
        },
      );
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }
    _jpush.enableAutoWakeup(enable: true);
    _jpush.setAuth(enable: true);
    _jpush.setup(
      appKey: JpushConfig.jpushAppKey,
      channel: getChannelName(),
      production: false,
      debug: BuildConfig.isDebug,
    );
    _jpush.applyPushAuthority(
      new NotificationSettingsIOS(sound: true, alert: true, badge: true),
    );

    // Platform messages may fail, so we use a try/catch PlatformException.
    _jpush.getRegistrationID().then((rid) {
      AtmobLog.d(tag, "极光id get registration id : $rid");
      print("qqq 极光id get registration id : $rid");

      registrationId = rid;
    });

    if (Platform.isIOS) {
      // iOS要是使用应用内消息，请在页面进入离开的时候配置pageEnterTo 和  pageLeave 函数，参数为页面名。
      // _jpush.pageEnterTo("HomePage");
    }
    isNotificationEnabled().then((hasPermission) {
      AtmobLog.d(
        "JpushHelper",
        ("flutter isNotificationEnabled: $hasPermission"),
      );
      if (hasPermission) {
        return;
      } else {
        requestRequiredPermission();
      }
    });
  }

  Future<void> setTags({required List<String> tag}) async {
    _jpush.setTags(tag).then((result) {
      AtmobLog.d("JpushHelper", ("flutter setTags: $result"));
    });
  }

  Future<void> cleanTags() async {
    _jpush.cleanTags().then((result) {
      AtmobLog.d("JpushHelper", ("flutter cleanTags: $result"));
    });
  }

  Future<bool> isNotificationEnabled() async {
    return _jpush.isNotificationEnabled();
  }

  void requestRequiredPermission() {
    _jpush.requestRequiredPermission();
  }

  void openSettingsForNotification() {
    _jpush.openSettingsForNotification();
  }

  static JpushHelper getInstance() => getIt.get<JpushHelper>();
}
