import 'dart:io';

import 'package:atmob_logging/atmob_logging.dart' as ALog;
import 'package:flutter/material.dart';
import 'package:flutter_bugly/flutter_bugly.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:location/push_notification/ios_push_notification_service.dart';
import 'package:location/resource/colors.gen.dart';
import 'package:location/resource/string.gen.dart';
import 'package:location/resource/string_source.dart';
import 'package:location/router/app_pages.dart';
import 'package:location/sdk/bugly/bugly_helper.dart';
import 'package:location/sdk/gravity/gravity_helper.dart';
import 'package:location/sdk/map/map_helper.dart';
import 'package:location/sdk/quicklogin/quick_login_helper.dart';
import 'package:location/sdk/umeng/umeng_helper.dart';
import 'package:location/sdk/wechat/wechat_helper.dart';
import 'package:location/utils/app_info_util.dart';
import 'package:location/utils/atmob_log.dart';
import 'package:location/utils/mmkv_util.dart';
import 'package:location/utils/privacy_compliance.dart';
import 'package:location/utils/toast_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'data/consts/build_config.dart';
import 'data/consts/channel_util.dart';
import 'data/consts/constants.dart';
import 'device/device_info_util.dart';
import 'di/get_it.dart';

void main() {
  FlutterBugly.postCatchedException(() async {
    WidgetsFlutterBinding.ensureInitialized();

    //必要初始化
    await initRequired();

    //非隐私相关
    initCommon();

    runApp(const MyApp());

    //隐私相关：系统参数&第三方sdk初始化
    await PrivacyCompliance.ensurePolicyGranted(AppInitTask());

    ///实现推送
    if (Platform.isIOS) {
      initPushNotification();
    }

    //檢查地址
    checkEnv();
  });
}

Future<void> initRequired() async {
  //Log
  AtmobLog.setLogLevel(
      BuildConfig.isDebug ? ALog.LogLevel.verbose : ALog.LogLevel.none);

  //存储
  await KVUtil.init();

  //getit
  configureDependencies();
}

void initCommon() {
  //全局配置smartDialog
  smartConfig();
  //渠道(仅Android)
  ChannelUtil.initChannel();
  //微信注册
  WechatHelper.registerApp();
}

/// 隐私相关初始化
class AppInitTask implements EnsurePolicyGrant {
  @override
  Future<void> onPolicyGrant() async {
    //初始化基础信息
    await appInfoUtil.init();
    await deviceInfoUtil.init();
    //bugly
    BuglyHelper.init();
    //引力引擎
    GravityHelper.init();
    //友盟
    UmengHelper.initCommon();
    //地图sdk
    await MapHelper.init();
    //一键登录
    QuickLoginHelper.init();
  }
}

void smartConfig() {
  SmartDialog.config.custom =
      SmartConfigCustom(animationType: SmartAnimationType.fade);
}

void checkEnv() {
  if (!Constants.isProdEnv() && !BuildConfig.isDebug) {
    ToastUtil.show('不是正式环境！！！', addPostFrame: true);
  }
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: const Size(360, 640),
      builder: (_, child) {
        return buildApp();
      },
    );
  }

  Widget buildApp() {
    return RefreshConfiguration(
      headerBuilder: () => Platform.isAndroid
          ? const MaterialClassicHeader(color: ColorName.colorPrimary)
          : const ClassicHeader(),
      footerBuilder: () => ClassicFooter(
        canLoadingText: StringName.loadingMore,
        idleText: StringName.loadPullUp,
        loadingText: StringName.loadingTxt,
        noDataText: StringName.loadNoData,
        failedText: StringName.loadFailed,
      ),
      child: Platform.isAndroid ? buildMaterialApp() : buildIosApp(),
    );
  }

  Widget buildIosApp() {
    return GetCupertinoApp(
      onGenerateTitle: AppCommonConfig.appName,
      getPages: AppCommonConfig.getPages,
      initialRoute: AppCommonConfig.initialRoute,
      initialBinding: AppCommonConfig.initialBinding,
      navigatorObservers: AppCommonConfig.navigatorObservers,
      builder: AppCommonConfig.builder,
      translations: AppCommonConfig.translations,
      localizationsDelegates: AppCommonConfig.localizations.delegates,
      supportedLocales: AppCommonConfig.localizations.supportedLocales,
      locale: AppCommonConfig.localizations.locale,
      fallbackLocale: AppCommonConfig.localizations.fallbackLocale,
    );
  }

  Widget buildMaterialApp() {
    return GetMaterialApp(
      onGenerateTitle: AppCommonConfig.appName,
      getPages: AppCommonConfig.getPages,
      initialRoute: AppCommonConfig.initialRoute,
      initialBinding: AppCommonConfig.initialBinding,
      theme: ThemeData(
        useMaterial3: true,
        textSelectionTheme: const TextSelectionThemeData(
          cursorColor: ColorName.colorPrimary, // 设置默认光标颜色
          selectionHandleColor: ColorName.colorPrimary, // 设置光标下面水滴的颜色
        ),
      ),
      navigatorObservers: AppCommonConfig.navigatorObservers,
      builder: AppCommonConfig.builder,
      translations: AppCommonConfig.translations,
      localizationsDelegates: AppCommonConfig.localizations.delegates,
      supportedLocales: AppCommonConfig.localizations.supportedLocales,
      locale: AppCommonConfig.localizations.locale,
      fallbackLocale: AppCommonConfig.localizations.fallbackLocale,
    );
  }
}

class AppCommonConfig {
  static GenerateAppTitle? appName = (_) => Platform.isIOS? StringName.appNameIos : StringName.appName;

  // 路由配置
  static List<GetPage>? getPages = AppPage.pages;
  static const initialRoute = RoutePath.splash;

  // 初始化绑定
  static Bindings initialBinding = AppBinding();

  // 导航观察者
  static List<NavigatorObserver> navigatorObservers = [
    FlutterSmartDialog.observer
  ];

  // 弹窗初始化
  static final builder = FlutterSmartDialog.init();

  // 本地化配置
  static const localizations = (
    delegates: [
      GlobalMaterialLocalizations.delegate,
      GlobalWidgetsLocalizations.delegate,
      GlobalCupertinoLocalizations.delegate,
    ],
    supportedLocales: [Locale('zh', 'CN')],
    locale: Locale('zh', 'CN'),
    fallbackLocale: Locale('zh', 'CN'),
  );

  // 多语言配置
  static Translations translations = StringResource();
}

///加入推送功能
void initPushNotification() {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化推送服务
  IosPushNotificationService.initialize();

  // 设置回调
  IosPushNotificationService.onTokenReceived = (token) {
    print('Device token: $token');
    // 可以将令牌发送到服务器
  };

  IosPushNotificationService.onTokenError = (error) {
    print('Token error: $error');
  };

  IosPushNotificationService.onNotificationReceived = (data) {
    print('Received notification: $data');
    IosPushNotificationService.handleNotificationPushChick(data);
    // 处理前台收到的通知
  };

  IosPushNotificationService.onNotificationTapped = (data) {
    //{skipType: 2, aps: {alert: {subtitle: Your friend Emergency Help - it is recommended to contact this friend immediately. , title: LocateX}, sound: default}}
    print('Notification tapped: $data');
    IosPushNotificationService.handleNotificationPushChick(data);
    // 处理通知点击事件
    ///埋点
  };
}