import 'dart:async';

import 'package:flutter/material.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart';
import 'package:vitalapp/architecture/network_connectivity.dart';
import 'package:vitalapp/store/store.dart';

import 'global.dart';
import 'routes/routes.dart';

void main() async {
  runZonedGuarded(
    () async {
      try {
        WidgetsFlutterBinding.ensureInitialized();
        await Global.init();
      } catch (e) {
        logger.e('Global init Error', e);
      }
      runApp(const _App());
    },
    (error, stack) {
      logger.e('runZonedGuarded Error', error);
      // GlobalErrorHandler.handle(error, stack);
    },
  );
}

class _App extends StatefulWidget {
  const _App();

  @override
  State<StatefulWidget> createState() => _AppState();
}

class _AppState extends State<_App> with WidgetsBindingObserver {
  Timer? _netCheckTimer;

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: "杏聆荟健康平台",
      // locale: const Locale('zh'),
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('en', 'US'), // English
        Locale('zh', 'CN'), // Chinese Simplified
        // other locales your app supports
      ],
      theme: ThemeData(
        // primaryColor: const Color.fromRGBO(0, 178, 237, 1),
        // TODO:
        primaryColor: Colors.blue,
        colorScheme:
            ColorScheme.fromSeed(seedColor: Color(Colors.blue.value - 40)),
        // colorScheme: ColorScheme.fromSeed(
        //   // seedColor: const Color.fromRGBO(44, 119, 229, 1),
        //   // seedColor: Colors.lightBlue,
        //   seedColor: const Color.fromRGBO(0, 178, 237, 1),
        // ),
        // colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
        fontFamily: "NotoSansSC-R-fixed",
        fontFamilyFallback: const ["NotoSansSC-R-fixed"],
      ),
      debugShowCheckedModeBanner: false,
      getPages: Routes.routes,
      initialRoute: "splash",
      // initialRoute: "/patient/create",
      // initialRoute: "/contract/signature",
      // initialRoute: "/",
      builder: EasyLoading.init(
        builder: (context, widget) {
          const designWidth = 1280.0; // 设计尺寸宽度：1280
          final size = MediaQuery.of(context).size;
          final scale = size.width / designWidth; // 计算缩放比例
          return FittedBox(
            fit: BoxFit.fitWidth,
            child: SizedBox(
              width: designWidth,
              height: size.height / scale,
              child: Center(child: widget ?? const SizedBox()),
            ),
          );
        },
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    switch (state) {
      case AppLifecycleState.resumed:
        _netCheckTimer?.cancel();
        _netCheckTimer = null;
        // 延迟300ms，等待其他APP状态恢复
        _netCheckTimer = Timer(const Duration(milliseconds: 300), () async {
          // 唤起后主动检查网络连接，防止状态不同步
          await netChecker.check();
        });
        break;
      case AppLifecycleState.inactive:
        break;
      case AppLifecycleState.paused:
        break;
      case AppLifecycleState.detached:
        break;
    }
  }
}
