// ignore_for_file: library_private_types_in_public_api, depend_on_referenced_packages

import 'dart:async';
import 'dart:io';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sizer/sizer.dart';
import 'package:special_equipment_flutter/common/color_const.dart';
import 'package:special_equipment_flutter/common/route_string.dart';
import 'package:special_equipment_flutter/dio/api.dart';
import 'package:special_equipment_flutter/utils/baidu_location_util.dart';
import 'package:special_equipment_flutter/utils/sp_util.dart';
import 'package:special_equipment_flutter/utils/storage_util.dart';

import 'ui/main/start_app.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  //预览：平滑滚动以提供不匹配的输入和显示频率
  //当输入和显示频率不同时，Flutter团队与Google内部合作伙伴合作，极大地提高了滚动性能。例如，Pixel 4输入的运行频率为120hz，而显示屏的运行频率为90hz。滚动时，这种不匹配会导致性能下降。使用新的resamplingEnabled标志，您可以利用我们在Flutter中完成的性能工作来解决此问题：
  GestureBinding.instance.resamplingEnabled = true;
  //状态栏透明
  if (Platform.isAndroid) {
    SystemUiOverlayStyle style = const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.dark, // 状态栏字体颜色（黑色）
    );
    SystemChrome.setSystemUIOverlayStyle(style);
  }
  StorageUtil.getInstance().init();
  runApp(const MyApp());
}

///当进行网络请求时，如果数据还没获取到而给Widget赋值，会出现短暂的红屏
void setFlutterErrorDetails() {
  ErrorWidget.builder = (FlutterErrorDetails flutterErrorDetails) {
    return Container(
      color: Colors.white,
      child: const CupertinoActivityIndicator(),
    );
  };
}

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

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    // loadVersion();
    super.initState();

    /// 设置EasyRefresh的默认样式
    EasyRefresh.defaultHeader = MaterialHeader(backgroundColor: Colors.white);
    EasyRefresh.defaultFooter = BallPulseFooter(color: ColorConst.themeBgColor);

    ///初始化百度定位
    BaiduLocationUtil baiduLocationUtil = BaiduLocationUtil();
    baiduLocationUtil.initBaiduLocation();
  }

  @override
  Widget build(BuildContext context) {
    //预先加载SPUtil
    return FutureBuilder<SPUtil?>(
      future: SPUtil.perInit(),
      builder: (BuildContext context, AsyncSnapshot<SPUtil?> snapshot) {
        //加载完成进入首页 否则就转圈
        Widget widget = snapshot.connectionState == ConnectionState.done
            ? const StartAppState() //自己定义的页面
//            ?  WebPage() //自己定义的页面
            : const Scaffold(
                body: Center(
                  child: CircularProgressIndicator(),
                ),
              );
        // final easyLoading = EasyLoading.init();
        final botToastBuilder = BotToastInit();
        return Sizer(builder: (context, orientation, deviceType) {
          return buildGetMaterialApp(widget, botToastBuilder, context);
        });
      },
    );
  }

  // buildGetMaterialApp(widget, botToastBuilder, context)

  GetMaterialApp buildGetMaterialApp(
      Widget widget, TransitionBuilder botToastBuilder, BuildContext context) {
    return GetMaterialApp(
      home: Api.IS_DEBUG ? const SplashScreen() : widget,

      ///去掉右上角的debug贴纸
      debugShowCheckedModeBanner: !Api.IS_DEBUG,
      initialRoute: "/",

      /// 配置全局路由页面切换动画效果
      defaultTransition: Transition.rightToLeft,

      /// 配置路由表
      getPages: RouteString.routes,

      builder: (context, child) {
        child = gestureDetector(context, child!);
        // child = easyLoading(context, child);
        child = botToastBuilder(context, child);
        return child;
      },
      navigatorObservers: [BotToastNavigatorObserver()],
      theme: ThemeData(
        primarySwatch: ColorConst.themeBgColor,
        visualDensity: VisualDensity.adaptivePlatformDensity,
        appBarTheme: Theme.of(context).appBarTheme.copyWith(centerTitle: true),
      ),
//          theme: ThemeData(
//            colorScheme: const ColorScheme.light(
//              primary: Colors.black54, //主题颜色
//              onPrimary: Colors.black26, //主题字体颜色
//            ),
//          ),
    );
  }

  ///全局点击空白处关闭软键盘
  Widget gestureDetector(BuildContext context, Widget child) {
    return GestureDetector(
      onTap: () {
        hideKeyboard(context);
      },
      child: child,
    );
  }

  ///关闭软键盘
  void hideKeyboard(BuildContext context) {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  // 动态申请定位权限
  void requestPermission() async {
    // 申请权限
    bool hasLocationPermission = await requestLocationPermission();
    if (hasLocationPermission) {
      // 权限申请通过
    } else {}
  }

  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }
}

class SplashScreen extends StatefulWidget {
  const SplashScreen({super.key});

  @override
  _SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    super.initState();
    Timer(
      const Duration(seconds: 2), // 可以在此设置启动页显示的时间
      () => Navigator.pushReplacement(
        context,
        MaterialPageRoute(
            builder: (context) => const StartAppState()), // 设置启动页后要显示的页面
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Image.asset(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        'assets/spalsh.jpeg',
        fit: BoxFit.fill,
      ),
    );
  }
}
