import 'dart:convert';
import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/bottom_picker.dart';
import 'package:qhd_prevention/customWidget/custom_alert_dialog.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:qhd_prevention/customWidget/department_person_picker.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/pages/home/tap/item_list_widget.dart';
import 'package:qhd_prevention/pages/home/work_alert.dart';
import 'package:qhd_prevention/pages/my_appbar.dart';
import 'package:qhd_prevention/services/nfc_service.dart';
import 'package:qhd_prevention/tools/tools.dart';

class HomeNfcAddPage extends StatefulWidget {
  const HomeNfcAddPage({super.key});

  @override
  State<HomeNfcAddPage> createState() => _HomeNfcAddPageState();
}

class _HomeNfcAddPageState extends State<HomeNfcAddPage> {
  late Map<String, dynamic> pd = {};
  int currentPage = 1;
  late List areaAllList = [];
  late List equipmentList = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getData();
  }

  /// 获取管道区域列表
  Future<void> _getData() async {
    final data = await ApiService.getNfcPipeLineAreaList();
    if (data['result'] == 'success') {
      areaAllList = data['varList'];
    }
  }

  /// 通过管道区域获取对应的设备列表
  Future<void> _getPipelineForArea() async {
    final data = await ApiService.getNfcEquipmentPipelineListAll(
      pd['PIPELINE_AREA_ID'],
    );
    if (data['result'] == 'success') {
      equipmentList = data['varList'];
    }
  }

  void _choosePipeLineHandle() async {
    // 创建选项列表
    final options = areaAllList.map((e) => e['AREA_NAME'] as String).toList();

    // 显示底部选择器
    final choice = await BottomPicker.show<String>(
      context,
      items: options,
      itemBuilder: (item) => Text(item, textAlign: TextAlign.center),
    );

    if (choice != null) {
      // 找到选择的索引
      final newIndex = options.indexOf(choice);
      if (newIndex != -1) {
        Map selectData = areaAllList[newIndex];
        pd['PIPELINE_AREA_ID'] = selectData['PIPELINE_AREA_ID'] ?? '';
        pd['AREA_NAME'] = selectData['AREA_NAME'] ?? '';
        _getPipelineForArea();
      }
    }
  }

  void _choosePipeHandle() async {
    if (!FormUtils.hasValue(pd, 'PIPELINE_AREA_ID')) {
      ToastUtil.showNormal(context, "请先选择管道区域");
      return;
    }
    // 创建选项列表
    final options =
        equipmentList.map((e) => e['EQUIPMENT_NAME'] as String).toList();

    // 显示底部选择器
    final choice = await BottomPicker.show<String>(
      context,
      items: options,
      itemBuilder: (item) => Text(item, textAlign: TextAlign.center),
    );

    if (choice != null) {
      // 找到选择的索引
      final newIndex = options.indexOf(choice);
      if (newIndex != -1) {
        Map selectData = equipmentList[newIndex];
        pd['EQUIPMENT_PIPELINE_ID'] = selectData['EQUIPMENT_PIPELINE_ID'] ?? '';
        pd['EQUIPMENT_NAME'] = selectData['EQUIPMENT_NAME'] ?? '';
      }
    }
  }

  Future<void> _startWrite() async{
    final textRules = <Map<String, dynamic>>[
      {'value': pd['PIPELINE_AREA_ID'] ?? '', 'message': '请选择管道区域'},
      {'value': pd['EQUIPMENT_PIPELINE_ID'] ?? '', 'message': '请选择对应的管道设备'},
      {'value': pd['TAG_NAME'] ?? '', 'message': '请填写标签名称'},
    ];
    for (var rule in textRules) {
      if ((rule['value'] as String).isEmpty) {
        ToastUtil.showNormal(context, rule['message']);
        return;
      }
    }
    final confirmed = await CustomAlertDialog.showConfirm(
      context,
      title: '提示',
      content: '请将手机靠近NFC标签准备写入',
      cancelText: '',
      confirmText: '我知道了',
      barrierDismissible: false,
    );
    if (confirmed) {
      LoadingDialogHelper.show(message: '等待手机靠近NFC标签');
      NfcService.instance.startScanOnceWithCallback(
        onResult: (uid, parsedText, rawMsg) async {
           final result = await ApiService.nfcWriteCheck(uid);
           if (result['result'] == 'success') {
             _writeNFCInfoRequest();
           }else{
             ToastUtil.showError(context, result['result'] ?? '');
           }
           LoadingDialogHelper.hide();
        },
        onError: (err) {
          ToastUtil.showNormal(context, '$err');
          LoadingDialogHelper.hide();

        },
        timeout: Duration(seconds: 12),
      );
    }
  }

  Future<void> _writeNFCInfoRequest() async{
   await NfcService.instance.writeText(
      mapToCompactJson({'PIPELINE_AREA_ID':pd['PIPELINE_AREA_ID'],'EQUIPMENT_PIPELINE_ID':pd['EQUIPMENT_PIPELINE_ID']}),
      timeout: Duration(seconds: 12),
      onComplete: (ok, msg) async{
        if (ok) {
          pd['NFC_CODE'] = msg;
          final result = await ApiService.nfcTagAdd(pd);
          if (result['result'] == 'success') {
            ToastUtil.showSuccess(context, '写入成功');
            Navigator.pop(context);
          }else{
            ToastUtil.showError(context, '写入失败，请重试');
          }
        }else{
          ToastUtil.showError(context, '$msg');

        }
        LoadingDialogHelper.hide();
      },
    );
   LoadingDialogHelper.hide();

  }

  String mapToCompactJson(Map<String, dynamic> map) {
    // 使用 jsonEncode 转换
    String jsonStr = jsonEncode(map);
    // 去掉所有空格、换行、制表符
    jsonStr = jsonStr.replaceAll(RegExp(r'\s+'), '');

    return jsonStr;
  }
  void _getNfcData() async{

    NfcService.instance.startScanOnceWithCallback(
      onResult: (uid, parsedText, rawMsg) async {
        final confirmed = await CustomAlertDialog.showConfirm(
          context,
          title: '内容',
          content: 'UID: $uid \n data: $parsedText',
          cancelText: '',
          confirmText: '我知道了',
          barrierDismissible: false,
        );
        print('UID: $uid, text: $parsedText');
      },
      onError: (err) => print('err: $err'),
      timeout: Duration(seconds: 12),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppbar(title: 'NFC标签写入'
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: EdgeInsets.all(12),
          child: Column(
            children: [
              ItemListWidget.itemContainer(
                horizontal: 5,
                Column(
                  children: [
                    ItemListWidget.selectableLineTitleTextRightButton(
                      label: '管道区域',
                      isEditable: true,
                      text: pd['AREA_NAME'] ?? '',
                      onTap: _choosePipeLineHandle,
                    ),
                    const Divider(),
                    ItemListWidget.selectableLineTitleTextRightButton(
                      label: '管道设备',
                      isEditable: true,
                      text: pd['EQUIPMENT_NAME'] ?? '',
                      onTap: _choosePipeHandle,
                    ),
                    const Divider(),
                    ItemListWidget.singleLineTitleText(
                      label: '标签名称',
                      isEditable: true,
                      hintText: '请输入标签名称',
                      onChanged: (val) {
                        pd['TAG_NAME'] = val;
                      },
                    ),
                  ],
                ),
              ),
              SizedBox(height: 20,),
              CustomButton(text: '立即写入', backgroundColor: Colors.blue,onPressed: _startWrite,)
            ],
          ),
        ),
      ),
    );
  }
}
