import 'dart:async';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';

import 'package:base/consts/color.dart';
import 'package:base/consts/external_assets_package_key.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:shared_preferences/shared_preferences.dart';

import '../../services/no_plan_inspection.dart';
import '../../view/CheckExecute/navigation_checkexec.dart';

class NfcPage extends StatefulWidget {
  final num taskId;

  const NfcPage({this.taskId});

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

class _NfcPageState extends State<NfcPage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.black54,
        appBar: AppBar(
          title: const Text(
            'NFC',
            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,
          child: Container(
            padding: const EdgeInsets.only(top: 50),
            child: Column(
              children: <Widget>[
                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)),
                  ),
                ),
                const Padding(
                  padding: EdgeInsets.only(bottom: 20),
                ),
                Image.asset(
                  'assets/images/noplan/nfc_m.png',
                  package: ExternalAssetsPackageKey.BASE,
                  width: 160.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();
  }

  String theme = '';

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

  Future<void> getContent(String no) async {
    await getQueryPlanTaskBySerialInfo(2, no, null).then((data) {
      if (data != null && data.success) {
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return NavigationCheckExec(data.id, pointName: data.name, checkMode: 'NFC');
        }));
      } else {
        shortMessage(data.message);
      }
    });
  }
}
