import 'package:chicken_farm/core/services/pda/rfid_manager.dart'; import 'package:chicken_farm/core/utils/logger.dart'; import 'package:flutter/material.dart'; import 'package:chicken_farm/components/vb_app_bar.dart'; import 'package:chicken_farm/core/utils/toast.dart'; import 'package:chicken_farm/core/services/pda/scan_channel.dart'; import 'package:chicken_farm/components/vb_rfid_field.dart'; class CageChangePage extends StatefulWidget { const CageChangePage({super.key}); @override State createState() => _CageChangePageState(); } class _CageChangePageState extends State { String? _sourceCageId; String? _targetCageId; final List _rfids = []; // 添加FocusNode用于控制焦点 final FocusNode _sourceCageFocusNode = FocusNode(); final FocusNode _targetCageFocusNode = FocusNode(); // 扫描状态 bool _isScanningSource = false; bool _isScanningTarget = false; int _scanTag = 1; late final RfidManager _rfidManager; @override void initState() { super.initState(); // 监听焦点变化以更新_scanTag值 _sourceCageFocusNode.addListener(() { if (_sourceCageFocusNode.hasFocus) { _scanTag = 1; } }); _targetCageFocusNode.addListener(() { if (_targetCageFocusNode.hasFocus) { _scanTag = 2; } }); ScanChannel.openScanHead().then((success) { if (success) { logger.d("扫描头已打开"); } else { logger.d("扫描头打开失败"); } }); // 初始化监听 ScanChannel.initScanListener( onScanResult: (result) { logger.d("扫码结果:$result"); if (_scanTag == 1) { // 源笼号 setState(() { _sourceCageId = result; _isScanningSource = false; }); // 源笼号扫描成功后自动延时扫描目标笼号 WidgetsBinding.instance.addPostFrameCallback((_) { _sourceCageFocusNode.requestFocus(); logger.d("开始自动扫描目标笼号"); _dealyScanCode(2); }); } else if (_scanTag == 2) { // 目标笼号 setState(() { _targetCageId = result; _isScanningTarget = false; }); } else if (_scanTag == 3) {} // 扫码成功后停止解码(保留扫描头) ScanChannel.stopSingleScan(); }, onScanError: (error) { logger.d("扫码错误:$error"); setState(() { _isScanningSource = false; }); }, ); // 进入页面默认使原笼号获取到焦点 WidgetsBinding.instance.addPostFrameCallback((_) { _sourceCageFocusNode.requestFocus(); }); } @override void dispose() { // 释放FocusNode _sourceCageFocusNode.dispose(); _targetCageFocusNode.dispose(); // 释放RFID _rfidManager.disposeRfid(); // 手动关闭扫描头,立即释放资源 ScanChannel.closeScanHead(); // 释放通道 ScanChannel.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: const VberAppBar(title: '换笼管理', showLeftButton: true), body: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // 源笼号区域 _buildCageSection(1), const SizedBox(height: 15), // 目标笼号区域 _buildCageSection(2), const SizedBox(height: 15), // 电子编号区域 _buildRfidSection(), const SizedBox(height: 15), // 提交按钮 SizedBox( width: double.infinity, child: ElevatedButton( onPressed: _sourceCageId != null && _targetCageId != null && _rfids.isNotEmpty ? _handleSubmit : null, style: ElevatedButton.styleFrom( backgroundColor: (_sourceCageId != null && _targetCageId != null && _rfids.isNotEmpty) ? Colors.blue : Colors.grey, foregroundColor: Colors.white, ), child: const Text('提交'), ), ), const SizedBox(height: 20), // 已扫描的电子编号列表 if (_rfids.isNotEmpty) ...[ const Text( '已扫描的电子编号', style: TextStyle(fontWeight: FontWeight.bold), ), const SizedBox(height: 10), Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(8), ), child: ListView.builder( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), padding: EdgeInsets.zero, itemCount: _rfids.length, itemBuilder: (context, index) { return ListTile( visualDensity: VisualDensity.compact, contentPadding: const EdgeInsets.symmetric( horizontal: 2, vertical: 0, ), title: Text(_rfids[index]), trailing: IconButton( icon: const Icon( Icons.delete, size: 18, color: Colors.red, ), onPressed: () => _removeRfid(index), ), ); }, ), ), ], const SizedBox(height: 20), ], ), ), ), ); } Widget _buildCageSection(int tag) { String title = '源笼号'; String? value = _sourceCageId; bool isScanning = _isScanningSource; FocusNode focusNode = _sourceCageFocusNode; if (tag != 1) { tag = 2; title = '目标笼号'; value = _targetCageId; isScanning = _isScanningTarget; focusNode = _targetCageFocusNode; } return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(title, style: const TextStyle(fontWeight: FontWeight.bold)), const SizedBox(height: 10), Container( padding: const EdgeInsets.fromLTRB(16, 2, 16, 2), decoration: BoxDecoration( border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(8), ), child: Row( children: [ Expanded( // 将Text替换为TextField child: TextField( focusNode: focusNode, controller: TextEditingController(text: value), decoration: InputDecoration( border: InputBorder.none, hintText: value ?? '未扫描', hintStyle: TextStyle( color: value != null ? Colors.black : Colors.grey, fontSize: 16, ), ), style: TextStyle( color: value != null ? Colors.black : Colors.grey, fontSize: 16, ), onChanged: (text) { // 根据标题判断是哪个输入框 if (title == '源笼号') { setState(() { _sourceCageId = text.isEmpty ? null : text; }); } else if (title == '目标笼号') { setState(() { _targetCageId = text.isEmpty ? null : text; }); } }, ), ), if (value != null) ...[ IconButton( icon: const Icon(Icons.refresh, size: 20), onPressed: () { _handleChangeCageCode(tag); }, ), ] else ...[ IconButton( icon: isScanning ? const SizedBox( width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2), ) : const Icon(Icons.qr_code_scanner, size: 20), onPressed: () { _handleScanCageCode(tag); }, ), ], ], ), ), ], ); } Widget _buildRfidSection() { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('电子编号', style: TextStyle(fontWeight: FontWeight.bold)), const SizedBox(height: 10), Container( padding: const EdgeInsets.fromLTRB(16, 2, 16, 2), decoration: BoxDecoration(), ), ], ); // return VberRfidField( // rfids: _rfids, // onRfidScanned: (rfid) { // setState(() { // _rfids.insert(0, rfid); // }); // ToastUtil.success("标签已添加"); // }, // multiple: true, // label: '鸡数量', // multiplePlaceholder: '未扫描', // multipleFormat: '已扫描 %d 只鸡', // ); } void _dealyScanCode(int scanTag, {int? dealy}) async { dealy ??= 800; _scanTag = scanTag; await Future.delayed(Duration(milliseconds: dealy)); bool success = await ScanChannel.startScan(); if (!success) { ToastUtil.error("扫码失败"); } } void _handleScanCageCode(int tag) async { if (_isScanningTarget || _isScanningSource) return; setState(() { if (tag == 1) { _isScanningSource = true; } else if (tag == 2) { _isScanningTarget = true; } }); _scanTag = tag; bool success = await ScanChannel.startScan(); if (!success) { ToastUtil.error("扫码失败"); } } void _handleChangeCageCode(int tag) { setState(() { _sourceCageId = null; }); _dealyScanCode(tag); } // 移除指定索引的电子编号 void _removeRfid(int index) { setState(() { _rfids.removeAt(index); }); } // 提交数据 void _handleSubmit() { // 在实际应用中,这里会发送数据到服务器 ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('换笼操作提交成功'), backgroundColor: Colors.green), ); // 提交后重置表单 setState(() { _sourceCageId = null; _targetCageId = null; _rfids.clear(); }); } }