import 'dart:async';
import 'dart:io' show Platform;
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bmfbase/BaiduMap/bmfmap_base.dart' show BMFMapSDK, BMF_COORD_TYPE;
import 'package:flutter_screenutil/screenutil_init.dart';
import 'package:hyzp_ybqx/pages/Login/LoginTabs2.dart';
import 'package:hyzp_ybqx/pages/MyMsics/05_updated/MyUpdatedNew.dart';
import 'package:hyzp_ybqx/services/EventBus.dart';
import 'package:hyzp_ybqx/services/Storage.dart';
import 'package:package_info/package_info.dart';
// 引入provider
import 'package:provider/provider.dart';

import 'components/commonFun.dart';
import 'file_manager/file_manager_init.dart';
import 'provider/player_ratio.dart';
import 'provider/player_region.dart';
import 'routers/router.dart';

// 整个Flutter App的Android入口
void main() {
  //file_manager_load();
  //runApp(MyApp());

  //整个Flutter App的入口01
  WidgetsFlutterBinding.ensureInitialized(); //必须要添加这个进行初始化 否则下面会错误
  //Flutter 强制竖屏
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]).then((_) {
    //整个Flutter App的入口02
    checkPermission(); //请求用户授权
  });
}

//整个Flutter App的入口07。入口处理结束，正式开始Flutter App
class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    initApp(); // 1、处理百度地图sdk初始化鉴权
    // startGetStatisDataNew(); // 2、登录前提前获取统计数据，改善用户登录体验
    // 3、处理版本更新
    PackageInfo.fromPlatform().then((PackageInfo packageInfo) async {
      String appName = packageInfo.appName;
      String packageName = packageInfo.packageName;
      String version = packageInfo.version;
      String buildNumber = packageInfo.buildNumber;
      String buildDate =
          '${buildNumber.substring(0, 4)}.${buildNumber.substring(4, 6)}.${buildNumber.substring(6, 8)}';

      print('appName = $appName');
      print('packageName = $packageName');
      print('version = $version');
      print('buildNumber = $buildNumber');
      print('buildDate = $buildDate');

      await MyUpdatedNew(
          ver: version,
          date: buildDate,
          theContext: context,
          bStartUpdated: true);
    });
    super.initState();
  }

  void initApp() async {
    getDeviceId().then((value) {
      g_userInfo.thisDeviceId = value;

      // 百度地图sdk初始化鉴权
      if (Platform.isIOS) {
        BMFMapSDK.setApiKeyAndCoordType('I022V5cRWKDn8gguTTa1gbxqPMYWU4G0', BMF_COORD_TYPE.BD09LL);
      } else if (Platform.isAndroid) {
        // Android 目前不支持接口设置Apikey,
        // 请在主工程的Manifest文件里设置，详细配置方法请参考官网(https://lbsyun.baidu.com/)demo
        BMFMapSDK.setCoordType(BMF_COORD_TYPE.BD09LL);
      }
    });

    // 从磁盘读取变量
    g_bVoiceRemind = await Storage.getBool('bVoiceRemind');
    // g_bVoiceRemind = (null == g_bVoiceRemind) ? false : g_bVoiceRemind; // 默认关闭
    g_bVoiceRemind = (null == g_bVoiceRemind) ? true : g_bVoiceRemind; // 默认开启
    // print('g_bVoiceRemind = $g_bVoiceRemind');
    eventBus.fire(VoiceRemindUpdate('g_bVoiceRemind 数据已更新'));
  }

  @override
  Widget build(BuildContext context) {
    //ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    //750:1334
    //默认 width : 1080px , height:1920px , allowFontScaling:false
    //double width = MediaQuery.of(context).size.width;

    //sizeMediaQuery = MediaQuery.of(context).size; //这样不对
    print('sizeMediaQuery = $sizeWindowPhysicalSize');
    //size: Size(360.0, 674.7)

    //自动适应安卓手机系统分辨率，解决 S10 手机正方形变形问题
    print('window.physicalSize = ${window.physicalSize}');
    //window.physicalSize = Size(1080.0, 2136.0)
    sizeWindowPhysicalSize = window.physicalSize;
    //double _heigth = 1080 * 16 / 9;
    double _heigth = 1080 * sizeWindowPhysicalSize.height / sizeWindowPhysicalSize.width;
    print('_heigth = $_heigth');

    return ScreenUtilInit(
      designSize: Size(1080, _heigth), //安卓手机宽高尺寸，_heigth = 1080 * 16 / 9;
      //designSize: Size(1080, 1920),   //安卓手机宽高尺寸，_heigth = 1080 * 16 / 9;
      //designSize: Size(750, 1334),  //统一使用美工设计的宽高尺寸，苹果比例
      //designSize: sizeWindowPhysicalSize, //自动适应安卓手机系统分辨率，解决 S10 手机正方形变形问题
      allowFontScaling: false,
      builder: () => MultiProvider(
        providers: [
          // ChangeNotifierProvider(builder: (_) => Counter()),
          // ChangeNotifierProvider(builder: (_) => Cart()),
          // ChangeNotifierProvider(builder: (_) => CheckOut()),
//        ChangeNotifierProvider(builder: (_) => PlayerRegionProvide()),
//        ChangeNotifierProvider(builder: (_) => PlayerRatioProvide()),
          ChangeNotifierProvider<PlayerRegionProvide>(create: (context) => PlayerRegionProvide()),
          ChangeNotifierProvider<PlayerRatioProvide>(create: (context) => PlayerRatioProvide()),
        ],
        child: MaterialApp(
          home: LoginTabs2(),
          debugShowCheckedModeBanner: false,
          initialRoute: '/',
          onGenerateRoute: onGenerateRoute,
          theme: ThemeData(
              // primaryColor: Colors.yellow
              primaryColor: Colors.white),
        ),
      ),
    );
  }
}

//整个Flutter App的入口06
class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => new _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  startTime() async {
    //设置启动图生效时间
    var _duration = new Duration(seconds: 2);
    return new Timer(_duration, navigationPage);
  }

  //整个Flutter App的入口07
  void navigationPage() {
    Navigator.of(context).pushReplacementNamed('/home');
  }

  @override
  void initState() {
    super.initState();
    startTime();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          SizedBox(height: MediaQuery.of(context).padding.top), // 不覆盖顶部状态栏
          Container(
              width: MediaQuery.of(context).size.width,
              // 屏幕宽度
              height: MediaQuery.of(context).size.height - MediaQuery.of(context).padding.top,
              // 屏幕高度
              // child: Image.asset('assets/images/hyzp_ybqx00_yibin_launche.png', fit: BoxFit.cover),
              // child: Image.asset('assets/images/hyzp_ybqx01_cuiping_launche.png', fit: BoxFit.cover),
              child: Image.asset('assets/images/hyzp_ybqx_launche.png', fit: BoxFit.cover)),
        ],
      ),
    );
  }
}
