
import 'package:atmob_channel_reader/atmob_channel_reader.dart';
import 'package:electronic_assistant/data/consts/build_config.dart';
import 'package:electronic_assistant/resource/colors.gen.dart';
import 'package:electronic_assistant/resource/string.gen.dart';
import 'package:electronic_assistant/resource/string_source.dart';
import 'package:electronic_assistant/router/app_pages.dart';
import 'package:electronic_assistant/sdk/gravity/gravity_helper.dart';
import 'package:electronic_assistant/sdk/umeng/umeng_helper.dart';
import 'package:electronic_assistant/utils/app_info_util.dart';
import 'package:electronic_assistant/device/device_info_util.dart';
import 'package:electronic_assistant/utils/desktop_shortcut_utils.dart';
import 'package:electronic_assistant/utils/mmkv_util.dart';
import 'package:electronic_assistant/utils/toast_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:get/get_navigation/src/root/get_material_app.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'data/consts/Constants.dart';
import 'device/atmob_platform_info.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  FlutterForegroundTask.initCommunicationPort();

  //注册快捷方式
  await DesktopShortcutUtils.registerDesktopShortcut();

  //全局配置smartDialog
  smartConfig();
  //mmkv
  await KVUtil.init();

  //渠道信息
  initChannel();

  //初始化
  await initAfterGrant();

  //檢查地址
  checkEnv();
  runApp(const MyApp());
}

void checkEnv() {
  if (!Constants.isProdEnv() && !BuildConfig.isDebug) {
    ToastUtil.showToast('不是正式环境！！！', addPostFrame: true);
  }
}

initChannel() async {
  await AtmobChannelReader.default4Test(Constants.appDefaultChannel,
      Constants.appDefaultAppId, Constants.appDefaultTgPlatformId);

  String? channel = KVUtil.getString(
      Constants.appChanelName, await AtmobChannelReader.getChannel());
  KVUtil.putString(Constants.appChanelName, channel);

  int? channelId = KVUtil.getInt(Constants.appChannelId, -1);
  if (channelId == -1) {
    channelId = await AtmobChannelReader.getAppId();
  }
  if (channelId != null) {
    KVUtil.putInt(Constants.appChannelId, channelId);
  }

  int? appTgPlatformId = KVUtil.getInt(Constants.appTgPlatformId, -1);
  if (appTgPlatformId == -1) {
    appTgPlatformId = await AtmobChannelReader.getTgPlatformId();
  }
  if (appTgPlatformId != null) {
    KVUtil.putInt(Constants.appTgPlatformId, appTgPlatformId);
  }
  atmobPlatformInfo.setChannelName(channel);
  atmobPlatformInfo.setAppId(channelId);
  atmobPlatformInfo.setTgPlatform(appTgPlatformId);
}

Future<void> initAfterGrant() async {
  if (!isAgreePrivacyPolicy()) {
    return;
  }
  //获取包信息
  await appInfoUtil.init();
  //获取设备信息
  await deviceInfoUtil.init();
  //引力引擎
  GravityHelper.init();
  //友盟
  UmengHelper.initCommon();
}

void smartConfig() {
  SmartDialog.config.custom =
      SmartConfigCustom(animationType: SmartAnimationType.fade);
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: const Size(360, 800),
      builder: (_, child) {
        return _buildMaterialApp();
      },
    );
  }

  _buildMaterialApp() {
    return RefreshConfiguration(
      headerBuilder: () =>
          const MaterialClassicHeader(color: ColorName.colorPrimary),
      footerBuilder: () => ClassicFooter(
        canLoadingText: StringName.loadingMore.tr,
        idleText: StringName.loadPullUp.tr,
        loadingText: StringName.loadingTxt.tr,
        noDataText: StringName.loadNoData.tr,
        failedText: StringName.loadFailed.tr,
      ),
      child: GetMaterialApp(
        onGenerateTitle: (_) => StringName.appName.tr,
        getPages: AppPage.pages,
        initialRoute: RoutePath.splash,
        initialBinding: AppBinding(),
        theme: ThemeData(
          useMaterial3: true,
          textSelectionTheme: const TextSelectionThemeData(
            cursorColor: ColorName.colorPrimary, // 设置默认光标颜色
            selectionHandleColor: ColorName.colorPrimary, // 设置光标下面水滴的颜色
          ),
        ),
        navigatorObservers: [FlutterSmartDialog.observer],
        builder: FlutterSmartDialog.init(),
        translations: StringResource(),
        localizationsDelegates: const [
          GlobalMaterialLocalizations.delegate,
          //是Flutter的一个本地化委托，用于提供Material组件库的本地化支持
          GlobalWidgetsLocalizations.delegate,
          //用于提供通用部件（Widgets）的本地化支持
          GlobalCupertinoLocalizations.delegate,
          //用于提供Cupertino风格的组件的本地化支持
        ],
        supportedLocales: const [
          Locale('zh', 'CN'), // 支持的语言和地区
        ],
        // 你的翻译
        locale: const Locale('zh', 'CN'),
        // 将会按照此处指定的语言翻译 添加一个回调语言选项，以备上面指定的语言翻译不存在
        fallbackLocale: const Locale('zh', 'CN'),
      ),
    );
  }
}
