import 'package:flutter/material.dart';
// 拨打电话、发短信 插件引用
import 'package:url_launcher/url_launcher.dart';
// 拍照、相册 插件引用
import 'package:image_picker/image_picker.dart';
// 权限插件引用
import 'package:permission_handler/permission_handler.dart';
//系统自带
import 'dart:io';

// nfc页面引用
import 'nfc_page.dart';
// 拨号、短信页面引用
import 'call_phone_page.dart';
// 扫码页面引用
import 'scan_page.dart';

// app 入口函数 固定写法，不能变动
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      debugShowCheckedModeBanner:false,
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
//
class MyHomePage extends StatefulWidget {
  //
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".
//
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
        appBar: AppBar(
          // Here we take the value from the MyHomePage object that was created by
          // the App.build method, and use it to set our appbar title.
          title: Text(widget.title),
        ),
        body: SingleChildScrollView(
          child: Center(
            // Center is a layout widget. It takes a single child and positions it
            // in the middle of the parent.
            child: Column(
              // Column is also a layout widget. It takes a list of children and
              // arranges them vertically. By default, it sizes itself to fit its
              // children horizontally, and tries to be as tall as its parent.
              //
              // Invoke "debug painting" (press "p" in the console, choose the
              // "Toggle Debug Paint" action from the Flutter Inspector in Android
              // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
              // to see the wireframe for each widget.
              //
              // Column has various properties to control how it sizes itself and
              // how it positions its children. Here we use mainAxisAlignment to
              // center the children vertically; the main axis here is the vertical
              // axis because Columns are vertical (the cross axis would be
              // horizontal).
              children: <Widget>[
                SizedBox(height: 30,), // 设置间隔
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // 拍照
                    setupTakingPicturesView(),
                    SizedBox(width: 30,), // 设置间隔
                    // 相册
                    setupAlbumView(),
                  ],
                ),
                SizedBox(height: 30,), // 设置间隔
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // 打电话
                    setupCallPhoneView(),
                    SizedBox(width: 30,), // 设置间隔
                    // 发短信
                    setupSendMessageView(),
                  ],
                ),
                SizedBox(height: 30,), // 设置间隔

                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // 扫描二维码
                    setupQRCodeView(),
                    SizedBox(width: 30,), // 设置间隔
                    setupNFCView(),
                  ],
                )
              ],
            ),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        ));
  }

  // 设置 拍照 视图
  Widget setupTakingPicturesView() {
    /// 通过GestureDetector手势组件包裹视图 添加点击事件
    return GestureDetector(
      onTap: (){
        _getCameraImage();
      },
      child: Container(
        width: 150,
        height: 120,
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10)),
            boxShadow: [
            BoxShadow(
                color: Colors.deepPurple,
                offset: Offset(0.0, 0.0), //阴影y轴偏移量
            blurRadius: 5, //阴影模糊程度
            spreadRadius: 5 //阴影扩散程度
        )]
      ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center, // 设置内容居中
          children: [
            Icon(Icons.photo_camera),
            SizedBox(height: 5,),
            Text("Taking pictures")
          ],
        ),
      ),
    );
  }

  // 设置 相册 视图
  Widget setupAlbumView() {
    /// 通过GestureDetector手势组件包裹视图 添加点击事件
    return GestureDetector(
      onTap: (){
        print("点击相册事件");
        _getAlbumImage();
      },
      child: Container(
        width: 150,
        height: 120,
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10)),
            boxShadow: [
              BoxShadow(
                  color: Colors.red,
                  offset: Offset(0.0, 0.0), //阴影y轴偏移量
                  blurRadius: 5, //阴影模糊程度
                  spreadRadius: 5 //阴影扩散程度
              )]
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center, // 设置内容居中
          children: [
            Icon(Icons.photo_album),
            SizedBox(height: 5,),
            Text("Photo album")
          ],
        ),
      ),
    );
  }

  TextEditingController _vc = TextEditingController(text: "10086");
  // 设置 拨打电话 视图
  Widget setupCallPhoneView() {
    /// 通过Flutter InkWell组件包裹视图 添加点击事件
    return InkWell(
      onTap: () async {
        showDialog(
            barrierDismissible: false,
            context: context,
            builder: (context) {
              return AlertDialog(
                content: CallPhoneDialogContent(
                  title: "Please enter phone number",
                  okBtnTap: () async {
                    print(
                      "输入框中的文字为:${_vc.text}",
                    );

                    var url = 'tel:${_vc.text}';
                    if (await canLaunch(url)) {
                    await launch(url);
                    } else {
                    throw 'Could not launch $url';
                    }
                  },
                  vc: _vc,
                  cancelBtnTap: () {},
                ),
              );
            });

      },
      child: Container(
        width: 150,
        height: 120,
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10)),
            boxShadow: [
              BoxShadow(
                  color: Colors.orange,
                  offset: Offset(0.0, 0.0), //阴影y轴偏移量
                  blurRadius: 5, //阴影模糊程度
                  spreadRadius: 5 //阴影扩散程度
              )]
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center, // 设置内容居中
          children: [
            Icon(Icons.phone),
            SizedBox(height: 5,),
            Text("Call phone")
          ],
        ),
      ),
    );
  }

  // 设置 读取二维码 视图
  Widget setupQRCodeView() {
    /// 通过Flutter GestureDetector组件包裹视图 添加点击事件
    return GestureDetector(
      onTap: ()async {
        var status = await Permission.camera.request();
        if(status.isGranted){
          Navigator.push(context, new MaterialPageRoute(builder: (context) => ScanPage()));

        }
      },
      child: Container(
        width: 150,
        height: 120,
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10)),
            boxShadow: [
              BoxShadow(
                  color: Colors.blue,
                  offset: Offset(0.0, 0.0), //阴影y轴偏移量
                  blurRadius: 5, //阴影模糊程度
                  spreadRadius: 5 //阴影扩散程度
              )]
        ),
        child: Column( // 纵向布局组件
          mainAxisAlignment: MainAxisAlignment.center, // 设置内容居中
          children: [
            Icon(Icons.qr_code_scanner_outlined),
            SizedBox(height: 5,),
            Text("Scan QR Code")
          ],
        ),
      ),
    );
  }

  // 设置 发送短信 视图
  Widget setupSendMessageView() {
    /// 通过Flutter InkWell组件包裹视图 添加点击事件
    return InkWell(
      onTap: () async {
        showDialog(
            barrierDismissible: false,
            context: context,
            builder: (context) {
              return AlertDialog(
                content: CallPhoneDialogContent(
                  title: "Please enter phone number",
                  okBtnTap: () async {
                    print(
                      "输入框中的文字为:${_vc.text}",
                    );

                    var url = 'sms:${_vc.text}';
                    if (await canLaunch(url)) {
                      await launch(url);
                    } else {
                      throw 'Could not launch $url';
                    }
                  },
                  vc: _vc,
                  cancelBtnTap: () {},
                  okBtnTitle: "Send",
                ),
              );
            });
      },
      child: Container(
        width: 150,
        height: 120,
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10)),
            boxShadow: [
              BoxShadow(
                  color: Colors.green,
                  offset: Offset(0.0, 0.0), //阴影y轴偏移量
                  blurRadius: 5, //阴影模糊程度
                  spreadRadius: 5 //阴影扩散程度
              )]
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center, // 设置内容居中
          children: [
            Icon(Icons.mail_outline),
            SizedBox(height: 5,),
            Text("SMS")
          ],
        ),
      ),
    );
  }

  // 设置 NFC 视图
  Widget setupNFCView() {
    /// 通过Flutter InkWell组件包裹视图 添加点击事件
    return InkWell(
      onTap: () async {
        Navigator.push(context, new  MaterialPageRoute(builder: (context) => NFCPage()));
      },
      child: Container(
        width: 150,
        height: 120,
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10)),
            boxShadow: [
              BoxShadow(
                  color: Colors.greenAccent,
                  offset: Offset(0.0, 0.0), //阴影y轴偏移量
                  blurRadius: 5, //阴影模糊程度
                  spreadRadius: 5 //阴影扩散程度
              )]

        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center, // 设置内容居中
          children: [
            Icon(Icons.nfc),
            SizedBox(height: 5,),
            Text("NFC")
          ],
        ),
      ),
    );
  }

  // 实例化选择图片
  final ImagePicker picker = new ImagePicker();
  // 用户本地图片
  File _imagePath;//存放获取到的本地路径
  // 异步调起相机拍摄新照片方法
  Future _getCameraImage() async {
    final cameraImages = await picker.getImage(source: ImageSource.camera);
    if (mounted) {
      setState(() {
        //拍摄照片不为空
        if (cameraImages != null) {
          _imagePath = File(cameraImages.path);
          print('你选择的路径是：${_imagePath.toString()}');
          showAlertDialog();
          //图片为空
        } else {
          print('没有照片可以选择');
        }
      });
    }
  }

  Future _getAlbumImage() async {
    //选择相册
    final pickerImages = await picker.getImage(source: ImageSource.gallery);
    if(mounted){
      setState(() {
        if(pickerImages != null){
          _imagePath = File(pickerImages.path);
          print('你选择的本地路径是：${_imagePath.toString()}');
          showAlertDialog();
        }else{
          print('没有照片可以选择');
        }
      });
    }
  }


  // 展示图片结果弹窗
  void showAlertDialog() {
    showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new AlertDialog(
            title: new Text('Current display image'),
            //可滑动
            content: new SingleChildScrollView(
              child: new Image.file(_imagePath),
            ),
            actions: <Widget>[
              new FlatButton(
                child: new Text('Confirm'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              new FlatButton(
                child: new Text('Cancel'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        });
  }
}


