import 'dart:async';
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_nfc_tools/flutter_nfc_tools.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

class NfcPage extends StatefulWidget {
  final num taskId;
  NfcPage({this.taskId});

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

class _NfcPageState extends State<NfcPage> {
//  NfcData _nfcData;
  String _platformVersion = 'Unknown';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            "NFC",
            style: TextStyle(color: Colors.black, fontSize: 19),
          ),
          centerTitle: true,
          elevation: 0.7,
          brightness: Brightness.light,
          backgroundColor: Colors.grey,
          leading: new Container(
            child: GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Icon(Icons.keyboard_arrow_left,
                  color: GetConfig.getColor(theme), size: 32),
            ),
          ),
        ),
        body: Container(
          color: Colors.black54,
          width: double.infinity,
          child: Container(
            padding: EdgeInsets.only(top: 30),
            child: Column(
              children: <Widget>[
                Container(
                  height: 40,
                  width: 200,
                  child: Align(
                    alignment: Alignment.center,
                    child: Text(
                      "靠近巡检标签",
                      style: TextStyle(fontSize: 16, color: Colors.white),
                    ),
                  ),
                  decoration: new BoxDecoration(
                    color: Colors.black38,
                    borderRadius: new BorderRadius.all(Radius.circular(25.0)),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(bottom: 20),
                ),
                Image.asset(
                  "assets/images/noplan/nfc_m.png",
                  package: 'base',
                  height: 200.0,
                  width: 270.0,
                )
              ],
            ),
          ),
        ));
  }

  Future<void> initPlatformState() async {
    try {
      FlutterNfcTools.ndefEventsStream.listen((m) {
        if (m['ndefMessage'] == null) {
          shortMessage('标签无内容');
          return;
        }

        print(m['ndefMessage'][0]['payload']);

        List<int> payload =
            m['ndefMessage'][0]['payload'].sublist(3).cast<int>().toList();
        String content = FlutterNfcTools.bytesToString(payload);
        if (content.isNotEmpty) {
          getContent(content);
        } else {
          shortMessage('标签内容无法识别！');
        }
      });
    } on PlatformException {
      shortMessage('内容读取失败！');
    }

    if (!mounted) return;
  }

  @override
  void initState() {
    super.initState();
    initPlatformState();
    initThemeConfig();
  }

//  getContentOld(String no) async{
//    await getQueryPlanTaskBySerialInfo(2,no).then((data){
//      // 跳转页面
//      if(data != null){
////        if(this.widget.taskId != null && this.widget.taskId>0){
////          Navigator.push( context,
////              new MaterialPageRoute(builder: (context) {
////                return NavigationCheckExec(data.id,planId: this.widget.taskId,);
////              }));
////        }else{
//          Navigator.push( context,
//              new MaterialPageRoute(builder: (context) {
//                return NavigationCheckExec(data.id,checkMode:"NFC");
//              }));
////        }
//      }else{
//        shortMessage(
//          msg: '没有对应的巡检计划！',
//          toastLength: Toast.LENGTH_SHORT,
//        );
//      }
//    });

  getContent(String pointNo) async {
    // 查询参数
    List<dynamic> params = new List<dynamic>();
    params.add(pointNo);
    // 根据点编号查询点信息
    List<Map<String, dynamic>> points = await dbAccess()
        .queryData("select * from Point where pointNo = ?;", params);
    print(points);

    if (points.length == 0) {
      shortMessage('没有对应的巡检点！');
    } else {
      List<Point> listPoint = await getOfflinePointList(points);
      Point chkPoint = listPoint[0];
      Navigator.push(context, new MaterialPageRoute(builder: (context) {
        return CheckExecInspection(chkPoint, "NFC");
      }));
    }
  }
}
