cage_change_page.dart 14 KB

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