import 'dart:io';

import 'package:atmob_logging/atmob_logging.dart';
import 'package:flutter/material.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:keyboard/plugins/keyboard_android_platform.dart';
import 'package:keyboard/resource/colors.gen.dart';
import 'package:keyboard/resource/string.gen.dart';
import 'package:keyboard/resource/string_source.dart';
import 'package:keyboard/router/app_pages.dart';
import 'package:keyboard/utils/app_info_util.dart';
import 'package:keyboard/utils/atmob_log.dart';
import 'package:keyboard/utils/channel_util.dart';
import 'package:keyboard/utils/mmkv_util.dart';
import 'package:keyboard/utils/privacy_compliance.dart';
import 'package:keyboard/utils/toast_util.dart';

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

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

  await initRequired();

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

  if (Platform.isAndroid) {
    //键盘
    KeyboardAndroidPlatform.getInstance();
  }

  runApp(const MyApp());
  //檢查地址
  checkEnv();
}

Future<void> initRequired() async {
  //存储
  await KVUtil.init();

  //getit
  configureDependencies();
}

void initCommon() {
  smartConfig();
  AtmobLog.setLogLevel(BuildConfig.isDebug ? LogLevel.verbose : LogLevel.none);

  //渠道(仅Android)
  ChannelUtil.initChannel();
}

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

/// 隐私相关初始化
class AppInitTask implements EnsurePolicyGrant {
  @override
  Future<void> onPolicyGrant() async {
    //初始化基础信息
    await appInfoUtil.init();
    await deviceInfoUtil.init();
    //初始化其他sdk
  }
}

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

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

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

  buildApp() {
    return Platform.isAndroid ? _buildMaterialApp() : _buildIosApp();
  }

  _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.localizationsTranslations,
      localizationsDelegates: AppCommonConfig.localizations.delegates,
      locale: AppCommonConfig.localizations.locale,
      fallbackLocale: AppCommonConfig.localizations.fallbackLocale,
    );
  }

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

class AppCommonConfig {
  static GenerateAppTitle appName = (_) => StringName.appName;

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

  // 初始化绑定
  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 localizationsTranslations = StringResource();
}
