LocalBusPatientService.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. package com.coffee.bus.service;
  2. import cn.hutool.core.collection.CollectionUtil;
  3. import cn.hutool.core.date.LocalDateTimeUtil;
  4. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  5. import cn.hutool.core.util.StrUtil;
  6. import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
  7. import com.baomidou.mybatisplus.core.metadata.IPage;
  8. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  9. import com.coffee.bus.entity.*;
  10. import com.coffee.bus.enums.DeviceAlarmEnum;
  11. import com.coffee.bus.enums.DeviceStatusEnum;
  12. import com.coffee.bus.enums.PatientAlarmEnum;
  13. import com.coffee.bus.hospital.HospitalManager;
  14. import com.coffee.bus.hospital.HospitalManagerRegister;
  15. import com.coffee.bus.hospital.his.HisScriptSession;
  16. import com.coffee.bus.hospital.his.HisScriptSessionManager;
  17. import com.coffee.bus.hospital.his.strategy.HisStrategyEnum;
  18. import com.coffee.bus.registry.device.DeviceRegistry;
  19. import com.coffee.bus.service.dto.*;
  20. import com.coffee.bus.mapper.BusPatientMapper;
  21. import com.coffee.bus.registry.patient.PatientOperator;
  22. import com.coffee.bus.registry.patient.PatientRegistry;
  23. import com.coffee.bus.utils.WsPublishUtils;
  24. import com.coffee.common.crud.BaseService;
  25. import com.coffee.common.enums.SexEnum;
  26. import com.coffee.common.exception.CustomException;
  27. import com.coffee.common.result.R;
  28. import lombok.extern.slf4j.Slf4j;
  29. import org.springframework.beans.factory.annotation.Autowired;
  30. import org.springframework.context.annotation.Lazy;
  31. import org.springframework.stereotype.Service;
  32. import org.springframework.transaction.annotation.Transactional;
  33. import org.springframework.web.context.request.async.DeferredResult;
  34. import java.time.LocalDateTime;
  35. import java.time.ZoneOffset;
  36. import java.util.*;
  37. import java.util.concurrent.CompletableFuture;
  38. import java.util.concurrent.Executors;
  39. import java.util.concurrent.ScheduledExecutorService;
  40. import java.util.concurrent.TimeUnit;
  41. /**
  42. * @author lifang
  43. * @version 1.0.0
  44. * @ClassName LocalBusHospitalService.java
  45. * @Description
  46. * @createTime 2022年03月19日 09:27:00
  47. */
  48. @Service
  49. @Slf4j
  50. public class LocalBusPatientService extends BaseService<BusPatientMapper, BusPatientEntity,String> {
  51. @Autowired
  52. @Lazy
  53. private LocalBusClinicService clinicService;
  54. @Autowired
  55. @Lazy
  56. private PatientRegistry patientRegistry;
  57. @Autowired
  58. @Lazy
  59. private HospitalManagerRegister hospitalManagerRegister;
  60. @Autowired
  61. @Lazy
  62. private WsPublishUtils wsPublishUtils;
  63. @Autowired
  64. @Lazy
  65. private LocalBusInfusionHistoryService infusionHistoryService;
  66. @Autowired
  67. @Lazy
  68. private LocalBusPatientService patientService;
  69. @Autowired
  70. @Lazy
  71. private DeviceRegistry deviceRegistry;
  72. @Autowired
  73. @Lazy
  74. private LocalBusHospitalService hospitalService;
  75. private ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
  76. @Override
  77. public void validateBeforeSave(BusPatientEntity entity) {
  78. if(entity.getGender()==null){
  79. entity.setGender(SexEnum.UNKNOW);
  80. }
  81. if(entity.getAlarm()==null){
  82. entity.setAlarm(PatientAlarmEnum.NONE);
  83. }
  84. }
  85. @Override
  86. public void validateBeforeUpdate(BusPatientEntity entity) {
  87. }
  88. @Override
  89. public void validateBeforeDelete(String id) {
  90. }
  91. @Override
  92. public void postSave(BusPatientEntity entity) {
  93. super.postSave(entity);
  94. //新增病人后推送主题,延迟推送,保证处理逻辑已全部完成
  95. executorService.schedule(()->{
  96. wsPublishUtils.publishPatientAdd(entity.getCode(),entity.getTenantId());
  97. wsPublishUtils.publishMonitorTotalCount(entity.getTenantId());
  98. }
  99. ,2, TimeUnit.SECONDS);
  100. }
  101. /**
  102. * 获取病人信息
  103. * @param hospitalId 医院id
  104. * @param patientCode 病号
  105. * @param sync 是否为同步操作
  106. */
  107. public DeferredResult<R<BusClinicEntity>> getPatientInfoFromHis(String hospitalId, String patientCode, long timeout,boolean sync){
  108. BusHospitalEntity hospital = hospitalService.getById(hospitalId);
  109. HospitalManager hospitalManager = hospitalManagerRegister.get(hospitalId);
  110. HisScriptSession hisScriptSession = hospitalManager.getScriptSession();
  111. HisStrategyEnum strategy = hospital.getStrategy();
  112. if(null==strategy||HisStrategyEnum.NONE.equals(strategy)){
  113. throw new CustomException("医院未对接his,请到【信息维护】->【HIS对接】配置his策略");
  114. }
  115. log.info("医院【{}】,开始拉取病号【{}】信息,拉取方式【{}】",hospitalId,patientCode,sync?"同步":"异步");
  116. return sync?hisScriptSession.syncGetPatientInfo(patientCode,timeout,TimeUnit.SECONDS):hisScriptSession.asyncGetPatientInfo(patientCode,timeout,TimeUnit.SECONDS,true);
  117. }
  118. /**
  119. * 描述: 对病人报警数量进行统计
  120. * @author lifang
  121. * @date 2022/5/20 16:42
  122. * @param tenantId
  123. * @param alarm
  124. * @return long
  125. */
  126. public long patientAlarmCount(String tenantId,PatientAlarmEnum alarm){
  127. return this.baseMapper.selectAlarmCount(tenantId,alarm.getValue());
  128. }
  129. public long patientAlarmCount(PatientAlarmEnum alarm){
  130. return patientAlarmCount(null,alarm);
  131. }
  132. public long monitorTotalCount(String tenantId){
  133. return this.baseMapper.monitorTotalCount(tenantId);
  134. }
  135. /**
  136. * 获取给定医院下所有的挂载多个设备的病人信息
  137. *
  138. */
  139. public List<PatientDeviceRepeatResult> repeatDevice() {
  140. List<PatientDeviceRepeatDomain> patientDeviceRepeats = this.baseMapper.selectRepeatDevice();
  141. Map<String, PatientDeviceRepeatResult> resultMap = new HashMap<>();
  142. patientDeviceRepeats.forEach(deviceRepeat->{
  143. PatientDeviceRepeatResult repeatResult = resultMap.computeIfAbsent(deviceRepeat.getCode()+deviceRepeat.getClinicId(),k->
  144. PatientDeviceRepeatResult.of(
  145. deviceRepeat.getName(),
  146. deviceRepeat.getGender(),
  147. deviceRepeat.getCode(),
  148. deviceRepeat.getAge(),
  149. deviceRepeat.getWard(),
  150. deviceRepeat.getBedNo(),
  151. deviceRepeat.getClinicName(),
  152. deviceRepeat.getClinicId(),
  153. new ArrayList<>())
  154. );
  155. List<PatientDeviceRepeatResult.DeviceRunningSmallInfo> deviceRunningSmallInfos = Optional.ofNullable(repeatResult.getDevices()).orElse(new ArrayList<>());
  156. deviceRunningSmallInfos.add(PatientDeviceRepeatResult.DeviceRunningSmallInfo.of(
  157. deviceRepeat.getDeviceId(),
  158. deviceRepeat.getDeviceAlias(),
  159. deviceRepeat.getDeviceRunState(),
  160. deviceRepeat.getDeviceAlarm(),
  161. deviceRepeat.getInfusionStartTime(),
  162. deviceRepeat.isMaster()
  163. ));
  164. repeatResult.setDevices(deviceRunningSmallInfos);
  165. });
  166. return new ArrayList<>(resultMap.values());
  167. }
  168. /**
  169. * 获取无设备绑定的临床手术信息
  170. * @return
  171. */
  172. public List<PatientDeviceNoneResult> noneDevice() {
  173. return this.baseMapper.selectNoneDevice();
  174. }
  175. public List<PatientMonitorResult> selectAll(PatientMonitorQuery query) {
  176. Page<PatientMonitorResult> page = new Page<>(0, 500, false);
  177. IPage<PatientMonitorResult> result = this.baseMapper.selectMonitor(page,query);
  178. if(CollectionUtil.isNotEmpty(result.getRecords())){
  179. result.getRecords().forEach(PatientMonitorResult::handleWarn);
  180. }
  181. return result.getRecords();
  182. }
  183. /**t
  184. * 根据医院和住院号获取一个患者
  185. * @param tenantId
  186. * @param patientCode
  187. * @return
  188. */
  189. public BusPatientEntity getOneByHospitalAndPatientCode(String tenantId, String patientCode) {
  190. BusPatientEntity patient = this.getOne(new QueryWrapper<BusPatientEntity>().lambda()
  191. .eq(BusPatientEntity::getTenantId,tenantId)
  192. .eq(BusPatientEntity::getCode,patientCode));
  193. // 如果患者不存在则新增一个患者
  194. if (Objects.isNull(patient)){
  195. patient = new BusPatientEntity();
  196. patient.setTenantId(tenantId);
  197. patient.setCode(patientCode);
  198. this.save(patient);
  199. }
  200. return patient;
  201. }
  202. /**
  203. *
  204. * 病人手动更新当前监控的临床信息
  205. * @param clinic
  206. */
  207. @Transactional(rollbackFor = Exception.class)
  208. public void manualEdit(BusClinicEntity clinic) {
  209. BusClinicEntity originClinicInfo = clinicService.getById(clinic.getId());
  210. if(originClinicInfo==null){
  211. throw new CustomException("该住院号临床信息不存在,请刷新后重试");
  212. }
  213. BusPatientEntity originPatientInfo = patientService.getById(originClinicInfo.getPatientId());
  214. if(originPatientInfo==null){
  215. throw new CustomException("该住院号信息不存在,请刷新后重试");
  216. }
  217. //先更新手术信息
  218. clinicService.updateById(clinic);
  219. //后更新病人信息
  220. BusPatientEntity patient = BusPatientEntity.of(clinic);
  221. PatientOperator patientOperator = patientRegistry.getOperator(patient.getTenantId(), originPatientInfo.getOriginCode());
  222. BusPatientEntity existPatient = this.getOne(new QueryWrapper<BusPatientEntity>().lambda().eq(BusPatientEntity::getCode, patient.getCode()).last("limit 1"));
  223. patient.setId(existPatient.getId());
  224. this.updateById(patient);
  225. patientOperator.setClinicId(patient.getClinicId());
  226. CompletableFuture.runAsync(()->{
  227. wsPublishUtils.publishPatientMonitor(originPatientInfo.getId(),patient.getTenantId());
  228. });
  229. }
  230. /**
  231. * 根据病号查询临床监控记录
  232. * @author lifang
  233. * @param patientId 病号id
  234. * @param tenantId 医院id
  235. * @return
  236. */
  237. public PatientMonitorResult lookMonitorByPatientCode(String patientId,String tenantId) {
  238. try {
  239. return this.baseMapper.findByPatientId(tenantId, patientId);
  240. } catch (Exception e) {
  241. log.error("根据病号查询临床失败,",e.getMessage());
  242. return null;
  243. }
  244. }
  245. /**
  246. * 描述: 设备状态数量统计
  247. * @author lifang
  248. * @date 2022/5/8 21:52
  249. * @param tenantId 医院id 用户请求时传输null
  250. * @return MonitorStatusStatsCountResult
  251. */
  252. public MonitorStatusStatsCountResult statusStats(String tenantId) {
  253. PatientMonitorQuery query = new PatientMonitorQuery();
  254. query.setTenantId(tenantId);
  255. List<PatientMonitorResult> patientMonitorResults = this.selectAll(query);
  256. MonitorStatusStatsCountResult result = new MonitorStatusStatsCountResult();
  257. if(CollectionUtil.isNotEmpty(patientMonitorResults)){
  258. patientMonitorResults.forEach(monitor->{
  259. //运行数量
  260. if(!Boolean.TRUE.equals(monitor.getInfusionFinished())&&
  261. DeviceStatusEnum.Running.equals(monitor.getDeviceRunState())){
  262. result.setRunningCount(result.getRunningCount()+1);
  263. }
  264. if((Boolean.TRUE.equals(monitor.getInfusionFinished()))||
  265. (DeviceStatusEnum.Shutdown.equals(monitor.getDeviceRunState())||DeviceStatusEnum.NoSignal.equals(monitor.getDeviceRunState()))){
  266. result.setWaitingFinish(result.getWaitingFinish()+1);
  267. }
  268. //报警数量
  269. if(!Boolean.TRUE.equals(monitor.getInfusionFinished())&&
  270. monitor.getDeviceAlarm()!=null&&!monitor.getDeviceAlarm().equals(DeviceAlarmEnum.None)){
  271. result.setAlarmCount(result.getAlarmCount()+1);
  272. }
  273. //提醒数量
  274. if(!Boolean.TRUE.equals(monitor.getInfusionFinished())&&
  275. (Boolean.TRUE.equals(monitor.getWarnAnalgesicPoor())
  276. ||Boolean.TRUE.equals(monitor.getWarnLowBattery())
  277. ||Boolean.TRUE.equals(monitor.getWarnWillFinished())
  278. ||monitor.getWarnFlow()!=null)){
  279. result.setWarnCount(result.getWarnCount()+1);
  280. }
  281. });
  282. }
  283. return result;
  284. }
  285. /**
  286. * 描述: 按照时间对输注监控进行统计
  287. * @author lifang
  288. * @date 2022/5/8 22:40
  289. * @param tenantId 医院id
  290. * @return MonitorTimeStatsCountResult
  291. */
  292. public MonitorTimeStatsCountResult timeStats(String tenantId) {
  293. PatientMonitorQuery query = new PatientMonitorQuery();
  294. query.setTenantId(tenantId);
  295. List<PatientMonitorResult> patientMonitorResults = this.selectAll(query);
  296. MonitorTimeStatsCountResult result = new MonitorTimeStatsCountResult();
  297. patientMonitorResults.forEach(monitor->{
  298. Date startTime = monitor.getMonitorStartTime();
  299. if(startTime==null){
  300. return;
  301. }
  302. if (includeTimes(startTime, 0)) {
  303. result.setToday(result.getToday()+1);
  304. return;
  305. }
  306. if (includeTimes(startTime, -1)) {
  307. result.setOneDay(result.getOneDay()+1);
  308. return;
  309. }
  310. if (includeTimes(startTime, -2)) {
  311. result.setTwoDay(result.getTwoDay()+1);
  312. return;
  313. }
  314. if (includeTimes(startTime, -3)) {
  315. result.setThreeDay(result.getThreeDay()+1);
  316. return;
  317. }
  318. result.setBeyondThreeDay(result.getBeyondThreeDay()+1);
  319. });
  320. return result;
  321. }
  322. /**
  323. * 描述: 判断所给时间是否在存在于某一时间段内
  324. * @author lifang
  325. * @date 2022/5/8 22:47
  326. * @param time 时间
  327. * @param offset 时间偏移量,单位:天 以当天时间为基准进行偏移
  328. * @return boolean
  329. */
  330. private boolean includeTimes(Date time,int offset){
  331. if(time==null){
  332. return false;
  333. }
  334. LocalDateTime dateTime = LocalDateTime.now().plusDays(offset);
  335. LocalDateTime beginTime = LocalDateTimeUtil.beginOfDay(dateTime);
  336. LocalDateTime endTime = LocalDateTimeUtil.endOfDay(dateTime);
  337. return beginTime.toInstant(ZoneOffset.of("+8")).toEpochMilli()<time.getTime()
  338. && time.getTime()<endTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
  339. }
  340. /**
  341. * 切换主泵
  342. * @param shiftConfig 切换配置
  343. */
  344. @Transactional(rollbackFor = Exception.class)
  345. public void shift(DeviceShiftConfig shiftConfig) {
  346. String formatCode = shiftConfig.getPatientCode();
  347. BusPatientEntity patient = patientService.getOne(new QueryWrapper<BusPatientEntity>().lambda().eq(BusPatientEntity::getCode, formatCode));
  348. if(patient==null){
  349. throw new CustomException(String.format("住院号【%s】不存在,请刷新后重试",shiftConfig.getPatientCode()));
  350. }
  351. shiftConfig.setPatientId(patient.getId());
  352. PatientOperator patientOperator = patientRegistry.getOperator(shiftConfig.getTenantId(), shiftConfig.getPatientCode());
  353. List<String> replicaDeviceIds = shiftConfig.getReplicaDeviceIds();
  354. String masterDeviceId = shiftConfig.getMasterDeviceId();
  355. BusInfusionHistoryEntity masterInfusion = infusionHistoryService.lastInfusion(masterDeviceId);
  356. //病患绑定主泵信息
  357. this.update(new UpdateWrapper<BusPatientEntity>().lambda()
  358. .eq(BusPatientEntity::getCode,shiftConfig.getPatientCode())
  359. .eq(BusPatientEntity::getTenantId,shiftConfig.getTenantId())
  360. .set(BusPatientEntity::getInfusionId,masterInfusion.getId()));
  361. //刷新缓存信息
  362. replicaDeviceIds.stream()
  363. .map(deviceRegistry::getOperator).forEach(deviceOperator->{
  364. deviceOperator.setMaster(false);
  365. });
  366. patientOperator.setBindDeviceId(shiftConfig.getMasterDeviceId());
  367. }
  368. public BusPatientEntity findByFormatCode(String patientCode, String tenantId){
  369. return this.getOne(new QueryWrapper<BusPatientEntity>().lambda().eq(BusPatientEntity::getCode,patientCode)
  370. .eq(StrUtil.isNotBlank(tenantId),BusPatientEntity::getTenantId,tenantId));
  371. }
  372. public BusPatientEntity findByFormatCode(String patientCode){
  373. return findByFormatCode(patientCode,null);
  374. }
  375. }