controller.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. import 'dart:convert';
  2. import 'package:fis_jsonrpc/rpc.dart';
  3. import 'package:flutter/material.dart';
  4. import 'package:get/get.dart';
  5. import 'package:uuid/uuid.dart';
  6. import 'package:vitalapp/architecture/utils/prompt_box.dart';
  7. import 'package:vitalapp/components/alert_dialog.dart';
  8. import 'package:vitalapp/database/db.dart';
  9. import 'package:vitalapp/database/entities/defines.dart';
  10. import 'package:vitalapp/database/entities/diagnosis.dart';
  11. import 'package:vitalapp/global.dart';
  12. import 'package:vitalapp/managers/interfaces/patient.dart';
  13. import 'package:vitalapp/managers/interfaces/record_data_cache.dart';
  14. import 'package:vnote_device_plugin/consts/types.dart';
  15. import 'package:vitalapp/architecture/defines.dart';
  16. import 'package:vitalapp/architecture/storage/text_storage.dart';
  17. import 'package:vitalapp/managers/interfaces/cachedRecord.dart';
  18. import 'package:vitalapp/managers/interfaces/device.dart';
  19. import 'package:vitalapp/managers/interfaces/diagnosis.dart';
  20. import 'package:vitalapp/managers/interfaces/models/device.dart';
  21. import 'package:vitalapp/pages/medical/models/item.dart';
  22. import 'package:vitalapp/pages/medical/state.dart';
  23. import 'package:vitalapp/store/store.dart';
  24. import 'package:vnote_device_plugin/events/event_type.dart';
  25. import 'package:fis_common/logger/logger.dart';
  26. class MedicalController extends FControllerBase {
  27. String patientCode = '';
  28. Map<String, dynamic> diagnosisDataValue = {};
  29. final _patientManager = Get.find<IPatientManager>();
  30. String appDataId = "";
  31. final state = MedicalState();
  32. final recordDataCacheManager = Get.find<IRecordDataCacheManager>();
  33. static final typeConvertMap = <String, String>{
  34. DeviceTypes.TEMP: "Temp",
  35. DeviceTypes.WEIGHT: "BMI",
  36. DeviceTypes.SPO2: "SpO2",
  37. DeviceTypes.NIBP: "NIBP",
  38. DeviceTypes.SUGAR: "GLU",
  39. DeviceTypes.URINE: "Urine",
  40. DeviceTypes.IC_READER: "ICReader",
  41. DeviceTypes.HEART: "HEART",
  42. };
  43. final changePatient = FEventHandler<String>();
  44. final _diagnosisManager = Get.find<IDiagnosisManager>();
  45. final _cachedRecordManager = Get.find<ICachedRecordManager>();
  46. final _deviceManager = Get.find<IDeviceManager>();
  47. final _medicalMenus = [
  48. MedicalItem(key: DeviceTypes.TEMP, diagnosticItem: '体温'),
  49. MedicalItem(key: DeviceTypes.SUGAR, diagnosticItem: '血糖'),
  50. MedicalItem(key: DeviceTypes.NIBP, diagnosticItem: '血压'),
  51. MedicalItem(key: DeviceTypes.SPO2, diagnosticItem: '血氧'),
  52. MedicalItem(key: DeviceTypes.WEIGHT, diagnosticItem: 'BMI'),
  53. MedicalItem(key: DeviceTypes.URINE, diagnosticItem: '尿常规'),
  54. MedicalItem(key: DeviceTypes.HEART, diagnosticItem: '心电'),
  55. ];
  56. @override
  57. void onInit() async {
  58. setBusy('Loading...');
  59. await initData();
  60. await getAccessTypes();
  61. state.currentTab = DeviceTypes.TEMP; //等数据加载完成之后在切换到体温页面
  62. busy = false;
  63. logger.i('MedicalController init end');
  64. super.onInit();
  65. }
  66. Future<void> initData() async {
  67. patientCode = Store.user.currentSelectPatientInfo?.code ?? '';
  68. if (patientCode.isNotEmpty) {
  69. logger.i(
  70. 'MedicalController initData patientName:${Store.user.currentSelectPatientInfo?.patientName} patientCode:${Store.user.currentSelectPatientInfo?.code}');
  71. var cachedAppDataId = await readCachedAppDataId();
  72. if (cachedAppDataId != null) {
  73. appDataId = cachedAppDataId;
  74. } else {
  75. await saveCachedAppDataId();
  76. }
  77. await initReadCached();
  78. }
  79. }
  80. Future<void> getAccessTypes() async {
  81. List<MedicalItem> medicalItemList = [];
  82. List<String> accessTypes = await _deviceManager.getAccessTypes();
  83. for (var element in _medicalMenus) {
  84. if (accessTypes.contains(element.key)) {
  85. medicalItemList.add(element);
  86. }
  87. }
  88. state.medicalMenuList = medicalItemList;
  89. }
  90. Future<DeviceModel?> getDevice(String type) async {
  91. List<DeviceModel> devices = await _deviceManager.getDeviceList();
  92. return devices.firstWhereOrNull((element) => element.type == type);
  93. }
  94. Future<void> initReadCached() async {
  95. if (patientCode.isNotEmpty) {
  96. TextStorage cachedRecord = TextStorage(
  97. fileName: 'JKJC',
  98. directory: "patient/$patientCode",
  99. );
  100. String? value = await cachedRecord.read();
  101. if (value == null) {
  102. diagnosisDataValue = {};
  103. Store.resident.handleSaveMedicalData(jsonEncode(diagnosisDataValue));
  104. return;
  105. }
  106. Store.resident.handleSaveMedicalData(value);
  107. diagnosisDataValue = jsonDecode(value);
  108. }
  109. }
  110. Future<bool?> saveCachedAppDataId() async {
  111. appDataId = const Uuid().v4().replaceAll('-', '');
  112. TextStorage cachedRecord = TextStorage(
  113. fileName: 'appDataId',
  114. directory: "patient/$patientCode",
  115. );
  116. Get.back();
  117. return cachedRecord.save(appDataId);
  118. }
  119. Future<String?> readCachedAppDataId() async {
  120. TextStorage cachedRecord = TextStorage(
  121. fileName: 'appDataId',
  122. directory: "patient/$patientCode",
  123. );
  124. return cachedRecord.read();
  125. }
  126. Future<bool?> saveCachedRecord() async {
  127. Store.resident.handleSaveMedicalData(jsonEncode(diagnosisDataValue));
  128. TextStorage cachedRecord = TextStorage(
  129. fileName: 'JKJC',
  130. directory: "patient/$patientCode",
  131. );
  132. return cachedRecord.save(jsonEncode(diagnosisDataValue));
  133. }
  134. Future<bool?> deleteDirectory() async {
  135. TextStorage cachedRecord = TextStorage(
  136. fileName: 'JKJC',
  137. directory: "patient/$patientCode",
  138. );
  139. return cachedRecord.deleteDirectory();
  140. }
  141. Future<void> submitDiagnosis(
  142. Map<String, dynamic> submitDiagnosisDataValue,
  143. ) async {
  144. try {
  145. List<DiagnosisItem> diagnosisItems = await recordDataCacheManager
  146. .convertDiagnosisDataToList(submitDiagnosisDataValue);
  147. state.currentTab = '-1';
  148. await recordDataCacheManager.saveRecordData(
  149. appDataId,
  150. patientCode,
  151. submitDiagnosisDataValue,
  152. );
  153. if (kIsOnline) {
  154. SubmitDiagnosisRequest submitDiagnosisRequest = SubmitDiagnosisRequest(
  155. appDataId: appDataId,
  156. patientCode: patientCode,
  157. diagnosisItems: diagnosisItems,
  158. diagnosisTime: DateTime.now().toUtc(),
  159. );
  160. print(submitDiagnosisRequest.toJson());
  161. busy = true;
  162. bool result;
  163. if (kIsOnline) {
  164. result = await _diagnosisManager.syncPatientAndDiagnosisData(
  165. SyncPatientAndDiagnosisDataRequest(
  166. patientCode: patientCode,
  167. patientName:
  168. Store.user.currentSelectPatientInfo?.patientName ?? '',
  169. patientAddress:
  170. Store.user.currentSelectPatientInfo?.patientAddress ?? '',
  171. patientGender:
  172. Store.user.currentSelectPatientInfo?.patientGender ??
  173. GenderEnum.Unknown,
  174. permanentResidenceAddress: Store
  175. .user.currentSelectPatientInfo?.permanentResidenceAddress,
  176. phone: Store.user.currentSelectPatientInfo?.phone,
  177. cardNo: Store.user.currentSelectPatientInfo?.cardNo,
  178. nationality: Store.user.currentSelectPatientInfo?.nationality,
  179. birthday: Store.user.currentSelectPatientInfo?.birthday,
  180. crowdLabels: Store.user.currentSelectPatientInfo?.crowdLabels,
  181. cardType: Store.user.currentSelectPatientInfo?.cardType ??
  182. CardTypeEnum.Identity,
  183. contractedDoctor:
  184. Store.user.currentSelectPatientInfo?.contractedDoctor,
  185. appDataId: appDataId,
  186. diagnosisTime: DateTime.now(),
  187. token: Store.user.token,
  188. diagnosisItems: diagnosisItems,
  189. ),
  190. );
  191. if (result) {
  192. //如果在线,则提交历史数据
  193. var submitSuccess = await _submitHistory();
  194. if (submitSuccess) {
  195. logger.i('当前数据提交成功,且历史记录:$patientCode 提交成功');
  196. }
  197. }
  198. } else {
  199. result = await _diagnosisManager
  200. .submitDiagnosisAsync(submitDiagnosisRequest);
  201. }
  202. if (result) {
  203. busy = false;
  204. recordDataCacheManager.recordSyncStateChange(appDataId);
  205. PromptBox.toast('提交成功');
  206. await saveCachedAppDataId();
  207. await deleteDirectory();
  208. await initReadCached();
  209. ///提交之后,测试结果清空
  210. diagnosisDataValue.clear();
  211. Future.delayed(const Duration(milliseconds: 10), () {
  212. state.currentTab = state.medicalMenuList[0].key;
  213. });
  214. } else {
  215. PromptBox.toast('提交失败');
  216. logger.i('提交失败:$patientCode');
  217. }
  218. if (busy) {
  219. busy = false;
  220. }
  221. } else {
  222. Future.delayed(const Duration(milliseconds: 10), () {
  223. state.currentTab = state.medicalMenuList[0].key;
  224. });
  225. PromptBox.toast("已缓存至本地");
  226. logger.i('已缓存至本地:$patientCode');
  227. await saveCachedAppDataId();
  228. await deleteDirectory();
  229. await initReadCached();
  230. ///提交之后,测试结果清空
  231. diagnosisDataValue.clear();
  232. Get.back();
  233. }
  234. } catch (err) {
  235. state.currentTab = state.medicalMenuList[0].key;
  236. logger.e('submitDiagnosis error: ${err.toString()}');
  237. }
  238. }
  239. Future<void> createDiagnosis() async {
  240. busy = true;
  241. try {
  242. if (Store.user.teamName.isEmpty) {
  243. PromptBox.toast('未设置团队无法提交检测数据');
  244. return;
  245. }
  246. if (patientCode.isEmpty ||
  247. patientCode != Store.user.currentSelectPatientInfo?.code) {
  248. initData();
  249. }
  250. Map<String, dynamic> submitDiagnosisDataValue =
  251. Map.from(diagnosisDataValue); //确定提交值不会发生变更
  252. List<DiagnosisItem> diagnosisItems = await recordDataCacheManager
  253. .convertDiagnosisDataToList(submitDiagnosisDataValue);
  254. logger.i('submitDiagnosis diagnosisItems.leng:${diagnosisItems.length}');
  255. if (diagnosisItems.isEmpty) {
  256. if (patientCode.isNotEmpty && kIsOnline) {
  257. bool submitHistory = await _submitHistory();
  258. if (submitHistory) {
  259. PromptBox.toast('提交成功');
  260. return;
  261. }
  262. }
  263. PromptBox.toast('不能提交空数据');
  264. return;
  265. }
  266. if (state.medicalMenuList.length > submitDiagnosisDataValue.length) {
  267. logger.i(
  268. 'state.medicalMenuList.length:${state.medicalMenuList.length},copiedDiagnosisDataValue.length:${diagnosisDataValue.length}');
  269. Get.dialog(
  270. VAlertDialog(
  271. title: '提示',
  272. content: Container(
  273. margin: const EdgeInsets.only(bottom: 20),
  274. child: const Text(
  275. '当前检测项目未完成,请确定是否提交本次检测',
  276. style: TextStyle(fontSize: 20),
  277. textAlign: TextAlign.center,
  278. ),
  279. ),
  280. showCancel: true,
  281. onConfirm: () {
  282. submitDiagnosis(submitDiagnosisDataValue);
  283. },
  284. onCanceled: () {},
  285. ),
  286. );
  287. return;
  288. } else {
  289. ///如果已完成所有检查,则直接提交
  290. submitDiagnosis(submitDiagnosisDataValue);
  291. }
  292. } catch (e) {
  293. logger.e('MedicalController createDiagnosis ex:', e);
  294. } finally {
  295. busy = false;
  296. }
  297. }
  298. @override
  299. void dispose() {
  300. print('MedicalController dispose');
  301. super.dispose();
  302. }
  303. ///提交历史记录
  304. Future<bool> _submitHistory() async {
  305. var existDatas =
  306. await recordDataCacheManager.getNoSubmitRecords(patientCode);
  307. var historyDatas = existDatas.where((element) => element.code != appDataId);
  308. if (historyDatas.isEmpty) {
  309. return false;
  310. }
  311. for (DiagnosisEntity data in historyDatas) {
  312. try {
  313. Map<String, dynamic> jsonData = jsonDecode(data.dataJson);
  314. var diagnosisItems =
  315. await recordDataCacheManager.convertDiagnosisDataToList(jsonData);
  316. SubmitDiagnosisRequest submitDiagnosisRequest = SubmitDiagnosisRequest(
  317. appDataId: data.code,
  318. patientCode: data.patientCode,
  319. diagnosisItems: diagnosisItems,
  320. diagnosisTime: data.updateTime ?? data.createTime,
  321. );
  322. bool submitResult;
  323. if (kIsOnline) {
  324. PatientDTO? patientInfo = await _patientManager.getDetail(
  325. data.patientCode,
  326. );
  327. if (patientInfo == null) {
  328. ///如果Server没有,则从本地读取
  329. var patientEntity = await db.repositories.patient
  330. .singleByCode(data.patientCode, Store.user.userCode!);
  331. if (patientEntity != null) {
  332. patientInfo =
  333. PatientDTO.fromJson(jsonDecode(patientEntity.dataJson));
  334. }
  335. }
  336. submitResult = await _diagnosisManager.syncPatientAndDiagnosisData(
  337. SyncPatientAndDiagnosisDataRequest(
  338. token: Store.user.token,
  339. patientCode: data.patientCode,
  340. patientName: patientInfo?.patientName ?? '',
  341. patientAddress: patientInfo?.patientAddress ?? '',
  342. patientGender: patientInfo?.patientGender ?? GenderEnum.Unknown,
  343. permanentResidenceAddress: patientInfo?.permanentResidenceAddress,
  344. phone: patientInfo?.phone,
  345. cardNo: patientInfo?.cardNo,
  346. nationality: patientInfo?.nationality,
  347. birthday: patientInfo?.birthday,
  348. crowdLabels: patientInfo?.crowdLabels,
  349. cardType: patientInfo?.cardType ?? CardTypeEnum.Identity,
  350. contractedDoctor: patientInfo?.contractedDoctor,
  351. appDataId: data.code,
  352. diagnosisTime: data.updateTime ?? data.createTime,
  353. diagnosisItems: diagnosisItems,
  354. ),
  355. );
  356. } else {
  357. submitResult = await _diagnosisManager
  358. .submitDiagnosisAsync(submitDiagnosisRequest);
  359. }
  360. OfflineDataSyncState state;
  361. if (submitResult) {
  362. state = OfflineDataSyncState.success;
  363. logger.i('提交历史记录:$patientCode 成功');
  364. } else {
  365. state = OfflineDataSyncState.fail;
  366. logger.i('提交历史记录:$patientCode 失败');
  367. }
  368. recordDataCacheManager.recordSyncStateChange(data.code, state: state);
  369. } catch (e) {
  370. logger.e('MedicalController _submitHistory ex:', e);
  371. }
  372. }
  373. return true;
  374. }
  375. }