/// 入口文件main.dart
library;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:loopin/IM/controller/chat_controller.dart';
import 'package:loopin/IM/controller/im_user_info_controller.dart';
import 'package:loopin/IM/controller/tab_bar_controller.dart';
import 'package:loopin/IM/im_core.dart' as im_core;
import 'package:loopin/IM/im_service.dart';
import 'package:loopin/service/http_config.dart';
import 'package:loopin/utils/common.dart';
import 'package:loopin/utils/deep_link_listener.dart';
import 'package:loopin/utils/lifecycle_handler.dart';
import 'package:loopin/utils/network_utils.dart';
import 'package:loopin/utils/storage.dart';
import 'package:media_kit/media_kit.dart';
import 'package:shirne_dialog/shirne_dialog.dart';

// 引入布局页面
import 'layouts/index.dart';
// 引入路由配置
import 'router/index.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // 初始化网络监听
  NetworkUtils().initialize();
  // 注入tabbar
  Get.put(TabBarController(), permanent: true);
  // 注入会话列表
  Get.put(ChatController(), permanent: true);
  // 注入底导菜单易选的
  // Get.put(ShopIndexController(), permanent: true);
  // 用户基本信息模型
  Get.put(ImUserInfoController(), permanent: true);

  // 监听app前后台状态
  WidgetsBinding.instance.addObserver(LifecycleHandler());
  // 禁止横屏
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
  // 显示状态栏
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);

  // 初始化http请求
  HttpConfig.init();
  // 初始化get_storage存储
  await GetStorage.init();

  // 初始化media_kit视频套件
  WidgetsFlutterBinding.ensureInitialized();
  MediaKit.ensureInitialized();

  // 检测登录状态
  if (Common.isLogin()) {
    // 初始化Im，并进行Im登录
    final res = await im_core.ImCore.init(sdkAppId: 1600080789);

    // 缺少userSig先用固定值ios用9365，安卓用0385
    try {
      if (res) {
        await ImService.instance.login(userID: Storage.read('userId'), userSig: Storage.read('userSig'));
      } else {
        logger.w('初始化未完成');
      }
    } catch (e) {
      logger.w(e.toString());
      Common.logout();
    }
    // String userId = '1940667704585248769'; //13212279365
    // String userId = '1943510443312078850'; //18832510385
    // String userSig =
    // 'eJwtjcEKgkAURf9l1iFPm*e8EdoYYUWFURAtg5nk5VRiEln0703q8p57Ofcj9qtd8LS1SEQUgBh1mY29NXzmDodaQhwrBRIJI0kq1sPsYcpTVbERSRgDAIEi3Tf2VXFtPUfEyFc9bfj6ZwrH4J1Ig4UL-6LX0ihyS7U5bi-Wzd8LzrK8TFs6TJ1sZwWGxlGas71PxPcHwH4y9Q__';
    // 'eJwtzLEKwjAUheF3ySwlNzXNbcHFxSIOaqTWUUgsF1FDG2tEfHdj2-F8P5wPO2x00tuWFUwknM2GTcbePV1oYEBMhQSeopxyZ65n58iwAjLOOXKF*VhscNTa6FJKEdOonm5-UxJQpZhN2lET3599Xllbv9ZBH2uHuDfvst5tG6FX0EFYVhpOpZ973z8W7PsDmYwyIw__';
    // await ImService.instance.login(userID: userId, userSig: userSig);
  }

  runApp(App());
}

class App extends StatelessWidget {
  App({super.key});

  final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();

  @override
  Widget build(BuildContext context) {
    return DeepLinkListener(
      child: GetMaterialApp(
        title: '无终街',
        locale: const Locale('zh'),
        supportedLocales: const [
          Locale('zh'),
        ],
        localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
        ],
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          // colorScheme: ColorScheme.fromSeed(seedColor: FStyle.primaryColor),
          useMaterial3: true,
        ),
        home: const Layout(),
        initialRoute: '/',
        getPages: routePages,
        navigatorKey: MyDialog.navigatorKey,

        // 注入 RouteObserver
        navigatorObservers: [routeObserver],

        // 注入到 GetX
        builder: (context, child) {
          Get.put<RouteObserver<PageRoute>>(routeObserver);
          return child!;
        },
      ),
    );
  }
}
