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

import '../../services/qis.dart';


class MeasurementScanCode extends StatefulWidget {
  final String bizType; // 接收扫码传递的设备编码

  const MeasurementScanCode({Key key, @required this.bizType}) : super(key: key);

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

class _MeasurementScanCodeState extends State<MeasurementScanCode> {
  MethodChannel methodChannel;

  @override
  void initState() {
    super.initState();
    methodChannel = const MethodChannel('amosMethodChannel');
    checkPermission();
  }

  /// 检查权限
  Future<void> checkPermission() async {
    bool hasPermission = await Permission.camera.isGranted;
    if (!hasPermission) {
      bool hasPermission = await Permission.camera.request().isGranted;
      if (!hasPermission) {
        MsgBox.showMessageOnly('请授予权限后重新操作！', context);
      } else {
        scan();
      }
    } else {
      scan();
    }
  }

  ///扫码
  Future<void> scan() async {
    // getContent('13513A00012');
    String result = await methodChannel.invokeMethod('scan');
    if (result != null && result.isNotEmpty) {
      getContent(result);
    } else {
      Navigator.pop(context);
    }
  }

  Future<void> getContent(String no) async {
    await API.scanEquipQrCodeBizCode(no, widget.bizType).then((data) {
      if (data != null) {
        if (data['message'] != null) {
          shortMessage(data['message']).then((v) {
            // scan();

            Navigator.pop(context);
          });
        } else {
          shortMessage('送检成功');
          Navigator.pop(context, data);
        }
      }
    }).catchError((error) {
      shortMessage(error.toString()).then((v) {
         scan();
      });
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black54,
      appBar: AppBar(
        title: const Text(
          '二维码扫描',
          style: TextStyle(color: Colors.white, fontSize: 18),
        ),
        centerTitle: true,
        elevation: 0,
        brightness: Brightness.light,
        backgroundColor: Colors.black54,
      ),
      body: Container(
        color: Colors.black54,
        width: double.infinity,
        height: double.infinity,
      ),
    );
  }
}
