import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';

//import 'package:flutter_qr_reader/flutter_qr_reader.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:safe_control/model/Task/TaskContentResult.dart';
import 'package:safe_control/model/Task/TaskModel.dart';

import '../../../view/task_process/task_process_screen.dart';
import '../task_detail_screen.dart';

class QrPage extends StatefulWidget {
  final TaskContent task;
  final TaskModel taskModel;

  const QrPage(this.task, this.taskModel);

  @override
  State<StatefulWidget> createState() => _QrPageState();
}

class _QrPageState extends State<QrPage> {
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
  var qrText = '';
  //QrReaderViewController _controller;

  bool camState = false;
  int returnTimes = 0;

  final Permission _permission = Permission.camera;
  PermissionStatus _permissionStatus = PermissionStatus.undetermined;

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

    setState(() {
      camState = true;
    });

    _listenForPermissionStatus();

    if (_permissionStatus == PermissionStatus.granted) {
      setState(() {
        camState = true;
      });
    } else {
      requestPermission(_permission).then((v) {
        if (_permissionStatus == PermissionStatus.granted) {
          setState(() {
            camState = true;
          });
        } else {
          setState(() {
            camState = false;
          });
          MsgBox.showMessageOnly('请授予权限后重新操作！', context);
        }
      });
    }
  }

  void _listenForPermissionStatus() async {
    final status = await _permission.status;
    setState(() => _permissionStatus = status);
  }

  Future<void> requestPermission(Permission permission) async {
    final status = await permission.request();

    setState(() {
      print(status);
      _permissionStatus = status;
      print(_permissionStatus);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text(
            '二维码扫描',
            style: TextStyle(color: Colors.black, fontSize: 19),
          ),
          centerTitle: true,
          elevation: 0.7,
          brightness: Brightness.light,
          backgroundColor: Colors.grey,
          leading: Container(
            child: GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: const Icon(Icons.keyboard_arrow_left, color: Colors.red, size: 32),
            ),
          ),
        ),
        body: Column(
          children: <Widget>[
            Expanded(
              child: Stack(
                children: <Widget>[
                  camState
                      ? /*QrReaderView(
                          width: 400,
                          height: 1000,
                          callback: (container) {
                            _controller = container;
                            _controller.startCamera(onScan);
                          })*/
                  Container(
                    decoration: const BoxDecoration(
                      color: Colors.black,
                    ),
                  )
                      : Container(
                          decoration: const BoxDecoration(
                            color: Colors.black,
                          ),
                        ),
                  Container(
                      height: 40,
                      width: double.infinity,
                      margin: const EdgeInsets.only(left: 60, right: 60, top: 40),
                      child: Container(
                        child: const Text(
                          '对准二维码',
                          style: TextStyle(fontSize: 16, color: Colors.white),
                        ),
                      ),
                      decoration: const BoxDecoration(
                        color: Colors.black38,
                        borderRadius: BorderRadius.all(Radius.circular(25.0)),
                      ),
                      alignment: Alignment.center),
                  GestureDetector(
                    child: Center(
                      child: Stack(
                        children: <Widget>[
                          const Padding(
                            padding: EdgeInsets.only(bottom: 10),
                          ),
                          SizedBox(
                            height: 300.0,
                            width: 270.0,
                            child: Container(
                              decoration: BoxDecoration(border: Border.all(color: Colors.white, width: 1.0)),
                            ),
                          ),
                          Positioned(
                            child: Container(
                              width: 270.0,
                              height: 1,
                              color: Colors.white,
                            ),
                          )
                        ],
                      ),
                    ),
                    onTap: () {
                      //_controller.setFlashlight();
                    },
                  ),
                ],
              ),
              flex: 4,
            ),
          ],
        ));
  }

  void onScan(String v, List<Offset> offsets) {
    if (v != null && v.isNotEmpty) {
      setState(() {
        returnTimes = returnTimes + 1;
      });
      if (returnTimes == 1) {
        scan(v);
      }
      //_controller.stopCamera();
    }
  }

  scan(String code) {
    if (code.isNotEmpty) {
      getContent(code);
    } else {
      shortMessage('标签内容无法识别！').then((v) {
       /* if (_controller != null) {
          setState(() {
            returnTimes = 0;
          });
          _controller.startCamera(onScan);
        }*/
      });
    }
  }

  getContent(String no) async {
    if (widget.taskModel.taskDetails[0].pointNo == no) {
      Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => TaskProcessPage(
                    task: widget.task,
                    taskModel: widget.taskModel,
                  ))).then((v) {
       /* if (_controller != null) {
          setState(() {
            returnTimes = 0;
          });
          _controller.startCamera(onScan);
        }*/

        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => TaskDetailPage(
                      task: widget.task,
                    )));
      });
    } else {
      shortMessage(
        '请扫描正确的标签！',
        toastLength: Toast.LENGTH_SHORT,
      ).then((v) {
        /*if (_controller != null) {
          setState(() {
            returnTimes = 0;
          });
          _controller.startCamera(onScan);
        }*/
      });
    }
  }
}
