import 'dart:convert';

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter_screenutil/screen_util.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:audioplayers/audio_cache.dart';
import '../../components/commonFun.dart';
import '../../components/dioFun.dart';

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

  @override
  _TakePictuerState createState() {
    return _TakePictuerState();
  }
}

class _TakePictuerState extends State<TakePictuer> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  String timestamp() => DateTime.now().millisecondsSinceEpoch.toString();

  Image image;
  String imagePath;
  CameraController _cameraController;

  @override
  void initState() {
    super.initState();
    //controller = CameraController(cameras[0], ResolutionPreset.medium); //后置相机
    _cameraController = CameraController(cameras[1], ResolutionPreset.medium); //前置相机
    _cameraController.initialize().then((_) {
      //初始化相机
      if (!mounted) {
        return;
      }
      _onCamera(); //开始拍照
      setState(() {});
    });
  }

  @override
  void dispose() {
    _cameraController?.dispose();
    super.dispose();
  }

  //开始拍照
  Future<void> _onCamera() async {
    await Future.delayed(Duration(milliseconds: 1000), () {
      print('开始拍照...');
      AudioCache().play(File('audio/yinxiao1064.mp3').path); //播放咔嚓声
      onTakePictureButtonPressed();
    });
  }

  @override
  Widget build(BuildContext context) {
    if (!_cameraController.value.isInitialized) {
      return Container();
    }

    return Scaffold(
      key: _scaffoldKey,
      // appBar: AppBar(
      //   automaticallyImplyLeading: false,
      //   title: Container(
      //     //获取 appBar 高度 kToolbarHeight，R:\Flutter\FlutterSDK\flutter\packages\flutter\lib\src\material\constants.dart
      //     height: kToolbarHeight,
      //     //width: ScreenUtil().screenWidth,
      //     width: double.infinity,
      //     child: Text('请拿起手机，眨眨眼 ...'),
      //     decoration: BoxDecoration(
      //       gradient: LinearGradient(
      //         begin: Alignment.centerLeft,
      //         end: Alignment.centerRight,
      //         colors: [
      //           Color.fromRGBO(12, 186, 156, 1),
      //           Color.fromRGBO(39, 127, 235, 1),
      //         ],
      //       ),
      //     ),
      //   ),
      // ),
      body: Container(
        decoration: new BoxDecoration(
          //color: Colors.black,
          color: Colors.transparent,
        ),
        child: Column(
          children: [
            SizedBox(height: ScreenUtil().statusBarHeight), //显示顶部状态栏
            Container(
              alignment: Alignment(0, 0),
              child: Text(
                '请拿起手机，眨眨眼 ...',
                style: TextStyle(fontSize: 18.0, color: Colors.white),
                textAlign: TextAlign.center,
              ),
              height: ScreenUtil().setHeight(173),
              //越界
              //height: kToolbarHeight,
              //width: ScreenUtil().screenWidth,
              width: double.infinity,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                  colors: [
                    Color.fromRGBO(12, 186, 156, 1),
                    Color.fromRGBO(39, 127, 235, 1),
                  ],
                ),
              ),
            ),
            Stack(
              children: <Widget>[
                Align(
                  child: _cameraPreviewWidget(),
                ),
                Align(
                  child: _getImage(),
                ),
                Positioned(
                  left: ScreenUtil().screenWidth / 3,
                  top: ScreenUtil().screenHeight / 4,
                  child: image == null ? getMoreWidget() : _getSuccess(),
                ),
                // Align(
                //   alignment: Alignment.bottomCenter,
                //   child: Center(
                //     child: image == null ? getMoreWidget() : _getSuccess(),
                //   ),
                // ),
              ],
            ),
            Expanded(child: Container(color: Colors.black))
          ],
        ),
      ),
    );
  }

  //mounted 是 bool 类型，表示当前 State 是否加载到树⾥。
  // 常用于判断页面是否释放。比如在程序中有些异步的处理，当处理结束时直接调用setState方法会直接报错，
  // 因为页面已经释放（dispose）了，此时无法渲染页面，这时就可以使用mounted来进行判断页面是否被释放，如果释放了就不进行渲染。
  // if(mounted){
  //     setState((){})
  // }
  void onTakePictureButtonPressed() async {
    image = null;
    takePicture().then((String filePath) async {
      if (mounted) {
        setState(() {
          imagePath = filePath;
        });

        if (filePath != null) {
          image = Image.file(File(filePath));
          print('Picture saved to $filePath');
        }

        await Future.delayed(Duration(milliseconds: 1000), () {
          if (filePath != null) {
            if ('FaceLogin' == widget.arguments) {
              //人脸验证，直接调用 uploadImage 进行验证登录
              faceLoginFun(filePath: filePath, context: context);
            } else if ('FaceReg' == widget.arguments) {
              //返回获得的人脸图片路径 filePath，等待管理员确认注册
              Navigator.pop(context, filePath);
              //人脸注册，username 用户名，filePath 人脸图片路径
              //faceRegFun(username: 'admin', filePath: filePath);
            }
          }
        });
      }
    });
  }

  Future<String> takePicture() async {
    if (!_cameraController.value.isInitialized) {
      print('Error: select a camera first.');
      return null;
    }
    final Directory extDir = await getApplicationDocumentsDirectory();
    final String dirPath = '${extDir.path}/Pictures/flutter_test';
    await Directory(dirPath).create(recursive: true);
    final String filePath = '$dirPath/${timestamp()}.jpg';

    if (_cameraController.value.isTakingPicture) {
      // A capture is already pending, do nothing.
      return null;
    }

    try {
      await _cameraController.takePicture(filePath);
    } on CameraException catch (e) {
      print('e = ${e.toString()}');
      return null;
    }
    return filePath;
  }

  //拍照成功
  Widget _getSuccess({String text = '拍照成功！'}) {
    if (image == null || _cameraController == null || !_cameraController.value.isInitialized) {
      return Container(); //不能放回null，否则Stack会报错
    } else {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Icon(
              Icons.check,
              size: 60,
              color: Colors.white,
            ),
            SizedBox(
              height: 10,
            ),
            Text(
              text,
              style: TextStyle(
                fontSize: 30.0, // 文字大小
                color: Colors.white, // 文字颜色
              ),
            ),
          ],
        ),
      );
    }
  }

  //加载照片
  Widget _getImage() {
    if (image == null || _cameraController == null || !_cameraController.value.isInitialized) {
      return Container(); //不能放回null，否则Stack会报错
    } else {
      return Center(
        child: AspectRatio(
          aspectRatio: _cameraController.value.aspectRatio,
          child: image,
        ),
      );
    }
  }

  Widget _cameraPreviewWidget() {
    if (_cameraController == null || !_cameraController.value.isInitialized) {
      return const Text(
        '正在启动相机...',
        style: TextStyle(
          color: Colors.white,
          fontSize: 24.0,
          fontWeight: FontWeight.w900,
        ),
      );
    } else {
      return AspectRatio(
        aspectRatio: _cameraController.value.aspectRatio,
        child: CameraPreview(_cameraController),
      );
    }
  }
}
