import 'dart:async';
import 'dart:convert';

import 'package:EasyDartModule/EasyDartModule.dart';
import 'package:EasyDartModule/base/logger/Logger.dart';
import 'package:EasyDartModule/base/websocket/WebSocket.dart';
import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get_storage/get_storage.dart';
import 'package:localstorage/localstorage.dart';
import 'package:syncfusion_localizations/syncfusion_localizations.dart';
import 'package:vbvs_app/common/color/ServiceConstant.dart';
import 'package:vbvs_app/common/util/CheckNetwork.dart';
import 'package:vbvs_app/common/util/CommonVariables.dart';
import 'package:vbvs_app/common/util/FitTool.dart';
import 'package:vbvs_app/controller/device/blueteeth_bind_controller.dart';
import 'package:vbvs_app/controller/device/body_device_controller.dart';
import 'package:vbvs_app/controller/device/device_calibration_controller.dart';
import 'package:vbvs_app/controller/device/device_share_controller.dart';
import 'package:vbvs_app/controller/device/device_share_list_controller.dart';
import 'package:vbvs_app/controller/device/device_type_controller.dart';
import 'package:vbvs_app/controller/home/home_controller.dart';
import 'package:vbvs_app/controller/login/login_controller.dart';
import 'package:vbvs_app/controller/main_bottom/global_controller.dart';
import 'package:vbvs_app/controller/main_bottom/main_page_controller.dart';
import 'package:vbvs_app/controller/message/message_controller.dart';
import 'package:vbvs_app/controller/person/person_controller.dart';
import 'package:vbvs_app/controller/repair/repair_controller.dart';
import 'package:vbvs_app/controller/setting/language/language_controller.dart';
import 'package:vbvs_app/controller/setting/pdf/PdfController.dart';
import 'package:vbvs_app/controller/theme_controller/ThemeController.dart';
import 'package:vbvs_app/controller/time/countdown_controller.dart';
import 'package:vbvs_app/language/AppLanguage.dart';
import 'package:vbvs_app/model/CustomThemeColor.dart';
import 'package:vbvs_app/model/user_data.dart';

import 'controller/user_info_controller.dart';
import 'routers/routers.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final Locale? deviceLocale = Get.deviceLocale;
  print('系统语言: ${deviceLocale?.languageCode}');

  // await AppLanguage().loadLanguage("en_US");
  await AppLanguage().loadLanguage("zh_CN");
  await initLanguageSetting();
  WidgetsFlutterBinding.ensureInitialized();

  // ApiService.init();
  await GetStorage.init();
  // 初始化登录
  await initLocalStorage();
  initEasyDartModule();
  await initLogin();
  await initLog();
  await messageStatus();
  startMessagePolling();
  // 检查网络
  Checknetwork.checkNetwork();
  // 微信开放平台注册
  initWX();
  // // 初始化 flutter_xupdate android app 更新
  // initXUpdate();

  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
      .then((_) {
    runApp(MyApp());
  });
}

initLanguageSetting() {
  Get.put(LanguageController());
  LanguageController languageController = Get.find();
  languageController.initLanuageList();
}

// 初始化微信开放平台注册
Future<void> initWX() async {
  Fluwx fluwx = Fluwx();
  fluwx.registerApi(
    //请填写自己的微信appid
    appId: "wxeb2688220799e2c5",
    doOnAndroid: true,
    doOnIOS: true,
  );
}

Timer? _messageTimer;
void startMessagePolling() {
  // 避免重复启动
  _messageTimer?.cancel();

  _messageTimer = Timer.periodic(Duration(seconds: 5), (timer) async {
    try {
      MessageController messageController = Get.find();
      messageController.getMessageStatus();
      // print("轮询消息状态成功");
    } catch (e) {
      print("轮询消息状态失败: $e");
    }
  });
}

messageStatus() async {
  Get.put(MessageController());
  MessageController messageController = Get.find();
  await messageController.getMessageStatus();
}

