patient.dart 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. import 'dart:convert';
  2. import 'package:fis_jsonrpc/rpc.dart';
  3. import 'package:flutter/foundation.dart';
  4. import 'package:get/get.dart';
  5. import 'package:vital_local_database/core/interface/queryable.dart';
  6. import 'package:vitalapp/database/db.dart';
  7. import 'package:vitalapp/database/entities/defines.dart';
  8. import 'package:vitalapp/database/entities/patient.dart';
  9. import 'package:vitalapp/global.dart';
  10. import 'package:vitalapp/managers/interfaces/data_sync.dart';
  11. import 'package:vitalapp/managers/interfaces/models/patient_model_dto.dart';
  12. import 'package:vitalapp/managers/interfaces/patient.dart';
  13. import 'package:vitalapp/mock/services/patient.dart';
  14. import 'package:vitalapp/pages/patient/info/widgets/ext_model.dart';
  15. import 'package:vitalapp/rpc.dart';
  16. import 'package:fis_common/logger/logger.dart';
  17. import 'package:vitalapp/store/store.dart';
  18. import 'interfaces/models/crowd_labels.dart';
  19. import 'interfaces/models/patient.dart';
  20. class PatientManager implements IPatientManager {
  21. String? get userCode => Store.user.userCode;
  22. @override
  23. Future<String?> create(CreatePatientRequest2 request) async {
  24. request.token = Store.user.token;
  25. request.code = request.cardNo;
  26. if (request.code == null || request.code!.isEmpty) {
  27. logger.i("PatientManager create request.cardNo is null.");
  28. return null;
  29. }
  30. print(jsonEncode(request.toJson()));
  31. final result = await rpc.vitalPatient.createPatientAsync(request);
  32. /// 在线状态,先查询是否存在本地未提交数据
  33. /// 在线的时候删除本地数据库数据
  34. if (kIsOnline) {
  35. if (result.isNotEmpty) {
  36. final entity = await db.repositories.patient
  37. .singleByCodeWithUserCode(request.code!, Store.user.userCode!);
  38. if (entity != null) {
  39. final deletePatient = await db.repositories.patient.delete(entity.id);
  40. if (!deletePatient) {
  41. logger.i("PatientManager deletePatient error.");
  42. return null;
  43. }
  44. }
  45. }
  46. }
  47. return result;
  48. }
  49. @override
  50. Future<List<PatientModelDTO>?> getPagedOfflineList(
  51. String? keyword,
  52. DateTime? startTime,
  53. DateTime? endTime,
  54. ) async {
  55. final isKeywordQuery = keyword != null && keyword.isNotEmpty;
  56. var query = db.repositories.patient.queryable.where((x) {
  57. final List<IDbColumnCondition> arr = [];
  58. arr.add(x.isValid.equals(true));
  59. arr.add(x.userCode.equals(Store.user.userCode));
  60. arr.add(x.overallSyncState.notEquals(OfflineDataSyncState.success));
  61. if (!isKeywordQuery) {}
  62. return arr;
  63. });
  64. if (isKeywordQuery) {
  65. // 根据 姓名or身份证号 模糊查询
  66. query = query.whereCustom(
  67. " AND ( name like '%$keyword%' OR code like '%$keyword%' ) ");
  68. } else {
  69. if (startTime != null) {
  70. query = query.and((x) => x.createTime.gte(startTime));
  71. }
  72. if (endTime != null) {
  73. query = query.and((x) => x.createTime.lt(endTime));
  74. }
  75. }
  76. final entities =
  77. await query.orderBy((x) => x.updateTime, DbOrderByType.desc).toList();
  78. final dtos = entities.map((e) {
  79. var patientModel = PatientModelDTO.fromJson(jsonDecode(e.dataJson));
  80. patientModel.isExistLocalData = true;
  81. return patientModel;
  82. }).toList();
  83. return dtos;
  84. }
  85. @override
  86. Future<PatientDTO?> getDetail(
  87. String code, {
  88. bool isValidOperationDoctor = true,
  89. bool allowOfflineData = true,
  90. }) async {
  91. final request = GetPatientRequest(
  92. code: code,
  93. token: Store.user.token,
  94. isValidOperationDoctor: isValidOperationDoctor,
  95. );
  96. try {
  97. if (kIsOnline) {
  98. if (!kIsWeb && allowOfflineData) {
  99. //在线状态,先查询是否存在本地未提交数据
  100. final entity = await db.repositories.patient
  101. .singleByCodeWithUserCode(code, Store.user.userCode!);
  102. if (entity != null &&
  103. entity.dataJson.isNotEmpty &&
  104. entity.syncState != OfflineDataSyncState.success) {
  105. logger.i("PatientManager query patient detail location exist.");
  106. final jsonMap = jsonDecode(entity.dataJson);
  107. final dto = PatientDTO.fromJson(jsonMap);
  108. return dto;
  109. } else {
  110. logger.i("PatientManager query patient detail location not exist.");
  111. }
  112. }
  113. } else {
  114. if (!allowOfflineData) {
  115. return null;
  116. }
  117. }
  118. final result = await rpc.vitalPatient.getPatientDetailAsync(request);
  119. return result;
  120. } catch (e) {
  121. logger.e("PatientManager query patient detail error.", e);
  122. logger.i("GetPatientRequest: ${jsonEncode(request.toJson())}");
  123. return null;
  124. }
  125. }
  126. @override
  127. Future<PatientFullInfoModel?> getOfflineFullInfo(String code) async {
  128. try {
  129. if (kIsWeb) {
  130. return null;
  131. }
  132. final entity = await db.repositories.patient
  133. .singleByCodeWithUserCode(code, Store.user.userCode!);
  134. if (entity == null) {
  135. return null;
  136. }
  137. final jsonMap = jsonDecode(entity.dataJson);
  138. final model = PatientFullInfoModel().fromJson(jsonMap);
  139. if (entity.extJson != null && entity.extJson!.isNotEmpty) {
  140. model.extJsonMap = jsonDecode(entity.extJson!);
  141. }
  142. return model;
  143. } catch (e) {
  144. logger.e("PatientManager getOfflineFullInfo error.", e);
  145. return null;
  146. }
  147. }
  148. @override
  149. Future<PageCollection<PatientModelDTO>?> getPagedList(
  150. PatientPageRequest request) async {
  151. PageCollection<PatientModelDTO>? listPatientDto =
  152. PageCollection<PatientModelDTO>();
  153. try {
  154. request.token = Store.user.token;
  155. print(jsonEncode(request.toJson()));
  156. final result = await rpc.vitalPatient.getPatientPageAsync(request);
  157. listPatientDto.dataCount = result.dataCount;
  158. listPatientDto.pageData = [];
  159. for (var element in result.pageData!) {
  160. var patientModel = PatientModelDTO.fromJson(element.toJson());
  161. if (!kIsWeb) {
  162. var isNotUploadedPatient = await db.repositories.patient
  163. .isNotUploadedPatient(element.code!, Store.user.userCode!);
  164. if (isNotUploadedPatient) {
  165. patientModel.isExistLocalData = true;
  166. }
  167. }
  168. listPatientDto.pageData?.add(patientModel);
  169. }
  170. return listPatientDto;
  171. } catch (e) {
  172. logger.e("PatientManager query patient paged list error.", e);
  173. return null;
  174. }
  175. }
  176. @override
  177. Future<bool> updatePatientAsync(UpdatePatientRequest2 request) async {
  178. try {
  179. if (kIsOnline && !kIsWeb) {
  180. await _updateLocalPatientAsync(request);
  181. }
  182. final result = await rpc.vitalPatient.updatePatientAsync(request);
  183. return result;
  184. } catch (e) {
  185. return false;
  186. }
  187. }
  188. ///在线编辑居民信息时,同步更改本地缓存
  189. Future<bool> _updateLocalPatientAsync(UpdatePatientRequest2 request) async {
  190. final code = request.code!;
  191. final existEntity = await _checkPatientExist(code);
  192. PatientEntity entity;
  193. PatientDTO dto;
  194. if (existEntity == null) {
  195. entity = PatientEntity();
  196. entity.code = request.code!;
  197. entity.isValid = true;
  198. entity.name = request.patientName!;
  199. entity.userCode = Store.user.userCode!; //添加用户code
  200. entity.syncState = OfflineDataSyncState.success;
  201. entity.overallSyncState = OfflineDataSyncState.success;
  202. dto = PatientDTO();
  203. ModelConverter.syncUpdate2Dto(dto, request);
  204. final dtoJson = dto.toJson();
  205. entity.dataJson = jsonEncode(dtoJson);
  206. final id = await db.repositories.patient.insert(entity);
  207. return id > 0;
  208. } else {
  209. entity = existEntity;
  210. final jsonMap = jsonDecode(entity.dataJson);
  211. dto = PatientDTO.fromJson(jsonMap);
  212. ModelConverter.syncUpdate2Dto(dto, request);
  213. final dtoJson = dto.toJson();
  214. entity.dataJson = jsonEncode(dtoJson);
  215. if (entity.syncState == OfflineDataSyncState.success &&
  216. entity.gxyFollowUpCount == 0 &&
  217. entity.tnbFollowUpCount == 0 &&
  218. entity.examCount == 0 &&
  219. entity.diagnosisCount == 0 &&
  220. entity.tcmConsitutionCount == 0) {
  221. entity.overallSyncState = OfflineDataSyncState.success;
  222. }
  223. final rows = await db.repositories.patient.update(entity);
  224. return rows > 0;
  225. }
  226. }
  227. Future<PatientEntity?> _checkPatientExist(String code) async {
  228. try {
  229. final entity = await db.repositories.patient
  230. .singleByCodeWithUserCode(code, Store.user.userCode!);
  231. return entity;
  232. } catch (e) {
  233. logger.e(
  234. "PatientServiceMock - Check patient exist error. Code: $code.", e);
  235. }
  236. return null;
  237. }
  238. @override
  239. Future<bool> setCrowdLabelsAsync(
  240. String patientCode, List<String> crowLabels) async {
  241. try {
  242. final request = SetCrowdLabelsRequest(
  243. code: patientCode, crowdLabels: crowLabels, token: Store.user.token);
  244. final result = rpc.vitalPatient.setCrowdLabelsAsync(request);
  245. return result;
  246. } catch (e) {
  247. logger.e("PatientManager setCrowdLabelsAsync error.", e);
  248. return false;
  249. }
  250. }
  251. Future<String> createPatientExtension(
  252. String patientCode,
  253. PatientHealthInfoModel healthInfo,
  254. PatientDetailInfoModel detailInfo,
  255. String healthCode) async {
  256. final jsonMap = <String, dynamic>{};
  257. final detailJsonMap = detailInfo.toJson();
  258. final healthJsonMap = healthInfo.toJson();
  259. jsonMap.addAll(detailJsonMap);
  260. jsonMap.addAll(healthJsonMap);
  261. jsonMap.removeWhere((key, value) => value == null);
  262. if (!kIsOnline) {
  263. if (healthCode.startsWith("mock")) {
  264. healthCode = ""; // TODO:update from server
  265. }
  266. }
  267. if (healthCode.isNotEmpty) {
  268. var request = UpdatePatientExtensionRequest(
  269. code: healthCode,
  270. token: Store.user.token,
  271. patientCode: patientCode,
  272. key: "PatientHealthInfo",
  273. extensionData: jsonEncode(jsonMap),
  274. );
  275. var result = await updatePatientExtensionAsync(request);
  276. if (result) {}
  277. } else {
  278. var request = CreatePatientExtensionRequest(
  279. token: Store.user.token,
  280. patientCode: patientCode,
  281. key: "PatientHealthInfo",
  282. extensionData: jsonEncode(jsonMap),
  283. );
  284. var result = await createPatientExtensionAsync(request);
  285. if (result.isNotEmpty) {
  286. healthCode = result;
  287. }
  288. }
  289. ///更新
  290. return healthCode;
  291. }
  292. @override
  293. Future<String> createPatientExtensionAsync(
  294. CreatePatientExtensionRequest request) async {
  295. try {
  296. final result =
  297. await rpc.vitalPatientExtension.createPatientExtensionAsync(request);
  298. return result;
  299. } catch (e) {
  300. logger.e("PatientManager createPatientExtension error.", e);
  301. return '';
  302. }
  303. }
  304. @override
  305. Future<PatientExtensionDTO?> getPatientExtensionDetailByCodeAndKeyAsync(
  306. GetPatientExtensionByCodeAndKeyRequest request) async {
  307. try {
  308. final result = await rpc.vitalPatientExtension
  309. .getPatientExtensionDetailByCodeAndKeyAsync(request);
  310. return result;
  311. } catch (e) {
  312. return null;
  313. }
  314. }
  315. @override
  316. Future<bool> updatePatientExtensionAsync(
  317. UpdatePatientExtensionRequest request) async {
  318. try {
  319. final result =
  320. await rpc.vitalPatientExtension.updatePatientExtensionAsync(request);
  321. return result;
  322. } catch (e) {
  323. logger.e("PatientManager updatePatientExtension error.", e);
  324. return false;
  325. }
  326. }
  327. ///获取所有userCode为空的数据,并赋值
  328. @override
  329. Future<void> resettingUsercodeIsEmptyData() async {
  330. if (kIsWeb) return;
  331. var version = await db.database.getVersion();
  332. if (version > 0) {
  333. final list = await db.repositories.patient.queryable.where((x) {
  334. final List<IDbColumnCondition> arr = [];
  335. arr.add(x.isValid.equals(true));
  336. arr.add(x.userCode.equals(''));
  337. return arr;
  338. }).toList();
  339. logger.w(
  340. "PatientManager resettingUsercodeIsEmptyData list.count:${list.length}.");
  341. for (var element in list) {
  342. if (element.syncState == OfflineDataSyncState.success) {
  343. var result = await getDetail(element.code);
  344. if (result != null) {
  345. element.userCode = result.createdDoctor!;
  346. }
  347. } else {
  348. element.userCode = Store.user.userCode!;
  349. }
  350. await db.repositories.patient.update(element);
  351. }
  352. // 更新归属于该医生下的居民的组织Code
  353. final orgCode = Store.user.organizationCode;
  354. final userCode = Store.user.userCode;
  355. await db.database.execute(
  356. "UPDATE patients SET orgCode = '$orgCode' WHERE 1=1 AND isValid=1 AND orgCode='' AND userCode='$userCode';");
  357. }
  358. }
  359. @override
  360. Future<void> switchCurrentPatient(PatientDTO dto) async {
  361. try {
  362. if (!kIsWeb) {
  363. await _syncCloud2Offline(dto);
  364. }
  365. Store.user.currentSelectPatientInfo = dto;
  366. } catch (e) {
  367. logger.e("PatientManager switchCurrentPatient-${dto.code} error.", e);
  368. }
  369. }
  370. @override
  371. Future<void> switchCurrentPatientByCode(String code) async {
  372. final dto = await getDetail(code);
  373. if (dto != null) {
  374. await switchCurrentPatient(dto);
  375. }
  376. }
  377. @override
  378. Future<RegisterPersonInfoDTO?>
  379. getRegisterPersonInfoByPhysicalExamNumberAsync({
  380. required String physicalExamNumber,
  381. }) async {
  382. try {
  383. var request = GetRegisterPersonRequest();
  384. request.physicalExamNumber = physicalExamNumber;
  385. final registerPersonInfo = await rpc.vitalHealthExamBooking
  386. .getRegisterPersonInfoByPhysicalExamNumberAsync(
  387. request,
  388. );
  389. return registerPersonInfo;
  390. } catch (e) {
  391. logger.e(
  392. "PatientManager sync getRegisterPersonInfoByPhysicalExamNumberAsync error.",
  393. e);
  394. return null;
  395. }
  396. }
  397. @override
  398. Future<bool> removePatient(String code) async {
  399. bool result = false;
  400. try {
  401. final entity = await db.repositories.patient
  402. .singleByCodeWithUserCode(code, Store.user.userCode!);
  403. if (entity != null) {
  404. result = await db.repositories.patient.delete(entity.id);
  405. if (!result) {
  406. return false;
  407. }
  408. }
  409. if (kIsOnline) {
  410. try {
  411. // 先检查云端是否有数据
  412. final dto = await rpc.vitalPatient.getPatientDetailAsync(
  413. GetPatientRequest(code: code, token: Store.user.token),
  414. );
  415. // 然后再请求删除
  416. result = await rpc.vitalPatient.removePatientAsync(
  417. RemovePatientRequest(code: code, token: Store.user.token),
  418. );
  419. } catch (e) {
  420. logger.e("PatientManager remove cloud patient-$code error.", e);
  421. }
  422. }
  423. } catch (e) {
  424. logger.e("PatientManager remove patient-$code error.", e);
  425. result = false;
  426. }
  427. if (result) {
  428. if (Store.user.currentSelectPatientInfo?.code == code) {
  429. Store.user.currentSelectPatientInfo = null;
  430. }
  431. }
  432. return result;
  433. }
  434. @override
  435. Future<PatientStatisticDTO> getStatistic() async {
  436. try {
  437. if (!kIsOnline) {
  438. // TODO: offline statistic
  439. return PatientStatisticDTO();
  440. }
  441. final result = await rpc.vitalPatient.getPatientStatisticAsync(
  442. GetPatientStatisticRequest(token: Store.user.token));
  443. return result;
  444. } catch (e) {
  445. logger.e("PatientManager get patient statistic error.", e);
  446. return PatientStatisticDTO();
  447. }
  448. }
  449. Future<void> _syncCloud2Offline(PatientDTO dto) async {
  450. PatientEntity? entity = await db.repositories.patient
  451. .singleByCodeWithUserCode(dto.code!, Store.user.userCode!);
  452. if (entity == null) {
  453. entity = PatientEntity();
  454. entity.isValid = true;
  455. entity.code = dto.code!;
  456. entity.userCode = userCode!;
  457. entity.orgCode = Store.user.organizationCode;
  458. // 从在线数据中刚获取的,不需要同步
  459. entity.syncState = OfflineDataSyncState.success;
  460. entity.overallSyncState = OfflineDataSyncState.success;
  461. // 先创建,后面统一代码更新
  462. final id = await db.repositories.patient.insert(entity);
  463. entity.id = id;
  464. } else {
  465. if (entity.syncState != OfflineDataSyncState.success) {
  466. return;
  467. }
  468. }
  469. if (Get.find<IDataSyncManager>().checkPatientSyncCompleted(entity)) {
  470. entity.overallSyncState = OfflineDataSyncState.success;
  471. }
  472. entity.name = dto.patientName!;
  473. final dtoJsonMap = dto.toJson();
  474. entity.dataJson = jsonEncode(dtoJsonMap);
  475. var extDto = await getPatientExtensionDetailByCodeAndKeyAsync(
  476. GetPatientExtensionByCodeAndKeyRequest(
  477. token: Store.user.token,
  478. patientCode: dto.code,
  479. key: "PatientHealthInfo",
  480. ),
  481. );
  482. if (extDto != null && extDto.code != null) {
  483. entity.extJson = extDto.extensionData;
  484. entity.extCode = extDto.code;
  485. }
  486. await db.repositories.patient.update(entity);
  487. }
  488. //显示的标签转换成可提交至接口的标签
  489. List<String> crowdLabelsConvert(List<String> labels) {
  490. final List<String> result = [];
  491. for (var l in labels) {
  492. //儿童和老年人这俩个标签不需要传给Server
  493. if (l != CrowdLabels.CHILDREN && l != CrowdLabels.ELDERLY) {
  494. switch (l) {
  495. case CrowdLabels.HYPERTENSION:
  496. result.add(CrowdLabelKeys.HYPERTENSION);
  497. break;
  498. case CrowdLabels.TYPE2_DIABETES:
  499. result.add(CrowdLabelKeys.TYPE2_DIABETES);
  500. break;
  501. case CrowdLabels.SUSPECTED_HYPERTENSION:
  502. result.add("CJJB_GXY_Suspected");
  503. break;
  504. case CrowdLabels.SUSPECTED_TYPE2_DIABETES:
  505. result.add("CJJB_TNB_Suspected");
  506. break;
  507. case CrowdLabels.MENTAlDISORDER:
  508. result.add(CrowdLabelKeys.MENTAlDISORDER);
  509. break;
  510. case CrowdLabels.TUBERCULOSIS:
  511. result.add(CrowdLabelKeys.TUBERCULOSIS);
  512. break;
  513. case CrowdLabels.PREGNAMTWOMAN:
  514. result.add(CrowdLabelKeys.PREGNAMTWOMAN);
  515. break;
  516. case CrowdLabels.SUSPECTEDTUBERCULOSIS:
  517. result.add(CrowdLabelKeys.SUSPECTEDTUBERCULOSIS);
  518. break;
  519. case CrowdLabels.SUPECTEDPSYCHOSIS:
  520. result.add(CrowdLabelKeys.SUPECTEDPSYCHOSIS);
  521. break;
  522. }
  523. }
  524. }
  525. return result;
  526. }
  527. ///将Dto中的标签转为可显示的标签
  528. List<String> convertLabelsFormDto(List<String> labels) {
  529. List<String> result = [];
  530. for (var label in labels) {
  531. switch (label) {
  532. case "RQFL_LNR":
  533. result.add(CrowdLabels.ELDERLY);
  534. break;
  535. case "RQFL_ET":
  536. result.add(CrowdLabels.CHILDREN);
  537. break;
  538. case "CJJB_GXY":
  539. result.add(CrowdLabels.HYPERTENSION);
  540. break;
  541. case "CJJB_TNB":
  542. result.add(CrowdLabels.TYPE2_DIABETES);
  543. break;
  544. case "CJJB_GXY_Suspected":
  545. result.add(CrowdLabels.SUSPECTED_HYPERTENSION);
  546. break;
  547. case "CJJB_TNB_Suspected":
  548. result.add(CrowdLabels.SUSPECTED_TYPE2_DIABETES);
  549. break;
  550. case CrowdLabelKeys.MENTAlDISORDER:
  551. result.add(CrowdLabels.MENTAlDISORDER);
  552. break;
  553. case CrowdLabelKeys.TUBERCULOSIS:
  554. result.add(CrowdLabels.TUBERCULOSIS);
  555. break;
  556. case CrowdLabelKeys.PREGNAMTWOMAN:
  557. result.add(CrowdLabels.PREGNAMTWOMAN);
  558. break;
  559. case CrowdLabelKeys.SUSPECTEDTUBERCULOSIS:
  560. result.add(CrowdLabels.SUSPECTEDTUBERCULOSIS);
  561. break;
  562. case CrowdLabelKeys.SUPECTEDPSYCHOSIS:
  563. result.add(CrowdLabels.SUPECTEDPSYCHOSIS);
  564. break;
  565. }
  566. }
  567. return result;
  568. }
  569. }