import 'dart:async';

import 'package:fis_jsonrpc/notifications/index.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/utils/sizer/sizer.dart';
import 'package:flyinsono/android_services/android_back.dart';
import 'package:flyinsono/architecture/error/global_error_handler.dart';
import 'package:flyinsono/architecture/utils/web_parameter_helpler.dart';
import 'package:flyinsono/lab/env/env.dart';
import 'package:flyinsono/pages/upgrade/upgrade_widgets/upgrade_center.dart';
import 'package:fis_common/index.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/global.dart';
import 'package:flyinsono/rpc.dart';
import 'package:flyinsono/views/wechat_mini_program/wx_env/wechat_env_native.dart';
import 'app.dart';
import 'architecture/router/desktop/routes.dart';
import 'architecture/services/notification/local_notification_service.dart';
import 'architecture/states/states.dart';
import 'architecture/theme.dart';

void main() async {
  runZonedGuarded(
    () async {
      try {
        WidgetsFlutterBinding.ensureInitialized();
        await Global.init();
        await LocalNotificationService.init();
      } catch (e) {
        logger.e('Global init Error', e);
      }
      final app = FPlatform.isPureWeb
          ? WebAppContainer((isFirstBuild) {
              if (!isFirstBuild && FPlatform.isPureWeb) {
                // 针对web端 PC ↔ Mobile 切换时刷新应用
                //html.window.location.reload();
              }
              return _App();
            })
          : _App();
      runApp(app);
    },
    (error, stack) {
      GlobalErrorHandler.handle(error, stack);
    },
  );
}

class _App extends StatelessWidget {
  _App({Key? key}) : super(key: key);

  static const _secondWindowPageNames = [
    'measure',
    'report',
    'reportPreview',
    'liveConsultation',
    'DeviceLive',
    'liveCourse',
    'remoteController',
    'secondSplashFirst',
  ];

  @override
  FWidget build(BuildContext context) {
    final theme = AppTheme.ins;
    String initRoute = RouteNames.App.Splash;
    // String initRoute = RouteNames.Home.Home;
    final page = ParameterHelper.parasmeters['page'];
    if (_secondWindowPageNames.contains(page)) {
      //TODO(Loki):名称应该常量化
      if (FPlatform.isPureWeb) {
        if (page == 'measure') {
          initRoute = RouteNames.Remedical.Measure;
        } else if (page == 'report') {
          initRoute = RouteNames.Remedical.ReportEdit;
        } else if (page == 'liveConsultation') {
          initRoute = RouteNames.RealTimeRemedical.LiveConsultation;
          Store.user.initNotificationConfig(type: WSType.Consultation);
        } else if (page == 'DeviceLive') {
          initRoute = RouteNames.Live.DeviceDetail;
        } else if (page == 'liveCourse') {
          initRoute = RouteNames.College.LiveCourseDetail;
        } else if (page == 'remoteController') {
          initRoute = RouteNames.Live.RemoteController;
        } else {
          initRoute = RouteNames.Remedical.ReportPreview;
        }
      } else {
        initRoute = RouteNames.App.SecondSplash;
        if (page == "secondSplashFirst") {
          rpc.platform.onSlaveWindowStart();
        }
      }
    }
    if (kIsWechat) {
      initRoute = MobileRouteNames.Wechat.MiniProgramHome;
    }
    if (kIsLab) {
      //initRoute = RouteNames.Lab.Main;
    }
    if (Global.isVStationSlave) {
      initRoute = RouteNames.Lab.Main;
      Store.user.handleSetAuth();
    }

    bool ifFirstTime = true; // 是否为首次进入
    UpgradeCenter.init();
    return FlyinsonoApp(
      locale: i18nBook.locale,
      fallbackLocale: ENGLISH_LOCALE,
      theme: theme.innerThemeData,
      // 锁定明亮模式
      darkTheme: theme.innerThemeData,
      themeMode: ThemeMode.light,
      // darkTheme: theme.getInnerThemeData(Brightness.dark),
      // themeMode: theme.themeMode,
      customTransition: kIsMobile ? null : FTransitions.fadeThrough,
      transitionDuration: kIsMobile ? null : Duration(milliseconds: 300),
      pages: router.routes,
      routingCallback: (routing) {
        if (ifFirstTime) {
          ifFirstTime = false;
          return;
        }
        // TODO:[Gavin] 此方式有待优化
        // 如果再次尝试访问splash就back to desktop
        if (routing!.current == '/splash') {
          AndroidBackTop.backDeskTop(); //设置为返回不退出app
          // 1s后
          Future.delayed(Duration(seconds: 1), () {
            router.to(RouteNames.Home.Home);
          });
        }
      },
      initialRoute: initRoute,
      unknownRoute: FErrorRouteSettings.NotFount,
      builder: EasyLoading.init(
        builder: (context, widget) {
          final size = Sizer.ins.size;
          _initScreenScale(context, size);

          Sizer.ins.addListener(
            (size) {
              _initScreenScale(context, size);
            },
          );

          return DefaultAssetBundle(
            bundle: Global.assetBundle,
            child: MediaQuery(
              ///设置文字大小不随系统设置改变
              data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
              child: widget ?? FContainer(),
            ),
          );
        },
      ),
    );
  }

  void _initScreenScale(BuildContext context, Size size) {
    final isMobile = Sizer.ins.isMobile;
    if (isMobile) {
      Global.SCALE_RATIO = size.width / 375;
      Global.SCALE_RATIO_BACK = 375 / size.width;
    }
    final designSize =
        isMobile ? Size(375, Global.SCALE_RATIO_BACK * size.height) : size;
    ScreenUtil.init(
      BoxConstraints(
        maxWidth: MediaQuery.of(context).size.width,
        maxHeight: MediaQuery.of(context).size.height,
      ),
      designSize: designSize,
      orientation: Orientation.portrait,
    );
  }
}
