import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hyzp_ybqx/pages/Works/TJXX/tj_data.dart';

import '../../components/commonFun.dart';
import '../../services/EventBus.dart';

class FaceLogin2 extends StatefulWidget {
  FaceLogin2({this.arguments, Key key}) : super(key: key);
  var arguments;

  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<FaceLogin2> {
  //try_setState();   //避免如下异常报错
  try_setState() {
    try {
      setState(() {});
    } catch (e) {
      print('setState(() {})异常：${e}');
    }
  }

  Future<void> camerasInit() async {
    try {
      WidgetsFlutterBinding.ensureInitialized();
      cameras = await availableCameras();
      print(cameras.toString());
    } on CameraException catch (e) {
      //logError(e.code, e.description);
    }
  }

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

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

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

  //监听登录页面销毁的事件
  dispose() {
    super.dispose();
    eventBus.fire(new UserEvent('登录成功...'));
  }

  double _heigth = 340;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(
      //   centerTitle: true,
      //   title: Text('人脸验证登录'),
      // ),
      body: Container(
        padding: EdgeInsets.only(
            left: ScreenUtil().setWidth(60),
            right: ScreenUtil().setWidth(60),
            top: ScreenUtil().setWidth(58)),
        child: ListView(
          children: <Widget>[
            InkWell(
              child: Center(
                child: Container(
                  //margin: EdgeInsets.only(top: ScreenUtil().setHeight(40)),
                  height: ScreenUtil().setHeight(_heigth), //这样在不同的手机上会变形
                  width: ScreenUtil().setWidth(_heigth),
                  // height: _heigth,
                  // width: _heigth,
                  color: Colors.black12,
                  child: Stack(
                    children: [
                      Align(
                        alignment: Alignment.center,
                        child: Image.asset('assets/images/图层 5.png', fit: BoxFit.cover),
                      ),
                      Align(
                        alignment: Alignment.center,
                        child: Column(
                          children: [
                            SizedBox(height: ScreenUtil().setHeight(_heigth / 3)),
                            Container(
                              height: ScreenUtil().setHeight(6),
                              color: Color.fromRGBO(53, 136, 240, 1),
                            ),
                          ],
                        ),
                      ),
                      Align(
                          alignment: Alignment.bottomCenter,
                          child: Container(
                            height: ScreenUtil().setHeight(_heigth - _heigth / 3 - 6),
                            decoration: BoxDecoration(
                              gradient: LinearGradient(
                                begin: Alignment.topCenter,
                                end: Alignment.bottomCenter,
                                colors: [
                                  Color.fromRGBO(222, 237, 255, 1),
                                  Color.fromRGBO(255, 255, 255, 0),
                                ],
                              ),
                            ),
                          )),
                    ],
                  ),
                ),
              ),
              onTap: faceLogin,
            ),
            SizedBox(height: ScreenUtil().setHeight(40)),
            Container(
              height: ScreenUtil().setWidth(130),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  _getImageWidget('assets/images/形状 811.png', '正对手机'),
                  _getImageWidget('assets/images/形状 810.png', '光线充足'),
                  _getImageWidget('assets/images/形状 809.png', '放慢动作'),
                ],
              ),
            ),
            SizedBox(height: ScreenUtil().setHeight(20)),
            InkWell(
              onTap: faceLogin,
              child: Container(
                alignment: Alignment(0, 0),
                margin: EdgeInsets.all(5),
                padding: EdgeInsets.all(5),
                width: ScreenUtil().setWidth(999),
                height: ScreenUtil().setHeight(126),
                decoration: BoxDecoration(
                    color: Color.fromRGBO(23, 176, 91, 1), borderRadius: BorderRadius.circular(10)),
                child: Text(
                  bMayLogin ? "开始检测" : "加载中 . . .",
                  style: TextStyle(color: Colors.white, fontSize: 18),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 定义一个图文组件
  Widget _getImageWidget(String imagePath, String text) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          height: ScreenUtil().setHeight(60),
          child: Image.asset(imagePath, fit: BoxFit.cover),
        ),
        Text(text, style: TextStyle(fontSize: 14)),
      ],
    );
  }

  //定义一个组件显示图片
  Widget _getImage(String filePath) {
    if (null == filePath) {
      return Text("请选择图片...");
    }
    File _image = File(filePath);
    //return Image.file(_image);

    int imageWidth;
    int imageHeight;
    // 预先获取图片信息
    Image image = Image.file(File.fromUri(Uri.parse(filePath)));
    image.image
        .resolve(new ImageConfiguration())
        .addListener(new ImageStreamListener((ImageInfo info, bool _) {
      imageWidth = info.image.width;
      imageHeight = info.image.height;
    }));

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        //480*720
        Text('宽高：${imageWidth}x${imageHeight}', style: TextStyle(fontSize: 17.0)),
        Container(
          width: imageWidth / 4,
          height: imageHeight / 4,
          decoration: BoxDecoration(
            image: DecorationImage(image: AssetImage(filePath), fit: BoxFit.cover),
          ),
        )
      ],
    );
  }

  faceLogin() async {
    if (!bMayLogin) {
      return;
    }
    Navigator.pushNamed(context, '/faceLogin_take_pictuer', arguments: 'FaceLogin');
  }
}
