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';
import './DeviceDetailPage.dart';

class NewQrPage extends StatefulWidget {
  const NewQrPage({Key key}) : super(key: key);

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

class _NewQrPageState extends State<NewQrPage> {
  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 {
    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.queryEquipDetailsByCode(no).then((data) {
      if (data != null) {
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return DeviceDetailPage(deviceCode: no);
        })).then((v) {
          Navigator.pop(context);
        });
      } else {
        shortMessage('无法识别改二维码，可能此二维码不是系统维护的设备二维码').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,
      ),
    );
  }
}
