import 'package:bot_toast/bot_toast.dart';
import 'package:eitc_erm_dental_flutter/db_util.dart';
import 'package:eitc_erm_dental_flutter/funcs.dart';
import 'package:eitc_erm_dental_flutter/sp_util.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image/image.dart' as img;
import 'package:package_info_plus/package_info_plus.dart';

import 'app_router.dart';
import 'generated/assets.dart';
import 'generated/l10n.dart';
import 'global.dart';

///全局导航key
final GlobalKey<NavigatorState> navigatorKey = GlobalKey();

void main() async {
  ///提前实例化WidgetsBinding
  WidgetsFlutterBinding.ensureInitialized();

  ///初始化Token
  await _initSettings();

  ///初始化数据库
  await DbUtil.instance.init();

  ///加载字体
  _loadFonts();

  runApp(ProviderScope(child: MyApp()));
}

///初始化设置
Future _initSettings() async {
  //初始化日志
  await initLog();

  PackageInfo packageInfo = await PackageInfo.fromPlatform();
  logd("""
    ====================app启动====================
    appName=${packageInfo.appName}
    flavor=$appFlavor
    packageName=${packageInfo.packageName}
    version=${packageInfo.version}
    buildNumber=${packageInfo.buildNumber}
    ==============================================
   """);

  //更新token
  updateToken(await SpUtil.getToken());
  //更新选择的咨询人ID
  selectedPatientId = await SpUtil.getSelectedPatientId();

  if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) {
    await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);
  }

  //注册微信SDK
  bool wxResult =
      await fluwx.registerApi(appId: wxAppId, universalLink: wxUniversalLink);
  logd("微信SDK注册结果=$wxResult");
  fluwx.addSubscriber((response) {
    logd(
        "微信SDK回调,isSuccess=${response.isSuccessful},data=${response.toRecord()}");
  });
}

void _loadFonts() async {
  logd("加载字体");
  try {
    ByteData data = await rootBundle.load(Assets.fontsBmfont);
    photoFont = img.BitmapFont.fromZip(data.buffer.asUint8List());
  } catch (e) {
    loge("加载字体异常", error: e);
  }
}

class MyApp extends StatelessWidget {
  final AppRouter _appRouter = AppRouter(navigatorKey: navigatorKey);

  MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    final botToastBuilder = BotToastInit();

    //使用这种方式处理旋转屏幕后ScreenUtil的数值问题,会导致这里多次build
    return OrientationBuilder(
      builder: (BuildContext context, Orientation orientation) {
        Size size = const Size(375, 812);
        if (MediaQuery.of(context).orientation == Orientation.landscape) {
          size = const Size(812, 375);
        }
        setFullScreen(orientation == Orientation.landscape);
        return ScreenUtilInit(
          designSize: size,
          child: MaterialApp.router(
            //debugShowCheckedModeBanner: false,
            onGenerateTitle: (ctx) => switch (appFlavor) {
              flavorHst => S.of(ctx).appNameHst,
              _ => S.of(ctx).appName
            },
            builder: (ctx, child) {
              return botToastBuilder(ctx, child);
            },
            routerConfig: _appRouter.config(
                navigatorObservers: () => [BotToastNavigatorObserver()]),
            localizationsDelegates: const [
              S.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate
            ],
            supportedLocales: S.delegate.supportedLocales,
            theme: ThemeData(
              colorScheme:
                  ColorScheme.fromSeed(seedColor: Colors.deepPurple).copyWith(
                primary: const Color(0xFF0A50B4),
                surface: Colors.white,
                surfaceContainerHigh: const Color(0xFFEDEDED),
                onSurface: const Color(0xFF333333),
                onSurfaceVariant: const Color(0xFF505050),
              ),
              useMaterial3: true,
            ),
          ),
        );
      },
    );
  }
}
