controller.dart 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'package:fis_jsonrpc/rpc.dart';
  4. import 'package:flutter/foundation.dart';
  5. import 'package:flutter/material.dart';
  6. import 'package:get/get.dart';
  7. import 'package:uuid/uuid.dart';
  8. import 'package:vitalapp/architecture/utils/prompt_box.dart';
  9. import 'package:vitalapp/architecture/utils/upload.dart';
  10. import 'package:vitalapp/components/alert_dialog.dart';
  11. import 'package:vitalapp/database/db.dart';
  12. import 'package:vitalapp/database/entities/defines.dart';
  13. import 'package:vitalapp/database/entities/diagnosis.dart';
  14. import 'package:vitalapp/global.dart';
  15. import 'package:vitalapp/managers/interfaces/exam.dart';
  16. import 'package:vitalapp/managers/interfaces/models/diagnosis_aggregation_record_model.dart';
  17. import 'package:vitalapp/managers/interfaces/patient.dart';
  18. import 'package:vitalapp/managers/interfaces/record_data_cache.dart';
  19. import 'package:vitalapp/routes/routes.dart';
  20. import 'package:vitalapp/rpc.dart';
  21. import 'package:vnote_device_plugin/consts/types.dart';
  22. import 'package:vitalapp/architecture/defines.dart';
  23. import 'package:vitalapp/architecture/storage/text_storage.dart';
  24. import 'package:vitalapp/managers/interfaces/cachedRecord.dart';
  25. import 'package:vitalapp/managers/interfaces/device.dart';
  26. import 'package:vitalapp/managers/interfaces/diagnosis.dart';
  27. import 'package:vitalapp/managers/interfaces/models/device.dart';
  28. import 'package:vitalapp/pages/medical/models/item.dart';
  29. import 'package:vitalapp/pages/medical/state.dart';
  30. import 'package:vitalapp/store/store.dart';
  31. import 'package:vnote_device_plugin/events/event_type.dart';
  32. import 'package:fis_common/logger/logger.dart';
  33. import 'package:vitalapp/architecture/storage/storage.dart';
  34. class MedicalController extends FControllerBase {
  35. String appDataId = "";
  36. String patientCode = '';
  37. Map<String, dynamic> diagnosisDataValue = {};
  38. ExamDTO? currentExam;
  39. final _patientManager = Get.find<IPatientManager>();
  40. final _examManager = Get.find<IExamManager>();
  41. final state = MedicalState();
  42. final recordDataCacheManager = Get.find<IRecordDataCacheManager>();
  43. final FEventHandler<bool> onSelectExam = FEventHandler<bool>();
  44. // /// 体检页面回填的数据
  45. // final FEventHandler<Map<String, dynamic>> onGetExamData =
  46. // FEventHandler<Map<String, dynamic>>();
  47. /// 返回给体检页面的数据
  48. final FEventHandler<Map<String, dynamic>> setExamData =
  49. FEventHandler<Map<String, dynamic>>();
  50. static final typeConvertMap = <String, String>{
  51. DeviceTypes.TEMP: "Temp",
  52. DeviceTypes.WEIGHT: "BMI",
  53. DeviceTypes.SPO2: "SpO2",
  54. DeviceTypes.NIBP: "NIBP",
  55. DeviceTypes.SUGAR: "GLU",
  56. DeviceTypes.URINE: "Urine",
  57. DeviceTypes.IC_READER: "ICReader",
  58. DeviceTypes.HEART: "HEART",
  59. DeviceTypes.TWELVEHEART: "Twelveheart",
  60. };
  61. final changePatient = FEventHandler<String>();
  62. final _diagnosisManager = Get.find<IDiagnosisManager>();
  63. final _cachedRecordManager = Get.find<ICachedRecordManager>();
  64. final _deviceManager = Get.find<IDeviceManager>();
  65. final _medicalMenus = [
  66. MedicalItem(key: DeviceTypes.TEMP, diagnosticItem: '体温'),
  67. MedicalItem(key: DeviceTypes.SUGAR, diagnosticItem: '血糖'),
  68. MedicalItem(key: DeviceTypes.NIBP, diagnosticItem: '血压'),
  69. MedicalItem(key: DeviceTypes.SPO2, diagnosticItem: '血氧'),
  70. MedicalItem(key: DeviceTypes.WEIGHT, diagnosticItem: 'BMI'),
  71. MedicalItem(key: DeviceTypes.WAIST, diagnosticItem: '腰臀比'),
  72. MedicalItem(key: DeviceTypes.URINE, diagnosticItem: '尿常规'),
  73. MedicalItem(key: DeviceTypes.HEART, diagnosticItem: '心电'),
  74. MedicalItem(key: DeviceTypes.TWELVEHEART, diagnosticItem: '十二导心电'),
  75. ];
  76. // @override
  77. // void onInit() {
  78. // super.onInit();
  79. // }
  80. @override
  81. void onReady() async {
  82. super.onReady();
  83. await initData();
  84. await getAccessTypes();
  85. // onGetExamData.addListener(getExamData);
  86. state.currentTab = DeviceTypes.TEMP; //等数据加载完成之后在切换到体温页面
  87. // busy = false;
  88. // logger.i('MedicalController init end');
  89. }
  90. Future<void> initData() async {
  91. patientCode = Store.user.currentSelectPatientInfo?.code ?? '';
  92. if (patientCode.isEmpty) {
  93. logger.w("MedicalController init fail, because `patientCode` not set.");
  94. return;
  95. }
  96. if (Routes.parameters["diagnosisEditData"] != null) {
  97. await _loadDataFromRoute();
  98. return;
  99. }
  100. logger.i(
  101. 'MedicalController initData patientName:${Store.user.currentSelectPatientInfo?.patientName} patientCode:${Store.user.currentSelectPatientInfo?.code}');
  102. var cachedAppDataId = await readCachedAppDataId();
  103. if (cachedAppDataId != null) {
  104. appDataId = cachedAppDataId;
  105. } else {
  106. await saveCachedAppDataId();
  107. }
  108. await initReadCached();
  109. }
  110. Future<void> _loadDataFromRoute() async {
  111. final model = Routes.parameters["diagnosisEditData"]
  112. as DiagnosisAggregationRecordModel;
  113. appDataId = model.appDataId!;
  114. final dataList = model.diagnosisAggregationData ?? [];
  115. diagnosisDataValue = {};
  116. for (var item in dataList) {
  117. if (item.key != null && item.diagnosisData != null) {
  118. diagnosisDataValue[item.key!] = jsonDecode(item.diagnosisData!);
  119. }
  120. }
  121. Routes.parameters["diagnosisEditData"] = null;
  122. }
  123. Future<void> getAccessTypes() async {
  124. List<MedicalItem> medicalItemList = [];
  125. List<String> accessTypes = await _deviceManager.getAccessTypes();
  126. for (var element in _medicalMenus) {
  127. if (accessTypes.contains(element.key)) {
  128. medicalItemList.add(element);
  129. }
  130. }
  131. state.medicalMenuList = medicalItemList;
  132. }
  133. Future<DeviceModel?> getDevice(String type) async {
  134. List<DeviceModel> devices = await _deviceManager.getDeviceList();
  135. return devices.firstWhereOrNull((element) => element.type == type);
  136. }
  137. Future<void> initReadCached() async {
  138. if (patientCode.isNotEmpty) {
  139. logger
  140. .i('MedicalController initReadCached fail,patientCod e:$patientCode');
  141. TextStorage cachedRecord = TextStorage(
  142. fileName: 'JKJC',
  143. directory: "patient/$patientCode",
  144. );
  145. String? value = await cachedRecord.read();
  146. if (value == null) {
  147. diagnosisDataValue = {};
  148. Store.resident.handleSaveMedicalData(jsonEncode(diagnosisDataValue));
  149. return;
  150. }
  151. Store.resident.handleSaveMedicalData(value);
  152. if (kIsWeb) {
  153. diagnosisDataValue = {};
  154. } else {
  155. diagnosisDataValue = jsonDecode(value);
  156. }
  157. }
  158. }
  159. Future<bool?> saveCachedAppDataId() async {
  160. appDataId = const Uuid().v4().replaceAll('-', '');
  161. TextStorage cachedRecord = TextStorage(
  162. fileName: 'appDataId',
  163. directory: "patient/$patientCode",
  164. );
  165. // Get.back();
  166. return cachedRecord.save(appDataId);
  167. }
  168. Future<String?> readCachedAppDataId() async {
  169. TextStorage cachedRecord = TextStorage(
  170. fileName: 'appDataId',
  171. directory: "patient/$patientCode",
  172. );
  173. return cachedRecord.read();
  174. }
  175. Future<bool?> saveCachedRecord() async {
  176. if (patientCode.isEmpty) {
  177. logger.i(
  178. 'MedicalController saveCachedRecord fail,patientCode:$patientCode');
  179. return false;
  180. }
  181. Store.resident.handleSaveMedicalData(jsonEncode(diagnosisDataValue));
  182. TextStorage cachedRecord = TextStorage(
  183. fileName: 'JKJC',
  184. directory: "patient/$patientCode",
  185. );
  186. return cachedRecord.save(jsonEncode(diagnosisDataValue));
  187. }
  188. Future<bool?> deleteDirectory() async {
  189. TextStorage cachedRecord = TextStorage(
  190. fileName: 'JKJC',
  191. directory: "patient/$patientCode",
  192. );
  193. //TODO(Loki):这里是否仅删除一个JKJC的文件就行了,不需要删除整个文件夹
  194. return cachedRecord.delete();
  195. }
  196. Future<void> submitDiagnosis(
  197. Map<String, dynamic> submitDiagnosisDataValue,
  198. ) async {
  199. try {
  200. List<DiagnosisItem> diagnosisItems = await recordDataCacheManager
  201. .verifyDiagnosisDataList(submitDiagnosisDataValue);
  202. state.currentTab = '-1';
  203. await recordDataCacheManager.saveRecordData(
  204. appDataId,
  205. patientCode,
  206. submitDiagnosisDataValue,
  207. );
  208. if (kIsOnline) {
  209. busy = true;
  210. diagnosisItems = await recordDataCacheManager
  211. .convertDiagnosisDataToList(submitDiagnosisDataValue);
  212. bool result;
  213. result = await _diagnosisManager.syncPatientAndDiagnosisData(
  214. SyncPatientAndDiagnosisDataRequest(
  215. patientCode: patientCode,
  216. patientName: Store.user.currentSelectPatientInfo?.patientName ?? '',
  217. patientAddress:
  218. Store.user.currentSelectPatientInfo?.patientAddress ?? '',
  219. patientGender: Store.user.currentSelectPatientInfo?.patientGender ??
  220. GenderEnum.Unknown,
  221. permanentResidenceAddress:
  222. Store.user.currentSelectPatientInfo?.permanentResidenceAddress,
  223. phone: Store.user.currentSelectPatientInfo?.phone,
  224. cardNo: Store.user.currentSelectPatientInfo?.cardNo,
  225. nationality: Store.user.currentSelectPatientInfo?.nationality,
  226. birthday: Store.user.currentSelectPatientInfo?.birthday,
  227. crowdLabels: Store.user.currentSelectPatientInfo?.crowdLabels,
  228. cardType: Store.user.currentSelectPatientInfo?.cardType ??
  229. CardTypeEnum.Identity,
  230. contractedDoctor:
  231. Store.user.currentSelectPatientInfo?.contractedDoctor,
  232. appDataId: appDataId,
  233. diagnosisTime: DateTime.now(),
  234. token: Store.user.token,
  235. diagnosisItems: diagnosisItems,
  236. ),
  237. );
  238. busy = false;
  239. if (result) {
  240. //如果在线,则提交历史数据
  241. var submitSuccess = await _submitHistory();
  242. if (submitSuccess) {
  243. logger.i('当前数据提交成功,且历史记录:$patientCode 提交成功');
  244. }
  245. recordDataCacheManager.recordSyncStateChange(appDataId);
  246. PromptBox.toast('提交成功');
  247. await initRecordDataState();
  248. Get.back();
  249. ///提交之后,测试结果清空
  250. diagnosisDataValue.clear();
  251. } else {
  252. PromptBox.toast('提交失败');
  253. logger.i('提交失败:$patientCode');
  254. }
  255. state.currentTab = state.medicalMenuList[0].key;
  256. } else {
  257. Future.delayed(const Duration(milliseconds: 10), () {
  258. state.currentTab = state.medicalMenuList[0].key;
  259. });
  260. PromptBox.toast("已缓存至本地");
  261. logger.i('已缓存至本地:$patientCode');
  262. await initRecordDataState();
  263. ///提交之后,测试结果清空
  264. diagnosisDataValue.clear();
  265. state.currentTab = state.medicalMenuList[0].key;
  266. state.refreshCurrentTab();
  267. Get.back();
  268. }
  269. } catch (err) {
  270. busy = false;
  271. state.currentTab = state.medicalMenuList[0].key;
  272. state.refreshCurrentTab();
  273. logger.e('submitDiagnosis error: ${err.toString()}');
  274. }
  275. }
  276. Future<void> initRecordDataState() async {
  277. await saveCachedAppDataId();
  278. await deleteDirectory();
  279. await initReadCached();
  280. }
  281. Future<void> createDiagnosis({
  282. required bool isHealthCheck,
  283. }) async {
  284. busy = true;
  285. try {
  286. if (Store.user.teamName.isEmpty) {
  287. PromptBox.toast('未设置团队无法提交检测数据');
  288. return;
  289. }
  290. if (patientCode.isEmpty ||
  291. patientCode != Store.user.currentSelectPatientInfo?.code) {
  292. initData();
  293. }
  294. Map<String, dynamic> submitDiagnosisDataValue =
  295. Map.from(diagnosisDataValue); //确定提交值不会发生变更
  296. List<DiagnosisItem> diagnosisItems = await recordDataCacheManager
  297. .verifyDiagnosisDataList(submitDiagnosisDataValue);
  298. logger.i('submitDiagnosis diagnosisItems.leng:${diagnosisItems.length}');
  299. if (diagnosisItems.isEmpty) {
  300. if (patientCode.isNotEmpty && kIsOnline) {
  301. bool submitHistory = await _submitHistory();
  302. if (submitHistory) {
  303. PromptBox.toast('提交成功');
  304. return;
  305. }
  306. }
  307. PromptBox.toast('不能提交空数据');
  308. return;
  309. }
  310. if (state.medicalMenuList.length > submitDiagnosisDataValue.length) {
  311. logger.i(
  312. 'state.medicalMenuList.length:${state.medicalMenuList.length},copiedDiagnosisDataValue.length:${diagnosisDataValue.length}');
  313. Get.dialog(
  314. VAlertDialog(
  315. title: '提示',
  316. content: Container(
  317. margin: const EdgeInsets.only(bottom: 20),
  318. child: const Text(
  319. '当前检测项目未完成,请确定是否提交本次检测',
  320. style: TextStyle(fontSize: 20),
  321. textAlign: TextAlign.center,
  322. ),
  323. ),
  324. showCancel: true,
  325. onConfirm: () {
  326. Get.back();
  327. if (isHealthCheck) {
  328. try {
  329. setExamData.emit(
  330. this,
  331. submitDiagnosisDataValue,
  332. );
  333. } catch (e) {
  334. print("MedicalController setExamData ex:$e");
  335. logger.e("MedicalController setExamData ex:$e");
  336. }
  337. }
  338. submitDiagnosis(submitDiagnosisDataValue);
  339. },
  340. onCanceled: () {},
  341. ),
  342. );
  343. return;
  344. } else {
  345. if (isHealthCheck) {
  346. try {
  347. setExamData.emit(
  348. this,
  349. submitDiagnosisDataValue,
  350. );
  351. } catch (e) {
  352. print("MedicalController setExamData ex:$e");
  353. logger.e("MedicalController setExamData ex:$e");
  354. }
  355. }
  356. ///如果已完成所有检查,则直接提交
  357. submitDiagnosis(submitDiagnosisDataValue);
  358. }
  359. } catch (e) {
  360. logger.e('MedicalController createDiagnosis ex:', e);
  361. } finally {
  362. busy = false;
  363. }
  364. }
  365. @override
  366. void dispose() {
  367. setExamData.dispose();
  368. // onGetExamData.removeListener(getExamData);
  369. print('MedicalController dispose');
  370. super.dispose();
  371. }
  372. RxBool _isNormalcy = RxBool(true);
  373. bool get isNormalcy => _isNormalcy.value;
  374. set isNormalcy(bool value) => _isNormalcy.value = value;
  375. /// 【TODO 接口需要变更】 心电
  376. Future<void> createHeart(
  377. String physicalExamNumber,
  378. String? keyValue,
  379. String recordCode,
  380. ) async {
  381. try {
  382. Map<String, dynamic> input = diagnosisDataValue;
  383. if (diagnosisDataValue.isEmpty) {
  384. PromptBox.toast('不能提交空数据');
  385. return;
  386. }
  387. await Get.dialog(
  388. VAlertDialog(
  389. title: '提示',
  390. content: Container(
  391. margin: const EdgeInsets.only(bottom: 20),
  392. child: Row(
  393. mainAxisAlignment: MainAxisAlignment.center,
  394. children: [
  395. const Text(
  396. '当前心电检测结果是否正常:',
  397. style: TextStyle(fontSize: 20),
  398. textAlign: TextAlign.center,
  399. ),
  400. SizedBox(
  401. width: 10,
  402. ),
  403. Obx(
  404. () => Row(
  405. children: [
  406. Radio(
  407. onChanged: (v) {
  408. isNormalcy = v ?? false;
  409. },
  410. value: true,
  411. groupValue: isNormalcy,
  412. ),
  413. Text(
  414. "正常",
  415. style: TextStyle(fontSize: 20),
  416. ),
  417. Radio(
  418. onChanged: (v) {
  419. isNormalcy = v ?? false;
  420. },
  421. value: false,
  422. groupValue: isNormalcy,
  423. ),
  424. Text(
  425. "异常",
  426. style: TextStyle(fontSize: 20),
  427. ),
  428. ],
  429. ),
  430. )
  431. ],
  432. )),
  433. showCancel: false,
  434. onConfirm: () {
  435. diagnosisDataValue["TwelveHeart"]["isHeartNormalcy"] = isNormalcy;
  436. Get.back();
  437. },
  438. ),
  439. );
  440. for (var entry in input.entries) {
  441. var key = entry.key;
  442. var value = entry.value;
  443. if (value != null) {
  444. Store.app.setBusy("提交中");
  445. if (['Heart', 'TwelveHeart'].contains(key) && value is Map) {
  446. value = await uploadData(value);
  447. }
  448. Store.app.busy = false;
  449. }
  450. print('$key: $value');
  451. }
  452. Map<String, dynamic> output = {};
  453. input.forEach((key, value) {
  454. value.forEach((innerKey, innerValue) {
  455. output[innerKey] = innerValue;
  456. });
  457. });
  458. bool? result = false;
  459. if (kIsWeb && currentExam != null) {
  460. result = await _examManager.editExam(UpdateExamRequest(
  461. key: keyValue ?? "HEIECG",
  462. examData: jsonEncode(output),
  463. code: currentExam!.code));
  464. } else {
  465. result = await _examManager.createExamDatas(
  466. recordCode,
  467. jsonEncode(output),
  468. );
  469. }
  470. if (result == true) {
  471. busy = false;
  472. PromptBox.toast('提交成功');
  473. Get.back();
  474. }
  475. } catch (e) {
  476. busy = false;
  477. logger.e('MedicalController createCheckup ex:', e);
  478. }
  479. }
  480. bool isUploaded(String url) {
  481. return url.startsWith('https://') || url.startsWith('http://');
  482. }
  483. // TODO Baka 体检暂时写法 需要封装
  484. Future<Map> uploadData(Map data) async {
  485. if (data['ECG_POINT'] != null && !isUploaded(data['ECG_POINT'])) {
  486. if (kIsWeb) {
  487. Uint8List ecgPointbyte =
  488. await rpc.storage.writeStringToByte(data['ECG_POINT']);
  489. String? ecgPointUrl = await rpc.storage.uploadByte(ecgPointbyte);
  490. data['ECG_POINT'] = ecgPointUrl ?? '';
  491. } else {
  492. File ecgPointFile =
  493. await rpc.storage.writeStringToFile(data['ECG_POINT']);
  494. String? ecgPointUrl = await rpc.storage.uploadFile(ecgPointFile);
  495. data['ECG_POINT'] = ecgPointUrl ?? '';
  496. }
  497. // ... 上传点集
  498. }
  499. if (data['ECG'] != null && !isUploaded(data['ECG'])) {
  500. // ... 上传图片
  501. /// 图片地址
  502. final imageFile = UploadUtils.convertBase64ToXFile(data['ECG']);
  503. String? imageUrl = await rpc.storage.upload(imageFile!);
  504. data['ECG'] = imageUrl ?? '';
  505. }
  506. if (data['ECG_POINT12'] != null && !isUploaded(data['ECG_POINT12'])) {
  507. if (kIsWeb) {
  508. Uint8List ecgPointBytes =
  509. await rpc.storage.writeStringToByte(data['ECG_POINT12']);
  510. String? ecgPointUrl = await rpc.storage.uploadByte(ecgPointBytes);
  511. data['ECG_POINT12'] = ecgPointUrl ?? '';
  512. } else {
  513. File ecgPointFile =
  514. await rpc.storage.writeStringToFile(data['ECG_POINT12']);
  515. String? ecgPointUrl = await rpc.storage.uploadFile(ecgPointFile);
  516. data['ECG_POINT12'] = ecgPointUrl ?? '';
  517. }
  518. // ... 上传点集
  519. }
  520. if (data['ECG12'] != null && !isUploaded(data['ECG12'])) {
  521. // ... 上传图片
  522. if (kIsWeb) {
  523. var file = UploadUtils.convertBase64ToFile(data['ECG12']);
  524. String? url = await rpc.storage.webUpload(file!);
  525. data['ECG12'] = url ?? '';
  526. } else {
  527. final imageFile = UploadUtils.convertBase64ToXFile(data['ECG12']);
  528. String? imageUrl =
  529. await rpc.storage.upload(imageFile!, fileType: "jpg");
  530. data['ECG12'] = imageUrl ?? '';
  531. }
  532. }
  533. if (data['ECG12_30s'] != null && !isUploaded(data['ECG12_30s'])) {
  534. // ... 上传图片
  535. if (kIsWeb) {
  536. var file = UploadUtils.convertBase64ToFile(data['ECG12_30s']);
  537. String? url = await rpc.storage.webUpload(file!);
  538. data['ECG12_30s'] = url ?? '';
  539. } else {
  540. final imageFile = UploadUtils.convertBase64ToXFile(data['ECG12_30s']);
  541. String? imageUrl =
  542. await rpc.storage.upload(imageFile!, fileType: "jpg");
  543. data['ECG12_30s'] = imageUrl ?? '';
  544. }
  545. }
  546. return data;
  547. }
  548. /// 体检 检查提交
  549. Future<void> createCheckup(
  550. String? physicalExamNumber,
  551. String? keyValue,
  552. ) async {
  553. try {
  554. Map<String, dynamic> input = diagnosisDataValue;
  555. Map<String, dynamic> output = {};
  556. if (diagnosisDataValue.isEmpty) {
  557. PromptBox.toast('不能提交空数据');
  558. return;
  559. }
  560. setBusy("提交中");
  561. input.forEach((key, value) {
  562. if (value is String) {
  563. output[key] = value;
  564. } else if (value is Map) {
  565. value.forEach((innerKey, innerValue) {
  566. output[innerKey] = innerValue;
  567. });
  568. }
  569. });
  570. var result = await _examManager.createExam(CreateExamRequest(
  571. key: keyValue ?? "HEIBasic",
  572. examData: jsonEncode(output),
  573. physicalExamNumber: physicalExamNumber,
  574. ));
  575. if (result == true) {
  576. busy = false;
  577. PromptBox.toast('提交成功');
  578. Get.back();
  579. }
  580. onSelectExam.emit(this, true);
  581. saveCachedRecord();
  582. } catch (e) {
  583. busy = false;
  584. logger.e('MedicalController createCheckup ex:', e);
  585. }
  586. }
  587. ///提交历史记录
  588. Future<bool> _submitHistory() async {
  589. var existDatas =
  590. await recordDataCacheManager.getNoSubmitRecords(patientCode);
  591. var historyDatas = existDatas.where((element) => element.code != appDataId);
  592. if (historyDatas.isEmpty) {
  593. return false;
  594. }
  595. for (DiagnosisEntity data in historyDatas) {
  596. try {
  597. Map<String, dynamic> jsonData = jsonDecode(data.dataJson);
  598. var diagnosisItems =
  599. await recordDataCacheManager.convertDiagnosisDataToList(jsonData);
  600. SubmitDiagnosisRequest submitDiagnosisRequest = SubmitDiagnosisRequest(
  601. appDataId: data.code,
  602. patientCode: data.patientCode,
  603. diagnosisItems: diagnosisItems,
  604. diagnosisTime: data.updateTime ?? data.createTime,
  605. );
  606. bool submitResult;
  607. if (kIsOnline) {
  608. PatientDTO? patientInfo = await _patientManager.getDetail(
  609. data.patientCode,
  610. );
  611. if (patientInfo == null) {
  612. ///如果Server没有,则从本地读取
  613. var patientEntity = await db.repositories.patient
  614. .singleByCodeWithUserCode(
  615. data.patientCode, Store.user.userCode!);
  616. if (patientEntity != null) {
  617. patientInfo =
  618. PatientDTO.fromJson(jsonDecode(patientEntity.dataJson));
  619. }
  620. }
  621. submitResult = await _diagnosisManager.syncPatientAndDiagnosisData(
  622. SyncPatientAndDiagnosisDataRequest(
  623. token: Store.user.token,
  624. patientCode: data.patientCode,
  625. patientName: patientInfo?.patientName ?? '',
  626. patientAddress: patientInfo?.patientAddress ?? '',
  627. patientGender: patientInfo?.patientGender ?? GenderEnum.Unknown,
  628. permanentResidenceAddress: patientInfo?.permanentResidenceAddress,
  629. phone: patientInfo?.phone,
  630. cardNo: patientInfo?.cardNo,
  631. nationality: patientInfo?.nationality,
  632. birthday: patientInfo?.birthday,
  633. crowdLabels: patientInfo?.crowdLabels,
  634. cardType: patientInfo?.cardType ?? CardTypeEnum.Identity,
  635. contractedDoctor: patientInfo?.contractedDoctor,
  636. appDataId: data.code,
  637. diagnosisTime: data.updateTime ?? data.createTime,
  638. diagnosisItems: diagnosisItems,
  639. ),
  640. );
  641. } else {
  642. submitResult = await _diagnosisManager
  643. .submitDiagnosisAsync(submitDiagnosisRequest);
  644. }
  645. OfflineDataSyncState state;
  646. if (submitResult) {
  647. state = OfflineDataSyncState.success;
  648. logger.i('提交历史记录:$patientCode 成功');
  649. } else {
  650. state = OfflineDataSyncState.fail;
  651. logger.i('提交历史记录:$patientCode 失败');
  652. }
  653. recordDataCacheManager.recordSyncStateChange(data.code, state: state);
  654. } catch (e) {
  655. logger.e('MedicalController _submitHistory ex:', e);
  656. }
  657. }
  658. return true;
  659. }
  660. }