import 'package:amos_flutter_ui/amos_flutter_ui.dart';

import 'package:base/consts/color.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
//import 'package:flutter_qr_reader/flutter_qr_reader.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../model/offline_plan_list_output.dart';
import '../../services/offline_plan_inspection_services.dart';
import '../../view/CheckExecute/checkexec_inspection.dart';

class QrPage extends StatefulWidget {
  final num planTaskId;
  final String inOrder;

  QrPage(this.planTaskId, this.inOrder);

  @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;
  List<Point> points;

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

  @override
  void initState() {
    super.initState();
    _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);
        }
      });
    }
    loadData();
    initThemeConfig();
  }

  String theme = '';

  initThemeConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        this.theme = preferences.getString("theme") ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }

  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);
    });
  }

  void loadData() async {
    await getOfflinePlanListOutputById(this.widget.planTaskId).then((data) {
      setState(() {
        points = data.points;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '二维码扫描',
          style: TextStyle(color: Colors.black, fontSize: 19),
        ),
        centerTitle: true,
        elevation: 0.2,
        brightness: Brightness.light,
        backgroundColor: Colors.grey,
        leading: Container(
          child: GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: Icon(Icons.keyboard_arrow_left, color: GetConfig.getColor(theme), size: 32),
          ),
        ),
//        actions: <Widget>[
//          IconButton(icon:ImageIcon(AssetImage("assets/images/noplan/no_plan_torch.png"),size: 30,),
//            onPressed: (){
//            this.controller.toggleTorch();
//          },)
//        ],
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: Stack(
              children: <Widget>[
                camState
                    ?
//                LastQrScannerPreview(
//                  key: qrKey,
//                  onQRViewCreated: _onQRViewCreated,
//                )
                    /*QrReaderView(
                        width: 400,
                        height: 1000,
                        callback: (container) {
                          this._controller = container;
                          _controller.startCamera(onScan);
                        })*/
                Container(
                  decoration: const BoxDecoration(
                    color: Colors.black,
                  ),
                )
                    : Container(
                        decoration: const BoxDecoration(
                          color: Colors.black,
                        ),
                      ),
                Align(
                  alignment: const Alignment(0, -1),
                  child: Padding(
                    padding: EdgeInsets.only(top: 50),
                    child: Container(
                      height: 40,
                      width: 200,
                      child: const Align(
                        alignment: Alignment.center,
                        child: Text(
                          "对准二维码",
                          style: TextStyle(fontSize: 16, color: Colors.white),
                        ),
                      ),
                      decoration: const BoxDecoration(
                        color: Colors.black38,
                        borderRadius: BorderRadius.all(Radius.circular(25.0)),
                      ),
                    ),
                  ),
                ),
                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.red, width: 1.0)),
                          ),
                        ),
                        Positioned(
                          child: Container(
                            width: 270.0,
                            height: 1,
                            color: Colors.red,
                          ),
                        )
                      ],
                    ),
                  ),
                  onTap: () {
                   // _controller.setFlashlight();
                  },
                ),
              ],
            ),
            flex: 1,
          )
        ],
      ),
    );
  }

  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) {
    print(code);
    if (code.isNotEmpty) {
      getContent(code);
    } else {
      shortMessage('标签内容无法识别！').then((v) {
       /* if (_controller != null) {
          setState(() {
            returnTimes = 0;
          });
          _controller.startCamera(onScan);
        }*/
      });
    }
  }

  getContent(String pointNo) async {
    // 获取点信息
    Point chkPoint;
    for (var point in this.points) {
      if (point.pointNO == pointNo) {
        chkPoint = point;
        break;
      }
    }
    if (chkPoint == null) {
      shortMessage('没有对应的巡检点！').then((v) {
        /*if (_controller != null) {
          setState(() {
            returnTimes = 0;
          });
          _controller.startCamera(onScan);
        }*/
      });
      return;
    }

    // 已巡检
    if (chkPoint.status == "1") {
      shortMessage('当前点已提交巡检记录！').then((v) {
        /*if (_controller != null) {
          setState(() {
            returnTimes = 0;
          });
          _controller.startCamera(onScan);
        }*/
      });
      return;
    }

    // 校验是否按顺序巡检
    if (widget.inOrder == '1') {
      num lastOrder = chkPoint.orderNo - 1;
      if (lastOrder < 1) {
        // 本次扫描的点就是第一个点
      } else {
        Point _lastPoint;
        for (final _point in points) {
          if (_point.orderNo == lastOrder) {
            _lastPoint = _point;
            break;
          }
        }
        // check data
        if (_lastPoint.status == '1') {
          // 已完成 ok
        } else {
          shortMessage('此巡检为按序巡检,请按顺序进行巡检任务！').then((v) {
           /* if (_controller != null) {
              setState(() {
                returnTimes = 0;
              });
              _controller.startCamera(onScan);
            }*/
          });
          return;
        }
      }
    }
    setState(() {
      camState = false;
    });
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return CheckExecInspection(chkPoint, "QR");
    })).then((v) {
      /*if (_controller != null) {
        setState(() {
          returnTimes = 0;
        });
        _controller.startCamera(onScan);
      }*/
      // 刷新页面点信息
      loadData();
      setState(() {
        camState = true;
      });
    });
  }
}
