import 'dart:convert';
import 'dart:async';
import 'dart:io';
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:mobpush_plugin/mobpush_custom_message.dart';
import 'package:mobpush_plugin/mobpush_notify_message.dart';
import 'package:mobpush_plugin/mobpush_plugin.dart';
import 'package:flutter/services.dart';
import 'package:zhiying_base_widget/dialog/global_dialog/policy_dialog/policy_dialog.dart';
import 'package:zhiying_base_widget/dialog/tip_dialog/tip_dialog.dart';
import 'package:mobpush_plugin/mobpush_custom_message.dart';
import 'package:mobpush_plugin/mobpush_notify_message.dart';
import 'package:mobpush_plugin/mobpush_plugin.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';
import 'package:fluttertoast/fluttertoast.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> with TickerProviderStateMixin {
  final GlobalKey navigatorKey = new GlobalKey();


  int showTime = 0;

  @override
  void initState() {

    validateInit();
    super.initState();
  }

  validateInit() async {
    // Connectivity().checkConnectivity().then((connectivityResult) async {
    //   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, s) async {
      print(s);
      // if (err.toString().contains("BaseSettingModel")) {
      //   await showDialog(
      //       context: context,
      //       child: TipDialog(
      //         content: "基本配置加载失败!请检查网络是否可用后再启动应用!",
      //       ));
      //   SystemNavigator.pop();
      // }
      if (showTime < 3) {
        showTime++;
        Fluttertoast.showToast(msg: "配置基础数据失败!请检查网络是否可用");
      }

      Timer(Duration(seconds: 5), () async {
        await SharedPreferencesUtil.setStringValue(GlobalConfig.GUIDE, "1");
        await SharedPreferencesUtil.setStringValue(GlobalConfig.MAIN_CONFIG, "1");
        validateInit();
      });
      Logger.error(err);
    });
    //   } else {
    //     ///在无网络情况下提示用户打开网络
    //     if(showTime<3){
    //       showTime++;
    //       Fluttertoast.showToast(msg: "无法连接网络!请打开移动网络/连接WIFI后再尝试");
    //     }
    //
    //     Timer(Duration(seconds: 5), () {
    //       validateInit();
    //     });
    //     Logger.error('未知网络，APP初始化失败');
    //     print('unknow');
    //   }
    // });
  }

  Future _showGuideImage() async {
    try {
      // 引导页
      AppConfigModel guide = AppConfigModel.getConfig();
      if (guide != null && guide.guideData.guideCss.length > 0) {
        Dio dio = Dio();
        print("加载图片");
        List<Uint8List> guideImages = List();
        List<Uint8List> bgImages = List();
        for (int i = 0; i < guide.guideData.guideCss.length; i++) {
          try {
            Response response = await dio.get(guide.guideData.guideCss[i].contentImage, options: Options(responseType: ResponseType.bytes));
            if (response.statusCode == 200) {
              Uint8List data = Uint8List.fromList(response.data);
              guideImages.add(data);
            }
          } catch (e, s) {
            guideImages.add(null);
          }

          try {
            Response response = await dio.get(guide.guideData.guideCss[i].bgImage, options: Options(responseType: ResponseType.bytes));
            if (response.statusCode == 200) {
              Uint8List data = Uint8List.fromList(response.data);
              bgImages.add(data);
            }
          } catch (e, s) {
            bgImages.add(null);
          }
        }
        NativeUtil.notifyInitSuccess();
        await Navigator.of(context).push(CupertinoPageRoute(builder: (context) => GuidePage(guide.guideData, guideImages, bgImages)));
      }
    } catch (e) {
      throw "引导图加载失败";
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
    );
  }
}