void initEasyDartModule() {
  try {
    EasyDartModule.init(
        loggerConfig:
            LoggerConfig(host: ServiceConstant.logService, serviceName: "web"),
        webSocketConfig:
            WebSocketConfig(ServiceConstant.webSocketService, (data) {
          // 接收到服务消息
          var json = jsonDecode(data);
          if (json["path"] != null) {
            var call = CommonVariables.callMap[json["path"]];
            if (call != null) {
              try {
                call(json["data"]);
              } catch (e) {
                print(e);
              }
            } else {
              print("未找到当前路径: ${json["path"]} 回调函数");
            }
          }
          // print(data);
        }, onOpen: () {
          // 连接建立完毕
          // EasyDartModule.websocket
          //     .sendData(jsonEncode({"path": "/aa/bb", "type": 1}));
          print("object");
        }));
  } catch (e) {
    print(e);
  }
  //初始化
}

initLog() {}

Future<void> initLogin() async {
  // 初始化控制器
  Get.put(UserInfoController());
  // Get.put(SettingController());

  // 获取设备信息,需要用户点击确认隐私协议与用户协议选择框时才能获取
  // Deviceconfig.initPlatformState();
  // 获取app版本号
  // SettingController settingController = Get.find();
  // settingController.model.appVersion = await Deviceconfig.getAppVersion();

  final box = GetStorage();
  UserInfoController userInfoController = Get.find();
  String? token = box.read('token');
  try {
    Map<String, dynamic>? userMap = box.read('user');
    if (userMap != null) {
      UserModel user = UserModel.fromJson(userMap);
      userInfoController.model.user = user;
    }
  } catch (e) {
    print(e);
  }

  if (token != null) {
    userInfoController.model.login = 1;
    // 根据token去请求
    // await userInfoController.autoLogin(token);
    EasyDartModule.dio.token = token;
  } else {
    // 如果没有 token，则将用户标记为未登录
    userInfoController.model.login = 0;
  }
}

class MyApp extends StatelessWidget {
  MyApp({super.key});
  final ThemeController themeController = Get.put(ThemeController());

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    themeController.changeTheme(CustomThemeColor.dark);
    UserInfoController userInfoController = Get.find();
    return LayoutBuilder(builder: (contxt, cons) {
      double width = cons.maxWidth;
      double height = cons.maxHeight;
      if (width < 1) {
        return Container();
      }
      FitTool.init(width < height ? width : height);
      return GetMaterialApp(
          translations: AppLanguage(),
          // locale: const Locale("zh", "CN"),
          locale: AppLanguage().currentLocale, // ✅ 动态读取当前语言
          fallbackLocale: const Locale("zh", "CN"),
          localizationsDelegates: [
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
            SfGlobalLocalizations.delegate,
          ],
          supportedLocales: [
            const Locale('zh', 'CN'), // 中文
            const Locale('en', 'US'), // ⚠️ 添加你支持的语言
          ],
          debugShowCheckedModeBanner: false,
          title: '',
          theme: themeController.currentTheme,
          // home: const MyHomePage(title: '智慧眠花糖 Home Page'),
          initialRoute: "/mianPageBottomChange",
          onGenerateRoute: onGenerateRoute,
          initialBinding: BindingsBuilder(() => [
                // Get.lazyPut(() => UserInfoController()),
                Get.put(GlobalController()),
                Get.lazyPut(() => MainPageController()),
                Get.lazyPut(() => BlueteethBindController()),
                Get.lazyPut(() => PersonController()),
                Get.lazyPut(() => CountdownController()),
                Get.lazyPut(() => LoginController()),
                Get.lazyPut(() => DeviceTypeController()),
                Get.lazyPut(() => BodyDeviceController()),
                Get.lazyPut(() => HomeController()),
                Get.lazyPut(() => DeviceShareController()),
                Get.lazyPut(() => DeviceShareListController()),
                Get.lazyPut(() => DeviceCalibrationController()),
                Get.lazyPut(() => RepairController()),
                Get.lazyPut(() => PdfController()),
              ]));
    });
  }
}
