import 'dart:typed_data';

import 'package:connectivity/connectivity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:zhiying_base_widget/models/app_config_model.dart';
import 'package:zhiying_base_widget/pages/guide_page/guide_page.dart';
import 'package:zhiying_base_widget/pages/home_page/home_page.dart';
import 'package:zhiying_comm/util/application.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:dio/dio.dart';
import 'package:zhiying_base_widget/utils/contants.dart';
import 'package:zhiying_comm/util/shared_prefe_util.dart';
import 'package:package_info/package_info.dart';

// 启动页，页面初始化等操作~跟原生启动页保持一致，防止白屏问题
class LaunchPage extends StatefulWidget {
  final WidgetBuilder builder;

  const LaunchPage({Key key, this.builder}) : super(key: key);

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

class _LaunchPageState extends State<LaunchPage> {
  @override
  void initState() {
    Connectivity().checkConnectivity().then((connectivityResult) {
      if (connectivityResult == ConnectivityResult.mobile ||
          connectivityResult == ConnectivityResult.wifi) {
        // I am connected to a wifi network.
        Logger.debug('ConnectivityResult.wifi');
        print('ConnectivityResult.wifi');
        Application.init().then((_) async {
          PackageInfo packageInfo = await PackageInfo.fromPlatform();
          String versionNumber =
          await SharedPreferencesUtil.getStringValue(Constants.versionNumber);
          String currentVersionCode =
          packageInfo.buildNumber?.toString() ?? '';
          if (versionNumber == null || versionNumber == '' || versionNumber != currentVersionCode) {
            await _showGuideImage();
            SharedPreferencesUtil.setStringValue(Constants.versionNumber, currentVersionCode);
          }


          if (widget.builder != null) {
            Navigator.of(context).pushReplacement(CupertinoPageRoute(builder: widget.builder));
          } else {
            // Navigator.of(context).pushReplacement(
            //     CupertinoPageRoute(builder: (context) => HomePage()));
            Navigator.of(context).pushReplacementNamed('/homePage');
          }
        }).catchError((err) {
          Logger.error(err);
        });
      } else {
        Logger.error('未知网络，APP初始化失败');
        print('unknow');
      }
    });

    super.initState();
  }

  Future _showGuideImage() async {
    // 引导页
    AppConfigGuideModel guide = AppConfigModel.getConfig()?.guideImage;
    if (guide != null && guide.images.length > 0) {
      Dio dio = Dio();

      List<Uint8List> guideImages = List();
      for (int i = 0; i < guide.images.length; i++) {
        Response response = await dio.get(guide.images[i], options: Options(responseType: ResponseType.bytes));
        if (response.statusCode == 200) {
          Uint8List data = Uint8List.fromList(response.data);
          guideImages.add(data);
        }
      }

      await Navigator.of(context).push(
          CupertinoPageRoute(builder: (context) => GuidePage(guide, guideImages)));
    }

  }

  @override
  Widget build(BuildContext context) {
    return Image.asset(
      'assets/images/launch_image/launch_image.png',
      package: 'zhiying_base_widget',
      fit: BoxFit.cover,
    );
  }
}
