import 'dart:async';
import 'dart:convert';

import 'package:base/consts/external_assets_package_key.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_nfc_tools/flutter_nfc_tools.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:base/consts//color.dart';
import 'package:shared_preferences/shared_preferences.dart';

///NFC发卡
class SendCard extends StatefulWidget {
  String pointNo;

  SendCard(this.pointNo);

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

class _SendCardState extends State<SendCard> {
  String theme = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text(
            'NFC',
          ),
          centerTitle: true,
          elevation: 0.7,
          brightness: Brightness.light,
        ),
        body: Container(
          color: Colors.black54,
          child: Column(
            children: <Widget>[
              Expanded(
                child: Stack(
                  children: <Widget>[
                    Align(
                      alignment: const Alignment(0, -1),
                      child: Padding(
                        padding: const 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)),
                          ),
                        ),
                      ),
                    ),
                    Center(
                      child: Stack(
                        children: <Widget>[
                          const Padding(
                            padding: EdgeInsets.only(bottom: 10),
                          ),
                          SizedBox(
                              height: 200.0,
                              width: 270.0,
                              child: Image.asset(
                                'assets/images/noplan/nfc_m.png',
                                package: ExternalAssetsPackageKey.BASE,
                              )),
                        ],
                      ),
                    ),
                  ],
                ),
                flex: 1,
              )
            ],
          ),
        ));
  }

  Future<void> initPlatformState() async {
    String response = 'No error';

    try {
      FlutterNfcTools.init().then((m) {
        print('initialized : ' + m);
      }).catchError((err) {
        print('err : ' + err.toString());
      });
    } on PlatformException {
      response = 'Failed to scan tag.';
    }

    try {
      FlutterNfcTools.tagsEventsStream.listen((m) {
        print('tag scanned : ' + m);
      });
    } on PlatformException {
      response = 'Failed to scan tag.';
    }

    try {
      FlutterNfcTools.ndefEventsStream.listen((m) {
        print(widget.pointNo);
        List<int> data = [];
        data.add(2);
        data.add(99);
        data.add(110);
        data.addAll(utf8.encode(widget.pointNo));

        if (m['ndefMessage'] == null) {
          Map dataMap = {};
          dataMap['payload'] = data;
          dataMap['type'] = [84];
          dataMap['tnf'] = 1;
          dataMap['id'] = [];
          List<Map> msg = [dataMap];
          m['ndefMessage'] = msg;
        } else {
          List<int> data = [];
          data.add(2);
          data.add(99);
          data.add(110);
          data.addAll(utf8.encode(widget.pointNo));
          m['ndefMessage'][0]['type'] = [84];
          m['ndefMessage'][0]['payload'] = data;
          m['ndefMessage'][0]['tnf'] = '1';
        }

        print(m['ndefMessage']);
        FlutterNfcTools.writeTag(m['ndefMessage']);

        shortMessage('发卡成功！');
      });
    } on PlatformException {
      response = 'Failed to scan ndef.';
    }

    try {
      FlutterNfcTools.ndefFormatableEventsStream.listen((m) {
        print('ndefFormatable scanned : ' + m);
      });
    } on PlatformException {
      response = 'Failed to scan ndefFormatable.';
    }

    if (!mounted) return;
    setState(() {});
  }

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

  Future<void> initThemeConfig() async {
    SharedPreferences.getInstance().then((preferences) {
      setState(() {
        theme = preferences.getString('theme') ?? KColorConstant.DEFAULT_COLOR;
      });
    });
  }
}
