import 'package:disable_screenshots/disable_screenshots.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; //import 'package:flustars/flustars.dart' as flustars; //该组件中有ScreenUtil，// 获取网络图片尺寸flustars.WidgetUtil
import 'package:hyzp_ybqx/pages/Works/TJXX/tj_data.dart';
import 'package:hyzp_ybqx/services/EventBus.dart';
import 'package:hyzp_ybqx/widget/my_Tabs.dart' as my_Tabs;

import '../../components/commonFun.dart';
import '../../services/Storage.dart';
import 'FaceLogin2.dart';
import 'LoginByName3.dart';

// class LoginTabsWidget extends StatelessWidget {
//   // This widget is the root of your application.
//   @override
//   Widget build(BuildContext context) {
//     //Flutter 强制竖屏
//     SystemChrome.setPreferredOrientations([
//       DeviceOrientation.portraitUp, //只能纵向
//       DeviceOrientation.portraitDown, //只能纵向
//     ]);
//
//     return MaterialApp(
//       debugShowCheckedModeBanner: false,
//       title: 'Flutter Demo',
//       theme: ThemeData(
//         primarySwatch: Colors.blue,
//         visualDensity: VisualDensity.adaptivePlatformDensity,
//       ),
//       home: MyHomePage(title: 'Flutter Demo Home Page'),
//     );
//   }
// }

class LoginTabsWidget extends StatefulWidget {
  LoginTabsWidget({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<LoginTabsWidget> with SingleTickerProviderStateMixin {
  // 初始化插件
  DisableScreenshots _watermarkPlugin = DisableScreenshots();

  int loginTabs_index = 0;

  //用TabController实现顶部tab切换
  TabController _tabController;

  //try_setState();   //避免如下异常报错
  try_setState() {
    try {
      setState(() {});
    } catch (e) {
      print('setState(() {})异常：${e}');
    }
  }

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

    //若下面文件不存在，
    // /data/data/com.flutter.hyzp_ybqx/shared_prefs/FlutterSharedPreferences.xml
    // value为null， 会抛出异常：
    // [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: Invalid argument(s): The source must not be null
    // int.parse (dart:core-patch/integers_patch.dart:51:25)
    Storage.getString("tabs_index").then((value) {
      g_iIndex = (null == value) ? 0 : int.parse(value);
    });

    Storage.getString("LoginTabs_index").then((value) {
      loginTabs_index = (null == value) ? 0 : int.parse(value);
      print('loginTabs_index = ${loginTabs_index}');
      //用TabController实现顶部tab切换，并设置默认 Tab。initialIndex: loginTabs_index
      _tabController = TabController(vsync: this, length: 1, initialIndex: loginTabs_index);

      //监听 _tabController 切换事件
      _tabController.addListener(() {
        Storage.setString("LoginTabs_index", _tabController.index.toString());
        print('_tabController.index = ${_tabController.index}');
      });

      //Flutter DefaultTabController 获取/设置当前 Tab - OK
      DefaultTabController.of(_scaffoldKey.currentContext).animateTo(loginTabs_index);
      try_setState();
    });

    //监听统计数据改变事件
    eventBus.on<StatisDataUpdate>().listen((event) {
      print(event.str);
      updateMayLogin();
    });

    // 去除可能存在的试用版水印
    _watermarkPlugin.removeWatermark();
  }

  //处理延迟登录
  updateMayLogin() {
    //判断从网络获取三种统计数据是否完成
    // if (listZptjStatisAlone.length >= dwSum &&
    //     listTodayShtj.length >= dwSum &&
    //     listClltjStatisAlone.length >= dwSum) {
    //   bMayLogin = true;
    // }
    if (listAllStatisData.length >= dwSum) {
      bMayLogin = true;
    } else {
      bMayLogin = false;
    }
    try_setState();
  }

  dispose() {
    _tabController?.dispose();
    super.dispose();
  }

  double _height = ScreenUtil().setHeight(1026);
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: _height,
      child: DefaultTabController(
        length: 2,
        child: Scaffold(
          key: _scaffoldKey,
          backgroundColor: Colors.transparent,
          appBar: PreferredSize(
            preferredSize: Size.fromHeight(50), // here the desired height
            child: AppBar(
              backgroundColor: Colors.transparent,
              bottom: TabBar(
                controller: _tabController,
                indicatorSize: TabBarIndicatorSize.label,
                labelColor: Color.fromRGBO(49, 216, 123, 1),
                unselectedLabelColor: Color.fromRGBO(118, 135, 162, 1),
                //tabs: <Widget>[Tab(text: "  密码登录  "), Tab(text: "  刷脸登录  ")],
                tabs: <Widget>[
                  my_Tabs.MyTab(
                      text: "  密码登录  ",
                      style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold)),
                  // my_Tabs.MyTab(
                  //     text: "  刷脸登录  ",
                  //     style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold))
                ],
                // tabs: <Widget>[
                //   Text("  密码登录  ", style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold)),
                //   Text("  刷脸登录  ", style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold)),
                // ],
              ),
            ),
          ),
          body: Stack(
            children: [
              TabBarView(
                controller: _tabController,
                //flutter tabbar禁止手势滑动-OK
                physics: new NeverScrollableScrollPhysics(),
                children: <Widget>[
                  LoginByName3(height: _height),
                  // FaceLogin2(),
                ],
              ),
              // bMayLogin
              //     ? SizedBox.shrink()
              //     : Positioned(
              //         left: ScreenUtil().setWidth(0),
              //         right: ScreenUtil().setWidth(0),
              //         top: ScreenUtil().setHeight(297),
              //         child: Container(
              //           height: 200,
              //           width: 400,
              //           child: getMoreWidget2(
              //             text: '正在获取网络数据 ...',
              //             color: Colors.orangeAccent,
              //             size: 25.0,
              //             strokeWidth: 3.0,
              //             fontWeight: FontWeight.w600,
              //             edge: 0,
              //             height: 60,
              //           ), //显示加载中的圈圈,
              //         ),
              //       ),
            ],
          ),
        ),
      ),
    );
  }
}
