import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:get_storage/get_storage.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:ln_jq_app/common/AuthGuard.dart';
import 'package:ln_jq_app/common/model/base_model.dart';
import 'package:ln_jq_app/common/token_interceptor.dart';
import 'package:ln_jq_app/storage_service.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'common/styles/theme.dart';
import 'pages/login/view.dart';
import 'pages/welcome/view.dart'; // 引入启动页

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

  WidgetsBinding widgetsBinding = await init(
    isDebug: true,
    logTag: '小羚羚',
    supportedLocales: [const Locale('zh', 'CN')],
  );

  // 保持原生闪屏页，直到 WelcomeController 调用 remove()
  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);

  await GetStorage.init();
  await Get.putAsync(() => StorageService().init());

  initHttpSet();

  runApp(
    GetxApp(
      // 设计稿尺寸 单位：dp
      designSize: const Size(390, 844),
      // Getx Log
      enableLog: true,
      // 默认的跳转动画
      defaultTransition: Transition.rightToLeft,
      // 主题模式
      themeMode: GlobalService.to.themeMode,
      // 主题
      theme: AppTheme.light,
      // Dark主题
      darkTheme: AppTheme.light,
      // AppTitle
      title: '小羚羚',
      // 将入口改为启动页
      home: const WelcomePage(),
      fallbackLocale: const Locale('zh', 'CN'),
      supportedLocales: const [Locale('zh', 'CN')],
      localizationsDelegates: const [
        RefreshLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      builder: (context, widget) {
        return widget!;
      },
    ),
  );
}

void initHttpSet() {
  AppTheme.test_service_url = StorageService.to.hostUrl ?? AppTheme.test_service_url;

  HttpService.to.init(timeout: 15);
  HttpService.to.setBaseUrl(AppTheme.test_service_url);
  HttpService.to.dio.interceptors.add(TokenInterceptor(tokenKey: 'asoco-token'));
  HttpService.to.setOnResponseHandler((response) async {
    try {
      if (response.data == null) {
        return null;
      }
      final baseModel = BaseModel.fromJson(response.data);
      if (baseModel.code == 0 || baseModel.code == 200) {
        return null;
      } else if (baseModel.code == 401) {
        await AuthGuard.handle401(baseModel.message);
        return baseModel.message;
      } else {
        return (baseModel.error.toString()).isEmpty
            ? "服务繁忙，稍后重试"
            : baseModel.error.toString();
      }
    } on Exception catch (e) {
      e.printInfo();
      return '服务器异常';
    }
  });
}
