controller.dart 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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/patient.dart';
  17. import 'package:vitalapp/managers/interfaces/record_data_cache.dart';
  18. import 'package:vitalapp/rpc.dart';
  19. import 'package:vnote_device_plugin/consts/types.dart';
  20. import 'package:vitalapp/architecture/defines.dart';
  21. import 'package:vitalapp/architecture/storage/text_storage.dart';
  22. import 'package:vitalapp/managers/interfaces/cachedRecord.dart';
  23. import 'package:vitalapp/managers/interfaces/device.dart';
  24. import 'package:vitalapp/managers/interfaces/diagnosis.dart';
  25. import 'package:vitalapp/managers/interfaces/models/device.dart';
  26. import 'package:vitalapp/pages/medical/models/item.dart';
  27. import 'package:vitalapp/pages/medical/state.dart';
  28. import 'package:vitalapp/store/store.dart';
  29. import 'package:vnote_device_plugin/events/event_type.dart';
  30. import 'package:fis_common/logger/logger.dart';
  31. import 'package:vitalapp/architecture/storage/storage.dart';
  32. class MedicalController extends FControllerBase {
  33. String patientCode = '';
  34. Map<String, dynamic> diagnosisDataValue = {};
  35. final _patientManager = Get.find<IPatientManager>();
  36. final _examManager = Get.find<IExamManager>();
  37. String appDataId = "";
  38. final state = MedicalState();
  39. final recordDataCacheManager = Get.find<IRecordDataCacheManager>();
  40. static final typeConvertMap = <String, String>{
  41. DeviceTypes.TEMP: "Temp",
  42. DeviceTypes.WEIGHT: "BMI",
  43. DeviceTypes.SPO2: "SpO2",
  44. DeviceTypes.NIBP: "NIBP",
  45. DeviceTypes.SUGAR: "GLU",
  46. DeviceTypes.URINE: "Urine",
  47. DeviceTypes.IC_READER: "ICReader",
  48. DeviceTypes.HEART: "HEART",
  49. DeviceTypes.TWELVEHEART: "Twelveheart",
  50. };
  51. final changePatient = FEventHandler<String>();
  52. final _diagnosisManager = Get.find<IDiagnosisManager>();
  53. final _cachedRecordManager = Get.find<ICachedRecordManager>();
  54. final _deviceManager = Get.find<IDeviceManager>();
  55. final _medicalMenus = [
  56. MedicalItem(key: DeviceTypes.TEMP, diagnosticItem: '体温'),
  57. MedicalItem(key: DeviceTypes.SUGAR, diagnosticItem: '血糖'),
  58. MedicalItem(key: DeviceTypes.NIBP, diagnosticItem: '血压'),
  59. MedicalItem(key: DeviceTypes.SPO2, diagnosticItem: '血氧'),
  60. MedicalItem(key: DeviceTypes.WEIGHT, diagnosticItem: 'BMI'),
  61. MedicalItem(key: DeviceTypes.WAIST, diagnosticItem: '腰臀比'),
  62. MedicalItem(key: DeviceTypes.URINE, diagnosticItem: '尿常规'),
  63. MedicalItem(key: DeviceTypes.HEART, diagnosticItem: '心电'),
  64. MedicalItem(key: DeviceTypes.TWELVEHEART, diagnosticItem: '十二导心电'),
  65. ];
  66. @override
  67. void onInit() async {
  68. setBusy('Loading...');
  69. await initData();
  70. await getAccessTypes();
  71. state.currentTab = DeviceTypes.TEMP; //等数据加载完成之后在切换到体温页面
  72. busy = false;
  73. logger.i('MedicalController init end');
  74. super.onInit();
  75. }
  76. Future<void> initData() async {
  77. patientCode = Store.user.currentSelectPatientInfo?.code ?? '';
  78. if (patientCode.isNotEmpty) {
  79. logger.i(
  80. 'MedicalController initData patientName:${Store.user.currentSelectPatientInfo?.patientName} patientCode:${Store.user.currentSelectPatientInfo?.code}');
  81. var cachedAppDataId = await readCachedAppDataId();
  82. if (cachedAppDataId != null) {
  83. appDataId = cachedAppDataId;
  84. } else {
  85. await saveCachedAppDataId();
  86. }
  87. await initReadCached();
  88. }
  89. }
  90. Future<void> getAccessTypes() async {
  91. List<MedicalItem> medicalItemList = [];
  92. List<String> accessTypes = await _deviceManager.getAccessTypes();
  93. for (var element in _medicalMenus) {
  94. if (accessTypes.contains(element.key)) {
  95. medicalItemList.add(element);
  96. }
  97. }
  98. state.medicalMenuList = medicalItemList;
  99. }
  100. Future<DeviceModel?> getDevice(String type) async {
  101. List<DeviceModel> devices = await _deviceManager.getDeviceList();
  102. return devices.firstWhereOrNull((element) => element.type == type);
  103. }
  104. Future<void> initReadCached() async {
  105. if (patientCode.isNotEmpty) {
  106. logger
  107. .i('MedicalController initReadCached fail,patientCod e:$patientCode');
  108. TextStorage cachedRecord = TextStorage(
  109. fileName: 'JKJC',
  110. directory: "patient/$patientCode",
  111. );
  112. String? value = await cachedRecord.read();
  113. if (value == null) {
  114. diagnosisDataValue = {};
  115. Store.resident.handleSaveMedicalData(jsonEncode(diagnosisDataValue));
  116. return;
  117. }
  118. Store.resident.handleSaveMedicalData(value);
  119. if (kIsWeb) {
  120. diagnosisDataValue = {};
  121. } else {
  122. diagnosisDataValue = jsonDecode(value);
  123. }
  124. }
  125. }
  126. Future<bool?> saveCachedAppDataId() async {
  127. appDataId = const Uuid().v4().replaceAll('-', '');
  128. TextStorage cachedRecord = TextStorage(
  129. fileName: 'appDataId',
  130. directory: "patient/$patientCode",
  131. );
  132. Get.back();
  133. return cachedRecord.save(appDataId);
  134. }
  135. Future<String?> readCachedAppDataId() async {
  136. TextStorage cachedRecord = TextStorage(
  137. fileName: 'appDataId',
  138. directory: "patient/$patientCode",
  139. );
  140. return cachedRecord.read();
  141. }
  142. Future<bool?> saveCachedRecord() async {
  143. if (patientCode.isEmpty) {
  144. logger.i(
  145. 'MedicalController saveCachedRecord fail,patientCode:$patientCode');
  146. return false;
  147. }
  148. Store.resident.handleSaveMedicalData(jsonEncode(diagnosisDataValue));
  149. TextStorage cachedRecord = TextStorage(
  150. fileName: 'JKJC',
  151. directory: "patient/$patientCode",
  152. );
  153. return cachedRecord.save(jsonEncode(diagnosisDataValue));
  154. }
  155. Future<bool?> deleteDirectory() async {
  156. TextStorage cachedRecord = TextStorage(
  157. fileName: 'JKJC',
  158. directory: "patient/$patientCode",
  159. );
  160. return cachedRecord.deleteDirectory();
  161. }
  162. Future<void> submitDiagnosis(
  163. Map<String, dynamic> submitDiagnosisDataValue,
  164. ) async {
  165. try {
  166. List<DiagnosisItem> diagnosisItems = await recordDataCacheManager
  167. .verifyDiagnosisDataList(submitDiagnosisDataValue);
  168. state.currentTab = '-1';
  169. await recordDataCacheManager.saveRecordData(
  170. appDataId,
  171. patientCode,
  172. submitDiagnosisDataValue,
  173. );
  174. if (kIsOnline) {
  175. busy = true;
  176. diagnosisItems = await recordDataCacheManager
  177. .convertDiagnosisDataToList(submitDiagnosisDataValue);
  178. bool result;
  179. result = await _diagnosisManager.syncPatientAndDiagnosisData(
  180. SyncPatientAndDiagnosisDataRequest(
  181. patientCode: patientCode,
  182. patientName: Store.user.currentSelectPatientInfo?.patientName ?? '',
  183. patientAddress:
  184. Store.user.currentSelectPatientInfo?.patientAddress ?? '',
  185. patientGender: Store.user.currentSelectPatientInfo?.patientGender ??
  186. GenderEnum.Unknown,
  187. permanentResidenceAddress:
  188. Store.user.currentSelectPatientInfo?.permanentResidenceAddress,
  189. phone: Store.user.currentSelectPatientInfo?.phone,
  190. cardNo: Store.user.currentSelectPatientInfo?.cardNo,
  191. nationality: Store.user.currentSelectPatientInfo?.nationality,
  192. birthday: Store.user.currentSelectPatientInfo?.birthday,
  193. crowdLabels: Store.user.currentSelectPatientInfo?.crowdLabels,
  194. cardType: Store.user.currentSelectPatientInfo?.cardType ??
  195. CardTypeEnum.Identity,
  196. contractedDoctor:
  197. Store.user.currentSelectPatientInfo?.contractedDoctor,
  198. appDataId: appDataId,
  199. diagnosisTime: DateTime.now(),
  200. token: Store.user.token,
  201. diagnosisItems: diagnosisItems,
  202. ),
  203. );
  204. // print(SyncPatientAndDiagnosisDataRequest(
  205. // patientCode: patientCode,
  206. // patientName: Store.user.currentSelectPatientInfo?.patientName ?? '',
  207. // patientAddress:
  208. // Store.user.currentSelectPatientInfo?.patientAddress ?? '',
  209. // patientGender: Store.user.currentSelectPatientInfo?.patientGender ??
  210. // GenderEnum.Unknown,
  211. // permanentResidenceAddress:
  212. // Store.user.currentSelectPatientInfo?.permanentResidenceAddress,
  213. // phone: Store.user.currentSelectPatientInfo?.phone,
  214. // cardNo: Store.user.currentSelectPatientInfo?.cardNo,
  215. // nationality: Store.user.currentSelectPatientInfo?.nationality,
  216. // birthday: Store.user.currentSelectPatientInfo?.birthday,
  217. // crowdLabels: Store.user.currentSelectPatientInfo?.crowdLabels,
  218. // cardType: Store.user.currentSelectPatientInfo?.cardType ??
  219. // CardTypeEnum.Identity,
  220. // contractedDoctor:
  221. // Store.user.currentSelectPatientInfo?.contractedDoctor,
  222. // appDataId: appDataId,
  223. // diagnosisTime: DateTime.now(),
  224. // token: Store.user.token,
  225. // diagnosisItems: diagnosisItems,
  226. // ).toJson());
  227. busy = false;
  228. if (result) {
  229. //如果在线,则提交历史数据
  230. var submitSuccess = await _submitHistory();
  231. if (submitSuccess) {
  232. logger.i('当前数据提交成功,且历史记录:$patientCode 提交成功');
  233. }
  234. recordDataCacheManager.recordSyncStateChange(appDataId);
  235. PromptBox.toast('提交成功');
  236. await initRecordDataState();
  237. ///提交之后,测试结果清空
  238. diagnosisDataValue.clear();
  239. } else {
  240. PromptBox.toast('提交失败');
  241. logger.i('提交失败:$patientCode');
  242. }
  243. state.currentTab = state.medicalMenuList[0].key;
  244. } else {
  245. Future.delayed(const Duration(milliseconds: 10), () {
  246. state.currentTab = state.medicalMenuList[0].key;
  247. });
  248. PromptBox.toast("已缓存至本地");
  249. logger.i('已缓存至本地:$patientCode');
  250. await initRecordDataState();
  251. ///提交之后,测试结果清空
  252. diagnosisDataValue.clear();
  253. state.currentTab = state.medicalMenuList[0].key;
  254. Get.back();
  255. }
  256. } catch (err) {
  257. busy = false;
  258. state.currentTab = state.medicalMenuList[0].key;
  259. logger.e('submitDiagnosis error: ${err.toString()}');
  260. }
  261. }
  262. Future<void> initRecordDataState() async {
  263. await saveCachedAppDataId();
  264. await deleteDirectory();
  265. await initReadCached();
  266. }
  267. Future<void> createDiagnosis() async {
  268. busy = true;
  269. try {
  270. if (Store.user.teamName.isEmpty) {
  271. PromptBox.toast('未设置团队无法提交检测数据');
  272. return;
  273. }
  274. if (patientCode.isEmpty ||
  275. patientCode != Store.user.currentSelectPatientInfo?.code) {
  276. initData();
  277. }
  278. Map<String, dynamic> submitDiagnosisDataValue =
  279. Map.from(diagnosisDataValue); //确定提交值不会发生变更
  280. List<DiagnosisItem> diagnosisItems = await recordDataCacheManager
  281. .verifyDiagnosisDataList(submitDiagnosisDataValue);
  282. logger.i('submitDiagnosis diagnosisItems.leng:${diagnosisItems.length}');
  283. if (diagnosisItems.isEmpty) {
  284. if (patientCode.isNotEmpty && kIsOnline) {
  285. bool submitHistory = await _submitHistory();
  286. if (submitHistory) {
  287. PromptBox.toast('提交成功');
  288. return;
  289. }
  290. }
  291. PromptBox.toast('不能提交空数据');
  292. return;
  293. }
  294. if (state.medicalMenuList.length > submitDiagnosisDataValue.length) {
  295. logger.i(
  296. 'state.medicalMenuList.length:${state.medicalMenuList.length},copiedDiagnosisDataValue.length:${diagnosisDataValue.length}');
  297. Get.dialog(
  298. VAlertDialog(
  299. title: '提示',
  300. content: Container(
  301. margin: const EdgeInsets.only(bottom: 20),
  302. child: const Text(
  303. '当前检测项目未完成,请确定是否提交本次检测',
  304. style: TextStyle(fontSize: 20),
  305. textAlign: TextAlign.center,
  306. ),
  307. ),
  308. showCancel: true,
  309. onConfirm: () {
  310. Get.back();
  311. submitDiagnosis(submitDiagnosisDataValue);
  312. },
  313. onCanceled: () {},
  314. ),
  315. );
  316. return;
  317. } else {
  318. ///如果已完成所有检查,则直接提交
  319. submitDiagnosis(submitDiagnosisDataValue);
  320. }
  321. } catch (e) {
  322. logger.e('MedicalController createDiagnosis ex:', e);
  323. } finally {
  324. busy = false;
  325. }
  326. }
  327. @override
  328. void dispose() {
  329. print('MedicalController dispose');
  330. super.dispose();
  331. }
  332. /// 【TODO 接口需要变更】 心电
  333. Future<void> createHeart(
  334. String physicalExamNumber,
  335. String? keyValue,
  336. ) async {
  337. Map<String, dynamic> input = diagnosisDataValue;
  338. for (var entry in input.entries) {
  339. var key = entry.key;
  340. var value = entry.value;
  341. if (value != null) {
  342. Store.app.setBusy("提交中");
  343. if (['Heart', 'TwelveHeart'].contains(key) && value is Map) {
  344. value = await uploadData(value);
  345. }
  346. Store.app.busy = false;
  347. // diagnosisItems.add(
  348. // DiagnosisItem(
  349. // key: key,
  350. // diagnosisData: jsonEncode(value),
  351. // ),
  352. // );
  353. }
  354. print('$key: $value');
  355. }
  356. Map<String, dynamic> output = {};
  357. input.forEach((key, value) {
  358. value.forEach((innerKey, innerValue) {
  359. output[innerKey] = innerValue;
  360. });
  361. });
  362. var result = await _examManager.createExam(CreateExamRequest(
  363. key: keyValue ?? "HEIBasic",
  364. examData: jsonEncode(output),
  365. physicalExamNumber: physicalExamNumber,
  366. ));
  367. if (result == true) {
  368. Get.back();
  369. }
  370. }
  371. bool isUploaded(String url) {
  372. return url.startsWith('https://') || url.startsWith('http://');
  373. }
  374. Future<Map> uploadData(Map data) async {
  375. if (data['ECG_POINT'] != null && !isUploaded(data['ECG_POINT'])) {
  376. File ecgPointFile =
  377. await rpc.storage.writeStringToFile(data['ECG_POINT']);
  378. String? ecgPointUrl = await rpc.storage.uploadFile(ecgPointFile);
  379. data['ECG_POINT'] = ecgPointUrl ?? '';
  380. // ... 上传点集
  381. }
  382. if (data['ECG'] != null && !isUploaded(data['ECG'])) {
  383. // ... 上传图片
  384. /// 图片地址
  385. final imageFile = UploadUtils.convertBase64ToXFile(data['ECG']);
  386. String? imageUrl = await rpc.storage.upload(imageFile!);
  387. data['ECG'] = imageUrl ?? '';
  388. }
  389. if (data['ECG_POINT12'] != null && !isUploaded(data['ECG_POINT12'])) {
  390. File ecgPointFile =
  391. await rpc.storage.writeStringToFile(data['ECG_POINT12']);
  392. String? ecgPointUrl = await rpc.storage.uploadFile(ecgPointFile);
  393. data['ECG_POINT12'] = ecgPointUrl ?? '';
  394. // ... 上传点集
  395. }
  396. if (data['ECG12'] != null && !isUploaded(data['ECG12'])) {
  397. // ... 上传图片
  398. final imageFile = UploadUtils.convertBase64ToXFile(data['ECG12']);
  399. String? imageUrl = await rpc.storage.upload(imageFile!, fileType: "jpg");
  400. data['ECG12'] = imageUrl ?? '';
  401. }
  402. return data;
  403. }
  404. /// 体检 检查提交
  405. Future<void> createCheckup(
  406. String? physicalExamNumber,
  407. String? keyValue,
  408. ) async {
  409. Map<String, dynamic> input = diagnosisDataValue;
  410. Map<String, dynamic> output = {};
  411. input.forEach((key, value) {
  412. value.forEach((innerKey, innerValue) {
  413. output[innerKey] = innerValue;
  414. });
  415. });
  416. var result = await _examManager.createExam(CreateExamRequest(
  417. key: keyValue ?? "HEIBasic",
  418. examData: jsonEncode(output),
  419. physicalExamNumber: physicalExamNumber,
  420. ));
  421. if (result == true) {
  422. Get.back();
  423. }
  424. print(result);
  425. }
  426. ///提交历史记录
  427. Future<bool> _submitHistory() async {
  428. var existDatas =
  429. await recordDataCacheManager.getNoSubmitRecords(patientCode);
  430. var historyDatas = existDatas.where((element) => element.code != appDataId);
  431. if (historyDatas.isEmpty) {
  432. return false;
  433. }
  434. for (DiagnosisEntity data in historyDatas) {
  435. try {
  436. Map<String, dynamic> jsonData = jsonDecode(data.dataJson);
  437. var diagnosisItems =
  438. await recordDataCacheManager.convertDiagnosisDataToList(jsonData);
  439. SubmitDiagnosisRequest submitDiagnosisRequest = SubmitDiagnosisRequest(
  440. appDataId: data.code,
  441. patientCode: data.patientCode,
  442. diagnosisItems: diagnosisItems,
  443. diagnosisTime: data.updateTime ?? data.createTime,
  444. );
  445. bool submitResult;
  446. if (kIsOnline) {
  447. PatientDTO? patientInfo = await _patientManager.getDetail(
  448. data.patientCode,
  449. );
  450. if (patientInfo == null) {
  451. ///如果Server没有,则从本地读取
  452. var patientEntity =
  453. await db.repositories.patient.singleByCode(data.patientCode);
  454. if (patientEntity != null) {
  455. patientInfo =
  456. PatientDTO.fromJson(jsonDecode(patientEntity.dataJson));
  457. }
  458. }
  459. submitResult = await _diagnosisManager.syncPatientAndDiagnosisData(
  460. SyncPatientAndDiagnosisDataRequest(
  461. token: Store.user.token,
  462. patientCode: data.patientCode,
  463. patientName: patientInfo?.patientName ?? '',
  464. patientAddress: patientInfo?.patientAddress ?? '',
  465. patientGender: patientInfo?.patientGender ?? GenderEnum.Unknown,
  466. permanentResidenceAddress: patientInfo?.permanentResidenceAddress,
  467. phone: patientInfo?.phone,
  468. cardNo: patientInfo?.cardNo,
  469. nationality: patientInfo?.nationality,
  470. birthday: patientInfo?.birthday,
  471. crowdLabels: patientInfo?.crowdLabels,
  472. cardType: patientInfo?.cardType ?? CardTypeEnum.Identity,
  473. contractedDoctor: patientInfo?.contractedDoctor,
  474. appDataId: data.code,
  475. diagnosisTime: data.updateTime ?? data.createTime,
  476. diagnosisItems: diagnosisItems,
  477. ),
  478. );
  479. } else {
  480. submitResult = await _diagnosisManager
  481. .submitDiagnosisAsync(submitDiagnosisRequest);
  482. }
  483. OfflineDataSyncState state;
  484. if (submitResult) {
  485. state = OfflineDataSyncState.success;
  486. logger.i('提交历史记录:$patientCode 成功');
  487. } else {
  488. state = OfflineDataSyncState.fail;
  489. logger.i('提交历史记录:$patientCode 失败');
  490. }
  491. recordDataCacheManager.recordSyncStateChange(data.code, state: state);
  492. } catch (e) {
  493. logger.e('MedicalController _submitHistory ex:', e);
  494. }
  495. }
  496. return true;
  497. }
  498. }