import 'package:flutter/services.dart';
import 'package:mobile_use_statistics/flutter_mobile_statistics.dart';


import '../data/bean/user_info.dart';
import '../data/repositories/account_repository.dart';
import '../data/repositories/phone_event_repository.dart';
import '../data/repositories/track_repository.dart';
import '../dialog/common_alert_dialog_impl.dart';
import '../dialog/common_confirm_dialog_impl.dart';
import '../handler/error_handler.dart';
import '../module/login/login_page.dart';
import '../module/member/member_page.dart';
import '../module/track/track_dialog/track_choose_friend_dialog.dart';
import '../module/track/track_page.dart';
import '../sdk/wechat/wechat_share_util.dart';
import '../utils/toast_util.dart';


class IosPushNotificationService {
  static const MethodChannel _channel = MethodChannel('com.example.app/push_notification');

  // 回调函数
  static Function(String)? onTokenReceived;
  static Function(String)? onTokenError;
  static Function(Map<String, dynamic>)? onNotificationReceived;
  static Function(Map<String, dynamic>)? onNotificationTapped;

  // 初始化推送服务
  static void initialize() {
    _channel.setMethodCallHandler((call) async {
      switch (call.method) {
        case 'onTokenReceived':
          onTokenReceived?.call(call.arguments);
          break;
        case 'onTokenError':
          onTokenError?.call(call.arguments);
          break;
        case 'onNotificationReceived':
          if (call.arguments is Map) {
            onNotificationReceived?.call(Map<String, dynamic>.from(call.arguments));
          }
          break;
        case 'onNotificationTapped':
          if (call.arguments is Map) {
            onNotificationTapped?.call(Map<String, dynamic>.from(call.arguments));
          }
          break;
        case 'applicationDidFinishLaunchingWithOptions':
          ///第一次打开app
          MobileUseStatistics.appLaunchAnActivation();
          break;
        case 'applicationDidEnterBackground':
        //进入后台通知
          MobileUseStatistics.appEntersTheBacken();
          break;
        default:
          throw PlatformException(
            code: 'UNIMPLEMENTED',
            message: 'Method not implemented',
            details: null,
          );
      }
    });
  }

  // 请求推送权限
  static Future<bool> requestPermission() async {
    try {
      final bool? granted = await _channel.invokeMethod('requestPermission');
      return granted ?? false;
    } on PlatformException catch (e) {
      print('Failed to request permission: ${e.message}');
      return false;
    }
  }

  // 获取设备令牌
  static Future<String?> getDeviceToken() async {
    try {
      final String? token = await _channel.invokeMethod('getDeviceToken');
      print("Strdefdjifjd---${token}");
      return token;
    } on PlatformException catch (e) {
      print('Failed to get device token: ${e.message}');
      return null;
    }
  }

  ///处理推送各种点击
  static void handleNotificationPushChick(Map<String,dynamic> pushDict) {
    String skipType = pushDict["functionType"];
    if (skipType == "daily_track") {
      TrackRepository trackRepository = TrackRepository.getInstance();
      trackRepository.locationTrackDailyDialogs().then((trackResponse) {
        //print("trackResponsesfsfsd---${trackResponse}");
        if ((trackResponse.trackDailyList ?? []).isNotEmpty) {
          if ((trackResponse.trackDailyList ?? []).length == 1) {
            UserInfo seleUseInfo = (trackResponse.trackDailyList ?? []).first;
            seleUseInfo.isShowYesterday = true;
            onViewTraceClic((trackResponse.trackDailyList ?? []).first);
          } else {
            TrackChooseFriendDialog.show(trackDailyList: trackResponse.trackDailyList,onSelectItem: (selectInfo) {
              selectInfo.isShowYesterday = true;
              onViewTraceClic(selectInfo);
            });
          }
        }
      }).catchError((error) {
        ErrorHandler.toastError(error);
      });
    }
  }

  static void onViewTraceClic(UserInfo userInfo) {
    AccountRepository accountRepository = AccountRepository.getInstance();
    if (!accountRepository.isLogin.value) {
      showTraceTipsDialog(onConfirm: () {
        LoginPage.start();
      });
      return;
    }
    if (!(userInfo.virtual ?? false) && accountRepository.memberIsExpired()) {
      MemberPage.start();
      return;
    }

    if (userInfo.blockedMe == true) {
      showBlockMeTipDialog(confirmOnTap: () {
        WechatShareUtil.shareWebPage().catchError((error) {
          ToastUtil.show(error.toString());
        });
      });
      return;
    }
    TrackPage.start(userInfo);
  }
}
