cage_change_page.dart 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. import 'package:chicken_farm/apis/index.dart';
  2. import 'package:chicken_farm/core/utils/logger.dart';
  3. import 'package:flutter/material.dart';
  4. import 'package:chicken_farm/components/vb_app_bar.dart';
  5. import 'package:chicken_farm/core/utils/toast.dart';
  6. import 'package:chicken_farm/core/services/pda/scan_channel.dart';
  7. import 'package:chicken_farm/components/vb_rfid_field.dart';
  8. class CageChangePage extends StatefulWidget {
  9. const CageChangePage({super.key});
  10. @override
  11. State<CageChangePage> createState() => _CageChangePageState();
  12. }
  13. class _CageChangePageState extends State<CageChangePage> {
  14. final List<String> _rfids = [];
  15. // 添加TextEditingControllers用于控制输入框
  16. final TextEditingController _sourceCageController = TextEditingController();
  17. final TextEditingController _targetCageController = TextEditingController();
  18. // 添加FocusNode用于控制焦点
  19. final FocusNode _sourceCageFocusNode = FocusNode();
  20. final FocusNode _targetCageFocusNode = FocusNode();
  21. // 扫描状态
  22. bool _isScanningSource = false;
  23. bool _isScanningTarget = false;
  24. int _scanTag = 1;
  25. @override
  26. void initState() {
  27. super.initState();
  28. _sourceCageController.clear();
  29. _targetCageController.clear();
  30. // 监听焦点变化以更新_scanTag值
  31. _sourceCageFocusNode.addListener(() {
  32. if (_sourceCageFocusNode.hasFocus) {
  33. _scanTag = 1;
  34. }
  35. });
  36. _targetCageFocusNode.addListener(() {
  37. if (_targetCageFocusNode.hasFocus) {
  38. _scanTag = 2;
  39. }
  40. });
  41. ScanChannel.openScanHead().then((success) {
  42. if (success) {
  43. logger.d("扫描头已打开");
  44. } else {
  45. logger.d("扫描头打开失败");
  46. }
  47. });
  48. // 初始化监听
  49. ScanChannel.initScanListener(
  50. onScanResult: (result) {
  51. if (_scanTag == 1) {
  52. // 源笼号
  53. setState(() {
  54. _sourceCageController.text = result;
  55. _isScanningSource = false;
  56. });
  57. if (_targetCageController.text.isEmpty) {
  58. // 源笼号扫描成功后自动延时扫描目标笼号
  59. ScanChannel.stopSingleScan();
  60. logger.d("自动扫描目标笼号");
  61. _targetCageFocusNode.requestFocus();
  62. _dealyScanCode(2);
  63. }
  64. } else if (_scanTag == 2) {
  65. // 目标笼号
  66. setState(() {
  67. _targetCageController.text = result;
  68. _isScanningTarget = false;
  69. });
  70. }
  71. // 扫码成功后停止解码(保留扫描头)
  72. ScanChannel.stopSingleScan();
  73. },
  74. onScanError: (error) {
  75. logger.d("扫码错误:$error");
  76. setState(() {
  77. _isScanningSource = false;
  78. });
  79. },
  80. onKeyPress: (bool isDouble, String keyCode) {
  81. if (isDouble && keyCode == "KEY_619") {
  82. _sourceCageController.clear();
  83. _targetCageController.clear();
  84. _scanTag = 1;
  85. ScanChannel.startScan();
  86. } else {
  87. logger.d("按键:$isDouble $keyCode");
  88. }
  89. },
  90. );
  91. _scanTag = 1;
  92. // 进入页面默认使原笼号获取到焦点
  93. // WidgetsBinding.instance.addPostFrameCallback((_) {
  94. // _sourceCageFocusNode.requestFocus();
  95. // });
  96. }
  97. @override
  98. void dispose() {
  99. // 释放TextEditingControllers
  100. _sourceCageController.dispose();
  101. _targetCageController.dispose();
  102. // 释放FocusNode
  103. _sourceCageFocusNode.dispose();
  104. _targetCageFocusNode.dispose();
  105. // 手动关闭扫描头,立即释放资源
  106. ScanChannel.closeScanHead();
  107. // 释放通道
  108. ScanChannel.dispose();
  109. super.dispose();
  110. }
  111. @override
  112. Widget build(BuildContext context) {
  113. return Scaffold(
  114. appBar: const VberAppBar(title: '换笼管理', showLeftButton: true),
  115. body: SingleChildScrollView(
  116. child: Padding(
  117. padding: const EdgeInsets.all(16.0),
  118. child: Column(
  119. crossAxisAlignment: CrossAxisAlignment.start,
  120. children: [
  121. // 源笼号区域
  122. _buildCageSection(1),
  123. const SizedBox(height: 15),
  124. // 目标笼号区域
  125. _buildCageSection(2),
  126. const SizedBox(height: 15),
  127. // 电子编号区域
  128. _buildRfidSection(),
  129. const SizedBox(height: 15),
  130. // 提交按钮
  131. SizedBox(
  132. width: double.infinity,
  133. child: ElevatedButton(
  134. onPressed:
  135. _sourceCageController.text.isNotEmpty &&
  136. _targetCageController.text.isNotEmpty &&
  137. _rfids.isNotEmpty
  138. ? _handleSubmit
  139. : null,
  140. style: ElevatedButton.styleFrom(
  141. backgroundColor:
  142. (_sourceCageController.text.isNotEmpty &&
  143. _targetCageController.text.isNotEmpty &&
  144. _rfids.isNotEmpty)
  145. ? Colors.blue
  146. : Colors.grey,
  147. foregroundColor: Colors.white,
  148. ),
  149. child: const Text('提交'),
  150. ),
  151. ),
  152. const SizedBox(height: 20),
  153. // 已识别的电子编号列表
  154. if (_rfids.isNotEmpty) ...[
  155. Row(
  156. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  157. children: [
  158. const Text(
  159. '已识别的电子编号',
  160. style: TextStyle(fontWeight: FontWeight.bold),
  161. ),
  162. IconButton(
  163. icon: const Icon(Icons.clear, size: 18),
  164. onPressed: _clearRfids,
  165. tooltip: '清空编号',
  166. ),
  167. ],
  168. ),
  169. const SizedBox(height: 10),
  170. Container(
  171. padding: const EdgeInsets.all(10),
  172. decoration: BoxDecoration(
  173. border: Border.all(color: Colors.grey),
  174. borderRadius: BorderRadius.circular(8),
  175. ),
  176. child: ListView.builder(
  177. shrinkWrap: true,
  178. physics: const NeverScrollableScrollPhysics(),
  179. padding: EdgeInsets.zero,
  180. itemCount: _rfids.length,
  181. itemBuilder: (context, index) {
  182. return ListTile(
  183. visualDensity: VisualDensity.compact,
  184. contentPadding: const EdgeInsets.symmetric(
  185. horizontal: 2,
  186. vertical: 0,
  187. ),
  188. title: Text(_rfids[index]),
  189. trailing: IconButton(
  190. icon: const Icon(
  191. Icons.delete,
  192. size: 18,
  193. color: Colors.red,
  194. ),
  195. onPressed: () => _removeRfid(index),
  196. ),
  197. );
  198. },
  199. ),
  200. ),
  201. ],
  202. const SizedBox(height: 20),
  203. ],
  204. ),
  205. ),
  206. ),
  207. );
  208. }
  209. Widget _buildCageSection(int tag) {
  210. String title = '源笼号';
  211. TextEditingController controller = _sourceCageController;
  212. FocusNode focusNode = _sourceCageFocusNode;
  213. bool isScanning = _isScanningSource;
  214. if (tag != 1) {
  215. tag = 2;
  216. title = '目标笼号';
  217. controller = _targetCageController;
  218. focusNode = _targetCageFocusNode;
  219. isScanning = _isScanningTarget;
  220. }
  221. // 确保光标在文本末尾
  222. if (controller.text.isNotEmpty) {
  223. controller.selection = TextSelection.fromPosition(
  224. TextPosition(offset: controller.text.length),
  225. );
  226. }
  227. return Column(
  228. crossAxisAlignment: CrossAxisAlignment.start,
  229. children: [
  230. Text(title, style: const TextStyle(fontWeight: FontWeight.bold)),
  231. const SizedBox(height: 10),
  232. Container(
  233. padding: const EdgeInsets.fromLTRB(16, 2, 16, 2),
  234. decoration: BoxDecoration(
  235. border: Border.all(color: Colors.grey),
  236. borderRadius: BorderRadius.circular(8),
  237. ),
  238. child: Row(
  239. children: [
  240. Expanded(
  241. // 将Text替换为TextField
  242. child: TextField(
  243. focusNode: focusNode,
  244. controller: controller,
  245. enabled: controller.text.isEmpty,
  246. decoration: InputDecoration(
  247. border: InputBorder.none,
  248. hintText: controller.text.isNotEmpty ? null : '未扫描',
  249. hintStyle: TextStyle(
  250. color: controller.text.isNotEmpty
  251. ? Colors.black
  252. : Colors.grey,
  253. fontSize: 16,
  254. ),
  255. ),
  256. style: TextStyle(
  257. color: controller.text.isNotEmpty
  258. ? Colors.black
  259. : Colors.grey,
  260. fontSize: 16,
  261. ),
  262. onChanged: (text) {
  263. setState(() {
  264. // 文本更改由controller自动处理
  265. });
  266. },
  267. ),
  268. ),
  269. if (controller.text.isNotEmpty) ...[
  270. IconButton(
  271. icon: const Icon(Icons.refresh, size: 20),
  272. onPressed: () {
  273. _handleChangeCageCode(tag);
  274. },
  275. ),
  276. ] else ...[
  277. IconButton(
  278. icon: isScanning
  279. ? const SizedBox(
  280. width: 20,
  281. height: 20,
  282. child: CircularProgressIndicator(strokeWidth: 2),
  283. )
  284. : const Icon(Icons.qr_code_scanner, size: 20),
  285. onPressed: () {
  286. _handleScanCageCode(tag);
  287. },
  288. ),
  289. ],
  290. ],
  291. ),
  292. ),
  293. ],
  294. );
  295. }
  296. Widget _buildRfidSection() {
  297. return VberRfidField(
  298. rfids: _rfids,
  299. onRfidScanned: (rfid) {
  300. // 检查是否已存在相同的RFID标签
  301. bool isDuplicate = _rfids.any((existingRfid) => existingRfid == rfid);
  302. if (isDuplicate) {
  303. ToastUtil.info("电子编号已存在");
  304. } else {
  305. // 如果不重复,添加到列表中
  306. setState(() {
  307. _rfids.insert(0, rfid);
  308. });
  309. ToastUtil.success("成功添加新的电子编号");
  310. }
  311. },
  312. multiple: true,
  313. multipleScan: false,
  314. label: '电子编号',
  315. multiplePlaceholder: '未识别',
  316. multipleFormat: '已识别 %d 枚电子编号',
  317. );
  318. }
  319. void _dealyScanCode(int scanTag, {int? dealy}) async {
  320. dealy ??= 800;
  321. _scanTag = scanTag;
  322. logger.d("开始扫码: $_scanTag");
  323. await Future.delayed(Duration(milliseconds: dealy));
  324. bool success = await ScanChannel.startScan();
  325. if (!success) {
  326. ToastUtil.error("扫码失败");
  327. }
  328. }
  329. void _handleScanCageCode(int tag) async {
  330. if (_isScanningTarget || _isScanningSource) return;
  331. setState(() {
  332. if (tag == 1) {
  333. _isScanningSource = true;
  334. } else if (tag == 2) {
  335. _isScanningTarget = true;
  336. }
  337. });
  338. _scanTag = tag;
  339. logger.d("开始扫码: $_scanTag");
  340. bool success = await ScanChannel.startScan();
  341. if (!success) {
  342. ToastUtil.error("扫码失败");
  343. }
  344. }
  345. void _handleChangeCageCode(int tag) {
  346. setState(() {
  347. if (tag == 1) {
  348. _sourceCageController.clear();
  349. } else {
  350. _targetCageController.clear();
  351. }
  352. });
  353. _dealyScanCode(tag);
  354. }
  355. // 移除指定索引的电子编号
  356. void _removeRfid(int index) {
  357. setState(() {
  358. _rfids.removeAt(index);
  359. });
  360. }
  361. // 清空所有已识别的电子编号
  362. void _clearRfids() {
  363. setState(() {
  364. _rfids.clear();
  365. });
  366. ToastUtil.info('已清空所有电子编号');
  367. }
  368. // 提交数据
  369. void _handleSubmit() {
  370. final data = {
  371. 'source_cage': _sourceCageController.text,
  372. 'target_cage': _targetCageController.text,
  373. 'rfids': _rfids,
  374. };
  375. apis.breeding.submitApi
  376. .cageChange(data)
  377. .then((_) {
  378. if (mounted) {
  379. ScaffoldMessenger.of(context).showSnackBar(
  380. const SnackBar(
  381. content: Text('换笼提交成功'),
  382. backgroundColor: Colors.green,
  383. ),
  384. );
  385. // 提交后重置表单
  386. setState(() {
  387. _sourceCageController.clear();
  388. _targetCageController.clear();
  389. _rfids.clear();
  390. });
  391. }
  392. })
  393. .catchError((err) {
  394. ToastUtil.error('换笼提交失败');
  395. if (mounted && err != null) {
  396. String errorMessage = err.toString();
  397. if (err is Exception) {
  398. errorMessage = err.toString();
  399. }
  400. ScaffoldMessenger.of(context).showSnackBar(
  401. SnackBar(
  402. content: Text(errorMessage),
  403. backgroundColor: Colors.red,
  404. ),
  405. );
  406. }
  407. });
  408. }
  409. }